Skip to main content

Repository Refactoring Methodology & Plan

Комплексная методология для решения проблем контекста и восстановления эффективности AI-агента

🎯 Проблемы, которые мы решаем

  1. Потеря контекста AI-агентом - слишком много несвязанного кода в одном репо
  2. Снижение качества разработки - мелкие баги из-за неправильного контекста
  3. Медленное восстановление контекста - 10+ действий вместо 2-3
  4. Смешение приоритетов - продакшн код (Mercury) смешан с экспериментами
  5. Устаревшая FDD методология - не учитывает специфику AI workflow

🏆 Выбранное решение: Cursor 0.50.7 Background Agent + Multi-Root Domains

КАРДИНАЛЬНАЯ СМЕНА ПОДХОДА на основе реальных фич Cursor 0.50.7 🚀

Что мы узнали из changelog и почему все меняется:

🤖 Background Agent (Preview) - Твой настоящий Sacred Grail:

  • Агенты работают параллельно в background в отдельных environments
  • Большие задачи выполняются без твоего участия
  • Множественные PR одновременно
  • Это именно высокоуровневый AI agent management!

📁 @folders - Instant full context:

  • Вся кодовая база в контексте одной командой
  • Нет нужды в сложных intel bundling скриптах
  • @folders domains/mercury = мгновенный полный контекст

🏗️ Multi-root workspaces - Идеально для domain structure:

  • Несколько репо/папок в одном workspace
  • Все индексируется автоматически
  • .cursor/rules работают во всех корнях

Rules generation - Автоматизация вместо хаоса:

  • /Generate Cursor Rules из успешных conversations
  • Auto Attached rules с path patterns
  • Agent автоматически применяет правила при работе с файлами

🎓 Чему тебе нужно научиться (Learning Plan):

Problem 1: Rules в бардаке 🤯

Твоя текущая боль: "rules превратились в бардак, не понимаю когда что используется"

Что освоить:

  1. Rules hierarchy - Always vs Auto Attached vs Manual
  2. Path patterns - когда .cursor/rules применяются автоматически
  3. Rules generation - как создавать rules из successful workflows
  4. Rules debugging - как понять какие rules активны

Problem 2: Неэффективное использование контекста 📚

Твоя текущая боль: Слишком много manual context restoration

Что освоить:

  1. @folders strategy - как правильно включать целые домены
  2. Multi-root setup - как structure workspace для доменов
  3. Context optimization - когда использовать @folders vs @files
  4. Context debugging - как понять что AI видит/не видит

Problem 3: Sequential workflow вместо parallel

Твоя текущая боль: Одна задача за раз, context switching

Что освоить:

  1. Background Agent workflow - как делегировать задачи
  2. Parallel development - Mercury + Arcana одновременно
  3. Agent management - monitoring, follow-up, take over
  4. Task decomposition - как разбивать большие задачи для agents

Почему именно этот Cursor-Native подход победил:

  • 🎯 Background Agent - реальный high-level AI management (твой Sacred Grail!)
  • 🎯 @folders - instant full context без сложных скриптов
  • 🎯 Multi-root workspaces - native domain isolation
  • 🎯 Auto rules - автоматическое применение правил по path patterns
  • 🎯 Rules generation - capture successful workflows автоматически
  • Обучающий компонент - исправляет твои текущие Cursor anti-patterns

🤖 Cursor 0.50.7 Native AI Workflow (с обучающим планом)

1. Background Agent - Твой настоящий Sacred Grail! 🤖

Что это реально дает (не теория, а практика):

Settings > Beta > Background Agent (включить)

Workflow который ты освоишь:

# Параллельное развитие доменов
Background Agent #1: "Optimize DIKE tournament in Mercury"
Background Agent #2: "Fix Arcana tarot spread calculations"
Background Agent #3: "Update Mercury dashboard performance"

# Ты продолжаешь работать, они работают в фоне
# Notification: "Agent #1 completed DIKE optimization PR"
# Review, approve, merge - готово!

Обучающие цели для тебя:

  1. Task decomposition - как формулировать задачи для background agents
  2. Agent monitoring - как отслеживать progress и вмешиваться
  3. Parallel workflow - как управлять несколькими agents одновременно
  4. Quality control - как review и merge agent work

2. @folders - Мгновенный полный контекст! 📁

Что ты делаешь сейчас неправильно: Manually добавляешь файлы, теряешь контекст

Что нужно освоить:

# Вместо manual file selection:
@folders domains/mercury # Весь Mercury domain
@folders libs/domain/kaido-talib # Вся TA библиотека
@folders platform/docs/mercury # Вся документация

# Settings > Full folder contents (включить)

Learning objectives:

  1. Folder strategy - какие папки включать для разных задач
  2. Context size management - как не перегрузить context
  3. Incremental context - начать с @folders, добавить @files по нужде
  4. Context debugging - понимать когда файлы не помещаются

3. Multi-Root Workspaces - Domain Isolation! 🏗️

Твоя текущая проблема: Один workspace = контекстное смешение доменов

Новый подход:

File > Add Folder to Workspace...
- domains/mercury/
- domains/arcana/
- libs/core/
- libs/domain/

# Каждый домен индексируется отдельно
# .cursor/rules применяются автоматически по path patterns

Learning objectives:

  1. Workspace design - как структурировать multi-root для доменов
  2. Path-based rules - как настроить автоматическое применение rules
  3. Domain switching - быстрое переключение между доменами
  4. Index management - понимание как Cursor индексирует multiple roots

