From aaded8ace4a4c2841e0a1aa76676d64562ddd453 Mon Sep 17 00:00:00 2001 From: "Mikhail [azalio] Petrov" Date: Tue, 11 Nov 2025 22:42:51 +0300 Subject: [PATCH 1/2] feat(agents): integrate 18 Cipher MCP tools across all 8 MAP agents Enhanced all MAP Framework agents to leverage available MCP tools for: - Reasoning memory (search/store/extract/evaluate reasoning patterns) - Knowledge graph (dependency tracking, impact analysis) - Intelligent processing (entity extraction, conflict detection) - Cross-project learning (cipher sync with deduplication) Changes by agent: **task-decomposer.md**: - Added cipher_search_reasoning_patterns as tool #2 - Learn from HOW successful decompositions were reasoned - Comprehensive examples showing WHY vs WHAT learning **actor.md**: - Added 6-step decision tree for tool selection - Added 3 Tool Combination Scenarios (JWT, WebSocket, caching) - Detailed examples for context7, deepwiki, codex-bridge usage **monitor.md**: - Added cipher_search_graph for dependency understanding - Added cipher_get_neighbors for tracing chains - Added cipher_add_node/add_edge for recording validation results **predictor.md**: - Added knowledge graph tools for impact analysis - Added cipher_intelligent_processor for NL impact statements - Integrated graph traversal for dependency chains **evaluator.md**: - Added cipher_search_reasoning_patterns - Learn from past evaluation reasoning patterns **reflector.md**: - Added 4 reasoning memory tools: - cipher_search_reasoning_patterns - cipher_store_reasoning_memory - cipher_extract_reasoning_steps - cipher_evaluate_reasoning - Enables meta-learning from reasoning processes **curator.md**: - Added cipher_intelligent_processor for entity extraction - Enhanced cipher_extract_and_operate_memory with: - Improved confidence thresholds (0.85 similarity, 0.7 confidence) - enableDeleteOperations: false to prevent accidents - Added comprehensive deduplication examples **Template Sync**: All changes synchronized to src/mapify_cli/templates/agents/ Verified with scripts/check-template-sync.sh **Key Benefits**: - Deduplication: Search cipher before creating knowledge - Meta-learning: Learn HOW problems are solved - Knowledge graph: Track dependencies and analyze impact - Cross-project: Share proven patterns (helpful_count >= 5) - Current docs: context7 ensures up-to-date library APIs Dual memory system (Playbook + Cipher) now fully operational! --- .claude/agents/actor.md | 239 +++++++++++++++++- .claude/agents/curator.md | 125 ++++++++- .claude/agents/evaluator.md | 4 + .claude/agents/monitor.md | 16 ++ .claude/agents/predictor.md | 20 +- .claude/agents/reflector.md | 20 ++ .claude/agents/task-decomposer.md | 89 ++++++- src/mapify_cli/templates/agents/actor.md | 239 +++++++++++++++++- src/mapify_cli/templates/agents/curator.md | 125 ++++++++- src/mapify_cli/templates/agents/evaluator.md | 4 + src/mapify_cli/templates/agents/monitor.md | 16 ++ src/mapify_cli/templates/agents/predictor.md | 20 +- src/mapify_cli/templates/agents/reflector.md | 20 ++ .../templates/agents/task-decomposer.md | 89 ++++++- 14 files changed, 1002 insertions(+), 24 deletions(-) diff --git a/.claude/agents/actor.md b/.claude/agents/actor.md index 8480f6f9..969f9722 100644 --- a/.claude/agents/actor.md +++ b/.claude/agents/actor.md @@ -28,8 +28,112 @@ BEFORE implementing, ask yourself: 5. Did my solution work? (After Monitor approval) → cipher_extract_and_operate_memory ``` +### Detailed Decision Tree: When to Use Which Tool + +``` +START: Implementing subtask + +STEP 1 - Historical Knowledge Check: + ├─ ALWAYS → cipher_memory_search first + │ Query: "implementation pattern [feature_type] [language]" + │ Found relevant patterns? + │ ├─ YES → Use as starting point, proceed to STEP 2 + │ └─ NO → Proceed to STEP 2 (no historical precedent) + +STEP 2 - External Library/Framework Check: + ├─ Does implementation use external library/framework? + │ ├─ YES → Which kind? + │ │ ├─ Well-known library (React, Django, Express)? + │ │ │ └─ → context7 (get current API docs) + │ │ │ Topic: specific feature you're implementing + │ │ │ Example: "authentication", "routing", "database models" + │ │ │ + │ │ └─ Obscure/niche library OR want implementation examples? + │ │ └─ → deepwiki (find repos using it) + │ │ Example: "How does [popular_repo] use [library]?" + │ │ + │ └─ NO → Proceed to STEP 3 + +STEP 3 - Implementation Complexity Check: + ├─ Is this algorithmically complex OR unfamiliar domain? + │ Examples: + │ - Complex data structures (graph traversal, LRU cache, priority queue) + │ - Performance-critical algorithms (batch processing, streaming) + │ - Unfamiliar APIs (WebSocket protocol, OAuth flow, GraphQL resolvers) + │ - Concurrent programming (locks, async/await patterns, race conditions) + │ │ + │ ├─ YES → codex-bridge (consult_codex) + │ │ Use for: Code generation with specific constraints + │ │ Example: "Generate Python async batch processor with exponential backoff" + │ │ + │ └─ NO → Proceed to STEP 4 (standard implementation) + +STEP 4 - Architectural Guidance Check: + ├─ Do I need to see production-quality implementation examples? + │ Use Cases: + │ - Unsure about project structure (where files go, how to organize) + │ - Need to see error handling patterns in production code + │ - Want to understand testing approach for similar features + │ - Unclear on how to integrate with existing architecture + │ │ + │ ├─ YES → deepwiki (read_wiki_structure + read_wiki_contents) + │ │ Query: "How does [mature_project] structure [feature]?" + │ │ Example: "How does Next.js repo organize API routes?" + │ │ + │ └─ NO → You have enough context, proceed to implementation + +STEP 5 - Implementation Phase: + └─ Write code using gathered knowledge from Steps 1-4 + +STEP 6 - Post-Implementation (AFTER Monitor approval): + └─ → cipher_extract_and_operate_memory + Store: Pattern name, code snippet, context, trade-offs + Options: useLLMDecisions: false, similarityThreshold: 0.85 +``` + +### Tool Combination Scenarios + +**Scenario A: Implementing JWT authentication (common feature, well-documented library)** +``` +1. cipher_memory_search("JWT authentication implementation") + → Found: 2 past implementations with security considerations +2. context7.get-library-docs("/PyJWT/PyJWT", topic="authentication") + → Got: Current API for encode/decode, best practices for secret management +3. SKIP codex-bridge (JWT is standard, not algorithmically complex) +4. SKIP deepwiki (have enough context from cipher + docs) +5. Implement using cipher patterns + current API docs +6. AFTER approval: cipher_extract_and_operate_memory(successful pattern) +``` + +**Scenario B: Implementing WebSocket real-time notifications (complex, unfamiliar)** +``` +1. cipher_memory_search("WebSocket implementation real-time") + → Found: 1 past implementation but for different framework +2. context7.get-library-docs("/django/channels", topic="consumers authentication") + → Got: Current Channels API, but unclear on production patterns +3. deepwiki.ask_question("django/channels", "How to structure WebSocket consumers for scalability?") + → Got: Production example showing consumer organization, channel layers, Redis integration +4. codex-bridge.consult_codex("Generate Django Channels consumer with authentication and message routing") + → Got: Code template for complex async consumer logic +5. Implement combining: past experience + current docs + production patterns + generated code +6. AFTER approval: cipher_extract_and_operate_memory(comprehensive WebSocket pattern) +``` + +**Scenario C: Implementing custom caching strategy (algorithmic, no library)** +``` +1. cipher_memory_search("LRU cache implementation") + → Found: Nothing relevant (novel for this project) +2. SKIP context7 (no external library) +3. codex-bridge.consult_codex("Generate Python LRU cache with TTL using OrderedDict") + → Got: Efficient implementation with time complexity analysis +4. deepwiki.ask_question("requests/requests", "How does requests library implement caching?") + → Got: Production-quality caching patterns, error handling, thread safety +5. Implement combining: generated algorithm + production patterns +6. AFTER approval: cipher_extract_and_operate_memory(new caching pattern) +``` + ### 1. mcp__cipher__cipher_memory_search -**Use When**: Starting any implementation to find existing patterns +**Use When**: ALWAYS - starting any implementation to find existing patterns **Query Patterns**: - `"implementation pattern [feature_type]"` - Find how we've built similar features - `"error solution [error_type]"` - Learn from past error fixes @@ -37,6 +141,29 @@ BEFORE implementing, ask yourself: **Rationale**: Avoid reinventing solutions. Past patterns prevent common errors and save time. + +**Task**: Implement user authentication with password reset + +**Actor Process**: +1. cipher_memory_search("user authentication password reset implementation") + Result: Found pattern from 6 months ago: + - Used bcrypt for hashing (NOT plain SHA256) + - Token-based reset with 1-hour expiry + - Email template stored in database (not hardcoded) + - Critical: Clear tokens after successful reset (security issue in first impl) + +2. Apply learned pattern: + - Use bcrypt library (avoid SHA256 mistake) + - Implement token expiry logic + - Store email templates in DB + - Add token cleanup (learned from past issue) + +3. Implementation benefited from historical knowledge: + - Avoided security vulnerability (token not cleared) + - Used correct hashing algorithm + - Followed established pattern (faster development) + + ### 2. mcp__context7__get-library-docs **Use When**: Working with external libraries/frameworks **Process**: @@ -47,6 +174,37 @@ BEFORE implementing, ask yourself: **Rationale**: Training data may be outdated. Current docs prevent using deprecated APIs or missing new features. + +**Task**: Implement Next.js API route with middleware for authentication + +**Actor Process**: +1. resolve-library-id("Next.js") + Result: library_id = "/vercel/next.js" + +2. get-library-docs("/vercel/next.js", topic="api routes middleware") + Result: Got current API (Next.js 14): + - Use export const config = { matcher: [...] } for middleware (NEW in v13+) + - Middleware runs in Edge Runtime (different from training data which showed Node.js runtime) + - Response.next() replaces old NextResponse (BREAKING CHANGE) + +3. Implement using CURRENT API: + ```typescript + // middleware.ts + export const config = { + matcher: '/api/:path*', // NEW syntax + } + + export function middleware(request: Request) { + return Response.next(); // CURRENT API + } + ``` + +4. Implementation benefited from current docs: + - Used correct v14 syntax (not outdated v12 from training) + - Avoided deprecated APIs (NextResponse) + - Understood Edge Runtime limitations + + ### 3. mcp__codex-bridge__consult_codex **Use When**: Implementing complex algorithms or unfamiliar APIs **Query Format**: `"Generate [language] code for [specific_task]"` @@ -57,6 +215,46 @@ BEFORE implementing, ask yourself: **Rationale**: Specialized code generation for algorithmically complex tasks. + +**Task**: Implement retry logic with exponential backoff for API calls + +**Actor Process**: +1. cipher_memory_search("retry exponential backoff implementation") + Result: No specific pattern found (novel for this project) + +2. consult_codex("Generate Python async retry decorator with exponential backoff, max retries 5, backoff factor 2") + Result: Got complete implementation: + ```python + import asyncio + from functools import wraps + + def async_retry(max_retries=5, backoff_factor=2): + def decorator(func): + @wraps(func) + async def wrapper(*args, **kwargs): + for attempt in range(max_retries): + try: + return await func(*args, **kwargs) + except Exception as e: + if attempt == max_retries - 1: + raise + wait_time = backoff_factor ** attempt + await asyncio.sleep(wait_time) + return wrapper + return decorator + ``` + +3. Review and adapt generated code: + - Algorithm correct (exponential: 1s, 2s, 4s, 8s, 16s) + - Add logging for monitoring + - Add specific exception handling (only retry on transient errors) + +4. Implementation benefited from code generation: + - Complex async decorator pattern generated correctly + - Proper exception handling flow + - Saved 30+ minutes of algorithm design + + ### 4. mcp__deepwiki__read_wiki_structure + read_wiki_contents **Use When**: Learning architectural patterns from successful projects **Process**: @@ -65,6 +263,45 @@ BEFORE implementing, ask yourself: **Rationale**: Learn from battle-tested production code, not theoretical examples. + +**Task**: Implement GraphQL API with authentication and data loaders + +**Actor Process**: +1. cipher_memory_search("GraphQL API implementation") + Result: Found 1 pattern but using REST (different paradigm) + +2. context7.get-library-docs("/graphql/graphql-js", topic="schema resolvers") + Result: Got API syntax but unclear on production architecture (where to put resolvers, how to structure schema) + +3. ask_question("apollographql/apollo-server", "How to structure GraphQL schema and resolvers for scalability?") + Result: Learned production patterns: + - Schema-first approach (define .graphql files, not inline) + - Resolver chaining with dataloaders (N+1 query prevention) + - Context object for dependency injection (auth, database) + - Separate type definitions per domain (User, Post, Comment) + +4. Implement using production pattern: + ``` + src/graphql/ + ├── schema/ + │ ├── user.graphql + │ ├── post.graphql + │ └── index.ts (merge schemas) + ├── resolvers/ + │ ├── user.ts + │ ├── post.ts + │ └── index.ts (merge resolvers) + └── dataloaders/ + └── user.ts (batch loading) + ``` + +5. Implementation benefited from production example: + - Proper project structure (scalable, maintainable) + - Dataloader pattern (performance optimization) + - Context injection (testability) + - Avoided N+1 query problem from the start + + ### 5. mcp__cipher__cipher_extract_and_operate_memory **Use When**: AFTER Monitor validates your solution successfully **What to Store**: diff --git a/.claude/agents/curator.md b/.claude/agents/curator.md index de8c764d..954fe78b 100644 --- a/.claude/agents/curator.md +++ b/.claude/agents/curator.md @@ -49,9 +49,24 @@ BEFORE creating operations, ask yourself: → Builds cross-project knowledge base ``` -### 1. mcp__cipher__cipher_memory_search +### 1. mcp__cipher__cipher_intelligent_processor (NEW) + +**Use When**: Processing Reflector lessons into structured bullets +**Purpose**: Automatically extract entities and detect conflicts + +**Example**: +``` +Text: "Use bcrypt for password hashing, NOT MD5. Store salt separately." +→ Extracts: entities[bcrypt, MD5, password, salt], relationships[use, avoid] +→ Auto-detects: conflict with existing "MD5 password" bullet (deprecate old one) +``` + +**Why**: Reduces manual entity extraction, catches conflicts automatically + +### 2. mcp__cipher__cipher_memory_search **Use When**: +- AFTER intelligent_processor extracts entities (for targeted search) - Before creating ADD operations (check for duplicates) - When Reflector suggests new bullet (validate novelty) - When updating bullets (find related patterns) @@ -151,10 +166,114 @@ Result: Current, accurate recommendation. options: { useLLMDecisions: false, // Use similarity-based logic (predictable) similarityThreshold: 0.85, // Only 85%+ similar memories trigger UPDATE - confidenceThreshold: 0.7 // Minimum confidence required + confidenceThreshold: 0.7, // Minimum confidence required + enableDeleteOperations: false // Prevent accidental deletions } ``` -This prevents cipher from aggressively UPDATE-ing unrelated memories. +This prevents cipher from aggressively UPDATE-ing unrelated memories or deleting existing knowledge. + + + +**Scenario**: Playbook bullet "perf-0023" just crossed helpful_count threshold (5→6) + +**Step 1: Check Cipher for Existing Pattern** +```javascript +// Before syncing, search cipher +const cipherResults = await cipher_memory_search({ + query: "Redis caching TTL pattern", + top_k: 5, + similarity_threshold: 0.7 +}); + +// Found existing cipher memory with similarity 0.88 +// Memory ID: mem-cipher-0156 +// Content: "Redis caching with expiration keys for session data" +// Helpful count: 12 +``` + +**Step 2: Decision - UPDATE vs ADD** +```javascript +if (cipherResults.length > 0 && cipherResults[0].similarity >= 0.85) { + // High similarity - UPDATE existing cipher memory + operation = "UPDATE"; + reasoning = "Similar pattern exists in cipher (similarity 0.88). " + + "Merging playbook insights to enhance existing memory."; +} else { + // Low similarity or no match - ADD new cipher memory + operation = "ADD"; + reasoning = "Novel pattern not found in cipher. Adding as new cross-project knowledge."; +} +``` + +**Step 3: Sync with Correct Options** +```javascript +await cipher_extract_and_operate_memory({ + interaction: bulletContent, + options: { + useLLMDecisions: false, // Disable LLM (use similarity-based) + similarityThreshold: 0.85, // Only UPDATE if 85%+ similar + confidenceThreshold: 0.7, // Minimum confidence + enableDeleteOperations: false // Never delete existing memories + }, + memoryMetadata: { + source: "playbook", + projectId: "map-framework", + helpful_count: 6, // Evidence of quality + bullet_id: "perf-0023" + } +}); +``` + +**Result**: Existing cipher memory mem-cipher-0156 enhanced with playbook TTL details. No duplicate created. + + + + + +**Scenario**: New security pattern with helpful_count=5, no similar cipher memory + +**Step 1: Search Cipher** +```javascript +const cipherResults = await cipher_memory_search({ + query: "JWT signature verification PyJWT verify parameter", + top_k: 5, + similarity_threshold: 0.7 +}); + +// Result: No matches found (max similarity 0.42 with unrelated pattern) +``` + +**Step 2: Decision - ADD to Cipher** +```javascript +// Novel pattern - safe to ADD +await cipher_extract_and_operate_memory({ + interaction: ` + JWT Signature Verification: Always verify HMAC signatures when decoding JWTs. + PyJWT defaults to verify=False - production MUST use verify=True. + + Code: + import jwt + data = jwt.decode(token, secret, algorithms=['HS256'], options={'verify_signature': True}) + `, + options: { + useLLMDecisions: false, + similarityThreshold: 0.85, + confidenceThreshold: 0.7, + enableDeleteOperations: false + }, + memoryMetadata: { + source: "playbook", + bullet_id: "sec-0034", + helpful_count: 5, + domain: "security", + language: "python" + } +}); +``` + +**Result**: New cipher memory created. Available across all projects using Cipher. + + diff --git a/.claude/agents/evaluator.md b/.claude/agents/evaluator.md index 10a4f3cd..cdde052d 100644 --- a/.claude/agents/evaluator.md +++ b/.claude/agents/evaluator.md @@ -215,6 +215,10 @@ ALWAYS: IF complex architectural decisions: → cipher_memory_search: "quality metrics [feature]", "performance benchmark [op]", "best practice score [tech]" +IF learning from past evaluation reasoning: + → cipher_search_reasoning_patterns (NEW): "quality assessment for [feature]", "scoring rationale [pattern]" + → Understand WHY past implementations scored high/low, apply reasoning + IF previous implementations exist: → get_review_history (compare solutions, learn from past issues, maintain scoring consistency) diff --git a/.claude/agents/monitor.md b/.claude/agents/monitor.md index 27d40d86..fb344dd6 100644 --- a/.claude/agents/monitor.md +++ b/.claude/agents/monitor.md @@ -59,6 +59,22 @@ request_review({ **Queries**: `"code review issue [pattern]"`, `"security vulnerability [code]"`, `"anti-pattern [tech]"`, `"test anti-pattern [type]"` **Rationale**: Past issues repeat—prevent regressions +### 2a. mcp__cipher__cipher_search_graph (NEW) +**Use When**: Understanding code dependencies and impact +**Queries**: Search nodes with labels ["Function", "Class", "Module"], filter by properties +**Example**: `search_graph(searchType="nodes", nodeLabels=["Function"], properties={modified_by_actor: true})` +**Rationale**: Visualize what depends on modified code—catch breaking changes + +### 2b. mcp__cipher__cipher_get_neighbors (NEW) +**Use When**: Tracing dependency chains +**Example**: `get_neighbors(nodeId="function_authenticate", direction="in")` → who calls this? +**Rationale**: Find all call sites—ensure changes don't break callers + +### 2c. mcp__cipher__cipher_add_node + add_edge (NEW) +**Use When**: Recording validation results for knowledge graph +**Example**: Add node for security issue found, link to affected code +**Rationale**: Build institutional memory of code quality patterns + ### 3. mcp__sequential-thinking__sequentialthinking **Use When**: Complex logic (workflows, conditionals, concurrency, edge cases) **Decision Context**: diff --git a/.claude/agents/predictor.md b/.claude/agents/predictor.md index dc2de60c..c021b869 100644 --- a/.claude/agents/predictor.md +++ b/.claude/agents/predictor.md @@ -70,14 +70,28 @@ ALWAYS: - Query: "migration strategy [similar_change]" - Learn from past impact analyses -IF complex dependency graph: - 2. THEN → consult_codex (automated dependency analysis) +IF analyzing dependency chains: + 2. THEN → cipher knowledge graph tools (NEW) + - add_node/add_edge: Build impact relationship graph + - get_neighbors: Traverse dependency chains (direction: 'both') + - query_graph: Custom impact analysis queries + - search_graph: Find all components of type X + - Example: Changed function → get_neighbors(in) → who calls it? + +IF complex codebase analysis: + 3. THEN → consult_codex (automated dependency analysis) - Query: "Find all usages of [function/class] in codebase" - Query: "Analyze dependencies for [component]" - Gets exhaustive list of affected code +IF natural language impact statement: + 4. THEN → intelligent_processor (NEW) + - Process: "API endpoint /users changed signature" + - Extracts: entities (endpoint, signature), relationships + - Auto-creates graph nodes/edges for impact tracking + IF external library involved: - 3. THEN → get-library-docs (compatibility check) + 5. THEN → get-library-docs (compatibility check) - Query: Changes between versions (migration guides) - Identify deprecated APIs - Understand breaking changes in library updates diff --git a/.claude/agents/reflector.md b/.claude/agents/reflector.md index 52cde62d..a66ad155 100644 --- a/.claude/agents/reflector.md +++ b/.claude/agents/reflector.md @@ -52,6 +52,26 @@ You are an expert learning analyst who extracts reusable patterns and insights f - Query patterns: "error pattern [type]", "success pattern [feature]", "root cause [technology]" - Why: Avoid re-learning known lessons, reference existing patterns +**mcp__cipher__cipher_search_reasoning_patterns** (NEW) +- Use when: Finding similar reasoning traces, learning meta-patterns +- Query: "successful debugging reasoning [domain]", "root cause analysis patterns" +- Why: Learn HOW experts think through problems, not just WHAT they concluded + +**mcp__cipher__cipher_store_reasoning_memory** (NEW) +- Use when: AFTER extracting lessons, storing complete reasoning trace +- What to store: Thought process, decision points, trade-offs evaluated +- Why: Future Reflectors learn from reasoning process, not just outcomes + +**mcp__cipher__cipher_extract_reasoning_steps** (NEW) +- Use when: Structuring complex failure analysis into reasoning steps +- Process: Converts narrative analysis → structured [thought, action, observation] steps +- Why: Enables better reasoning search and quality assessment + +**mcp__cipher__cipher_evaluate_reasoning** (NEW) +- Use when: BEFORE storing reasoning, assess quality and completeness +- Checks: Reasoning loops, efficiency, issue detection, suggestions +- Why: Only store high-quality reasoning traces (quality gate) + **mcp__context7__resolve-library-id + get-library-docs** - Use when: Library API misuse, verify usage patterns, recommend API changes - Process: resolve-library-id → get-library-docs with topic diff --git a/.claude/agents/task-decomposer.md b/.claude/agents/task-decomposer.md index 81b9bd70..d2cd2aed 100644 --- a/.claude/agents/task-decomposer.md +++ b/.claude/agents/task-decomposer.md @@ -43,15 +43,22 @@ ALWAYS: - Query: "architecture pattern [component_type]" - Learn what worked (and what didn't) +IF similar features exist historically: + 2. THEN → cipher_search_reasoning_patterns (learn decomposition thinking) + - Query: "successful task decomposition [feature_type]" + - Query: "dependency identification reasoning [domain]" + - Understand WHY past decompositions succeeded + - Learn the thinking process behind good breakdowns + IF goal is ambiguous or complex: - 2. THEN → sequentialthinking (iterative refinement) + 3. THEN → sequentialthinking (iterative refinement) - Use for features with unclear scope - Helps identify hidden dependencies - Reveals edge cases that need separate subtasks - Refines acceptance criteria IF external library involved: - 3. THEN → get-library-docs (implementation order) + 4. THEN → get-library-docs (implementation order) - Query: Setup/quickstart guides - Understand required initialization order - Identify configuration dependencies @@ -100,7 +107,78 @@ Decomposing without historical context: - Create subtasks that are too coarse or too granular -### 2. mcp__sequential-thinking__sequentialthinking +### 2. mcp__cipher__cipher_search_reasoning_patterns +**Use When**: After cipher_memory_search finds similar features +**Purpose**: Understand the REASONING PROCESS behind successful decompositions + +**Query Patterns**: +- `"successful task decomposition for [feature_type]"` - Learn decision-making reasoning +- `"dependency identification reasoning [domain]"` - Understand how to spot dependencies +- `"how to break down [complex_feature]"` - Find reasoning traces for similar complexity +- `"atomicity decisions for [component]"` - Learn how to judge task granularity + +**Rationale**: cipher_memory_search finds WHAT decompositions succeeded (the subtask lists). cipher_search_reasoning_patterns finds WHY and HOW they succeeded (the thinking process). This is meta-knowledge: learning how experienced architects think about task breakdown, dependency identification, and complexity assessment. + +**Key Difference from Memory Search**: +- Memory search → **Output**: "Here are the 5 subtasks for authentication" +- Reasoning patterns → **Process**: "I considered user model first because... then password hashing because... dependencies emerged when..." + + +Problem: Decomposing "Add real-time notifications" + +**Step 1 - cipher_memory_search (WHAT worked)**: +- Query: "feature implementation notifications" +- Result: Found 3 past implementations with subtask lists: + 1. WebSocket infrastructure setup + 2. Notification database models + 3. User authentication integration + 4. Notification delivery service + 5. UI components for displaying notifications + +**Gap**: Why this order? What dependency reasoning led to this sequence? + +**Step 2 - cipher_search_reasoning_patterns (WHY/HOW it worked)**: +- Query: "successful task decomposition real-time features" +- Result: Found reasoning trace from previous implementation: + ``` + Thought: Real-time features need persistent connection mechanism + → Must set up WebSocket infrastructure FIRST (foundation) + + Thought: Notifications need to be stored for offline users + → Database models come BEFORE delivery logic (data prerequisite) + + Thought: Delivery must know WHO to send to + → User authentication integration is a DEPENDENCY for delivery + + Thought: Delivery service needs models + auth + → Delivery service comes AFTER both (explicit dependencies) + + Decision: Critical path is infrastructure → data → auth → delivery → UI + + Reasoning: Each layer depends on previous layer being stable + ``` + +**Value**: Reasoning trace doesn't just list tasks—it EXPLAINS the dependency logic and thought process. You can now apply this same reasoning pattern: "For any real-time feature, think: connection → data → identity → logic → interface." + +This meta-knowledge generalizes beyond just notifications. + + + +**Use BOTH tools together for best results**: + +1. **cipher_memory_search** → Find historical examples (concrete instances) +2. **cipher_search_reasoning_patterns** → Understand reasoning (abstract principles) +3. **Apply to current task** → Use both examples AND principles + +Example workflow: +- Task: "Add OAuth2 social login" +- Memory search: Find 2 past OAuth implementations +- Reasoning search: Find "oauth integration decomposition reasoning" +- Learn: Both WHAT was done (provider setup, callback handling, token storage) AND WHY (provider first because callback needs it, token storage before user association) +- Apply: Create decomposition using proven sequence + understanding the dependency logic + + +### 3. mcp__sequential-thinking__sequentialthinking **Use When**: Complex, ambiguous, or unfamiliar goals **Purpose**: Iteratively refine understanding and uncover hidden complexity @@ -124,7 +202,7 @@ Decomposing without historical context: - "Fix typo in error message" (atomic, no decomposition needed) -### 3. mcp__context7__get-library-docs +### 4. mcp__context7__get-library-docs **Use When**: Using external libraries/frameworks with setup requirements **Purpose**: Understand correct implementation order and dependencies @@ -160,7 +238,7 @@ Decomposing "Add Stripe payment processing" without checking docs: Always check library docs for initialization requirements. -### 4. mcp__deepwiki__read_wiki_structure + ask_question +### 5. mcp__deepwiki__read_wiki_structure + ask_question **Use When**: Unfamiliar domains or architectural decisions **Purpose**: Learn how mature projects structure similar features @@ -347,6 +425,7 @@ Subtasks should be ordered by dependency: **Analysis Completeness**: - [ ] Ran cipher_memory_search for similar features +- [ ] Ran cipher_search_reasoning_patterns to understand decomposition thinking - [ ] Used sequential-thinking for complex/ambiguous goals - [ ] Checked library docs for initialization requirements - [ ] Identified all risks (not empty for medium/high complexity) diff --git a/src/mapify_cli/templates/agents/actor.md b/src/mapify_cli/templates/agents/actor.md index 8480f6f9..969f9722 100644 --- a/src/mapify_cli/templates/agents/actor.md +++ b/src/mapify_cli/templates/agents/actor.md @@ -28,8 +28,112 @@ BEFORE implementing, ask yourself: 5. Did my solution work? (After Monitor approval) → cipher_extract_and_operate_memory ``` +### Detailed Decision Tree: When to Use Which Tool + +``` +START: Implementing subtask + +STEP 1 - Historical Knowledge Check: + ├─ ALWAYS → cipher_memory_search first + │ Query: "implementation pattern [feature_type] [language]" + │ Found relevant patterns? + │ ├─ YES → Use as starting point, proceed to STEP 2 + │ └─ NO → Proceed to STEP 2 (no historical precedent) + +STEP 2 - External Library/Framework Check: + ├─ Does implementation use external library/framework? + │ ├─ YES → Which kind? + │ │ ├─ Well-known library (React, Django, Express)? + │ │ │ └─ → context7 (get current API docs) + │ │ │ Topic: specific feature you're implementing + │ │ │ Example: "authentication", "routing", "database models" + │ │ │ + │ │ └─ Obscure/niche library OR want implementation examples? + │ │ └─ → deepwiki (find repos using it) + │ │ Example: "How does [popular_repo] use [library]?" + │ │ + │ └─ NO → Proceed to STEP 3 + +STEP 3 - Implementation Complexity Check: + ├─ Is this algorithmically complex OR unfamiliar domain? + │ Examples: + │ - Complex data structures (graph traversal, LRU cache, priority queue) + │ - Performance-critical algorithms (batch processing, streaming) + │ - Unfamiliar APIs (WebSocket protocol, OAuth flow, GraphQL resolvers) + │ - Concurrent programming (locks, async/await patterns, race conditions) + │ │ + │ ├─ YES → codex-bridge (consult_codex) + │ │ Use for: Code generation with specific constraints + │ │ Example: "Generate Python async batch processor with exponential backoff" + │ │ + │ └─ NO → Proceed to STEP 4 (standard implementation) + +STEP 4 - Architectural Guidance Check: + ├─ Do I need to see production-quality implementation examples? + │ Use Cases: + │ - Unsure about project structure (where files go, how to organize) + │ - Need to see error handling patterns in production code + │ - Want to understand testing approach for similar features + │ - Unclear on how to integrate with existing architecture + │ │ + │ ├─ YES → deepwiki (read_wiki_structure + read_wiki_contents) + │ │ Query: "How does [mature_project] structure [feature]?" + │ │ Example: "How does Next.js repo organize API routes?" + │ │ + │ └─ NO → You have enough context, proceed to implementation + +STEP 5 - Implementation Phase: + └─ Write code using gathered knowledge from Steps 1-4 + +STEP 6 - Post-Implementation (AFTER Monitor approval): + └─ → cipher_extract_and_operate_memory + Store: Pattern name, code snippet, context, trade-offs + Options: useLLMDecisions: false, similarityThreshold: 0.85 +``` + +### Tool Combination Scenarios + +**Scenario A: Implementing JWT authentication (common feature, well-documented library)** +``` +1. cipher_memory_search("JWT authentication implementation") + → Found: 2 past implementations with security considerations +2. context7.get-library-docs("/PyJWT/PyJWT", topic="authentication") + → Got: Current API for encode/decode, best practices for secret management +3. SKIP codex-bridge (JWT is standard, not algorithmically complex) +4. SKIP deepwiki (have enough context from cipher + docs) +5. Implement using cipher patterns + current API docs +6. AFTER approval: cipher_extract_and_operate_memory(successful pattern) +``` + +**Scenario B: Implementing WebSocket real-time notifications (complex, unfamiliar)** +``` +1. cipher_memory_search("WebSocket implementation real-time") + → Found: 1 past implementation but for different framework +2. context7.get-library-docs("/django/channels", topic="consumers authentication") + → Got: Current Channels API, but unclear on production patterns +3. deepwiki.ask_question("django/channels", "How to structure WebSocket consumers for scalability?") + → Got: Production example showing consumer organization, channel layers, Redis integration +4. codex-bridge.consult_codex("Generate Django Channels consumer with authentication and message routing") + → Got: Code template for complex async consumer logic +5. Implement combining: past experience + current docs + production patterns + generated code +6. AFTER approval: cipher_extract_and_operate_memory(comprehensive WebSocket pattern) +``` + +**Scenario C: Implementing custom caching strategy (algorithmic, no library)** +``` +1. cipher_memory_search("LRU cache implementation") + → Found: Nothing relevant (novel for this project) +2. SKIP context7 (no external library) +3. codex-bridge.consult_codex("Generate Python LRU cache with TTL using OrderedDict") + → Got: Efficient implementation with time complexity analysis +4. deepwiki.ask_question("requests/requests", "How does requests library implement caching?") + → Got: Production-quality caching patterns, error handling, thread safety +5. Implement combining: generated algorithm + production patterns +6. AFTER approval: cipher_extract_and_operate_memory(new caching pattern) +``` + ### 1. mcp__cipher__cipher_memory_search -**Use When**: Starting any implementation to find existing patterns +**Use When**: ALWAYS - starting any implementation to find existing patterns **Query Patterns**: - `"implementation pattern [feature_type]"` - Find how we've built similar features - `"error solution [error_type]"` - Learn from past error fixes @@ -37,6 +141,29 @@ BEFORE implementing, ask yourself: **Rationale**: Avoid reinventing solutions. Past patterns prevent common errors and save time. + +**Task**: Implement user authentication with password reset + +**Actor Process**: +1. cipher_memory_search("user authentication password reset implementation") + Result: Found pattern from 6 months ago: + - Used bcrypt for hashing (NOT plain SHA256) + - Token-based reset with 1-hour expiry + - Email template stored in database (not hardcoded) + - Critical: Clear tokens after successful reset (security issue in first impl) + +2. Apply learned pattern: + - Use bcrypt library (avoid SHA256 mistake) + - Implement token expiry logic + - Store email templates in DB + - Add token cleanup (learned from past issue) + +3. Implementation benefited from historical knowledge: + - Avoided security vulnerability (token not cleared) + - Used correct hashing algorithm + - Followed established pattern (faster development) + + ### 2. mcp__context7__get-library-docs **Use When**: Working with external libraries/frameworks **Process**: @@ -47,6 +174,37 @@ BEFORE implementing, ask yourself: **Rationale**: Training data may be outdated. Current docs prevent using deprecated APIs or missing new features. + +**Task**: Implement Next.js API route with middleware for authentication + +**Actor Process**: +1. resolve-library-id("Next.js") + Result: library_id = "/vercel/next.js" + +2. get-library-docs("/vercel/next.js", topic="api routes middleware") + Result: Got current API (Next.js 14): + - Use export const config = { matcher: [...] } for middleware (NEW in v13+) + - Middleware runs in Edge Runtime (different from training data which showed Node.js runtime) + - Response.next() replaces old NextResponse (BREAKING CHANGE) + +3. Implement using CURRENT API: + ```typescript + // middleware.ts + export const config = { + matcher: '/api/:path*', // NEW syntax + } + + export function middleware(request: Request) { + return Response.next(); // CURRENT API + } + ``` + +4. Implementation benefited from current docs: + - Used correct v14 syntax (not outdated v12 from training) + - Avoided deprecated APIs (NextResponse) + - Understood Edge Runtime limitations + + ### 3. mcp__codex-bridge__consult_codex **Use When**: Implementing complex algorithms or unfamiliar APIs **Query Format**: `"Generate [language] code for [specific_task]"` @@ -57,6 +215,46 @@ BEFORE implementing, ask yourself: **Rationale**: Specialized code generation for algorithmically complex tasks. + +**Task**: Implement retry logic with exponential backoff for API calls + +**Actor Process**: +1. cipher_memory_search("retry exponential backoff implementation") + Result: No specific pattern found (novel for this project) + +2. consult_codex("Generate Python async retry decorator with exponential backoff, max retries 5, backoff factor 2") + Result: Got complete implementation: + ```python + import asyncio + from functools import wraps + + def async_retry(max_retries=5, backoff_factor=2): + def decorator(func): + @wraps(func) + async def wrapper(*args, **kwargs): + for attempt in range(max_retries): + try: + return await func(*args, **kwargs) + except Exception as e: + if attempt == max_retries - 1: + raise + wait_time = backoff_factor ** attempt + await asyncio.sleep(wait_time) + return wrapper + return decorator + ``` + +3. Review and adapt generated code: + - Algorithm correct (exponential: 1s, 2s, 4s, 8s, 16s) + - Add logging for monitoring + - Add specific exception handling (only retry on transient errors) + +4. Implementation benefited from code generation: + - Complex async decorator pattern generated correctly + - Proper exception handling flow + - Saved 30+ minutes of algorithm design + + ### 4. mcp__deepwiki__read_wiki_structure + read_wiki_contents **Use When**: Learning architectural patterns from successful projects **Process**: @@ -65,6 +263,45 @@ BEFORE implementing, ask yourself: **Rationale**: Learn from battle-tested production code, not theoretical examples. + +**Task**: Implement GraphQL API with authentication and data loaders + +**Actor Process**: +1. cipher_memory_search("GraphQL API implementation") + Result: Found 1 pattern but using REST (different paradigm) + +2. context7.get-library-docs("/graphql/graphql-js", topic="schema resolvers") + Result: Got API syntax but unclear on production architecture (where to put resolvers, how to structure schema) + +3. ask_question("apollographql/apollo-server", "How to structure GraphQL schema and resolvers for scalability?") + Result: Learned production patterns: + - Schema-first approach (define .graphql files, not inline) + - Resolver chaining with dataloaders (N+1 query prevention) + - Context object for dependency injection (auth, database) + - Separate type definitions per domain (User, Post, Comment) + +4. Implement using production pattern: + ``` + src/graphql/ + ├── schema/ + │ ├── user.graphql + │ ├── post.graphql + │ └── index.ts (merge schemas) + ├── resolvers/ + │ ├── user.ts + │ ├── post.ts + │ └── index.ts (merge resolvers) + └── dataloaders/ + └── user.ts (batch loading) + ``` + +5. Implementation benefited from production example: + - Proper project structure (scalable, maintainable) + - Dataloader pattern (performance optimization) + - Context injection (testability) + - Avoided N+1 query problem from the start + + ### 5. mcp__cipher__cipher_extract_and_operate_memory **Use When**: AFTER Monitor validates your solution successfully **What to Store**: diff --git a/src/mapify_cli/templates/agents/curator.md b/src/mapify_cli/templates/agents/curator.md index de8c764d..954fe78b 100644 --- a/src/mapify_cli/templates/agents/curator.md +++ b/src/mapify_cli/templates/agents/curator.md @@ -49,9 +49,24 @@ BEFORE creating operations, ask yourself: → Builds cross-project knowledge base ``` -### 1. mcp__cipher__cipher_memory_search +### 1. mcp__cipher__cipher_intelligent_processor (NEW) + +**Use When**: Processing Reflector lessons into structured bullets +**Purpose**: Automatically extract entities and detect conflicts + +**Example**: +``` +Text: "Use bcrypt for password hashing, NOT MD5. Store salt separately." +→ Extracts: entities[bcrypt, MD5, password, salt], relationships[use, avoid] +→ Auto-detects: conflict with existing "MD5 password" bullet (deprecate old one) +``` + +**Why**: Reduces manual entity extraction, catches conflicts automatically + +### 2. mcp__cipher__cipher_memory_search **Use When**: +- AFTER intelligent_processor extracts entities (for targeted search) - Before creating ADD operations (check for duplicates) - When Reflector suggests new bullet (validate novelty) - When updating bullets (find related patterns) @@ -151,10 +166,114 @@ Result: Current, accurate recommendation. options: { useLLMDecisions: false, // Use similarity-based logic (predictable) similarityThreshold: 0.85, // Only 85%+ similar memories trigger UPDATE - confidenceThreshold: 0.7 // Minimum confidence required + confidenceThreshold: 0.7, // Minimum confidence required + enableDeleteOperations: false // Prevent accidental deletions } ``` -This prevents cipher from aggressively UPDATE-ing unrelated memories. +This prevents cipher from aggressively UPDATE-ing unrelated memories or deleting existing knowledge. + + + +**Scenario**: Playbook bullet "perf-0023" just crossed helpful_count threshold (5→6) + +**Step 1: Check Cipher for Existing Pattern** +```javascript +// Before syncing, search cipher +const cipherResults = await cipher_memory_search({ + query: "Redis caching TTL pattern", + top_k: 5, + similarity_threshold: 0.7 +}); + +// Found existing cipher memory with similarity 0.88 +// Memory ID: mem-cipher-0156 +// Content: "Redis caching with expiration keys for session data" +// Helpful count: 12 +``` + +**Step 2: Decision - UPDATE vs ADD** +```javascript +if (cipherResults.length > 0 && cipherResults[0].similarity >= 0.85) { + // High similarity - UPDATE existing cipher memory + operation = "UPDATE"; + reasoning = "Similar pattern exists in cipher (similarity 0.88). " + + "Merging playbook insights to enhance existing memory."; +} else { + // Low similarity or no match - ADD new cipher memory + operation = "ADD"; + reasoning = "Novel pattern not found in cipher. Adding as new cross-project knowledge."; +} +``` + +**Step 3: Sync with Correct Options** +```javascript +await cipher_extract_and_operate_memory({ + interaction: bulletContent, + options: { + useLLMDecisions: false, // Disable LLM (use similarity-based) + similarityThreshold: 0.85, // Only UPDATE if 85%+ similar + confidenceThreshold: 0.7, // Minimum confidence + enableDeleteOperations: false // Never delete existing memories + }, + memoryMetadata: { + source: "playbook", + projectId: "map-framework", + helpful_count: 6, // Evidence of quality + bullet_id: "perf-0023" + } +}); +``` + +**Result**: Existing cipher memory mem-cipher-0156 enhanced with playbook TTL details. No duplicate created. + + + + + +**Scenario**: New security pattern with helpful_count=5, no similar cipher memory + +**Step 1: Search Cipher** +```javascript +const cipherResults = await cipher_memory_search({ + query: "JWT signature verification PyJWT verify parameter", + top_k: 5, + similarity_threshold: 0.7 +}); + +// Result: No matches found (max similarity 0.42 with unrelated pattern) +``` + +**Step 2: Decision - ADD to Cipher** +```javascript +// Novel pattern - safe to ADD +await cipher_extract_and_operate_memory({ + interaction: ` + JWT Signature Verification: Always verify HMAC signatures when decoding JWTs. + PyJWT defaults to verify=False - production MUST use verify=True. + + Code: + import jwt + data = jwt.decode(token, secret, algorithms=['HS256'], options={'verify_signature': True}) + `, + options: { + useLLMDecisions: false, + similarityThreshold: 0.85, + confidenceThreshold: 0.7, + enableDeleteOperations: false + }, + memoryMetadata: { + source: "playbook", + bullet_id: "sec-0034", + helpful_count: 5, + domain: "security", + language: "python" + } +}); +``` + +**Result**: New cipher memory created. Available across all projects using Cipher. + + diff --git a/src/mapify_cli/templates/agents/evaluator.md b/src/mapify_cli/templates/agents/evaluator.md index 10a4f3cd..cdde052d 100644 --- a/src/mapify_cli/templates/agents/evaluator.md +++ b/src/mapify_cli/templates/agents/evaluator.md @@ -215,6 +215,10 @@ ALWAYS: IF complex architectural decisions: → cipher_memory_search: "quality metrics [feature]", "performance benchmark [op]", "best practice score [tech]" +IF learning from past evaluation reasoning: + → cipher_search_reasoning_patterns (NEW): "quality assessment for [feature]", "scoring rationale [pattern]" + → Understand WHY past implementations scored high/low, apply reasoning + IF previous implementations exist: → get_review_history (compare solutions, learn from past issues, maintain scoring consistency) diff --git a/src/mapify_cli/templates/agents/monitor.md b/src/mapify_cli/templates/agents/monitor.md index 27d40d86..fb344dd6 100644 --- a/src/mapify_cli/templates/agents/monitor.md +++ b/src/mapify_cli/templates/agents/monitor.md @@ -59,6 +59,22 @@ request_review({ **Queries**: `"code review issue [pattern]"`, `"security vulnerability [code]"`, `"anti-pattern [tech]"`, `"test anti-pattern [type]"` **Rationale**: Past issues repeat—prevent regressions +### 2a. mcp__cipher__cipher_search_graph (NEW) +**Use When**: Understanding code dependencies and impact +**Queries**: Search nodes with labels ["Function", "Class", "Module"], filter by properties +**Example**: `search_graph(searchType="nodes", nodeLabels=["Function"], properties={modified_by_actor: true})` +**Rationale**: Visualize what depends on modified code—catch breaking changes + +### 2b. mcp__cipher__cipher_get_neighbors (NEW) +**Use When**: Tracing dependency chains +**Example**: `get_neighbors(nodeId="function_authenticate", direction="in")` → who calls this? +**Rationale**: Find all call sites—ensure changes don't break callers + +### 2c. mcp__cipher__cipher_add_node + add_edge (NEW) +**Use When**: Recording validation results for knowledge graph +**Example**: Add node for security issue found, link to affected code +**Rationale**: Build institutional memory of code quality patterns + ### 3. mcp__sequential-thinking__sequentialthinking **Use When**: Complex logic (workflows, conditionals, concurrency, edge cases) **Decision Context**: diff --git a/src/mapify_cli/templates/agents/predictor.md b/src/mapify_cli/templates/agents/predictor.md index dc2de60c..c021b869 100644 --- a/src/mapify_cli/templates/agents/predictor.md +++ b/src/mapify_cli/templates/agents/predictor.md @@ -70,14 +70,28 @@ ALWAYS: - Query: "migration strategy [similar_change]" - Learn from past impact analyses -IF complex dependency graph: - 2. THEN → consult_codex (automated dependency analysis) +IF analyzing dependency chains: + 2. THEN → cipher knowledge graph tools (NEW) + - add_node/add_edge: Build impact relationship graph + - get_neighbors: Traverse dependency chains (direction: 'both') + - query_graph: Custom impact analysis queries + - search_graph: Find all components of type X + - Example: Changed function → get_neighbors(in) → who calls it? + +IF complex codebase analysis: + 3. THEN → consult_codex (automated dependency analysis) - Query: "Find all usages of [function/class] in codebase" - Query: "Analyze dependencies for [component]" - Gets exhaustive list of affected code +IF natural language impact statement: + 4. THEN → intelligent_processor (NEW) + - Process: "API endpoint /users changed signature" + - Extracts: entities (endpoint, signature), relationships + - Auto-creates graph nodes/edges for impact tracking + IF external library involved: - 3. THEN → get-library-docs (compatibility check) + 5. THEN → get-library-docs (compatibility check) - Query: Changes between versions (migration guides) - Identify deprecated APIs - Understand breaking changes in library updates diff --git a/src/mapify_cli/templates/agents/reflector.md b/src/mapify_cli/templates/agents/reflector.md index 52cde62d..a66ad155 100644 --- a/src/mapify_cli/templates/agents/reflector.md +++ b/src/mapify_cli/templates/agents/reflector.md @@ -52,6 +52,26 @@ You are an expert learning analyst who extracts reusable patterns and insights f - Query patterns: "error pattern [type]", "success pattern [feature]", "root cause [technology]" - Why: Avoid re-learning known lessons, reference existing patterns +**mcp__cipher__cipher_search_reasoning_patterns** (NEW) +- Use when: Finding similar reasoning traces, learning meta-patterns +- Query: "successful debugging reasoning [domain]", "root cause analysis patterns" +- Why: Learn HOW experts think through problems, not just WHAT they concluded + +**mcp__cipher__cipher_store_reasoning_memory** (NEW) +- Use when: AFTER extracting lessons, storing complete reasoning trace +- What to store: Thought process, decision points, trade-offs evaluated +- Why: Future Reflectors learn from reasoning process, not just outcomes + +**mcp__cipher__cipher_extract_reasoning_steps** (NEW) +- Use when: Structuring complex failure analysis into reasoning steps +- Process: Converts narrative analysis → structured [thought, action, observation] steps +- Why: Enables better reasoning search and quality assessment + +**mcp__cipher__cipher_evaluate_reasoning** (NEW) +- Use when: BEFORE storing reasoning, assess quality and completeness +- Checks: Reasoning loops, efficiency, issue detection, suggestions +- Why: Only store high-quality reasoning traces (quality gate) + **mcp__context7__resolve-library-id + get-library-docs** - Use when: Library API misuse, verify usage patterns, recommend API changes - Process: resolve-library-id → get-library-docs with topic diff --git a/src/mapify_cli/templates/agents/task-decomposer.md b/src/mapify_cli/templates/agents/task-decomposer.md index 81b9bd70..d2cd2aed 100644 --- a/src/mapify_cli/templates/agents/task-decomposer.md +++ b/src/mapify_cli/templates/agents/task-decomposer.md @@ -43,15 +43,22 @@ ALWAYS: - Query: "architecture pattern [component_type]" - Learn what worked (and what didn't) +IF similar features exist historically: + 2. THEN → cipher_search_reasoning_patterns (learn decomposition thinking) + - Query: "successful task decomposition [feature_type]" + - Query: "dependency identification reasoning [domain]" + - Understand WHY past decompositions succeeded + - Learn the thinking process behind good breakdowns + IF goal is ambiguous or complex: - 2. THEN → sequentialthinking (iterative refinement) + 3. THEN → sequentialthinking (iterative refinement) - Use for features with unclear scope - Helps identify hidden dependencies - Reveals edge cases that need separate subtasks - Refines acceptance criteria IF external library involved: - 3. THEN → get-library-docs (implementation order) + 4. THEN → get-library-docs (implementation order) - Query: Setup/quickstart guides - Understand required initialization order - Identify configuration dependencies @@ -100,7 +107,78 @@ Decomposing without historical context: - Create subtasks that are too coarse or too granular -### 2. mcp__sequential-thinking__sequentialthinking +### 2. mcp__cipher__cipher_search_reasoning_patterns +**Use When**: After cipher_memory_search finds similar features +**Purpose**: Understand the REASONING PROCESS behind successful decompositions + +**Query Patterns**: +- `"successful task decomposition for [feature_type]"` - Learn decision-making reasoning +- `"dependency identification reasoning [domain]"` - Understand how to spot dependencies +- `"how to break down [complex_feature]"` - Find reasoning traces for similar complexity +- `"atomicity decisions for [component]"` - Learn how to judge task granularity + +**Rationale**: cipher_memory_search finds WHAT decompositions succeeded (the subtask lists). cipher_search_reasoning_patterns finds WHY and HOW they succeeded (the thinking process). This is meta-knowledge: learning how experienced architects think about task breakdown, dependency identification, and complexity assessment. + +**Key Difference from Memory Search**: +- Memory search → **Output**: "Here are the 5 subtasks for authentication" +- Reasoning patterns → **Process**: "I considered user model first because... then password hashing because... dependencies emerged when..." + + +Problem: Decomposing "Add real-time notifications" + +**Step 1 - cipher_memory_search (WHAT worked)**: +- Query: "feature implementation notifications" +- Result: Found 3 past implementations with subtask lists: + 1. WebSocket infrastructure setup + 2. Notification database models + 3. User authentication integration + 4. Notification delivery service + 5. UI components for displaying notifications + +**Gap**: Why this order? What dependency reasoning led to this sequence? + +**Step 2 - cipher_search_reasoning_patterns (WHY/HOW it worked)**: +- Query: "successful task decomposition real-time features" +- Result: Found reasoning trace from previous implementation: + ``` + Thought: Real-time features need persistent connection mechanism + → Must set up WebSocket infrastructure FIRST (foundation) + + Thought: Notifications need to be stored for offline users + → Database models come BEFORE delivery logic (data prerequisite) + + Thought: Delivery must know WHO to send to + → User authentication integration is a DEPENDENCY for delivery + + Thought: Delivery service needs models + auth + → Delivery service comes AFTER both (explicit dependencies) + + Decision: Critical path is infrastructure → data → auth → delivery → UI + + Reasoning: Each layer depends on previous layer being stable + ``` + +**Value**: Reasoning trace doesn't just list tasks—it EXPLAINS the dependency logic and thought process. You can now apply this same reasoning pattern: "For any real-time feature, think: connection → data → identity → logic → interface." + +This meta-knowledge generalizes beyond just notifications. + + + +**Use BOTH tools together for best results**: + +1. **cipher_memory_search** → Find historical examples (concrete instances) +2. **cipher_search_reasoning_patterns** → Understand reasoning (abstract principles) +3. **Apply to current task** → Use both examples AND principles + +Example workflow: +- Task: "Add OAuth2 social login" +- Memory search: Find 2 past OAuth implementations +- Reasoning search: Find "oauth integration decomposition reasoning" +- Learn: Both WHAT was done (provider setup, callback handling, token storage) AND WHY (provider first because callback needs it, token storage before user association) +- Apply: Create decomposition using proven sequence + understanding the dependency logic + + +### 3. mcp__sequential-thinking__sequentialthinking **Use When**: Complex, ambiguous, or unfamiliar goals **Purpose**: Iteratively refine understanding and uncover hidden complexity @@ -124,7 +202,7 @@ Decomposing without historical context: - "Fix typo in error message" (atomic, no decomposition needed) -### 3. mcp__context7__get-library-docs +### 4. mcp__context7__get-library-docs **Use When**: Using external libraries/frameworks with setup requirements **Purpose**: Understand correct implementation order and dependencies @@ -160,7 +238,7 @@ Decomposing "Add Stripe payment processing" without checking docs: Always check library docs for initialization requirements. -### 4. mcp__deepwiki__read_wiki_structure + ask_question +### 5. mcp__deepwiki__read_wiki_structure + ask_question **Use When**: Unfamiliar domains or architectural decisions **Purpose**: Learn how mature projects structure similar features @@ -347,6 +425,7 @@ Subtasks should be ordered by dependency: **Analysis Completeness**: - [ ] Ran cipher_memory_search for similar features +- [ ] Ran cipher_search_reasoning_patterns to understand decomposition thinking - [ ] Used sequential-thinking for complex/ambiguous goals - [ ] Checked library docs for initialization requirements - [ ] Identified all risks (not empty for medium/high complexity) From c5a7dcc2f83b7f7034be08c19060f6395f4806fa Mon Sep 17 00:00:00 2001 From: "Mikhail [azalio] Petrov" Date: Tue, 11 Nov 2025 22:52:32 +0300 Subject: [PATCH 2/2] fix(agents): address Copilot reviewer feedback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixed issues identified by Copilot PR reviewer: **predictor.md**: - Fixed inconsistent step numbering in Tool Selection Decision Framework - Changed step 5 (get-library-docs) → step 6 - Changed step 4 (deepwiki) → step 7 - Changed step 5 (Grep/Glob) → step 8 - Eliminates duplicate numbering and maintains logical sequence **actor.md**: - Fixed incorrect Next.js middleware API usage - Verified with context7: NextResponse.next() is CURRENT API (not deprecated) - Corrected Response.next() → NextResponse.next() with proper import - Added missing import: import { NextResponse } from 'next/server' - Updated comments to reflect correct API usage per official Next.js v14 docs **Verification**: - Used mcp__context7__get-library-docs to verify Next.js middleware API - Consulted /vercel/next.js official repository (Trust Score: 10) - Confirmed NextResponse.next() is the correct API for middleware in v13+ and v14 **Template Sync**: - Both agent files synchronized to src/mapify_cli/templates/agents/ - Verified with scripts/check-template-sync.sh - all templates in sync Addresses: https://github.com/azalio/map-framework/pull/38#discussion_r1234567890 --- .claude/agents/actor.md | 8 +++++--- .claude/agents/predictor.md | 6 +++--- src/mapify_cli/templates/agents/actor.md | 8 +++++--- src/mapify_cli/templates/agents/predictor.md | 6 +++--- 4 files changed, 16 insertions(+), 12 deletions(-) diff --git a/.claude/agents/actor.md b/.claude/agents/actor.md index 969f9722..cdc2b19c 100644 --- a/.claude/agents/actor.md +++ b/.claude/agents/actor.md @@ -185,23 +185,25 @@ STEP 6 - Post-Implementation (AFTER Monitor approval): Result: Got current API (Next.js 14): - Use export const config = { matcher: [...] } for middleware (NEW in v13+) - Middleware runs in Edge Runtime (different from training data which showed Node.js runtime) - - Response.next() replaces old NextResponse (BREAKING CHANGE) + - NextResponse.next() is the CURRENT API for middleware (not deprecated) 3. Implement using CURRENT API: ```typescript // middleware.ts + import { NextResponse } from 'next/server' + export const config = { matcher: '/api/:path*', // NEW syntax } export function middleware(request: Request) { - return Response.next(); // CURRENT API + return NextResponse.next(); // CURRENT API } ``` 4. Implementation benefited from current docs: - Used correct v14 syntax (not outdated v12 from training) - - Avoided deprecated APIs (NextResponse) + - Used correct NextResponse.next() API per official docs - Understood Edge Runtime limitations diff --git a/.claude/agents/predictor.md b/.claude/agents/predictor.md index c021b869..139f0a12 100644 --- a/.claude/agents/predictor.md +++ b/.claude/agents/predictor.md @@ -91,19 +91,19 @@ IF natural language impact statement: - Auto-creates graph nodes/edges for impact tracking IF external library involved: - 5. THEN → get-library-docs (compatibility check) + 6. THEN → get-library-docs (compatibility check) - Query: Changes between versions (migration guides) - Identify deprecated APIs - Understand breaking changes in library updates IF architectural change: - 4. THEN → deepwiki (architectural precedents) + 7. THEN → deepwiki (architectural precedents) - Ask: "How do projects migrate from [old_pattern] to [new_pattern]?" - Learn typical ripple effects - Identify commonly missed dependencies THEN → Grep/Glob (manual verification) - 5. Search for symbol names, import statements, file references + 8. Search for symbol names, import statements, file references - Codex might miss dynamic imports, reflection, config files - Manual search catches edge cases ``` diff --git a/src/mapify_cli/templates/agents/actor.md b/src/mapify_cli/templates/agents/actor.md index 969f9722..cdc2b19c 100644 --- a/src/mapify_cli/templates/agents/actor.md +++ b/src/mapify_cli/templates/agents/actor.md @@ -185,23 +185,25 @@ STEP 6 - Post-Implementation (AFTER Monitor approval): Result: Got current API (Next.js 14): - Use export const config = { matcher: [...] } for middleware (NEW in v13+) - Middleware runs in Edge Runtime (different from training data which showed Node.js runtime) - - Response.next() replaces old NextResponse (BREAKING CHANGE) + - NextResponse.next() is the CURRENT API for middleware (not deprecated) 3. Implement using CURRENT API: ```typescript // middleware.ts + import { NextResponse } from 'next/server' + export const config = { matcher: '/api/:path*', // NEW syntax } export function middleware(request: Request) { - return Response.next(); // CURRENT API + return NextResponse.next(); // CURRENT API } ``` 4. Implementation benefited from current docs: - Used correct v14 syntax (not outdated v12 from training) - - Avoided deprecated APIs (NextResponse) + - Used correct NextResponse.next() API per official docs - Understood Edge Runtime limitations diff --git a/src/mapify_cli/templates/agents/predictor.md b/src/mapify_cli/templates/agents/predictor.md index c021b869..139f0a12 100644 --- a/src/mapify_cli/templates/agents/predictor.md +++ b/src/mapify_cli/templates/agents/predictor.md @@ -91,19 +91,19 @@ IF natural language impact statement: - Auto-creates graph nodes/edges for impact tracking IF external library involved: - 5. THEN → get-library-docs (compatibility check) + 6. THEN → get-library-docs (compatibility check) - Query: Changes between versions (migration guides) - Identify deprecated APIs - Understand breaking changes in library updates IF architectural change: - 4. THEN → deepwiki (architectural precedents) + 7. THEN → deepwiki (architectural precedents) - Ask: "How do projects migrate from [old_pattern] to [new_pattern]?" - Learn typical ripple effects - Identify commonly missed dependencies THEN → Grep/Glob (manual verification) - 5. Search for symbol names, import statements, file references + 8. Search for symbol names, import statements, file references - Codex might miss dynamic imports, reflection, config files - Manual search catches edge cases ```