agent-working-memory 0.3.2 → 0.4.1

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.
package/dist/mcp.js CHANGED
@@ -52,257 +52,307 @@ import { RetractionEngine } from './engine/retraction.js';
52
52
  import { EvalEngine } from './engine/eval.js';
53
53
  import { ConsolidationEngine } from './engine/consolidation.js';
54
54
  import { ConsolidationScheduler } from './engine/consolidation-scheduler.js';
55
- import { evaluateSalience } from './core/salience.js';
55
+ import { evaluateSalience, computeNovelty } from './core/salience.js';
56
56
  import { DEFAULT_AGENT_CONFIG } from './types/agent.js';
57
57
  import { embed } from './core/embeddings.js';
58
- // --- Setup ---
59
- const DB_PATH = process.env.AWM_DB_PATH ?? 'memory.db';
60
- const AGENT_ID = process.env.AWM_AGENT_ID ?? 'claude-code';
61
- const store = new EngramStore(DB_PATH);
62
- const activationEngine = new ActivationEngine(store);
63
- const connectionEngine = new ConnectionEngine(store, activationEngine);
64
- const stagingBuffer = new StagingBuffer(store, activationEngine);
65
- const evictionEngine = new EvictionEngine(store);
66
- const retractionEngine = new RetractionEngine(store);
67
- const evalEngine = new EvalEngine(store);
68
- const consolidationEngine = new ConsolidationEngine(store);
69
- const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
70
- stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
71
- consolidationScheduler.start();
72
- const server = new McpServer({
73
- name: 'agent-working-memory',
74
- version: '0.3.0',
75
- });
76
- // --- Tools ---
77
- server.tool('memory_write', `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
58
+ import { startSidecar } from './hooks/sidecar.js';
59
+ import { initLogger, log, getLogPath } from './core/logger.js';
60
+ // --- Incognito Mode ---
61
+ // When AWM_INCOGNITO=1, register zero tools. Claude won't see memory tools at all.
62
+ // No DB, no engines, no sidecar — just a bare MCP server that exposes nothing.
63
+ const INCOGNITO = process.env.AWM_INCOGNITO === '1' || process.env.AWM_INCOGNITO === 'true';
64
+ if (INCOGNITO) {
65
+ console.error('AWM: incognito mode all memory tools disabled, nothing will be recorded');
66
+ const server = new McpServer({ name: 'agent-working-memory', version: '0.4.0' });
67
+ const transport = new StdioServerTransport();
68
+ server.connect(transport).catch(err => {
69
+ console.error('MCP server failed:', err);
70
+ process.exit(1);
71
+ });
72
+ // No tools registered — Claude won't see any memory_* tools
73
+ }
74
+ else {
75
+ // --- Setup ---
76
+ const DB_PATH = process.env.AWM_DB_PATH ?? 'memory.db';
77
+ const AGENT_ID = process.env.AWM_AGENT_ID ?? 'claude-code';
78
+ const HOOK_PORT = parseInt(process.env.AWM_HOOK_PORT ?? '8401', 10);
79
+ const HOOK_SECRET = process.env.AWM_HOOK_SECRET ?? null;
80
+ initLogger(DB_PATH);
81
+ log(AGENT_ID, 'startup', `MCP server starting (db: ${DB_PATH}, hooks: ${HOOK_PORT})`);
82
+ const store = new EngramStore(DB_PATH);
83
+ const activationEngine = new ActivationEngine(store);
84
+ const connectionEngine = new ConnectionEngine(store, activationEngine);
85
+ const stagingBuffer = new StagingBuffer(store, activationEngine);
86
+ const evictionEngine = new EvictionEngine(store);
87
+ const retractionEngine = new RetractionEngine(store);
88
+ const evalEngine = new EvalEngine(store);
89
+ const consolidationEngine = new ConsolidationEngine(store);
90
+ const consolidationScheduler = new ConsolidationScheduler(store, consolidationEngine);
91
+ stagingBuffer.start(DEFAULT_AGENT_CONFIG.stagingTtlMs);
92
+ consolidationScheduler.start();
93
+ const server = new McpServer({
94
+ name: 'agent-working-memory',
95
+ version: '0.4.0',
96
+ });
97
+ // --- Tools ---
98
+ server.tool('memory_write', `Store a memory. The salience filter decides whether it's worth keeping (active), needs more evidence (staging), or should be discarded.
78
99
 
79
- Use this when you learn something that might be useful later:
80
- - Discoveries about the codebase, bugs, or architecture
81
- - Decisions you made and why
82
- - Errors encountered and how they were resolved
83
- - User preferences or project patterns
100
+ CALL THIS PROACTIVELY do not wait to be asked. Write memories when you:
101
+ - Discover something about the codebase, bugs, or architecture
102
+ - Make a decision and want to remember why
103
+ - Encounter and resolve an error
104
+ - Learn a user preference or project pattern
105
+ - Complete a significant piece of work
84
106
 
85
107
  The concept should be a short label (3-8 words). The content should be the full detail.`, {
86
- concept: z.string().describe('Short label for this memory (3-8 words)'),
87
- content: z.string().describe('Full detail of what was learned'),
88
- tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
89
- event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
90
- .optional().default('observation')
91
- .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
92
- surprise: z.number().min(0).max(1).optional().default(0.3)
93
- .describe('How surprising was this? 0=expected, 1=very unexpected'),
94
- decision_made: z.boolean().optional().default(false)
95
- .describe('Was a decision made? True boosts importance'),
96
- causal_depth: z.number().min(0).max(1).optional().default(0.3)
97
- .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
98
- resolution_effort: z.number().min(0).max(1).optional().default(0.3)
99
- .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
100
- }, async (params) => {
101
- const salience = evaluateSalience({
102
- content: params.content,
103
- eventType: params.event_type,
104
- surprise: params.surprise,
105
- decisionMade: params.decision_made,
106
- causalDepth: params.causal_depth,
107
- resolutionEffort: params.resolution_effort,
108
- });
109
- if (salience.disposition === 'discard') {
108
+ concept: z.string().describe('Short label for this memory (3-8 words)'),
109
+ content: z.string().describe('Full detail of what was learned'),
110
+ tags: z.array(z.string()).optional().describe('Optional tags for categorization'),
111
+ event_type: z.enum(['observation', 'decision', 'friction', 'surprise', 'causal'])
112
+ .optional().default('observation')
113
+ .describe('Type of event: observation (default), decision, friction (error/blocker), surprise, causal (root cause)'),
114
+ surprise: z.number().min(0).max(1).optional().default(0.3)
115
+ .describe('How surprising was this? 0=expected, 1=very unexpected'),
116
+ decision_made: z.boolean().optional().default(false)
117
+ .describe('Was a decision made? True boosts importance'),
118
+ causal_depth: z.number().min(0).max(1).optional().default(0.3)
119
+ .describe('How deep is the causal understanding? 0=surface, 1=root cause'),
120
+ resolution_effort: z.number().min(0).max(1).optional().default(0.3)
121
+ .describe('How much effort to resolve? 0=trivial, 1=significant debugging'),
122
+ }, async (params) => {
123
+ // Check novelty — is this new information or a duplicate?
124
+ const novelty = computeNovelty(store, AGENT_ID, params.concept, params.content);
125
+ const salience = evaluateSalience({
126
+ content: params.content,
127
+ eventType: params.event_type,
128
+ surprise: params.surprise,
129
+ decisionMade: params.decision_made,
130
+ causalDepth: params.causal_depth,
131
+ resolutionEffort: params.resolution_effort,
132
+ novelty,
133
+ });
134
+ if (salience.disposition === 'discard') {
135
+ log(AGENT_ID, 'write:discard', `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)}`);
136
+ return {
137
+ content: [{
138
+ type: 'text',
139
+ text: `Discarded (salience ${salience.score.toFixed(2)}, novelty ${novelty.toFixed(1)})`,
140
+ }],
141
+ };
142
+ }
143
+ const engram = store.createEngram({
144
+ agentId: AGENT_ID,
145
+ concept: params.concept,
146
+ content: params.content,
147
+ tags: params.tags,
148
+ salience: salience.score,
149
+ salienceFeatures: salience.features,
150
+ reasonCodes: salience.reasonCodes,
151
+ ttl: salience.disposition === 'staging' ? DEFAULT_AGENT_CONFIG.stagingTtlMs : undefined,
152
+ });
153
+ if (salience.disposition === 'staging') {
154
+ store.updateStage(engram.id, 'staging');
155
+ }
156
+ else {
157
+ connectionEngine.enqueue(engram.id);
158
+ }
159
+ // Generate embedding asynchronously (don't block response)
160
+ embed(`${params.concept} ${params.content}`).then(vec => {
161
+ store.updateEmbedding(engram.id, vec);
162
+ }).catch(() => { }); // Embedding failure is non-fatal
163
+ // Auto-checkpoint: track write
164
+ try {
165
+ store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
166
+ }
167
+ catch { /* non-fatal */ }
168
+ log(AGENT_ID, `write:${salience.disposition}`, `"${params.concept}" salience=${salience.score.toFixed(2)} novelty=${novelty.toFixed(1)} id=${engram.id}`);
110
169
  return {
111
170
  content: [{
112
171
  type: 'text',
113
- text: `Memory discarded (salience ${salience.score.toFixed(2)} below threshold). Not worth storing.`,
172
+ text: `Stored (${salience.disposition}) "${params.concept}" [${salience.score.toFixed(2)}]`,
114
173
  }],
115
174
  };
116
- }
117
- const engram = store.createEngram({
118
- agentId: AGENT_ID,
119
- concept: params.concept,
120
- content: params.content,
121
- tags: params.tags,
122
- salience: salience.score,
123
- salienceFeatures: salience.features,
124
- reasonCodes: salience.reasonCodes,
125
- ttl: salience.disposition === 'staging' ? DEFAULT_AGENT_CONFIG.stagingTtlMs : undefined,
126
175
  });
127
- if (salience.disposition === 'staging') {
128
- store.updateStage(engram.id, 'staging');
129
- }
130
- else {
131
- connectionEngine.enqueue(engram.id);
132
- }
133
- // Generate embedding asynchronously (don't block response)
134
- embed(`${params.concept} ${params.content}`).then(vec => {
135
- store.updateEmbedding(engram.id, vec);
136
- }).catch(() => { }); // Embedding failure is non-fatal
137
- // Auto-checkpoint: track write
138
- try {
139
- store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
140
- }
141
- catch { /* non-fatal */ }
142
- return {
143
- content: [{
144
- type: 'text',
145
- text: `Memory stored (${salience.disposition}). ID: ${engram.id}\nConcept: ${params.concept}\nSalience: ${salience.score.toFixed(2)}`,
146
- }],
147
- };
148
- });
149
- server.tool('memory_recall', `Recall memories relevant to a context. Uses cognitive activation — not keyword search.
176
+ server.tool('memory_recall', `Recall memories relevant to a query. Uses cognitive activation — not keyword search.
150
177
 
151
- Use this when you need to remember something:
152
- - Starting a new task (recall relevant past experience)
178
+ ALWAYS call this when:
179
+ - Starting work on a project or topic (recall what you know)
153
180
  - Debugging (recall similar errors and solutions)
154
181
  - Making decisions (recall past decisions and outcomes)
182
+ - The user mentions a topic you might have stored memories about
155
183
 
156
- Returns the most relevant memories ranked by a composite score of text relevance, temporal recency, and associative strength.`, {
157
- context: z.string().describe('What are you thinking about? Describe the current situation or question'),
158
- limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
159
- min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
160
- include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
161
- use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
162
- use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
163
- }, async (params) => {
164
- const results = await activationEngine.activate({
165
- agentId: AGENT_ID,
166
- context: params.context,
167
- limit: params.limit,
168
- minScore: params.min_score,
169
- includeStaging: params.include_staging,
170
- useReranker: params.use_reranker,
171
- useExpansion: params.use_expansion,
172
- });
173
- // Auto-checkpoint: track recall
174
- try {
175
- const ids = results.map(r => r.engram.id);
176
- store.updateAutoCheckpointRecall(AGENT_ID, params.context, ids);
177
- }
178
- catch { /* non-fatal */ }
179
- if (results.length === 0) {
184
+ Accepts either "query" or "context" parameter both work identically.
185
+ Returns the most relevant memories ranked by text relevance, temporal recency, and associative strength.`, {
186
+ query: z.string().optional().describe('What to search for — describe the situation, question, or topic'),
187
+ context: z.string().optional().describe('Alias for query (either works)'),
188
+ limit: z.number().optional().default(5).describe('Max memories to return (default 5)'),
189
+ min_score: z.number().optional().default(0.05).describe('Minimum relevance score (default 0.05)'),
190
+ include_staging: z.boolean().optional().default(false).describe('Include weak/unconfirmed memories?'),
191
+ use_reranker: z.boolean().optional().default(true).describe('Use cross-encoder re-ranking for better relevance (default true)'),
192
+ use_expansion: z.boolean().optional().default(true).describe('Expand query with synonyms for better recall (default true)'),
193
+ }, async (params) => {
194
+ const queryText = params.query ?? params.context;
195
+ if (!queryText) {
196
+ return {
197
+ content: [{
198
+ type: 'text',
199
+ text: 'Error: provide either "query" or "context" parameter with your search text.',
200
+ }],
201
+ };
202
+ }
203
+ const results = await activationEngine.activate({
204
+ agentId: AGENT_ID,
205
+ context: queryText,
206
+ limit: params.limit,
207
+ minScore: params.min_score,
208
+ includeStaging: params.include_staging,
209
+ useReranker: params.use_reranker,
210
+ useExpansion: params.use_expansion,
211
+ });
212
+ // Auto-checkpoint: track recall
213
+ try {
214
+ const ids = results.map(r => r.engram.id);
215
+ store.updateAutoCheckpointRecall(AGENT_ID, queryText, ids);
216
+ }
217
+ catch { /* non-fatal */ }
218
+ log(AGENT_ID, 'recall', `"${queryText.slice(0, 80)}" → ${results.length} results`);
219
+ if (results.length === 0) {
220
+ return {
221
+ content: [{
222
+ type: 'text',
223
+ text: 'No relevant memories found.',
224
+ }],
225
+ };
226
+ }
227
+ const lines = results.map((r, i) => {
228
+ return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)}): ${r.engram.content}`;
229
+ });
180
230
  return {
181
231
  content: [{
182
232
  type: 'text',
183
- text: 'No relevant memories found.',
233
+ text: lines.join('\n'),
184
234
  }],
185
235
  };
186
- }
187
- const lines = results.map((r, i) => {
188
- const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
189
- return `${i + 1}. **${r.engram.concept}** (score: ${r.score.toFixed(3)})${tags}\n ${r.engram.content}\n _${r.why}_\n ID: ${r.engram.id}`;
190
236
  });