4. Rules Generation - Автоматизация вместо хаоса! ⚡

Твоя текущая боль: "rules в бардаке, не понимаю когда что используется"

Новый workflow:

# После successful conversation:
/Generate Cursor Rules

# Cursor автоматически создает:
domains/mercury/.cursor/rules

Пример auto-generated rule:

When working in domains/mercury/:
- NEVER import from mercury-ta, ALWAYS use kaido-talib
- Use mythological naming (APOLLO, DIKE, TYCHE, etc.)
- NO hardcoded ports (dangerous_defaults rule)
- Background jobs MUST use Redis queues

Learning objectives (критично для тебя!):

  1. Rules hierarchy понимание:
    • Always: Применяются везде
    • Auto Attached: Автоматически по path patterns
    • Manual: Добавляешь руками в conversation
  2. Rules debugging: Как понять какие rules активны в текущей conversation
  3. Rules optimization: Как не создавать conflicting rules
  4. Rules maintenance: Когда удалять/обновлять устаревшие rules

5. Context Strategy - Что когда использовать 🎯

Твоя обучающая матрица:

ЗадачаМетодПример
Feature development@folders domain + Background Agent@folders domains/mercury + Agent: "Add DIKE tournament feature"
Bug investigation@folders + @files specific@folders domains/mercury + @files error.log
RefactoringMulti-root workspace + @foldersOpen Mercury+Libs workspace + @folders all
Documentation@folders docs + Auto rules@folders platform/docs with auto writing rules
Cross-domainMulti-root + multiple @folders@folders domains/mercury + @folders domains/arcana

6. Практический Learning Plan для тебя 📚

Неделя 1: Rules Mastery

  • День 1-2: Audit текущих rules, understand hierarchy
  • День 3-4: Create path-based auto rules для каждого domain
  • День 5-7: Practice rules generation из successful conversations

Неделя 2: Context Optimization

  • День 1-3: Master @folders strategy для каждого domain
  • День 4-5: Setup multi-root workspace правильно
  • День 6-7: Practice context debugging и optimization

Неделя 3: Background Agent Workflow

  • День 1-3: Simple background tasks (bug fixes, small features)
  • День 4-5: Complex tasks (new modules, refactoring)
  • День 6-7: Parallel development (multiple agents)

Success metrics для тебя:

  • ✅ Rules больше не в хаосе - понимаешь когда что применяется
  • ✅ Context restoration с 10+ действий до 1 команды @folders
  • ✅ Параллельная разработка - Mercury + Arcana одновременно
  • ✅ Background Agents выполняют 70%+ routine tasks без тебя

📁 Финальная структура репозитория

ton-arcana/
├── domains/ # Domain-driven organization
│ ├── mercury/ # 🥇 Priority #1 - Trading system
│ │ ├── backend/ # apps/mercury → NestJS app
│ │ ├── dashboard/ # apps/mercury-dashboard → React
│ │ ├── packages/ # Mercury-specific packages
│ │ ├── ai-manifest.md # AI context + instructions
│ │ └── project.json # Nx configuration
│ ├── arcana/ # 🔮 Tarot system
│ │ ├── backend/ # apps/arcana-backend
│ │ ├── twa/ # apps/arcana-twa
│ │ ├── ai-manifest.md
│ │ └── project.json
│ ├── anytracker/ # 📊 Tracking system
│ │ ├── backend/ # apps/anytracker-backend
│ │ ├── mini-app/ # apps/anytracker-mini-app
│ │ └── ai-manifest.md
│ └── maschine/ # 🤖 AI assistant features
│ ├── core/
│ └── ai-manifest.md
├── libs/ # Shared libraries (packages/*)
│ ├── core/ # Essential utilities
│ │ ├── common-utils/
│ │ ├── types/
│ │ ├── auth-utils/
│ │ └── project.json
│ ├── integrations/ # External service wrappers
│ │ ├── kaido-telegram/
│ │ ├── kaido-ton/
│ │ ├── kaido-ollama/
│ │ ├── openai-utils/
│ │ └── project.json
│ ├── domain/ # Domain-specific libs
│ │ ├── kaido-talib/ # TS technical analysis
│ │ ├── curvinator/ # Legacy but used
│ │ └── project.json
│ └── deprecated/ # Marked for removal
│ └── mercury-ta/ # Python TA (deprecated)
├── platform/ # Infrastructure & tooling
│ ├── tools/ # Development utilities
│ │ ├── intel/ # AI context generator
│ │ ├── workspace-manager/ # Context switching
│ │ └── project.json
│ ├── infra/ # Infrastructure as code
│ │ ├── ansible/
│ │ ├── docker/
│ │ ├── grafana/
│ │ └── project.json
│ └── docs/ # Documentation
│ ├── adr/ # Architecture decisions
│ ├── mercury/ # Domain-specific docs
│ ├── platform/ # General docs
│ └── project.json
├── archive/ # Fully deprecated
│ ├── k8s/ # Old Kubernetes configs
│ ├── mcp-task-warrior/ # MCP experiment
│ └── kaido.team/ # Empty public blog
├── tools/ # Nx/dev tooling
│ ├── intel/ # AI context bundler
│ │ ├── intel.ts # Main intel generator
│ │ └── templates/ # Context templates
│ └── workspace-manager/ # Context switching
├── workspaces/ # VS Code workspace configs
│ ├── mercury.code-workspace # Mercury-focused development
│ ├── arcana.code-workspace # Arcana-focused development
│ ├── anytracker.code-workspace # AnyTracker-focused development
│ └── platform.code-workspace # Infrastructure work
├── nx.json # Nx workspace configuration
├── pnpm-workspace.yaml # pnpm workspace definition
└── package.json # Root package.json

