agent-working-memory 0.7.17 → 0.8.6

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 (188) hide show
  1. package/README.md +156 -15
  2. package/dist/adapters/common.d.ts.map +1 -1
  3. package/dist/adapters/common.js +289 -202
  4. package/dist/adapters/common.js.map +1 -1
  5. package/dist/adapters/http.js +22 -22
  6. package/dist/api/routes.d.ts +1 -1
  7. package/dist/api/routes.d.ts.map +1 -1
  8. package/dist/api/routes.js +258 -79
  9. package/dist/api/routes.js.map +1 -1
  10. package/dist/cli/migrate.d.ts +42 -0
  11. package/dist/cli/migrate.d.ts.map +1 -0
  12. package/dist/cli/migrate.js +268 -0
  13. package/dist/cli/migrate.js.map +1 -0
  14. package/dist/cli.js +147 -103
  15. package/dist/cli.js.map +1 -1
  16. package/dist/coordination/circuit-breaker.d.ts +24 -0
  17. package/dist/coordination/circuit-breaker.d.ts.map +1 -0
  18. package/dist/coordination/circuit-breaker.js +70 -0
  19. package/dist/coordination/circuit-breaker.js.map +1 -0
  20. package/dist/coordination/failure-modes.d.ts +21 -0
  21. package/dist/coordination/failure-modes.d.ts.map +1 -0
  22. package/dist/coordination/failure-modes.js +49 -0
  23. package/dist/coordination/failure-modes.js.map +1 -0
  24. package/dist/coordination/peer-decisions.js +7 -7
  25. package/dist/coordination/routes.d.ts.map +1 -1
  26. package/dist/coordination/routes.js +44 -1
  27. package/dist/coordination/routes.js.map +1 -1
  28. package/dist/coordination/schema.d.ts.map +1 -1
  29. package/dist/coordination/schema.js +18 -0
  30. package/dist/coordination/schema.js.map +1 -1
  31. package/dist/coordination/schemas.d.ts +9 -9
  32. package/dist/coordination/stale.d.ts +9 -1
  33. package/dist/coordination/stale.d.ts.map +1 -1
  34. package/dist/coordination/stale.js +53 -9
  35. package/dist/coordination/stale.js.map +1 -1
  36. package/dist/core/embeddings.d.ts +16 -10
  37. package/dist/core/embeddings.d.ts.map +1 -1
  38. package/dist/core/embeddings.js +54 -38
  39. package/dist/core/embeddings.js.map +1 -1
  40. package/dist/core/ml-worker-entry.d.ts +17 -0
  41. package/dist/core/ml-worker-entry.d.ts.map +1 -0
  42. package/dist/core/ml-worker-entry.js +193 -0
  43. package/dist/core/ml-worker-entry.js.map +1 -0
  44. package/dist/core/ml-worker.d.ts +59 -0
  45. package/dist/core/ml-worker.d.ts.map +1 -0
  46. package/dist/core/ml-worker.js +253 -0
  47. package/dist/core/ml-worker.js.map +1 -0
  48. package/dist/core/query-expander.d.ts +13 -15
  49. package/dist/core/query-expander.d.ts.map +1 -1
  50. package/dist/core/query-expander.js +48 -54
  51. package/dist/core/query-expander.js.map +1 -1
  52. package/dist/core/reranker.d.ts +9 -19
  53. package/dist/core/reranker.d.ts.map +1 -1
  54. package/dist/core/reranker.js +33 -35
  55. package/dist/core/reranker.js.map +1 -1
  56. package/dist/core/salience.d.ts +32 -5
  57. package/dist/core/salience.d.ts.map +1 -1
  58. package/dist/core/salience.js +201 -28
  59. package/dist/core/salience.js.map +1 -1
  60. package/dist/core/write-pipeline.d.ts +10 -2
  61. package/dist/core/write-pipeline.d.ts.map +1 -1
  62. package/dist/core/write-pipeline.js +218 -49
  63. package/dist/core/write-pipeline.js.map +1 -1
  64. package/dist/engine/activation.d.ts +2 -2
  65. package/dist/engine/activation.d.ts.map +1 -1
  66. package/dist/engine/activation.js +238 -115
  67. package/dist/engine/activation.js.map +1 -1
  68. package/dist/engine/confidence.d.ts +62 -0
  69. package/dist/engine/confidence.d.ts.map +1 -0
  70. package/dist/engine/confidence.js +100 -0
  71. package/dist/engine/confidence.js.map +1 -0
  72. package/dist/engine/connections.d.ts +47 -8
  73. package/dist/engine/connections.d.ts.map +1 -1
  74. package/dist/engine/connections.js +83 -22
  75. package/dist/engine/connections.js.map +1 -1
  76. package/dist/engine/consolidation-scheduler.d.ts +46 -10
  77. package/dist/engine/consolidation-scheduler.d.ts.map +1 -1
  78. package/dist/engine/consolidation-scheduler.js +170 -50
  79. package/dist/engine/consolidation-scheduler.js.map +1 -1
  80. package/dist/engine/consolidation.d.ts +16 -2
  81. package/dist/engine/consolidation.d.ts.map +1 -1
  82. package/dist/engine/consolidation.js +143 -44
  83. package/dist/engine/consolidation.js.map +1 -1
  84. package/dist/engine/eval.d.ts +2 -2
  85. package/dist/engine/eval.d.ts.map +1 -1
  86. package/dist/engine/eval.js +9 -9
  87. package/dist/engine/eval.js.map +1 -1
  88. package/dist/engine/eviction.d.ts +4 -4
  89. package/dist/engine/eviction.d.ts.map +1 -1
  90. package/dist/engine/eviction.js +15 -15
  91. package/dist/engine/eviction.js.map +1 -1
  92. package/dist/engine/retraction.d.ts +93 -5
  93. package/dist/engine/retraction.d.ts.map +1 -1
  94. package/dist/engine/retraction.js +238 -19
  95. package/dist/engine/retraction.js.map +1 -1
  96. package/dist/engine/staging.d.ts +1 -1
  97. package/dist/engine/staging.d.ts.map +1 -1
  98. package/dist/engine/staging.js +3 -3
  99. package/dist/engine/staging.js.map +1 -1
  100. package/dist/hooks/sidecar.d.ts +1 -1
  101. package/dist/hooks/sidecar.d.ts.map +1 -1
  102. package/dist/hooks/sidecar.js +4 -4
  103. package/dist/hooks/sidecar.js.map +1 -1
  104. package/dist/index.js +48 -31
  105. package/dist/index.js.map +1 -1
  106. package/dist/mcp.js +167 -141
  107. package/dist/mcp.js.map +1 -1
  108. package/dist/storage/factory.d.ts +55 -0
  109. package/dist/storage/factory.d.ts.map +1 -0
  110. package/dist/storage/factory.js +135 -0
  111. package/dist/storage/factory.js.map +1 -0
  112. package/dist/storage/pglite-schema.d.ts +20 -0
  113. package/dist/storage/pglite-schema.d.ts.map +1 -0
  114. package/dist/storage/pglite-schema.js +165 -0
  115. package/dist/storage/pglite-schema.js.map +1 -0
  116. package/dist/storage/pglite.d.ts +187 -0
  117. package/dist/storage/pglite.d.ts.map +1 -0
  118. package/dist/storage/pglite.js +1114 -0
  119. package/dist/storage/pglite.js.map +1 -0
  120. package/dist/storage/sqlite.d.ts +117 -0
  121. package/dist/storage/sqlite.d.ts.map +1 -1
  122. package/dist/storage/sqlite.js +357 -8
  123. package/dist/storage/sqlite.js.map +1 -1
  124. package/dist/storage/store.d.ts +63 -0
  125. package/dist/storage/store.d.ts.map +1 -0
  126. package/dist/storage/store.js +27 -0
  127. package/dist/storage/store.js.map +1 -0
  128. package/dist/types/engram.d.ts +92 -2
  129. package/dist/types/engram.d.ts.map +1 -1
  130. package/dist/types/engram.js.map +1 -1
  131. package/package.json +3 -1
  132. package/src/adapters/claude-code.ts +218 -218
  133. package/src/adapters/codex.ts +252 -252
  134. package/src/adapters/common.ts +498 -411
  135. package/src/adapters/cursor.ts +135 -135
  136. package/src/adapters/http.ts +93 -93
  137. package/src/adapters/index.ts +31 -31
  138. package/src/adapters/types.ts +75 -75
  139. package/src/api/index.ts +3 -3
  140. package/src/api/routes.ts +970 -714
  141. package/src/cli/migrate.ts +307 -0
  142. package/src/cli.ts +755 -719
  143. package/src/coordination/circuit-breaker.ts +83 -0
  144. package/src/coordination/events.ts +90 -90
  145. package/src/coordination/failure-modes.ts +50 -0
  146. package/src/coordination/peer-decisions.ts +105 -105
  147. package/src/coordination/plugin-loader.ts +60 -60
  148. package/src/coordination/plugin.ts +44 -44
  149. package/src/coordination/routes.ts +56 -1
  150. package/src/coordination/schema.ts +13 -0
  151. package/src/coordination/stale.ts +80 -11
  152. package/src/coordination/types.ts +311 -311
  153. package/src/coordination/write-mutex.ts +69 -69
  154. package/src/core/auto-tagger.ts +168 -168
  155. package/src/core/decay.ts +63 -63
  156. package/src/core/embeddings.ts +110 -93
  157. package/src/core/index.ts +5 -5
  158. package/src/core/logger.ts +36 -36
  159. package/src/core/ml-worker-entry.ts +194 -0
  160. package/src/core/ml-worker.ts +281 -0
  161. package/src/core/query-expander.ts +122 -128
  162. package/src/core/reranker.ts +119 -125
  163. package/src/core/salience.ts +200 -33
  164. package/src/core/write-pipeline.ts +521 -343
  165. package/src/engine/activation.ts +235 -109
  166. package/src/engine/confidence.ts +120 -0
  167. package/src/engine/connections.ts +162 -103
  168. package/src/engine/consolidation-scheduler.ts +242 -125
  169. package/src/engine/consolidation.ts +138 -45
  170. package/src/engine/eval.ts +102 -102
  171. package/src/engine/eviction.ts +101 -101
  172. package/src/engine/index.ts +8 -8
  173. package/src/engine/retraction.ts +366 -116
  174. package/src/engine/staging.ts +74 -74
  175. package/src/hooks/sidecar.ts +5 -5
  176. package/src/index.ts +226 -212
  177. package/src/mcp.ts +1145 -1121
  178. package/src/storage/factory.ts +147 -0
  179. package/src/storage/index.ts +3 -3
  180. package/src/storage/pglite-schema.ts +166 -0
  181. package/src/storage/pglite.ts +1363 -0
  182. package/src/storage/sqlite.ts +402 -7
  183. package/src/storage/store.ts +80 -0
  184. package/src/types/agent.ts +67 -67
  185. package/src/types/checkpoint.ts +46 -46
  186. package/src/types/engram.ts +101 -3
  187. package/src/types/eval.ts +100 -100
  188. package/src/types/index.ts +6 -6
