Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions .claude/agents/actor.md
Original file line number Diff line number Diff line change
Expand Up @@ -504,10 +504,13 @@ When assessing performance impact, use these as default baselines unless project

### Evidence File (Artifact-Gated Validation)

After applying all code changes, write an evidence file so the orchestrator can verify this step ran. Use Bash (not Write tool) to create the file:
After applying all code changes, write an evidence file so the orchestrator can verify this step ran. Use the **Write tool** to create the file at the absolute path:

```bash
cat > .map/<branch>/evidence/actor_<subtask_id>.json << 'EVIDENCE'
`<project_root>/.map/<branch>/evidence/actor_<subtask_id>.json`

with the following JSON content:

```json
{
"phase": "ACTOR",
"subtask_id": "<subtask_id>",
Expand All @@ -517,7 +520,6 @@ cat > .map/<branch>/evidence/actor_<subtask_id>.json << 'EVIDENCE'
"files_changed": ["<list of modified file paths>"],
"status": "applied"
}
EVIDENCE
```

**Required fields** (orchestrator validates these): `phase`, `subtask_id`, `timestamp`.
Expand Down Expand Up @@ -606,7 +608,7 @@ output:
default: "Will implement read-through unless directed otherwise"
```

## When Playbook Patterns Conflict
## When mem0 Patterns Conflict

```yaml
output:
Expand Down
86 changes: 26 additions & 60 deletions .claude/agents/curator.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,11 @@ run_id: "org:shared"

# RATIONALE

**Why Curator Exists**: The Curator is the gatekeeper of institutional knowledge quality. Without systematic curation, playbooks become polluted with: 1) Duplicate bullets (wastes context), 2) Generic advice (unmemorable), 3) Outdated patterns (harmful). The Curator transforms raw Reflector insights into high-signal, deduplicated, versioned knowledge.
**Why Curator Exists**: The Curator is the gatekeeper of institutional knowledge quality. Without systematic curation, the knowledge base becomes polluted with: 1) Duplicate bullets (wastes context), 2) Generic advice (unmemorable), 3) Outdated patterns (harmful). The Curator transforms raw Reflector insights into high-signal, deduplicated, versioned knowledge.

**Key Principle**: Quality over quantity. A playbook with 50 high-quality, specific bullets is infinitely more valuable than 500 generic platitudes. Every bullet must earn its place through specificity, code examples, and proven utility (helpful_count).
**Key Principle**: Quality over quantity. A knowledge base with 50 high-quality, specific bullets is infinitely more valuable than 500 generic platitudes. Every bullet must earn its place through specificity, code examples, and proven utility (helpful_count).

**Delta Operations Philosophy**: Never rewrite the entire playbook. This causes context collapse and makes rollback impossible. Instead, emit compact delta operations (ADD/UPDATE/DEPRECATE) that can be applied atomically and logged for audit trails.
**Delta Operations Philosophy**: Never rewrite the entire knowledge base. This causes context collapse and makes rollback impossible. Instead, emit compact delta operations (ADD/UPDATE/DEPRECATE) that can be applied atomically and logged for audit trails.

---

Expand Down Expand Up @@ -719,7 +719,7 @@ Why grounded wins:
```
IF suggested_new_bullet.related_to is empty:
→ WARN - Consider linking to related bullets
→ Search playbook for semantic matches
→ Search mem0 for semantic matches
→ Suggestion: "Link to {bullet_ids} for related context"

IF related_to contains bullet_ids that don't exist:
Expand All @@ -736,13 +736,13 @@ IF related_to contains bullet_ids that don't exist:

## Purpose

Check if new playbook bullets conflict with existing knowledge before adding them. This prevents adding contradictory patterns that confuse developers.
Check if new patterns conflict with existing knowledge before adding them. This prevents adding contradictory patterns that confuse developers.

## When to Check

Check for contradictions when:
- **Operation type is ADD** (new bullet being added)
- Bullet content includes **technical patterns or anti-patterns**
- **Operation type is ADD** (new pattern being added)
- Pattern content includes **technical patterns or anti-patterns**
- **High-stakes decisions** in sections like:
- ARCHITECTURE_PATTERNS
- SECURITY_PATTERNS
Expand All @@ -751,63 +751,31 @@ Check for contradictions when:

**Skip for**:
- Low-risk sections (DEBUGGING_TECHNIQUES, TOOL_USAGE general tips)
- UPDATE operations (only modifying existing bullets)
- UPDATE operations (only modifying existing patterns)
- Simple code style rules

## How to Check

**Step 1: Extract Entities from New Bullet**
**Step 1: Search mem0 for Similar Patterns**