🤖 Cursor-Native AI Context Recovery System

1. Composer Projects (Beta v0.41.1) - Ключевая фича! 🎯

Революционная возможность: Share instructions across multiple Composer sessions для agentic workflow

# composer-projects/mercury-agent.yaml
name: 'Mercury Trading System Agent'
description: 'Agentic development for Mercury with mythological architecture'

context:
include:
- 'domains/mercury/**'
- 'libs/domain/kaido-talib/**'
- 'libs/core/**'
exclude:
- 'archive/**'
- 'domains/arcana/**'

instructions:
- '🔥 CRITICAL: NEVER use mercury-ta (Python) → ALWAYS use kaido-talib (TypeScript)'
- '🔥 NO default ports (dangerous_defaults rule enforced)'
- '🏛️ Mythological naming: All modules named after Greek/Roman gods'
- '🎯 Current focus: DIKE tournament system optimization'
- '⚡ Use Redis queues for background processing'
- '📊 Tournament system logic for market comparisons'
- '🧪 Test with nx test mercury-backend before applying'

templates:
feature_request: |
When implementing new features:
1. Check ai-manifest.md for current sprint focus
2. Use Command-K Autoselect to find relevant code
3. Apply changes incrementally with chat lints validation
4. Run nx affected:test to ensure no regressions

debugging: |
For debugging Mercury issues:
1. Check recent commits: git log -n 5 domains/mercury/
2. Review failing tests: nx test mercury-backend --verbose
3. Use chat symbol links to navigate to error sources
4. Validate with intel bundle before major changes

Как использовать:

  1. cmd+I → Select "Mercury Trading System Agent"
  2. Все future Composer sessions автоматически получают этот контекст
  3. AI помнит mythological architecture, knows kaido-talib vs mercury-ta, follows rules

2. Chat Tabs (v0.41.x) - Parallel Context Management 💬

Революция в контексте: Отдельные conversations для каждого домена

// Cursor workspace configuration
{
"cursor.chat.tabs": {
"mercury": {
"scope": ["domains/mercury/**", "libs/domain/kaido-talib/**"],
"composerProject": "mercury-agent",
"model": "claude-3.5-sonnet",
"systemPrompt": "You are Mercury domain expert. Focus on trading system with mythological modules."
},
"arcana": {
"scope": ["domains/arcana/**", "libs/integrations/kaido-telegram/**"],
"composerProject": "arcana-agent",
"model": "claude-3.5-sonnet",
"systemPrompt": "You are Arcana domain expert. Focus on tarot bot with LLM-powered readings."
},
"platform": {
"scope": ["platform/**", "libs/core/**"],
"model": "claude-3.5-sonnet",
"systemPrompt": "You are platform/infrastructure expert."
}
}
}

Benefits:

  • Context isolation - Mercury chat никогда не confused с Arcana кодом
  • Persistent memory per domain - AI помнит recent changes в каждом домене
  • Parallel development - можешь работать над Mercury + AnyTracker simultaneously

3. Command-K Autoselect (v0.34.1) + Project Structure in Context (v0.41.x) 🎯

Auto-magic code selection: Cursor автоматически выбирает релевантный код

// .cursor/settings.json
{
"cursor.ai.autoselect": {
"enabled": true,
"useProjectStructure": true,
"maxContextLines": 2000,
"prioritizeRecentEdits": true,
"domainAwareness": {
"mercury": ["APOLLO", "DIKE", "TYCHE", "KAIROS", "MINERVA", "MORPHEUS"],
"arcana": ["tarot", "readings", "spreads", "interpretations"],
"anytracker": ["tracking", "analytics", "metrics"]
}
},
"cursor.ai.projectStructure": {
"includeInContext": true,
"excludePatterns": ["archive/**", "node_modules/**", "dist/**"],
"maxDepth": 3,
"prioritizeDomains": ["domains/mercury"]
}
}

Workflow:

  1. Открываешь файл в Mercury domain
  2. cmd+K + "add new endpoint to APOLLO module"
  3. Cursor automatically selects relevant APOLLO files
  4. AI видит only Mercury context через project structure
  5. Perfect suggestions без noise от других доменов

4. Auto-imports TypeScript (v0.41.1) + Symbol Linking 🔗

Seamless shared modules: Zero friction для использования libs

// domains/mercury/backend/src/apollo/portfolio.service.ts

import { TechnicalAnalysis } from '@libs/kaido-talib'; // ← Auto-imported!
import { AuthUtils } from '@libs/auth-utils'; // ← Auto-imported!
import { UserEntity } from '@libs/types'; // ← Auto-imported!

// При chat symbol links - cmd+click ведет прямо в source
export class PortfolioService {
// AI знает structure через auto-imports
}

Chat Symbol Links Magic:

  • В chat: "modify TechnicalAnalysis.calculateRSI"
  • Cursor создает clickable link прямо к libs/domain/kaido-talib/src/indicators/rsi.ts
  • Instant navigation без search/find

5. Chat Lints (v0.41.1) - Validation Before Apply 🛡️

Prevent bugs: Cursor validates code symbols before applying

