agent-working-memory 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +200 -238
  2. package/dist/adapters/common.d.ts +6 -0
  3. package/dist/adapters/common.d.ts.map +1 -1
  4. package/dist/adapters/common.js +457 -362
  5. package/dist/adapters/common.js.map +1 -1
  6. package/dist/api/routes.d.ts.map +1 -1
  7. package/dist/api/routes.js +24 -8
  8. package/dist/api/routes.js.map +1 -1
  9. package/dist/core/alias-map.d.ts +16 -0
  10. package/dist/core/alias-map.d.ts.map +1 -0
  11. package/dist/core/alias-map.js +102 -0
  12. package/dist/core/alias-map.js.map +1 -0
  13. package/dist/core/embeddings.d.ts +17 -0
  14. package/dist/core/embeddings.d.ts.map +1 -1
  15. package/dist/core/embeddings.js +52 -1
  16. package/dist/core/embeddings.js.map +1 -1
  17. package/dist/core/model-cache.d.ts +28 -0
  18. package/dist/core/model-cache.d.ts.map +1 -0
  19. package/dist/core/model-cache.js +50 -0
  20. package/dist/core/model-cache.js.map +1 -0
  21. package/dist/core/query-expander.d.ts.map +1 -1
  22. package/dist/core/query-expander.js +2 -0
  23. package/dist/core/query-expander.js.map +1 -1
  24. package/dist/core/recall-config.d.ts +52 -0
  25. package/dist/core/recall-config.d.ts.map +1 -0
  26. package/dist/core/recall-config.js +110 -0
  27. package/dist/core/recall-config.js.map +1 -0
  28. package/dist/core/rerank-window.d.ts +61 -0
  29. package/dist/core/rerank-window.d.ts.map +1 -0
  30. package/dist/core/rerank-window.js +153 -0
  31. package/dist/core/rerank-window.js.map +1 -0
  32. package/dist/core/rerank2.d.ts +62 -0
  33. package/dist/core/rerank2.d.ts.map +1 -0
  34. package/dist/core/rerank2.js +75 -0
  35. package/dist/core/rerank2.js.map +1 -0
  36. package/dist/core/reranker.d.ts.map +1 -1
  37. package/dist/core/reranker.js +2 -0
  38. package/dist/core/reranker.js.map +1 -1
  39. package/dist/core/retrieval-text.d.ts +55 -0
  40. package/dist/core/retrieval-text.d.ts.map +1 -0
  41. package/dist/core/retrieval-text.js +87 -0
  42. package/dist/core/retrieval-text.js.map +1 -0
  43. package/dist/core/temporal-query.d.ts +61 -0
  44. package/dist/core/temporal-query.d.ts.map +1 -0
  45. package/dist/core/temporal-query.js +168 -0
  46. package/dist/core/temporal-query.js.map +1 -0
  47. package/dist/core/token-budget.d.ts +75 -0
  48. package/dist/core/token-budget.d.ts.map +1 -0
  49. package/dist/core/token-budget.js +136 -0
  50. package/dist/core/token-budget.js.map +1 -0
  51. package/dist/core/whoami.d.ts +11 -0
  52. package/dist/core/whoami.d.ts.map +1 -1
  53. package/dist/core/whoami.js +10 -0
  54. package/dist/core/whoami.js.map +1 -1
  55. package/dist/core/write-pipeline.d.ts.map +1 -1
  56. package/dist/core/write-pipeline.js +6 -3
  57. package/dist/core/write-pipeline.js.map +1 -1
  58. package/dist/engine/activation.d.ts.map +1 -1
  59. package/dist/engine/activation.js +135 -32
  60. package/dist/engine/activation.js.map +1 -1
  61. package/dist/hooks/prime.d.ts +77 -0
  62. package/dist/hooks/prime.d.ts.map +1 -0
  63. package/dist/hooks/prime.js +92 -0
  64. package/dist/hooks/prime.js.map +1 -0
  65. package/dist/hooks/sidecar.d.ts.map +1 -1
  66. package/dist/hooks/sidecar.js +39 -0
  67. package/dist/hooks/sidecar.js.map +1 -1
  68. package/dist/mcp.js +134 -102
  69. package/dist/mcp.js.map +1 -1
  70. package/dist/storage/pglite.d.ts.map +1 -1
  71. package/dist/storage/pglite.js +10 -2
  72. package/dist/storage/pglite.js.map +1 -1
  73. package/dist/storage/postgres.d.ts.map +1 -1
  74. package/dist/storage/postgres.js +10 -2
  75. package/dist/storage/postgres.js.map +1 -1
  76. package/dist/storage/sqlite.d.ts.map +1 -1
  77. package/dist/storage/sqlite.js +12 -2
  78. package/dist/storage/sqlite.js.map +1 -1
  79. package/dist/types/engram.d.ts +7 -0
  80. package/dist/types/engram.d.ts.map +1 -1
  81. package/package.json +3 -2
  82. package/src/adapters/common.ts +666 -567
  83. package/src/api/routes.ts +1015 -999
  84. package/src/core/alias-map.ts +97 -0
  85. package/src/core/embeddings.ts +172 -113
  86. package/src/core/model-cache.ts +51 -0
  87. package/src/core/query-expander.ts +2 -0
  88. package/src/core/recall-config.ts +115 -0
  89. package/src/core/rerank-window.ts +158 -0
  90. package/src/core/rerank2.ts +82 -0
  91. package/src/core/reranker.ts +2 -0
  92. package/src/core/retrieval-text.ts +82 -0
  93. package/src/core/temporal-query.ts +193 -0
  94. package/src/core/token-budget.ts +160 -0
  95. package/src/core/whoami.ts +110 -92
  96. package/src/core/write-pipeline.ts +6 -3
  97. package/src/engine/activation.ts +1568 -1468
  98. package/src/hooks/prime.ts +136 -0
  99. package/src/hooks/sidecar.ts +43 -0
  100. package/src/mcp.ts +1422 -1387
  101. package/src/storage/pglite.ts +10 -2
  102. package/src/storage/postgres.ts +10 -2
  103. package/src/storage/sqlite.ts +12 -2
  104. package/src/types/engram.ts +7 -0
