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