// .cursor/chat-lints.json
{
"mercury": {
"bannedImports": [
"mercury-ta", // Force kaido-talib usage
"hardcoded-ports" // Enforce dangerous_defaults rule
],
"requiredPatterns": [
"mythological-naming", // Enforce APOLLO, DIKE naming
"redis-queue-usage" // Ensure background jobs use queues
],
"testRequirements": [
"nx-test-required" // Must pass tests before apply
]
}
}

Benefits:

  • Invalid symbols highlighted in chat before apply
  • Banned imports (mercury-ta) prevented automatically
  • Required patterns enforced (mythological naming)
  • Test validation required before changes applied

6. Enhanced Intel Bundling (Cursor-optimized)

// tools/intel/cursor-intel.ts
import { projectGraphAsync } from 'nx/src/project-graph/project-graph';

async function generateCursorIntel(domain: string) {
const graph = await projectGraphAsync();

const cursorIntel = {
domain,
composerProject: `${domain}-agent`,
cursorVersion: '0.41.3',
features: {
chatTabs: true,
autoselect: true,
symbolLinks: true,
chatLints: true,
},
workspace: {
scope: [`domains/${domain}/**`],
excludes: ['archive/**', 'node_modules/**'],
dependencies: graph.dependencies[domain],
},
aiManifest: readFile(`domains/${domain}/ai-manifest.md`),
recentCommits: execSync(`git log -n 5 --oneline domains/${domain}`),
activeFeatures: getActiveFeatures(domain),
composerInstructions: loadComposerProject(`${domain}-agent.yaml`),
};

// Create Cursor-specific bundle
writeFileSync(
`/tmp/cursor-intel-${domain}.json`,
JSON.stringify(cursorIntel),
);

// Auto-open chat tab with loaded context
execSync(
`cursor --chat-tab ${domain} --load-intel /tmp/cursor-intel-${domain}.json`,
);
}

7. Cursor-Native Context Switching Scripts 🚀

Новая философия: Используем Cursor CLI + Chat Tabs + Composer Projects

// package.json scripts (Cursor-optimized)
{
"scripts": {
"cursor:mercury": "cursor --chat-tab mercury --composer mercury-agent --workspace workspaces/mercury.code-workspace",
"cursor:arcana": "cursor --chat-tab arcana --composer arcana-agent --workspace workspaces/arcana.code-workspace",
"cursor:anytracker": "cursor --chat-tab anytracker --composer anytracker-agent",
"cursor:platform": "cursor --chat-tab platform --scope platform/**",

"intel:mercury": "nx run tools:cursor-intel mercury",
"intel:all": "nx run-many --target=cursor-intel --projects=mercury,arcana,anytracker",

"ctx:switch": "node tools/context-switcher.js",
"agentic:mercury": "pnpm cursor:mercury && echo '🥇 Mercury agentic mode ready!'",
"agentic:arcana": "pnpm cursor:arcana && echo '🔮 Arcana agentic mode ready!'"
}
}

Smart Context Switcher:

// tools/context-switcher.js
#!/usr/bin/env node

const { execSync } = require('child_process');
const inquirer = require('inquirer');

async function switchContext() {
const { domain } = await inquirer.prompt([{
type: 'list',
name: 'domain',
message: 'Which domain to enter? 🎯',
choices: [
{ name: '🥇 Mercury (Trading System)', value: 'mercury' },
{ name: '🔮 Arcana (Tarot Bot)', value: 'arcana' },
{ name: '📊 AnyTracker (Analytics)', value: 'anytracker' },
{ name: '🔧 Platform (Infrastructure)', value: 'platform' }
]
}]);

console.log(`🚀 Switching to ${domain} domain with Cursor optimization...`);

// Generate fresh intel
execSync(`pnpm intel:${domain}`, { stdio: 'inherit' });

// Open Cursor with Chat Tab + Composer Project
execSync(`pnpm cursor:${domain}`, { stdio: 'inherit' });

// Show quick reference
console.log(`
${domain.toUpperCase()} AGENTIC MODE ACTIVATED!

🎯 Active Features:
- Chat Tab: ${domain} (isolated context)
- Composer Project: ${domain}-agent (persistent instructions)
- Auto-select: Enabled for ${domain} domain
- Symbol Links: Navigate instantly with cmd+click
- Chat Lints: Validates before apply

💡 Quick Commands:
- cmd+I: Open Composer with ${domain}-agent
- cmd+K: Auto-select relevant code
- cmd+L: Chat in ${domain} tab
- cmd+click: Jump to symbol definition

🔥 Sacred Grail achieved! Code with confidence! 🏆
`);
}

switchContext().catch(console.error);

8. Enhanced Cursor Workspace Configuration

mercury.code-workspace (v0.41.x optimized):