package/src/api/routes.ts CHANGED
@@ -1,999 +1,1015 @@
1
- // Copyright 2026 Robert Winter / Complete Ideas
2
- // SPDX-License-Identifier: Apache-2.0
3
- /**
4
- * API Routes — the black box interface agents interact with.
5
- *
6
- * Core (agent-facing):
7
- * POST /memory/write — write a memory (salience filter decides disposition)
8
- * POST /memory/activate — retrieve by context activation
9
- * POST /memory/feedback — report whether a memory was useful
10
- * POST /memory/retract — invalidate a wrong memory
11
- *
12
- * Checkpointing:
13
- * POST /memory/checkpoint — save explicit execution state
14
- * GET /memory/restore/:agentId — restore state + targeted recall + async mini-consolidation
15
- *
16
- * Task management:
17
- * POST /task/create — create a prioritized task
18
- * POST /task/update — update status, priority, or blocking
19
- * GET /task/list/:agentId — list tasks (filtered by status)
20
- * GET /task/next/:agentId — get highest-priority actionable task
21
- *
22
- * Diagnostic (debugging/eval):
23
- * POST /memory/search — deterministic search (not cognitive)
24
- * GET /memory/:id — get a specific engram
25
- * GET /agent/:id/stats — memory stats for an agent
26
- * GET /agent/:id/metrics — eval metrics
27
- * POST /agent/register — register a new agent
28
- *
29
- * System:
30
- * POST /system/evict — trigger eviction check
31
- * POST /system/decay — trigger edge decay
32
- * POST /system/consolidate — run sleep cycle (strengthen, decay, sweep)
33
- * GET /health — health check
34
- */
35
-
36
- import type { FastifyInstance } from 'fastify';
37
- import { buildWhoami } from '../core/whoami.js';
38
- import { getConsolidationState } from '../core/write-telemetry.js';
39
- import type { IEngramStore as EngramStore } from '../storage/store.js';
40
- import type { ActivationEngine } from '../engine/activation.js';
41
- import type { ConnectionEngine } from '../engine/connections.js';
42
- import type { EvictionEngine } from '../engine/eviction.js';
43
- import type { RetractionEngine } from '../engine/retraction.js';
44
- import type { EvalEngine } from '../engine/eval.js';
45
- import type { ConsolidationEngine } from '../engine/consolidation.js';
46
- import type { ConsolidationScheduler } from '../engine/consolidation-scheduler.js';
47
- import { evaluateSalience, computeNovelty } from '../core/salience.js';
48
- import type { SalienceEventType } from '../core/salience.js';
49
- import { performWrite } from '../core/write-pipeline.js';
50
- import type { TaskStatus, TaskPriority } from '../types/engram.js';
51
- import type { ConsciousState } from '../types/checkpoint.js';
52
- import { DEFAULT_AGENT_CONFIG } from '../types/agent.js';
53
- import { embed, embedBatch } from '../core/embeddings.js';
54
- import { VERSION } from '../version.js';
55
-
56
- export interface MemoryDeps {
57
- store: EngramStore;
58
- activationEngine: ActivationEngine;
59
- connectionEngine: ConnectionEngine;
60
- evictionEngine: EvictionEngine;
61
- retractionEngine: RetractionEngine;
62
- evalEngine: EvalEngine;
63
- consolidationEngine: ConsolidationEngine;
64
- consolidationScheduler: ConsolidationScheduler;
65
- }
66
-
67
- export function registerRoutes(app: FastifyInstance, deps: MemoryDeps): void {
68
- const { store, activationEngine, connectionEngine, evictionEngine, retractionEngine, evalEngine, consolidationEngine, consolidationScheduler } = deps;
69
-
70
- // ============================================================
71
- // CORE — Agent-facing endpoints
72
- // ============================================================
73
-
74
- app.post('/memory/write', async (req, reply) => {
75
- const body = req.body as {
76
- agentId: string;
77
- concept: string;
78
- content: string;
79
- tags?: string[];
80
- eventType?: SalienceEventType;
81
- surprise?: number;
82
- decisionMade?: boolean;
83
- causalDepth?: number;
84
- resolutionEffort?: number;
85
- confidence?: number;
86
- // Memory class — canonical bypasses salience filter; structural is
87
- // for system-written event-log records (see 0.8 spec). Restored in
88
- // 0.8.0 after the field was dropped from the HTTP body schema during
89
- // the 0.7.x refactor core/salience.ts:88-89,124,187 and
90
- // core/write-pipeline.ts:77 still expect and honor it, so HTTP
91
- // callers were silently losing the canonical-bypass signal.
92
- memory_class?: 'canonical' | 'working' | 'ephemeral' | 'structural';
93
- // Optional story-time / sequence ordering (0.8 Cluster A). NULL by
94
- // default. Used by sortBy: "sequence" on /memory/search and by
95
- // /memory/latest-by-tag (0.8 Cluster C).
96
- sequence?: number;
97
- // Force embedding for structural-class writes. Defaults to false for
98
- // structural (deterministic retrieval only) opt in here when cognitive
99
- // recall over a structural engram is desired. (0.8 Cluster A)
100
- embed?: boolean;
101
- // Typed cross-record links (0.8 Cluster D). Each reference is
102
- // {type, matchEngramId?, matchConcept?}. If matchConcept is given
103
- // without matchEngramId, AWM resolves it to the most recent active
104
- // engram at write time and stores BOTH on the reference (stable link).
105
- // If no match found, stores just matchConcept (caller may be linking
106
- // to a future or deleted engram). Types: advances | resolves |
107
- // subverts | abandons | extends | supersedes.
108
- references?: Array<{
109
- type: 'advances' | 'resolves' | 'subverts' | 'abandons' | 'extends' | 'supersedes';
110
- matchEngramId?: string;
111
- matchConcept?: string;
112
- matchTags?: string[];
113
- }>;
114
- // Agent-provided metadata (stored as searchable tags)
115
- project?: string;
116
- topic?: string;
117
- source?: string;
118
- confidenceLevel?: string;
119
- sessionId?: string;
120
- intent?: string;
121
- // Memory spine (D5/D8, 2026-07-30) — camelCase and snake_case accepted.
122
- originClass?: string; origin_class?: string;
123
- recipeId?: string; recipe_id?: string;
124
- validFrom?: string; valid_from?: string;
125
- validTo?: string; valid_to?: string;
126
- };
127
-
128
- if (!body.agentId || typeof body.agentId !== 'string' ||
129
- !body.concept || typeof body.concept !== 'string' ||
130
- !body.content || typeof body.content !== 'string') {
131
- return reply.status(400).send({ error: 'agentId, concept, and content are required strings' });
132
- }
133
-
134
- // Assemble tags: user-provided + agent metadata
135
- const userTags = body.tags ?? [];
136
- const metaTags: string[] = [];
137
- if (body.project) metaTags.push(`proj=${body.project}`);
138
- if (body.topic) metaTags.push(`topic=${body.topic}`);
139
- if (body.source) metaTags.push(`src=${body.source}`);
140
- if (body.confidenceLevel) metaTags.push(`conf=${body.confidenceLevel}`);
141
- if (body.sessionId) metaTags.push(`sid=${body.sessionId}`);
142
- if (body.intent) metaTags.push(`intent=${body.intent}`);
143
-
144
- // Resolve references (0.8 Cluster D): if matchConcept is given without
145
- // matchEngramId, look up the most recent active engram with that concept
146
- // (+ optional matchTags) and store both. Stable link survives concept
147
- // edits. No match found store just matchConcept so the intent
148
- // (link-to-future or link-to-deleted) is preserved.
149
- const resolvedRefs = await Promise.all((body.references ?? []).map(async ref => {
150
- if (!ref.matchEngramId && ref.matchConcept) {
151
- const matched = await store.findActiveMatchByConcept(
152
- body.agentId, ref.matchConcept, ref.matchTags,
153
- );
154
- if (matched) {
155
- return { type: ref.type, matchEngramId: matched.id, matchConcept: ref.matchConcept };
156
- }
157
- }
158
- return { type: ref.type, matchEngramId: ref.matchEngramId, matchConcept: ref.matchConcept };
159
- }));
160
-
161
- const result = await performWrite({ store, connectionEngine }, {
162
- agentId: body.agentId,
163
- concept: body.concept,
164
- content: body.content,
165
- tags: [...userTags, ...metaTags],
166
- memoryClass: body.memory_class,
167
- eventType: body.eventType,
168
- surprise: body.surprise,
169
- decisionMade: body.decisionMade,
170
- causalDepth: body.causalDepth,
171
- resolutionEffort: body.resolutionEffort,
172
- confidence: body.confidence,
173
- sequence: body.sequence,
174
- embed: body.embed,
175
- references: resolvedRefs.length > 0 ? resolvedRefs : undefined,
176
- originClass: body.originClass ?? body.origin_class,
177
- writerSession: body.sessionId,
178
- recipeId: body.recipeId ?? body.recipe_id,
179
- validFrom: body.validFrom ?? body.valid_from,
180
- validTo: body.validTo ?? body.valid_to,
181
- });
182
-
183
- // Auto-checkpoint always (covers create, reinforce, and supersede).
184
- try { await store.updateAutoCheckpointWrite(body.agentId, result.engram.id); } catch { /* non-fatal */ }
185
-
186
- if (result.action === 'reinforce') {
187
- return reply.code(200).send({
188
- stored: false,
189
- action: 'reinforce',
190
- disposition: 'reinforced',
191
- engram: result.engram,
192
- reinforce: result.reinforce,
193
- novelty: result.noveltyResult.novelty,
194
- });
195
- }
196
-
197
- // create / supersede paths follow legacy temporal-edge + episode logic.
198
- // Structural-class writes (0.8 Cluster A) skip these: they're system-written
199
- // event-log records, not conversational beats, so keeping them out of the
200
- // temporal graph + episode index keeps cognitive retrieval clean.
201
- const isStructural = body.memory_class === 'structural';
202
- if (!isStructural) {
203
- try {
204
- const prev = await store.getLatestEngram(body.agentId, result.engram.id);
205
- if (prev) {
206
- await store.upsertAssociation(prev.id, result.engram.id, 0.3, 'temporal', 0.8);
207
- }
208
- } catch { /* Temporal edge creation is non-fatal */ }
209
-
210
- if (result.salience
211
- && (result.salience.disposition === 'active' || result.salience.disposition === 'discard')) {
212
- try {
213
- let episode = await store.getActiveEpisode(body.agentId, 3600_000);
214
- if (!episode) {
215
- episode = await store.createEpisode({ agentId: body.agentId, label: body.concept });
216
- }
217
- await store.addEngramToEpisode(result.engram.id, episode.id);
218
- } catch { /* Episode assignment is non-fatal */ }
219
- }
220
- }
221
-
222
- const isLowSalience = result.salience?.disposition === 'discard';
223
- return reply.code(201).send({
224
- stored: true,
225
- action: result.action,
226
- // disposition: legacy field — 'low-salience' is returned for discard so
227
- // callers know the engram was kept but marked low-value. The raw inner
228
- // salience decision is exposed as `salienceDisposition` for callers
229
- // (and tests) that want the unmapped value.
230
- disposition: isLowSalience ? 'low-salience' : (result.salience?.disposition ?? 'active'),
231
- salienceDisposition: result.salience?.disposition ?? null,
232
- salience: result.salience?.score ?? 0,
233
- reasonCodes: result.salience?.reasonCodes ?? [],
234
- engram: result.engram,
235
- supersedeOf: result.supersedeOf,
236
- });
237
- });
238
-
239
- /**
240
- * Bulk write — accepts many facts in one request.
241
- * Creates engrams in a single transaction, embeds in batch.
242
- * Returns all IDs for downstream supersession calls.
243
- */
244
- app.post('/memory/write-batch', async (req, reply) => {
245
- const body = req.body as {
246
- agentId: string;
247
- sessionId?: string; // Shared session ID for all memories in this batch
248
- memories: Array<{
249
- concept: string;
250
- content: string;
251
- tags?: string[];
252
- supersedes?: string;
253
- sessionId?: string; // Per-memory session override
254
- }>;
255
- };
256
-
257
- if (!body.agentId || !body.memories || body.memories.length === 0) {
258
- return reply.code(400).send({ error: 'agentId and non-empty memories array required' });
259
- }
260
-
261
- const results: Array<{ id: string; concept: string; disposition: string }> = [];
262
-
263
- for (const mem of body.memories) {
264
- // Add session ID tag if provided (batch-level or per-memory)
265
- const sid = mem.sessionId ?? body.sessionId;
266
- const memTags = [...(mem.tags ?? [])];
267
- if (sid) memTags.push(`sid=${sid}`);
268
-
269
- const engram = await store.createEngram({
270
- agentId: body.agentId,
271
- concept: mem.concept,
272
- content: mem.content,
273
- tags: memTags,
274
- salience: 0.5,
275
- confidence: 0.5,
276
- supersedes: mem.supersedes ?? undefined,
277
- });
278
-
279
- // Handle supersession inline — archive superseded memory to remove from active pool
280
- if (mem.supersedes) {
281
- await store.supersedeEngram(mem.supersedes, engram.id);
282
- await store.updateConfidence(mem.supersedes, 0.1);
283
- await store.updateStage(mem.supersedes, 'archived'); // Remove from active search pool
284
- }
285
-
286
- results.push({ id: engram.id, concept: mem.concept, disposition: 'active' });
287
- }
288
-
289
- // Batch embed synchronously — ensures embeddings are ready before queries hit
290
- const texts = body.memories.map((m, i) => `${m.concept} ${m.content}`);
291
- try {
292
- const vecs = await embedBatch(texts);
293
- for (let i = 0; i < vecs.length; i++) {
294
- if (results[i]) {
295
- await store.updateEmbedding(results[i].id, vecs[i]);
296
- }
297
- }
298
- } catch { /* Embedding failure is non-fatal */ }
299
-
300
- try { await store.updateAutoCheckpointWrite(body.agentId, results[results.length - 1]?.id ?? ''); } catch {}
301
-
302
- return reply.code(201).send({
303
- stored: results.length,
304
- results,
305
- });
306
- });
307
-
308
- app.post('/memory/activate', async (req, reply) => {
309
- const body = req.body as {
310
- agentId: string;
311
- context: string;
312
- limit?: number;
313
- minScore?: number;
314
- includeStaging?: boolean;
315
- useReranker?: boolean;
316
- useExpansion?: boolean;
317
- abstentionThreshold?: number;
318
- requireConfidence?: number;
319
- workspace?: string;
320
- bm25Only?: boolean;
321
- granularity?: 'full' | 'compact' | 'auto';
322
- };
323
-
324
- const results = await activationEngine.activate({
325
- agentId: body.agentId,
326
- context: body.context,
327
- limit: body.limit,
328
- minScore: body.minScore,
329
- includeStaging: body.includeStaging,
330
- useReranker: body.useReranker,
331
- useExpansion: body.useExpansion,
332
- abstentionThreshold: body.abstentionThreshold,
333
- requireConfidence: body.requireConfidence,
334
- workspace: body.workspace,
335
- bm25Only: body.bm25Only,
336
- granularity: body.granularity,
337
- });
338
-
339
- // Auto-checkpoint: track recall for consolidation scheduling
340
- try {
341
- const ids = results.map(r => r.engram.id);
342
- await store.updateAutoCheckpointRecall(body.agentId, body.context, ids);
343
- } catch { /* non-fatal */ }
344
-
345
- // Surface recall confidence as a top-level field too — same value is on
346
- // every result, but it describes the recall as a whole, so exposing it
347
- // once is easier for consumers (and lets them inspect 0-result recalls).
348
- const confidence = results[0]?.confidence ?? 0;
349
- return reply.send({ results, confidence });
350
- });
351
-
352
- app.post('/memory/feedback', async (req, reply) => {
353
- const body = req.body as {
354
- activationEventId?: string;
355
- engramId: string;
356
- useful: boolean;
357
- context?: string;
358
- };
359
-
360
- await store.logRetrievalFeedback(
361
- body.activationEventId ?? null,
362
- body.engramId,
363
- body.useful,
364
- body.context ?? ''
365
- );
366
-
367
- // Update engram confidence based on feedback
368
- const engram = await store.getEngram(body.engramId);
369
- if (engram) {
370
- const config = DEFAULT_AGENT_CONFIG;
371
- const delta = body.useful
372
- ? config.feedbackPositiveBoost
373
- : -config.feedbackNegativePenalty;
374
- await store.updateConfidence(engram.id, engram.confidence + delta);
375
- }
376
-
377
- // Touch activity for consolidation scheduling
378
- if (engram) {
379
- try { await store.touchActivity(engram.agentId); } catch { /* non-fatal */ }
380
- }
381
-
382
- return reply.send({ recorded: true });
383
- });
384
-
385
- app.post('/memory/retract', async (req, reply) => {
386
- const body = req.body as {
387
- agentId: string;
388
- targetEngramId: string;
389
- reason: string;
390
- counterContent?: string;
391
- };
392
-
393
- const result = await retractionEngine.retract({
394
- agentId: body.agentId,
395
- targetEngramId: body.targetEngramId,
396
- reason: body.reason,
397
- counterContent: body.counterContent,
398
- });
399
-
400
- // Touch activity for consolidation scheduling
401
- try { await store.touchActivity(body.agentId); } catch { /* non-fatal */ }
402
-
403
- return reply.send(result);
404
- });
405
-
406
- app.post('/memory/supersede', async (req, reply) => {
407
- const body = req.body as {
408
- // ── Form A — supersede by existing engram IDs (pre-0.8 behavior) ──
409
- oldEngramId?: string;
410
- newEngramId?: string;
411
- // ── Form B — atomic write-and-supersede by concept match (0.8 Cluster D) ──
412
- agentId?: string;
413
- matchConcept?: string;
414
- matchTags?: string[];
415
- newEngram?: {
416
- concept: string;
417
- content: string;
418
- tags?: string[];
419
- memory_class?: 'canonical' | 'working' | 'ephemeral' | 'structural';
420
- sequence?: number;
421
- eventType?: SalienceEventType;
422
- };
423
- // Common
424
- reason?: string;
425
- };
426
-
427
- const isFormA = !!(body.oldEngramId && body.newEngramId);
428
- const isFormB = !!(body.matchConcept && body.newEngram && body.agentId);
429
-
430
- if (isFormA && isFormB) {
431
- return reply.code(400).send({
432
- error: 'Pass either {oldEngramId, newEngramId} (Form A) OR ' +
433
- '{agentId, matchConcept, newEngram} (Form B), not both.',
434
- });
435
- }
436
- if (!isFormA && !isFormB) {
437
- return reply.code(400).send({
438
- error: 'Missing required fields. Form A: {oldEngramId, newEngramId}. ' +
439
- 'Form B: {agentId, matchConcept, newEngram}.',
440
- });
441
- }
442
-
443
- // ── Form A — by IDs ──
444
- if (isFormA) {
445
- const oldEngram = await store.getEngram(body.oldEngramId!);
446
- const newEngram = await store.getEngram(body.newEngramId!);
447
- if (!oldEngram) return reply.code(404).send({ error: `Old engram ${body.oldEngramId} not found` });
448
- if (!newEngram) return reply.code(404).send({ error: `New engram ${body.newEngramId} not found` });
449
-
450
- await store.upsertAssociation(body.newEngramId!, body.oldEngramId!, 0.8, 'causal', 1.0);
451
- await store.updateConfidence(body.oldEngramId!, oldEngram.confidence * 0.2);
452
- await store.supersedeEngram(body.oldEngramId!, body.newEngramId!);
453
- try { await store.touchActivity(oldEngram.agentId); } catch { /* non-fatal */ }
454
-
455
- return reply.send({
456
- superseded: body.oldEngramId,
457
- supersededBy: body.newEngramId,
458
- reason: body.reason ?? 'outdated',
459
- });
460
- }
461
-
462
- // ── Form B — atomic write-and-supersede by concept match ──
463
- // Find old (most recent active match by concept + optional tags), write
464
- // new engram via performWrite, link them all in one SQL transaction.
465
- // If no match: write new anyway, return { superseded: null }.
466
- // AWM 0.8.x P4b follow-up: Form B atomicity via withTransaction.
467
- // Holds the SQLite/PGlite lock across the async write + supersede pair
468
- // so callers never observe a half-completed state.
469
- const result = await (store.withTransaction(async () => {
470
- const matched = await store.findActiveMatchByConcept(
471
- body.agentId!, body.matchConcept!, body.matchTags,
472
- );
473
-
474
- const writeRes = await performWrite({ store, connectionEngine }, {
475
- agentId: body.agentId!,
476
- concept: body.newEngram!.concept,
477
- content: body.newEngram!.content,
478
- tags: body.newEngram!.tags ?? [],
479
- memoryClass: body.newEngram!.memory_class,
480
- sequence: body.newEngram!.sequence,
481
- eventType: body.newEngram!.eventType,
482
- enableReinforcement: false,
483
- });
484
-
485
- if (matched) {
486
- await store.upsertAssociation(writeRes.engram.id, matched.id, 0.8, 'causal', 1.0);
487
- await store.updateConfidence(matched.id, matched.confidence * 0.2);
488
- await store.supersedeEngram(matched.id, writeRes.engram.id);
489
- }
490
- return { writeRes, matched };
491
- }) as Promise<{ writeRes: Awaited<ReturnType<typeof performWrite>>; matched: any }>);
492
-
493
- try { await store.touchActivity(body.agentId!); } catch { /* non-fatal */ }
494
-
495
- return reply.code(201).send({
496
- newEngram: result.writeRes.engram,
497
- superseded: result.matched ? result.matched.id : null,
498
- supersededBy: result.writeRes.engram.id,
499
- reason: body.reason ?? 'resolved by concept match',
500
- });
501
- });
502
-
503
- // ============================================================
504
- // DIAGNOSTIC — Debugging and inspection
505
- // ============================================================
506
-
507
- app.post('/memory/search', async (req, reply) => {
508
- const body = req.body as {
509
- agentId: string;
510
- text?: string;
511
- concept?: string;
512
- tags?: string[]; // legacy AND-filter — preserved, equivalent to tagsAll
513
- tagsAll?: string[]; // 0.8 Cluster B explicit AND
514
- tagsAny?: string[]; // 0.8 Cluster B — OR (at least one)
515
- tagsNone?: string[]; // 0.8 Cluster B — NOT (exclude all)
516
- stage?: string;
517
- retracted?: boolean;
518
- limit?: number;
519
- offset?: number;
520
- sortBy?: 'createdAt' | 'sequence' | 'salience' | 'confidence' | 'lastAccessed';
521
- sortOrder?: 'asc' | 'desc';
522
- };
523
-
524
- const results = await store.search({
525
- agentId: body.agentId,
526
- text: body.text,
527
- concept: body.concept,
528
- tags: body.tags,
529
- tagsAll: body.tagsAll,
530
- tagsAny: body.tagsAny,
531
- tagsNone: body.tagsNone,
532
- stage: body.stage as any,
533
- retracted: body.retracted,
534
- limit: body.limit,
535
- offset: body.offset,
536
- sortBy: body.sortBy,
537
- sortOrder: body.sortOrder,
538
- });
539
-
540
- return reply.send({ results, count: results.length });
541
- });
542
-
543
- // ============================================================
544
- // 0.8 Cluster C — materialized-view + atomic-counter endpoints
545
- // ============================================================
546
-
547
- /**
548
- * For each distinct value of `tagKey`, return the most recent active
549
- * engram. Used by NovelForge for "latest emotional state per character",
550
- * "latest motif phase per motif", etc.
551
- */
552
- app.post('/memory/latest-by-tag', async (req, reply) => {
553
- const body = req.body as {
554
- agentId: string;
555
- tagKey: string; // e.g. "character=", "motif="
556
- scopeTagsAll?: string[]; // optional narrowing
557
- retracted?: boolean;
558
- sortBy?: 'createdAt' | 'sequence';
559
- limit?: number;
560
- };
561
- if (!body.agentId || !body.tagKey) {
562
- return reply.code(400).send({ error: 'agentId and tagKey are required' });
563
- }
564
- const results = await store.getLatestByTag({
565
- agentId: body.agentId,
566
- tagKeyPrefix: body.tagKey,
567
- scopeTagsAll: body.scopeTagsAll,
568
- retracted: body.retracted ?? false,
569
- sortBy: body.sortBy,
570
- limit: body.limit,
571
- });
572
- return reply.send({ results, count: results.length });
573
- });
574
-
575
- /**
576
- * Filter by tag-set operators, sort by numeric value extracted from a
577
- * tag prefix, return top N. Used by NovelForge for "top N active
578
- * promises by weight".
579
- */
580
- app.post('/memory/top-by', async (req, reply) => {
581
- const body = req.body as {
582
- agentId: string;
583
- sortField: string; // tag prefix, e.g. "weight="
584
- order?: 'asc' | 'desc'; // default desc
585
- filterTagsAll?: string[];
586
- filterTagsAny?: string[];
587
- filterTagsNone?: string[];
588
- retracted?: boolean;
589
- limit?: number;
590
- };
591
- if (!body.agentId || !body.sortField) {
592
- return reply.code(400).send({ error: 'agentId and sortField are required' });
593
- }
594
- const results = await store.getTopBy({
595
- agentId: body.agentId,
596
- sortField: body.sortField,
597
- order: body.order ?? 'desc',
598
- filterTagsAll: body.filterTagsAll,
599
- filterTagsAny: body.filterTagsAny,
600
- filterTagsNone: body.filterTagsNone,
601
- retracted: body.retracted ?? false,
602
- limit: body.limit,
603
- });
604
- return reply.send({ results, count: results.length });
605
- });
606
-
607
- /**
608
- * Compute effective state of an engram from referenced events. Two
609
- * targeting modes: by ID, or by concept match (same semantics as Form B's
610
- * findActiveMatchByConcept).
611
- */
612
- app.post('/memory/resolve', async (req, reply) => {
613
- const body = req.body as {
614
- agentId: string;
615
- targetEngramId?: string;
616
- matchConcept?: string;
617
- matchTags?: string[];
618
- };
619
- if (!body.agentId) {
620
- return reply.code(400).send({ error: 'agentId is required' });
621
- }
622
-
623
- let targetId = body.targetEngramId;
624
- if (!targetId && body.matchConcept) {
625
- const matched = await store.findActiveMatchByConcept(
626
- body.agentId, body.matchConcept, body.matchTags,
627
- );
628
- if (!matched) {
629
- return reply.code(404).send({
630
- error: `No active engram matches concept "${body.matchConcept}"`,
631
- });
632
- }
633
- targetId = matched.id;
634
- }
635
- if (!targetId) {
636
- return reply.code(400).send({
637
- error: 'Provide either targetEngramId or matchConcept',
638
- });
639
- }
640
-
641
- const result = await store.resolveEffectiveState(targetId);
642
- if (!result) return reply.code(404).send({ error: `Engram ${targetId} not found` });
643
- return reply.send(result);
644
- });
645
-
646
- /**
647
- * Race-free next-sequence allocator. Caller writes the engram with the
648
- * returned value in `sequence`. Doesn't reserve concurrent allocations
649
- * always serialize via BEGIN IMMEDIATE.
650
- */
651
- app.get('/memory/sequence/:agentId/next', async (req, reply) => {
652
- const { agentId } = req.params as { agentId: string };
653
- const next = await store.allocateNextSequence(agentId);
654
- return reply.send({ agentId, next });
655
- });
656
-
657
- app.get('/memory/:id', async (req, reply) => {
658
- const { id } = req.params as { id: string };
659
- const engram = await store.getEngram(id);
660
- if (!engram) return reply.code(404).send({ error: 'Not found' });
661
-
662
- const associations = await store.getAssociationsFor(id);
663
- return reply.send({ engram, associations });
664
- });
665
-
666
- app.get('/agent/:id/stats', async (req, reply) => {
667
- const { id } = req.params as { id: string };
668
- const active = await store.getEngramsByAgent(id, 'active');
669
- const staging = await store.getEngramsByAgent(id, 'staging');
670
- const retracted = (await store.getEngramsByAgent(id, undefined, true)).filter(e => e.retracted);
671
- const associations = await store.getAllAssociations(id);
672
-
673
- return reply.send({
674
- agentId: id,
675
- engrams: {
676
- active: active.length,
677
- staging: staging.length,
678
- retracted: retracted.length,
679
- total: active.length + staging.length + retracted.length,
680
- },
681
- associations: associations.length,
682
- avgConfidence: active.length > 0
683
- ? +(active.reduce((s, e) => s + e.confidence, 0) / active.length).toFixed(3)
684
- : 0,
685
- });
686
- });
687
-
688
- app.get('/agent/:id/metrics', async (req, reply) => {
689
- const { id } = req.params as { id: string };
690
- const windowHours = parseInt((req.query as any).window ?? '24', 10);
691
- const metrics = await evalEngine.computeMetrics(id, windowHours);
692
- return reply.send({ metrics });
693
- });
694
-
695
- app.post('/agent/register', async (req, reply) => {
696
- const body = req.body as { name: string };
697
- const id = crypto.randomUUID();
698
- return reply.code(201).send({
699
- id,
700
- name: body.name,
701
- config: DEFAULT_AGENT_CONFIG,
702
- });
703
- });
704
-
705
- // ============================================================
706
- // SYSTEM — Maintenance operations
707
- // ============================================================
708
-
709
- app.post('/system/evict', async (req, reply) => {
710
- const body = req.body as { agentId: string };
711
- const result = await evictionEngine.enforceCapacity(body.agentId, DEFAULT_AGENT_CONFIG);
712
- return reply.send(result);
713
- });
714
-
715
- app.post('/system/decay', async (req, reply) => {
716
- const body = req.body as { agentId: string; halfLifeDays?: number };
717
- const decayed = await evictionEngine.decayEdges(body.agentId, body.halfLifeDays);
718
- return reply.send({ edgesDecayed: decayed });
719
- });
720
-
721
- app.post('/system/consolidate', async (req, reply) => {
722
- const body = req.body as { agentId: string };
723
- const result = await consolidationEngine.consolidate(body.agentId);
724
- return reply.send(result);
725
- });
726
-
727
- // ============================================================
728
- // CHECKPOINTING — Conscious state preservation
729
- // ============================================================
730
-
731
- app.post('/memory/checkpoint', async (req, reply) => {
732
- const body = req.body as {
733
- agentId: string;
734
- currentTask: string;
735
- decisions?: string[];
736
- activeFiles?: string[];
737
- nextSteps?: string[];
738
- relatedMemoryIds?: string[];
739
- notes?: string;
740
- episodeId?: string | null;
741
- };
742
-
743
- const state: ConsciousState = {
744
- currentTask: body.currentTask,
745
- decisions: body.decisions ?? [],
746
- activeFiles: body.activeFiles ?? [],
747
- nextSteps: body.nextSteps ?? [],
748
- relatedMemoryIds: body.relatedMemoryIds ?? [],
749
- notes: body.notes ?? '',
750
- episodeId: body.episodeId ?? null,
751
- };
752
-
753
- store.saveCheckpoint(body.agentId, state);
754
- return reply.send({ saved: true, agentId: body.agentId });
755
- });
756
-
757
- app.get('/memory/restore/:agentId', async (req, reply) => {
758
- const { agentId } = req.params as { agentId: string };
759
- const checkpoint = await store.getCheckpoint(agentId);
760
-
761
- const now = Date.now();
762
- const idleMs = checkpoint
763
- ? now - checkpoint.auto.lastActivityAt.getTime()
764
- : 0;
765
-
766
- // Get last written engram for context
767
- let lastWrite: { id: string; concept: string; content: string } | null = null;
768
- if (checkpoint?.auto.lastWriteId) {
769
- const engram = await store.getEngram(checkpoint.auto.lastWriteId);
770
- if (engram) {
771
- lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
772
- }
773
- }
774
-
775
- // Recall memories using last context (if available)
776
- let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
777
- const recallContext = checkpoint?.auto.lastRecallContext
778
- ?? checkpoint?.executionState?.currentTask
779
- ?? null;
780
-
781
- if (recallContext) {
782
- try {
783
- const results = await activationEngine.activate({
784
- agentId,
785
- context: recallContext,
786
- limit: 5,
787
- minScore: 0.05,
788
- useReranker: true,
789
- useExpansion: true,
790
- });
791
- recalledMemories = results.map(r => ({
792
- id: r.engram.id,
793
- concept: r.engram.concept,
794
- content: r.engram.content,
795
- score: r.score,
796
- }));
797
- } catch { /* recall failure is non-fatal */ }
798
- }
799
-
800
- // Trigger mini-consolidation if idle >5min (async, fire-and-forget)
801
- const MINI_CONSOLIDATION_IDLE_MS = 5 * 60_000;
802
- let miniConsolidationTriggered = false;
803
- if (idleMs > MINI_CONSOLIDATION_IDLE_MS) {
804
- miniConsolidationTriggered = true;
805
- consolidationScheduler.runMiniConsolidation(agentId).catch(() => {});
806
- }
807
-
808
- return reply.send({
809
- executionState: checkpoint?.executionState ?? null,
810
- checkpointAt: checkpoint?.checkpointAt ?? null,
811
- recalledMemories,
812
- lastWrite,
813
- idleMs,
814
- miniConsolidationTriggered,
815
- });
816
- });
817
-
818
- // ============================================================
819
- // TASK MANAGEMENT
820
- // ============================================================
821
-
822
- app.post('/task/create', async (req, reply) => {
823
- const body = req.body as {
824
- agentId: string;
825
- concept: string;
826
- content: string;
827
- tags?: string[];
828
- priority?: TaskPriority;
829
- blockedBy?: string;
830
- };
831
-
832
- const engram = await store.createEngram({
833
- agentId: body.agentId,
834
- concept: body.concept,
835
- content: body.content,
836
- tags: [...(body.tags ?? []), 'task'],
837
- salience: 0.9,
838
- confidence: 0.8,
839
- salienceFeatures: {
840
- surprise: 0.5, decisionMade: true, causalDepth: 0.5,
841
- resolutionEffort: 0.5, eventType: 'decision',
842
- },
843
- reasonCodes: ['task-created'],
844
- taskStatus: body.blockedBy ? 'blocked' : 'open',
845
- taskPriority: body.priority ?? 'medium',
846
- blockedBy: body.blockedBy,
847
- });
848
-
849
- connectionEngine.enqueue(engram.id);
850
- embed(`${body.concept} ${body.content}`).then(async vec => {
851
- await store.updateEmbedding(engram.id, vec);
852
- }).catch(() => {});
853
-
854
- return reply.send(engram);
855
- });
856
-
857
- app.post('/task/update', async (req, reply) => {
858
- const body = req.body as {
859
- taskId: string;
860
- status?: TaskStatus;
861
- priority?: TaskPriority;
862
- blockedBy?: string | null;
863
- };
864
-
865
- const engram = await store.getEngram(body.taskId);
866
- if (!engram || !engram.taskStatus) {
867
- return reply.code(404).send({ error: 'Task not found' });
868
- }
869
-
870
- if (body.blockedBy !== undefined) {
871
- await store.updateBlockedBy(body.taskId, body.blockedBy);
872
- }
873
- if (body.status) {
874
- await store.updateTaskStatus(body.taskId, body.status);
875
- }
876
- if (body.priority) {
877
- await store.updateTaskPriority(body.taskId, body.priority);
878
- }
879
-
880
- return reply.send(await store.getEngram(body.taskId));
881
- });
882
-
883
- app.get('/task/list/:agentId', async (req, reply) => {
884
- const { agentId } = req.params as { agentId: string };
885
- const { status, includeDone } = req.query as { status?: TaskStatus; includeDone?: string };
886
-
887
- let tasks = await store.getTasks(agentId, status);
888
- if (includeDone !== 'true' && !status) {
889
- tasks = tasks.filter(t => t.taskStatus !== 'done');
890
- }
891
-
892
- return reply.send({ tasks, count: tasks.length });
893
- });
894
-
895
- app.get('/task/next/:agentId', async (req, reply) => {
896
- const { agentId } = req.params as { agentId: string };
897
- const next = await store.getNextTask(agentId);
898
- return reply.send(next ? { task: next } : { task: null, message: 'No actionable tasks' });
899
- });
900
-
901
- // Time warp — shift all timestamps backward by N days (for testing)
902
- app.post('/system/time-warp', async (req, reply) => {
903
- const body = req.body as { agentId: string; days: number };
904
- const ms = body.days * 24 * 60 * 60 * 1000;
905
- const shifted = await store.timeWarp(body.agentId, ms);
906
- return reply.send({ shifted, days: body.days });
907
- });
908
-
909
- // ─── Export ─────────────────────────────────────────────────────────────
910
-
911
- app.get('/memory/export', async (req, reply) => {
912
- const { agentId, all } = req.query as { agentId?: string; all?: string };
913
- const includeAll = all === 'true';
914
- // /memory/export uses raw SQL — SQLite-only. On PGlite, callers should use
915
- // the awm CLI export/merge tools instead.
916
- if (typeof (store as any).getDb !== 'function') {
917
- return reply.code(501).send({ error: 'export endpoint requires the SQLite backend' });
918
- }
919
- const db = (store as any).getDb();
920
-
921
- let engramSql = `SELECT id, agent_id, concept, content, confidence, salience, access_count,
922
- last_accessed, created_at, salience_features, reason_codes, stage, ttl,
923
- retracted, retracted_by, retracted_at, tags
924
- FROM engrams`;
925
- const conditions: string[] = [];
926
- const params: string[] = [];
927
-
928
- if (agentId) {
929
- conditions.push('agent_id = ?');
930
- params.push(agentId);
931
- }
932
- if (!includeAll) {
933
- conditions.push('retracted = 0');
934
- conditions.push("stage = 'active'");
935
- }
936
- if (conditions.length > 0) {
937
- engramSql += ' WHERE ' + conditions.join(' AND ');
938
- }
939
- engramSql += ' ORDER BY created_at ASC';
940
-
941
- const engrams = db.prepare(engramSql).all(...params) as { id: string }[];
942
-
943
- const engramIds = new Set(engrams.map(e => e.id));
944
- const allAssocs = db.prepare(
945
- `SELECT id, from_engram_id, to_engram_id, weight, confidence, type, activation_count, created_at, last_activated
946
- FROM associations`
947
- ).all() as { from_engram_id: string; to_engram_id: string }[];
948
- const associations = allAssocs.filter(a => engramIds.has(a.from_engram_id) && engramIds.has(a.to_engram_id));
949
-
950
- return reply.send({
951
- exported_at: new Date().toISOString(),
952
- agent_id: agentId ?? null,
953
- include_all: includeAll,
954
- engrams_count: engrams.length,
955
- associations_count: associations.length,
956
- engrams,
957
- associations,
958
- });
959
- });
960
-
961
- // ─── Health ─────────────────────────────────────────────────────────────
962
-
963
- // D3 (2026-07-30): instance identity — which AWM is this?
964
- app.get('/whoami', async (req) => {
965
- const agentId = (req.query as { agent?: string })?.agent ?? process.env.AWM_AGENT_ID ?? 'default';
966
- return buildWhoami(store, agentId, 'http');
967
- });
968
-
969
- app.get('/health', async () => {
970
- const coordEnabled = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
971
- const base: Record<string, unknown> = {
972
- status: 'ok',
973
- timestamp: new Date().toISOString(),
974
- version: VERSION,
975
- coordination: coordEnabled,
976
- // D15 (2026-07-30): consolidation visibility — finishes the long-unwired
977
- // "DMN endpoint" (May P2). Answers "is a sleep cycle running right now
978
- // and is the scheduler even on" without reading logs.
979
- consolidation: {
980
- schedulerDisabled: consolidationScheduler.isDisabled(),
981
- cycleRunning: consolidationScheduler.isRunning(),
982
- ...getConsolidationState().active
983
- ? { activeCycle: getConsolidationState() }
984
- : {},
985
- },
986
- };
987
- if (coordEnabled && typeof (deps.store as any).getDb === 'function') {
988
- try {
989
- const db = (deps.store as any).getDb();
990
- const stats = db.prepare(`SELECT
991
- (SELECT COUNT(*) FROM coord_agents WHERE status != 'dead') AS agents_alive,
992
- (SELECT COUNT(*) FROM coord_assignments WHERE status = 'pending') AS pending_tasks,
993
- (SELECT COUNT(*) FROM coord_locks) AS active_locks`).get() as { agents_alive: number; pending_tasks: number; active_locks: number };
994
- Object.assign(base, stats);
995
- } catch { /* tables may not exist yet */ }
996
- }
997
- return base;
998
- });
999
- }
1
+ // Copyright 2026 Robert Winter / Complete Ideas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ /**
4
+ * API Routes — the black box interface agents interact with.
5
+ *
6
+ * Core (agent-facing):
7
+ * POST /memory/write — write a memory (salience filter decides disposition)
8
+ * POST /memory/activate — retrieve by context activation
9
+ * POST /memory/feedback — report whether a memory was useful
10
+ * POST /memory/retract — invalidate a wrong memory
11
+ *
12
+ * Checkpointing:
13
+ * POST /memory/checkpoint — save explicit execution state
14
+ * GET /memory/restore/:agentId — restore state + targeted recall + async mini-consolidation
15
+ *
16
+ * Task management:
17
+ * POST /task/create — create a prioritized task
18
+ * POST /task/update — update status, priority, or blocking
19
+ * GET /task/list/:agentId — list tasks (filtered by status)
20
+ * GET /task/next/:agentId — get highest-priority actionable task
21
+ *
22
+ * Diagnostic (debugging/eval):
23
+ * POST /memory/search — deterministic search (not cognitive)
24
+ * GET /memory/:id — get a specific engram
25
+ * GET /agent/:id/stats — memory stats for an agent
26
+ * GET /agent/:id/metrics — eval metrics
27
+ * POST /agent/register — register a new agent
28
+ *
29
+ * System:
30
+ * POST /system/evict — trigger eviction check
31
+ * POST /system/decay — trigger edge decay
32
+ * POST /system/consolidate — run sleep cycle (strengthen, decay, sweep)
33
+ * GET /health — health check
34
+ */
35
+
36
+ import type { FastifyInstance } from 'fastify';
37
+ import { buildWhoami } from '../core/whoami.js';
38
+ import { getConsolidationState } from '../core/write-telemetry.js';
39
+ import type { IEngramStore as EngramStore } from '../storage/store.js';
40
+ import type { ActivationEngine } from '../engine/activation.js';
41
+ import type { ConnectionEngine } from '../engine/connections.js';
42
+ import type { EvictionEngine } from '../engine/eviction.js';
43
+ import type { RetractionEngine } from '../engine/retraction.js';
44
+ import type { EvalEngine } from '../engine/eval.js';
45
+ import type { ConsolidationEngine } from '../engine/consolidation.js';
46
+ import type { ConsolidationScheduler } from '../engine/consolidation-scheduler.js';
47
+ import { evaluateSalience, computeNovelty } from '../core/salience.js';
48
+ import type { SalienceEventType } from '../core/salience.js';
49
+ import { performWrite } from '../core/write-pipeline.js';
50
+ import type { TaskStatus, TaskPriority } from '../types/engram.js';
51
+ import type { ConsciousState } from '../types/checkpoint.js';
52
+ import { DEFAULT_AGENT_CONFIG } from '../types/agent.js';
53
+ import { embed, embedBatch, embeddingHealth } from '../core/embeddings.js';
54
+ import { VERSION } from '../version.js';
55
+ import { activeRecallConfig, recallConfigFingerprint } from '../core/recall-config.js';
56
+
57
+ export interface MemoryDeps {
58
+ store: EngramStore;
59
+ activationEngine: ActivationEngine;
60
+ connectionEngine: ConnectionEngine;
61
+ evictionEngine: EvictionEngine;
62
+ retractionEngine: RetractionEngine;
63
+ evalEngine: EvalEngine;
64
+ consolidationEngine: ConsolidationEngine;
65
+ consolidationScheduler: ConsolidationScheduler;
66
+ }
67
+
68
+ export function registerRoutes(app: FastifyInstance, deps: MemoryDeps): void {
69
+ const { store, activationEngine, connectionEngine, evictionEngine, retractionEngine, evalEngine, consolidationEngine, consolidationScheduler } = deps;
70
+
71
+ // ============================================================
72
+ // CORE — Agent-facing endpoints
73
+ // ============================================================
74
+
75
+ app.post('/memory/write', async (req, reply) => {
76
+ const body = req.body as {
77
+ agentId: string;
78
+ concept: string;
79
+ content: string;
80
+ tags?: string[];
81
+ eventType?: SalienceEventType;
82
+ surprise?: number;
83
+ decisionMade?: boolean;
84
+ causalDepth?: number;
85
+ resolutionEffort?: number;
86
+ confidence?: number;
87
+ // Memory class canonical bypasses salience filter; structural is
88
+ // for system-written event-log records (see 0.8 spec). Restored in
89
+ // 0.8.0 after the field was dropped from the HTTP body schema during
90
+ // the 0.7.x refactor — core/salience.ts:88-89,124,187 and
91
+ // core/write-pipeline.ts:77 still expect and honor it, so HTTP
92
+ // callers were silently losing the canonical-bypass signal.
93
+ memory_class?: 'canonical' | 'working' | 'ephemeral' | 'structural';
94
+ // Optional story-time / sequence ordering (0.8 Cluster A). NULL by
95
+ // default. Used by sortBy: "sequence" on /memory/search and by
96
+ // /memory/latest-by-tag (0.8 Cluster C).
97
+ sequence?: number;
98
+ // Force embedding for structural-class writes. Defaults to false for
99
+ // structural (deterministic retrieval only) opt in here when cognitive
100
+ // recall over a structural engram is desired. (0.8 Cluster A)
101
+ embed?: boolean;
102
+ // Typed cross-record links (0.8 Cluster D). Each reference is
103
+ // {type, matchEngramId?, matchConcept?}. If matchConcept is given
104
+ // without matchEngramId, AWM resolves it to the most recent active
105
+ // engram at write time and stores BOTH on the reference (stable link).
106
+ // If no match found, stores just matchConcept (caller may be linking
107
+ // to a future or deleted engram). Types: advances | resolves |
108
+ // subverts | abandons | extends | supersedes.
109
+ references?: Array<{
110
+ type: 'advances' | 'resolves' | 'subverts' | 'abandons' | 'extends' | 'supersedes';
111
+ matchEngramId?: string;
112
+ matchConcept?: string;
113
+ matchTags?: string[];
114
+ }>;
115
+ // Agent-provided metadata (stored as searchable tags)
116
+ project?: string;
117
+ topic?: string;
118
+ source?: string;
119
+ confidenceLevel?: string;
120
+ sessionId?: string;
121
+ intent?: string;
122
+ // Memory spine (D5/D8, 2026-07-30) — camelCase and snake_case accepted.
123
+ originClass?: string; origin_class?: string;
124
+ recipeId?: string; recipe_id?: string;
125
+ validFrom?: string; valid_from?: string;
126
+ validTo?: string; valid_to?: string;
127
+ };
128
+
129
+ if (!body.agentId || typeof body.agentId !== 'string' ||
130
+ !body.concept || typeof body.concept !== 'string' ||
131
+ !body.content || typeof body.content !== 'string') {
132
+ return reply.status(400).send({ error: 'agentId, concept, and content are required strings' });
133
+ }
134
+
135
+ // Assemble tags: user-provided + agent metadata
136
+ const userTags = body.tags ?? [];
137
+ const metaTags: string[] = [];
138
+ if (body.project) metaTags.push(`proj=${body.project}`);
139
+ if (body.topic) metaTags.push(`topic=${body.topic}`);
140
+ if (body.source) metaTags.push(`src=${body.source}`);
141
+ if (body.confidenceLevel) metaTags.push(`conf=${body.confidenceLevel}`);
142
+ if (body.sessionId) metaTags.push(`sid=${body.sessionId}`);
143
+ if (body.intent) metaTags.push(`intent=${body.intent}`);
144
+
145
+ // Resolve references (0.8 Cluster D): if matchConcept is given without
146
+ // matchEngramId, look up the most recent active engram with that concept
147
+ // (+ optional matchTags) and store both. Stable link survives concept
148
+ // edits. No match found → store just matchConcept so the intent
149
+ // (link-to-future or link-to-deleted) is preserved.
150
+ const resolvedRefs = await Promise.all((body.references ?? []).map(async ref => {
151
+ if (!ref.matchEngramId && ref.matchConcept) {
152
+ const matched = await store.findActiveMatchByConcept(
153
+ body.agentId, ref.matchConcept, ref.matchTags,
154
+ );
155
+ if (matched) {
156
+ return { type: ref.type, matchEngramId: matched.id, matchConcept: ref.matchConcept };
157
+ }
158
+ }
159
+ return { type: ref.type, matchEngramId: ref.matchEngramId, matchConcept: ref.matchConcept };
160
+ }));
161
+
162
+ const result = await performWrite({ store, connectionEngine }, {
163
+ agentId: body.agentId,
164
+ concept: body.concept,
165
+ content: body.content,
166
+ tags: [...userTags, ...metaTags],
167
+ memoryClass: body.memory_class,
168
+ eventType: body.eventType,
169
+ surprise: body.surprise,
170
+ decisionMade: body.decisionMade,
171
+ causalDepth: body.causalDepth,
172
+ resolutionEffort: body.resolutionEffort,
173
+ confidence: body.confidence,
174
+ sequence: body.sequence,
175
+ embed: body.embed,
176
+ references: resolvedRefs.length > 0 ? resolvedRefs : undefined,
177
+ originClass: body.originClass ?? body.origin_class,
178
+ writerSession: body.sessionId,
179
+ recipeId: body.recipeId ?? body.recipe_id,
180
+ validFrom: body.validFrom ?? body.valid_from,
181
+ validTo: body.validTo ?? body.valid_to,
182
+ });
183
+
184
+ // Auto-checkpoint always (covers create, reinforce, and supersede).
185
+ try { await store.updateAutoCheckpointWrite(body.agentId, result.engram.id); } catch { /* non-fatal */ }
186
+
187
+ if (result.action === 'reinforce') {
188
+ return reply.code(200).send({
189
+ stored: false,
190
+ action: 'reinforce',
191
+ disposition: 'reinforced',
192
+ engram: result.engram,
193
+ reinforce: result.reinforce,
194
+ novelty: result.noveltyResult.novelty,
195
+ });
196
+ }
197
+
198
+ // create / supersede paths follow legacy temporal-edge + episode logic.
199
+ // Structural-class writes (0.8 Cluster A) skip these: they're system-written
200
+ // event-log records, not conversational beats, so keeping them out of the
201
+ // temporal graph + episode index keeps cognitive retrieval clean.
202
+ const isStructural = body.memory_class === 'structural';
203
+ if (!isStructural) {
204
+ try {
205
+ const prev = await store.getLatestEngram(body.agentId, result.engram.id);
206
+ if (prev) {
207
+ await store.upsertAssociation(prev.id, result.engram.id, 0.3, 'temporal', 0.8);
208
+ }
209
+ } catch { /* Temporal edge creation is non-fatal */ }
210
+
211
+ if (result.salience
212
+ && (result.salience.disposition === 'active' || result.salience.disposition === 'discard')) {
213
+ try {
214
+ let episode = await store.getActiveEpisode(body.agentId, 3600_000);
215
+ if (!episode) {
216
+ episode = await store.createEpisode({ agentId: body.agentId, label: body.concept });
217
+ }
218
+ await store.addEngramToEpisode(result.engram.id, episode.id);
219
+ } catch { /* Episode assignment is non-fatal */ }
220
+ }
221
+ }
222
+
223
+ const isLowSalience = result.salience?.disposition === 'discard';
224
+ return reply.code(201).send({
225
+ stored: true,
226
+ action: result.action,
227
+ // disposition: legacy field 'low-salience' is returned for discard so
228
+ // callers know the engram was kept but marked low-value. The raw inner
229
+ // salience decision is exposed as `salienceDisposition` for callers
230
+ // (and tests) that want the unmapped value.
231
+ disposition: isLowSalience ? 'low-salience' : (result.salience?.disposition ?? 'active'),
232
+ salienceDisposition: result.salience?.disposition ?? null,
233
+ salience: result.salience?.score ?? 0,
234
+ reasonCodes: result.salience?.reasonCodes ?? [],
235
+ engram: result.engram,
236
+ supersedeOf: result.supersedeOf,
237
+ });
238
+ });
239
+
240
+ /**
241
+ * Bulk write accepts many facts in one request.
242
+ * Creates engrams in a single transaction, embeds in batch.
243
+ * Returns all IDs for downstream supersession calls.
244
+ */
245
+ app.post('/memory/write-batch', async (req, reply) => {
246
+ const body = req.body as {
247
+ agentId: string;
248
+ sessionId?: string; // Shared session ID for all memories in this batch
249
+ memories: Array<{
250
+ concept: string;
251
+ content: string;
252
+ tags?: string[];
253
+ supersedes?: string;
254
+ sessionId?: string; // Per-memory session override
255
+ }>;
256
+ };
257
+
258
+ if (!body.agentId || !body.memories || body.memories.length === 0) {
259
+ return reply.code(400).send({ error: 'agentId and non-empty memories array required' });
260
+ }
261
+
262
+ const results: Array<{ id: string; concept: string; disposition: string }> = [];
263
+
264
+ for (const mem of body.memories) {
265
+ // Add session ID tag if provided (batch-level or per-memory)
266
+ const sid = mem.sessionId ?? body.sessionId;
267
+ const memTags = [...(mem.tags ?? [])];
268
+ if (sid) memTags.push(`sid=${sid}`);
269
+
270
+ const engram = await store.createEngram({
271
+ agentId: body.agentId,
272
+ concept: mem.concept,
273
+ content: mem.content,
274
+ tags: memTags,
275
+ salience: 0.5,
276
+ confidence: 0.5,
277
+ supersedes: mem.supersedes ?? undefined,
278
+ });
279
+
280
+ // Handle supersession inline — archive superseded memory to remove from active pool
281
+ if (mem.supersedes) {
282
+ await store.supersedeEngram(mem.supersedes, engram.id);
283
+ await store.updateConfidence(mem.supersedes, 0.1);
284
+ await store.updateStage(mem.supersedes, 'archived'); // Remove from active search pool
285
+ }
286
+
287
+ results.push({ id: engram.id, concept: mem.concept, disposition: 'active' });
288
+ }
289
+
290
+ // Batch embed synchronously ensures embeddings are ready before queries hit
291
+ const texts = body.memories.map((m, i) => `${m.concept} ${m.content}`);
292
+ try {
293
+ const vecs = await embedBatch(texts);
294
+ for (let i = 0; i < vecs.length; i++) {
295
+ if (results[i]) {
296
+ await store.updateEmbedding(results[i].id, vecs[i]);
297
+ }
298
+ }
299
+ } catch { /* Embedding failure is non-fatal */ }
300
+
301
+ try { await store.updateAutoCheckpointWrite(body.agentId, results[results.length - 1]?.id ?? ''); } catch {}
302
+
303
+ return reply.code(201).send({
304
+ stored: results.length,
305
+ results,
306
+ });
307
+ });
308
+
309
+ app.post('/memory/activate', async (req, reply) => {
310
+ const body = req.body as {
311
+ agentId: string;
312
+ context: string;
313
+ limit?: number;
314
+ minScore?: number;
315
+ includeStaging?: boolean;
316
+ useReranker?: boolean;
317
+ useExpansion?: boolean;
318
+ abstentionThreshold?: number;
319
+ requireConfidence?: number;
320
+ workspace?: string;
321
+ bm25Only?: boolean;
322
+ granularity?: 'full' | 'compact' | 'auto';
323
+ };
324
+
325
+ const results = await activationEngine.activate({
326
+ agentId: body.agentId,
327
+ context: body.context,
328
+ limit: body.limit,
329
+ minScore: body.minScore,
330
+ includeStaging: body.includeStaging,
331
+ useReranker: body.useReranker,
332
+ useExpansion: body.useExpansion,
333
+ abstentionThreshold: body.abstentionThreshold,
334
+ requireConfidence: body.requireConfidence,
335
+ workspace: body.workspace,
336
+ bm25Only: body.bm25Only,
337
+ granularity: body.granularity,
338
+ });
339
+
340
+ // Auto-checkpoint: track recall for consolidation scheduling
341
+ try {
342
+ const ids = results.map(r => r.engram.id);
343
+ await store.updateAutoCheckpointRecall(body.agentId, body.context, ids);
344
+ } catch { /* non-fatal */ }
345
+
346
+ // Surface recall confidence as a top-level field too same value is on
347
+ // every result, but it describes the recall as a whole, so exposing it
348
+ // once is easier for consumers (and lets them inspect 0-result recalls).
349
+ const confidence = results[0]?.confidence ?? 0;
350
+ return reply.send({ results, confidence });
351
+ });
352
+
353
+ app.post('/memory/feedback', async (req, reply) => {
354
+ const body = req.body as {
355
+ activationEventId?: string;
356
+ engramId: string;
357
+ useful: boolean;
358
+ context?: string;
359
+ };
360
+
361
+ await store.logRetrievalFeedback(
362
+ body.activationEventId ?? null,
363
+ body.engramId,
364
+ body.useful,
365
+ body.context ?? ''
366
+ );
367
+
368
+ // Update engram confidence based on feedback
369
+ const engram = await store.getEngram(body.engramId);
370
+ if (engram) {
371
+ const config = DEFAULT_AGENT_CONFIG;
372
+ const delta = body.useful
373
+ ? config.feedbackPositiveBoost
374
+ : -config.feedbackNegativePenalty;
375
+ await store.updateConfidence(engram.id, engram.confidence + delta);
376
+ }
377
+
378
+ // Touch activity for consolidation scheduling
379
+ if (engram) {
380
+ try { await store.touchActivity(engram.agentId); } catch { /* non-fatal */ }
381
+ }
382
+
383
+ return reply.send({ recorded: true });
384
+ });
385
+
386
+ app.post('/memory/retract', async (req, reply) => {
387
+ const body = req.body as {
388
+ agentId: string;
389
+ targetEngramId: string;
390
+ reason: string;
391
+ counterContent?: string;
392
+ };
393
+
394
+ const result = await retractionEngine.retract({
395
+ agentId: body.agentId,
396
+ targetEngramId: body.targetEngramId,
397
+ reason: body.reason,
398
+ counterContent: body.counterContent,
399
+ });
400
+
401
+ // Touch activity for consolidation scheduling
402
+ try { await store.touchActivity(body.agentId); } catch { /* non-fatal */ }
403
+
404
+ return reply.send(result);
405
+ });
406
+
407
+ app.post('/memory/supersede', async (req, reply) => {
408
+ const body = req.body as {
409
+ // ── Form A — supersede by existing engram IDs (pre-0.8 behavior) ──
410
+ oldEngramId?: string;
411
+ newEngramId?: string;
412
+ // ── Form B — atomic write-and-supersede by concept match (0.8 Cluster D) ──
413
+ agentId?: string;
414
+ matchConcept?: string;
415
+ matchTags?: string[];
416
+ newEngram?: {
417
+ concept: string;
418
+ content: string;
419
+ tags?: string[];
420
+ memory_class?: 'canonical' | 'working' | 'ephemeral' | 'structural';
421
+ sequence?: number;
422
+ eventType?: SalienceEventType;
423
+ };
424
+ // Common
425
+ reason?: string;
426
+ };
427
+
428
+ const isFormA = !!(body.oldEngramId && body.newEngramId);
429
+ const isFormB = !!(body.matchConcept && body.newEngram && body.agentId);
430
+
431
+ if (isFormA && isFormB) {
432
+ return reply.code(400).send({
433
+ error: 'Pass either {oldEngramId, newEngramId} (Form A) OR ' +
434
+ '{agentId, matchConcept, newEngram} (Form B), not both.',
435
+ });
436
+ }
437
+ if (!isFormA && !isFormB) {
438
+ return reply.code(400).send({
439
+ error: 'Missing required fields. Form A: {oldEngramId, newEngramId}. ' +
440
+ 'Form B: {agentId, matchConcept, newEngram}.',
441
+ });
442
+ }
443
+
444
+ // ── Form A — by IDs ──
445
+ if (isFormA) {
446
+ const oldEngram = await store.getEngram(body.oldEngramId!);
447
+ const newEngram = await store.getEngram(body.newEngramId!);
448
+ if (!oldEngram) return reply.code(404).send({ error: `Old engram ${body.oldEngramId} not found` });
449
+ if (!newEngram) return reply.code(404).send({ error: `New engram ${body.newEngramId} not found` });
450
+
451
+ await store.upsertAssociation(body.newEngramId!, body.oldEngramId!, 0.8, 'causal', 1.0);
452
+ await store.updateConfidence(body.oldEngramId!, oldEngram.confidence * 0.2);
453
+ await store.supersedeEngram(body.oldEngramId!, body.newEngramId!);
454
+ try { await store.touchActivity(oldEngram.agentId); } catch { /* non-fatal */ }
455
+
456
+ return reply.send({
457
+ superseded: body.oldEngramId,
458
+ supersededBy: body.newEngramId,
459
+ reason: body.reason ?? 'outdated',
460
+ });
461
+ }
462
+
463
+ // ── Form B atomic write-and-supersede by concept match ──
464
+ // Find old (most recent active match by concept + optional tags), write
465
+ // new engram via performWrite, link them all in one SQL transaction.
466
+ // If no match: write new anyway, return { superseded: null }.
467
+ // AWM 0.8.x P4b follow-up: Form B atomicity via withTransaction.
468
+ // Holds the SQLite/PGlite lock across the async write + supersede pair
469
+ // so callers never observe a half-completed state.
470
+ const result = await (store.withTransaction(async () => {
471
+ const matched = await store.findActiveMatchByConcept(
472
+ body.agentId!, body.matchConcept!, body.matchTags,
473
+ );
474
+
475
+ const writeRes = await performWrite({ store, connectionEngine }, {
476
+ agentId: body.agentId!,
477
+ concept: body.newEngram!.concept,
478
+ content: body.newEngram!.content,
479
+ tags: body.newEngram!.tags ?? [],
480
+ memoryClass: body.newEngram!.memory_class,
481
+ sequence: body.newEngram!.sequence,
482
+ eventType: body.newEngram!.eventType,
483
+ enableReinforcement: false,
484
+ });
485
+
486
+ if (matched) {
487
+ await store.upsertAssociation(writeRes.engram.id, matched.id, 0.8, 'causal', 1.0);
488
+ await store.updateConfidence(matched.id, matched.confidence * 0.2);
489
+ await store.supersedeEngram(matched.id, writeRes.engram.id);
490
+ }
491
+ return { writeRes, matched };
492
+ }) as Promise<{ writeRes: Awaited<ReturnType<typeof performWrite>>; matched: any }>);
493
+
494
+ try { await store.touchActivity(body.agentId!); } catch { /* non-fatal */ }
495
+
496
+ return reply.code(201).send({
497
+ newEngram: result.writeRes.engram,
498
+ superseded: result.matched ? result.matched.id : null,
499
+ supersededBy: result.writeRes.engram.id,
500
+ reason: body.reason ?? 'resolved by concept match',
501
+ });
502
+ });
503
+
504
+ // ============================================================
505
+ // DIAGNOSTIC — Debugging and inspection
506
+ // ============================================================
507
+
508
+ app.post('/memory/search', async (req, reply) => {
509
+ const body = req.body as {
510
+ agentId: string;
511
+ text?: string;
512
+ concept?: string;
513
+ tags?: string[]; // legacy AND-filterpreserved, equivalent to tagsAll
514
+ tagsAll?: string[]; // 0.8 Cluster B — explicit AND
515
+ tagsAny?: string[]; // 0.8 Cluster B — OR (at least one)
516
+ tagsNone?: string[]; // 0.8 Cluster B — NOT (exclude all)
517
+ stage?: string;
518
+ retracted?: boolean;
519
+ limit?: number;
520
+ offset?: number;
521
+ sortBy?: 'createdAt' | 'sequence' | 'salience' | 'confidence' | 'lastAccessed';
522
+ sortOrder?: 'asc' | 'desc';
523
+ };
524
+
525
+ const results = await store.search({
526
+ agentId: body.agentId,
527
+ text: body.text,
528
+ concept: body.concept,
529
+ tags: body.tags,
530
+ tagsAll: body.tagsAll,
531
+ tagsAny: body.tagsAny,
532
+ tagsNone: body.tagsNone,
533
+ stage: body.stage as any,
534
+ retracted: body.retracted,
535
+ limit: body.limit,
536
+ offset: body.offset,
537
+ sortBy: body.sortBy,
538
+ sortOrder: body.sortOrder,
539
+ });
540
+
541
+ return reply.send({ results, count: results.length });
542
+ });
543
+
544
+ // ============================================================
545
+ // 0.8 Cluster C — materialized-view + atomic-counter endpoints
546
+ // ============================================================
547
+
548
+ /**
549
+ * For each distinct value of `tagKey`, return the most recent active
550
+ * engram. Used by NovelForge for "latest emotional state per character",
551
+ * "latest motif phase per motif", etc.
552
+ */
553
+ app.post('/memory/latest-by-tag', async (req, reply) => {
554
+ const body = req.body as {
555
+ agentId: string;
556
+ tagKey: string; // e.g. "character=", "motif="
557
+ scopeTagsAll?: string[]; // optional narrowing
558
+ retracted?: boolean;
559
+ sortBy?: 'createdAt' | 'sequence';
560
+ limit?: number;
561
+ };
562
+ if (!body.agentId || !body.tagKey) {
563
+ return reply.code(400).send({ error: 'agentId and tagKey are required' });
564
+ }
565
+ const results = await store.getLatestByTag({
566
+ agentId: body.agentId,
567
+ tagKeyPrefix: body.tagKey,
568
+ scopeTagsAll: body.scopeTagsAll,
569
+ retracted: body.retracted ?? false,
570
+ sortBy: body.sortBy,
571
+ limit: body.limit,
572
+ });
573
+ return reply.send({ results, count: results.length });
574
+ });
575
+
576
+ /**
577
+ * Filter by tag-set operators, sort by numeric value extracted from a
578
+ * tag prefix, return top N. Used by NovelForge for "top N active
579
+ * promises by weight".
580
+ */
581
+ app.post('/memory/top-by', async (req, reply) => {
582
+ const body = req.body as {
583
+ agentId: string;
584
+ sortField: string; // tag prefix, e.g. "weight="
585
+ order?: 'asc' | 'desc'; // default desc
586
+ filterTagsAll?: string[];
587
+ filterTagsAny?: string[];
588
+ filterTagsNone?: string[];
589
+ retracted?: boolean;
590
+ limit?: number;
591
+ };
592
+ if (!body.agentId || !body.sortField) {
593
+ return reply.code(400).send({ error: 'agentId and sortField are required' });
594
+ }
595
+ const results = await store.getTopBy({
596
+ agentId: body.agentId,
597
+ sortField: body.sortField,
598
+ order: body.order ?? 'desc',
599
+ filterTagsAll: body.filterTagsAll,
600
+ filterTagsAny: body.filterTagsAny,
601
+ filterTagsNone: body.filterTagsNone,
602
+ retracted: body.retracted ?? false,
603
+ limit: body.limit,
604
+ });
605
+ return reply.send({ results, count: results.length });
606
+ });
607
+
608
+ /**
609
+ * Compute effective state of an engram from referenced events. Two
610
+ * targeting modes: by ID, or by concept match (same semantics as Form B's
611
+ * findActiveMatchByConcept).
612
+ */
613
+ app.post('/memory/resolve', async (req, reply) => {
614
+ const body = req.body as {
615
+ agentId: string;
616
+ targetEngramId?: string;
617
+ matchConcept?: string;
618
+ matchTags?: string[];
619
+ };
620
+ if (!body.agentId) {
621
+ return reply.code(400).send({ error: 'agentId is required' });
622
+ }
623
+
624
+ let targetId = body.targetEngramId;
625
+ if (!targetId && body.matchConcept) {
626
+ const matched = await store.findActiveMatchByConcept(
627
+ body.agentId, body.matchConcept, body.matchTags,
628
+ );
629
+ if (!matched) {
630
+ return reply.code(404).send({
631
+ error: `No active engram matches concept "${body.matchConcept}"`,
632
+ });
633
+ }
634
+ targetId = matched.id;
635
+ }
636
+ if (!targetId) {
637
+ return reply.code(400).send({
638
+ error: 'Provide either targetEngramId or matchConcept',
639
+ });
640
+ }
641
+
642
+ const result = await store.resolveEffectiveState(targetId);
643
+ if (!result) return reply.code(404).send({ error: `Engram ${targetId} not found` });
644
+ return reply.send(result);
645
+ });
646
+
647
+ /**
648
+ * Race-free next-sequence allocator. Caller writes the engram with the
649
+ * returned value in `sequence`. Doesn't reserve — concurrent allocations
650
+ * always serialize via BEGIN IMMEDIATE.
651
+ */
652
+ app.get('/memory/sequence/:agentId/next', async (req, reply) => {
653
+ const { agentId } = req.params as { agentId: string };
654
+ const next = await store.allocateNextSequence(agentId);
655
+ return reply.send({ agentId, next });
656
+ });
657
+
658
+ app.get('/memory/:id', async (req, reply) => {
659
+ const { id } = req.params as { id: string };
660
+ const engram = await store.getEngram(id);
661
+ if (!engram) return reply.code(404).send({ error: 'Not found' });
662
+
663
+ const associations = await store.getAssociationsFor(id);
664
+ return reply.send({ engram, associations });
665
+ });
666
+
667
+ app.get('/agent/:id/stats', async (req, reply) => {
668
+ const { id } = req.params as { id: string };
669
+ const active = await store.getEngramsByAgent(id, 'active');
670
+ const staging = await store.getEngramsByAgent(id, 'staging');
671
+ const retracted = (await store.getEngramsByAgent(id, undefined, true)).filter(e => e.retracted);
672
+ const associations = await store.getAllAssociations(id);
673
+
674
+ return reply.send({
675
+ agentId: id,
676
+ engrams: {
677
+ active: active.length,
678
+ staging: staging.length,
679
+ retracted: retracted.length,
680
+ total: active.length + staging.length + retracted.length,
681
+ },
682
+ associations: associations.length,
683
+ avgConfidence: active.length > 0
684
+ ? +(active.reduce((s, e) => s + e.confidence, 0) / active.length).toFixed(3)
685
+ : 0,
686
+ });
687
+ });
688
+
689
+ app.get('/agent/:id/metrics', async (req, reply) => {
690
+ const { id } = req.params as { id: string };
691
+ const windowHours = parseInt((req.query as any).window ?? '24', 10);
692
+ const metrics = await evalEngine.computeMetrics(id, windowHours);
693
+ return reply.send({ metrics });
694
+ });
695
+
696
+ app.post('/agent/register', async (req, reply) => {
697
+ const body = req.body as { name: string };
698
+ const id = crypto.randomUUID();
699
+ return reply.code(201).send({
700
+ id,
701
+ name: body.name,
702
+ config: DEFAULT_AGENT_CONFIG,
703
+ });
704
+ });
705
+
706
+ // ============================================================
707
+ // SYSTEM — Maintenance operations
708
+ // ============================================================
709
+
710
+ app.post('/system/evict', async (req, reply) => {
711
+ const body = req.body as { agentId: string };
712
+ const result = await evictionEngine.enforceCapacity(body.agentId, DEFAULT_AGENT_CONFIG);
713
+ return reply.send(result);
714
+ });
715
+
716
+ app.post('/system/decay', async (req, reply) => {
717
+ const body = req.body as { agentId: string; halfLifeDays?: number };
718
+ const decayed = await evictionEngine.decayEdges(body.agentId, body.halfLifeDays);
719
+ return reply.send({ edgesDecayed: decayed });
720
+ });
721
+
722
+ app.post('/system/consolidate', async (req, reply) => {
723
+ const body = req.body as { agentId: string };
724
+ const result = await consolidationEngine.consolidate(body.agentId);
725
+ return reply.send(result);
726
+ });
727
+
728
+ // ============================================================
729
+ // CHECKPOINTING — Conscious state preservation
730
+ // ============================================================
731
+
732
+ app.post('/memory/checkpoint', async (req, reply) => {
733
+ const body = req.body as {
734
+ agentId: string;
735
+ currentTask: string;
736
+ decisions?: string[];
737
+ activeFiles?: string[];
738
+ nextSteps?: string[];
739
+ relatedMemoryIds?: string[];
740
+ notes?: string;
741
+ episodeId?: string | null;
742
+ };
743
+
744
+ const state: ConsciousState = {
745
+ currentTask: body.currentTask,
746
+ decisions: body.decisions ?? [],
747
+ activeFiles: body.activeFiles ?? [],
748
+ nextSteps: body.nextSteps ?? [],
749
+ relatedMemoryIds: body.relatedMemoryIds ?? [],
750
+ notes: body.notes ?? '',
751
+ episodeId: body.episodeId ?? null,
752
+ };
753
+
754
+ store.saveCheckpoint(body.agentId, state);
755
+ return reply.send({ saved: true, agentId: body.agentId });
756
+ });
757
+
758
+ app.get('/memory/restore/:agentId', async (req, reply) => {
759
+ const { agentId } = req.params as { agentId: string };
760
+ const checkpoint = await store.getCheckpoint(agentId);
761
+
762
+ const now = Date.now();
763
+ const idleMs = checkpoint
764
+ ? now - checkpoint.auto.lastActivityAt.getTime()
765
+ : 0;
766
+
767
+ // Get last written engram for context
768
+ let lastWrite: { id: string; concept: string; content: string } | null = null;
769
+ if (checkpoint?.auto.lastWriteId) {
770
+ const engram = await store.getEngram(checkpoint.auto.lastWriteId);
771
+ if (engram) {
772
+ lastWrite = { id: engram.id, concept: engram.concept, content: engram.content };
773
+ }
774
+ }
775
+
776
+ // Recall memories using last context (if available)
777
+ let recalledMemories: Array<{ id: string; concept: string; content: string; score: number }> = [];
778
+ const recallContext = checkpoint?.auto.lastRecallContext
779
+ ?? checkpoint?.executionState?.currentTask
780
+ ?? null;
781
+
782
+ if (recallContext) {
783
+ try {
784
+ const results = await activationEngine.activate({
785
+ agentId,
786
+ context: recallContext,
787
+ limit: 5,
788
+ minScore: 0.05,
789
+ useReranker: true,
790
+ useExpansion: true,
791
+ });
792
+ recalledMemories = results.map(r => ({
793
+ id: r.engram.id,
794
+ concept: r.engram.concept,
795
+ content: r.engram.content,
796
+ score: r.score,
797
+ }));
798
+ } catch { /* recall failure is non-fatal */ }
799
+ }
800
+
801
+ // Trigger mini-consolidation if idle >5min (async, fire-and-forget)
802
+ const MINI_CONSOLIDATION_IDLE_MS = 5 * 60_000;
803
+ let miniConsolidationTriggered = false;
804
+ if (idleMs > MINI_CONSOLIDATION_IDLE_MS) {
805
+ miniConsolidationTriggered = true;
806
+ consolidationScheduler.runMiniConsolidation(agentId).catch(() => {});
807
+ }
808
+
809
+ return reply.send({
810
+ executionState: checkpoint?.executionState ?? null,
811
+ checkpointAt: checkpoint?.checkpointAt ?? null,
812
+ recalledMemories,
813
+ lastWrite,
814
+ idleMs,
815
+ miniConsolidationTriggered,
816
+ });
817
+ });
818
+
819
+ // ============================================================
820
+ // TASK MANAGEMENT
821
+ // ============================================================
822
+
823
+ app.post('/task/create', async (req, reply) => {
824
+ const body = req.body as {
825
+ agentId: string;
826
+ concept: string;
827
+ content: string;
828
+ tags?: string[];
829
+ priority?: TaskPriority;
830
+ blockedBy?: string;
831
+ };
832
+
833
+ const engram = await store.createEngram({
834
+ agentId: body.agentId,
835
+ concept: body.concept,
836
+ content: body.content,
837
+ tags: [...(body.tags ?? []), 'task'],
838
+ salience: 0.9,
839
+ confidence: 0.8,
840
+ salienceFeatures: {
841
+ surprise: 0.5, decisionMade: true, causalDepth: 0.5,
842
+ resolutionEffort: 0.5, eventType: 'decision',
843
+ },
844
+ reasonCodes: ['task-created'],
845
+ taskStatus: body.blockedBy ? 'blocked' : 'open',
846
+ taskPriority: body.priority ?? 'medium',
847
+ blockedBy: body.blockedBy,
848
+ });
849
+
850
+ connectionEngine.enqueue(engram.id);
851
+ embed(`${body.concept} ${body.content}`).then(async vec => {
852
+ await store.updateEmbedding(engram.id, vec);
853
+ }).catch(() => {});
854
+
855
+ return reply.send(engram);
856
+ });
857
+
858
+ app.post('/task/update', async (req, reply) => {
859
+ const body = req.body as {
860
+ taskId: string;
861
+ status?: TaskStatus;
862
+ priority?: TaskPriority;
863
+ blockedBy?: string | null;
864
+ };
865
+
866
+ const engram = await store.getEngram(body.taskId);
867
+ if (!engram || !engram.taskStatus) {
868
+ return reply.code(404).send({ error: 'Task not found' });
869
+ }
870
+
871
+ if (body.blockedBy !== undefined) {
872
+ await store.updateBlockedBy(body.taskId, body.blockedBy);
873
+ }
874
+ if (body.status) {
875
+ await store.updateTaskStatus(body.taskId, body.status);
876
+ }
877
+ if (body.priority) {
878
+ await store.updateTaskPriority(body.taskId, body.priority);
879
+ }
880
+
881
+ return reply.send(await store.getEngram(body.taskId));
882
+ });
883
+
884
+ app.get('/task/list/:agentId', async (req, reply) => {
885
+ const { agentId } = req.params as { agentId: string };
886
+ const { status, includeDone } = req.query as { status?: TaskStatus; includeDone?: string };
887
+
888
+ let tasks = await store.getTasks(agentId, status);
889
+ if (includeDone !== 'true' && !status) {
890
+ tasks = tasks.filter(t => t.taskStatus !== 'done');
891
+ }
892
+
893
+ return reply.send({ tasks, count: tasks.length });
894
+ });
895
+
896
+ app.get('/task/next/:agentId', async (req, reply) => {
897
+ const { agentId } = req.params as { agentId: string };
898
+ const next = await store.getNextTask(agentId);
899
+ return reply.send(next ? { task: next } : { task: null, message: 'No actionable tasks' });
900
+ });
901
+
902
+ // Time warp shift all timestamps backward by N days (for testing)
903
+ app.post('/system/time-warp', async (req, reply) => {
904
+ const body = req.body as { agentId: string; days: number };
905
+ const ms = body.days * 24 * 60 * 60 * 1000;
906
+ const shifted = await store.timeWarp(body.agentId, ms);
907
+ return reply.send({ shifted, days: body.days });
908
+ });
909
+
910
+ // ─── Export ─────────────────────────────────────────────────────────────
911
+
912
+ app.get('/memory/export', async (req, reply) => {
913
+ const { agentId, all } = req.query as { agentId?: string; all?: string };
914
+ const includeAll = all === 'true';
915
+ // /memory/export uses raw SQL SQLite-only. On PGlite, callers should use
916
+ // the awm CLI export/merge tools instead.
917
+ if (typeof (store as any).getDb !== 'function') {
918
+ return reply.code(501).send({ error: 'export endpoint requires the SQLite backend' });
919
+ }
920
+ const db = (store as any).getDb();
921
+
922
+ let engramSql = `SELECT id, agent_id, concept, content, confidence, salience, access_count,
923
+ last_accessed, created_at, salience_features, reason_codes, stage, ttl,
924
+ retracted, retracted_by, retracted_at, tags
925
+ FROM engrams`;
926
+ const conditions: string[] = [];
927
+ const params: string[] = [];
928
+
929
+ if (agentId) {
930
+ conditions.push('agent_id = ?');
931
+ params.push(agentId);
932
+ }
933
+ if (!includeAll) {
934
+ conditions.push('retracted = 0');
935
+ conditions.push("stage = 'active'");
936
+ }
937
+ if (conditions.length > 0) {
938
+ engramSql += ' WHERE ' + conditions.join(' AND ');
939
+ }
940
+ engramSql += ' ORDER BY created_at ASC';
941
+
942
+ const engrams = db.prepare(engramSql).all(...params) as { id: string }[];
943
+
944
+ const engramIds = new Set(engrams.map(e => e.id));
945
+ const allAssocs = db.prepare(
946
+ `SELECT id, from_engram_id, to_engram_id, weight, confidence, type, activation_count, created_at, last_activated
947
+ FROM associations`
948
+ ).all() as { from_engram_id: string; to_engram_id: string }[];
949
+ const associations = allAssocs.filter(a => engramIds.has(a.from_engram_id) && engramIds.has(a.to_engram_id));
950
+
951
+ return reply.send({
952
+ exported_at: new Date().toISOString(),
953
+ agent_id: agentId ?? null,
954
+ include_all: includeAll,
955
+ engrams_count: engrams.length,
956
+ associations_count: associations.length,
957
+ engrams,
958
+ associations,
959
+ });
960
+ });
961
+
962
+ // ─── Health ─────────────────────────────────────────────────────────────
963
+
964
+ // D3 (2026-07-30): instance identity — which AWM is this?
965
+ app.get('/whoami', async (req) => {
966
+ const agentId = (req.query as { agent?: string })?.agent ?? process.env.AWM_AGENT_ID ?? 'default';
967
+ return buildWhoami(store, agentId, 'http');
968
+ });
969
+
970
+ app.get('/health', async () => {
971
+ const coordEnabled = process.env.AWM_COORDINATION === 'true' || process.env.AWM_COORDINATION === '1';
972
+ const base: Record<string, unknown> = {
973
+ status: 'ok',
974
+ timestamp: new Date().toISOString(),
975
+ version: VERSION,
976
+ coordination: coordEnabled,
977
+ // Self-reported recall configuration. A benchmark arm can assert this
978
+ // matches what it set, turning "I measured a stale server with the wrong
979
+ // config" from a silent false result into a loud failure. See
980
+ // src/core/recall-config.ts for why this exists.
981
+ recall: {
982
+ fingerprint: recallConfigFingerprint(),
983
+ flags: activeRecallConfig(),
984
+ },
985
+ // Embedding-corpus integrity. A dimension mismatch scores 0 on the vector
986
+ // channel for the affected memories — recall still answers, just much worse,
987
+ // with no error anywhere. Reported here so "why did quality drop" has somewhere
988
+ // to look other than guessing. Absent when healthy.
989
+ ...(embeddingHealth().dimensionMismatches > 0
990
+ ? { embeddingIntegrity: { status: 'degraded' as const, ...embeddingHealth() } }
991
+ : {}),
992
+ // D15 (2026-07-30): consolidation visibility finishes the long-unwired
993
+ // "DMN endpoint" (May P2). Answers "is a sleep cycle running right now
994
+ // and is the scheduler even on" without reading logs.
995
+ consolidation: {
996
+ schedulerDisabled: consolidationScheduler.isDisabled(),
997
+ cycleRunning: consolidationScheduler.isRunning(),
998
+ ...getConsolidationState().active
999
+ ? { activeCycle: getConsolidationState() }
1000
+ : {},
1001
+ },
1002
+ };
1003
+ if (coordEnabled && typeof (deps.store as any).getDb === 'function') {
1004
+ try {
1005
+ const db = (deps.store as any).getDb();
1006
+ const stats = db.prepare(`SELECT
1007
+ (SELECT COUNT(*) FROM coord_agents WHERE status != 'dead') AS agents_alive,
1008
+ (SELECT COUNT(*) FROM coord_assignments WHERE status = 'pending') AS pending_tasks,
1009
+ (SELECT COUNT(*) FROM coord_locks) AS active_locks`).get() as { agents_alive: number; pending_tasks: number; active_locks: number };
1010
+ Object.assign(base, stats);
1011
+ } catch { /* tables may not exist yet */ }
1012
+ }
1013
+ return base;
1014
+ });
1015
+ }