loki-mode 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +691 -0
  3. package/SKILL.md +191 -0
  4. package/VERSION +1 -0
  5. package/autonomy/.loki/dashboard/index.html +2634 -0
  6. package/autonomy/CONSTITUTION.md +508 -0
  7. package/autonomy/README.md +201 -0
  8. package/autonomy/config.example.yaml +152 -0
  9. package/autonomy/loki +526 -0
  10. package/autonomy/run.sh +3636 -0
  11. package/bin/loki-mode.js +26 -0
  12. package/bin/postinstall.js +60 -0
  13. package/docs/ACKNOWLEDGEMENTS.md +234 -0
  14. package/docs/COMPARISON.md +325 -0
  15. package/docs/COMPETITIVE-ANALYSIS.md +333 -0
  16. package/docs/INSTALLATION.md +547 -0
  17. package/docs/auto-claude-comparison.md +276 -0
  18. package/docs/cursor-comparison.md +225 -0
  19. package/docs/dashboard-guide.md +355 -0
  20. package/docs/screenshots/README.md +149 -0
  21. package/docs/screenshots/dashboard-agents.png +0 -0
  22. package/docs/screenshots/dashboard-tasks.png +0 -0
  23. package/docs/thick2thin.md +173 -0
  24. package/package.json +48 -0
  25. package/references/advanced-patterns.md +453 -0
  26. package/references/agent-types.md +243 -0
  27. package/references/agents.md +1043 -0
  28. package/references/business-ops.md +550 -0
  29. package/references/competitive-analysis.md +216 -0
  30. package/references/confidence-routing.md +371 -0
  31. package/references/core-workflow.md +275 -0
  32. package/references/cursor-learnings.md +207 -0
  33. package/references/deployment.md +604 -0
  34. package/references/lab-research-patterns.md +534 -0
  35. package/references/mcp-integration.md +186 -0
  36. package/references/memory-system.md +467 -0
  37. package/references/openai-patterns.md +647 -0
  38. package/references/production-patterns.md +568 -0
  39. package/references/prompt-repetition.md +192 -0
  40. package/references/quality-control.md +437 -0
  41. package/references/sdlc-phases.md +410 -0
  42. package/references/task-queue.md +361 -0
  43. package/references/tool-orchestration.md +691 -0
  44. package/skills/00-index.md +120 -0
  45. package/skills/agents.md +249 -0
  46. package/skills/artifacts.md +174 -0
  47. package/skills/github-integration.md +218 -0
  48. package/skills/model-selection.md +125 -0
  49. package/skills/parallel-workflows.md +526 -0
  50. package/skills/patterns-advanced.md +188 -0
  51. package/skills/production.md +292 -0
  52. package/skills/quality-gates.md +180 -0
  53. package/skills/testing.md +149 -0
  54. package/skills/troubleshooting.md +109 -0