{
"folders": [
{
"path": "./domains/mercury",
"name": "🥇 Mercury Core"
},
{
"path": "./libs/domain/kaido-talib",
"name": "📊 Technical Analysis"
},
{
"path": "./libs/core",
"name": "🔧 Shared Core"
}
],
"settings": {
// Cursor v0.41.x features
"cursor.chat.defaultModel": "claude-3.5-sonnet",
"cursor.chat.tabs.enabled": true,
"cursor.chat.tabs.default": "mercury",
"cursor.composer.defaultProject": "mercury-agent",
"cursor.ai.autoselect.enabled": true,
"cursor.ai.symbolLinks.enabled": true,
"cursor.ai.chatLints.enabled": true,

// TypeScript auto-imports optimization
"typescript.preferences.includePackageJsonAutoImports": "on",
"typescript.suggest.autoImports": true,
"typescript.suggest.paths": true,

// Project structure in context
"cursor.ai.projectStructure.includeInContext": true,
"cursor.ai.projectStructure.maxDepth": 3,
"cursor.ai.projectStructure.prioritize": ["domains/mercury"],

// Search optimization for agentic workflows
"search.exclude": {
"**/archive/**": true,
"**/domains/arcana/**": true,
"**/domains/anytracker/**": true,
"**/domains/maschine/**": true,
"**/node_modules/**": true,
"**/dist/**": true,
"**/.nx/**": true
},

// Files to always include in context
"cursor.ai.alwaysInclude": [
"domains/mercury/ai-manifest.md",
"nx.json",
"pnpm-workspace.yaml"
]
},
"extensions": {
"recommendations": [
"ms-vscode.vscode-typescript-next",
"bradlc.vscode-tailwindcss",
"nrwl.angular-console" // Nx support
]
},
"tasks": {
"version": "2.0.0",
"tasks": [
{
"label": "🥇 Mercury Dev Server",
"type": "shell",
"command": "nx serve mercury-backend",
"group": "build",
"presentation": {
"reveal": "always",
"panel": "new"
}
},
{
"label": "🧪 Mercury Tests",
"type": "shell",
"command": "nx test mercury-backend --watch",
"group": "test"
}
]
}
}

🚀 Cursor 0.50.7 Migration + Learning Plan (Sacred Grail Implementation)

Phase 1: Cursor Mastery Bootcamp (3 дня) 🎓

Цель: Научиться правильно использовать Cursor 0.50.7 и исправить текущие anti-patterns

Day 1: Rules Audit & Cleanup 🧹

Твоя задача: Разобраться с rules хаосом

# 1. Audit текущих rules
find . -name ".cursor" -type d
ls -la .cursor/rules*

# 2. Понять что у тебя есть
cat .cursor/rules # Always rules
find . -name "rules" -path "*/.cursor/*" # Auto attached rules

# 3. Backup & clean start
mv .cursor .cursor-backup-$(date +%Y%m%d)
mkdir .cursor

Learning objectives:

  • Понимаешь разницу Always vs Auto Attached vs Manual rules
  • Знаешь где лежат все твои текущие rules
  • Можешь объяснить когда какой rule применяется

Day 2: @folders Strategy 📁

Твоя задача: Научиться эффективному context management

# Enable full folder contents
Settings > Full folder contents = ON

# Practice @folders commands:
@folders apps/mercury # Test current structure
@folders packages/kaido-talib # Test shared lib
@folders toma/docs/mercury # Test docs

Learning objectives:

  • Понимаешь когда использовать @folders vs @files
  • Знаешь как не перегрузить context
  • Видишь в UI когда файлы не помещаются (icon на context pill)

Day 3: Background Agent Setup 🤖

Твоя задача: Включить и протестировать Background Agent

# Enable Background Agent
Settings > Beta > Background Agent = ON

# Test simple task
Background Agent: "Fix any linting errors in apps/mercury/src"
# Monitor progress, review results

Learning objectives:

  • Умеешь формулировать задачи для background agents
  • Понимаешь как monitor progress
  • Знаешь когда take over vs let agent finish

Phase 2: Domain Structure Migration (4 дня) ⚡

Цель: Migrate к domain structure с multi-root workspaces

Day 1-2: Create Domain Structure 🏗️

# Create new structure
mkdir -p domains/{mercury,arcana,anytracker,maschine}
mkdir -p libs/{core,domain,integrations,deprecated}
mkdir -p platform/{tools,infra,docs}
mkdir -p archive

# Move Mercury (most critical first)
mv apps/mercury domains/mercury/backend
mv apps/mercury-dashboard domains/mercury/dashboard

# Test multi-root workspace
File > Add Folder to Workspace...
- domains/mercury/
- libs/core/

Learning objectives:

  • Понимаешь как создать multi-root workspace
  • Видишь что все папки индексируются отдельно
  • Можешь переключаться между domain contexts

Day 3-4: Rules per Domain 📝

# Create domain-specific rules
domains/mercury/.cursor/rules:
When working in Mercury trading system:
- NEVER import mercury-ta, ALWAYS use kaido-talib
- Use mythological naming: APOLLO, DIKE, TYCHE, KAIROS, MINERVA, MORPHEUS
- NO hardcoded ports (6379, 5432, etc.) - use env vars
- Background jobs MUST use Redis queues
- All modules follow Greek/Roman god naming convention

Learning objectives:

  • Умеешь создавать path-based auto rules
  • Понимаешь как rules наследуются в папках
  • Можешь debug какие rules активны

Phase 3: Background Agent Mastery (3 дня) 🎯

Цель: Освоить parallel development workflow

Day 1: Simple Background Tasks

# Start with easy wins
Background Agent #1: "Update all imports in domains/mercury to use kaido-talib instead of mercury-ta"
Background Agent #2: "Fix any TypeScript errors in domains/arcana"
Background Agent #3: "Update README.md with new domain structure"

Learning objectives:

  • Умеешь decompose tasks для background agents
  • Понимаешь какие задачи подходят для background
  • Можешь monitor multiple agents simultaneously

Day 2: Complex Feature Development

# More challenging tasks
Background Agent: "Implement new DIKE tournament ranking algorithm in Mercury"
# Specification: @folders domains/mercury + detailed requirements

# While agent works, you continue with other tasks
Background Agent #2: "Optimize Arcana tarot spread calculation performance"