191
- return {
192
- content: [{
193
- type: 'text',
194
- text: `Recalled ${results.length} memories:\n\n${lines.join('\n\n')}`,
195
- }],
196
- };
197
- });
198
- server.tool('memory_feedback', `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
237
+ server.tool('memory_feedback', `Report whether a recalled memory was actually useful. This updates the memory's confidence score — useful memories become stronger, useless ones weaken.
199
238
 
200
239
  Always call this after using a recalled memory so the system learns what's valuable.`, {
201
- engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
202
- useful: z.boolean().describe('Was this memory actually helpful?'),
203
- context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
204
- }, async (params) => {
205
- store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
206
- const engram = store.getEngram(params.engram_id);
207
- if (engram) {
208
- const delta = params.useful
209
- ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
210
- : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
211
- store.updateConfidence(engram.id, engram.confidence + delta);
212
- }
213
- return {
214
- content: [{
215
- type: 'text',
216
- text: `Feedback recorded: ${params.useful ? 'useful' : 'not useful'}. Confidence ${params.useful ? 'increased' : 'decreased'}.`,
217
- }],
218
- };
219
- });
220
- server.tool('memory_retract', `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
240
+ engram_id: z.string().describe('ID of the memory (from memory_recall results)'),
241
+ useful: z.boolean().describe('Was this memory actually helpful?'),
242
+ context: z.string().optional().describe('Brief note on why it was/wasn\'t useful'),
243
+ }, async (params) => {
244
+ store.logRetrievalFeedback(null, params.engram_id, params.useful, params.context ?? '');
245
+ const engram = store.getEngram(params.engram_id);
246
+ if (engram) {
247
+ const delta = params.useful
248
+ ? DEFAULT_AGENT_CONFIG.feedbackPositiveBoost
249
+ : -DEFAULT_AGENT_CONFIG.feedbackNegativePenalty;
250
+ store.updateConfidence(engram.id, engram.confidence + delta);
251
+ }
252
+ return {
253
+ content: [{
254
+ type: 'text',
255
+ text: `Feedback: ${params.useful ? '+useful' : '-not useful'}`,
256
+ }],
257
+ };
258
+ });
259
+ server.tool('memory_retract', `Retract a memory that turned out to be wrong. Creates a correction and reduces confidence of related memories.
221
260
 
222
261
  Use this when you discover a memory contains incorrect information.`, {
223
- engram_id: z.string().describe('ID of the wrong memory'),
224
- reason: z.string().describe('Why is this memory wrong?'),
225
- correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
226
- }, async (params) => {
227
- const result = retractionEngine.retract({
228
- agentId: AGENT_ID,
229
- targetEngramId: params.engram_id,
230
- reason: params.reason,
231
- counterContent: params.correction,
262
+ engram_id: z.string().describe('ID of the wrong memory'),
263
+ reason: z.string().describe('Why is this memory wrong?'),
264
+ correction: z.string().optional().describe('What is the correct information? (creates a new memory)'),
265
+ }, async (params) => {
266
+ const result = retractionEngine.retract({
267
+ agentId: AGENT_ID,
268
+ targetEngramId: params.engram_id,
269
+ reason: params.reason,
270
+ counterContent: params.correction,
271
+ });
272
+ const parts = [`Memory ${params.engram_id} retracted.`];
273
+ if (result.correctionId) {
274
+ parts.push(`Correction stored as ${result.correctionId}.`);
275
+ }
276
+ parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
277
+ return {
278
+ content: [{
279
+ type: 'text',
280
+ text: parts.join(' '),
281
+ }],
282
+ };
232
283
  });
233
- const parts = [`Memory ${params.engram_id} retracted.`];
234
- if (result.correctionId) {
235
- parts.push(`Correction stored as ${result.correctionId}.`);
236
- }
237
- parts.push(`${result.associatesAffected} related memories had confidence reduced.`);
238
- return {
239
- content: [{
240
- type: 'text',
241
- text: parts.join(' '),
242
- }],
243
- };
244
- });
245
- server.tool('memory_stats', `Get memory health stats — how many memories, confidence levels, association count, and system performance.`, {}, async () => {
246
- const metrics = evalEngine.computeMetrics(AGENT_ID);
247
- const lines = [
248
- `Agent: ${AGENT_ID}`,
249
- `Active memories: ${metrics.activeEngramCount}`,
250
- `Staging: ${metrics.stagingEngramCount}`,
251
- `Retracted: ${metrics.retractedCount}`,
252
- `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
253
- `Total edges: ${metrics.totalEdges}`,
254
- `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
255
- `Activations (24h): ${metrics.activationCount}`,
256
- `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
257
- ];
258
- return {
259
- content: [{
260
- type: 'text',
261
- text: lines.join('\n'),
262
- }],
263
- };
264
- });
265
- // --- Checkpointing Tools ---
266
- server.tool('memory_checkpoint', `Save your current execution state so you can recover after context compaction.
284
+ server.tool('memory_stats', `Get memory health stats — how many memories, confidence levels, association count, and system performance.
285
+ Also shows the activity log path so the user can tail it to see what's happening.`, {}, async () => {
286
+ const metrics = evalEngine.computeMetrics(AGENT_ID);
287
+ const checkpoint = store.getCheckpoint(AGENT_ID);
288
+ const lines = [
289
+ `Agent: ${AGENT_ID}`,
290
+ `Active memories: ${metrics.activeEngramCount}`,
291
+ `Staging: ${metrics.stagingEngramCount}`,
292
+ `Retracted: ${metrics.retractedCount}`,
293
+ `Avg confidence: ${metrics.avgConfidence.toFixed(3)}`,
294
+ `Total edges: ${metrics.totalEdges}`,
295
+ `Edge utility: ${(metrics.edgeUtilityRate * 100).toFixed(1)}%`,
296
+ `Activations (24h): ${metrics.activationCount}`,
297
+ `Avg latency: ${metrics.avgLatencyMs.toFixed(1)}ms`,
298
+ ``,
299
+ `Session writes: ${checkpoint?.auto.writeCountSinceConsolidation ?? 0}`,
300
+ `Session recalls: ${checkpoint?.auto.recallCountSinceConsolidation ?? 0}`,
301
+ `Last activity: ${checkpoint?.auto.lastActivityAt?.toISOString() ?? 'never'}`,
302
+ `Checkpoint: ${checkpoint?.executionState ? checkpoint.executionState.currentTask : 'none'}`,
303
+ ``,
304
+ `Activity log: ${getLogPath() ?? 'not configured'}`,
305
+ `Hook sidecar: 127.0.0.1:${HOOK_PORT}`,
306
+ ];
307
+ return {
308
+ content: [{
309
+ type: 'text',
310
+ text: lines.join('\n'),
311
+ }],
312
+ };
313
+ });
314
+ // --- Checkpointing Tools ---
315
+ server.tool('memory_checkpoint', `Save your current execution state so you can recover after context compaction.
267
316
 
268
- Use this when:
269
- - You're about to do something that might fill the context window
270
- - You've made important decisions you don't want to lose
271
- - You want to preserve your working state before a long operation
317
+ ALWAYS call this before:
318
+ - Long operations (multi-file generation, large refactors, overnight work)
319
+ - Anything that might fill the context window
320
+ - Switching to a different task
272
321
 
273
- The state is saved per-agent and overwrites any previous checkpoint.`, {
274
- current_task: z.string().describe('What you are currently working on'),
275
- decisions: z.array(z.string()).optional().default([])
276
- .describe('Key decisions made so far'),
277
- active_files: z.array(z.string()).optional().default([])
278
- .describe('Files you are currently working with'),
279
- next_steps: z.array(z.string()).optional().default([])
280
- .describe('What needs to happen next'),
281
- related_memory_ids: z.array(z.string()).optional().default([])
282
- .describe('IDs of memories relevant to current work'),
283
- notes: z.string().optional().default('')
284
- .describe('Any other context worth preserving'),
285
- episode_id: z.string().optional()
286
- .describe('Current episode ID if known'),
287
- }, async (params) => {
288
- const state = {
289
- currentTask: params.current_task,
290
- decisions: params.decisions,
291
- activeFiles: params.active_files,
292
- nextSteps: params.next_steps,
293
- relatedMemoryIds: params.related_memory_ids,
294
- notes: params.notes,
295
- episodeId: params.episode_id ?? null,
296
- };
297
- store.saveCheckpoint(AGENT_ID, state);
298
- return {
299
- content: [{
300
- type: 'text',
301
- text: `Checkpoint saved.\nTask: ${params.current_task}\nDecisions: ${params.decisions.length}\nNext steps: ${params.next_steps.length}\nFiles: ${params.active_files.length}`,
302
- }],
303
- };
304
- });
305
- server.tool('memory_restore', `Restore your previous execution state after context compaction or at session start.
322
+ Also call periodically during long sessions to avoid losing state. The state is saved per-agent and overwrites any previous checkpoint.`, {
323
+ current_task: z.string().describe('What you are currently working on'),
324
+ decisions: z.array(z.string()).optional().default([])
325
+ .describe('Key decisions made so far'),
326
+ active_files: z.array(z.string()).optional().default([])
327
+ .describe('Files you are currently working with'),
328
+ next_steps: z.array(z.string()).optional().default([])
329
+ .describe('What needs to happen next'),
330
+ related_memory_ids: z.array(z.string()).optional().default([])
331
+ .describe('IDs of memories relevant to current work'),
332
+ notes: z.string().optional().default('')
333
+ .describe('Any other context worth preserving'),
334
+ episode_id: z.string().optional()
335
+ .describe('Current episode ID if known'),
336
+ }, async (params) => {
337
+ const state = {
338
+ currentTask: params.current_task,
339
+ decisions: params.decisions,
340
+ activeFiles: params.active_files,
341
+ nextSteps: params.next_steps,
342
+ relatedMemoryIds: params.related_memory_ids,
343
+ notes: params.notes,
344
+ episodeId: params.episode_id ?? null,
345
+ };
346
+ store.saveCheckpoint(AGENT_ID, state);
347
+ log(AGENT_ID, 'checkpoint', `"${params.current_task}" decisions=${params.decisions.length} files=${params.active_files.length}`);
348
+ return {
349
+ content: [{
350
+ type: 'text',
351
+ text: `Checkpoint saved: "${params.current_task}" (${params.decisions.length} decisions, ${params.active_files.length} files)`,
352
+ }],
353
+ };
354
+ });
355
+ server.tool('memory_restore', `Restore your previous execution state after context compaction or at session start.
306
356
 
307
357
  Returns:
308
358
  - Your saved execution state (task, decisions, next steps, files)
@@ -311,89 +361,116 @@ Returns:
311
361
  - How long you were idle
312
362
 
313
363
  Use this at the start of every session or after compaction to pick up where you left off.`, {}, async () => {
314
- const checkpoint = store.getCheckpoint(AGENT_ID);
315
- const now = Date.now();
316
- const idleMs = checkpoint
317
- ? now - checkpoint.auto.lastActivityAt.getTime()
318
- : 0;
319
- // Get last written engram
320
- let lastWrite = null;
321
- if (checkpoint?.auto.lastWriteId) {
322
- const engram = store.getEngram(checkpoint.auto.lastWriteId);
323
- if (engram) {
324
- lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
364
+ const checkpoint = store.getCheckpoint(AGENT_ID);
365
+ const now = Date.now();
366
+ const idleMs = checkpoint
367
+ ? now - checkpoint.auto.lastActivityAt.getTime()
368
+ : 0;
369
+ // Get last written engram
370
+ let lastWrite = null;
371
+ if (checkpoint?.auto.lastWriteId) {
372
+ const engram = store.getEngram(checkpoint.auto.lastWriteId);
373
+ if (engram) {
374
+ lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
375
+ }
325
376
  }
326
- }
327
- // Recall memories using last context
328
- let recalledMemories = [];
329
- const recallContext = checkpoint?.auto.lastRecallContext
330
- ?? checkpoint?.executionState?.currentTask
331
- ?? null;
332
- if (recallContext) {
333
- try {
334
- const results = await activationEngine.activate({
335
- agentId: AGENT_ID,
336
- context: recallContext,
337
- limit: 5,
338
- minScore: 0.05,
339
- useReranker: true,
340
- useExpansion: true,
341
- });
342
- recalledMemories = results.map(r => ({
343
- id: r.engram.id,
344
- concept: r.engram.concept,
345
- content: r.engram.content,
346
- score: r.score,
347
- }));
377
+ // Recall memories using last context
378
+ let recalledMemories = [];
379
+ const recallContext = checkpoint?.auto.lastRecallContext
380
+ ?? checkpoint?.executionState?.currentTask
381
+ ?? null;
382
+ if (recallContext) {
383
+ try {
384
+ const results = await activationEngine.activate({
385
+ agentId: AGENT_ID,
386
+ context: recallContext,
387
+ limit: 5,
388
+ minScore: 0.05,
389
+ useReranker: true,
390
+ useExpansion: true,
391
+ });
392
+ recalledMemories = results.map(r => ({
393
+ id: r.engram.id,
394
+ concept: r.engram.concept,
395
+ content: r.engram.content,
396
+ score: r.score,
397
+ }));
398
+ }
399
+ catch { /* recall failure is non-fatal */ }
348
400
  }
349
- catch { /* recall failure is non-fatal */ }
350
- }
351
- // Trigger mini-consolidation if idle >5min
352
- const MINI_IDLE_MS = 5 * 60_000;
353
- let miniConsolidationTriggered = false;
354
- if (idleMs > MINI_IDLE_MS) {
355
- miniConsolidationTriggered = true;
356
- consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => { });
357
- }
358
- // Format response
359
- const parts = [];
360
- const idleMin = Math.round(idleMs / 60_000);
361
- parts.push(`Idle: ${idleMin}min${miniConsolidationTriggered ? ' (mini-consolidation triggered)' : ''}`);
362
- if (checkpoint?.executionState) {
363
- const s = checkpoint.executionState;
364
- parts.push(`\n**Current task:** ${s.currentTask}`);
365
- if (s.decisions.length)
366
- parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
367
- if (s.nextSteps.length)
368
- parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
369
- if (s.activeFiles.length)
370
- parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
371
- if (s.notes)
372
- parts.push(`**Notes:** ${s.notes}`);
373
- if (checkpoint.checkpointAt)
374
- parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
375
- }
376
- else {
377
- parts.push('\nNo explicit checkpoint saved.');
378
- }
379
- if (lastWrite) {
380
- parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
381
- }
382
- if (recalledMemories.length > 0) {
383
- parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
384
- for (const m of recalledMemories) {
385
- parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
401
+ // Consolidation on restore:
402
+ // - If idle >5min but last consolidation was recent (graceful exit ran it), skip
403
+ // - If idle >5min and no recent consolidation, run full cycle (non-graceful exit fallback)
404
+ const MINI_IDLE_MS = 5 * 60_000;
405
+ const FULL_CONSOLIDATION_GAP_MS = 10 * 60_000; // 10 min — if last consolidation was longer ago, run full
406
+ let miniConsolidationTriggered = false;
407
+ let fullConsolidationTriggered = false;
408
+ if (idleMs > MINI_IDLE_MS) {
409
+ const sinceLastConsolidation = checkpoint?.lastConsolidationAt
410
+ ? now - checkpoint.lastConsolidationAt.getTime()
411
+ : Infinity;
412
+ if (sinceLastConsolidation > FULL_CONSOLIDATION_GAP_MS) {
413
+ // No recent consolidation — graceful exit didn't happen, run full cycle
414
+ fullConsolidationTriggered = true;
415
+ try {
416
+ const result = consolidationEngine.consolidate(AGENT_ID);
417
+ store.markConsolidation(AGENT_ID, false);
418
+ 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`);
419
+ }
420
+ catch { /* consolidation failure is non-fatal */ }
421
+ }
422
+ else {
423
+ // Recent consolidation exists — graceful exit already handled it, just do mini
424
+ miniConsolidationTriggered = true;
425
+ consolidationScheduler.runMiniConsolidation(AGENT_ID).catch(() => { });
426
+ }
386
427
  }
387
- }
388
- return {
389
- content: [{
390
- type: 'text',
391
- text: parts.join('\n'),
392
- }],
393
- };
394
- });
395
- // --- Task Management Tools ---
396
- server.tool('memory_task_add', `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
428
+ // Format response
429
+ const parts = [];
430
+ const idleMin = Math.round(idleMs / 60_000);
431
+ const consolidationNote = fullConsolidationTriggered
432
+ ? ' (full consolidation — no graceful exit detected)'
433
+ : miniConsolidationTriggered
434
+ ? ' (mini-consolidation triggered)'
435
+ : '';
436
+ log(AGENT_ID, 'restore', `idle=${idleMin}min checkpoint=${!!checkpoint?.executionState} recalled=${recalledMemories.length} lastWrite=${lastWrite?.concept ?? 'none'}${fullConsolidationTriggered ? ' FULL_CONSOLIDATION' : ''}`);
437
+ parts.push(`Idle: ${idleMin}min${consolidationNote}`);
438
+ if (checkpoint?.executionState) {
439
+ const s = checkpoint.executionState;
440
+ parts.push(`\n**Current task:** ${s.currentTask}`);
441
+ if (s.decisions.length)
442
+ parts.push(`**Decisions:** ${s.decisions.join('; ')}`);
443
+ if (s.nextSteps.length)
444
+ parts.push(`**Next steps:** ${s.nextSteps.map((st, i) => `${i + 1}. ${st}`).join(', ')}`);
445
+ if (s.activeFiles.length)
446
+ parts.push(`**Active files:** ${s.activeFiles.join(', ')}`);
447
+ if (s.notes)
448
+ parts.push(`**Notes:** ${s.notes}`);
449
+ if (checkpoint.checkpointAt)
450
+ parts.push(`_Saved at: ${checkpoint.checkpointAt.toISOString()}_`);
451
+ }
452
+ else {
453
+ parts.push('\nNo explicit checkpoint saved.');
454
+ parts.push('\n**Tip:** Use memory_write to save important learnings, and memory_checkpoint before long operations so you can recover state.');
455
+ }
456
+ if (lastWrite) {
457
+ parts.push(`\n**Last write:** ${lastWrite.concept}\n${lastWrite.content}`);
458
+ }
459
+ if (recalledMemories.length > 0) {
460
+ parts.push(`\n**Recalled memories (${recalledMemories.length}):**`);
461
+ for (const m of recalledMemories) {
462
+ parts.push(`- **${m.concept}** (${m.score.toFixed(3)}): ${m.content.slice(0, 150)}${m.content.length > 150 ? '...' : ''}`);
463
+ }
464
+ }
465
+ return {
466
+ content: [{
467
+ type: 'text',
468
+ text: parts.join('\n'),
469
+ }],
470
+ };
471
+ });
472
+ // --- Task Management Tools ---
473
+ server.tool('memory_task_add', `Create a task that you need to come back to. Tasks are memories with status and priority tracking.
397
474
 
398
475
  Use this when:
399
476
  - You identify work that needs doing but can't do it right now
@@ -401,132 +478,269 @@ Use this when:
401
478
  - You want to park a sub-task while focusing on something more urgent
402
479
 
403
480
  Tasks automatically get high salience so they won't be discarded.`, {
404
- concept: z.string().describe('Short task title (3-10 words)'),
405
- content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
406
- tags: z.array(z.string()).optional().describe('Tags for categorization'),
407
- priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
408
- .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
409
- blocked_by: z.string().optional().describe('ID of a task that must finish first'),
410
- }, async (params) => {
411
- const engram = store.createEngram({
412
- agentId: AGENT_ID,
413
- concept: params.concept,
414
- content: params.content,
415
- tags: [...(params.tags ?? []), 'task'],
416
- salience: 0.9, // Tasks always high salience
417
- confidence: 0.8,
418
- salienceFeatures: {
419
- surprise: 0.5,
420
- decisionMade: true,
421
- causalDepth: 0.5,
422
- resolutionEffort: 0.5,
423
- eventType: 'decision',
424
- },
425
- reasonCodes: ['task-created'],
426
- taskStatus: params.blocked_by ? 'blocked' : 'open',
427
- taskPriority: params.priority,
428
- blockedBy: params.blocked_by,
481
+ concept: z.string().describe('Short task title (3-10 words)'),
482
+ content: z.string().describe('Full task description — what needs doing, context, acceptance criteria'),
483
+ tags: z.array(z.string()).optional().describe('Tags for categorization'),
484
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).default('medium')
485
+ .describe('Task priority: urgent (do now), high (do soon), medium (normal), low (backlog)'),
486
+ blocked_by: z.string().optional().describe('ID of a task that must finish first'),
487
+ }, async (params) => {
488
+ const engram = store.createEngram({
489
+ agentId: AGENT_ID,
490
+ concept: params.concept,
491
+ content: params.content,
492
+ tags: [...(params.tags ?? []), 'task'],
493
+ salience: 0.9, // Tasks always high salience
494
+ confidence: 0.8,
495
+ salienceFeatures: {
496
+ surprise: 0.5,
497
+ decisionMade: true,
498
+ causalDepth: 0.5,
499
+ resolutionEffort: 0.5,
500
+ eventType: 'decision',
501
+ },
502
+ reasonCodes: ['task-created'],
503
+ taskStatus: params.blocked_by ? 'blocked' : 'open',
504
+ taskPriority: params.priority,
505
+ blockedBy: params.blocked_by,
506
+ });
507
+ connectionEngine.enqueue(engram.id);
508
+ // Generate embedding asynchronously
509
+ embed(`${params.concept} ${params.content}`).then(vec => {
510
+ store.updateEmbedding(engram.id, vec);
511
+ }).catch(() => { });
512
+ return {
513
+ content: [{
514
+ type: 'text',
515
+ text: `Task created: "${params.concept}" (${params.priority})`,
516
+ }],
517
+ };
429
518
  });
430
- connectionEngine.enqueue(engram.id);
431
- // Generate embedding asynchronously
432
- embed(`${params.concept} ${params.content}`).then(vec => {
433
- store.updateEmbedding(engram.id, vec);
434
- }).catch(() => { });
435
- return {
436
- content: [{
437
- type: 'text',
438
- text: `Task created: ${engram.id}\nTitle: ${params.concept}\nPriority: ${params.priority}\nStatus: ${engram.taskStatus}`,
439
- }],
440
- };
441
- });
442
- server.tool('memory_task_update', `Update a task's status or priority. Use this to:
519
+ server.tool('memory_task_update', `Update a task's status or priority. Use this to:
443
520
  - Start working on a task (open → in_progress)
444
521
  - Mark a task done (→ done)
445
522
  - Block a task on another (→ blocked)
446
523
  - Reprioritize (change priority)
447
524
  - Unblock a task (clear blocked_by)`, {
448
- task_id: z.string().describe('ID of the task to update'),
449
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
450
- .describe('New status'),
451
- priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
452
- .describe('New priority'),
453
- blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
454
- }, async (params) => {
455
- const engram = store.getEngram(params.task_id);
456
- if (!engram || !engram.taskStatus) {
457
- return { content: [{ type: 'text', text: `Task not found: ${params.task_id}` }] };
458
- }
459
- if (params.blocked_by !== undefined) {
460
- store.updateBlockedBy(params.task_id, params.blocked_by || null);
461
- }
462
- if (params.status) {
463
- store.updateTaskStatus(params.task_id, params.status);
464
- }
465
- if (params.priority) {
466
- store.updateTaskPriority(params.task_id, params.priority);
467
- }
468
- const updated = store.getEngram(params.task_id);
469
- return {
470
- content: [{
471
- type: 'text',
472
- text: `Task updated: ${updated.concept}\nStatus: ${updated.taskStatus}\nPriority: ${updated.taskPriority}${updated.blockedBy ? `\nBlocked by: ${updated.blockedBy}` : ''}`,
473
- }],
474
- };
475
- });
476
- server.tool('memory_task_list', `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
525
+ task_id: z.string().describe('ID of the task to update'),
526
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
527
+ .describe('New status'),
528
+ priority: z.enum(['urgent', 'high', 'medium', 'low']).optional()
529
+ .describe('New priority'),
530
+ blocked_by: z.string().optional().describe('ID of blocking task (set to empty string to unblock)'),
531
+ }, async (params) => {
532
+ const engram = store.getEngram(params.task_id);
533
+ if (!engram || !engram.taskStatus) {
534
+ return { content: [{ type: 'text', text: `Task not found: ${params.task_id}` }] };
535
+ }
536
+ if (params.blocked_by !== undefined) {
537
+ store.updateBlockedBy(params.task_id, params.blocked_by || null);
538
+ }
539
+ if (params.status) {
540
+ store.updateTaskStatus(params.task_id, params.status);
541
+ }
542
+ if (params.priority) {
543
+ store.updateTaskPriority(params.task_id, params.priority);
544
+ }
545
+ const updated = store.getEngram(params.task_id);
546
+ return {
547
+ content: [{
548
+ type: 'text',
549
+ text: `Updated: "${updated.concept}" ${updated.taskStatus} (${updated.taskPriority})`,
550
+ }],
551
+ };
552
+ });
553
+ server.tool('memory_task_list', `List tasks with optional status filter. Shows tasks ordered by priority (urgent first).
477
554
 
478
555
  Use at the start of a session to see what's pending, or to check blocked/done tasks.`, {
479
- status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
480
- .describe('Filter by status (omit to see all active tasks)'),
481
- include_done: z.boolean().optional().default(false)
482
- .describe('Include completed tasks?'),
483
- }, async (params) => {
484
- let tasks = store.getTasks(AGENT_ID, params.status);
485
- if (!params.include_done && !params.status) {
486
- tasks = tasks.filter(t => t.taskStatus !== 'done');
487
- }
488
- if (tasks.length === 0) {
489
- return { content: [{ type: 'text', text: 'No tasks found.' }] };
490
- }
491
- const lines = tasks.map((t, i) => {
492
- const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
493
- const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
494
- 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}`;
556
+ status: z.enum(['open', 'in_progress', 'blocked', 'done']).optional()
557
+ .describe('Filter by status (omit to see all active tasks)'),
558
+ include_done: z.boolean().optional().default(false)
559
+ .describe('Include completed tasks?'),
560
+ }, async (params) => {
561
+ let tasks = store.getTasks(AGENT_ID, params.status);
562
+ if (!params.include_done && !params.status) {
563
+ tasks = tasks.filter(t => t.taskStatus !== 'done');
564
+ }
565
+ if (tasks.length === 0) {
566
+ return { content: [{ type: 'text', text: 'No tasks found.' }] };
567
+ }
568
+ const lines = tasks.map((t, i) => {
569
+ const blocked = t.blockedBy ? ` [blocked by ${t.blockedBy}]` : '';
570
+ const tags = t.tags?.filter(tag => tag !== 'task').join(', ');
571
+ 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}`;
572
+ });
573
+ return {
574
+ content: [{
575
+ type: 'text',
576
+ text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
577
+ }],
578
+ };
495
579
  });
496
- return {
497
- content: [{
498
- type: 'text',
499
- text: `Tasks (${tasks.length}):\n\n${lines.join('\n\n')}`,
500
- }],
501
- };
502
- });
503
- server.tool('memory_task_next', `Get the single most important task to work on next.
580
+ server.tool('memory_task_next', `Get the single most important task to work on next.
504
581
 
505
582
  Prioritizes: in_progress tasks first (finish what you started), then by priority level, then oldest first. Skips blocked and done tasks.
506
583
 
507
584
  Use this when you finish a task or need to decide what to do next.`, {}, async () => {
508
- const next = store.getNextTask(AGENT_ID);
509
- if (!next) {
510
- return { content: [{ type: 'text', text: 'No actionable tasks. All clear!' }] };
585
+ const next = store.getNextTask(AGENT_ID);
586
+ if (!next) {
587
+ return { content: [{ type: 'text', text: 'No actionable tasks. All clear!' }] };
588
+ }
589
+ const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
590
+ const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
591
+ return {
592
+ content: [{
593
+ type: 'text',
594
+ text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
595
+ }],
596
+ };
597
+ });
598
+ // --- Task Bracket Tools ---
599
+ server.tool('memory_task_begin', `Signal that you're starting a significant task. Auto-checkpoints current state and recalls relevant memories.
600
+
601
+ CALL THIS when starting:
602
+ - A multi-step operation (doc generation, large refactor, migration)
603
+ - Work on a new topic or project area
604
+ - Anything that might fill the context window
605
+
606
+ This ensures your state is saved before you start, and primes recall with relevant context.`, {
607
+ topic: z.string().describe('What task are you starting? (3-15 words)'),
608
+ files: z.array(z.string()).optional().default([])
609
+ .describe('Files you expect to work with'),
610
+ notes: z.string().optional().default('')
611
+ .describe('Any additional context'),
612
+ }, async (params) => {
613
+ // 1. Checkpoint current state
614
+ const checkpoint = store.getCheckpoint(AGENT_ID);
615
+ const prevTask = checkpoint?.executionState?.currentTask ?? 'None';
616
+ store.saveCheckpoint(AGENT_ID, {
617
+ currentTask: params.topic,
618
+ decisions: [],
619
+ activeFiles: params.files,
620
+ nextSteps: [],
621
+ relatedMemoryIds: [],
622
+ notes: params.notes || `Started via memory_task_begin. Previous task: ${prevTask}`,
623
+ episodeId: null,
624
+ });
625
+ // 2. Auto-recall relevant memories
626
+ let recalledSummary = '';
627
+ try {
628
+ const results = await activationEngine.activate({
629
+ agentId: AGENT_ID,
630
+ context: params.topic,
631
+ limit: 5,
632
+ minScore: 0.05,
633
+ useReranker: true,
634
+ useExpansion: true,
635
+ });
636
+ if (results.length > 0) {
637
+ const lines = results.map((r, i) => {
638
+ const tags = r.engram.tags?.length ? ` [${r.engram.tags.join(', ')}]` : '';
639
+ return `${i + 1}. **${r.engram.concept}** (${r.score.toFixed(3)})${tags}\n ${r.engram.content.slice(0, 150)}${r.engram.content.length > 150 ? '...' : ''}`;
640
+ });
641
+ recalledSummary = `\n\n**Recalled memories (${results.length}):**\n${lines.join('\n')}`;
642
+ // Track recall
643
+ store.updateAutoCheckpointRecall(AGENT_ID, params.topic, results.map(r => r.engram.id));
644
+ }
645
+ }
646
+ catch { /* recall failure is non-fatal */ }
647
+ log(AGENT_ID, 'task:begin', `"${params.topic}" prev="${prevTask}"`);
648
+ return {
649
+ content: [{
650
+ type: 'text',
651
+ text: `Started: "${params.topic}" (prev: ${prevTask})${recalledSummary}`,
652
+ }],
653
+ };
654
+ });
655
+ server.tool('memory_task_end', `Signal that you've finished a significant task. Writes a summary memory and auto-checkpoints.
656
+
657
+ CALL THIS when you finish:
658
+ - A multi-step operation
659
+ - Before switching to a different topic
660
+ - At the end of a work session
661
+
662
+ This captures what was accomplished so future sessions can recall it.`, {
663
+ summary: z.string().describe('What was accomplished? Include key outcomes, decisions, and any issues.'),
664
+ tags: z.array(z.string()).optional().default([])
665
+ .describe('Tags for the summary memory'),
666
+ }, async (params) => {
667
+ // 1. Write summary as a memory
668
+ const salience = evaluateSalience({
669
+ content: params.summary,
670
+ eventType: 'decision',
671
+ surprise: 0.3,
672
+ decisionMade: true,
673
+ causalDepth: 0.5,
674
+ resolutionEffort: 0.5,
675
+ });
676
+ const engram = store.createEngram({
677
+ agentId: AGENT_ID,
678
+ concept: 'Task completed',
679
+ content: params.summary,
680
+ tags: [...params.tags, 'task-summary'],
681
+ salience: Math.max(salience.score, 0.7), // Always high salience for task summaries
682
+ salienceFeatures: salience.features,
683
+ reasonCodes: [...salience.reasonCodes, 'task-end'],
684
+ });
685
+ connectionEngine.enqueue(engram.id);
686
+ // Generate embedding asynchronously
687
+ embed(`Task completed: ${params.summary}`).then(vec => {
688
+ store.updateEmbedding(engram.id, vec);
689
+ }).catch(() => { });
690
+ // 2. Update checkpoint to reflect completion
691
+ const checkpoint = store.getCheckpoint(AGENT_ID);
692
+ const completedTask = checkpoint?.executionState?.currentTask ?? 'Unknown task';
693
+ store.saveCheckpoint(AGENT_ID, {
694
+ currentTask: `Completed: ${completedTask}`,
695
+ decisions: checkpoint?.executionState?.decisions ?? [],
696
+ activeFiles: [],
697
+ nextSteps: [],
698
+ relatedMemoryIds: [engram.id],
699
+ notes: `Task completed. Summary memory: ${engram.id}`,
700
+ episodeId: null,
701
+ });
702
+ store.updateAutoCheckpointWrite(AGENT_ID, engram.id);
703
+ log(AGENT_ID, 'task:end', `"${completedTask}" summary=${engram.id} salience=${salience.score.toFixed(2)}`);
704
+ return {
705
+ content: [{
706
+ type: 'text',
707
+ text: `Completed: "${completedTask}" [${salience.score.toFixed(2)}]`,
708
+ }],
709
+ };
710
+ });
711
+ // --- Start ---
712
+ async function main() {
713
+ const transport = new StdioServerTransport();
714
+ await server.connect(transport);
715
+ // Start hook sidecar (lightweight HTTP for Claude Code hooks)
716
+ const sidecar = startSidecar({
717
+ store,
718
+ agentId: AGENT_ID,
719
+ secret: HOOK_SECRET,
720
+ port: HOOK_PORT,
721
+ onConsolidate: (agentId, reason) => {
722
+ console.error(`[mcp] consolidation triggered: ${reason}`);
723
+ const result = consolidationEngine.consolidate(agentId);
724
+ store.markConsolidation(agentId, false);
725
+ console.error(`[mcp] consolidation done: ${result.edgesStrengthened} strengthened, ${result.memoriesForgotten} forgotten`);
726
+ },
727
+ });
728
+ // Log to stderr (stdout is reserved for MCP protocol)
729
+ console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
730
+ console.error(`Hook sidecar on 127.0.0.1:${HOOK_PORT}${HOOK_SECRET ? ' (auth enabled)' : ' (no auth — set AWM_HOOK_SECRET)'}`);
731
+ // Clean shutdown
732
+ const cleanup = () => {
733
+ sidecar.close();
734
+ consolidationScheduler.stop();
735
+ stagingBuffer.stop();
736
+ store.close();
737
+ };
738
+ process.on('SIGINT', () => { cleanup(); process.exit(0); });
739
+ process.on('SIGTERM', () => { cleanup(); process.exit(0); });
511
740
  }
512
- const blocked = next.blockedBy ? `\nBlocked by: ${next.blockedBy}` : '';
513
- const tags = next.tags?.filter(tag => tag !== 'task').join(', ');
514
- return {
515
- content: [{
516
- type: 'text',
517
- text: `Next task:\n**${next.concept}** (${next.taskPriority})\nStatus: ${next.taskStatus}\n${next.content}${blocked}\n${tags ? `Tags: ${tags}\n` : ''}ID: ${next.id}`,
518
- }],
519
- };
520
- });
521
- // --- Start ---
522
- async function main() {
523
- const transport = new StdioServerTransport();
524
- await server.connect(transport);
525
- // Log to stderr (stdout is reserved for MCP protocol)
526
- console.error(`AgentWorkingMemory MCP server started (agent: ${AGENT_ID}, db: ${DB_PATH})`);
527
- }
528
- main().catch(err => {
529
- console.error('MCP server failed:', err);
530
- process.exit(1);
531
- });
741
+ main().catch(err => {
742
+ console.error('MCP server failed:', err);
743
+ process.exit(1);
744
+ });
745
+ } // end else (non-incognito)
532
746
  //# sourceMappingURL=mcp.js.map