agent-working-memory 0.11.0 → 0.12.3

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 (115) hide show
  1. package/README.md +71 -297
  2. package/dist/adapters/claude-code.d.ts.map +1 -1
  3. package/dist/adapters/claude-code.js +63 -3
  4. package/dist/adapters/claude-code.js.map +1 -1
  5. package/dist/adapters/common.d.ts.map +1 -1
  6. package/dist/adapters/common.js +358 -306
  7. package/dist/adapters/common.js.map +1 -1
  8. package/dist/api/routes.d.ts.map +1 -1
  9. package/dist/api/routes.js +29 -7
  10. package/dist/api/routes.js.map +1 -1
  11. package/dist/coordination/routes.d.ts.map +1 -1
  12. package/dist/coordination/routes.js +174 -170
  13. package/dist/coordination/routes.js.map +1 -1
  14. package/dist/core/embeddings.d.ts.map +1 -1
  15. package/dist/core/embeddings.js +4 -1
  16. package/dist/core/embeddings.js.map +1 -1
  17. package/dist/core/entity-extract.d.ts +3 -0
  18. package/dist/core/entity-extract.d.ts.map +1 -0
  19. package/dist/core/entity-extract.js +47 -0
  20. package/dist/core/entity-extract.js.map +1 -0
  21. package/dist/core/format-recall.d.ts +16 -0
  22. package/dist/core/format-recall.d.ts.map +1 -0
  23. package/dist/core/format-recall.js +24 -0
  24. package/dist/core/format-recall.js.map +1 -0
  25. package/dist/core/query-expander.js +1 -1
  26. package/dist/core/query-expander.js.map +1 -1
  27. package/dist/core/reranker.js +1 -1
  28. package/dist/core/reranker.js.map +1 -1
  29. package/dist/core/salience.d.ts.map +1 -1
  30. package/dist/core/salience.js +14 -2
  31. package/dist/core/salience.js.map +1 -1
  32. package/dist/core/whoami.d.ts +24 -0
  33. package/dist/core/whoami.d.ts.map +1 -0
  34. package/dist/core/whoami.js +66 -0
  35. package/dist/core/whoami.js.map +1 -0
  36. package/dist/core/write-pipeline.d.ts +9 -0
  37. package/dist/core/write-pipeline.d.ts.map +1 -1
  38. package/dist/core/write-pipeline.js +109 -68
  39. package/dist/core/write-pipeline.js.map +1 -1
  40. package/dist/core/write-telemetry.d.ts +33 -0
  41. package/dist/core/write-telemetry.d.ts.map +1 -0
  42. package/dist/core/write-telemetry.js +110 -0
  43. package/dist/core/write-telemetry.js.map +1 -0
  44. package/dist/engine/activation.d.ts +22 -12
  45. package/dist/engine/activation.d.ts.map +1 -1
  46. package/dist/engine/activation.js +133 -17
  47. package/dist/engine/activation.js.map +1 -1
  48. package/dist/engine/consolidation-scheduler.d.ts +1 -1
  49. package/dist/engine/consolidation-scheduler.js +1 -1
  50. package/dist/engine/consolidation.d.ts +1 -0
  51. package/dist/engine/consolidation.d.ts.map +1 -1
  52. package/dist/engine/consolidation.js +18 -0
  53. package/dist/engine/consolidation.js.map +1 -1
  54. package/dist/engine/eval.d.ts.map +1 -1
  55. package/dist/engine/eval.js +5 -1
  56. package/dist/engine/eval.js.map +1 -1
  57. package/dist/hooks/sidecar.d.ts +26 -0
  58. package/dist/hooks/sidecar.d.ts.map +1 -1
  59. package/dist/hooks/sidecar.js +30 -0
  60. package/dist/hooks/sidecar.js.map +1 -1
  61. package/dist/index.js +20 -2
  62. package/dist/index.js.map +1 -1
  63. package/dist/mcp.d.ts +2 -1
  64. package/dist/mcp.d.ts.map +1 -1
  65. package/dist/mcp.js +222 -108
  66. package/dist/mcp.js.map +1 -1
  67. package/dist/recipes/index.d.ts +57 -0
  68. package/dist/recipes/index.d.ts.map +1 -0
  69. package/dist/recipes/index.js +81 -0
  70. package/dist/recipes/index.js.map +1 -0
  71. package/dist/storage/pglite-schema.d.ts.map +1 -1
  72. package/dist/storage/pglite-schema.js +27 -0
  73. package/dist/storage/pglite-schema.js.map +1 -1
  74. package/dist/storage/pglite.d.ts +5 -0
  75. package/dist/storage/pglite.d.ts.map +1 -1
  76. package/dist/storage/pglite.js +180 -138
  77. package/dist/storage/pglite.js.map +1 -1
  78. package/dist/storage/postgres.d.ts +5 -0
  79. package/dist/storage/postgres.d.ts.map +1 -1
  80. package/dist/storage/postgres.js +180 -138
  81. package/dist/storage/postgres.js.map +1 -1
  82. package/dist/storage/sqlite.d.ts +9 -0
  83. package/dist/storage/sqlite.d.ts.map +1 -1
  84. package/dist/storage/sqlite.js +394 -326
  85. package/dist/storage/sqlite.js.map +1 -1
  86. package/dist/types/engram.d.ts +14 -0
  87. package/dist/types/engram.d.ts.map +1 -1
  88. package/dist/types/engram.js.map +1 -1
  89. package/package.json +1 -1
  90. package/src/adapters/claude-code.ts +66 -3
  91. package/src/adapters/common.ts +567 -515
  92. package/src/api/routes.ts +999 -971
  93. package/src/coordination/routes.ts +2155 -2150
  94. package/src/core/embeddings.ts +4 -1
  95. package/src/core/entity-extract.ts +47 -0
  96. package/src/core/format-recall.ts +25 -0
  97. package/src/core/query-expander.ts +1 -1
  98. package/src/core/reranker.ts +1 -1
  99. package/src/core/salience.ts +529 -514
  100. package/src/core/whoami.ts +92 -0
  101. package/src/core/write-pipeline.ts +60 -8
  102. package/src/core/write-telemetry.ts +131 -0
  103. package/src/engine/activation.ts +1468 -1369
  104. package/src/engine/consolidation-scheduler.ts +1 -1
  105. package/src/engine/consolidation.ts +887 -869
  106. package/src/engine/eval.ts +6 -1
  107. package/src/hooks/sidecar.ts +55 -0
  108. package/src/index.ts +248 -227
  109. package/src/mcp.ts +1387 -1270
  110. package/src/recipes/index.ts +125 -0
  111. package/src/storage/pglite-schema.ts +27 -0
  112. package/src/storage/pglite.ts +1420 -1372
  113. package/src/storage/postgres.ts +1523 -1475
  114. package/src/storage/sqlite.ts +1936 -1861
  115. package/src/types/engram.ts +22 -0