Learning objectives:

  • Умеешь давать detailed specifications для complex tasks
  • Понимаешь когда вмешаться в agent work
  • Можешь review и merge agent PRs effectively

Day 3: Parallel Domain Development

# Ultimate test - work on multiple domains
Background Agent #1: "@folders domains/mercury - Add new APOLLO portfolio metrics"
Background Agent #2: "@folders domains/arcana - Improve tarot interpretation accuracy"
Background Agent #3: "@folders libs/domain/kaido-talib - Add new RSI indicator"

# You focus on high-level architecture while agents implement

Learning objectives:

  • Можешь manage 3+ background agents одновременно
  • Умеешь coordinate work между agents (dependencies)
  • Достигнуто 70%+ routine development через agents

Phase 4: Advanced Workflow Optimization (2 дня) 🚀

Day 1: Rules Generation Mastery

# After successful Mercury feature development:
/Generate Cursor Rules

# Review generated rules, refine, deploy to domains/mercury/.cursor/rules
# Test auto-application в новых conversations

Day 2: Archive & Cleanup

# Move deprecated code
mv mercury-ta archive/
mv k8s archive/
mv mcp-task-warrior archive/

# Update multi-root workspace to exclude archive/
# Test @folders performance without deprecated code

Phase 5: Sacred Grail Validation (1 день) 🏆

Цель: Prove that Sacred Grail achieved

Sacred Grail Test Scenarios:

  1. Context Switch Test:

    # Open multi-root workspace
    # @folders domains/mercury
    # Should have instant full context
  2. Parallel Development Test:

    Background Agent #1: "@folders domains/mercury - Optimize DIKE performance"
    Background Agent #2: "@folders domains/arcana - Add new tarot spread"
    # Both should work simultaneously without interference
  3. Rules Auto-Application Test:

    # Open domains/mercury/backend/src/new-feature.ts
    # Rules should auto-apply (no mercury-ta imports, mythological naming)
    # Ask: "Add new APOLLO endpoint"
    # Should follow rules automatically
  4. Learning Validation:

    • Rules не в хаосе - знаешь где что лежит и когда применяется
    • Context management efficient - @folders вместо manual selection
    • Background Agents handle 70%+ routine tasks
    • Parallel development works - Mercury + Arcana simultaneously

🎯 Success Metrics & Graduation:

Ты graduated from Cursor Bootcamp когда:

  • Rules mastery: Понимаешь Always/Auto/Manual, можешь debug active rules
  • Context efficiency: @folders + multi-root вместо manual context restoration
  • Background Agent fluency: 3+ agents working parallel, 70% routine tasks automated
  • Sacred Grail achieved: "Add Mercury feature" → working code first try via Background Agent

Время на migration: 12 дней total (3+4+3+2 дня) Expected ROI: 3x faster development, 70% fewer bugs, 100% confidence in agent work

🏆 РЕЗУЛЬТАТ: Ты становишься Cursor 0.50.7 power user с perfect agentic workflow!

🔧 Technical Implementation Details

Nx Project Configuration

// domains/mercury/project.json
{
"name": "mercury-backend",
"projectType": "application",
"root": "domains/mercury/backend",
"sourceRoot": "domains/mercury/backend/src",
"targets": {
"build": {
"executor": "@nx/node:build",
"options": {
"outputPath": "dist/domains/mercury/backend",
"main": "domains/mercury/backend/src/main.ts",
"tsConfig": "domains/mercury/backend/tsconfig.app.json"
}
},
"serve": {
"executor": "@nx/node:execute",
"options": {
"buildTarget": "mercury-backend:build"
}
},
"test": {
"executor": "@nx/jest:jest",
"options": {
"jestConfig": "domains/mercury/backend/jest.config.ts"
}
}
},
"tags": ["domain:mercury", "type:backend", "scope:production"]
}

pnpm-workspace.yaml

packages:
- 'domains/*/backend'
- 'domains/*/dashboard'
- 'domains/*/mini-app'
- 'libs/*/*'
- 'platform/*'
- 'tools/*'

Intel Bundle Format

interface IntelBundle {
domain: string;
priority: 'high' | 'medium' | 'low';
status: 'production' | 'stable' | 'experimental';
aiManifest: string;
dependencies: string[];
recentCommits: string[];
recentTests: TestSummary;
keyFiles: string[];
nxGraph: NxProjectGraph;
contextInstructions: string[];
}

Этот подход объединяет лучшее от всех моделей и даст тебе Sacred Grail - мгновенный, надежный AI в режиме агента! 🎯

Sacred Grail Achievement: Cursor 0.50.7 Background Agent Mastery 🏆

До (твоя текущая боль + неправильное использование Cursor):

😤 "AI, добавь фичу в Mercury..."

🤯 10+ минут manual context restoration:
- Manually selecting files один за одним
- Rules в хаосе - не знаешь какие применяются
- Explanation архитектуры каждый раз
- mercury-ta vs kaido-talib confusion
- Search релевантных модулей по всему монорепо
- Борьба с noise от других доменов (Arcana, AnyTracker)

😱 2 недели багфиксов после "working" кода:
- Wrong imports (mercury-ta instead of kaido-talib)
- Hardcoded ports (dangerous defaults violated)
- Cross-domain pollution (Arcana code in Mercury)
- Missing Redis queue usage
- Сломанные тесты от context confusion
- Sequential development - одна задача за раз

После (Sacred Grail - Cursor 0.50.7 mastery):

