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