package/src/mcp.ts CHANGED
@@ -1,1270 +1,1387 @@
1
- // Copyright 2026 Robert Winter / Complete Ideas
2
- // SPDX-License-Identifier: Apache-2.0
3
- /**
4
- * MCP Server — Model Context Protocol interface for AgentWorkingMemory.
5
- *
6
- * Runs as a stdio-based MCP server that Claude Code connects to directly.
7
- * Uses the storage and engine layers in-process (no HTTP overhead).
8
- *
9
- * Tools exposed (16):
10
- * memory_write — store a memory (salience filter decides disposition)
11
- * memory_recall — activate memories by context (cognitive retrieval)
12
- * memory_feedback — report whether a recalled memory was useful
13
- * memory_retract — invalidate a wrong memory with optional correction
14
- * memory_supersede — replace an outdated memory with a current one
15
- * memory_stats — get memory health metrics
16
- * memory_checkpoint save structured execution state (survives compaction)
17
- * memory_restore restore state + targeted recall after compaction
18
- * memory_task_add create a prioritized task
19
- * memory_task_update change task status, priority, or blocking
20
- * memory_task_list list tasks filtered by status
21
- * memory_task_nextget the highest-priority actionable task
22
- * memory_task_begin start a task (auto-checkpoint + recall)
23
- * memory_task_end end a task (write summary + checkpoint)
24
- * compress_outputencode structured tool output as TOON (token-efficient, lossless)
25
- * retrieve_original get the verbatim source for a compress_output ref
26
- *
27
- * Run: npx tsx src/mcp.ts
28
- * Config: add to ~/.claude.json or .mcp.json
29
- */
30
-
31
- import { readFileSync } from 'node:fs';
32
- import { resolve, basename } from 'node:path';
33
- import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
34
-
35
- // Load .env file if present (no external dependency)
36
- try {
37
- const envPath = resolve(process.cwd(), '.env');
38
- const envContent = readFileSync(envPath, 'utf-8');
39
- for (const line of envContent.split('\n')) {
40
- const trimmed = line.trim();
41
- if (!trimmed || trimmed.startsWith('#')) continue;
42
- const eqIdx = trimmed.indexOf('=');
43
- if (eqIdx === -1) continue;
44
- const key = trimmed.slice(0, eqIdx).trim();
45
- const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, '');
46
- if (!process.env[key]) process.env[key] = val;
47
- }
48
- } catch { /* No .env file */ }
49
-
50
- // MCP uses stdout for JSON-RPC. Redirect console.log to stderr so engine
51
- // startup messages (ConsolidationScheduler, model loading, etc.) don't
52
- // corrupt the transport. This MUST happen before any engine imports.
53
- console.log = console.error;
54
-
55
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
56
- import { z } from 'zod';
57
-
58
- import { EngramStore } from './storage/sqlite.js';
59
- import { openStore, getConfiguredBackend, type StoreBackend } from './storage/factory.js';
60
- import type { IEngramStore } from './storage/store.js';
61
- import { ActivationEngine } from './engine/activation.js';
62
- import { ConnectionEngine } from './engine/connections.js';
63
- import { StagingBuffer } from './engine/staging.js';
64
- import { EvictionEngine } from './engine/eviction.js';
65
- import { RetractionEngine } from './engine/retraction.js';
66
- import { EvalEngine } from './engine/eval.js';
67
- import { ConsolidationEngine } from './engine/consolidation.js';
68
- import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
69
- import { evaluateSalience, computeNovelty, computeNoveltyWithMatch } from './core/salience.js';
70
- import { performWrite } from './core/write-pipeline.js';
71
- import type { ConsciousState } from './types/checkpoint.js';
72
- import type { SalienceEventType } from './core/salience.js';
73
- import type { TaskStatus, TaskPriority } from './types/engram.js';
74
- import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
75
- import { embed } from './core/embeddings.js';
76
- import { startSidecar } from './hooks/sidecar.js';
77
- import { initLogger, log, getLogPath } from './core/logger.js';
78
- import { VERSION } from './version.js';
79
- import { buildPack, INTERVIEW_QUESTIONS } from './onboard/index.js';
80
- import { liteCompress, retrieveOriginal } from './core/lite-compress.js';
81
- import { queryPeerDecisions, formatPeerDecisions } from './coordination/peer-decisions.js';
82
-
83
- // --- Incognito Mode ---
84
- // When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
85
- // No DB, no engines, no sidecar — just a bare MCP server that exposes nothing.
86
-
87
- const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
88
-
89
- if (INCOGNITO) {
90
- console.error('AWM: incognito mode all memory tools disabled, nothing will be recorded');
91
- const server = new McpServer({ name: 'agent-working-memory', version: VERSION });
92
- const transport = new StdioServerTransport();
93
- server.connect(transport).catch(err => {
94
- console.error('MCP server failed:', err);
95
- process.exit(1);
96
- });
97
- // No tools registered Claude won't see any memory_* tools
98
- } else {
99
-
100
- // --- Setup ---
101
-
102
- const BACKEND: StoreBackend = getConfiguredBackend();
103
- const DB_PATH = process.env.AWM_DB_PATH ?? (BACKEND === 'pglite' ? 'memory-pglite' : 'memory.db');
104
-
105
- // Fallback agent selection when AWM_AGENT_ID/WORKER_NAME are unset: derive from
106
- // the project directory so plain `claude` launches still bind to the right
107
- // store. Personal-Projects -> 'personal'; everything else -> 'work' (the
108
- // primary store). MUST stay in sync with the SessionStart hook
109
- // (~/.claude/hooks/awm-session-start.ps1) so the hook's restore and the
110
- // server's reads/writes never diverge. Guard the AWM package's own path
111
- // (it lives under Personal-Projects) so a stray server cwd can't mis-bind.
112
- function deriveAgentFromDir(): string {
113
- const dir = (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()).replace(/\\/g, '/');
114
- if (/\/AgentSynapse\//i.test(dir)) return 'work';
115
- return /\/Personal-Projects(\/|$)/i.test(dir) ? 'personal' : 'work';
116
- }
117
- const AGENT_ID = process.env.AWM_AGENT_ID ?? process.env.WORKER_NAME ?? deriveAgentFromDir();
118
- const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
119
- const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
120
-
121
- initLogger(DB_PATH);
122
- log(AGENT_ID, 'startup', `MCP server starting (backend: ${BACKEND}, db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
123
-
124
- // AWM 0.8.x: openStore() returns either SQLite (sync) or PGlite (async) store.
125
- // Engines accept either via IEngramStore (MaybePromise<T> contract).
126
- const { store: storeAny } = await openStore();
127
- // Engines accept the async contract; SQLite-only call sites must guard on BACKEND.
128
- const store = storeAny as unknown as IEngramStore & Partial<EngramStore>;
129
- const activationEngine = new ActivationEngine(store);
130
- const connectionEngine = new ConnectionEngine(store, activationEngine);
131
- const stagingBuffer = new StagingBuffer(store, activationEngine);
132
- const evictionEngine = new EvictionEngine(store);
133
- const retractionEngine = new RetractionEngine(store);
134
- const evalEngine = new EvalEngine(store);
135
- const consolidationEngine = new ConsolidationEngine(store, connectionEngine);
136
- const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
137
-
138
- stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
139
- consolidationScheduler.start();
140
-
141
- // Coordination DB handle — set when AWM_COORDINATION=true, used by memory_write for decision propagation
142
- let coordDb: import('better-sqlite3').Database | null = null;
143
-
144
- const server = new McpServer({
145
- name: 'agent-working-memory',
146
- version: VERSION,
147
- });
148
-
149
- server.registerResource(
150
- 'awm-overview',
151
- 'awm://server/overview',
152
- {
153
- title: 'AWM Overview',
154
- description: 'AgentWorkingMemory MCP server metadata and discovery notes',
155
- mimeType: 'text/markdown',
156
- },
157
- async () => ({
158
- contents: [{
159
- uri: 'awm://server/overview',
160
- text: [
161
- '# Agent Working Memory',
162
- '',
163
- `Agent: ${AGENT_ID}`,
164
- `DB: ${DB_PATH}`,
165
- `Coordination: ${process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1' ? 'enabled' : 'disabled'}`,
166
- '',
167
- 'This MCP server primarily exposes tools such as `memory_restore`, `memory_recall`, `memory_write`, and task/checkpoint operations.',
168
- 'The resources below exist so generic MCP clients can discover the server through `resources/list` and `resources/templates/list`.',
169
- ].join('\n'),
170
- mimeType: 'text/markdown',
171
- }],
172
- })
173
- );
174
-
175
- server.registerResource(
176
- 'awm-memory-template',
177
- new ResourceTemplate('awm://memory/{id}', { list: undefined }),
178
- {
179
- title: 'AWM Memory By ID',
180
- description: 'Metadata resource template for a memory identifier',
181
- mimeType: 'text/markdown',
182
- },
183
- async (_uri, variables) => ({
184
- contents: [{
185
- uri: `awm://memory/${variables.id ?? ''}`,
186
- text: [
187
- '# AWM Memory Reference',
188
- '',
189
- `Requested memory id: ${variables.id ?? ''}`,
190
- '',
191
- 'Use the AWM memory tools for actual retrieval and mutation:',
192
- '- `memory_recall` for cognitive retrieval',
193
- '- `memory_restore` for session state',
194
- '- `memory_feedback`, `memory_retract`, `memory_supersede` for memory maintenance',
195
- ].join('\n'),
196
- mimeType: 'text/markdown',
197
- }],
198
- })
199
- );
200
-
201
- // --- Auto-classification for memory types ---
202
-
203
- function classifyMemoryType(content: string): 'episodic' | 'semantic' | 'procedural' | 'unclassified' {
204
- const lower = content.toLowerCase();
205
- // Procedural: how-to, steps, numbered lists
206
- if (/\bhow to\b|\bsteps?:/i.test(content) || /^\s*\d+[\.\)]\s/m.test(content) || /\bthen run\b|\bfirst,?\s/i.test(content)) {
207
- return 'procedural';
208
- }
209
- // Episodic: past tense events, incidents, specific time references
210
- if (/\b(discovered|debugged|fixed|encountered|happened|resolved|found that|we did|i did|yesterday|last week|today)\b/i.test(content)) {
211
- return 'episodic';
212
- }
213
- // Semantic: facts, decisions, rules, patterns
214
- if (/\b(is|are|should|always|never|must|uses?|requires?|means|pattern|decision|rule|convention)\b/i.test(content) && content.length < 500) {
215
- return 'semantic';
216
- }
217
- return 'unclassified';
218
- }
219
-
220
- // --- Tools ---
221
-
222
- server.tool(
223
- 'memory_write',
224
- `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
225
-
226
- CALL THIS PROACTIVELY — do not wait to be asked. Write memories when you:
227
- - Discover something about the codebase, bugs, or architecture
228
- - Make a decision and want to remember why
229
- - Encounter and resolve an error
230
- - Learn a user preference or project pattern
231
- - Complete a significant piece of work
232
-
233
- The concept should be a short label (3-8 words). The content should be the full detail.`,
234
- {
235
- concept: z.string().describe('Short label for this memory (3-8 words)'),
236
- content: z.string().describe('Full detail of what was learned'),
237
- tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
238
- event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
239
- .optional().default('observation')
240
- .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
241
- surprise: z.number().min(0).max(1).optional().default(0.3)
242
- .describe('How surprising was this? 0=expected, 1=very unexpected'),
243
- decision_made: z.boolean().optional().default(false)
244
- .describe('Was a decision made? True boosts importance'),
245
- causal_depth: z.number().min(0).max(1).optional().default(0.3)
246
- .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
247
- resolution_effort: z.number().min(0).max(1).optional().default(0.3)
248
- .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
249
- memory_class: z.enum(['canonical', 'working', 'ephemeral']).optional().default('working')
250
- .describe('Memory class: canonical (source-of-truth, never stages), working (default), ephemeral (temporary, decays faster)'),
251
- memory_type: z.enum(['episodic', 'semantic', 'procedural', 'unclassified']).optional()
252
- .describe('Memory type: episodic (events/incidents), semantic (facts/decisions), procedural (how-to/steps). Auto-classified if omitted.'),
253
- supersedes: z.string().optional()
254
- .describe('ID of an older memory this one replaces. The old memory is down-ranked, not deleted.'),
255
- // --- Agent-provided metadata (stored as searchable tags) ---
256
- project: z.string().optional()
257
- .describe('Project context (e.g., "EquiHub", "AWM"). Becomes a searchable tag.'),
258
- topic: z.string().optional()
259
- .describe('Subject area (e.g., "database-migration", "auth-flow"). Becomes a searchable tag.'),
260
- source: z.enum(['code-reading', 'debugging', 'discussion', 'research', 'testing', 'observation']).optional()
261
- .describe('How this knowledge was acquired.'),
262
- confidence_level: z.enum(['verified', 'observed', 'assumed']).optional()
263
- .describe('Confidence: verified (tested), observed (read in code), assumed (reasoning).'),
264
- session_id: z.string().optional()
265
- .describe('Session/conversation grouping ID. Memories with same session_id are associated.'),
266
- intent: z.enum(['decision', 'question', 'todo', 'finding', 'context']).optional()
267
- .describe('What kind of memory this is.'),
268
- },
269
- async (params) => {
270
- // Assemble tags: user-provided + agent metadata (stored as searchable prefixed tags)
271
- const userTags = params.tags ?? [];
272
- const metaTags: string[] = [];
273
- if (params.project) metaTags.push(`proj=${params.project}`);
274
- if (params.topic) metaTags.push(`topic=${params.topic}`);
275
- if (params.source) metaTags.push(`src=${params.source}`);
276
- if (params.confidence_level) metaTags.push(`conf=${params.confidence_level}`);
277
- if (params.session_id) metaTags.push(`sid=${params.session_id}`);
278
- if (params.intent) metaTags.push(`intent=${params.intent}`);
279
-
280
- const memoryType = params.memory_type ?? classifyMemoryType(params.content);
281
-
282
- const result = await performWrite({ store, connectionEngine }, {
283
- agentId: AGENT_ID,
284
- concept: params.concept,
285
- content: params.content,
286
- tags: [...userTags, ...metaTags],
287
- eventType: params.event_type as SalienceEventType,
288
- surprise: params.surprise,
289
- decisionMade: params.decision_made,
290
- causalDepth: params.causal_depth,
291
- resolutionEffort: params.resolution_effort,
292
- memoryClass: params.memory_class,
293
- memoryType,
294
- supersedes: params.supersedes,
295
- });
296
-
297
- // Auto-checkpoint covers create/reinforce/supersede uniformly
298
- try { await store.updateAutoCheckpointWrite(AGENT_ID, result.engram.id); } catch { /* non-fatal */ }
299
-
300
- if (result.action === 'reinforce') {
301
- log(AGENT_ID, 'write:reinforce', `"${params.concept}" → reinforced "${result.engram.concept}" (conf ${result.reinforce!.previousConfidence.toFixed(2)} → ${result.reinforce!.newConfidence.toFixed(2)}, novelty=${result.noveltyResult.novelty.toFixed(2)})`);
302
- return {
303
- content: [{
304
- type: 'text' as const,
305
- text: `Reinforced existing memory "${result.engram.concept}" (confidence ${result.reinforce!.previousConfidence.toFixed(2)} → ${result.reinforce!.newConfidence.toFixed(2)})`,
306
- }],
307
- };
308
- }
309
-
310
- const engram = result.engram;
311
- const salience = result.salience!; // create/supersede always have salience
312
- const novelty = result.noveltyResult.novelty;
313
- const isLowSalience = salience.disposition === 'discard';
314
-
315
- // Decision propagation: when decision_made=true and coordination is enabled,
316
- // broadcast to coord_decisions so other agents can discover it
317
- if (params.decision_made && coordDb) {
318
- try {
319
- const agent = coordDb.prepare(
320
- `SELECT id, current_task FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
321
- ).get(AGENT_ID) as { id: string; current_task: string | null } | undefined;
322
- if (agent) {
323
- coordDb.prepare(
324
- `INSERT INTO coord_decisions (author_id, assignment_id, tags, summary) VALUES (?, ?, ?, ?)`
325
- ).run(agent.id, agent.current_task, params.tags ? JSON.stringify(params.tags) : null, params.concept);
326
- }
327
- } catch { /* decision propagation is non-fatal */ }
328
- }
329
-
330
- const logDisposition = isLowSalience ? 'low-salience' : salience.disposition;
331
- log(AGENT_ID, `write:${logDisposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
332
-
333
- return {
334
- content: [{
335
- type: 'text' as const,
336
- text: `Stored (${salience.disposition}) "${params.concept}" [${salience.score.toFixed(2)}]\nID: ${engram.id}`,
337
- }],
338
- };
339
- }
340
- );
341
-
342
- server.tool(
343
- 'memory_recall',
344
- `Recall memories relevant to a query. Uses cognitive activation — not keyword search.
345
-
346
- ALWAYS call this when:
347
- - Starting work on a project or topic (recall what you know)
348
- - Debugging (recall similar errors and solutions)
349
- - Making decisions (recall past decisions and outcomes)
350
- - The user mentions a topic you might have stored memories about
351
-
352
- Accepts either "query" or "context" parameter — both work identically.
353
- Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`,
354
- {
355
- query: z.string().optional().describe('What to search for — describe the situation, question, or topic'),
356
- context: z.string().optional().describe('Alias for query (either works)'),
357
- limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
358
- min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
359
- include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
360
- use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
361
- use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
362
- memory_type: z.enum(['episodic', 'semantic', 'procedural']).optional().describe('Filter by memory type (omit to search all types)'),
363
- workspace: z.string().optional().describe('Search across all agents in this workspace (hive mode). Omit for agent-scoped recall only.'),
364
- require_confidence: z.number().optional().describe('Opt-in: abstain (return []) when recall confidence is below this threshold. Typical values: 0.10 (strict), 0.25 (balanced), 0.40 (aggressive). Confidence is the shape of the result-score distribution; low confidence indicates a noisy or best-of-bad-bunch recall.'),
365
- granularity: z.enum(['full', 'compact', 'auto']).optional().describe('Output granularity (Paper 3: cognitive teaming). "full" (default): no change. "compact": every result carries a short summary field. "auto": confidence-adaptive — top result gets a longer summary when there is a clear winner, otherwise everything is compact for scanning.'),
366
- },
367
- async (params) => {
368
- const queryText = params.query ?? params.context;
369
- if (!queryText) {
370
- return {
371
- content: [{
372
- type: 'text' as const,
373
- text: 'Error: provide either "query" or "context" parameter with your search text.',
374
- }],
375
- };
376
- }
377
- // Use workspace from param, env var, or omit for agent-scoped
378
- const workspace = params.workspace ?? process.env.AWM_WORKSPACE ?? undefined;
379
- const results = await activationEngine.activate({
380
- agentId: AGENT_ID,
381
- context: queryText,
382
- limit: params.limit,
383
- minScore: params.min_score,
384
- includeStaging: params.include_staging,
385
- useReranker: params.use_reranker,
386
- useExpansion: params.use_expansion,
387
- memoryType: params.memory_type,
388
- workspace,
389
- requireConfidence: params.require_confidence,
390
- granularity: params.granularity,
391
- });
392
-
393
- // Auto-checkpoint: track recall
394
- try {
395
- const ids = results.map(r => r.engram.id);
396
- await store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
397
- } catch { /* non-fatal */ }
398
-
399
- log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" ${results.length} results`);
400
-
401
- // Peer decisions: append recent decisions by other agents relevant to this query
402
- const peerSuffix = coordDb
403
- ? formatPeerDecisions(queryPeerDecisions(coordDb, AGENT_ID, queryText))
404
- : '';
405
-
406
- if (results.length === 0) {
407
- return {
408
- content: [{
409
- type: 'text' as const,
410
- text: 'No relevant memories found.' + peerSuffix,
411
- }],
412
- };
413
- }
414
-
415
- const lines = results.map((r, i) => {
416
- // Confidence-adaptive output (Paper 3: cognitive teaming). When the caller
417
- // requested 'compact' or 'auto' granularity, surface the engine-computed
418
- // summary instead of the full content — same engram, less to read.
419
- const body = r.summary ?? r.engram.content;
420
- return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)}): ${body}`;
421
- });
422
-
423
- return {
424
- content: [{
425
- type: 'text' as const,
426
- text: lines.join('\n') + peerSuffix,
427
- }],
428
- };
429
- }
430
- );
431
-
432
- server.tool(
433
- 'memory_feedback',
434
- `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
435
-
436
- Always call this after using a recalled memory so the system learns what's valuable.`,
437
- {
438
- engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
439
- useful: z.boolean().describe('Was this memory actually helpful?'),
440
- context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
441
- },
442
- async (params) => {
443
- await store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
444
-
445
- const engram = await store.getEngram(params.engram_id);
446
- if (engram) {
447
- const delta = params.useful
448
- ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
449
- : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
450
- await store.updateConfidence(engram.id, engram.confidence + delta);
451
- }
452
-
453
- // Validation-gated Hebbian: resolve pending co-activation pairs for this engram
454
- const hebbianUpdated = await activationEngine.resolveHebbianFeedback(params.engram_id, params.useful);
455
-
456
- return {
457
- content: [{
458
- type: 'text' as const,
459
- text: `Feedback: ${params.useful ? '+useful' : '-not useful'}${hebbianUpdated > 0 ? ` (${hebbianUpdated} association${hebbianUpdated > 1 ? 's' : ''} ${params.useful ? 'strengthened' : 'weakened'})` : ''}`,
460
- }],
461
- };
462
- }
463
- );
464
-
465
- server.tool(
466
- 'memory_retract',
467
- `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
468
-
469
- Use this when you discover a memory contains incorrect information.`,
470
- {
471
- engram_id: z.string().describe('ID of the wrong memory'),
472
- reason: z.string().describe('Why is this memory wrong?'),
473
- correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
474
- },
475
- async (params) => {
476
- const result = await retractionEngine.retract({
477
- agentId: AGENT_ID,
478
- targetEngramId: params.engram_id,
479
- reason: params.reason,
480
- counterContent: params.correction,
481
- });
482
-
483
- const parts = [`Memory ${params.engram_id} retracted.`];
484
- if (result.correctionId) {
485
- parts.push(`Correction stored as ${result.correctionId}.`);
486
- }
487
- parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
488
-
489
- return {
490
- content: [{
491
- type: 'text' as const,
492
- text: parts.join(' '),
493
- }],
494
- };
495
- }
496
- );
497
-
498
- server.tool(
499
- 'memory_supersede',
500
- `Replace an outdated memory with a newer one. Unlike retraction (which marks memories as wrong), supersession marks the old memory as outdated but historically correct.
501
-
502
- Use this when:
503
- - A status or count has changed (e.g., "5 reviews done" → "7 reviews done")
504
- - Architecture or infrastructure evolved (e.g., "two-repo model" → "three-repo model")
505
- - A schedule or plan was updated
506
-
507
- The old memory stays in the database (searchable for history) but is heavily down-ranked in recall so the current version dominates.`,
508
- {
509
- old_engram_id: z.string().describe('ID of the outdated memory'),
510
- new_engram_id: z.string().describe('ID of the replacement memory'),
511
- reason: z.string().optional().describe('Why the old memory is outdated'),
512
- },
513
- async (params) => {
514
- const oldEngram = await store.getEngram(params.old_engram_id);
515
- if (!oldEngram) {
516
- return { content: [{ type: 'text' as const, text: `Old memory not found: ${params.old_engram_id}` }] };
517
- }
518
- const newEngram = await store.getEngram(params.new_engram_id);
519
- if (!newEngram) {
520
- return { content: [{ type: 'text' as const, text: `New memory not found: ${params.new_engram_id}` }] };
521
- }
522
-
523
- await store.supersedeEngram(params.old_engram_id, params.new_engram_id);
524
-
525
- // Create supersession association (new old)
526
- await store.upsertAssociation(params.new_engram_id, params.old_engram_id, 0.8, 'causal', 0.9);
527
-
528
- // Reduce old memory's confidence (not to zero — it's historical, not wrong)
529
- await store.updateConfidence(params.old_engram_id, Math.max(0.2, oldEngram.confidence * 0.4));
530
-
531
- log(AGENT_ID, 'supersede', `"${oldEngram.concept}" → "${newEngram.concept}"${params.reason ? ` (${params.reason})` : ''}`);
532
-
533
- return {
534
- content: [{
535
- type: 'text' as const,
536
- text: `Superseded: "${oldEngram.concept}" → "${newEngram.concept}"`,
537
- }],
538
- };
539
- }
540
- );
541
-
542
- server.tool(
543
- 'memory_stats',
544
- `Get memory health stats — how many memories, confidence levels, association count, and system performance.
545
- Also shows the activity log path so the user can tail it to see what's happening.`,
546
- {},
547
- async () => {
548
- const metrics = await evalEngine.computeMetrics(AGENT_ID);
549
- const checkpoint = await store.getCheckpoint(AGENT_ID);
550
- const lines = [
551
- `Agent: ${AGENT_ID}`,
552
- `Active memories: ${metrics.activeEngramCount}`,
553
- `Staging: ${metrics.stagingEngramCount}`,
554
- `Retracted: ${metrics.retractedCount}`,
555
- `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
556
- `Total edges: ${metrics.totalEdges}`,
557
- `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
558
- `Activations (24h): ${metrics.activationCount}`,
559
- `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
560
- ``,
561
- `Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
562
- `Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
563
- `Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
564
- `Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
565
- ``,
566
- `Activity log: ${getLogPath() ?? 'not configured'}`,
567
- `Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
568
- ];
569
-
570
- return {
571
- content: [{
572
- type: 'text' as const,
573
- text: lines.join('\n'),
574
- }],
575
- };
576
- }
577
- );
578
-
579
- // --- Checkpointing Tools ---
580
-
581
- server.tool(
582
- 'memory_checkpoint',
583
- `Save your current execution state so you can recover after context compaction.
584
-
585
- ALWAYS call this before:
586
- - Long operations (multi-file generation, large refactors, overnight work)
587
- - Anything that might fill the context window
588
- - Switching to a different task
589
-
590
- Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`,
591
- {
592
- current_task: z.string().describe('What you are currently working on'),
593
- decisions: z.array(z.string()).optional().default([])
594
- .describe('Key decisions made so far'),
595
- active_files: z.array(z.string()).optional().default([])
596
- .describe('Files you are currently working with'),
597
- next_steps: z.array(z.string()).optional().default([])
598
- .describe('What needs to happen next'),
599
- related_memory_ids: z.array(z.string()).optional().default([])
600
- .describe('IDs of memories relevant to current work'),
601
- notes: z.string().optional().default('')
602
- .describe('Any other context worth preserving'),
603
- episode_id: z.string().optional()
604
- .describe('Current episode ID if known'),
605
- },
606
- async (params) => {
607
- const state: ConsciousState = {
608
- currentTask: params.current_task,
609
- decisions: params.decisions,
610
- activeFiles: params.active_files,
611
- nextSteps: params.next_steps,
612
- relatedMemoryIds: params.related_memory_ids,
613
- notes: params.notes,
614
- episodeId: params.episode_id ?? null,
615
- };
616
-
617
- await store.saveCheckpoint(AGENT_ID, state);
618
- log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
619
-
620
- return {
621
- content: [{
622
- type: 'text' as const,
623
- text: `Checkpoint saved: "${params.current_task}" (${params.decisions.length} decisions, ${params.active_files.length} files)`,
624
- }],
625
- };
626
- }
627
- );
628
-
629
- server.tool(
630
- 'memory_restore',
631
- `Restore your previous execution state after context compaction or at session start.
632
-
633
- Returns:
634
- - Your saved execution state (task, decisions, next steps, files)
635
- - Recently recalled memories for context
636
- - Your last write for continuity
637
- - How long you were idle
638
-
639
- Use this at the start of every session or after compaction to pick up where you left off.`,
640
- {},
641
- async () => {
642
- const checkpoint = await store.getCheckpoint(AGENT_ID);
643
-
644
- // Cold-store nudge: an empty store means the agent has nothing to recall — offer to warm-start.
645
- let coldStoreNudge = '';
646
- try {
647
- const activeCount = (await store.getEngramsByAgent(AGENT_ID)).length;
648
- if (activeCount < 3) {
649
- coldStoreNudge = `🌱 **This memory store is nearly empty (${activeCount} ${activeCount === 1 ? 'memory' : 'memories'}).** Warm-start it before other work: recall the "onboard a new project" skill and follow it — or call \`onboard_scan\` on this project's docs/repo, refine the results, and save them with \`memory_write\` (canonical). Recall becomes useful immediately.`;
650
- }
651
- } catch { /* count is best-effort */ }
652
-
653
- const now = Date.now();
654
- const idleMs = checkpoint
655
- ? now - checkpoint.auto.lastActivityAt.getTime()
656
- : 0;
657
-
658
- // Get last written engram
659
- let lastWrite: { id: string; concept: string; content: string } | null = null;
660
- if (checkpoint?.auto.lastWriteId) {
661
- const engram = await store.getEngram(checkpoint.auto.lastWriteId);
662
- if (engram) {
663
- lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
664
- }
665
- }
666
-
667
- // Recall memories using last context
668
- let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
669
- const recallContext = checkpoint?.auto.lastRecallContext
670
- ?? checkpoint?.executionState?.currentTask
671
- ?? null;
672
-
673
- if (recallContext) {
674
- try {
675
- const results = await activationEngine.activate({
676
- agentId: AGENT_ID,
677
- context: recallContext,
678
- limit: 5,
679
- minScore: 0.05,
680
- useReranker: true,
681
- useExpansion: true,
682
- workspace: process.env.AWM_WORKSPACE ?? undefined,
683
- });
684
- recalledMemories = results.map(r => ({
685
- id: r.engram.id,
686
- concept: r.engram.concept,
687
- content: r.engram.content,
688
- score: r.score,
689
- }));
690
- } catch { /* recall failure is non-fatal */ }
691
- }
692
-
693
- // Consolidation on restore:
694
- // - If idle >5min but last consolidation was recent (graceful exit ran it), skip
695
- // - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
696
- const MINI_IDLE_MS = 5 * 60_000;
697
- const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min — if last consolidation was longer ago, run full
698
- let miniConsolidationTriggered = false;
699
- let fullConsolidationTriggered = false;
700
-
701
- if (idleMs > MINI_IDLE_MS) {
702
- const sinceLastConsolidation = checkpoint?.lastConsolidationAt
703
- ? now - checkpoint.lastConsolidationAt.getTime()
704
- : Infinity;
705
-
706
- if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
707
- // No recent consolidation — graceful exit didn't happen, run full cycle
708
- fullConsolidationTriggered = true;
709
- try {
710
- const result = await consolidationEngine.consolidate(AGENT_ID);
711
- await store.markConsolidation(AGENT_ID, false);
712
- log(AGENT_ID, 'consolidation', `full sleep cycle on restore (no graceful exit, idle ${Math.round(idleMs / 60_000)}min, last consolidation ${Math.round(sinceLastConsolidation / 60_000)}min ago) — ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
713
- } catch { /* consolidation failure is non-fatal */ }
714
- } else {
715
- // Recent consolidation exists — graceful exit already handled it, just do mini
716
- miniConsolidationTriggered = true;
717
- consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => {});
718
- }
719
- }
720
-
721
- // Format response
722
- const parts: string[] = [];
723
- const idleMin = Math.round(idleMs / 60_000);
724
- const consolidationNote = fullConsolidationTriggered
725
- ? ' (full consolidation — no graceful exit detected)'
726
- : miniConsolidationTriggered
727
- ? ' (mini-consolidation triggered)'
728
- : '';
729
- log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
730
- parts.push(`Idle: ${idleMin}min${consolidationNote}`);
731
- if (coldStoreNudge) parts.push(`\n${coldStoreNudge}`);
732
-
733
- if (checkpoint?.executionState) {
734
- const s = checkpoint.executionState;
735
- parts.push(`\n**Current task:** ${s.currentTask}`);
736
- if (s.decisions.length) parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
737
- if (s.nextSteps.length) parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
738
- if (s.activeFiles.length) parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
739
- if (s.notes) parts.push(`**Notes:** ${s.notes}`);
740
- if (checkpoint.checkpointAt) parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
741
- } else {
742
- parts.push('\nNo explicit checkpoint saved.');
743
- parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
744
- }
745
-
746
- if (lastWrite) {
747
- parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
748
- }
749
-
750
- if (recalledMemories.length > 0) {
751
- parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
752
- for (const m of recalledMemories) {
753
- parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
754
- }
755
- }
756
-
757
- // Peer decisions: show recent decisions from other agents (last 30 min)
758
- if (coordDb) {
759
- try {
760
- const myAgent = coordDb.prepare(
761
- `SELECT id FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
762
- ).get(AGENT_ID) as { id: string } | undefined;
763
-
764
- const peerDecisions = coordDb.prepare(
765
- `SELECT d.summary, a.name AS author_name, d.created_at
766
- FROM coord_decisions d JOIN coord_agents a ON d.author_id = a.id
767
- WHERE d.author_id != ? AND d.created_at > datetime('now', '-30 minutes')
768
- ORDER BY d.created_at DESC LIMIT 10`
769
- ).all(myAgent?.id ?? '') as Array<{ summary: string; author_name: string; created_at: string }>;
770
-
771
- if (peerDecisions.length > 0) {
772
- parts.push(`\n**Peer decisions (last 30 min):**`);
773
- for (const d of peerDecisions) {
774
- parts.push(`- [${d.author_name}] ${d.summary} (${d.created_at})`);
775
- }
776
- }
777
- } catch { /* peer decisions are non-fatal */ }
778
- }
779
-
780
- return {
781
- content: [{
782
- type: 'text' as const,
783
- text: parts.join('\n'),
784
- }],
785
- };
786
- }
787
- );
788
-
789
- // --- Onboarding Tools (warm-start a cold store) ---
790
-
791
- server.tool(
792
- 'onboard_scan',
793
- `Scan a project's documentation + repository and return CANDIDATE memories to seed a cold store.
794
-
795
- Use this when the store is empty / you're new to a project. The scan is deterministic
796
- (real file contents, not guesses) — YOUR job is to refine the candidates into atomic,
797
- recall-shaped memories, run the interview (onboard_questions), confirm with the user, then
798
- save the good ones with memory_write (memory_class="canonical"). Nothing is saved by this tool.`,
799
- {
800
- docs: z.array(z.string()).optional()
801
- .describe('Doc files/dirs to scan (Markdown/text). Defaults to the repo (or cwd).'),
802
- repo: z.string().optional()
803
- .describe('Repo root also derives stack (package.json) + layout memories.'),
804
- project: z.string().optional()
805
- .describe('Project name (becomes a tag). Defaults to the repo/dir name.'),
806
- purpose: z.string().optional()
807
- .describe('The goal of this memory system, if known — becomes the anchor memory.'),
808
- },
809
- async (params) => {
810
- const repo = params.repo;
811
- const docs = params.docs && params.docs.length ? params.docs : [repo ?? process.cwd()];
812
- const project = params.project ?? basename(resolve(repo ?? docs[0] ?? process.cwd()));
813
- const pack = buildPack({ docs, repo, project, agentId: AGENT_ID, purpose: params.purpose });
814
- log(AGENT_ID, 'onboard', `scan ${docs.join(',')}${repo ? ' +repo' : ''} → ${pack.memories.length} candidates`);
815
- const text = [
816
- `Scanned ${docs.join(', ')}${repo ? ` (+repo ${repo})` : ''} → ${pack.memories.length} CANDIDATE memories (NOT saved).`,
817
- `Next: refine each into an atomic memory (lead with the fact + identifiers), run onboard_questions,`,
818
- `confirm with the user, then save the good ones with memory_write (memory_class="canonical").`,
819
- ``,
820
- JSON.stringify({ project, candidates: pack.memories, questions: pack.questions }, null, 2),
821
- ].join('\n');
822
- return { content: [{ type: 'text' as const, text }] };
823
- }
824
- );
825
-
826
- server.tool(
827
- 'onboard_questions',
828
- `Return the onboarding interview questions. Ask the user ONE at a time, starting with the
829
- goal of the memory system, and ask follow-ups for clarity. Turn each answer into a canonical memory.`,
830
- {},
831
- async () => ({
832
- content: [{ type: 'text' as const, text: INTERVIEW_QUESTIONS.map((q, i) => `${i + 1}. ${q}`).join('\n') }],
833
- })
834
- );
835
-
836
- // --- Task Management Tools ---
837
-
838
- server.tool(
839
- 'memory_task_add',
840
- `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
841
-
842
- Use this when:
843
- - You identify work that needs doing but can't do it right now
844
- - The user mentions something to do later
845
- - You want to park a sub-task while focusing on something more urgent
846
-
847
- Tasks automatically get high salience so they won't be discarded.`,
848
- {
849
- concept: z.string().describe('Short task title (3-10 words)'),
850
- content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
851
- tags: z.array(z.string()).optional().describe('Tags for categorization'),
852
- priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
853
- .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
854
- blocked_by: z.string().optional().describe('ID of a task that must finish first'),
855
- },
856
- async (params) => {
857
- const engram = await store.createEngram({
858
- agentId: AGENT_ID,
859
- concept: params.concept,
860
- content: params.content,
861
- tags: [...(params.tags ?? []), 'task'],
862
- salience: 0.9, // Tasks always high salience
863
- confidence: 0.8,
864
- salienceFeatures: {
865
- surprise: 0.5,
866
- decisionMade: true,
867
- causalDepth: 0.5,
868
- resolutionEffort: 0.5,
869
- eventType: 'decision',
870
- },
871
- reasonCodes: ['task-created'],
872
- taskStatus: params.blocked_by ? 'blocked' : 'open',
873
- taskPriority: params.priority as TaskPriority,
874
- blockedBy: params.blocked_by,
875
- });
876
-
877
- connectionEngine.enqueue(engram.id);
878
-
879
- // Generate embedding asynchronously
880
- embed(`${params.concept} ${params.content}`).then(async vec => {
881
- await store.updateEmbedding(engram.id, vec);
882
- }).catch(() => {});
883
-
884
- return {
885
- content: [{
886
- type: 'text' as const,
887
- text: `Task created: "${params.concept}" (${params.priority})`,
888
- }],
889
- };
890
- }
891
- );
892
-
893
- server.tool(
894
- 'memory_task_update',
895
- `Update a task's status or priority. Use this to:
896
- - Start working on a task (open → in_progress)
897
- - Mark a task done (→ done)
898
- - Block a task on another (→ blocked)
899
- - Reprioritize (change priority)
900
- - Unblock a task (clear blocked_by)`,
901
- {
902
- task_id: z.string().describe('ID of the task to update'),
903
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
904
- .describe('New status'),
905
- priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
906
- .describe('New priority'),
907
- blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
908
- },
909
- async (params) => {
910
- const engram = await store.getEngram(params.task_id);
911
- if (!engram || !engram.taskStatus) {
912
- return { content: [{ type: 'text' as const, text: `Task not found: ${params.task_id}` }] };
913
- }
914
-
915
- if (params.blocked_by !== undefined) {
916
- await store.updateBlockedBy(params.task_id, params.blocked_by || null);
917
- }
918
- if (params.status) {
919
- await store.updateTaskStatus(params.task_id, params.status as TaskStatus);
920
- }
921
- if (params.priority) {
922
- await store.updateTaskPriority(params.task_id, params.priority as TaskPriority);
923
- }
924
-
925
- const updated = (await store.getEngram(params.task_id))!;
926
- return {
927
- content: [{
928
- type: 'text' as const,
929
- text: `Updated: "${updated.concept}" → ${updated.taskStatus} (${updated.taskPriority})`,
930
- }],
931
- };
932
- }
933
- );
934
-
935
- server.tool(
936
- 'memory_task_list',
937
- `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
938
-
939
- Use at the start of a session to see what's pending, or to check blocked/done tasks.`,
940
- {
941
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
942
- .describe('Filter by status (omit to see all active tasks)'),
943
- include_done: z.boolean().optional().default(false)
944
- .describe('Include completed tasks?'),
945
- },
946
- async (params) => {
947
- let tasks = await store.getTasks(AGENT_ID, params.status as TaskStatus | undefined);
948
- if (!params.include_done && !params.status) {
949
- tasks = tasks.filter(t => t.taskStatus !== 'done');
950
- }
951
-
952
- if (tasks.length === 0) {
953
- return { content: [{ type: 'text' as const, text: 'No tasks found.' }] };
954
- }
955
-
956
- const lines = tasks.map((t, i) => {
957
- const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
958
- const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
959
- return `${i + 1}. [${t.taskStatus}] **${t.concept}** (${t.taskPriority})${blocked}\n ${t.content.slice(0, 120)}${t.content.length > 120 ? '...' : ''}\n ${tags ? `Tags: ${tags} | ` : ''}ID: ${t.id}`;
960
- });
961
-
962
- return {
963
- content: [{
964
- type: 'text' as const,
965
- text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
966
- }],
967
- };
968
- }
969
- );
970
-
971
- server.tool(
972
- 'memory_task_next',
973
- `Get the single most important task to work on next.
974
-
975
- Prioritizes: in_progress tasks first (finish what you started), then by priority level, then oldest first. Skips blocked and done tasks.
976
-
977
- Use this when you finish a task or need to decide what to do next.`,
978
- {},
979
- async () => {
980
- const next = await store.getNextTask(AGENT_ID);
981
- if (!next) {
982
- return { content: [{ type: 'text' as const, text: 'No actionable tasks. All clear!' }] };
983
- }
984
-
985
- const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
986
- const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
987
-
988
- return {
989
- content: [{
990
- type: 'text' as const,
991
- text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
992
- }],
993
- };
994
- }
995
- );
996
-
997
- // --- Task Bracket Tools ---
998
-
999
- server.tool(
1000
- 'memory_task_begin',
1001
- `Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
1002
-
1003
- CALL THIS when starting:
1004
- - A multi-step operation (doc generation, large refactor, migration)
1005
- - Work on a new topic or project area
1006
- - Anything that might fill the context window
1007
-
1008
- This ensures your state is saved before you start, and primes recall with relevant context.`,
1009
- {
1010
- topic: z.string().describe('What task are you starting? (3-15 words)'),
1011
- files: z.array(z.string()).optional().default([])
1012
- .describe('Files you expect to work with'),
1013
- notes: z.string().optional().default('')
1014
- .describe('Any additional context'),
1015
- },
1016
- async (params) => {
1017
- // 1. Checkpoint current state
1018
- const checkpoint = await store.getCheckpoint(AGENT_ID);
1019
- const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
1020
-
1021
- await store.saveCheckpoint(AGENT_ID, {
1022
- currentTask: params.topic,
1023
- decisions: [],
1024
- activeFiles: params.files,
1025
- nextSteps: [],
1026
- relatedMemoryIds: [],
1027
- notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
1028
- episodeId: null,
1029
- });
1030
-
1031
- // 2. Auto-recall relevant memories
1032
- let recalledSummary = '';
1033
- try {
1034
- const results = await activationEngine.activate({
1035
- agentId: AGENT_ID,
1036
- context: params.topic,
1037
- limit: 5,
1038
- minScore: 0.05,
1039
- useReranker: true,
1040
- useExpansion: true,
1041
- workspace: process.env.AWM_WORKSPACE ?? undefined,
1042
- });
1043
-
1044
- if (results.length > 0) {
1045
- const lines = results.map((r, i) => {
1046
- const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
1047
- return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
1048
- });
1049
- recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
1050
-
1051
- // Track recall
1052
- await store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
1053
- }
1054
- } catch { /* recall failure is non-fatal */ }
1055
-
1056
- log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
1057
-
1058
- return {
1059
- content: [{
1060
- type: 'text' as const,
1061
- text: `Started: "${params.topic}" (prev: ${prevTask})${recalledSummary}`,
1062
- }],
1063
- };
1064
- }
1065
- );
1066
-
1067
- server.tool(
1068
- 'memory_task_end',
1069
- `Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
1070
-
1071
- CALL THIS when you finish:
1072
- - A multi-step operation
1073
- - Before switching to a different topic
1074
- - At the end of a work session
1075
-
1076
- This captures what was accomplished so future sessions can recall it.`,
1077
- {
1078
- summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
1079
- tags: z.array(z.string()).optional().default([])
1080
- .describe('Tags for the summary memory'),
1081
- supersedes: z.array(z.string()).optional().default([])
1082
- .describe('IDs of older memories this task summary replaces (marks them as superseded)'),
1083
- },
1084
- async (params) => {
1085
- // 1. Write summary as a memory
1086
- const salience = evaluateSalience({
1087
- content: params.summary,
1088
- eventType: 'decision',
1089
- surprise: 0.3,
1090
- decisionMade: true,
1091
- causalDepth: 0.5,
1092
- resolutionEffort: 0.5,
1093
- });
1094
-
1095
- // Determine the real task name for the summary engram
1096
- const checkpoint = await store.getCheckpoint(AGENT_ID);
1097
- const rawTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
1098
- // Strip any "Completed: " prefixes to avoid cascading
1099
- const cleanedTask = rawTask.replace(/^(Completed: )+/, '');
1100
- // Don't use auto-checkpoint or already-completed tasks as real task names
1101
- const isNamedTask = !cleanedTask.startsWith('Auto-checkpoint') && cleanedTask !== 'Unknown task';
1102
- const completedTask = isNamedTask
1103
- ? cleanedTask
1104
- : params.summary.slice(0, 60).replace(/\n/g, ' ');
1105
-
1106
- const engram = await store.createEngram({
1107
- agentId: AGENT_ID,
1108
- concept: completedTask.slice(0, 80),
1109
- content: params.summary,
1110
- tags: [...params.tags, 'task-summary'],
1111
- salience: isNamedTask ? Math.max(salience.score, 0.7) : salience.score, // Only floor salience for named tasks
1112
- confidence: 0.65, // Task summaries are decision-grade (completed work)
1113
- salienceFeatures: salience.features,
1114
- reasonCodes: [...salience.reasonCodes, 'task-end'],
1115
- });
1116
-
1117
- connectionEngine.enqueue(engram.id);
1118
-
1119
- // 2. Handle supersessions — mark old memories as outdated
1120
- let supersededCount = 0;
1121
- for (const oldId of params.supersedes) {
1122
- const oldEngram = await store.getEngram(oldId);
1123
- if (oldEngram) {
1124
- await store.supersedeEngram(oldId, engram.id);
1125
- await store.upsertAssociation(engram.id, oldId, 0.8, 'causal', 0.9);
1126
- await store.updateConfidence(oldId, Math.max(0.2, oldEngram.confidence * 0.4));
1127
- supersededCount++;
1128
- }
1129
- }
1130
-
1131
- // Generate embedding asynchronously
1132
- embed(`Task completed: ${params.summary}`).then(async vec => {
1133
- await store.updateEmbedding(engram.id, vec);
1134
- }).catch(() => {});
1135
-
1136
- // 2. Update checkpoint to reflect completion
1137
- await store.saveCheckpoint(AGENT_ID, {
1138
- currentTask: `Completed: ${completedTask}`,
1139
- decisions: checkpoint?.executionState?.decisions ?? [],
1140
- activeFiles: [],
1141
- nextSteps: [],
1142
- relatedMemoryIds: [engram.id],
1143
- notes: `Task completed. Summary memory: ${engram.id}`,
1144
- episodeId: null,
1145
- });
1146
-
1147
- await store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
1148
- log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)} superseded=${supersededCount}`);
1149
-
1150
- const supersededNote = supersededCount > 0 ? ` (${supersededCount} old memories superseded)` : '';
1151
- return {
1152
- content: [{
1153
- type: 'text' as const,
1154
- text: `Completed: "${completedTask}" [${salience.score.toFixed(2)}]${supersededNote}`,
1155
- }],
1156
- };
1157
- }
1158
- );
1159
-
1160
- server.tool(
1161
- 'compress_output',
1162
- `Compress a STRUCTURED tool output (JSON object/array, query rows, log records) into TOON —
1163
- a compact, schema-aware tabular encoding — before putting it in your context. Cuts ~50-65%
1164
- of the tokens on uniform arrays at zero comprehension cost (validated: models read TOON as
1165
- accurately as JSON). Use this on large tool results you need to keep in context.
1166
-
1167
- Output-only and safe: it never changes the data. Non-JSON / prose is returned unchanged.
1168
- TOON is only emitted when it reproduces the input exactly (self-verified round-trip);
1169
- otherwise you get plain JSON back. When compressed, you also get a 'ref' — call
1170
- retrieve_original(ref) to get the verbatim source back if you ever need it.`,
1171
- {
1172
- output: z.string().describe('The tool output to compress JSON text (preferred) or any string. Non-JSON is returned unchanged.'),
1173
- min_saving_chars: z.number().optional().describe('Only emit TOON if it saves at least this many characters (default 40).'),
1174
- },
1175
- async (params) => {
1176
- const r = liteCompress(params.output, { minSavingChars: params.min_saving_chars });
1177
- log(AGENT_ID, 'compress', `${r.format} ${r.charsBefore}->${r.charsAfter} chars (${(r.ratio * 100).toFixed(0)}%)${r.ref ? ` ref=${r.ref}` : ''}`);
1178
- const header = r.format === 'toon'
1179
- ? `[TOON, ${(r.ratio * 100).toFixed(0)}% smaller compact lossless JSON; read as data, ref=${r.ref}]\n`
1180
- : '';
1181
- return {
1182
- content: [{ type: 'text' as const, text: header + r.text }],
1183
- };
1184
- }
1185
- );
1186
-
1187
- server.tool(
1188
- 'retrieve_original',
1189
- `Retrieve the verbatim original text for a 'ref' returned by compress_output. Use this when
1190
- you need the exact, uncompressed source (e.g. to pass it to another tool unchanged). Returns
1191
- an error if the ref has expired (originals are kept for the most recent compressions only).`,
1192
- {
1193
- ref: z.string().describe('The ref handle returned by compress_output (e.g. "awm_orig_12").'),
1194
- },
1195
- async (params) => {
1196
- const original = retrieveOriginal(params.ref);
1197
- if (original === undefined) {
1198
- return {
1199
- content: [{ type: 'text' as const, text: `Error: ref "${params.ref}" not found or expired.` }],
1200
- };
1201
- }
1202
- return {
1203
- content: [{ type: 'text' as const, text: original }],
1204
- };
1205
- }
1206
- );
1207
-
1208
- // --- Start ---
1209
-
1210
- async function main() {
1211
- const transport = new StdioServerTransport();
1212
- await server.connect(transport);
1213
-
1214
- // Start hook sidecar (lightweight HTTP for Claude Code hooks)
1215
- const sidecar = startSidecar({
1216
- store,
1217
- agentId: AGENT_ID,
1218
- secret: HOOK_SECRET,
1219
- port: HOOK_PORT,
1220
- onConsolidate: async (agentId, reason) => {
1221
- console.error(`[mcp] consolidation triggered: ${reason}`);
1222
- const result = await consolidationEngine.consolidate(agentId);
1223
- await store.markConsolidation(agentId, false);
1224
- console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
1225
- },
1226
- });
1227
-
1228
- // Coordination MCP tools (opt-in via AWM_COORDINATION=true)
1229
- // AWM 0.8.x: coordination requires SQLite (uses store.getDb()). On PGlite,
1230
- // coordination is auto-disabled with a warning; re-enable when coordination
1231
- // is ported to async/PGlite.
1232
- const coordRequested = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
1233
- const coordEnabled = coordRequested && BACKEND === 'sqlite';
1234
- if (coordEnabled) {
1235
- const { initCoordinationTables } = await import('./coordination/schema.js');
1236
- const { registerCoordinationTools } = await import('./coordination/mcp-tools.js');
1237
- const sqliteStore = store as unknown as EngramStore;
1238
- initCoordinationTables(sqliteStore.getDb());
1239
- registerCoordinationTools(server, sqliteStore.getDb());
1240
- coordDb = sqliteStore.getDb();
1241
- } else if (coordRequested && BACKEND === 'pglite') {
1242
- console.error('AWM: coordination requested but disabled coordination plugin requires SQLite backend');
1243
- } else {
1244
- console.error('AWM: coordination tools disabled (set AWM_COORDINATION=true to enable)');
1245
- }
1246
-
1247
- // Log to stderr (stdout is reserved for MCP protocol)
1248
- console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
1249
- console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
1250
-
1251
- // Clean shutdown
1252
- const cleanup = async () => {
1253
- sidecar.close();
1254
- consolidationScheduler.stop();
1255
- stagingBuffer.stop();
1256
- if (BACKEND === 'sqlite') {
1257
- try { (store as Partial<EngramStore>).walCheckpoint?.(); } catch { /* non-fatal */ }
1258
- }
1259
- try { await (store as any).close?.(); } catch { /* best-effort */ }
1260
- };
1261
- process.on('SIGINT', () => { void cleanup().finally(() => process.exit(0)); });
1262
- process.on('SIGTERM', () => { void cleanup().finally(() => process.exit(0)); });
1263
- }
1264
-
1265
- main().catch(err => {
1266
- console.error('MCP server failed:', err);
1267
- process.exit(1);
1268
- });
1269
-
1270
- } // end else (non-incognito)
1
+ // Copyright 2026 Robert Winter / Complete Ideas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * MCP Server — Model Context Protocol interface for AgentWorkingMemory.
5
+ *
6
+ * Runs as a stdio-based MCP server that Claude Code connects to directly.
7
+ * Uses the storage and engine layers in-process (no HTTP overhead).
8
+ *
9
+ * Tools exposed (19):
10
+ * memory_write — store a memory (salience filter decides disposition)
11
+ * memory_recall — activate memories by context (cognitive retrieval)
12
+ * memory_feedback — report whether a recalled memory was useful
13
+ * memory_retract — invalidate a wrong memory with optional correction
14
+ * memory_supersede — replace an outdated memory with a current one
15
+ * memory_stats — get memory health metrics
16
+ * memory_whoami identify this instance, mode, store, and sibling agent spaces
17
+ * memory_checkpoint save structured execution state (survives compaction)
18
+ * memory_restore restore state + targeted recall after compaction
19
+ * memory_task_add create a prioritized task
20
+ * memory_task_update change task status, priority, or blocking
21
+ * memory_task_listlist tasks filtered by status
22
+ * memory_task_next get the highest-priority actionable task
23
+ * memory_task_begin start a task (auto-checkpoint + recall)
24
+ * memory_task_endend a task (write summary + checkpoint)
25
+ * compress_output encode structured tool output as TOON (token-efficient, lossless)
26
+ * retrieve_original — get the verbatim source for a compress_output ref
27
+ *
28
+ * Run: npx tsx src/mcp.ts
29
+ * Config: add to ~/.claude.json or .mcp.json
30
+ */
31
+
32
+ import { readFileSync } from 'node:fs';
33
+ import { resolve, basename } from 'node:path';
34
+ import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
35
+
36
+ // Load .env file if present (no external dependency)
37
+ try {
38
+ const envPath = resolve(process.cwd(), '.env');
39
+ const envContent = readFileSync(envPath, 'utf-8');
40
+ for (const line of envContent.split('\n')) {
41
+ const trimmed = line.trim();
42
+ if (!trimmed || trimmed.startsWith('#')) continue;
43
+ const eqIdx = trimmed.indexOf('=');
44
+ if (eqIdx === -1) continue;
45
+ const key = trimmed.slice(0, eqIdx).trim();
46
+ const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, '');
47
+ if (!process.env[key]) process.env[key] = val;
48
+ }
49
+ } catch { /* No .env file */ }
50
+
51
+ // MCP uses stdout for JSON-RPC. Redirect console.log to stderr so engine
52
+ // startup messages (ConsolidationScheduler, model loading, etc.) don't
53
+ // corrupt the transport. This MUST happen before any engine imports.
54
+ console.log = console.error;
55
+
56
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
57
+ import { z } from 'zod';
58
+
59
+ import { EngramStore } from './storage/sqlite.js';
60
+ import { openStore, getConfiguredBackend, type StoreBackend } from './storage/factory.js';
61
+ import type { IEngramStore } from './storage/store.js';
62
+ import { ActivationEngine } from './engine/activation.js';
63
+ import { ConnectionEngine } from './engine/connections.js';
64
+ import { StagingBuffer } from './engine/staging.js';
65
+ import { EvictionEngine } from './engine/eviction.js';
66
+ import { RetractionEngine } from './engine/retraction.js';
67
+ import { EvalEngine } from './engine/eval.js';
68
+ import { ConsolidationEngine } from './engine/consolidation.js';
69
+ import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
70
+ import { evaluateSalience, computeNovelty, computeNoveltyWithMatch } from './core/salience.js';
71
+ import { performWrite } from './core/write-pipeline.js';
72
+ import type { ConsciousState } from './types/checkpoint.js';
73
+ import type { SalienceEventType } from './core/salience.js';
74
+ import type { TaskStatus, TaskPriority } from './types/engram.js';
75
+ import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
76
+ import { embed, getEmbedder } from './core/embeddings.js';
77
+ import { getReranker } from './core/reranker.js';
78
+ import { getExpander } from './core/query-expander.js';
79
+ import { startSidecar } from './hooks/sidecar.js';
80
+ import { initLogger, log, getLogPath } from './core/logger.js';
81
+ import { VERSION } from './version.js';
82
+ import { buildPack, INTERVIEW_QUESTIONS } from './onboard/index.js';
83
+ import { liteCompress, retrieveOriginal } from './core/lite-compress.js';
84
+ import { queryPeerDecisions, formatPeerDecisions } from './coordination/peer-decisions.js';
85
+ import { startLoopLagMonitor } from './core/write-telemetry.js';
86
+ import { buildWhoami, formatWhoami } from './core/whoami.js';
87
+ import { renderTaskEndInvitation, validateRecipeWrite, recipeSlug, getRecipe } from './recipes/index.js';
88
+ import { formatRecallResultLine } from './core/format-recall.js';
89
+
90
+ // --- Incognito Mode ---
91
+ // When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
92
+ // No DB, no engines, no sidecar — just a bare MCP server that exposes nothing.
93
+
94
+ const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
95
+
96
+ if (INCOGNITO) {
97
+ console.error('AWM: incognito modeall memory tools disabled, nothing will be recorded');
98
+ const server = new McpServer({ name: 'agent-working-memory', version: VERSION });
99
+ const transport = new StdioServerTransport();
100
+ server.connect(transport).catch(err => {
101
+ console.error('MCP server failed:', err);
102
+ process.exit(1);
103
+ });
104
+ // No tools registered — Claude won't see any memory_* tools
105
+ } else {
106
+
107
+ // --- Setup ---
108
+
109
+ const BACKEND: StoreBackend = getConfiguredBackend();
110
+ const DB_PATH = process.env.AWM_DB_PATH ?? (BACKEND === 'pglite' ? 'memory-pglite' : 'memory.db');
111
+
112
+ // Fallback agent selection when AWM_AGENT_ID/WORKER_NAME are unset: derive from
113
+ // the project directory so plain `claude` launches still bind to the right
114
+ // store. Personal-Projects -> 'personal'; everything else -> 'work' (the
115
+ // primary store). MUST stay in sync with the SessionStart hook
116
+ // (~/.claude/hooks/awm-session-start.ps1) so the hook's restore and the
117
+ // server's reads/writes never diverge. Guard the AWM package's own path
118
+ // (it lives under Personal-Projects) so a stray server cwd can't mis-bind.
119
+ function deriveAgentFromDir(): string {
120
+ const dir = (process.env.CLAUDE_PROJECT_DIR ?? process.cwd()).replace(/\\/g, '/');
121
+ if (/\/AgentSynapse\//i.test(dir)) return 'work';
122
+ return /\/Personal-Projects(\/|$)/i.test(dir) ? 'personal' : 'work';
123
+ }
124
+ const AGENT_ID = process.env.AWM_AGENT_ID ?? process.env.WORKER_NAME ?? deriveAgentFromDir();
125
+ const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
126
+ const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
127
+
128
+ initLogger(DB_PATH);
129
+ log(AGENT_ID, 'startup', `MCP server starting (backend: ${BACKEND}, db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
130
+
131
+ // AWM 0.8.x: openStore() returns either SQLite (sync) or PGlite (async) store.
132
+ // Engines accept either via IEngramStore (MaybePromise<T> contract).
133
+ const { store: storeAny } = await openStore();
134
+ // Engines accept the async contract; SQLite-only call sites must guard on BACKEND.
135
+ const store = storeAny as unknown as IEngramStore & Partial<EngramStore>;
136
+ const activationEngine = new ActivationEngine(store);
137
+ const connectionEngine = new ConnectionEngine(store, activationEngine);
138
+ const stagingBuffer = new StagingBuffer(store, activationEngine);
139
+ const evictionEngine = new EvictionEngine(store);
140
+ const retractionEngine = new RetractionEngine(store);
141
+ const evalEngine = new EvalEngine(store);
142
+ const consolidationEngine = new ConsolidationEngine(store, connectionEngine);
143
+ const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
144
+
145
+ stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
146
+ consolidationScheduler.start();
147
+ startLoopLagMonitor();
148
+
149
+ // Coordination DB handle — set when AWM_COORDINATION=true, used by memory_write for decision propagation
150
+ let coordDb: import('better-sqlite3').Database | null = null;
151
+
152
+ const server = new McpServer({
153
+ name: 'agent-working-memory',
154
+ version: VERSION,
155
+ });
156
+
157
+ server.registerResource(
158
+ 'awm-overview',
159
+ 'awm://server/overview',
160
+ {
161
+ title: 'AWM Overview',
162
+ description: 'AgentWorkingMemory MCP server metadata and discovery notes',
163
+ mimeType: 'text/markdown',
164
+ },
165
+ async () => ({
166
+ contents: [{
167
+ uri: 'awm://server/overview',
168
+ text: [
169
+ '# Agent Working Memory',
170
+ '',
171
+ `Agent: ${AGENT_ID}`,
172
+ `DB: ${DB_PATH}`,
173
+ `Coordination: ${process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1' ? 'enabled' : 'disabled'}`,
174
+ '',
175
+ 'This MCP server primarily exposes tools such as `memory_restore`, `memory_recall`, `memory_write`, and task/checkpoint operations.',
176
+ 'The resources below exist so generic MCP clients can discover the server through `resources/list` and `resources/templates/list`.',
177
+ ].join('\n'),
178
+ mimeType: 'text/markdown',
179
+ }],
180
+ })
181
+ );
182
+
183
+ server.registerResource(
184
+ 'awm-memory-template',
185
+ new ResourceTemplate('awm://memory/{id}', { list: undefined }),
186
+ {
187
+ title: 'AWM Memory By ID',
188
+ description: 'Metadata resource template for a memory identifier',
189
+ mimeType: 'text/markdown',
190
+ },
191
+ async (_uri, variables) => ({
192
+ contents: [{
193
+ uri: `awm://memory/${variables.id ?? ''}`,
194
+ text: [
195
+ '# AWM Memory Reference',
196
+ '',
197
+ `Requested memory id: ${variables.id ?? ''}`,
198
+ '',
199
+ 'Use the AWM memory tools for actual retrieval and mutation:',
200
+ '- `memory_recall` for cognitive retrieval',
201
+ '- `memory_restore` for session state',
202
+ '- `memory_feedback`, `memory_retract`, `memory_supersede` for memory maintenance',
203
+ ].join('\n'),
204
+ mimeType: 'text/markdown',
205
+ }],
206
+ })
207
+ );
208
+
209
+ // --- Auto-classification for memory types ---
210
+
211
+ function classifyMemoryType(content: string): 'episodic' | 'semantic' | 'procedural' | 'unclassified' {
212
+ const lower = content.toLowerCase();
213
+ // Procedural: how-to, steps, numbered lists
214
+ if (/\bhow to\b|\bsteps?:/i.test(content) || /^\s*\d+[\.\)]\s/m.test(content) || /\bthen run\b|\bfirst,?\s/i.test(content)) {
215
+ return 'procedural';
216
+ }
217
+ // Episodic: past tense events, incidents, specific time references
218
+ if (/\b(discovered|debugged|fixed|encountered|happened|resolved|found that|we did|i did|yesterday|last week|today)\b/i.test(content)) {
219
+ return 'episodic';
220
+ }
221
+ // Semantic: facts, decisions, rules, patterns
222
+ if (/\b(is|are|should|always|never|must|uses?|requires?|means|pattern|decision|rule|convention)\b/i.test(content) && content.length < 500) {
223
+ return 'semantic';
224
+ }
225
+ return 'unclassified';
226
+ }
227
+
228
+ // --- Tools ---
229
+
230
+ server.tool(
231
+ 'memory_write',
232
+ `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
233
+
234
+ CALL THIS PROACTIVELY — do not wait to be asked. Write memories when you:
235
+ - Discover something about the codebase, bugs, or architecture
236
+ - Make a decision and want to remember why
237
+ - Encounter and resolve an error
238
+ - Learn a user preference or project pattern
239
+ - Complete a significant piece of work
240
+
241
+ The concept should be a short label (3-8 words). The content should be the full detail.`,
242
+ {
243
+ concept: z.string().describe('Short label for this memory (3-8 words)'),
244
+ content: z.string().describe('Full detail of what was learned'),
245
+ tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
246
+ event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
247
+ .optional().default('observation')
248
+ .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
249
+ surprise: z.number().min(0).max(1).optional().default(0.3)
250
+ .describe('How surprising was this? 0=expected, 1=very unexpected'),
251
+ decision_made: z.boolean().optional().default(false)
252
+ .describe('Was a decision made? True boosts importance'),
253
+ causal_depth: z.number().min(0).max(1).optional().default(0.3)
254
+ .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
255
+ resolution_effort: z.number().min(0).max(1).optional().default(0.3)
256
+ .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
257
+ memory_class: z.enum(['canonical', 'working', 'ephemeral']).optional().default('working')
258
+ .describe('Memory class: canonical (source-of-truth, never stages), working (default), ephemeral (temporary, decays faster)'),
259
+ memory_type: z.enum(['episodic', 'semantic', 'procedural', 'unclassified']).optional()
260
+ .describe('Memory type: episodic (events/incidents), semantic (facts/decisions), procedural (how-to/steps). Auto-classified if omitted.'),
261
+ supersedes: z.string().optional()
262
+ .describe('ID of an older memory this one replaces. The old memory is down-ranked, not deleted.'),
263
+ // --- Agent-provided metadata (stored as searchable tags) ---
264
+ project: z.string().optional()
265
+ .describe('Project context (e.g., "EquiHub", "AWM"). Becomes a searchable tag.'),
266
+ topic: z.string().optional()
267
+ .describe('Subject area (e.g., "database-migration", "auth-flow"). Becomes a searchable tag.'),
268
+ source: z.enum(['code-reading', 'debugging', 'discussion', 'research', 'testing', 'observation']).optional()
269
+ .describe('How this knowledge was acquired.'),
270
+ confidence_level: z.enum(['verified', 'observed', 'assumed']).optional()
271
+ .describe('Confidence: verified (tested), observed (read in code), assumed (reasoning).'),
272
+ session_id: z.string().optional()
273
+ .describe('Session/conversation grouping ID. Memories with same session_id are associated.'),
274
+ origin_class: z.enum(['user-stated', 'tool-output', 'inference', 'recipe']).optional()
275
+ .describe('Provenance (D5, log-only): where this knowledge came from. user-stated = the human said it; tool-output = read from a tool/system; inference = your reasoning; recipe = produced by a cognition recipe.'),
276
+ recipe_id: z.string().optional()
277
+ .describe('Cognition-recipe id+version when origin_class is recipe.'),
278
+ valid_from: z.string().optional()
279
+ .describe('ISO date when the FACT becomes valid (temporal validity, not ingestion time).'),
280
+ valid_to: z.string().optional()
281
+ .describe('ISO date when the FACT stops being valid (e.g., a deadline or a superseding change).'),
282
+ intent: z.enum(['decision', 'question', 'todo', 'finding', 'context']).optional()
283
+ .describe('What kind of memory this is.'),
284
+ },
285
+ async (params) => {
286
+ // Assemble tags: user-provided + agent metadata (stored as searchable prefixed tags)
287
+ const userTags = params.tags ?? [];
288
+ const metaTags: string[] = [];
289
+ if (params.project) metaTags.push(`proj=${params.project}`);
290
+ if (params.topic) metaTags.push(`topic=${params.topic}`);
291
+ if (params.source) metaTags.push(`src=${params.source}`);
292
+ if (params.confidence_level) metaTags.push(`conf=${params.confidence_level}`);
293
+ if (params.session_id) metaTags.push(`sid=${params.session_id}`);
294
+ if (params.intent) metaTags.push(`intent=${params.intent}`);
295
+
296
+ // D14 (2026-07-30): recipe write-backs are contract-checked. Provenance
297
+ // must never claim a recipe that does not exist, and malformed
298
+ // derivations are rejected with the contract echoed back so the host
299
+ // can self-correct in one retry.
300
+ if (params.origin_class === 'recipe') {
301
+ if (!params.recipe_id) {
302
+ return { content: [{ type: 'text' as const, text: "Recipe write rejected: origin_class 'recipe' requires recipe_id (e.g. 'skill-derivation@1')." }] };
303
+ }
304
+ const v = validateRecipeWrite(params.recipe_id, params.concept, params.content);
305
+ if (!v.ok) {
306
+ const contract = getRecipe(params.recipe_id)?.writeBack ?? 'unknown recipe';
307
+ return { content: [{ type: 'text' as const, text: `Recipe write rejected (${params.recipe_id}): ${v.errors.join('; ')}\nContract: ${contract}` }] };
308
+ }
309
+ // Standardize recipe write-backs: canonical class, standard tags.
310
+ const slug = recipeSlug(params.concept);
311
+ const ensure = (tag: string) => { if (!userTags.includes(tag) && !metaTags.includes(tag)) metaTags.push(tag); };
312
+ if (params.recipe_id.startsWith('skill-derivation')) {
313
+ ensure('topic=skill'); ensure(`skill=${slug}`);
314
+ params.memory_type = params.memory_type ?? 'procedural';
315
+ } else if (params.recipe_id.startsWith('friction-lesson')) {
316
+ ensure('topic=friction'); ensure(`about=${slug}`);
317
+ // zod defaults event_type to 'observation', so force the recipe's
318
+ // contract value rather than ??-guarding against undefined.
319
+ params.event_type = 'friction';
320
+ }
321
+ params.memory_class = 'canonical';
322
+ }
323
+
324
+ const memoryType = params.memory_type ?? classifyMemoryType(params.content);
325
+
326
+ const result = await performWrite({ store, connectionEngine }, {
327
+ agentId: AGENT_ID,
328
+ concept: params.concept,
329
+ content: params.content,
330
+ tags: [...userTags, ...metaTags],
331
+ eventType: params.event_type as SalienceEventType,
332
+ surprise: params.surprise,
333
+ decisionMade: params.decision_made,
334
+ causalDepth: params.causal_depth,
335
+ resolutionEffort: params.resolution_effort,
336
+ memoryClass: params.memory_class,
337
+ memoryType,
338
+ supersedes: params.supersedes,
339
+ originClass: params.origin_class,
340
+ writerSession: params.session_id,
341
+ recipeId: params.recipe_id,
342
+ validFrom: params.valid_from,
343
+ validTo: params.valid_to,
344
+ });
345
+
346
+ // Auto-checkpoint covers create/reinforce/supersede uniformly
347
+ try { await store.updateAutoCheckpointWrite(AGENT_ID, result.engram.id); } catch { /* non-fatal */ }
348
+
349
+ if (result.action === 'reinforce') {
350
+ log(AGENT_ID, 'write:reinforce', `"${params.concept}" reinforced "${result.engram.concept}" (conf ${result.reinforce!.previousConfidence.toFixed(2)} ${result.reinforce!.newConfidence.toFixed(2)}, novelty=${result.noveltyResult.novelty.toFixed(2)})`);
351
+ return {
352
+ content: [{
353
+ type: 'text' as const,
354
+ text: `Reinforced existing memory "${result.engram.concept}" (confidence ${result.reinforce!.previousConfidence.toFixed(2)} → ${result.reinforce!.newConfidence.toFixed(2)})`,
355
+ }],
356
+ };
357
+ }
358
+
359
+ const engram = result.engram;
360
+ const salience = result.salience!; // create/supersede always have salience
361
+ const novelty = result.noveltyResult.novelty;
362
+ const isLowSalience = salience.disposition === 'discard';
363
+
364
+ // Decision propagation: when decision_made=true and coordination is enabled,
365
+ // broadcast to coord_decisions so other agents can discover it
366
+ if (params.decision_made && coordDb) {
367
+ try {
368
+ const agent = coordDb.prepare(
369
+ `SELECT id, current_task FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
370
+ ).get(AGENT_ID) as { id: string; current_task: string | null } | undefined;
371
+ if (agent) {
372
+ coordDb.prepare(
373
+ `INSERT INTO coord_decisions (author_id, assignment_id, tags, summary) VALUES (?, ?, ?, ?)`
374
+ ).run(agent.id, agent.current_task, params.tags ? JSON.stringify(params.tags) : null, params.concept);
375
+ }
376
+ } catch { /* decision propagation is non-fatal */ }
377
+ }
378
+
379
+ const logDisposition = isLowSalience ? 'low-salience' : salience.disposition;
380
+ log(AGENT_ID, `write:${logDisposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
381
+
382
+ return {
383
+ content: [{
384
+ type: 'text' as const,
385
+ text: `Stored (${salience.disposition}) "${params.concept}" [${salience.score.toFixed(2)}]\nID: ${engram.id}`
386
+ + (isLowSalience
387
+ ? `\nNOTE: low salience — this memory is kept but demoted and may fade first. If it MUST survive and be recallable, retry with memory_class: 'canonical'. (Discards are audited: reason codes ${JSON.stringify(salience.reasonCodes.slice(0, 4))})`
388
+ : ''),
389
+ }],
390
+ };
391
+ }
392
+ );
393
+
394
+ server.tool(
395
+ 'memory_recall',
396
+ `Recall memories relevant to a query. Uses cognitive activation — not keyword search.
397
+
398
+ ALWAYS call this when:
399
+ - Starting work on a project or topic (recall what you know)
400
+ - Debugging (recall similar errors and solutions)
401
+ - Making decisions (recall past decisions and outcomes)
402
+ - The user mentions a topic you might have stored memories about
403
+
404
+ Accepts either "query" or "context" parameter — both work identically.
405
+ Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`,
406
+ {
407
+ query: z.string().optional().describe('What to search for — describe the situation, question, or topic'),
408
+ context: z.string().optional().describe('Alias for query (either works)'),
409
+ limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
410
+ min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
411
+ include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
412
+ use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
413
+ use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
414
+ memory_type: z.enum(['episodic', 'semantic', 'procedural']).optional().describe('Filter by memory type (omit to search all types)'),
415
+ workspace: z.string().optional().describe('Search across all agents in this workspace (hive mode). Omit for agent-scoped recall only.'),
416
+ require_confidence: z.number().optional().describe('Opt-in: abstain (return []) when recall confidence is below this threshold. Typical values: 0.10 (strict), 0.25 (balanced), 0.40 (aggressive). Confidence is the shape of the result-score distribution; low confidence indicates a noisy or best-of-bad-bunch recall.'),
417
+ granularity: z.enum(['full', 'compact', 'auto']).optional().describe('Output granularity (Paper 3: cognitive teaming). "full" (default): no change. "compact": every result carries a short summary field. "auto": confidence-adaptive — top result gets a longer summary when there is a clear winner, otherwise everything is compact for scanning.'),
418
+ },
419
+ async (params) => {
420
+ const queryText = params.query ?? params.context;
421
+ if (!queryText) {
422
+ return {
423
+ content: [{
424
+ type: 'text' as const,
425
+ text: 'Error: provide either "query" or "context" parameter with your search text.',
426
+ }],
427
+ };
428
+ }
429
+ // Use workspace from param, env var, or omit for agent-scoped
430
+ const workspace = params.workspace ?? process.env.AWM_WORKSPACE ?? undefined;
431
+ const results = await activationEngine.activate({
432
+ agentId: AGENT_ID,
433
+ context: queryText,
434
+ limit: params.limit,
435
+ minScore: params.min_score,
436
+ includeStaging: params.include_staging,
437
+ useReranker: params.use_reranker,
438
+ useExpansion: params.use_expansion,
439
+ memoryType: params.memory_type,
440
+ workspace,
441
+ requireConfidence: params.require_confidence,
442
+ granularity: params.granularity,
443
+ });
444
+
445
+ // Auto-checkpoint: track recall
446
+ try {
447
+ const ids = results.map(r => r.engram.id);
448
+ await store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
449
+ } catch { /* non-fatal */ }
450
+
451
+ log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" → ${results.length} results`);
452
+
453
+ // Peer decisions: append recent decisions by other agents relevant to this query
454
+ const peerSuffix = coordDb
455
+ ? formatPeerDecisions(queryPeerDecisions(coordDb, AGENT_ID, queryText))
456
+ : '';
457
+
458
+ if (results.length === 0) {
459
+ return {
460
+ content: [{
461
+ type: 'text' as const,
462
+ text: 'No relevant memories found.' + peerSuffix,
463
+ }],
464
+ };
465
+ }
466
+
467
+ // Confidence-adaptive output (Paper 3: cognitive teaming) and D8
468
+ // (2026-07-30) conflict surfacing both live in the shared formatter now —
469
+ // see core/format-recall.ts for why it's extracted (0.12.1: unit-testable
470
+ // without booting the server) and why the id sits after the score.
471
+ const lines = results.map(formatRecallResultLine);
472
+
473
+ return {
474
+ content: [{
475
+ type: 'text' as const,
476
+ text: lines.join('\n') + peerSuffix,
477
+ }],
478
+ };
479
+ }
480
+ );
481
+
482
+ server.tool(
483
+ 'memory_feedback',
484
+ `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
485
+
486
+ Always call this after using a recalled memory so the system learns what's valuable.`,
487
+ {
488
+ engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
489
+ useful: z.boolean().describe('Was this memory actually helpful?'),
490
+ context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
491
+ },
492
+ async (params) => {
493
+ await store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
494
+
495
+ const engram = await store.getEngram(params.engram_id);
496
+ if (engram) {
497
+ const delta = params.useful
498
+ ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
499
+ : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
500
+ await store.updateConfidence(engram.id, engram.confidence + delta);
501
+ }
502
+
503
+ // Validation-gated Hebbian: resolve pending co-activation pairs for this engram
504
+ const hebbianUpdated = await activationEngine.resolveHebbianFeedback(params.engram_id, params.useful);
505
+
506
+ return {
507
+ content: [{
508
+ type: 'text' as const,
509
+ text: `Feedback: ${params.useful ? '+useful' : '-not useful'}${hebbianUpdated > 0 ? ` (${hebbianUpdated} association${hebbianUpdated > 1 ? 's' : ''} ${params.useful ? 'strengthened' : 'weakened'})` : ''}`,
510
+ }],
511
+ };
512
+ }
513
+ );
514
+
515
+ server.tool(
516
+ 'memory_retract',
517
+ `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
518
+
519
+ Use this when you discover a memory contains incorrect information.`,
520
+ {
521
+ engram_id: z.string().describe('ID of the wrong memory'),
522
+ reason: z.string().describe('Why is this memory wrong?'),
523
+ correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
524
+ },
525
+ async (params) => {
526
+ const result = await retractionEngine.retract({
527
+ agentId: AGENT_ID,
528
+ targetEngramId: params.engram_id,
529
+ reason: params.reason,
530
+ counterContent: params.correction,
531
+ });
532
+
533
+ const parts = [`Memory ${params.engram_id} retracted.`];
534
+ if (result.correctionId) {
535
+ parts.push(`Correction stored as ${result.correctionId}.`);
536
+ }
537
+ parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
538
+
539
+ return {
540
+ content: [{
541
+ type: 'text' as const,
542
+ text: parts.join(' '),
543
+ }],
544
+ };
545
+ }
546
+ );
547
+
548
+ server.tool(
549
+ 'memory_supersede',
550
+ `Replace an outdated memory with a newer one. Unlike retraction (which marks memories as wrong), supersession marks the old memory as outdated but historically correct.
551
+
552
+ Use this when:
553
+ - A status or count has changed (e.g., "5 reviews done" → "7 reviews done")
554
+ - Architecture or infrastructure evolved (e.g., "two-repo model" → "three-repo model")
555
+ - A schedule or plan was updated
556
+
557
+ The old memory stays in the database (searchable for history) but is heavily down-ranked in recall so the current version dominates.`,
558
+ {
559
+ old_engram_id: z.string().describe('ID of the outdated memory (from memory_recall results, or memory_write\'s own response if you just wrote it)'),
560
+ new_engram_id: z.string().describe('ID of the replacement memory'),
561
+ reason: z.string().optional().describe('Why the old memory is outdated'),
562
+ },
563
+ async (params) => {
564
+ const oldEngram = await store.getEngram(params.old_engram_id);
565
+ if (!oldEngram) {
566
+ return { content: [{ type: 'text' as const, text: `Old memory not found: ${params.old_engram_id}` }] };
567
+ }
568
+ const newEngram = await store.getEngram(params.new_engram_id);
569
+ if (!newEngram) {
570
+ return { content: [{ type: 'text' as const, text: `New memory not found: ${params.new_engram_id}` }] };
571
+ }
572
+
573
+ await store.supersedeEngram(params.old_engram_id, params.new_engram_id);
574
+
575
+ // Create supersession association (new → old)
576
+ await store.upsertAssociation(params.new_engram_id, params.old_engram_id, 0.8, 'causal', 0.9);
577
+
578
+ // Reduce old memory's confidence (not to zero — it's historical, not wrong)
579
+ await store.updateConfidence(params.old_engram_id, Math.max(0.2, oldEngram.confidence * 0.4));
580
+
581
+ log(AGENT_ID, 'supersede', `"${oldEngram.concept}" → "${newEngram.concept}"${params.reason ? ` (${params.reason})` : ''}`);
582
+
583
+ return {
584
+ content: [{
585
+ type: 'text' as const,
586
+ text: `Superseded: "${oldEngram.concept}" "${newEngram.concept}"`,
587
+ }],
588
+ };
589
+ }
590
+ );
591
+
592
+ server.tool(
593
+ 'memory_whoami',
594
+ `Identify THIS AWM instance — agent id, mode (standalone/hive), backend, store path, code provenance, ports, and the sibling agent spaces present in the same store. Call when unsure which AWM instance or memory space you are talking to.`,
595
+ {},
596
+ async () => {
597
+ const info = await buildWhoami(store, AGENT_ID, 'mcp');
598
+ return { content: [{ type: 'text', text: formatWhoami(info) }] };
599
+ },
600
+ );
601
+
602
+ server.tool(
603
+ 'memory_stats',
604
+ `Get memory health stats — how many memories, confidence levels, association count, and system performance.
605
+ Also shows the activity log path so the user can tail it to see what's happening.`,
606
+ {},
607
+ async () => {
608
+ const metrics = await evalEngine.computeMetrics(AGENT_ID);
609
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
610
+ const lines = [
611
+ `Agent: ${AGENT_ID}`,
612
+ `Active memories: ${metrics.activeEngramCount}`,
613
+ `Staging: ${metrics.stagingEngramCount}`,
614
+ `Retracted: ${metrics.retractedCount}`,
615
+ `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
616
+ `Total edges: ${metrics.totalEdges}`,
617
+ `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
618
+ `Activations (24h): ${metrics.activationCount}`,
619
+ `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
620
+ ``,
621
+ `Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
622
+ `Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
623
+ `Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
624
+ `Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
625
+ ``,
626
+ `Activity log: ${getLogPath() ?? 'not configured'}`,
627
+ `Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
628
+ ];
629
+
630
+ return {
631
+ content: [{
632
+ type: 'text' as const,
633
+ text: lines.join('\n'),
634
+ }],
635
+ };
636
+ }
637
+ );
638
+
639
+ // --- Checkpointing Tools ---
640
+
641
+ server.tool(
642
+ 'memory_checkpoint',
643
+ `Save your current execution state so you can recover after context compaction.
644
+
645
+ ALWAYS call this before:
646
+ - Long operations (multi-file generation, large refactors, overnight work)
647
+ - Anything that might fill the context window
648
+ - Switching to a different task
649
+
650
+ Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`,
651
+ {
652
+ current_task: z.string().describe('What you are currently working on'),
653
+ decisions: z.array(z.string()).optional().default([])
654
+ .describe('Key decisions made so far'),
655
+ active_files: z.array(z.string()).optional().default([])
656
+ .describe('Files you are currently working with'),
657
+ next_steps: z.array(z.string()).optional().default([])
658
+ .describe('What needs to happen next'),
659
+ related_memory_ids: z.array(z.string()).optional().default([])
660
+ .describe('IDs of memories relevant to current work'),
661
+ notes: z.string().optional().default('')
662
+ .describe('Any other context worth preserving'),
663
+ episode_id: z.string().optional()
664
+ .describe('Current episode ID if known'),
665
+ },
666
+ async (params) => {
667
+ const state: ConsciousState = {
668
+ currentTask: params.current_task,
669
+ decisions: params.decisions,
670
+ activeFiles: params.active_files,
671
+ nextSteps: params.next_steps,
672
+ relatedMemoryIds: params.related_memory_ids,
673
+ notes: params.notes,
674
+ episodeId: params.episode_id ?? null,
675
+ };
676
+
677
+ await store.saveCheckpoint(AGENT_ID, state);
678
+ log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
679
+
680
+ return {
681
+ content: [{
682
+ type: 'text' as const,
683
+ text: `Checkpoint saved: "${params.current_task}" (${params.decisions.length} decisions, ${params.active_files.length} files)`,
684
+ }],
685
+ };
686
+ }
687
+ );
688
+
689
+ server.tool(
690
+ 'memory_restore',
691
+ `Restore your previous execution state after context compaction or at session start.
692
+
693
+ Returns:
694
+ - Your saved execution state (task, decisions, next steps, files)
695
+ - Recently recalled memories for context
696
+ - Your last write for continuity
697
+ - How long you were idle
698
+
699
+ Use this at the start of every session or after compaction to pick up where you left off.`,
700
+ {},
701
+ async () => {
702
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
703
+
704
+ // Cold-store nudge: an empty store means the agent has nothing to recall — offer to warm-start.
705
+ let coldStoreNudge = '';
706
+ try {
707
+ const activeCount = (await store.getEngramsByAgent(AGENT_ID)).length;
708
+ if (activeCount < 3) {
709
+ coldStoreNudge = `🌱 **This memory store is nearly empty (${activeCount} ${activeCount === 1 ? 'memory' : 'memories'}).** Warm-start it before other work: recall the "onboard a new project" skill and follow it — or call \`onboard_scan\` on this project's docs/repo, refine the results, and save them with \`memory_write\` (canonical). Recall becomes useful immediately.`;
710
+ }
711
+ } catch { /* count is best-effort */ }
712
+
713
+ const now = Date.now();
714
+ const idleMs = checkpoint
715
+ ? now - checkpoint.auto.lastActivityAt.getTime()
716
+ : 0;
717
+
718
+ // Get last written engram
719
+ let lastWrite: { id: string; concept: string; content: string } | null = null;
720
+ if (checkpoint?.auto.lastWriteId) {
721
+ const engram = await store.getEngram(checkpoint.auto.lastWriteId);
722
+ if (engram) {
723
+ lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
724
+ }
725
+ }
726
+
727
+ // Recall memories using last context
728
+ let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
729
+ const recallContext = checkpoint?.auto.lastRecallContext
730
+ ?? checkpoint?.executionState?.currentTask
731
+ ?? null;
732
+
733
+ if (recallContext) {
734
+ try {
735
+ const results = await activationEngine.activate({
736
+ agentId: AGENT_ID,
737
+ context: recallContext,
738
+ limit: 5,
739
+ minScore: 0.05,
740
+ useReranker: true,
741
+ useExpansion: true,
742
+ workspace: process.env.AWM_WORKSPACE ?? undefined,
743
+ });
744
+ recalledMemories = results.map(r => ({
745
+ id: r.engram.id,
746
+ concept: r.engram.concept,
747
+ content: r.engram.content,
748
+ score: r.score,
749
+ }));
750
+ } catch { /* recall failure is non-fatal */ }
751
+ }
752
+
753
+ // Consolidation on restore:
754
+ // - If idle >5min but last consolidation was recent (graceful exit ran it), skip
755
+ // - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
756
+ const MINI_IDLE_MS = 5 * 60_000;
757
+ const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min — if last consolidation was longer ago, run full
758
+ let miniConsolidationTriggered = false;
759
+ let fullConsolidationTriggered = false;
760
+
761
+ if (idleMs > MINI_IDLE_MS) {
762
+ const sinceLastConsolidation = checkpoint?.lastConsolidationAt
763
+ ? now - checkpoint.lastConsolidationAt.getTime()
764
+ : Infinity;
765
+
766
+ if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
767
+ // No recent consolidation graceful exit didn't happen, run full cycle
768
+ fullConsolidationTriggered = true;
769
+ try {
770
+ const result = await consolidationEngine.consolidate(AGENT_ID);
771
+ await store.markConsolidation(AGENT_ID, false);
772
+ log(AGENT_ID, 'consolidation', `full sleep cycle on restore (no graceful exit, idle ${Math.round(idleMs / 60_000)}min, last consolidation ${Math.round(sinceLastConsolidation / 60_000)}min ago) — ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
773
+ } catch { /* consolidation failure is non-fatal */ }
774
+ } else {
775
+ // Recent consolidation exists — graceful exit already handled it, just do mini
776
+ miniConsolidationTriggered = true;
777
+ consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => {});
778
+ }
779
+ }
780
+
781
+ // Format response
782
+ const parts: string[] = [];
783
+ const idleMin = Math.round(idleMs / 60_000);
784
+ const consolidationNote = fullConsolidationTriggered
785
+ ? ' (full consolidation — no graceful exit detected)'
786
+ : miniConsolidationTriggered
787
+ ? ' (mini-consolidation triggered)'
788
+ : '';
789
+ log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
790
+ parts.push(`Idle: ${idleMin}min${consolidationNote}`);
791
+ if (coldStoreNudge) parts.push(`\n${coldStoreNudge}`);
792
+
793
+ if (checkpoint?.executionState) {
794
+ const s = checkpoint.executionState;
795
+ parts.push(`\n**Current task:** ${s.currentTask}`);
796
+ if (s.decisions.length) parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
797
+ if (s.nextSteps.length) parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
798
+ if (s.activeFiles.length) parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
799
+ if (s.notes) parts.push(`**Notes:** ${s.notes}`);
800
+ if (checkpoint.checkpointAt) parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
801
+ } else {
802
+ parts.push('\nNo explicit checkpoint saved.');
803
+ parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
804
+ }
805
+
806
+ if (lastWrite) {
807
+ parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
808
+ }
809
+
810
+ if (recalledMemories.length > 0) {
811
+ parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
812
+ for (const m of recalledMemories) {
813
+ parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
814
+ }
815
+ }
816
+
817
+ // Peer decisions: show recent decisions from other agents (last 30 min)
818
+ if (coordDb) {
819
+ try {
820
+ const myAgent = coordDb.prepare(
821
+ `SELECT id FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
822
+ ).get(AGENT_ID) as { id: string } | undefined;
823
+
824
+ const peerDecisions = coordDb.prepare(
825
+ `SELECT d.summary, a.name AS author_name, d.created_at
826
+ FROM coord_decisions d JOIN coord_agents a ON d.author_id = a.id
827
+ WHERE d.author_id != ? AND d.created_at > datetime('now', '-30 minutes')
828
+ ORDER BY d.created_at DESC LIMIT 10`
829
+ ).all(myAgent?.id ?? '') as Array<{ summary: string; author_name: string; created_at: string }>;
830
+
831
+ if (peerDecisions.length > 0) {
832
+ parts.push(`\n**Peer decisions (last 30 min):**`);
833
+ for (const d of peerDecisions) {
834
+ parts.push(`- [${d.author_name}] ${d.summary} (${d.created_at})`);
835
+ }
836
+ }
837
+ } catch { /* peer decisions are non-fatal */ }
838
+ }
839
+
840
+ return {
841
+ content: [{
842
+ type: 'text' as const,
843
+ text: parts.join('\n'),
844
+ }],
845
+ };
846
+ }
847
+ );
848
+
849
+ // --- Onboarding Tools (warm-start a cold store) ---
850
+
851
+ server.tool(
852
+ 'onboard_scan',
853
+ `Scan a project's documentation + repository and return CANDIDATE memories to seed a cold store.
854
+
855
+ Use this when the store is empty / you're new to a project. The scan is deterministic
856
+ (real file contents, not guesses) YOUR job is to refine the candidates into atomic,
857
+ recall-shaped memories, run the interview (onboard_questions), confirm with the user, then
858
+ save the good ones with memory_write (memory_class="canonical"). Nothing is saved by this tool.`,
859
+ {
860
+ docs: z.array(z.string()).optional()
861
+ .describe('Doc files/dirs to scan (Markdown/text). Defaults to the repo (or cwd).'),
862
+ repo: z.string().optional()
863
+ .describe('Repo root — also derives stack (package.json) + layout memories.'),
864
+ project: z.string().optional()
865
+ .describe('Project name (becomes a tag). Defaults to the repo/dir name.'),
866
+ purpose: z.string().optional()
867
+ .describe('The goal of this memory system, if known — becomes the anchor memory.'),
868
+ },
869
+ async (params) => {
870
+ const repo = params.repo;
871
+ const docs = params.docs && params.docs.length ? params.docs : [repo ?? process.cwd()];
872
+ const project = params.project ?? basename(resolve(repo ?? docs[0] ?? process.cwd()));
873
+ const pack = buildPack({ docs, repo, project, agentId: AGENT_ID, purpose: params.purpose });
874
+ log(AGENT_ID, 'onboard', `scan ${docs.join(',')}${repo ? ' +repo' : ''} → ${pack.memories.length} candidates`);
875
+ const text = [
876
+ `Scanned ${docs.join(', ')}${repo ? ` (+repo ${repo})` : ''} → ${pack.memories.length} CANDIDATE memories (NOT saved).`,
877
+ `Next: refine each into an atomic memory (lead with the fact + identifiers), run onboard_questions,`,
878
+ `confirm with the user, then save the good ones with memory_write (memory_class="canonical").`,
879
+ ``,
880
+ JSON.stringify({ project, candidates: pack.memories, questions: pack.questions }, null, 2),
881
+ ].join('\n');
882
+ return { content: [{ type: 'text' as const, text }] };
883
+ }
884
+ );
885
+
886
+ server.tool(
887
+ 'onboard_questions',
888
+ `Return the onboarding interview questions. Ask the user ONE at a time, starting with the
889
+ goal of the memory system, and ask follow-ups for clarity. Turn each answer into a canonical memory.`,
890
+ {},
891
+ async () => ({
892
+ content: [{ type: 'text' as const, text: INTERVIEW_QUESTIONS.map((q, i) => `${i + 1}. ${q}`).join('\n') }],
893
+ })
894
+ );
895
+
896
+ // --- Task Management Tools ---
897
+
898
+ server.tool(
899
+ 'memory_task_add',
900
+ `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
901
+
902
+ Use this when:
903
+ - You identify work that needs doing but can't do it right now
904
+ - The user mentions something to do later
905
+ - You want to park a sub-task while focusing on something more urgent
906
+
907
+ Tasks automatically get high salience so they won't be discarded.`,
908
+ {
909
+ concept: z.string().describe('Short task title (3-10 words)'),
910
+ content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
911
+ tags: z.array(z.string()).optional().describe('Tags for categorization'),
912
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
913
+ .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
914
+ blocked_by: z.string().optional().describe('ID of a task that must finish first'),
915
+ },
916
+ async (params) => {
917
+ const engram = await store.createEngram({
918
+ agentId: AGENT_ID,
919
+ concept: params.concept,
920
+ content: params.content,
921
+ tags: [...(params.tags ?? []), 'task'],
922
+ salience: 0.9, // Tasks always high salience
923
+ confidence: 0.8,
924
+ salienceFeatures: {
925
+ surprise: 0.5,
926
+ decisionMade: true,
927
+ causalDepth: 0.5,
928
+ resolutionEffort: 0.5,
929
+ eventType: 'decision',
930
+ },
931
+ reasonCodes: ['task-created'],
932
+ taskStatus: params.blocked_by ? 'blocked' : 'open',
933
+ taskPriority: params.priority as TaskPriority,
934
+ blockedBy: params.blocked_by,
935
+ });
936
+
937
+ connectionEngine.enqueue(engram.id);
938
+
939
+ // Generate embedding asynchronously
940
+ embed(`${params.concept} ${params.content}`).then(async vec => {
941
+ await store.updateEmbedding(engram.id, vec);
942
+ }).catch(() => {});
943
+
944
+ return {
945
+ content: [{
946
+ type: 'text' as const,
947
+ text: `Task created: "${params.concept}" (${params.priority})`,
948
+ }],
949
+ };
950
+ }
951
+ );
952
+
953
+ server.tool(
954
+ 'memory_task_update',
955
+ `Update a task's status or priority. Use this to:
956
+ - Start working on a task (open → in_progress)
957
+ - Mark a task done (→ done)
958
+ - Block a task on another ( blocked)
959
+ - Reprioritize (change priority)
960
+ - Unblock a task (clear blocked_by)`,
961
+ {
962
+ task_id: z.string().describe('ID of the task to update'),
963
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
964
+ .describe('New status'),
965
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
966
+ .describe('New priority'),
967
+ blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
968
+ },
969
+ async (params) => {
970
+ const engram = await store.getEngram(params.task_id);
971
+ if (!engram || !engram.taskStatus) {
972
+ return { content: [{ type: 'text' as const, text: `Task not found: ${params.task_id}` }] };
973
+ }
974
+
975
+ if (params.blocked_by !== undefined) {
976
+ await store.updateBlockedBy(params.task_id, params.blocked_by || null);
977
+ }
978
+ if (params.status) {
979
+ await store.updateTaskStatus(params.task_id, params.status as TaskStatus);
980
+ }
981
+ if (params.priority) {
982
+ await store.updateTaskPriority(params.task_id, params.priority as TaskPriority);
983
+ }
984
+
985
+ const updated = (await store.getEngram(params.task_id))!;
986
+ return {
987
+ content: [{
988
+ type: 'text' as const,
989
+ text: `Updated: "${updated.concept}" → ${updated.taskStatus} (${updated.taskPriority})`,
990
+ }],
991
+ };
992
+ }
993
+ );
994
+
995
+ server.tool(
996
+ 'memory_task_list',
997
+ `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
998
+
999
+ Use at the start of a session to see what's pending, or to check blocked/done tasks.`,
1000
+ {
1001
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
1002
+ .describe('Filter by status (omit to see all active tasks)'),
1003
+ include_done: z.boolean().optional().default(false)
1004
+ .describe('Include completed tasks?'),
1005
+ },
1006
+ async (params) => {
1007
+ let tasks = await store.getTasks(AGENT_ID, params.status as TaskStatus | undefined);
1008
+ if (!params.include_done && !params.status) {
1009
+ tasks = tasks.filter(t => t.taskStatus !== 'done');
1010
+ }
1011
+
1012
+ if (tasks.length === 0) {
1013
+ return { content: [{ type: 'text' as const, text: 'No tasks found.' }] };
1014
+ }
1015
+
1016
+ const lines = tasks.map((t, i) => {
1017
+ const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
1018
+ const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
1019
+ return `${i + 1}. [${t.taskStatus}] **${t.concept}** (${t.taskPriority})${blocked}\n ${t.content.slice(0, 120)}${t.content.length > 120 ? '...' : ''}\n ${tags ? `Tags: ${tags} | ` : ''}ID: ${t.id}`;
1020
+ });
1021
+
1022
+ return {
1023
+ content: [{
1024
+ type: 'text' as const,
1025
+ text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
1026
+ }],
1027
+ };
1028
+ }
1029
+ );
1030
+
1031
+ server.tool(
1032
+ 'memory_task_next',
1033
+ `Get the single most important task to work on next.
1034
+
1035
+ Prioritizes: in_progress tasks first (finish what you started), then by priority level, then oldest first. Skips blocked and done tasks.
1036
+
1037
+ Use this when you finish a task or need to decide what to do next.`,
1038
+ {},
1039
+ async () => {
1040
+ const next = await store.getNextTask(AGENT_ID);
1041
+ if (!next) {
1042
+ return { content: [{ type: 'text' as const, text: 'No actionable tasks. All clear!' }] };
1043
+ }
1044
+
1045
+ const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
1046
+ const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
1047
+
1048
+ return {
1049
+ content: [{
1050
+ type: 'text' as const,
1051
+ text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
1052
+ }],
1053
+ };
1054
+ }
1055
+ );
1056
+
1057
+ // --- Task Bracket Tools ---
1058
+
1059
+ server.tool(
1060
+ 'memory_task_begin',
1061
+ `Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
1062
+
1063
+ CALL THIS when starting:
1064
+ - A multi-step operation (doc generation, large refactor, migration)
1065
+ - Work on a new topic or project area
1066
+ - Anything that might fill the context window
1067
+
1068
+ This ensures your state is saved before you start, and primes recall with relevant context.`,
1069
+ {
1070
+ topic: z.string().describe('What task are you starting? (3-15 words)'),
1071
+ files: z.array(z.string()).optional().default([])
1072
+ .describe('Files you expect to work with'),
1073
+ notes: z.string().optional().default('')
1074
+ .describe('Any additional context'),
1075
+ },
1076
+ async (params) => {
1077
+ // 1. Checkpoint current state
1078
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
1079
+ const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
1080
+
1081
+ await store.saveCheckpoint(AGENT_ID, {
1082
+ currentTask: params.topic,
1083
+ decisions: [],
1084
+ activeFiles: params.files,
1085
+ nextSteps: [],
1086
+ relatedMemoryIds: [],
1087
+ notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
1088
+ episodeId: null,
1089
+ });
1090
+
1091
+ // 2. Auto-recall relevant memories
1092
+ let recalledSummary = '';
1093
+ try {
1094
+ const results = await activationEngine.activate({
1095
+ agentId: AGENT_ID,
1096
+ context: params.topic,
1097
+ limit: 5,
1098
+ minScore: 0.05,
1099
+ useReranker: true,
1100
+ useExpansion: true,
1101
+ workspace: process.env.AWM_WORKSPACE ?? undefined,
1102
+ });
1103
+
1104
+ if (results.length > 0) {
1105
+ const lines = results.map((r, i) => {
1106
+ const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
1107
+ return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
1108
+ });
1109
+ recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
1110
+
1111
+ // Track recall
1112
+ await store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
1113
+ }
1114
+ } catch { /* recall failure is non-fatal */ }
1115
+
1116
+ log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
1117
+
1118
+ return {
1119
+ content: [{
1120
+ type: 'text' as const,
1121
+ text: `Started: "${params.topic}" (prev: ${prevTask})${recalledSummary}`,
1122
+ }],
1123
+ };
1124
+ }
1125
+ );
1126
+
1127
+ server.tool(
1128
+ 'memory_task_end',
1129
+ `Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
1130
+
1131
+ CALL THIS when you finish:
1132
+ - A multi-step operation
1133
+ - Before switching to a different topic
1134
+ - At the end of a work session
1135
+
1136
+ This captures what was accomplished so future sessions can recall it.`,
1137
+ {
1138
+ summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
1139
+ tags: z.array(z.string()).optional().default([])
1140
+ .describe('Tags for the summary memory'),
1141
+ supersedes: z.array(z.string()).optional().default([])
1142
+ .describe('IDs of older memories this task summary replaces (marks them as superseded)'),
1143
+ },
1144
+ async (params) => {
1145
+ // 1. Write summary as a memory
1146
+ const salience = evaluateSalience({
1147
+ content: params.summary,
1148
+ eventType: 'decision',
1149
+ surprise: 0.3,
1150
+ decisionMade: true,
1151
+ causalDepth: 0.5,
1152
+ resolutionEffort: 0.5,
1153
+ });
1154
+
1155
+ // Determine the real task name for the summary engram
1156
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
1157
+ const rawTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
1158
+ // Strip any "Completed: " prefixes to avoid cascading
1159
+ const cleanedTask = rawTask.replace(/^(Completed: )+/, '');
1160
+ // Don't use auto-checkpoint or already-completed tasks as real task names
1161
+ const isNamedTask = !cleanedTask.startsWith('Auto-checkpoint') && cleanedTask !== 'Unknown task';
1162
+ const completedTask = isNamedTask
1163
+ ? cleanedTask
1164
+ : params.summary.slice(0, 60).replace(/\n/g, ' ');
1165
+
1166
+ const engram = await store.createEngram({
1167
+ agentId: AGENT_ID,
1168
+ concept: completedTask.slice(0, 80),
1169
+ content: params.summary,
1170
+ tags: [...params.tags, 'task-summary'],
1171
+ salience: isNamedTask ? Math.max(salience.score, 0.7) : salience.score, // Only floor salience for named tasks
1172
+ confidence: 0.65, // Task summaries are decision-grade (completed work)
1173
+ salienceFeatures: salience.features,
1174
+ reasonCodes: [...salience.reasonCodes, 'task-end'],
1175
+ });
1176
+
1177
+ connectionEngine.enqueue(engram.id);
1178
+
1179
+ // 2. Handle supersessionsmark old memories as outdated
1180
+ let supersededCount = 0;
1181
+ for (const oldId of params.supersedes) {
1182
+ const oldEngram = await store.getEngram(oldId);
1183
+ if (oldEngram) {
1184
+ await store.supersedeEngram(oldId, engram.id);
1185
+ await store.upsertAssociation(engram.id, oldId, 0.8, 'causal', 0.9);
1186
+ await store.updateConfidence(oldId, Math.max(0.2, oldEngram.confidence * 0.4));
1187
+ supersededCount++;
1188
+ }
1189
+ }
1190
+
1191
+ // Generate embedding asynchronously
1192
+ embed(`Task completed: ${params.summary}`).then(async vec => {
1193
+ await store.updateEmbedding(engram.id, vec);
1194
+ }).catch(() => {});
1195
+
1196
+ // 2. Update checkpoint to reflect completion
1197
+ await store.saveCheckpoint(AGENT_ID, {
1198
+ currentTask: `Completed: ${completedTask}`,
1199
+ decisions: checkpoint?.executionState?.decisions ?? [],
1200
+ activeFiles: [],
1201
+ nextSteps: [],
1202
+ relatedMemoryIds: [engram.id],
1203
+ notes: `Task completed. Summary memory: ${engram.id}`,
1204
+ episodeId: null,
1205
+ });
1206
+
1207
+ await store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
1208
+ log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)} superseded=${supersededCount}`);
1209
+
1210
+ const supersededNote = supersededCount > 0 ? ` (${supersededCount} old memories superseded)` : '';
1211
+ return {
1212
+ content: [{
1213
+ type: 'text' as const,
1214
+ // D14 (2026-07-30): task end is the recipe moment — invite the host
1215
+ // to distill a skill and/or a failure lesson in separate focused
1216
+ // passes. The host owns the gates; AWM validates the write-backs.
1217
+ text: `Completed: "${completedTask}" [${salience.score.toFixed(2)}]${supersededNote}\n${renderTaskEndInvitation()}`,
1218
+ }],
1219
+ };
1220
+ }
1221
+ );
1222
+
1223
+ server.tool(
1224
+ 'compress_output',
1225
+ `Compress a STRUCTURED tool output (JSON object/array, query rows, log records) into TOON —
1226
+ a compact, schema-aware tabular encoding — before putting it in your context. Cuts ~50-65%
1227
+ of the tokens on uniform arrays at zero comprehension cost (validated: models read TOON as
1228
+ accurately as JSON). Use this on large tool results you need to keep in context.
1229
+
1230
+ Output-only and safe: it never changes the data. Non-JSON / prose is returned unchanged.
1231
+ TOON is only emitted when it reproduces the input exactly (self-verified round-trip);
1232
+ otherwise you get plain JSON back. When compressed, you also get a 'ref' — call
1233
+ retrieve_original(ref) to get the verbatim source back if you ever need it.`,
1234
+ {
1235
+ output: z.string().describe('The tool output to compress — JSON text (preferred) or any string. Non-JSON is returned unchanged.'),
1236
+ min_saving_chars: z.number().optional().describe('Only emit TOON if it saves at least this many characters (default 40).'),
1237
+ },
1238
+ async (params) => {
1239
+ const r = liteCompress(params.output, { minSavingChars: params.min_saving_chars });
1240
+ log(AGENT_ID, 'compress', `${r.format} ${r.charsBefore}->${r.charsAfter} chars (${(r.ratio * 100).toFixed(0)}%)${r.ref ? ` ref=${r.ref}` : ''}`);
1241
+ const header = r.format === 'toon'
1242
+ ? `[TOON, ${(r.ratio * 100).toFixed(0)}% smaller compact lossless JSON; read as data, ref=${r.ref}]\n`
1243
+ : '';
1244
+ return {
1245
+ content: [{ type: 'text' as const, text: header + r.text }],
1246
+ };
1247
+ }
1248
+ );
1249
+
1250
+ server.tool(
1251
+ 'retrieve_original',
1252
+ `Retrieve the verbatim original text for a 'ref' returned by compress_output. Use this when
1253
+ you need the exact, uncompressed source (e.g. to pass it to another tool unchanged). Returns
1254
+ an error if the ref has expired (originals are kept for the most recent compressions only).`,
1255
+ {
1256
+ ref: z.string().describe('The ref handle returned by compress_output (e.g. "awm_orig_12").'),
1257
+ },
1258
+ async (params) => {
1259
+ const original = retrieveOriginal(params.ref);
1260
+ if (original === undefined) {
1261
+ return {
1262
+ content: [{ type: 'text' as const, text: `Error: ref "${params.ref}" not found or expired.` }],
1263
+ };
1264
+ }
1265
+ return {
1266
+ content: [{ type: 'text' as const, text: original }],
1267
+ };
1268
+ }
1269
+ );
1270
+
1271
+ // --- Start ---
1272
+
1273
+ async function main() {
1274
+ const transport = new StdioServerTransport();
1275
+ await server.connect(transport);
1276
+
1277
+ // Start hook sidecar (lightweight HTTP for Claude Code hooks)
1278
+ const sidecar = startSidecar({
1279
+ store,
1280
+ agentId: AGENT_ID,
1281
+ secret: HOOK_SECRET,
1282
+ port: HOOK_PORT,
1283
+ // 0.12.2: warm recall for hooks — the sidecar shares this process's
1284
+ // activation engine and loaded models, so a UserPromptSubmit hook can get
1285
+ // warm-latency recall without any standing server. Trimmed result shape
1286
+ // (no embeddings/phase scores — hooks don't need them and the vectors
1287
+ // alone would 10x the payload).
1288
+ activate: async (q) => {
1289
+ const results = await activationEngine.activate({
1290
+ agentId: AGENT_ID,
1291
+ context: q.context,
1292
+ limit: q.limit,
1293
+ requireConfidence: q.requireConfidence,
1294
+ granularity: q.granularity,
1295
+ });
1296
+ return results.map(r => ({
1297
+ engram: {
1298
+ id: r.engram.id,
1299
+ concept: r.engram.concept,
1300
+ content: r.engram.content,
1301
+ createdAt: r.engram.createdAt instanceof Date
1302
+ ? r.engram.createdAt.toISOString()
1303
+ : (r.engram.createdAt as unknown as string | undefined),
1304
+ memoryClass: r.engram.memoryClass,
1305
+ validTo: r.engram.validTo,
1306
+ },
1307
+ score: r.score,
1308
+ summary: r.summary,
1309
+ confidence: r.confidence,
1310
+ }));
1311
+ },
1312
+ onConsolidate: async (agentId, reason) => {
1313
+ console.error(`[mcp] consolidation triggered: ${reason}`);
1314
+ const result = await consolidationEngine.consolidate(agentId);
1315
+ await store.markConsolidation(agentId, false);
1316
+ console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
1317
+ },
1318
+ });
1319
+
1320
+ // 0.12.2: eager warm — fire-and-forget, mirrors index.ts:208-218. Without
1321
+ // this, every Claude Code session paid the full cold cost (~3s measured on
1322
+ // a 29.7k-engram store: slim cache ~0.9s + three model loads ~1.8s) on its
1323
+ // FIRST recall, which is exactly the "first recall is slow → recall gets
1324
+ // avoided" failure mode. Warming here overlaps session startup instead.
1325
+ // All output is stderr-safe (stdout carries JSON-RPC frames).
1326
+ // Escape hatch: AWM_NO_EAGER_WARM=1 restores lazy loading.
1327
+ if (process.env.AWM_NO_EAGER_WARM !== '1') {
1328
+ getEmbedder().catch(err => console.error('Embedding model unavailable:', err.message));
1329
+ getReranker().catch(err => console.error('Reranker model unavailable:', err.message));
1330
+ getExpander().catch(err => console.error('Query expander model unavailable:', err.message));
1331
+ if (BACKEND === 'sqlite') {
1332
+ setImmediate(() => {
1333
+ try {
1334
+ const t0 = Date.now();
1335
+ (store as unknown as EngramStore).warmSlimCache();
1336
+ const stats = (store as unknown as EngramStore).getSlimCacheStats();
1337
+ console.error(`Slim cache warmed: ${stats.size} entries in ${Date.now() - t0}ms`);
1338
+ } catch (err) {
1339
+ console.error(`Slim cache warm failed: ${(err as Error).message}`);
1340
+ }
1341
+ });
1342
+ }
1343
+ }
1344
+
1345
+ // Coordination MCP tools (opt-in via AWM_COORDINATION=true)
1346
+ // AWM 0.8.x: coordination requires SQLite (uses store.getDb()). On PGlite,
1347
+ // coordination is auto-disabled with a warning; re-enable when coordination
1348
+ // is ported to async/PGlite.
1349
+ const coordRequested = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
1350
+ const coordEnabled = coordRequested && BACKEND === 'sqlite';
1351
+ if (coordEnabled) {
1352
+ const { initCoordinationTables } = await import('./coordination/schema.js');
1353
+ const { registerCoordinationTools } = await import('./coordination/mcp-tools.js');
1354
+ const sqliteStore = store as unknown as EngramStore;
1355
+ initCoordinationTables(sqliteStore.getDb());
1356
+ registerCoordinationTools(server, sqliteStore.getDb());
1357
+ coordDb = sqliteStore.getDb();
1358
+ } else if (coordRequested && BACKEND === 'pglite') {
1359
+ console.error('AWM: coordination requested but disabled — coordination plugin requires SQLite backend');
1360
+ } else {
1361
+ console.error('AWM: coordination tools disabled (set AWM_COORDINATION=true to enable)');
1362
+ }
1363
+
1364
+ // Log to stderr (stdout is reserved for MCP protocol)
1365
+ console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
1366
+ console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
1367
+
1368
+ // Clean shutdown
1369
+ const cleanup = async () => {
1370
+ sidecar.close();
1371
+ consolidationScheduler.stop();
1372
+ stagingBuffer.stop();
1373
+ if (BACKEND === 'sqlite') {
1374
+ try { (store as Partial<EngramStore>).walCheckpoint?.(); } catch { /* non-fatal */ }
1375
+ }
1376
+ try { await (store as any).close?.(); } catch { /* best-effort */ }
1377
+ };
1378
+ process.on('SIGINT', () => { void cleanup().finally(() => process.exit(0)); });
1379
+ process.on('SIGTERM', () => { void cleanup().finally(() => process.exit(0)); });
1380
+ }
1381
+
1382
+ main().catch(err => {
1383
+ console.error('MCP server failed:', err);
1384
+ process.exit(1);
1385
+ });
1386
+
1387
+ } // end else (non-incognito)