😎 Multi-root workspace already open
↓ (instant setup)
🚀 Background Agent #1: "@folders domains/mercury - Add DIKE tournament optimization"
🚀 Background Agent #2: "@folders domains/arcana - Fix tarot spread calculations"
🚀 Background Agent #3: "@folders libs/domain/kaido-talib - Add new RSI indicator"
↓ (agents work in parallel)
✨ CURSOR 0.50.7 MAGIC HAPPENS:
✅ @folders = instant full domain context (no manual file selection)
✅ Auto rules = каждый agent знает domain правила автоматически
✅ Multi-root = zero cross-domain pollution
✅ Background environments = agents work independently
✅ Path-based rules = mercury правила только в Mercury domain
✅ Parallel execution = 3 tasks simultaneously
↓ (while you focus on architecture)
🎯 30 minutes later:
✅ Agent #1: "DIKE optimization complete - PR ready for review"
✅ Agent #2: "Arcana calculations fixed - tests passing"
✅ Agent #3: "New RSI indicator implemented - docs updated"

🏆 3 FEATURES COMPLETED SIMULTANEOUSLY
- Perfect Mercury mythological naming
- No mercury-ta imports (kaido-talib used correctly)
- No dangerous defaults (env vars used)
- Clean domain separation
- All tests passing
- Zero debugging needed

Конкретный Sacred Grail пример в действии:

# ТЫ (high-level architect mode):
Background Agent: "@folders domains/mercury - Implement new APOLLO portfolio analytics endpoint with DIKE tournament integration"

# CURSOR 0.50.7 автоматически в background environment:
# 1. @folders loads ENTIRE Mercury domain context instantly
# 2. domains/mercury/.cursor/rules auto-apply:
# - NEVER mercury-ta → ALWAYS kaido-talib ✅
# - Mythological naming enforced ✅
# - NO hardcoded ports ✅
# - Redis queues required ✅
# 3. Multi-root workspace prevents Arcana/AnyTracker noise ✅
# 4. Agent implements in background while you continue other work

# ⚡ RESULT (30 minutes later, working first try):
# domains/mercury/backend/src/apollo/portfolio-analytics.controller.ts

import { Controller, Get, Param } from '@nestjs/common';
import { TechnicalAnalysis, RSI } from '@libs/kaido-talib'; // ← Auto-correct import! ✅
import { TournamentService } from '../dike/tournament.service'; // ← Mythological structure! ✅
import { RedisService } from '../redis/redis.service'; // ← Background jobs! ✅

@Controller('apollo/portfolio-analytics') // ← APOLLO naming! ✅
export class PortfolioAnalyticsController {
constructor(
private readonly tournamentService: TournamentService,
private readonly ta: TechnicalAnalysis,
private readonly redis: RedisService
) {}

@Get('tournament/:id/analytics')
async getTournamentAnalytics(@Param('id') id: string) {
// Queue heavy computation ✅
const job = await this.redis.addJob('portfolio-analytics', { tournamentId: id });

// Use DIKE tournament service ✅
const tournament = await this.tournamentService.getResults(id);

// Technical analysis via kaido-talib ✅
const rsi = await this.ta.calculateRSI(tournament.priceData);

return {
tournamentId: id,
analytics: { rsi, trend: tournament.trend },
jobId: job.id
};
}
}

// ✅ Auto-generated tests passing
// ✅ No dangerous defaults (uses env vars)
// ✅ Perfect mythological naming
// ✅ Clean domain separation
// ✅ Ready for production

Измеримые результаты Sacred Grail:

МетрикаДо (старый способ)После Cursor 0.50.7 Power User
Context restoration10+ manual actions1 command (@folders domains/mercury)
Parallel development1 task at a time3+ Background Agents simultaneously
Rules managementChaos, don't understandAuto-apply by path, perfect hierarchy
Bug rate70% code needs fixes<5% (auto rules prevent mistakes)
Development time3 hours per feature30 minutes (background agent workflow)
Context pollutionCross-domain noise0% (multi-root isolation)
Confidence level"половина сломается""works first try"
Routine tasksManual implementation70% automated via Background Agents
Import errorsmercury-ta confusionAuto-corrected to kaido-talib
Domain knowledgeRe-explain each timePersistent in path-based rules

Learning Success Validation:

  • Rules mastery: Из хаоса к полному пониманию Always/Auto/Manual hierarchy
  • Context efficiency: @folders replaced manual file selection completely
  • Background Agent fluency: Managing 3+ parallel agents как senior architect
  • Multi-root expertise: Domain isolation без cross-contamination
  • Sacred Grail achieved: High-level task → working code via Background Agent

🎓 Graduation Test:

"Background Agent: @folders domains/mercury - Add new MINERVA technical analysis feature integrating with TYCHE market rankings"

# Should result in:
✅ Working code first try
✅ Perfect mythological architecture
✅ Zero manual context setup
✅ No debugging needed
✅ Ready for production

Это твой Sacred Grail: Ты превращаешься из manual context warrior в high-level AI architect, управляющего Background Agents с нулевой болью и 100% предсказуемостью, powered by Cursor 0.50.7 mastery! 🚀🏆

Финальный результат: Ты coding как senior architect, agents делают implementation, Mercury развивается в 3x speed без багов! 💪

⚠️ Risk Assessment & Mitigation (минное поле которое мы принимаем)

🚨 Critical Risks We Accept (betting on Cursor evolution)

1. Background Agent Instability (Risk: 8/10) 🤖