package/src/mcp.ts CHANGED
@@ -1,1121 +1,1145 @@
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 (12):
10
- * memory_write — store a memory (salience filter decides disposition)
11
- * memory_recall — activate memories by context (cognitive retrieval)
12
- * memory_feedback — report whether a recalled memory was useful
13
- * memory_retract — invalidate a wrong memory with optional correction
14
- * memory_supersede — replace an outdated memory with a current one
15
- * memory_stats — get memory health metrics
16
- * memory_checkpoint — save structured execution state (survives compaction)
17
- * memory_restore — restore state + targeted recall after compaction
18
- * memory_task_add — create a prioritized task
19
- * memory_task_update — change task status, priority, or blocking
20
- * memory_task_list — list tasks filtered by status
21
- * memory_task_next — get the highest-priority actionable task
22
- *
23
- * Run: npx tsx src/mcp.ts
24
- * Config: add to ~/.claude.json or .mcp.json
25
- */
26
-
27
- import { readFileSync } from 'node:fs';
28
- import { resolve } from 'node:path';
29
- import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
30
-
31
- // Load .env file if present (no external dependency)
32
- try {
33
- const envPath = resolve(process.cwd(), '.env');
34
- const envContent = readFileSync(envPath, 'utf-8');
35
- for (const line of envContent.split('\n')) {
36
- const trimmed = line.trim();
37
- if (!trimmed || trimmed.startsWith('#')) continue;
38
- const eqIdx = trimmed.indexOf('=');
39
- if (eqIdx === -1) continue;
40
- const key = trimmed.slice(0, eqIdx).trim();
41
- const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, '');
42
- if (!process.env[key]) process.env[key] = val;
43
- }
44
- } catch { /* No .env file */ }
45
-
46
- // MCP uses stdout for JSON-RPC. Redirect console.log to stderr so engine
47
- // startup messages (ConsolidationScheduler, model loading, etc.) don't
48
- // corrupt the transport. This MUST happen before any engine imports.
49
- console.log = console.error;
50
-
51
- import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
52
- import { z } from 'zod';
53
-
54
- import { EngramStore } from './storage/sqlite.js';
55
- import { ActivationEngine } from './engine/activation.js';
56
- import { ConnectionEngine } from './engine/connections.js';
57
- import { StagingBuffer } from './engine/staging.js';
58
- import { EvictionEngine } from './engine/eviction.js';
59
- import { RetractionEngine } from './engine/retraction.js';
60
- import { EvalEngine } from './engine/eval.js';
61
- import { ConsolidationEngine } from './engine/consolidation.js';
62
- import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
63
- import { evaluateSalience, computeNovelty, computeNoveltyWithMatch } from './core/salience.js';
64
- import { performWrite } from './core/write-pipeline.js';
65
- import type { ConsciousState } from './types/checkpoint.js';
66
- import type { SalienceEventType } from './core/salience.js';
67
- import type { TaskStatus, TaskPriority } from './types/engram.js';
68
- import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
69
- import { embed } from './core/embeddings.js';
70
- import { startSidecar } from './hooks/sidecar.js';
71
- import { initLogger, log, getLogPath } from './core/logger.js';
72
- import { queryPeerDecisions, formatPeerDecisions } from './coordination/peer-decisions.js';
73
-
74
- // --- Incognito Mode ---
75
- // When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
76
- // No DB, no engines, no sidecar — just a bare MCP server that exposes nothing.
77
-
78
- const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
79
-
80
- if (INCOGNITO) {
81
- console.error('AWM: incognito mode — all memory tools disabled, nothing will be recorded');
82
- const server = new McpServer({ name: 'agent-working-memory', version: '0.7.17' });
83
- const transport = new StdioServerTransport();
84
- server.connect(transport).catch(err => {
85
- console.error('MCP server failed:', err);
86
- process.exit(1);
87
- });
88
- // No tools registered — Claude won't see any memory_* tools
89
- } else {
90
-
91
- // --- Setup ---
92
-
93
- const DB_PATH = process.env.AWM_DB_PATH ?? 'memory.db';
94
- const AGENT_ID = process.env.AWM_AGENT_ID ?? process.env.WORKER_NAME ?? 'claude-code';
95
- const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
96
- const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
97
-
98
- initLogger(DB_PATH);
99
- log(AGENT_ID, 'startup', `MCP server starting (db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
100
-
101
- const store = new EngramStore(DB_PATH);
102
- const activationEngine = new ActivationEngine(store);
103
- const connectionEngine = new ConnectionEngine(store, activationEngine);
104
- const stagingBuffer = new StagingBuffer(store, activationEngine);
105
- const evictionEngine = new EvictionEngine(store);
106
- const retractionEngine = new RetractionEngine(store);
107
- const evalEngine = new EvalEngine(store);
108
- const consolidationEngine = new ConsolidationEngine(store);
109
- const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
110
-
111
- stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
112
- consolidationScheduler.start();
113
-
114
- // Coordination DB handle — set when AWM_COORDINATION=true, used by memory_write for decision propagation
115
- let coordDb: import('better-sqlite3').Database | null = null;
116
-
117
- const server = new McpServer({
118
- name: 'agent-working-memory',
119
- version: '0.7.17',
120
- });
121
-
122
- server.registerResource(
123
- 'awm-overview',
124
- 'awm://server/overview',
125
- {
126
- title: 'AWM Overview',
127
- description: 'AgentWorkingMemory MCP server metadata and discovery notes',
128
- mimeType: 'text/markdown',
129
- },
130
- async () => ({
131
- contents: [{
132
- uri: 'awm://server/overview',
133
- text: [
134
- '# Agent Working Memory',
135
- '',
136
- `Agent: ${AGENT_ID}`,
137
- `DB: ${DB_PATH}`,
138
- `Coordination: ${process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1' ? 'enabled' : 'disabled'}`,
139
- '',
140
- 'This MCP server primarily exposes tools such as `memory_restore`, `memory_recall`, `memory_write`, and task/checkpoint operations.',
141
- 'The resources below exist so generic MCP clients can discover the server through `resources/list` and `resources/templates/list`.',
142
- ].join('\n'),
143
- mimeType: 'text/markdown',
144
- }],
145
- })
146
- );
147
-
148
- server.registerResource(
149
- 'awm-memory-template',
150
- new ResourceTemplate('awm://memory/{id}', { list: undefined }),
151
- {
152
- title: 'AWM Memory By ID',
153
- description: 'Metadata resource template for a memory identifier',
154
- mimeType: 'text/markdown',
155
- },
156
- async (_uri, variables) => ({
157
- contents: [{
158
- uri: `awm://memory/${variables.id ?? ''}`,
159
- text: [
160
- '# AWM Memory Reference',
161
- '',
162
- `Requested memory id: ${variables.id ?? ''}`,
163
- '',
164
- 'Use the AWM memory tools for actual retrieval and mutation:',
165
- '- `memory_recall` for cognitive retrieval',
166
- '- `memory_restore` for session state',
167
- '- `memory_feedback`, `memory_retract`, `memory_supersede` for memory maintenance',
168
- ].join('\n'),
169
- mimeType: 'text/markdown',
170
- }],
171
- })
172
- );
173
-
174
- // --- Auto-classification for memory types ---
175
-
176
- function classifyMemoryType(content: string): 'episodic' | 'semantic' | 'procedural' | 'unclassified' {
177
- const lower = content.toLowerCase();
178
- // Procedural: how-to, steps, numbered lists
179
- if (/\bhow to\b|\bsteps?:/i.test(content) || /^\s*\d+[\.\)]\s/m.test(content) || /\bthen run\b|\bfirst,?\s/i.test(content)) {
180
- return 'procedural';
181
- }
182
- // Episodic: past tense events, incidents, specific time references
183
- if (/\b(discovered|debugged|fixed|encountered|happened|resolved|found that|we did|i did|yesterday|last week|today)\b/i.test(content)) {
184
- return 'episodic';
185
- }
186
- // Semantic: facts, decisions, rules, patterns
187
- if (/\b(is|are|should|always|never|must|uses?|requires?|means|pattern|decision|rule|convention)\b/i.test(content) && content.length < 500) {
188
- return 'semantic';
189
- }
190
- return 'unclassified';
191
- }
192
-
193
- // --- Tools ---
194
-
195
- server.tool(
196
- 'memory_write',
197
- `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
198
-
199
- CALL THIS PROACTIVELY — do not wait to be asked. Write memories when you:
200
- - Discover something about the codebase, bugs, or architecture
201
- - Make a decision and want to remember why
202
- - Encounter and resolve an error
203
- - Learn a user preference or project pattern
204
- - Complete a significant piece of work
205
-
206
- The concept should be a short label (3-8 words). The content should be the full detail.`,
207
- {
208
- concept: z.string().describe('Short label for this memory (3-8 words)'),
209
- content: z.string().describe('Full detail of what was learned'),
210
- tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
211
- event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
212
- .optional().default('observation')
213
- .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
214
- surprise: z.number().min(0).max(1).optional().default(0.3)
215
- .describe('How surprising was this? 0=expected, 1=very unexpected'),
216
- decision_made: z.boolean().optional().default(false)
217
- .describe('Was a decision made? True boosts importance'),
218
- causal_depth: z.number().min(0).max(1).optional().default(0.3)
219
- .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
220
- resolution_effort: z.number().min(0).max(1).optional().default(0.3)
221
- .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
222
- memory_class: z.enum(['canonical', 'working', 'ephemeral']).optional().default('working')
223
- .describe('Memory class: canonical (source-of-truth, never stages), working (default), ephemeral (temporary, decays faster)'),
224
- memory_type: z.enum(['episodic', 'semantic', 'procedural', 'unclassified']).optional()
225
- .describe('Memory type: episodic (events/incidents), semantic (facts/decisions), procedural (how-to/steps). Auto-classified if omitted.'),
226
- supersedes: z.string().optional()
227
- .describe('ID of an older memory this one replaces. The old memory is down-ranked, not deleted.'),
228
- // --- Agent-provided metadata (stored as searchable tags) ---
229
- project: z.string().optional()
230
- .describe('Project context (e.g., "EquiHub", "AWM"). Becomes a searchable tag.'),
231
- topic: z.string().optional()
232
- .describe('Subject area (e.g., "database-migration", "auth-flow"). Becomes a searchable tag.'),
233
- source: z.enum(['code-reading', 'debugging', 'discussion', 'research', 'testing', 'observation']).optional()
234
- .describe('How this knowledge was acquired.'),
235
- confidence_level: z.enum(['verified', 'observed', 'assumed']).optional()
236
- .describe('Confidence: verified (tested), observed (read in code), assumed (reasoning).'),
237
- session_id: z.string().optional()
238
- .describe('Session/conversation grouping ID. Memories with same session_id are associated.'),
239
- intent: z.enum(['decision', 'question', 'todo', 'finding', 'context']).optional()
240
- .describe('What kind of memory this is.'),
241
- },
242
- async (params) => {
243
- // Assemble tags: user-provided + agent metadata (stored as searchable prefixed tags)
244
- const userTags = params.tags ?? [];
245
- const metaTags: string[] = [];
246
- if (params.project) metaTags.push(`proj=${params.project}`);
247
- if (params.topic) metaTags.push(`topic=${params.topic}`);
248
- if (params.source) metaTags.push(`src=${params.source}`);
249
- if (params.confidence_level) metaTags.push(`conf=${params.confidence_level}`);
250
- if (params.session_id) metaTags.push(`sid=${params.session_id}`);
251
- if (params.intent) metaTags.push(`intent=${params.intent}`);
252
-
253
- const memoryType = params.memory_type ?? classifyMemoryType(params.content);
254
-
255
- const result = performWrite({ store, connectionEngine }, {
256
- agentId: AGENT_ID,
257
- concept: params.concept,
258
- content: params.content,
259
- tags: [...userTags, ...metaTags],
260
- eventType: params.event_type as SalienceEventType,
261
- surprise: params.surprise,
262
- decisionMade: params.decision_made,
263
- causalDepth: params.causal_depth,
264
- resolutionEffort: params.resolution_effort,
265
- memoryClass: params.memory_class,
266
- memoryType,
267
- supersedes: params.supersedes,
268
- });
269
-
270
- // Auto-checkpoint — covers create/reinforce/supersede uniformly
271
- try { store.updateAutoCheckpointWrite(AGENT_ID, result.engram.id); } catch { /* non-fatal */ }
272
-
273
- if (result.action === 'reinforce') {
274
- 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)})`);
275
- return {
276
- content: [{
277
- type: 'text' as const,
278
- text: `Reinforced existing memory "${result.engram.concept}" (confidence ${result.reinforce!.previousConfidence.toFixed(2)} ${result.reinforce!.newConfidence.toFixed(2)})`,
279
- }],
280
- };
281
- }
282
-
283
- const engram = result.engram;
284
- const salience = result.salience!; // create/supersede always have salience
285
- const novelty = result.noveltyResult.novelty;
286
- const isLowSalience = salience.disposition === 'discard';
287
-
288
- // Decision propagation: when decision_made=true and coordination is enabled,
289
- // broadcast to coord_decisions so other agents can discover it
290
- if (params.decision_made && coordDb) {
291
- try {
292
- const agent = coordDb.prepare(
293
- `SELECT id, current_task FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
294
- ).get(AGENT_ID) as { id: string; current_task: string | null } | undefined;
295
- if (agent) {
296
- coordDb.prepare(
297
- `INSERT INTO coord_decisions (author_id, assignment_id, tags, summary) VALUES (?, ?, ?, ?)`
298
- ).run(agent.id, agent.current_task, params.tags ? JSON.stringify(params.tags) : null, params.concept);
299
- }
300
- } catch { /* decision propagation is non-fatal */ }
301
- }
302
-
303
- const logDisposition = isLowSalience ? 'low-salience' : salience.disposition;
304
- log(AGENT_ID, `write:${logDisposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
305
-
306
- return {
307
- content: [{
308
- type: 'text' as const,
309
- text: `Stored (${salience.disposition}) "${params.concept}" [${salience.score.toFixed(2)}]\nID: ${engram.id}`,
310
- }],
311
- };
312
- }
313
- );
314
-
315
- server.tool(
316
- 'memory_recall',
317
- `Recall memories relevant to a query. Uses cognitive activation — not keyword search.
318
-
319
- ALWAYS call this when:
320
- - Starting work on a project or topic (recall what you know)
321
- - Debugging (recall similar errors and solutions)
322
- - Making decisions (recall past decisions and outcomes)
323
- - The user mentions a topic you might have stored memories about
324
-
325
- Accepts either "query" or "context" parameter — both work identically.
326
- Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`,
327
- {
328
- query: z.string().optional().describe('What to search for — describe the situation, question, or topic'),
329
- context: z.string().optional().describe('Alias for query (either works)'),
330
- limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
331
- min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
332
- include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
333
- use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
334
- use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
335
- memory_type: z.enum(['episodic', 'semantic', 'procedural']).optional().describe('Filter by memory type (omit to search all types)'),
336
- workspace: z.string().optional().describe('Search across all agents in this workspace (hive mode). Omit for agent-scoped recall only.'),
337
- },
338
- async (params) => {
339
- const queryText = params.query ?? params.context;
340
- if (!queryText) {
341
- return {
342
- content: [{
343
- type: 'text' as const,
344
- text: 'Error: provide either "query" or "context" parameter with your search text.',
345
- }],
346
- };
347
- }
348
- // Use workspace from param, env var, or omit for agent-scoped
349
- const workspace = params.workspace ?? process.env.AWM_WORKSPACE ?? undefined;
350
- const results = await activationEngine.activate({
351
- agentId: AGENT_ID,
352
- context: queryText,
353
- limit: params.limit,
354
- minScore: params.min_score,
355
- includeStaging: params.include_staging,
356
- useReranker: params.use_reranker,
357
- useExpansion: params.use_expansion,
358
- memoryType: params.memory_type,
359
- workspace,
360
- });
361
-
362
- // Auto-checkpoint: track recall
363
- try {
364
- const ids = results.map(r => r.engram.id);
365
- store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
366
- } catch { /* non-fatal */ }
367
-
368
- log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" → ${results.length} results`);
369
-
370
- // Peer decisions: append recent decisions by other agents relevant to this query
371
- const peerSuffix = coordDb
372
- ? formatPeerDecisions(queryPeerDecisions(coordDb, AGENT_ID, queryText))
373
- : '';
374
-
375
- if (results.length === 0) {
376
- return {
377
- content: [{
378
- type: 'text' as const,
379
- text: 'No relevant memories found.' + peerSuffix,
380
- }],
381
- };
382
- }
383
-
384
- const lines = results.map((r, i) => {
385
- return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)}): ${r.engram.content}`;
386
- });
387
-
388
- return {
389
- content: [{
390
- type: 'text' as const,
391
- text: lines.join('\n') + peerSuffix,
392
- }],
393
- };
394
- }
395
- );
396
-
397
- server.tool(
398
- 'memory_feedback',
399
- `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
400
-
401
- Always call this after using a recalled memory so the system learns what's valuable.`,
402
- {
403
- engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
404
- useful: z.boolean().describe('Was this memory actually helpful?'),
405
- context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
406
- },
407
- async (params) => {
408
- store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
409
-
410
- const engram = store.getEngram(params.engram_id);
411
- if (engram) {
412
- const delta = params.useful
413
- ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
414
- : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
415
- store.updateConfidence(engram.id, engram.confidence + delta);
416
- }
417
-
418
- // Validation-gated Hebbian: resolve pending co-activation pairs for this engram
419
- const hebbianUpdated = activationEngine.resolveHebbianFeedback(params.engram_id, params.useful);
420
-
421
- return {
422
- content: [{
423
- type: 'text' as const,
424
- text: `Feedback: ${params.useful ? '+useful' : '-not useful'}${hebbianUpdated > 0 ? ` (${hebbianUpdated} association${hebbianUpdated > 1 ? 's' : ''} ${params.useful ? 'strengthened' : 'weakened'})` : ''}`,
425
- }],
426
- };
427
- }
428
- );
429
-
430
- server.tool(
431
- 'memory_retract',
432
- `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
433
-
434
- Use this when you discover a memory contains incorrect information.`,
435
- {
436
- engram_id: z.string().describe('ID of the wrong memory'),
437
- reason: z.string().describe('Why is this memory wrong?'),
438
- correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
439
- },
440
- async (params) => {
441
- const result = retractionEngine.retract({
442
- agentId: AGENT_ID,
443
- targetEngramId: params.engram_id,
444
- reason: params.reason,
445
- counterContent: params.correction,
446
- });
447
-
448
- const parts = [`Memory ${params.engram_id} retracted.`];
449
- if (result.correctionId) {
450
- parts.push(`Correction stored as ${result.correctionId}.`);
451
- }
452
- parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
453
-
454
- return {
455
- content: [{
456
- type: 'text' as const,
457
- text: parts.join(' '),
458
- }],
459
- };
460
- }
461
- );
462
-
463
- server.tool(
464
- 'memory_supersede',
465
- `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.
466
-
467
- Use this when:
468
- - A status or count has changed (e.g., "5 reviews done" → "7 reviews done")
469
- - Architecture or infrastructure evolved (e.g., "two-repo model" → "three-repo model")
470
- - A schedule or plan was updated
471
-
472
- The old memory stays in the database (searchable for history) but is heavily down-ranked in recall so the current version dominates.`,
473
- {
474
- old_engram_id: z.string().describe('ID of the outdated memory'),
475
- new_engram_id: z.string().describe('ID of the replacement memory'),
476
- reason: z.string().optional().describe('Why the old memory is outdated'),
477
- },
478
- async (params) => {
479
- const oldEngram = store.getEngram(params.old_engram_id);
480
- if (!oldEngram) {
481
- return { content: [{ type: 'text' as const, text: `Old memory not found: ${params.old_engram_id}` }] };
482
- }
483
- const newEngram = store.getEngram(params.new_engram_id);
484
- if (!newEngram) {
485
- return { content: [{ type: 'text' as const, text: `New memory not found: ${params.new_engram_id}` }] };
486
- }
487
-
488
- store.supersedeEngram(params.old_engram_id, params.new_engram_id);
489
-
490
- // Create supersession association (new → old)
491
- store.upsertAssociation(params.new_engram_id, params.old_engram_id, 0.8, 'causal', 0.9);
492
-
493
- // Reduce old memory's confidence (not to zero — it's historical, not wrong)
494
- store.updateConfidence(params.old_engram_id, Math.max(0.2, oldEngram.confidence * 0.4));
495
-
496
- log(AGENT_ID, 'supersede', `"${oldEngram.concept}" "${newEngram.concept}"${params.reason ? ` (${params.reason})` : ''}`);
497
-
498
- return {
499
- content: [{
500
- type: 'text' as const,
501
- text: `Superseded: "${oldEngram.concept}" → "${newEngram.concept}"`,
502
- }],
503
- };
504
- }
505
- );
506
-
507
- server.tool(
508
- 'memory_stats',
509
- `Get memory health stats — how many memories, confidence levels, association count, and system performance.
510
- Also shows the activity log path so the user can tail it to see what's happening.`,
511
- {},
512
- async () => {
513
- const metrics = evalEngine.computeMetrics(AGENT_ID);
514
- const checkpoint = store.getCheckpoint(AGENT_ID);
515
- const lines = [
516
- `Agent: ${AGENT_ID}`,
517
- `Active memories: ${metrics.activeEngramCount}`,
518
- `Staging: ${metrics.stagingEngramCount}`,
519
- `Retracted: ${metrics.retractedCount}`,
520
- `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
521
- `Total edges: ${metrics.totalEdges}`,
522
- `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
523
- `Activations (24h): ${metrics.activationCount}`,
524
- `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
525
- ``,
526
- `Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
527
- `Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
528
- `Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
529
- `Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
530
- ``,
531
- `Activity log: ${getLogPath() ?? 'not configured'}`,
532
- `Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
533
- ];
534
-
535
- return {
536
- content: [{
537
- type: 'text' as const,
538
- text: lines.join('\n'),
539
- }],
540
- };
541
- }
542
- );
543
-
544
- // --- Checkpointing Tools ---
545
-
546
- server.tool(
547
- 'memory_checkpoint',
548
- `Save your current execution state so you can recover after context compaction.
549
-
550
- ALWAYS call this before:
551
- - Long operations (multi-file generation, large refactors, overnight work)
552
- - Anything that might fill the context window
553
- - Switching to a different task
554
-
555
- Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`,
556
- {
557
- current_task: z.string().describe('What you are currently working on'),
558
- decisions: z.array(z.string()).optional().default([])
559
- .describe('Key decisions made so far'),
560
- active_files: z.array(z.string()).optional().default([])
561
- .describe('Files you are currently working with'),
562
- next_steps: z.array(z.string()).optional().default([])
563
- .describe('What needs to happen next'),
564
- related_memory_ids: z.array(z.string()).optional().default([])
565
- .describe('IDs of memories relevant to current work'),
566
- notes: z.string().optional().default('')
567
- .describe('Any other context worth preserving'),
568
- episode_id: z.string().optional()
569
- .describe('Current episode ID if known'),
570
- },
571
- async (params) => {
572
- const state: ConsciousState = {
573
- currentTask: params.current_task,
574
- decisions: params.decisions,
575
- activeFiles: params.active_files,
576
- nextSteps: params.next_steps,
577
- relatedMemoryIds: params.related_memory_ids,
578
- notes: params.notes,
579
- episodeId: params.episode_id ?? null,
580
- };
581
-
582
- store.saveCheckpoint(AGENT_ID, state);
583
- log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
584
-
585
- return {
586
- content: [{
587
- type: 'text' as const,
588
- text: `Checkpoint saved: "${params.current_task}" (${params.decisions.length} decisions, ${params.active_files.length} files)`,
589
- }],
590
- };
591
- }
592
- );
593
-
594
- server.tool(
595
- 'memory_restore',
596
- `Restore your previous execution state after context compaction or at session start.
597
-
598
- Returns:
599
- - Your saved execution state (task, decisions, next steps, files)
600
- - Recently recalled memories for context
601
- - Your last write for continuity
602
- - How long you were idle
603
-
604
- Use this at the start of every session or after compaction to pick up where you left off.`,
605
- {},
606
- async () => {
607
- const checkpoint = store.getCheckpoint(AGENT_ID);
608
-
609
- const now = Date.now();
610
- const idleMs = checkpoint
611
- ? now - checkpoint.auto.lastActivityAt.getTime()
612
- : 0;
613
-
614
- // Get last written engram
615
- let lastWrite: { id: string; concept: string; content: string } | null = null;
616
- if (checkpoint?.auto.lastWriteId) {
617
- const engram = store.getEngram(checkpoint.auto.lastWriteId);
618
- if (engram) {
619
- lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
620
- }
621
- }
622
-
623
- // Recall memories using last context
624
- let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
625
- const recallContext = checkpoint?.auto.lastRecallContext
626
- ?? checkpoint?.executionState?.currentTask
627
- ?? null;
628
-
629
- if (recallContext) {
630
- try {
631
- const results = await activationEngine.activate({
632
- agentId: AGENT_ID,
633
- context: recallContext,
634
- limit: 5,
635
- minScore: 0.05,
636
- useReranker: true,
637
- useExpansion: true,
638
- workspace: process.env.AWM_WORKSPACE ?? undefined,
639
- });
640
- recalledMemories = results.map(r => ({
641
- id: r.engram.id,
642
- concept: r.engram.concept,
643
- content: r.engram.content,
644
- score: r.score,
645
- }));
646
- } catch { /* recall failure is non-fatal */ }
647
- }
648
-
649
- // Consolidation on restore:
650
- // - If idle >5min but last consolidation was recent (graceful exit ran it), skip
651
- // - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
652
- const MINI_IDLE_MS = 5 * 60_000;
653
- const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min — if last consolidation was longer ago, run full
654
- let miniConsolidationTriggered = false;
655
- let fullConsolidationTriggered = false;
656
-
657
- if (idleMs > MINI_IDLE_MS) {
658
- const sinceLastConsolidation = checkpoint?.lastConsolidationAt
659
- ? now - checkpoint.lastConsolidationAt.getTime()
660
- : Infinity;
661
-
662
- if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
663
- // No recent consolidation — graceful exit didn't happen, run full cycle
664
- fullConsolidationTriggered = true;
665
- try {
666
- const result = await consolidationEngine.consolidate(AGENT_ID);
667
- store.markConsolidation(AGENT_ID, false);
668
- 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`);
669
- } catch { /* consolidation failure is non-fatal */ }
670
- } else {
671
- // Recent consolidation exists — graceful exit already handled it, just do mini
672
- miniConsolidationTriggered = true;
673
- consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => {});
674
- }
675
- }
676
-
677
- // Format response
678
- const parts: string[] = [];
679
- const idleMin = Math.round(idleMs / 60_000);
680
- const consolidationNote = fullConsolidationTriggered
681
- ? ' (full consolidation — no graceful exit detected)'
682
- : miniConsolidationTriggered
683
- ? ' (mini-consolidation triggered)'
684
- : '';
685
- log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
686
- parts.push(`Idle: ${idleMin}min${consolidationNote}`);
687
-
688
- if (checkpoint?.executionState) {
689
- const s = checkpoint.executionState;
690
- parts.push(`\n**Current task:** ${s.currentTask}`);
691
- if (s.decisions.length) parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
692
- if (s.nextSteps.length) parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
693
- if (s.activeFiles.length) parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
694
- if (s.notes) parts.push(`**Notes:** ${s.notes}`);
695
- if (checkpoint.checkpointAt) parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
696
- } else {
697
- parts.push('\nNo explicit checkpoint saved.');
698
- parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
699
- }
700
-
701
- if (lastWrite) {
702
- parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
703
- }
704
-
705
- if (recalledMemories.length > 0) {
706
- parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
707
- for (const m of recalledMemories) {
708
- parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
709
- }
710
- }
711
-
712
- // Peer decisions: show recent decisions from other agents (last 30 min)
713
- if (coordDb) {
714
- try {
715
- const myAgent = coordDb.prepare(
716
- `SELECT id FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
717
- ).get(AGENT_ID) as { id: string } | undefined;
718
-
719
- const peerDecisions = coordDb.prepare(
720
- `SELECT d.summary, a.name AS author_name, d.created_at
721
- FROM coord_decisions d JOIN coord_agents a ON d.author_id = a.id
722
- WHERE d.author_id != ? AND d.created_at > datetime('now', '-30 minutes')
723
- ORDER BY d.created_at DESC LIMIT 10`
724
- ).all(myAgent?.id ?? '') as Array<{ summary: string; author_name: string; created_at: string }>;
725
-
726
- if (peerDecisions.length > 0) {
727
- parts.push(`\n**Peer decisions (last 30 min):**`);
728
- for (const d of peerDecisions) {
729
- parts.push(`- [${d.author_name}] ${d.summary} (${d.created_at})`);
730
- }
731
- }
732
- } catch { /* peer decisions are non-fatal */ }
733
- }
734
-
735
- return {
736
- content: [{
737
- type: 'text' as const,
738
- text: parts.join('\n'),
739
- }],
740
- };
741
- }
742
- );
743
-
744
- // --- Task Management Tools ---
745
-
746
- server.tool(
747
- 'memory_task_add',
748
- `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
749
-
750
- Use this when:
751
- - You identify work that needs doing but can't do it right now
752
- - The user mentions something to do later
753
- - You want to park a sub-task while focusing on something more urgent
754
-
755
- Tasks automatically get high salience so they won't be discarded.`,
756
- {
757
- concept: z.string().describe('Short task title (3-10 words)'),
758
- content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
759
- tags: z.array(z.string()).optional().describe('Tags for categorization'),
760
- priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
761
- .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
762
- blocked_by: z.string().optional().describe('ID of a task that must finish first'),
763
- },
764
- async (params) => {
765
- const engram = store.createEngram({
766
- agentId: AGENT_ID,
767
- concept: params.concept,
768
- content: params.content,
769
- tags: [...(params.tags ?? []), 'task'],
770
- salience: 0.9, // Tasks always high salience
771
- confidence: 0.8,
772
- salienceFeatures: {
773
- surprise: 0.5,
774
- decisionMade: true,
775
- causalDepth: 0.5,
776
- resolutionEffort: 0.5,
777
- eventType: 'decision',
778
- },
779
- reasonCodes: ['task-created'],
780
- taskStatus: params.blocked_by ? 'blocked' : 'open',
781
- taskPriority: params.priority as TaskPriority,
782
- blockedBy: params.blocked_by,
783
- });
784
-
785
- connectionEngine.enqueue(engram.id);
786
-
787
- // Generate embedding asynchronously
788
- embed(`${params.concept} ${params.content}`).then(vec => {
789
- store.updateEmbedding(engram.id, vec);
790
- }).catch(() => {});
791
-
792
- return {
793
- content: [{
794
- type: 'text' as const,
795
- text: `Task created: "${params.concept}" (${params.priority})`,
796
- }],
797
- };
798
- }
799
- );
800
-
801
- server.tool(
802
- 'memory_task_update',
803
- `Update a task's status or priority. Use this to:
804
- - Start working on a task (open → in_progress)
805
- - Mark a task done (→ done)
806
- - Block a task on another (→ blocked)
807
- - Reprioritize (change priority)
808
- - Unblock a task (clear blocked_by)`,
809
- {
810
- task_id: z.string().describe('ID of the task to update'),
811
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
812
- .describe('New status'),
813
- priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
814
- .describe('New priority'),
815
- blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
816
- },
817
- async (params) => {
818
- const engram = store.getEngram(params.task_id);
819
- if (!engram || !engram.taskStatus) {
820
- return { content: [{ type: 'text' as const, text: `Task not found: ${params.task_id}` }] };
821
- }
822
-
823
- if (params.blocked_by !== undefined) {
824
- store.updateBlockedBy(params.task_id, params.blocked_by || null);
825
- }
826
- if (params.status) {
827
- store.updateTaskStatus(params.task_id, params.status as TaskStatus);
828
- }
829
- if (params.priority) {
830
- store.updateTaskPriority(params.task_id, params.priority as TaskPriority);
831
- }
832
-
833
- const updated = store.getEngram(params.task_id)!;
834
- return {
835
- content: [{
836
- type: 'text' as const,
837
- text: `Updated: "${updated.concept}" → ${updated.taskStatus} (${updated.taskPriority})`,
838
- }],
839
- };
840
- }
841
- );
842
-
843
- server.tool(
844
- 'memory_task_list',
845
- `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
846
-
847
- Use at the start of a session to see what's pending, or to check blocked/done tasks.`,
848
- {
849
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
850
- .describe('Filter by status (omit to see all active tasks)'),
851
- include_done: z.boolean().optional().default(false)
852
- .describe('Include completed tasks?'),
853
- },
854
- async (params) => {
855
- let tasks = store.getTasks(AGENT_ID, params.status as TaskStatus | undefined);
856
- if (!params.include_done && !params.status) {
857
- tasks = tasks.filter(t => t.taskStatus !== 'done');
858
- }
859
-
860
- if (tasks.length === 0) {
861
- return { content: [{ type: 'text' as const, text: 'No tasks found.' }] };
862
- }
863
-
864
- const lines = tasks.map((t, i) => {
865
- const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
866
- const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
867
- 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}`;
868
- });
869
-
870
- return {
871
- content: [{
872
- type: 'text' as const,
873
- text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
874
- }],
875
- };
876
- }
877
- );
878
-
879
- server.tool(
880
- 'memory_task_next',
881
- `Get the single most important task to work on next.
882
-
883
- Prioritizes: in_progress tasks first (finish what you started), then by priority level, then oldest first. Skips blocked and done tasks.
884
-
885
- Use this when you finish a task or need to decide what to do next.`,
886
- {},
887
- async () => {
888
- const next = store.getNextTask(AGENT_ID);
889
- if (!next) {
890
- return { content: [{ type: 'text' as const, text: 'No actionable tasks. All clear!' }] };
891
- }
892
-
893
- const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
894
- const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
895
-
896
- return {
897
- content: [{
898
- type: 'text' as const,
899
- text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
900
- }],
901
- };
902
- }
903
- );
904
-
905
- // --- Task Bracket Tools ---
906
-
907
- server.tool(
908
- 'memory_task_begin',
909
- `Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
910
-
911
- CALL THIS when starting:
912
- - A multi-step operation (doc generation, large refactor, migration)
913
- - Work on a new topic or project area
914
- - Anything that might fill the context window
915
-
916
- This ensures your state is saved before you start, and primes recall with relevant context.`,
917
- {
918
- topic: z.string().describe('What task are you starting? (3-15 words)'),
919
- files: z.array(z.string()).optional().default([])
920
- .describe('Files you expect to work with'),
921
- notes: z.string().optional().default('')
922
- .describe('Any additional context'),
923
- },
924
- async (params) => {
925
- // 1. Checkpoint current state
926
- const checkpoint = store.getCheckpoint(AGENT_ID);
927
- const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
928
-
929
- store.saveCheckpoint(AGENT_ID, {
930
- currentTask: params.topic,
931
- decisions: [],
932
- activeFiles: params.files,
933
- nextSteps: [],
934
- relatedMemoryIds: [],
935
- notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
936
- episodeId: null,
937
- });
938
-
939
- // 2. Auto-recall relevant memories
940
- let recalledSummary = '';
941
- try {
942
- const results = await activationEngine.activate({
943
- agentId: AGENT_ID,
944
- context: params.topic,
945
- limit: 5,
946
- minScore: 0.05,
947
- useReranker: true,
948
- useExpansion: true,
949
- workspace: process.env.AWM_WORKSPACE ?? undefined,
950
- });
951
-
952
- if (results.length > 0) {
953
- const lines = results.map((r, i) => {
954
- const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
955
- return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
956
- });
957
- recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
958
-
959
- // Track recall
960
- store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
961
- }
962
- } catch { /* recall failure is non-fatal */ }
963
-
964
- log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
965
-
966
- return {
967
- content: [{
968
- type: 'text' as const,
969
- text: `Started: "${params.topic}" (prev: ${prevTask})${recalledSummary}`,
970
- }],
971
- };
972
- }
973
- );
974
-
975
- server.tool(
976
- 'memory_task_end',
977
- `Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
978
-
979
- CALL THIS when you finish:
980
- - A multi-step operation
981
- - Before switching to a different topic
982
- - At the end of a work session
983
-
984
- This captures what was accomplished so future sessions can recall it.`,
985
- {
986
- summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
987
- tags: z.array(z.string()).optional().default([])
988
- .describe('Tags for the summary memory'),
989
- supersedes: z.array(z.string()).optional().default([])
990
- .describe('IDs of older memories this task summary replaces (marks them as superseded)'),
991
- },
992
- async (params) => {
993
- // 1. Write summary as a memory
994
- const salience = evaluateSalience({
995
- content: params.summary,
996
- eventType: 'decision',
997
- surprise: 0.3,
998
- decisionMade: true,
999
- causalDepth: 0.5,
1000
- resolutionEffort: 0.5,
1001
- });
1002
-
1003
- // Determine the real task name for the summary engram
1004
- const checkpoint = store.getCheckpoint(AGENT_ID);
1005
- const rawTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
1006
- // Strip any "Completed: " prefixes to avoid cascading
1007
- const cleanedTask = rawTask.replace(/^(Completed: )+/, '');
1008
- // Don't use auto-checkpoint or already-completed tasks as real task names
1009
- const isNamedTask = !cleanedTask.startsWith('Auto-checkpoint') && cleanedTask !== 'Unknown task';
1010
- const completedTask = isNamedTask
1011
- ? cleanedTask
1012
- : params.summary.slice(0, 60).replace(/\n/g, ' ');
1013
-
1014
- const engram = store.createEngram({
1015
- agentId: AGENT_ID,
1016
- concept: completedTask.slice(0, 80),
1017
- content: params.summary,
1018
- tags: [...params.tags, 'task-summary'],
1019
- salience: isNamedTask ? Math.max(salience.score, 0.7) : salience.score, // Only floor salience for named tasks
1020
- confidence: 0.65, // Task summaries are decision-grade (completed work)
1021
- salienceFeatures: salience.features,
1022
- reasonCodes: [...salience.reasonCodes, 'task-end'],
1023
- });
1024
-
1025
- connectionEngine.enqueue(engram.id);
1026
-
1027
- // 2. Handle supersessions — mark old memories as outdated
1028
- let supersededCount = 0;
1029
- for (const oldId of params.supersedes) {
1030
- const oldEngram = store.getEngram(oldId);
1031
- if (oldEngram) {
1032
- store.supersedeEngram(oldId, engram.id);
1033
- store.upsertAssociation(engram.id, oldId, 0.8, 'causal', 0.9);
1034
- store.updateConfidence(oldId, Math.max(0.2, oldEngram.confidence * 0.4));
1035
- supersededCount++;
1036
- }
1037
- }
1038
-
1039
- // Generate embedding asynchronously
1040
- embed(`Task completed: ${params.summary}`).then(vec => {
1041
- store.updateEmbedding(engram.id, vec);
1042
- }).catch(() => {});
1043
-
1044
- // 2. Update checkpoint to reflect completion
1045
- store.saveCheckpoint(AGENT_ID, {
1046
- currentTask: `Completed: ${completedTask}`,
1047
- decisions: checkpoint?.executionState?.decisions ?? [],
1048
- activeFiles: [],
1049
- nextSteps: [],
1050
- relatedMemoryIds: [engram.id],
1051
- notes: `Task completed. Summary memory: ${engram.id}`,
1052
- episodeId: null,
1053
- });
1054
-
1055
- store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
1056
- log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)} superseded=${supersededCount}`);
1057
-
1058
- const supersededNote = supersededCount > 0 ? ` (${supersededCount} old memories superseded)` : '';
1059
- return {
1060
- content: [{
1061
- type: 'text' as const,
1062
- text: `Completed: "${completedTask}" [${salience.score.toFixed(2)}]${supersededNote}`,
1063
- }],
1064
- };
1065
- }
1066
- );
1067
-
1068
- // --- Start ---
1069
-
1070
- async function main() {
1071
- const transport = new StdioServerTransport();
1072
- await server.connect(transport);
1073
-
1074
- // Start hook sidecar (lightweight HTTP for Claude Code hooks)
1075
- const sidecar = startSidecar({
1076
- store,
1077
- agentId: AGENT_ID,
1078
- secret: HOOK_SECRET,
1079
- port: HOOK_PORT,
1080
- onConsolidate: async (agentId, reason) => {
1081
- console.error(`[mcp] consolidation triggered: ${reason}`);
1082
- const result = await consolidationEngine.consolidate(agentId);
1083
- store.markConsolidation(agentId, false);
1084
- console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
1085
- },
1086
- });
1087
-
1088
- // Coordination MCP tools (opt-in via AWM_COORDINATION=true)
1089
- const coordEnabled = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
1090
- if (coordEnabled) {
1091
- const { initCoordinationTables } = await import('./coordination/schema.js');
1092
- const { registerCoordinationTools } = await import('./coordination/mcp-tools.js');
1093
- initCoordinationTables(store.getDb());
1094
- registerCoordinationTools(server, store.getDb());
1095
- coordDb = store.getDb();
1096
- } else {
1097
- console.error('AWM: coordination tools disabled (set AWM_COORDINATION=true to enable)');
1098
- }
1099
-
1100
- // Log to stderr (stdout is reserved for MCP protocol)
1101
- console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
1102
- console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
1103
-
1104
- // Clean shutdown
1105
- const cleanup = () => {
1106
- sidecar.close();
1107
- consolidationScheduler.stop();
1108
- stagingBuffer.stop();
1109
- try { store.walCheckpoint(); } catch { /* non-fatal */ }
1110
- store.close();
1111
- };
1112
- process.on('SIGINT', () => { cleanup(); process.exit(0); });
1113
- process.on('SIGTERM', () => { cleanup(); process.exit(0); });
1114
- }
1115
-
1116
- main().catch(err => {
1117
- console.error('MCP server failed:', err);
1118
- process.exit(1);
1119
- });
1120
-
1121
- } // 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 (12):
10
+ * memory_write — store a memory (salience filter decides disposition)
11
+ * memory_recall — activate memories by context (cognitive retrieval)
12
+ * memory_feedback — report whether a recalled memory was useful
13
+ * memory_retract — invalidate a wrong memory with optional correction
14
+ * memory_supersede — replace an outdated memory with a current one
15
+ * memory_stats — get memory health metrics
16
+ * memory_checkpoint — save structured execution state (survives compaction)
17
+ * memory_restore — restore state + targeted recall after compaction
18
+ * memory_task_add — create a prioritized task
19
+ * memory_task_update — change task status, priority, or blocking
20
+ * memory_task_list — list tasks filtered by status
21
+ * memory_task_next — get the highest-priority actionable task
22
+ *
23
+ * Run: npx tsx src/mcp.ts
24
+ * Config: add to ~/.claude.json or .mcp.json
25
+ */
26
+
27
+ import { readFileSync } from 'node:fs';
28
+ import { resolve } from 'node:path';
29
+ import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
30
+
31
+ // Load .env file if present (no external dependency)
32
+ try {
33
+ const envPath = resolve(process.cwd(), '.env');
34
+ const envContent = readFileSync(envPath, 'utf-8');
35
+ for (const line of envContent.split('\n')) {
36
+ const trimmed = line.trim();
37
+ if (!trimmed || trimmed.startsWith('#')) continue;
38
+ const eqIdx = trimmed.indexOf('=');
39
+ if (eqIdx === -1) continue;
40
+ const key = trimmed.slice(0, eqIdx).trim();
41
+ const val = trimmed.slice(eqIdx + 1).trim().replace(/^["']|["']$/g, '');
42
+ if (!process.env[key]) process.env[key] = val;
43
+ }
44
+ } catch { /* No .env file */ }
45
+
46
+ // MCP uses stdout for JSON-RPC. Redirect console.log to stderr so engine
47
+ // startup messages (ConsolidationScheduler, model loading, etc.) don't
48
+ // corrupt the transport. This MUST happen before any engine imports.
49
+ console.log = console.error;
50
+
51
+ import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
52
+ import { z } from 'zod';
53
+
54
+ import { EngramStore } from './storage/sqlite.js';
55
+ import { openStore, getConfiguredBackend, type StoreBackend } from './storage/factory.js';
56
+ import type { IEngramStore } from './storage/store.js';
57
+ import { ActivationEngine } from './engine/activation.js';
58
+ import { ConnectionEngine } from './engine/connections.js';
59
+ import { StagingBuffer } from './engine/staging.js';
60
+ import { EvictionEngine } from './engine/eviction.js';
61
+ import { RetractionEngine } from './engine/retraction.js';
62
+ import { EvalEngine } from './engine/eval.js';
63
+ import { ConsolidationEngine } from './engine/consolidation.js';
64
+ import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
65
+ import { evaluateSalience, computeNovelty, computeNoveltyWithMatch } from './core/salience.js';
66
+ import { performWrite } from './core/write-pipeline.js';
67
+ import type { ConsciousState } from './types/checkpoint.js';
68
+ import type { SalienceEventType } from './core/salience.js';
69
+ import type { TaskStatus, TaskPriority } from './types/engram.js';
70
+ import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
71
+ import { embed } from './core/embeddings.js';
72
+ import { startSidecar } from './hooks/sidecar.js';
73
+ import { initLogger, log, getLogPath } from './core/logger.js';
74
+ import { queryPeerDecisions, formatPeerDecisions } from './coordination/peer-decisions.js';
75
+
76
+ // --- Incognito Mode ---
77
+ // When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
78
+ // No DB, no engines, no sidecar just a bare MCP server that exposes nothing.
79
+
80
+ const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
81
+
82
+ if (INCOGNITO) {
83
+ console.error('AWM: incognito mode all memory tools disabled, nothing will be recorded');
84
+ const server = new McpServer({ name: 'agent-working-memory', version: '0.8.6' });
85
+ const transport = new StdioServerTransport();
86
+ server.connect(transport).catch(err => {
87
+ console.error('MCP server failed:', err);
88
+ process.exit(1);
89
+ });
90
+ // No tools registered — Claude won't see any memory_* tools
91
+ } else {
92
+
93
+ // --- Setup ---
94
+
95
+ const BACKEND: StoreBackend = getConfiguredBackend();
96
+ const DB_PATH = process.env.AWM_DB_PATH ?? (BACKEND === 'pglite' ? 'memory-pglite' : 'memory.db');
97
+ const AGENT_ID = process.env.AWM_AGENT_ID ?? process.env.WORKER_NAME ?? 'claude-code';
98
+ const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
99
+ const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
100
+
101
+ initLogger(DB_PATH);
102
+ log(AGENT_ID, 'startup', `MCP server starting (backend: ${BACKEND}, db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
103
+
104
+ // AWM 0.8.x: openStore() returns either SQLite (sync) or PGlite (async) store.
105
+ // Engines accept either via IEngramStore (MaybePromise<T> contract).
106
+ const { store: storeAny } = await openStore();
107
+ // Engines accept the async contract; SQLite-only call sites must guard on BACKEND.
108
+ const store = storeAny as unknown as IEngramStore & Partial<EngramStore>;
109
+ const activationEngine = new ActivationEngine(store);
110
+ const connectionEngine = new ConnectionEngine(store, activationEngine);
111
+ const stagingBuffer = new StagingBuffer(store, activationEngine);
112
+ const evictionEngine = new EvictionEngine(store);
113
+ const retractionEngine = new RetractionEngine(store);
114
+ const evalEngine = new EvalEngine(store);
115
+ const consolidationEngine = new ConsolidationEngine(store, connectionEngine);
116
+ const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
117
+
118
+ stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
119
+ consolidationScheduler.start();
120
+
121
+ // Coordination DB handle — set when AWM_COORDINATION=true, used by memory_write for decision propagation
122
+ let coordDb: import('better-sqlite3').Database | null = null;
123
+
124
+ const server = new McpServer({
125
+ name: 'agent-working-memory',
126
+ version: '0.8.6',
127
+ });
128
+
129
+ server.registerResource(
130
+ 'awm-overview',
131
+ 'awm://server/overview',
132
+ {
133
+ title: 'AWM Overview',
134
+ description: 'AgentWorkingMemory MCP server metadata and discovery notes',
135
+ mimeType: 'text/markdown',
136
+ },
137
+ async () => ({
138
+ contents: [{
139
+ uri: 'awm://server/overview',
140
+ text: [
141
+ '# Agent Working Memory',
142
+ '',
143
+ `Agent: ${AGENT_ID}`,
144
+ `DB: ${DB_PATH}`,
145
+ `Coordination: ${process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1' ? 'enabled' : 'disabled'}`,
146
+ '',
147
+ 'This MCP server primarily exposes tools such as `memory_restore`, `memory_recall`, `memory_write`, and task/checkpoint operations.',
148
+ 'The resources below exist so generic MCP clients can discover the server through `resources/list` and `resources/templates/list`.',
149
+ ].join('\n'),
150
+ mimeType: 'text/markdown',
151
+ }],
152
+ })
153
+ );
154
+
155
+ server.registerResource(
156
+ 'awm-memory-template',
157
+ new ResourceTemplate('awm://memory/{id}', { list: undefined }),
158
+ {
159
+ title: 'AWM Memory By ID',
160
+ description: 'Metadata resource template for a memory identifier',
161
+ mimeType: 'text/markdown',
162
+ },
163
+ async (_uri, variables) => ({
164
+ contents: [{
165
+ uri: `awm://memory/${variables.id ?? ''}`,
166
+ text: [
167
+ '# AWM Memory Reference',
168
+ '',
169
+ `Requested memory id: ${variables.id ?? ''}`,
170
+ '',
171
+ 'Use the AWM memory tools for actual retrieval and mutation:',
172
+ '- `memory_recall` for cognitive retrieval',
173
+ '- `memory_restore` for session state',
174
+ '- `memory_feedback`, `memory_retract`, `memory_supersede` for memory maintenance',
175
+ ].join('\n'),
176
+ mimeType: 'text/markdown',
177
+ }],
178
+ })
179
+ );
180
+
181
+ // --- Auto-classification for memory types ---
182
+
183
+ function classifyMemoryType(content: string): 'episodic' | 'semantic' | 'procedural' | 'unclassified' {
184
+ const lower = content.toLowerCase();
185
+ // Procedural: how-to, steps, numbered lists
186
+ if (/\bhow to\b|\bsteps?:/i.test(content) || /^\s*\d+[\.\)]\s/m.test(content) || /\bthen run\b|\bfirst,?\s/i.test(content)) {
187
+ return 'procedural';
188
+ }
189
+ // Episodic: past tense events, incidents, specific time references
190
+ if (/\b(discovered|debugged|fixed|encountered|happened|resolved|found that|we did|i did|yesterday|last week|today)\b/i.test(content)) {
191
+ return 'episodic';
192
+ }
193
+ // Semantic: facts, decisions, rules, patterns
194
+ if (/\b(is|are|should|always|never|must|uses?|requires?|means|pattern|decision|rule|convention)\b/i.test(content) && content.length < 500) {
195
+ return 'semantic';
196
+ }
197
+ return 'unclassified';
198
+ }
199
+
200
+ // --- Tools ---
201
+
202
+ server.tool(
203
+ 'memory_write',
204
+ `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
205
+
206
+ CALL THIS PROACTIVELY do not wait to be asked. Write memories when you:
207
+ - Discover something about the codebase, bugs, or architecture
208
+ - Make a decision and want to remember why
209
+ - Encounter and resolve an error
210
+ - Learn a user preference or project pattern
211
+ - Complete a significant piece of work
212
+
213
+ The concept should be a short label (3-8 words). The content should be the full detail.`,
214
+ {
215
+ concept: z.string().describe('Short label for this memory (3-8 words)'),
216
+ content: z.string().describe('Full detail of what was learned'),
217
+ tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
218
+ event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
219
+ .optional().default('observation')
220
+ .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
221
+ surprise: z.number().min(0).max(1).optional().default(0.3)
222
+ .describe('How surprising was this? 0=expected, 1=very unexpected'),
223
+ decision_made: z.boolean().optional().default(false)
224
+ .describe('Was a decision made? True boosts importance'),
225
+ causal_depth: z.number().min(0).max(1).optional().default(0.3)
226
+ .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
227
+ resolution_effort: z.number().min(0).max(1).optional().default(0.3)
228
+ .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
229
+ memory_class: z.enum(['canonical', 'working', 'ephemeral']).optional().default('working')
230
+ .describe('Memory class: canonical (source-of-truth, never stages), working (default), ephemeral (temporary, decays faster)'),
231
+ memory_type: z.enum(['episodic', 'semantic', 'procedural', 'unclassified']).optional()
232
+ .describe('Memory type: episodic (events/incidents), semantic (facts/decisions), procedural (how-to/steps). Auto-classified if omitted.'),
233
+ supersedes: z.string().optional()
234
+ .describe('ID of an older memory this one replaces. The old memory is down-ranked, not deleted.'),
235
+ // --- Agent-provided metadata (stored as searchable tags) ---
236
+ project: z.string().optional()
237
+ .describe('Project context (e.g., "EquiHub", "AWM"). Becomes a searchable tag.'),
238
+ topic: z.string().optional()
239
+ .describe('Subject area (e.g., "database-migration", "auth-flow"). Becomes a searchable tag.'),
240
+ source: z.enum(['code-reading', 'debugging', 'discussion', 'research', 'testing', 'observation']).optional()
241
+ .describe('How this knowledge was acquired.'),
242
+ confidence_level: z.enum(['verified', 'observed', 'assumed']).optional()
243
+ .describe('Confidence: verified (tested), observed (read in code), assumed (reasoning).'),
244
+ session_id: z.string().optional()
245
+ .describe('Session/conversation grouping ID. Memories with same session_id are associated.'),
246
+ intent: z.enum(['decision', 'question', 'todo', 'finding', 'context']).optional()
247
+ .describe('What kind of memory this is.'),
248
+ },
249
+ async (params) => {
250
+ // Assemble tags: user-provided + agent metadata (stored as searchable prefixed tags)
251
+ const userTags = params.tags ?? [];
252
+ const metaTags: string[] = [];
253
+ if (params.project) metaTags.push(`proj=${params.project}`);
254
+ if (params.topic) metaTags.push(`topic=${params.topic}`);
255
+ if (params.source) metaTags.push(`src=${params.source}`);
256
+ if (params.confidence_level) metaTags.push(`conf=${params.confidence_level}`);
257
+ if (params.session_id) metaTags.push(`sid=${params.session_id}`);
258
+ if (params.intent) metaTags.push(`intent=${params.intent}`);
259
+
260
+ const memoryType = params.memory_type ?? classifyMemoryType(params.content);
261
+
262
+ const result = await performWrite({ store, connectionEngine }, {
263
+ agentId: AGENT_ID,
264
+ concept: params.concept,
265
+ content: params.content,
266
+ tags: [...userTags, ...metaTags],
267
+ eventType: params.event_type as SalienceEventType,
268
+ surprise: params.surprise,
269
+ decisionMade: params.decision_made,
270
+ causalDepth: params.causal_depth,
271
+ resolutionEffort: params.resolution_effort,
272
+ memoryClass: params.memory_class,
273
+ memoryType,
274
+ supersedes: params.supersedes,
275
+ });
276
+
277
+ // Auto-checkpoint covers create/reinforce/supersede uniformly
278
+ try { await store.updateAutoCheckpointWrite(AGENT_ID, result.engram.id); } catch { /* non-fatal */ }
279
+
280
+ if (result.action === 'reinforce') {
281
+ 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)})`);
282
+ return {
283
+ content: [{
284
+ type: 'text' as const,
285
+ text: `Reinforced existing memory "${result.engram.concept}" (confidence ${result.reinforce!.previousConfidence.toFixed(2)} → ${result.reinforce!.newConfidence.toFixed(2)})`,
286
+ }],
287
+ };
288
+ }
289
+
290
+ const engram = result.engram;
291
+ const salience = result.salience!; // create/supersede always have salience
292
+ const novelty = result.noveltyResult.novelty;
293
+ const isLowSalience = salience.disposition === 'discard';
294
+
295
+ // Decision propagation: when decision_made=true and coordination is enabled,
296
+ // broadcast to coord_decisions so other agents can discover it
297
+ if (params.decision_made && coordDb) {
298
+ try {
299
+ const agent = coordDb.prepare(
300
+ `SELECT id, current_task FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
301
+ ).get(AGENT_ID) as { id: string; current_task: string | null } | undefined;
302
+ if (agent) {
303
+ coordDb.prepare(
304
+ `INSERT INTO coord_decisions (author_id, assignment_id, tags, summary) VALUES (?, ?, ?, ?)`
305
+ ).run(agent.id, agent.current_task, params.tags ? JSON.stringify(params.tags) : null, params.concept);
306
+ }
307
+ } catch { /* decision propagation is non-fatal */ }
308
+ }
309
+
310
+ const logDisposition = isLowSalience ? 'low-salience' : salience.disposition;
311
+ log(AGENT_ID, `write:${logDisposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
312
+
313
+ return {
314
+ content: [{
315
+ type: 'text' as const,
316
+ text: `Stored (${salience.disposition}) "${params.concept}" [${salience.score.toFixed(2)}]\nID: ${engram.id}`,
317
+ }],
318
+ };
319
+ }
320
+ );
321
+
322
+ server.tool(
323
+ 'memory_recall',
324
+ `Recall memories relevant to a query. Uses cognitive activation — not keyword search.
325
+
326
+ ALWAYS call this when:
327
+ - Starting work on a project or topic (recall what you know)
328
+ - Debugging (recall similar errors and solutions)
329
+ - Making decisions (recall past decisions and outcomes)
330
+ - The user mentions a topic you might have stored memories about
331
+
332
+ Accepts either "query" or "context" parameter — both work identically.
333
+ Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`,
334
+ {
335
+ query: z.string().optional().describe('What to search for describe the situation, question, or topic'),
336
+ context: z.string().optional().describe('Alias for query (either works)'),
337
+ limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
338
+ min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
339
+ include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
340
+ use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
341
+ use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
342
+ memory_type: z.enum(['episodic', 'semantic', 'procedural']).optional().describe('Filter by memory type (omit to search all types)'),
343
+ workspace: z.string().optional().describe('Search across all agents in this workspace (hive mode). Omit for agent-scoped recall only.'),
344
+ 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.'),
345
+ 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.'),
346
+ },
347
+ async (params) => {
348
+ const queryText = params.query ?? params.context;
349
+ if (!queryText) {
350
+ return {
351
+ content: [{
352
+ type: 'text' as const,
353
+ text: 'Error: provide either "query" or "context" parameter with your search text.',
354
+ }],
355
+ };
356
+ }
357
+ // Use workspace from param, env var, or omit for agent-scoped
358
+ const workspace = params.workspace ?? process.env.AWM_WORKSPACE ?? undefined;
359
+ const results = await activationEngine.activate({
360
+ agentId: AGENT_ID,
361
+ context: queryText,
362
+ limit: params.limit,
363
+ minScore: params.min_score,
364
+ includeStaging: params.include_staging,
365
+ useReranker: params.use_reranker,
366
+ useExpansion: params.use_expansion,
367
+ memoryType: params.memory_type,
368
+ workspace,
369
+ requireConfidence: params.require_confidence,
370
+ granularity: params.granularity,
371
+ });
372
+
373
+ // Auto-checkpoint: track recall
374
+ try {
375
+ const ids = results.map(r => r.engram.id);
376
+ await store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
377
+ } catch { /* non-fatal */ }
378
+
379
+ log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" → ${results.length} results`);
380
+
381
+ // Peer decisions: append recent decisions by other agents relevant to this query
382
+ const peerSuffix = coordDb
383
+ ? formatPeerDecisions(queryPeerDecisions(coordDb, AGENT_ID, queryText))
384
+ : '';
385
+
386
+ if (results.length === 0) {
387
+ return {
388
+ content: [{
389
+ type: 'text' as const,
390
+ text: 'No relevant memories found.' + peerSuffix,
391
+ }],
392
+ };
393
+ }
394
+
395
+ const lines = results.map((r, i) => {
396
+ // Confidence-adaptive output (Paper 3: cognitive teaming). When the caller
397
+ // requested 'compact' or 'auto' granularity, surface the engine-computed
398
+ // summary instead of the full content — same engram, less to read.
399
+ const body = r.summary ?? r.engram.content;
400
+ return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)}): ${body}`;
401
+ });
402
+
403
+ return {
404
+ content: [{
405
+ type: 'text' as const,
406
+ text: lines.join('\n') + peerSuffix,
407
+ }],
408
+ };
409
+ }
410
+ );
411
+
412
+ server.tool(
413
+ 'memory_feedback',
414
+ `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
415
+
416
+ Always call this after using a recalled memory so the system learns what's valuable.`,
417
+ {
418
+ engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
419
+ useful: z.boolean().describe('Was this memory actually helpful?'),
420
+ context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
421
+ },
422
+ async (params) => {
423
+ await store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
424
+
425
+ const engram = await store.getEngram(params.engram_id);
426
+ if (engram) {
427
+ const delta = params.useful
428
+ ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
429
+ : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
430
+ await store.updateConfidence(engram.id, engram.confidence + delta);
431
+ }
432
+
433
+ // Validation-gated Hebbian: resolve pending co-activation pairs for this engram
434
+ const hebbianUpdated = await activationEngine.resolveHebbianFeedback(params.engram_id, params.useful);
435
+
436
+ return {
437
+ content: [{
438
+ type: 'text' as const,
439
+ text: `Feedback: ${params.useful ? '+useful' : '-not useful'}${hebbianUpdated > 0 ? ` (${hebbianUpdated} association${hebbianUpdated > 1 ? 's' : ''} ${params.useful ? 'strengthened' : 'weakened'})` : ''}`,
440
+ }],
441
+ };
442
+ }
443
+ );
444
+
445
+ server.tool(
446
+ 'memory_retract',
447
+ `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
448
+
449
+ Use this when you discover a memory contains incorrect information.`,
450
+ {
451
+ engram_id: z.string().describe('ID of the wrong memory'),
452
+ reason: z.string().describe('Why is this memory wrong?'),
453
+ correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
454
+ },
455
+ async (params) => {
456
+ const result = await retractionEngine.retract({
457
+ agentId: AGENT_ID,
458
+ targetEngramId: params.engram_id,
459
+ reason: params.reason,
460
+ counterContent: params.correction,
461
+ });
462
+
463
+ const parts = [`Memory ${params.engram_id} retracted.`];
464
+ if (result.correctionId) {
465
+ parts.push(`Correction stored as ${result.correctionId}.`);
466
+ }
467
+ parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
468
+
469
+ return {
470
+ content: [{
471
+ type: 'text' as const,
472
+ text: parts.join(' '),
473
+ }],
474
+ };
475
+ }
476
+ );
477
+
478
+ server.tool(
479
+ 'memory_supersede',
480
+ `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.
481
+
482
+ Use this when:
483
+ - A status or count has changed (e.g., "5 reviews done" → "7 reviews done")
484
+ - Architecture or infrastructure evolved (e.g., "two-repo model" → "three-repo model")
485
+ - A schedule or plan was updated
486
+
487
+ The old memory stays in the database (searchable for history) but is heavily down-ranked in recall so the current version dominates.`,
488
+ {
489
+ old_engram_id: z.string().describe('ID of the outdated memory'),
490
+ new_engram_id: z.string().describe('ID of the replacement memory'),
491
+ reason: z.string().optional().describe('Why the old memory is outdated'),
492
+ },
493
+ async (params) => {
494
+ const oldEngram = await store.getEngram(params.old_engram_id);
495
+ if (!oldEngram) {
496
+ return { content: [{ type: 'text' as const, text: `Old memory not found: ${params.old_engram_id}` }] };
497
+ }
498
+ const newEngram = await store.getEngram(params.new_engram_id);
499
+ if (!newEngram) {
500
+ return { content: [{ type: 'text' as const, text: `New memory not found: ${params.new_engram_id}` }] };
501
+ }
502
+
503
+ await store.supersedeEngram(params.old_engram_id, params.new_engram_id);
504
+
505
+ // Create supersession association (new → old)
506
+ await store.upsertAssociation(params.new_engram_id, params.old_engram_id, 0.8, 'causal', 0.9);
507
+
508
+ // Reduce old memory's confidence (not to zero — it's historical, not wrong)
509
+ await store.updateConfidence(params.old_engram_id, Math.max(0.2, oldEngram.confidence * 0.4));
510
+
511
+ log(AGENT_ID, 'supersede', `"${oldEngram.concept}" → "${newEngram.concept}"${params.reason ? ` (${params.reason})` : ''}`);
512
+
513
+ return {
514
+ content: [{
515
+ type: 'text' as const,
516
+ text: `Superseded: "${oldEngram.concept}" → "${newEngram.concept}"`,
517
+ }],
518
+ };
519
+ }
520
+ );
521
+
522
+ server.tool(
523
+ 'memory_stats',
524
+ `Get memory health stats — how many memories, confidence levels, association count, and system performance.
525
+ Also shows the activity log path so the user can tail it to see what's happening.`,
526
+ {},
527
+ async () => {
528
+ const metrics = await evalEngine.computeMetrics(AGENT_ID);
529
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
530
+ const lines = [
531
+ `Agent: ${AGENT_ID}`,
532
+ `Active memories: ${metrics.activeEngramCount}`,
533
+ `Staging: ${metrics.stagingEngramCount}`,
534
+ `Retracted: ${metrics.retractedCount}`,
535
+ `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
536
+ `Total edges: ${metrics.totalEdges}`,
537
+ `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
538
+ `Activations (24h): ${metrics.activationCount}`,
539
+ `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
540
+ ``,
541
+ `Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
542
+ `Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
543
+ `Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
544
+ `Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
545
+ ``,
546
+ `Activity log: ${getLogPath() ?? 'not configured'}`,
547
+ `Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
548
+ ];
549
+
550
+ return {
551
+ content: [{
552
+ type: 'text' as const,
553
+ text: lines.join('\n'),
554
+ }],
555
+ };
556
+ }
557
+ );
558
+
559
+ // --- Checkpointing Tools ---
560
+
561
+ server.tool(
562
+ 'memory_checkpoint',
563
+ `Save your current execution state so you can recover after context compaction.
564
+
565
+ ALWAYS call this before:
566
+ - Long operations (multi-file generation, large refactors, overnight work)
567
+ - Anything that might fill the context window
568
+ - Switching to a different task
569
+
570
+ Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`,
571
+ {
572
+ current_task: z.string().describe('What you are currently working on'),
573
+ decisions: z.array(z.string()).optional().default([])
574
+ .describe('Key decisions made so far'),
575
+ active_files: z.array(z.string()).optional().default([])
576
+ .describe('Files you are currently working with'),
577
+ next_steps: z.array(z.string()).optional().default([])
578
+ .describe('What needs to happen next'),
579
+ related_memory_ids: z.array(z.string()).optional().default([])
580
+ .describe('IDs of memories relevant to current work'),
581
+ notes: z.string().optional().default('')
582
+ .describe('Any other context worth preserving'),
583
+ episode_id: z.string().optional()
584
+ .describe('Current episode ID if known'),
585
+ },
586
+ async (params) => {
587
+ const state: ConsciousState = {
588
+ currentTask: params.current_task,
589
+ decisions: params.decisions,
590
+ activeFiles: params.active_files,
591
+ nextSteps: params.next_steps,
592
+ relatedMemoryIds: params.related_memory_ids,
593
+ notes: params.notes,
594
+ episodeId: params.episode_id ?? null,
595
+ };
596
+
597
+ await store.saveCheckpoint(AGENT_ID, state);
598
+ log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
599
+
600
+ return {
601
+ content: [{
602
+ type: 'text' as const,
603
+ text: `Checkpoint saved: "${params.current_task}" (${params.decisions.length} decisions, ${params.active_files.length} files)`,
604
+ }],
605
+ };
606
+ }
607
+ );
608
+
609
+ server.tool(
610
+ 'memory_restore',
611
+ `Restore your previous execution state after context compaction or at session start.
612
+
613
+ Returns:
614
+ - Your saved execution state (task, decisions, next steps, files)
615
+ - Recently recalled memories for context
616
+ - Your last write for continuity
617
+ - How long you were idle
618
+
619
+ Use this at the start of every session or after compaction to pick up where you left off.`,
620
+ {},
621
+ async () => {
622
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
623
+
624
+ const now = Date.now();
625
+ const idleMs = checkpoint
626
+ ? now - checkpoint.auto.lastActivityAt.getTime()
627
+ : 0;
628
+
629
+ // Get last written engram
630
+ let lastWrite: { id: string; concept: string; content: string } | null = null;
631
+ if (checkpoint?.auto.lastWriteId) {
632
+ const engram = await store.getEngram(checkpoint.auto.lastWriteId);
633
+ if (engram) {
634
+ lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
635
+ }
636
+ }
637
+
638
+ // Recall memories using last context
639
+ let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
640
+ const recallContext = checkpoint?.auto.lastRecallContext
641
+ ?? checkpoint?.executionState?.currentTask
642
+ ?? null;
643
+
644
+ if (recallContext) {
645
+ try {
646
+ const results = await activationEngine.activate({
647
+ agentId: AGENT_ID,
648
+ context: recallContext,
649
+ limit: 5,
650
+ minScore: 0.05,
651
+ useReranker: true,
652
+ useExpansion: true,
653
+ workspace: process.env.AWM_WORKSPACE ?? undefined,
654
+ });
655
+ recalledMemories = results.map(r => ({
656
+ id: r.engram.id,
657
+ concept: r.engram.concept,
658
+ content: r.engram.content,
659
+ score: r.score,
660
+ }));
661
+ } catch { /* recall failure is non-fatal */ }
662
+ }
663
+
664
+ // Consolidation on restore:
665
+ // - If idle >5min but last consolidation was recent (graceful exit ran it), skip
666
+ // - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
667
+ const MINI_IDLE_MS = 5 * 60_000;
668
+ const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min if last consolidation was longer ago, run full
669
+ let miniConsolidationTriggered = false;
670
+ let fullConsolidationTriggered = false;
671
+
672
+ if (idleMs > MINI_IDLE_MS) {
673
+ const sinceLastConsolidation = checkpoint?.lastConsolidationAt
674
+ ? now - checkpoint.lastConsolidationAt.getTime()
675
+ : Infinity;
676
+
677
+ if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
678
+ // No recent consolidation — graceful exit didn't happen, run full cycle
679
+ fullConsolidationTriggered = true;
680
+ try {
681
+ const result = await consolidationEngine.consolidate(AGENT_ID);
682
+ await store.markConsolidation(AGENT_ID, false);
683
+ 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`);
684
+ } catch { /* consolidation failure is non-fatal */ }
685
+ } else {
686
+ // Recent consolidation exists — graceful exit already handled it, just do mini
687
+ miniConsolidationTriggered = true;
688
+ consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => {});
689
+ }
690
+ }
691
+
692
+ // Format response
693
+ const parts: string[] = [];
694
+ const idleMin = Math.round(idleMs / 60_000);
695
+ const consolidationNote = fullConsolidationTriggered
696
+ ? ' (full consolidation — no graceful exit detected)'
697
+ : miniConsolidationTriggered
698
+ ? ' (mini-consolidation triggered)'
699
+ : '';
700
+ log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
701
+ parts.push(`Idle: ${idleMin}min${consolidationNote}`);
702
+
703
+ if (checkpoint?.executionState) {
704
+ const s = checkpoint.executionState;
705
+ parts.push(`\n**Current task:** ${s.currentTask}`);
706
+ if (s.decisions.length) parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
707
+ if (s.nextSteps.length) parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
708
+ if (s.activeFiles.length) parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
709
+ if (s.notes) parts.push(`**Notes:** ${s.notes}`);
710
+ if (checkpoint.checkpointAt) parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
711
+ } else {
712
+ parts.push('\nNo explicit checkpoint saved.');
713
+ parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
714
+ }
715
+
716
+ if (lastWrite) {
717
+ parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
718
+ }
719
+
720
+ if (recalledMemories.length > 0) {
721
+ parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
722
+ for (const m of recalledMemories) {
723
+ parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
724
+ }
725
+ }
726
+
727
+ // Peer decisions: show recent decisions from other agents (last 30 min)
728
+ if (coordDb) {
729
+ try {
730
+ const myAgent = coordDb.prepare(
731
+ `SELECT id FROM coord_agents WHERE name = ? AND status != 'dead' ORDER BY last_seen DESC LIMIT 1`
732
+ ).get(AGENT_ID) as { id: string } | undefined;
733
+
734
+ const peerDecisions = coordDb.prepare(
735
+ `SELECT d.summary, a.name AS author_name, d.created_at
736
+ FROM coord_decisions d JOIN coord_agents a ON d.author_id = a.id
737
+ WHERE d.author_id != ? AND d.created_at > datetime('now', '-30 minutes')
738
+ ORDER BY d.created_at DESC LIMIT 10`
739
+ ).all(myAgent?.id ?? '') as Array<{ summary: string; author_name: string; created_at: string }>;
740
+
741
+ if (peerDecisions.length > 0) {
742
+ parts.push(`\n**Peer decisions (last 30 min):**`);
743
+ for (const d of peerDecisions) {
744
+ parts.push(`- [${d.author_name}] ${d.summary} (${d.created_at})`);
745
+ }
746
+ }
747
+ } catch { /* peer decisions are non-fatal */ }
748
+ }
749
+
750
+ return {
751
+ content: [{
752
+ type: 'text' as const,
753
+ text: parts.join('\n'),
754
+ }],
755
+ };
756
+ }
757
+ );
758
+
759
+ // --- Task Management Tools ---
760
+
761
+ server.tool(
762
+ 'memory_task_add',
763
+ `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
764
+
765
+ Use this when:
766
+ - You identify work that needs doing but can't do it right now
767
+ - The user mentions something to do later
768
+ - You want to park a sub-task while focusing on something more urgent
769
+
770
+ Tasks automatically get high salience so they won't be discarded.`,
771
+ {
772
+ concept: z.string().describe('Short task title (3-10 words)'),
773
+ content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
774
+ tags: z.array(z.string()).optional().describe('Tags for categorization'),
775
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
776
+ .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
777
+ blocked_by: z.string().optional().describe('ID of a task that must finish first'),
778
+ },
779
+ async (params) => {
780
+ const engram = await store.createEngram({
781
+ agentId: AGENT_ID,
782
+ concept: params.concept,
783
+ content: params.content,
784
+ tags: [...(params.tags ?? []), 'task'],
785
+ salience: 0.9, // Tasks always high salience
786
+ confidence: 0.8,
787
+ salienceFeatures: {
788
+ surprise: 0.5,
789
+ decisionMade: true,
790
+ causalDepth: 0.5,
791
+ resolutionEffort: 0.5,
792
+ eventType: 'decision',
793
+ },
794
+ reasonCodes: ['task-created'],
795
+ taskStatus: params.blocked_by ? 'blocked' : 'open',
796
+ taskPriority: params.priority as TaskPriority,
797
+ blockedBy: params.blocked_by,
798
+ });
799
+
800
+ connectionEngine.enqueue(engram.id);
801
+
802
+ // Generate embedding asynchronously
803
+ embed(`${params.concept} ${params.content}`).then(async vec => {
804
+ await store.updateEmbedding(engram.id, vec);
805
+ }).catch(() => {});
806
+
807
+ return {
808
+ content: [{
809
+ type: 'text' as const,
810
+ text: `Task created: "${params.concept}" (${params.priority})`,
811
+ }],
812
+ };
813
+ }
814
+ );
815
+
816
+ server.tool(
817
+ 'memory_task_update',
818
+ `Update a task's status or priority. Use this to:
819
+ - Start working on a task (open in_progress)
820
+ - Mark a task done (→ done)
821
+ - Block a task on another (→ blocked)
822
+ - Reprioritize (change priority)
823
+ - Unblock a task (clear blocked_by)`,
824
+ {
825
+ task_id: z.string().describe('ID of the task to update'),
826
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
827
+ .describe('New status'),
828
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
829
+ .describe('New priority'),
830
+ blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
831
+ },
832
+ async (params) => {
833
+ const engram = await store.getEngram(params.task_id);
834
+ if (!engram || !engram.taskStatus) {
835
+ return { content: [{ type: 'text' as const, text: `Task not found: ${params.task_id}` }] };
836
+ }
837
+
838
+ if (params.blocked_by !== undefined) {
839
+ await store.updateBlockedBy(params.task_id, params.blocked_by || null);
840
+ }
841
+ if (params.status) {
842
+ await store.updateTaskStatus(params.task_id, params.status as TaskStatus);
843
+ }
844
+ if (params.priority) {
845
+ await store.updateTaskPriority(params.task_id, params.priority as TaskPriority);
846
+ }
847
+
848
+ const updated = (await store.getEngram(params.task_id))!;
849
+ return {
850
+ content: [{
851
+ type: 'text' as const,
852
+ text: `Updated: "${updated.concept}" ${updated.taskStatus} (${updated.taskPriority})`,
853
+ }],
854
+ };
855
+ }
856
+ );
857
+
858
+ server.tool(
859
+ 'memory_task_list',
860
+ `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
861
+
862
+ Use at the start of a session to see what's pending, or to check blocked/done tasks.`,
863
+ {
864
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
865
+ .describe('Filter by status (omit to see all active tasks)'),
866
+ include_done: z.boolean().optional().default(false)
867
+ .describe('Include completed tasks?'),
868
+ },
869
+ async (params) => {
870
+ let tasks = await store.getTasks(AGENT_ID, params.status as TaskStatus | undefined);
871
+ if (!params.include_done && !params.status) {
872
+ tasks = tasks.filter(t => t.taskStatus !== 'done');
873
+ }
874
+
875
+ if (tasks.length === 0) {
876
+ return { content: [{ type: 'text' as const, text: 'No tasks found.' }] };
877
+ }
878
+
879
+ const lines = tasks.map((t, i) => {
880
+ const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
881
+ const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
882
+ 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}`;
883
+ });
884
+
885
+ return {
886
+ content: [{
887
+ type: 'text' as const,
888
+ text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
889
+ }],
890
+ };
891
+ }
892
+ );
893
+
894
+ server.tool(
895
+ 'memory_task_next',
896
+ `Get the single most important task to work on next.
897
+
898
+ Prioritizes: in_progress tasks first (finish what you started), then by priority level, then oldest first. Skips blocked and done tasks.
899
+
900
+ Use this when you finish a task or need to decide what to do next.`,
901
+ {},
902
+ async () => {
903
+ const next = await store.getNextTask(AGENT_ID);
904
+ if (!next) {
905
+ return { content: [{ type: 'text' as const, text: 'No actionable tasks. All clear!' }] };
906
+ }
907
+
908
+ const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
909
+ const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
910
+
911
+ return {
912
+ content: [{
913
+ type: 'text' as const,
914
+ text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
915
+ }],
916
+ };
917
+ }
918
+ );
919
+
920
+ // --- Task Bracket Tools ---
921
+
922
+ server.tool(
923
+ 'memory_task_begin',
924
+ `Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
925
+
926
+ CALL THIS when starting:
927
+ - A multi-step operation (doc generation, large refactor, migration)
928
+ - Work on a new topic or project area
929
+ - Anything that might fill the context window
930
+
931
+ This ensures your state is saved before you start, and primes recall with relevant context.`,
932
+ {
933
+ topic: z.string().describe('What task are you starting? (3-15 words)'),
934
+ files: z.array(z.string()).optional().default([])
935
+ .describe('Files you expect to work with'),
936
+ notes: z.string().optional().default('')
937
+ .describe('Any additional context'),
938
+ },
939
+ async (params) => {
940
+ // 1. Checkpoint current state
941
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
942
+ const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
943
+
944
+ await store.saveCheckpoint(AGENT_ID, {
945
+ currentTask: params.topic,
946
+ decisions: [],
947
+ activeFiles: params.files,
948
+ nextSteps: [],
949
+ relatedMemoryIds: [],
950
+ notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
951
+ episodeId: null,
952
+ });
953
+
954
+ // 2. Auto-recall relevant memories
955
+ let recalledSummary = '';
956
+ try {
957
+ const results = await activationEngine.activate({
958
+ agentId: AGENT_ID,
959
+ context: params.topic,
960
+ limit: 5,
961
+ minScore: 0.05,
962
+ useReranker: true,
963
+ useExpansion: true,
964
+ workspace: process.env.AWM_WORKSPACE ?? undefined,
965
+ });
966
+
967
+ if (results.length > 0) {
968
+ const lines = results.map((r, i) => {
969
+ const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
970
+ return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
971
+ });
972
+ recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
973
+
974
+ // Track recall
975
+ await store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
976
+ }
977
+ } catch { /* recall failure is non-fatal */ }
978
+
979
+ log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
980
+
981
+ return {
982
+ content: [{
983
+ type: 'text' as const,
984
+ text: `Started: "${params.topic}" (prev: ${prevTask})${recalledSummary}`,
985
+ }],
986
+ };
987
+ }
988
+ );
989
+
990
+ server.tool(
991
+ 'memory_task_end',
992
+ `Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
993
+
994
+ CALL THIS when you finish:
995
+ - A multi-step operation
996
+ - Before switching to a different topic
997
+ - At the end of a work session
998
+
999
+ This captures what was accomplished so future sessions can recall it.`,
1000
+ {
1001
+ summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
1002
+ tags: z.array(z.string()).optional().default([])
1003
+ .describe('Tags for the summary memory'),
1004
+ supersedes: z.array(z.string()).optional().default([])
1005
+ .describe('IDs of older memories this task summary replaces (marks them as superseded)'),
1006
+ },
1007
+ async (params) => {
1008
+ // 1. Write summary as a memory
1009
+ const salience = evaluateSalience({
1010
+ content: params.summary,
1011
+ eventType: 'decision',
1012
+ surprise: 0.3,
1013
+ decisionMade: true,
1014
+ causalDepth: 0.5,
1015
+ resolutionEffort: 0.5,
1016
+ });
1017
+
1018
+ // Determine the real task name for the summary engram
1019
+ const checkpoint = await store.getCheckpoint(AGENT_ID);
1020
+ const rawTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
1021
+ // Strip any "Completed: " prefixes to avoid cascading
1022
+ const cleanedTask = rawTask.replace(/^(Completed: )+/, '');
1023
+ // Don't use auto-checkpoint or already-completed tasks as real task names
1024
+ const isNamedTask = !cleanedTask.startsWith('Auto-checkpoint') && cleanedTask !== 'Unknown task';
1025
+ const completedTask = isNamedTask
1026
+ ? cleanedTask
1027
+ : params.summary.slice(0, 60).replace(/\n/g, ' ');
1028
+
1029
+ const engram = await store.createEngram({
1030
+ agentId: AGENT_ID,
1031
+ concept: completedTask.slice(0, 80),
1032
+ content: params.summary,
1033
+ tags: [...params.tags, 'task-summary'],
1034
+ salience: isNamedTask ? Math.max(salience.score, 0.7) : salience.score, // Only floor salience for named tasks
1035
+ confidence: 0.65, // Task summaries are decision-grade (completed work)
1036
+ salienceFeatures: salience.features,
1037
+ reasonCodes: [...salience.reasonCodes, 'task-end'],
1038
+ });
1039
+
1040
+ connectionEngine.enqueue(engram.id);
1041
+
1042
+ // 2. Handle supersessions — mark old memories as outdated
1043
+ let supersededCount = 0;
1044
+ for (const oldId of params.supersedes) {
1045
+ const oldEngram = await store.getEngram(oldId);
1046
+ if (oldEngram) {
1047
+ await store.supersedeEngram(oldId, engram.id);
1048
+ await store.upsertAssociation(engram.id, oldId, 0.8, 'causal', 0.9);
1049
+ await store.updateConfidence(oldId, Math.max(0.2, oldEngram.confidence * 0.4));
1050
+ supersededCount++;
1051
+ }
1052
+ }
1053
+
1054
+ // Generate embedding asynchronously
1055
+ embed(`Task completed: ${params.summary}`).then(async vec => {
1056
+ await store.updateEmbedding(engram.id, vec);
1057
+ }).catch(() => {});
1058
+
1059
+ // 2. Update checkpoint to reflect completion
1060
+ await store.saveCheckpoint(AGENT_ID, {
1061
+ currentTask: `Completed: ${completedTask}`,
1062
+ decisions: checkpoint?.executionState?.decisions ?? [],
1063
+ activeFiles: [],
1064
+ nextSteps: [],
1065
+ relatedMemoryIds: [engram.id],
1066
+ notes: `Task completed. Summary memory: ${engram.id}`,
1067
+ episodeId: null,
1068
+ });
1069
+
1070
+ await store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
1071
+ log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)} superseded=${supersededCount}`);
1072
+
1073
+ const supersededNote = supersededCount > 0 ? ` (${supersededCount} old memories superseded)` : '';
1074
+ return {
1075
+ content: [{
1076
+ type: 'text' as const,
1077
+ text: `Completed: "${completedTask}" [${salience.score.toFixed(2)}]${supersededNote}`,
1078
+ }],
1079
+ };
1080
+ }
1081
+ );
1082
+
1083
+ // --- Start ---
1084
+
1085
+ async function main() {
1086
+ const transport = new StdioServerTransport();
1087
+ await server.connect(transport);
1088
+
1089
+ // Start hook sidecar (lightweight HTTP for Claude Code hooks)
1090
+ const sidecar = startSidecar({
1091
+ store,
1092
+ agentId: AGENT_ID,
1093
+ secret: HOOK_SECRET,
1094
+ port: HOOK_PORT,
1095
+ onConsolidate: async (agentId, reason) => {
1096
+ console.error(`[mcp] consolidation triggered: ${reason}`);
1097
+ const result = await consolidationEngine.consolidate(agentId);
1098
+ await store.markConsolidation(agentId, false);
1099
+ console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
1100
+ },
1101
+ });
1102
+
1103
+ // Coordination MCP tools (opt-in via AWM_COORDINATION=true)
1104
+ // AWM 0.8.x: coordination requires SQLite (uses store.getDb()). On PGlite,
1105
+ // coordination is auto-disabled with a warning; re-enable when coordination
1106
+ // is ported to async/PGlite.
1107
+ const coordRequested = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
1108
+ const coordEnabled = coordRequested && BACKEND === 'sqlite';
1109
+ if (coordEnabled) {
1110
+ const { initCoordinationTables } = await import('./coordination/schema.js');
1111
+ const { registerCoordinationTools } = await import('./coordination/mcp-tools.js');
1112
+ const sqliteStore = store as unknown as EngramStore;
1113
+ initCoordinationTables(sqliteStore.getDb());
1114
+ registerCoordinationTools(server, sqliteStore.getDb());
1115
+ coordDb = sqliteStore.getDb();
1116
+ } else if (coordRequested && BACKEND === 'pglite') {
1117
+ console.error('AWM: coordination requested but disabled — coordination plugin requires SQLite backend');
1118
+ } else {
1119
+ console.error('AWM: coordination tools disabled (set AWM_COORDINATION=true to enable)');
1120
+ }
1121
+
1122
+ // Log to stderr (stdout is reserved for MCP protocol)
1123
+ console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
1124
+ console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
1125
+
1126
+ // Clean shutdown
1127
+ const cleanup = async () => {
1128
+ sidecar.close();
1129
+ consolidationScheduler.stop();
1130
+ stagingBuffer.stop();
1131
+ if (BACKEND === 'sqlite') {
1132
+ try { (store as Partial<EngramStore>).walCheckpoint?.(); } catch { /* non-fatal */ }
1133
+ }
1134
+ try { await (store as any).close?.(); } catch { /* best-effort */ }
1135
+ };
1136
+ process.on('SIGINT', () => { void cleanup().finally(() => process.exit(0)); });
1137
+ process.on('SIGTERM', () => { void cleanup().finally(() => process.exit(0)); });
1138
+ }
1139
+
1140
+ main().catch(err => {
1141
+ console.error('MCP server failed:', err);
1142
+ process.exit(1);
1143
+ });
1144
+
1145
+ } // end else (non-incognito)