agent-working-memory 0.13.0 → 0.14.0

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