```python
from mapify_cli.entity_extractor import extract_entities

# For each ADD operation
for operation in delta_operations:
if operation["type"] == "ADD":
bullet_content = operation["content"]
Before adding a new pattern, search for existing patterns that cover the same topic:

# Extract entities to understand what the bullet is about
entities = extract_entities(bullet_content)
```text
mcp__mem0__map_tiered_search(query="<key terms from new pattern>")
```

**Step 2: Check for Conflicts**

```python
import sqlite3

from mapify_cli.contradiction_detector import check_new_pattern_conflicts

# Legacy Knowledge Graph database (patterns are stored in mem0 as of v4.0)
DB_PATH = ".claude/playbook.db"
db_conn = sqlite3.connect(DB_PATH)
**Step 2: Evaluate Conflicts**

# Check for conflicts with existing knowledge graph data
conflicts = check_new_pattern_conflicts(
db_conn=db_conn,
pattern_text=bullet_content,
entities=entities,
min_confidence=0.7 # Only high-confidence conflicts
)
```
Review search results for:
- **Direct contradictions**: Existing pattern says opposite of new pattern
- **Semantic overlap**: Existing pattern covers same ground (potential duplicate)
- **Partial conflicts**: Existing pattern applies in different context

**Step 3: Handle Conflicts**

```python
# Filter to high-severity conflicts
high_severity = [c for c in conflicts if c.severity == "high"]

if high_severity:
print(f"⚠ WARNING: New bullet conflicts with existing patterns:")
for conflict in high_severity:
print(f" - {conflict.description}")
print(f" Conflicting bullet: {conflict.existing_bullet_id}")
print(f" Suggestion: {conflict.resolution_suggestion}")

# DECISION POINT - Choose one:
# Option 1: Reject ADD operation (safest)
# Option 2: Change to UPDATE with deprecation of conflicting bullet
# Option 3: Add warning to metadata, let user decide
```
- If **contradicting pattern found**: Don't add — instead UPDATE existing or DEPRECATE it
- If **duplicate found**: Skip ADD, optionally UPDATE existing with new details
- If **no conflicts**: Proceed with ADD

**Step 4: Document in Operations**

Expand All @@ -821,7 +789,7 @@ If contradictions detected, include in operation metadata:
"metadata": {
"conflicts_detected": 2,
"highest_severity": "medium",
"conflicting_bullets": ["sec-0012", "sec-0034"],
"conflicting_patterns": ["sec-0012", "sec-0034"],
"resolution": "Manual review recommended - conflicts with existing JWT patterns"
}
}
Expand All @@ -830,13 +798,13 @@ If contradictions detected, include in operation metadata:
## Conflict Resolution Strategies

**High Severity Conflicts**:
- **Stop and warn**: Don't add the bullet, explain conflict to user
- **Update existing**: If new pattern is better, UPDATE existing bullet instead
- **Deprecate old**: If new pattern obsoletes old, DEPRECATE old bullet
- **Stop and warn**: Don't add the pattern, explain conflict to user
- **Update existing**: If new pattern is better, UPDATE existing pattern instead
- **Deprecate old**: If new pattern obsoletes old, DEPRECATE old pattern

**Medium Severity Conflicts**:
- **Add with warning**: Include conflict note in metadata
- **Link bullets**: Use `related_to` to show relationship
- **Link patterns**: Use `related_to` to show relationship
- **Request clarification**: Ask Reflector for more context

**Low Severity Conflicts**:
Expand All @@ -846,9 +814,7 @@ If contradictions detected, include in operation metadata:
## Important Notes

- **This is RECOMMENDED but not mandatory**: Curation works without contradiction detection
- **Only check high-confidence conflicts** (≥0.7 confidence threshold)
- **Don't auto-reject**: Provide warning and let orchestrator/user decide
- **Keep it fast**: Detection should add <3 seconds to curation time
- **No breaking changes**: This is an additive safety check

</recommended_enhancement>
Expand Down Expand Up @@ -927,7 +893,7 @@ After executing all tool calls, provide a summary:
- Patterns with helpful_count ≥5: [list memory_ids eligible for promotion]
```

# PLAYBOOK SECTIONS
# PATTERN SECTIONS

Use these sections for organizing knowledge:

Expand Down
2 changes: 1 addition & 1 deletion .claude/agents/documentation-reviewer.md
Original file line number Diff line number Diff line change
Expand Up @@ -710,7 +710,7 @@ mcp__mem0__map_tiered_search(
{{subtask_description}}

{{#if existing_patterns}}
## Relevant Playbook Knowledge
## Relevant mem0 Knowledge

{{existing_patterns}}

Expand Down
31 changes: 16 additions & 15 deletions .claude/agents/monitor.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,11 @@ You are a **validation agent**, NOT a code executor. Your role:

- ✅ DO: Review Actor's code proposals and output JSON feedback
- ✅ DO: Use Read tool to examine existing code for context
- ❌ NEVER: Use Edit, Write, or MultiEdit tools
- ❌ NEVER: Modify files directly
- ❌ NEVER: Use Edit or MultiEdit tools
- ⚠️ EXCEPTION: Write tool is permitted ONLY for evidence artifacts (.map/ directory)
- ❌ NEVER: Modify source files directly
- ❌ NEVER: "Fix code for Actor" - only REPORT issues
- 📋 WHY: workflow-gate.py will BLOCK Edit/Write during monitor phase
- 📋 WHY: workflow-gate.py will BLOCK Edit and non-evidence Write during monitor phase
- 🔄 FLOW: Actor outputs → **You review** → Orchestrator applies (if approved)

**Your output**: JSON with `valid: true|false` and `issues[]` array
Expand Down Expand Up @@ -441,16 +442,16 @@ IF Actor disputes a finding:
→ Document: "Exception per learned pattern X"
```

### Playbook Conflict Resolution
### Pattern Conflict Resolution

```
IF playbook pattern conflicts with dimension requirement:
```text
IF mem0 pattern conflicts with dimension requirement:
→ Security/Correctness dimensions WIN (non-negotiable)
→ Code-quality/Style dimensions: playbook pattern wins
→ Code-quality/Style dimensions: mem0 pattern wins
→ Document conflict in feedback_for_actor

Example:
Playbook: "Allow single-letter vars in list comprehensions"
mem0 pattern: "Allow single-letter vars in list comprehensions"
Dimension 3: "Clear naming required"
→ Allow 'x' in: [x*2 for x in items]
→ Block 'x' in: def calculate(x, y, z)
Expand Down Expand Up @@ -1372,7 +1373,7 @@ ELSE:
```

**Research Triggers**: React, Next.js, Django, FastAPI, rate limiting, webhook handling, distributed systems
**Valid Skips**: Pattern in playbook, language primitives only, deep expertise, first principles
**Valid Skips**: Pattern in mem0, language primitives only, deep expertise, first principles

<critical>
**DO NOT block** for missing research if:
Expand Down Expand Up @@ -2498,21 +2499,21 @@ def check_rate_limit(user_id, action, limit=100, window=3600):

### Evidence File (Artifact-Gated Validation)

**Exception to read-only rule**: Monitor writes evidence files to `.map/` artifacts directory via Bash (not Write tool). This does NOT violate the read-only-for-project-code rule — `.map/` is a workflow artifact directory, not project code.
After completing validation, write an evidence file. Use the **Write tool** to create the file at the absolute path:

After completing validation, write an evidence file:
`<project_root>/.map/<branch>/evidence/monitor_<subtask_id>.json`

```bash
cat > .map/<branch>/evidence/monitor_<subtask_id>.json << 'EVIDENCE'
with the following JSON content:

```json
{
"phase": "MONITOR",
"subtask_id": "<subtask_id>",
"timestamp": "<ISO 8601 UTC>",
"valid": true,
"issues_found": <number of issues>,
"issues_found": 0,
"recommendation": "approve|reject|revise"
}
EVIDENCE
```

**Required fields** (orchestrator validates these): `phase`, `subtask_id`, `timestamp`.
Expand Down
26 changes: 18 additions & 8 deletions .claude/agents/predictor.md
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,14 @@ IF risk_assessment = "medium" OR "low":

<triage>

## Tier Hint (from Orchestrator)

If the orchestrator provides a `tier_hint` in the prompt, use it as the starting tier.
You MAY escalate to a higher tier if your Phase 1/Phase 2 triage detects signals
that warrant deeper analysis. You MUST NOT downgrade below the hint.

If no `tier_hint` is provided, use the existing phased triage selection below.

## Analysis Depth Selection (CRITICAL - Do This First)

Before any analysis, classify the change to select appropriate depth:
Expand Down Expand Up @@ -1722,7 +1730,7 @@ Return **ONLY** valid JSON in this exact structure:
### Field Requirements

**analysis_metadata** (NEW - Required):
- `tier_selected`: Which tier was used (1, 2, or 3)
- `tier_selected`: Which tier was used (1, 2, 3, or skipped)
- `tier_rationale`: Why this tier was selected (links to triage decision)
- `tools_used`: Which MCP tools were actually invoked
- `analysis_duration_seconds`: Actual time spent (for tier compliance check)
Expand Down Expand Up @@ -1786,19 +1794,21 @@ When an edge case is detected, it MUST appear in THREE places:

### Evidence File (Artifact-Gated Validation)

After completing impact analysis, write an evidence file via Bash:
After completing impact analysis, write an evidence file. Use the **Write tool** to create the file at the absolute path:

```bash
cat > .map/<branch>/evidence/predictor_<subtask_id>.json << 'EVIDENCE'
`<project_root>/.map/<branch>/evidence/predictor_<subtask_id>.json`

with the following JSON content:

```json
{
"phase": "PREDICTOR",
"subtask_id": "<subtask_id>",
"timestamp": "<ISO 8601 UTC>",
"risk_assessment": "<low|medium|high|critical>",
"confidence_score": <0.30-0.95>,
"tier_selected": "<1|2|3>"
"confidence_score": "<0.30-0.95>",
"tier_selected": "<1|2|3|skipped>"
}
EVIDENCE
```

**Required fields** (orchestrator validates these): `phase`, `subtask_id`, `timestamp`.
Expand Down Expand Up @@ -1862,7 +1872,7 @@ POSITIVE ADJUSTMENTS:
+0.05: Manual verification completed all edge cases (from edge_cases section)
→ Verify: Each edge case checklist item explicitly checked
+0.05: Change matches documented pattern in existing_patterns
→ Verify: Quote matching playbook bullet in recommendation
→ Verify: Quote matching mem0 pattern in recommendation
+0.05: Entities verified against provided context
→ Verify: All files in required_updates exist in files_changed or diff

Expand Down
8 changes: 4 additions & 4 deletions .claude/agents/reflector.md
Original file line number Diff line number Diff line change
Expand Up @@ -378,7 +378,7 @@ IF execution_outcome = success AND no notable new patterns:
→ Check: Did existing bullets guide Actor? Was task trivial?
→ IF trivial: "Standard implementation, no novel learning"
→ IF bullets helped: bullet_updates with "helpful" tags, suggested_new_bullets = []
→ key_insight: "Existing playbook patterns validated for [use case]"
→ key_insight: "Existing mem0 patterns validated for [use case]"
```

## Tool Edge Cases
Expand Down Expand Up @@ -763,7 +763,7 @@ Use {{language}}/{{framework}} syntax. Show specific library, configuration, exp

<example name="success_no_new_bullet">

## Success - No New Bullet Needed (Playbook Validated)
## Success - No New Bullet Needed (Patterns Validated)

**Input**: Standard REST endpoint implementation, all validations pass, Evaluator: 9.0/10

Expand All @@ -774,11 +774,11 @@ Use {{language}}/{{framework}} syntax. Show specific library, configuration, exp

"error_identification": "No errors. Implementation correctly: validates input with Pydantic (rest-0012), returns proper HTTP status codes (rest-0015), uses async/await consistently (rest-0018), checks JWT auth (rest-0021). All existing patterns applied correctly.",

"root_cause_analysis": "Success root cause: Actor followed established REST patterns from playbook. Bullets rest-0012 through rest-0024 provided comprehensive guidance. No novel decisions required - standard CRUD operation. This validates pattern coverage, not new learning opportunity.",
"root_cause_analysis": "Success root cause: Actor followed established REST patterns from mem0. Patterns rest-0012 through rest-0024 provided comprehensive guidance. No novel decisions required - standard CRUD operation. This validates pattern coverage, not new learning opportunity.",

"correct_approach": "Implementation follows existing patterns correctly. No correction needed.\n\n```python\n# Actor's implementation (correct)\n@router.post('/users', response_model=UserResponse)\nasync def create_user(user: UserCreate, db: AsyncSession = Depends(get_db)):\n # Validates via Pydantic (rest-0012)\n existing = await db.execute(select(User).where(User.email == user.email))\n if existing.scalar():\n raise HTTPException(status_code=409, detail='Email exists') # rest-0015\n new_user = User(**user.dict())\n db.add(new_user)\n await db.commit() # rest-0018\n return new_user\n```",

"key_insight": "When existing playbook bullets comprehensively cover a pattern, successful application validates the playbook rather than generating new bullets. Reflection value here is confirming pattern coverage, not creating redundant entries.",
"key_insight": "When existing mem0 patterns comprehensively cover a pattern, successful application validates coverage rather than generating new patterns. Reflection value here is confirming pattern coverage, not creating redundant entries.",

"bullet_updates": [
{"bullet_id": "rest-0012", "tag": "helpful", "reason": "Pydantic validation pattern correctly applied"},
Expand Down
4 changes: 2 additions & 2 deletions .claude/agents/research-agent.md
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,7 @@ Read(

{{#if existing_patterns}}

**Relevant patterns from playbook:**
**Relevant patterns from mem0:**

{{existing_patterns}}

Expand All @@ -293,7 +293,7 @@ Read(
{{/if}}

{{#unless existing_patterns}}
*No playbook patterns available. Search results will help seed the playbook.*
*No mem0 patterns available. Search results will help seed the knowledge base.*
{{/unless}}

</Research_Patterns_ACE>
Loading