Что может сломаться:

  • Agent уходит "в астрал" на complex tasks
  • Генерит код который работает но противоречит архитектуре
  • Debugging agent work = nightmare

Mitigation:

  • Start simple - bug fixes, small features first
  • Staged review - всегда review agent PRs before merge
  • Fallback plan - если agent сломался, возвращаемся к manual mode
  • Learning curve - 3 недели на mastery, ожидаем косяки

2. Rules Auto-Generation Chaos (Risk: 7/10) 📝

Что может сломаться:

  • /Generate Cursor Rules создает conflicting rules
  • Rules drift от реальности (like metrics problem)
  • Rules hierarchy confusion возвращается

Mitigation:

  • Manual review always - never auto-apply generated rules
  • Regular audit - раз в месяц cleaning rules
  • Simple rules first - start with basic domain rules
  • Documentation - каждый rule с примером usage

3. Mercury Migration Risk (Risk: 7/10) 🚚

Что может сломаться:

  • Production system down during migration
  • Import paths broken, build fails
  • Revenue impact if Mercury broken

Mitigation:

  • Staged approach - Mercury last, после тестов на других доменах
  • Full backup - вся текущая structure в archive
  • Rollback plan - готовый script для возврата
  • Testing environment - отдельная среда для migration testing

🤔 Acceptable Risks (worth the potential gains)

4. @folders Context Limitations (Risk: 6/10) 📁

  • Large domains могут не поместиться в context
  • Missing dependencies outside @folders scope

5. Multi-root Workspace Complexity (Risk: 5/10) 🏗️

  • Indexing performance degradation
  • Cross-root dependencies resolution issues

💡 Risk Philosophy

Honest expectation: Первые 2-4 недели = debugging Cursor workflow больше чем actual coding. Это investment period.

ROI timeline:

  • Week 1-2: Pain & learning (negative productivity)
  • Week 3-4: Break-even
  • Month 2+: 3x productivity gains

Fallback strategy: Если Background Agent слишком buggy → manual development + @folders + rules. Still better than current state.

🎯 Contract-Driven Grafana Solution

Problem Statement

Твоя боль: Метрики в коде ≠ панели в Grafana → пустые дашборды, zero информативность

Solution: TypeScript Contracts + Background Agent

Step 1: Metrics Contracts Definition

// libs/core/monitoring/mercury-metrics.contract.ts
export interface MercuryMetricsContract {
apollo: {
portfolio_performance: MetricDefinition<'gauge', 'Portfolio return rate %'>;
active_positions: MetricDefinition<
'counter',
'Number of active trading positions'
>;
portfolio_value_usd: MetricDefinition<
'gauge',
'Total portfolio value in USD'
>;
};
dike: {
tournaments_completed: MetricDefinition<
'counter',
'Completed tournaments count'
>;
tournament_duration_avg: MetricDefinition<
'histogram',
'Average tournament duration'
>;
};
tyche: {
market_ranking_score: MetricDefinition<
'gauge',
'Current market ranking score'
>;
};
}

interface MetricDefinition<T extends MetricType, D extends string> {
type: T;
description: D;
grafanaPanel: 'stat' | 'graph' | 'heatmap';
prometheusQuery: string;
}

Step 2: Code Metrics Implementation

// domains/mercury/backend/src/apollo/apollo.metrics.ts
import { createMetrics } from '@libs/core/monitoring';
import type { MercuryMetricsContract } from '@libs/core/monitoring/mercury-metrics.contract';

export const apolloMetrics = createMetrics<MercuryMetricsContract['apollo']>({
portfolio_performance: {
type: 'gauge',
description: 'Portfolio return rate %',
grafanaPanel: 'stat',
prometheusQuery: 'mercury_apollo_portfolio_return_rate',
},
// TypeScript FORCES us to implement all contract metrics
});

Step 3: Contract-Validated Dashboards

// platform/grafana/dashboards/mercury.dashboard.ts
import type { MercuryMetricsContract } from '@libs/core/monitoring/mercury-metrics.contract';

export const mercuryDashboard = createDashboard<MercuryMetricsContract>({
title: 'Mercury Trading System',
panels: [
{
metric: 'apollo.portfolio_performance', // ← TypeScript validation!
title: 'Portfolio Performance',
type: 'stat',
},
{
metric: 'dike.tournaments_completed', // ← Must exist in contract
title: 'Tournaments Completed',
type: 'graph',
},
// metric: 'nonexistent.metric' ← COMPILATION ERROR!
],
});

Step 4: Background Agent Automation

# Auto-sync Grafana JSON from TypeScript definitions
Background Agent: "@folders platform/grafana - Generate Grafana JSON configs from TypeScript dashboard definitions"

# Auto-cleanup unused panels
Background Agent: "@folders platform/grafana - Remove any panels that don't have corresponding metrics in contracts"

Guaranteed Benefits:

  • Impossible to deploy broken dashboard (TypeScript compilation fails)
  • No metrics drift - code metrics = single source of truth
  • Auto-cleanup via Background Agent
  • Better metrics - forced to think about description & purpose
  • Domain isolation - Mercury metrics in Mercury contracts only

Contract-Driven Rules:

# domains/mercury/.cursor/rules
When working with metrics in Mercury:
- ALL metrics MUST be defined in MercuryMetricsContract first
- NO direct Prometheus metrics without TypeScript contract
- Background Agent MUST validate dashboard sync weekly
- Remove any metric unused for 30+ days from contract

Result: Твои дашборды finally информативны, sync с реальными метриками guaranteed! 📊✅