@@ -0,0 +1,186 @@
1
+ # MCP Integration Reference
2
+
3
+ Model Context Protocol (MCP) servers extend Claude Code's capabilities with specialized tools.
4
+
5
+ ---
6
+
7
+ ## Recommended MCP Servers
8
+
9
+ ### 1. Playwright MCP (E2E Testing)
10
+
11
+ **Purpose:** Browser automation for end-to-end testing and visual verification.
12
+
13
+ **When to use:**
14
+ - Feature verification (visual confirmation)
15
+ - E2E test automation
16
+ - Screenshot capture for artifacts
17
+
18
+ **Configuration:**
19
+ ```json
20
+ {
21
+ "mcpServers": {
22
+ "playwright": {
23
+ "command": "npx",
24
+ "args": ["@anthropic-ai/playwright-mcp"]
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ **Tools provided:**
31
+ - `browser_navigate` - Navigate to URL
32
+ - `browser_click` - Click elements
33
+ - `browser_type` - Type text
34
+ - `browser_screenshot` - Capture screenshots
35
+
36
+ **SDLC Phase:** QA (E2E testing)
37
+
38
+ **Limitation:** Cannot detect browser-native alert modals. Use custom UI for confirmations.
39
+
40
+ ---
41
+
42
+ ### 2. Parallel AI (Web Research)
43
+
44
+ **Purpose:** Production-grade web research with evidence-based results and provenance.
45
+
46
+ **Why Parallel AI:**
47
+ - 48% accuracy on complex research tasks (vs native LLM search)
48
+ - Evidence-based results with provenance for every atomic output
49
+ - Monitor API for tracking web changes (dependencies, competitors)
50
+ - Task API with custom input/output schemas for structured research
51
+
52
+ **When to use:**
53
+ - Discovery phase: PRD gap analysis, competitor research
54
+ - Web Research phase: Feature comparisons, market analysis
55
+ - Dependency Management: Security advisory monitoring
56
+
57
+ **Configuration:**
58
+ ```json
59
+ {
60
+ "mcpServers": {
61
+ "parallel-search": {
62
+ "command": "npx",
63
+ "args": ["-y", "@anthropic-ai/parallel-search-mcp"],
64
+ "env": {
65
+ "PARALLEL_API_KEY": "your-api-key"
66
+ }
67
+ },
68
+ "parallel-task": {
69
+ "command": "npx",
70
+ "args": ["-y", "@anthropic-ai/parallel-task-mcp"],
71
+ "env": {
72
+ "PARALLEL_API_KEY": "your-api-key"
73
+ }
74
+ }
75
+ }
76
+ }
77
+ ```
78
+
79
+ **Tools provided:**
80
+
81
+ | Tool | Purpose | Use Case |
82
+ |------|---------|----------|
83
+ | `parallel_search` | Web search with LLM-optimized excerpts | Quick lookups, fact-checking |
84
+ | `parallel_extract` | Extract content from specific URLs | Documentation parsing |
85
+ | `parallel_task` | Complex research with custom schemas | Competitor analysis, market research |
86
+ | `parallel_monitor` | Track web changes with webhooks | Dependency updates, security alerts |
87
+
88
+ **SDLC Phases:** Discovery, Web Research, Continuous Monitoring
89
+
90
+ **Pricing:** Pay-per-query (not token-based). See https://parallel.ai/pricing
91
+
92
+ **API Documentation:** https://docs.parallel.ai/
93
+
94
+ ---
95
+
96
+ ## MCP Configuration Location
97
+
98
+ Claude Code reads MCP configuration from:
99
+
100
+ 1. **Project-level:** `.claude/mcp.json` (recommended for project-specific tools)
101
+ 2. **User-level:** `~/.claude/mcp.json` (for global tools)
102
+
103
+ Example full configuration:
104
+ ```json
105
+ {
106
+ "mcpServers": {
107
+ "playwright": {
108
+ "command": "npx",
109
+ "args": ["@anthropic-ai/playwright-mcp"]
110
+ },
111
+ "parallel-search": {
112
+ "command": "npx",
113
+ "args": ["-y", "@anthropic-ai/parallel-search-mcp"],
114
+ "env": {
115
+ "PARALLEL_API_KEY": "${PARALLEL_API_KEY}"
116
+ }
117
+ }
118
+ }
119
+ }
120
+ ```
121
+
122
+ ---
123
+
124
+ ## Using MCP Tools in Loki Mode
125
+
126
+ MCP tools are automatically available to Claude Code when configured. The orchestrator can dispatch agents that use these tools:
127
+
128
+ ```python
129
+ # Agent using Playwright for E2E verification
130
+ Task(
131
+ subagent_type="general-purpose",
132
+ model="sonnet",
133
+ description="Verify login feature visually",
134
+ prompt="""
135
+ Use Playwright MCP to:
136
+ 1. Navigate to http://localhost:3000/login
137
+ 2. Fill in test credentials
138
+ 3. Click login button
139
+ 4. Take screenshot of dashboard
140
+ 5. Verify user name is displayed
141
+ """
142
+ )
143
+
144
+ # Agent using Parallel AI for research
145
+ Task(
146
+ subagent_type="general-purpose",
147
+ model="opus",
148
+ description="Research competitor pricing",
149
+ prompt="""
150
+ Use Parallel AI Task API to:
151
+ 1. Research top 5 competitors in [market]
152
+ 2. Extract pricing tiers from each
153
+ 3. Return structured comparison table
154
+
155
+ Output schema: {competitors: [{name, tiers: [{name, price, features}]}]}
156
+ """
157
+ )
158
+ ```
159
+
160
+ ---
161
+
162
+ ## When NOT to Use MCP
163
+
164
+ - **Simple searches:** Claude's built-in `WebSearch` is sufficient for basic lookups
165
+ - **Cost sensitivity:** MCP tools add API costs on top of Claude costs
166
+ - **Offline work:** MCP tools require network access
167
+
168
+ ---
169
+
170
+ ## Adding New MCP Servers
171
+
172
+ When evaluating new MCP servers for Loki Mode integration, assess:
173
+
174
+ 1. **Autonomous fit:** Does it work without human intervention?
175
+ 2. **Evidence quality:** Does it provide verifiable, citable results?
176
+ 3. **SDLC alignment:** Which phase(s) does it enhance?
177
+ 4. **Cost model:** Predictable pricing for autonomous operation?
178
+ 5. **Error handling:** Does it fail gracefully?
179
+
180
+ ---
181
+
182
+ ## References
183
+
184
+ - [MCP Specification](https://modelcontextprotocol.io/)
185
+ - [Parallel AI Documentation](https://docs.parallel.ai/)
186
+ - [Playwright MCP](https://github.com/anthropics/anthropic-quickstarts/tree/main/mcp-playwright)
@@ -0,0 +1,467 @@
1
+ # Memory System Reference
2
+
3
+ Enhanced memory architecture based on 2025 research (MIRIX, A-Mem, MemGPT, AriGraph).
4
+
5
+ ---
6
+
7
+ ## Core Insight: Memory Over Reasoning
8
+
9
+ > *"Your Agent's Reasoning Is Fine - Its Memory Isn't"*
10
+ > -- Cursor Scaling Blog, January 2026
11
+
12
+ **The fundamental bottleneck in production AI systems is not reasoning capability but context retrieval.**
13
+
14
+ Production incidents aren't slowed by inability to fix problems - they're slowed by fragmented context. An agent with perfect reasoning but poor memory will:
15
+ - Re-discover the same patterns repeatedly
16
+ - Miss relevant prior experiences
17
+ - Fail to apply learned anti-patterns
18
+ - Lose context across session boundaries
19
+
20
+ An agent with good reasoning and excellent memory will:
21
+ - Retrieve relevant patterns before acting
22
+ - Avoid previously-encountered failures
23
+ - Build on successful approaches
24
+ - Maintain continuity across long-running operations
25
+
26
+ **Implication for Loki Mode:** Invest heavily in memory architecture. The episodic-to-semantic consolidation pipeline, Zettelkasten linking, and CONTINUITY.md working memory are not optional optimizations - they are the core competitive advantage.
27
+
28
+ ---
29
+
30
+ ## Memory Hierarchy Overview
31
+
32
+ ```
33
+ +------------------------------------------------------------------+
34
+ | WORKING MEMORY (CONTINUITY.md) |
35
+ | - Current session state |
36
+ | - Updated every turn |
37
+ | - What am I doing right NOW? |
38
+ +------------------------------------------------------------------+
39
+ |
40
+ v
41
+ +------------------------------------------------------------------+
42
+ | EPISODIC MEMORY (.loki/memory/episodic/) |
43
+ | - Specific interaction traces |
44
+ | - Full context with timestamps |
45
+ | - "What happened when I tried X?" |
46
+ +------------------------------------------------------------------+
47
+ |
48
+ v (consolidation)
49
+ +------------------------------------------------------------------+
50
+ | SEMANTIC MEMORY (.loki/memory/semantic/) |
51
+ | - Generalized patterns and facts |
52
+ | - Context-independent knowledge |
53
+ | - "How does X work in general?" |
54
+ +------------------------------------------------------------------+
55
+ |
56
+ v
57
+ +------------------------------------------------------------------+
58
+ | PROCEDURAL MEMORY (.loki/memory/skills/) |
59
+ | - Learned action sequences |
60
+ | - Reusable skill templates |
61
+ | - "How to do X successfully" |
62
+ +------------------------------------------------------------------+
63
+ ```
64
+
65
+ ---
66
+
67
+ ## Directory Structure
68
+
69
+ ```
70
+ .loki/memory/
71
+ +-- episodic/
72
+ | +-- 2026-01-06/
73
+ | | +-- task-001.json # Full trace of task execution
74
+ | | +-- task-002.json
75
+ | +-- index.json # Temporal index for retrieval
76
+ |
77
+ +-- semantic/
78
+ | +-- patterns.json # Generalized patterns
79
+ | +-- anti-patterns.json # What NOT to do
80
+ | +-- facts.json # Domain knowledge
81
+ | +-- links.json # Zettelkasten-style connections
82
+ |
83
+ +-- skills/
84
+ | +-- api-implementation.md # Skill: How to implement an API
85
+ | +-- test-writing.md # Skill: How to write tests
86
+ | +-- debugging.md # Skill: How to debug issues
87
+ |
88
+ +-- ledgers/ # Agent-specific checkpoints
89
+ | +-- eng-001.json
90
+ | +-- qa-001.json
91
+ |
92
+ +-- handoffs/ # Agent-to-agent transfers
93
+ | +-- handoff-001.json
94
+ |
95
+ +-- learnings/ # Extracted from errors
96
+ | +-- 2026-01-06.json
97
+
98
+ # Related: Metrics System (separate from memory)
99
+ # .loki/metrics/
100
+ # +-- efficiency/ # Task cost tracking (time, agents, retries)
101
+ # +-- rewards/ # Outcome/efficiency/preference signals
102
+ # +-- dashboard.json # Rolling 7-day metrics summary
103
+ # See references/tool-orchestration.md for details
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Episodic Memory Schema
109
+
110
+ Each task execution creates an episodic trace:
111
+
112
+ ```json
113
+ {
114
+ "id": "ep-2026-01-06-001",
115
+ "task_id": "task-042",
116
+ "timestamp": "2026-01-06T10:30:00Z",
117
+ "duration_seconds": 342,
118
+ "agent": "eng-001-backend",
119
+ "context": {
120
+ "phase": "development",
121
+ "goal": "Implement POST /api/todos endpoint",
122
+ "constraints": ["No third-party deps", "< 200ms response"],
123
+ "files_involved": ["src/routes/todos.ts", "src/db/todos.ts"]
124
+ },
125
+ "action_log": [
126
+ {"t": 0, "action": "read_file", "target": "openapi.yaml"},
127
+ {"t": 5, "action": "write_file", "target": "src/routes/todos.ts"},
128
+ {"t": 120, "action": "run_test", "result": "fail", "error": "missing return type"},
129
+ {"t": 140, "action": "edit_file", "target": "src/routes/todos.ts"},
130
+ {"t": 180, "action": "run_test", "result": "pass"}
131
+ ],
132
+ "outcome": "success",
133
+ "errors_encountered": [
134
+ {
135
+ "type": "TypeScript compilation",
136
+ "message": "Missing return type annotation",
137
+ "resolution": "Added explicit :void to route handler"
138
+ }
139
+ ],
140
+ "artifacts_produced": ["src/routes/todos.ts", "tests/todos.test.ts"],
141
+ "git_commit": "abc123"
142
+ }
143
+ ```
144
+
145
+ ---
146
+
147
+ ## Semantic Memory Schema
148
+
149
+ Generalized patterns extracted from episodic memory:
150
+
151
+ ```json
152
+ {
153
+ "id": "sem-001",
154
+ "pattern": "Express route handlers require explicit return types in strict mode",
155
+ "category": "typescript",
156
+ "conditions": [
157
+ "Using TypeScript strict mode",
158
+ "Writing Express route handlers",
159
+ "Handler doesn't return a value"
160
+ ],
161
+ "correct_approach": "Add `: void` to handler signature: `(req, res): void =>`",
162
+ "incorrect_approach": "Omitting return type annotation",
163
+ "confidence": 0.95,
164
+ "source_episodes": ["ep-2026-01-06-001", "ep-2026-01-05-012"],
165
+ "usage_count": 8,
166
+ "last_used": "2026-01-06T14:00:00Z",
167
+ "links": [
168
+ {"to": "sem-005", "relation": "related_to"},
169
+ {"to": "sem-012", "relation": "supersedes"}
170
+ ]
171
+ }
172
+ ```
173
+
174
+ ---
175
+
176
+ ## Episodic-to-Semantic Consolidation
177
+
178
+ **When to consolidate:** After task completion, during idle time, at phase boundaries.
179
+
180
+ ```python
181
+ def consolidate_episodic_to_semantic():
182
+ """
183
+ Transform specific experiences into general knowledge.
184
+ Based on MemGPT and Voyager research.
185
+ """
186
+ # 1. Load recent episodic memories
187
+ recent_episodes = load_episodes(since=hours_ago(24))
188
+
189
+ # 2. Group by similarity
190
+ clusters = cluster_by_similarity(recent_episodes)
191
+
192
+ for cluster in clusters:
193
+ if len(cluster) >= 2: # Pattern appears multiple times
194
+ # 3. Extract common pattern
195
+ pattern = extract_common_pattern(cluster)
196
+
197
+ # 4. Validate pattern
198
+ if pattern.confidence >= 0.8:
199
+ # 5. Check if already exists
200
+ existing = find_similar_semantic(pattern)
201
+ if existing:
202
+ # Update existing with new evidence
203
+ existing.source_episodes.extend([e.id for e in cluster])
204
+ existing.confidence = recalculate_confidence(existing)
205
+ existing.usage_count += 1
206
+ else:
207
+ # Create new semantic memory
208
+ save_semantic(pattern)
209
+
210
+ # 6. Consolidate anti-patterns from errors
211
+ error_episodes = [e for e in recent_episodes if e.errors_encountered]
212
+ for episode in error_episodes:
213
+ for error in episode.errors_encountered:
214
+ anti_pattern = {
215
+ "what_fails": error.type,
216
+ "why": error.message,
217
+ "prevention": error.resolution,
218
+ "source": episode.id
219
+ }
220
+ save_anti_pattern(anti_pattern)
221
+ ```
222
+
223
+ ---
224
+
225
+ ## Zettelkasten-Style Linking
226
+
227
+ Each memory note can link to related notes:
228
+
229
+ ```json
230
+ {
231
+ "links": [
232
+ {"to": "sem-005", "relation": "derived_from"},
233
+ {"to": "sem-012", "relation": "contradicts"},
234
+ {"to": "sem-018", "relation": "elaborates"},
235
+ {"to": "sem-023", "relation": "example_of"},
236
+ {"to": "sem-031", "relation": "superseded_by"}
237
+ ]
238
+ }
239
+ ```
240
+
241
+ ### Link Relations
242
+
243
+ | Relation | Meaning |
244
+ |----------|---------|
245
+ | `derived_from` | This pattern was extracted from that episode |
246
+ | `related_to` | Conceptually similar, often used together |
247
+ | `contradicts` | These patterns conflict - need resolution |
248
+ | `elaborates` | Provides more detail on the linked pattern |
249
+ | `example_of` | Specific instance of a general pattern |
250
+ | `supersedes` | This pattern replaces an older one |
251
+ | `superseded_by` | This pattern is outdated, use the linked one |
252
+
253
+ ---
254
+
255
+ ## Procedural Memory (Skills)
256
+
257
+ Reusable action sequences:
258
+
259
+ ```markdown
260
+ # Skill: API Endpoint Implementation
261
+
262
+ ## Prerequisites
263
+ - OpenAPI spec exists at .loki/specs/openapi.yaml
264
+ - Database schema defined
265
+
266
+ ## Steps
267
+ 1. Read endpoint spec from openapi.yaml
268
+ 2. Create route handler in src/routes/{resource}.ts
269
+ 3. Implement request validation using spec schema
270
+ 4. Implement business logic
271
+ 5. Add database operations if needed
272
+ 6. Return response matching spec schema
273
+ 7. Write contract tests
274
+ 8. Run tests, verify passing
275
+
276
+ ## Common Errors & Fixes
277
+ - Missing return type: Add `: void` to handler
278
+ - Schema mismatch: Regenerate types from spec
279
+
280
+ ## Exit Criteria
281
+ - All contract tests pass
282
+ - Response matches OpenAPI spec
283
+ - No TypeScript errors
284
+ ```
285
+
286
+ ---
287
+
288
+ ## Memory Retrieval
289
+
290
+ ### Retrieval by Similarity
291
+
292
+ ```python
293
+ def retrieve_relevant_memory(current_context):
294
+ """
295
+ Retrieve memories relevant to current task.
296
+ Uses semantic similarity + temporal recency.
297
+ """
298
+ query_embedding = embed(current_context.goal)
299
+
300
+ # 1. Search semantic memory first
301
+ semantic_matches = vector_search(
302
+ collection="semantic",
303
+ query=query_embedding,
304
+ top_k=5
305
+ )
306
+
307
+ # 2. Search episodic memory for similar situations
308
+ episodic_matches = vector_search(
309
+ collection="episodic",
310
+ query=query_embedding,
311
+ top_k=3,
312
+ filters={"outcome": "success"} # Prefer successful episodes
313
+ )
314
+
315
+ # 3. Search skills
316
+ skill_matches = keyword_search(
317
+ collection="skills",
318
+ keywords=extract_keywords(current_context)
319
+ )
320
+
321
+ # 4. Combine and rank
322
+ combined = merge_and_rank(
323
+ semantic_matches,
324
+ episodic_matches,
325
+ skill_matches,
326
+ weights={"semantic": 0.5, "episodic": 0.3, "skills": 0.2}
327
+ )
328
+
329
+ return combined[:5] # Return top 5 most relevant
330
+ ```
331
+
332
+ ### Retrieval Before Task Execution
333
+
334
+ **CRITICAL:** Before executing any task, retrieve relevant memories:
335
+
336
+ ```python
337
+ def before_task_execution(task):
338
+ """
339
+ Inject relevant memories into task context.
340
+ """
341
+ # 1. Retrieve relevant memories
342
+ memories = retrieve_relevant_memory(task)
343
+
344
+ # 2. Check for anti-patterns
345
+ anti_patterns = search_anti_patterns(task.action_type)
346
+
347
+ # 3. Inject into prompt
348
+ task.context["relevant_patterns"] = [m.summary for m in memories]
349
+ task.context["avoid_these"] = [a.summary for a in anti_patterns]
350
+ task.context["applicable_skills"] = find_skills(task.type)
351
+
352
+ return task
353
+ ```
354
+
355
+ ---
356
+
357
+ ## Ledger System (Agent Checkpoints)
358
+
359
+ Each agent maintains its own ledger:
360
+
361
+ ```json
362
+ {
363
+ "agent_id": "eng-001-backend",
364
+ "last_checkpoint": "2026-01-06T10:00:00Z",
365
+ "tasks_completed": 12,
366
+ "current_task": "task-042",
367
+ "state": {
368
+ "files_modified": ["src/routes/todos.ts"],
369
+ "uncommitted_changes": true,
370
+ "last_git_commit": "abc123"
371
+ },
372
+ "context": {
373
+ "tech_stack": ["express", "typescript", "sqlite"],
374
+ "patterns_learned": ["sem-001", "sem-005"],
375
+ "current_goal": "Implement CRUD for todos"
376
+ }
377
+ }
378
+ ```
379
+
380
+ ---
381
+
382
+ ## Handoff Protocol
383
+
384
+ When switching between agents:
385
+
386
+ ```json
387
+ {
388
+ "id": "handoff-001",
389
+ "from_agent": "eng-001-backend",
390
+ "to_agent": "qa-001-testing",
391
+ "timestamp": "2026-01-06T11:00:00Z",
392
+ "context": {
393
+ "what_was_done": "Implemented POST /api/todos endpoint",
394
+ "artifacts": ["src/routes/todos.ts"],
395
+ "git_state": "commit abc123",
396
+ "needs_testing": ["unit tests for validation", "contract tests"],
397
+ "known_issues": [],
398
+ "relevant_patterns": ["sem-001"]
399
+ }
400
+ }
401
+ ```
402
+
403
+ ---
404
+
405
+ ## Memory Maintenance
406
+
407
+ ### Pruning Old Episodic Memories
408
+
409
+ ```python
410
+ def prune_episodic_memories():
411
+ """
412
+ Keep episodic memories from:
413
+ - Last 7 days (full detail)
414
+ - Last 30 days (summarized)
415
+ - Older: only if referenced by semantic memory
416
+ """
417
+ now = datetime.now()
418
+
419
+ for episode in load_all_episodes():
420
+ age_days = (now - episode.timestamp).days
421
+
422
+ if age_days > 30:
423
+ if not is_referenced_by_semantic(episode):
424
+ archive_episode(episode)
425
+ elif age_days > 7:
426
+ summarize_episode(episode)
427
+ ```
428
+
429
+ ### Merging Duplicate Patterns
430
+
431
+ ```python
432
+ def merge_duplicate_semantics():
433
+ """
434
+ Find and merge semantically similar patterns.
435
+ """
436
+ all_patterns = load_semantic_patterns()
437
+
438
+ clusters = cluster_by_embedding_similarity(all_patterns, threshold=0.9)
439
+
440
+ for cluster in clusters:
441
+ if len(cluster) > 1:
442
+ # Keep highest confidence, merge sources
443
+ primary = max(cluster, key=lambda p: p.confidence)
444
+ for other in cluster:
445
+ if other != primary:
446
+ primary.source_episodes.extend(other.source_episodes)
447
+ primary.usage_count += other.usage_count
448
+ create_link(other, primary, "superseded_by")
449
+ save_semantic(primary)
450
+ ```
451
+
452
+ ---
453
+
454
+ ## Integration with CONTINUITY.md
455
+
456
+ CONTINUITY.md is working memory - it references but doesn't duplicate long-term memory:
457
+
458
+ ```markdown
459
+ ## Relevant Memories (Auto-Retrieved)
460
+ - [sem-001] Express handlers need explicit return types
461
+ - [ep-2026-01-05-012] Similar endpoint implementation succeeded
462
+ - [skill: api-implementation] Standard API implementation flow
463
+
464
+ ## Mistakes to Avoid (From Learnings)
465
+ - Don't forget return type annotations
466
+ - Run contract tests before marking complete
467
+ ```