agent-working-memory 0.11.0 → 0.12.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 (99) hide show
  1. package/README.md +29 -0
  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 +329 -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 +3 -0
  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/salience.d.ts.map +1 -1
  22. package/dist/core/salience.js +14 -2
  23. package/dist/core/salience.js.map +1 -1
  24. package/dist/core/whoami.d.ts +24 -0
  25. package/dist/core/whoami.d.ts.map +1 -0
  26. package/dist/core/whoami.js +66 -0
  27. package/dist/core/whoami.js.map +1 -0
  28. package/dist/core/write-pipeline.d.ts +9 -0
  29. package/dist/core/write-pipeline.d.ts.map +1 -1
  30. package/dist/core/write-pipeline.js +109 -68
  31. package/dist/core/write-pipeline.js.map +1 -1
  32. package/dist/core/write-telemetry.d.ts +33 -0
  33. package/dist/core/write-telemetry.d.ts.map +1 -0
  34. package/dist/core/write-telemetry.js +110 -0
  35. package/dist/core/write-telemetry.js.map +1 -0
  36. package/dist/engine/activation.d.ts +22 -12
  37. package/dist/engine/activation.d.ts.map +1 -1
  38. package/dist/engine/activation.js +133 -17
  39. package/dist/engine/activation.js.map +1 -1
  40. package/dist/engine/consolidation-scheduler.d.ts +1 -1
  41. package/dist/engine/consolidation-scheduler.js +1 -1
  42. package/dist/engine/consolidation.d.ts +1 -0
  43. package/dist/engine/consolidation.d.ts.map +1 -1
  44. package/dist/engine/consolidation.js +18 -0
  45. package/dist/engine/consolidation.js.map +1 -1
  46. package/dist/engine/eval.d.ts.map +1 -1
  47. package/dist/engine/eval.js +5 -1
  48. package/dist/engine/eval.js.map +1 -1
  49. package/dist/index.js +20 -2
  50. package/dist/index.js.map +1 -1
  51. package/dist/mcp.d.ts +2 -1
  52. package/dist/mcp.d.ts.map +1 -1
  53. package/dist/mcp.js +168 -100
  54. package/dist/mcp.js.map +1 -1
  55. package/dist/recipes/index.d.ts +57 -0
  56. package/dist/recipes/index.d.ts.map +1 -0
  57. package/dist/recipes/index.js +81 -0
  58. package/dist/recipes/index.js.map +1 -0
  59. package/dist/storage/pglite-schema.d.ts.map +1 -1
  60. package/dist/storage/pglite-schema.js +27 -0
  61. package/dist/storage/pglite-schema.js.map +1 -1
  62. package/dist/storage/pglite.d.ts +5 -0
  63. package/dist/storage/pglite.d.ts.map +1 -1
  64. package/dist/storage/pglite.js +180 -138
  65. package/dist/storage/pglite.js.map +1 -1
  66. package/dist/storage/postgres.d.ts +5 -0
  67. package/dist/storage/postgres.d.ts.map +1 -1
  68. package/dist/storage/postgres.js +180 -138
  69. package/dist/storage/postgres.js.map +1 -1
  70. package/dist/storage/sqlite.d.ts +9 -0
  71. package/dist/storage/sqlite.d.ts.map +1 -1
  72. package/dist/storage/sqlite.js +394 -326
  73. package/dist/storage/sqlite.js.map +1 -1
  74. package/dist/types/engram.d.ts +14 -0
  75. package/dist/types/engram.d.ts.map +1 -1
  76. package/dist/types/engram.js.map +1 -1
  77. package/package.json +1 -1
  78. package/src/adapters/claude-code.ts +66 -3
  79. package/src/adapters/common.ts +538 -515
  80. package/src/api/routes.ts +999 -971
  81. package/src/coordination/routes.ts +2155 -2150
  82. package/src/core/embeddings.ts +3 -0
  83. package/src/core/entity-extract.ts +47 -0
  84. package/src/core/salience.ts +529 -514
  85. package/src/core/whoami.ts +92 -0
  86. package/src/core/write-pipeline.ts +60 -8
  87. package/src/core/write-telemetry.ts +131 -0
  88. package/src/engine/activation.ts +1468 -1369
  89. package/src/engine/consolidation-scheduler.ts +1 -1
  90. package/src/engine/consolidation.ts +887 -869
  91. package/src/engine/eval.ts +6 -1
  92. package/src/index.ts +248 -227
  93. package/src/mcp.ts +1341 -1270
  94. package/src/recipes/index.ts +125 -0
  95. package/src/storage/pglite-schema.ts +27 -0
  96. package/src/storage/pglite.ts +1420 -1372
  97. package/src/storage/postgres.ts +1523 -1475
  98. package/src/storage/sqlite.ts +1936 -1861
  99. package/src/types/engram.ts +22 -0
@@ -164,311 +164,334 @@ export function upsertAwmSection(filePath, newContent, options = {}) {
164
164
  writeFileSync(filePath, rebuilt);
165
165
  return `${fname}: AWM section updated (preserved surrounding content)`;
166
166
  }
167
- export const AWM_INSTRUCTION_CONTENT = `
168
- ## Memory (AWM) — MANDATORY
169
-
170
- **AWM is THE memory system.** Use it via the \`agent-working-memory\` MCP server
171
- (preferred) or HTTP at \`http://127.0.0.1:8400\` (fallback). The file-based
172
- auto-memory at \`~/.claude/projects/.../memory/*.md\` is a LEGACY bootstrap path —
173
- **do not write new memories to it.** All persistent knowledge goes through AWM.
174
-
175
- If MCP tools aren't loaded at session start, use ToolSearch with
176
- \`select:mcp__agent-working-memory__memory_recall,mcp__agent-working-memory__memory_write\`
177
- to load them. If the MCP server isn't responsive, restart with \`/mcp\` or use
178
- the HTTP endpoints (\`POST /memory/write-batch\`, \`POST /memory/activate\`)
179
- directly — but **DO NOT fall back to markdown files**. Files drift the moment
180
- you write them; AWM stays current because every agent reads + writes the same store.
181
-
182
- ### Lifecycle (always do these, in this order)
183
- 1. **Session start**: call \`memory_restore\` to recover previous context. If it reports the
184
- store is empty/new (or recall keeps returning nothing), **warm-start first**: recall the
185
- \`onboard a new project\` skill and follow it — or call \`onboard_scan\` on the project's
186
- docs/repo, refine the candidates, run \`onboard_questions\`, and save the good ones with
187
- \`memory_write\` (canonical). A cold store is nearly useless until it's seeded.
188
- 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
189
- 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
190
- the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
191
- than one filesystem search.
192
- 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
193
- 5. **Finishing a task**: call \`memory_task_end\` with a summary.
194
- 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
195
-
196
- ### Write memory when:
197
- - A project decision is made or changed
198
- - A root cause is discovered after debugging
199
- - A reusable implementation pattern is established
200
- - A user preference, constraint, or requirement is clarified
201
- - A prior assumption is found to be wrong
202
- - A significant piece of work is completed
203
-
204
- ### Writing for recall (the highest-leverage section)
205
- A memory's recall quality is set the moment you write it. AWM is fast at
206
- finding what's findable — but if the write is shaped wrong, no retriever
207
- can rescue it. Be slightly more verbose at the front than feels natural:
208
- the first 1-2 sentences are what BM25, the embedding model, and concept
209
- extraction all see most strongly.
210
-
211
- - **Lead with the rule or fact.** Don't open with context or backstory.
212
- "Don't mock the database in integration tests." comes first; the reason
213
- comes second. Recall scans the head of the body, not the tail.
214
- - **Pick the most specific topic.** Not \`auth\` — \`auth-magic-link-rate-limit\`.
215
- Topic is a hard filter at recall time. Generic topics hide the memory in
216
- a noisy bucket where it competes with everything else in the area.
217
- - **Include 2+ retrievable identifiers.** File paths, function names, table
218
- columns, ticket IDs, exact error strings, the literal terms a future query
219
- will use. \`AccountingService.closePeriod()\` beats "the accounting code."
220
- \`tblMemberDetails.activation_date\` beats "the activation column."
221
- \`schema/072-period-close.sql\` beats "the migration."
222
- - **Write in the vocabulary of the future question.** When you imagine asking
223
- this in three months, what nouns will you use? Use those nouns. Don't
224
- paraphrase the user's domain language into your own neutral summary.
225
- - **Reserve canonical for stable invariants.** Decisions, requirements,
226
- hard facts, cross-agent shared context. Working class (default) is correct
227
- for findings, observations, and progress notes. The canonical floor is
228
- 0.7 salience — overusing it pollutes the canonical layer and the floor
229
- loses meaning.
230
- - **Include the why for feedback memories.** A rule without a reason can't
231
- be applied to edge cases. "Don't mock the database" is brittle. "Don't
232
- mock the database — last quarter mocked tests masked a broken migration"
233
- is portable to new situations.
234
-
235
- ### Tagging rules (REQUIRED — AWM's prefix-tag retrieval boost depends on these)
236
-
237
- Every \`memory_write\` should pass these structured fields. AWM stores each as a
238
- prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
239
- and entity-bridge boosts at recall time.
240
-
241
- | Field | Required? | Format | Example |
242
- |---|---|---|---|
243
- | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
244
- | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
245
- | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
246
- | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
247
- | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
248
- | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
249
- | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
250
- | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
251
-
252
- **Always add identifier tags when present in the content:**
253
- - \`ticket=<id>\` for Freshdesk tickets
254
- - \`member=<id>\` for member IDs
255
- - \`horse=<id>\` for horse_member_id
256
- - \`usef=<id>\` for USEF lookups
257
- - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
258
- - \`person=<Name>\` for stakeholder quotes / decisions
259
- - \`version=<X.Y.Z>\` for release-specific findings
260
-
261
- ### Memory classes (controls how strictly the salience filter gates the write)
262
- - \`memory_class: canonical\` — source-of-truth memories. Floor 0.7 salience, never staged.
263
- Use for: user-stated decisions, project requirements, verified architectural facts,
264
- cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
265
- for writes that other agents must be able to recall** — the default \`working\` class
266
- may get filtered.
267
- - \`memory_class: working\` (default) — observations and findings. Salience-gated.
268
- - \`memory_class: ephemeral\` — short-lived context that should decay quickly.
269
-
270
- ### Salience auto-promotion (defense in depth)
271
- The salience filter automatically promotes certain content patterns even if you forget
272
- to set \`memory_class\` explicitly:
273
- - **User feedback** — content starting with "Robert said…", "Katherine directed…",
274
- "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
275
- always preserves the decision.
276
- - **Verified operational records** — content with an action verb (Submitted, Finalized,
277
- Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
278
- Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
279
- or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
280
- a 0.45 salience floor. So batch summaries with real IDs survive even when topic
281
- terms repeat.
282
-
283
- If neither pattern applies and you want a memory to definitely survive, set
284
- \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
285
-
286
- ### Recall memory when:
287
- - **BEFORE stating ANY fact about how a system works** — recall first; if AWM doesn't
288
- have it, read the code. Never guess and present it as fact.
289
- - **BEFORE searching the filesystem** — recall first; AWM is faster and has cross-session
290
- knowledge that file search doesn't.
291
- - Starting work on a new task or subsystem
292
- - Re-entering code you haven't touched recently
293
- - After a failed attempt — check if there's prior knowledge
294
- - Before refactoring or making architectural changes
295
- - When a topic comes up that you might have prior context on
296
-
297
- Recall is fast (~300ms typical). Use it freely.
298
-
299
- ### Recall strategy (when one query isn't enough)
300
- AWM's adaptive retrieval handles most query variations natively — synonym
301
- expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
302
- A single recall is usually enough.
303
-
304
- When it isn't:
305
- - **If the first recall returns nothing or returns the wrong things, reformulate.**
306
- Try a second query with different phrasing — synonyms, more specific nouns,
307
- the exact identifier from the code rather than the conceptual name. Two or
308
- three recalls cost less than one filesystem search.
309
- - **Use the words a domain expert would use, not generic English.** "Period
310
- close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
311
- - **For broad exploration, pass \`mode: "exploratory"\`** — wider candidate
312
- pool, lower precision floor. For specific lookups, leave mode unset (auto).
313
- - **Don't ensemble more than 3 reformulations.** If three different phrasings
314
- return nothing, the memory probably isn't there — read the code instead of
315
- burning more recalls.
316
-
317
- ### Recall tuning (0.8.x — opt-in parameters for higher-quality recall)
318
- Default \`memory_recall\` is tuned for the common case. The 0.8.x recall pipeline
319
- exposes four opt-in parameters that change the cost/quality tradeoff. Use them
320
- when the default doesn't match what you actually need.
321
-
322
- - **\`granularity: 'compact'\`** — every result carries a 200-char \`summary\`
323
- field with a query-aware snippet (the densest window of query terms in the
324
- content). Use this when you expect to scan 5+ results to find one — saves
325
- ~70% of recall output tokens. The full content stays available in
326
- \`engram.content\` if you want to drill into a specific result.
327
- - **\`granularity: 'auto'\`** — confidence-adaptive. If the top result is a clear
328
- winner, it gets a longer summary while the rest are compact. If confidence
329
- is uniform across results, everything is compact. Use when you don't know
330
- in advance whether one result will dominate.
331
- - **\`require_confidence: 0.10 | 0.25 | 0.40\`** — opt-in abstention. AWM
332
- returns \`[]\` instead of low-confidence noise. Use when you're about to ACT
333
- on the recalled fact (grounding a decision, citing the memory verbatim,
334
- contradicting a prior assumption). Thresholds: \`0.10\` strict — only abstain
335
- on garbage; \`0.25\` balanced; \`0.40\` aggressive — prefer "I don't know"
336
- over "best of bad." When abstention fires (empty result), treat it as a
337
- signal — either the memory genuinely isn't there (read the code) or your
338
- query missed (reformulate). Don't retry without the threshold.
339
- - **\`workspace: "<name>"\`** — hive-mode recall across all agents in the
340
- workspace. Use when other agents may have written canonical knowledge you
341
- need. Default is agent-scoped (your own memories only). Can also be set
342
- globally via the \`AWM_WORKSPACE\` env var.
343
-
344
- ### Keep memory fresh
345
- - After recalling a memory, if you observe the real state is different → call
346
- \`memory_supersede\` immediately with the corrected version.
347
- - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
348
- activation engine learns what's valuable.
349
- - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
350
- - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
351
- drifts out of date. The system relies on you to keep it current. This is the #1
352
- failure mode.**
353
-
354
- ### Content fadewrite-and-forget is safe (0.8.x)
355
- Un-recalled engrams gradually fade their content while preserving cue pathways
356
- (concept + tags + embedding stay intact). This is Paper 1 storage
357
- degradation. Practical implications:
358
-
359
- - **Don't manually purge memories** to "save space." The system already
360
- compresses unused content. Old memories stay findable via cue match even
361
- when their body has decayed.
362
- - **Don't over-pin with \`memory_class: canonical\`** to fight fade. Canonical
363
- only changes salience gating at write time, not fade behavior. Fade
364
- affects un-recalled engrams of any class.
365
- - **Recall keeps content alive.** Every recall touches the engram and resets
366
- its fade clock. Frequently-recalled memories stay full-fidelity automatically.
367
- - **Supersede is the right tool for stale facts.** When you observe a memory
368
- is outdated, call \`memory_supersede\`the new version inherits the old
369
- one's coherent associations (counter-narrative replacement, 0.8.x) so cue
370
- pathways carry forward to the replacement.
371
-
372
- ### Examplegood vs bad memory_write
373
-
374
- **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
375
- \`\`\`
376
- memory_write(
377
- concept="found a bug",
378
- content="The thing I was looking at was broken so I fixed it."
379
- )
380
- \`\`\`
381
-
382
- **GOOD** (rich identifiers, structured metadata, prefix tags):
383
- \`\`\`
384
- memory_write(
385
- concept="EquiHub period-close BLOCKED check missing server-side",
386
- content="apps/web/app/(accounting)/accounting/period-close/page.tsx had client-only BLOCKED enforcement. Fixed by adding server-side check in AccountingService.closePeriod() per schema/072-period-close.sql. Without server-side check a malicious request could bypass via direct API call.",
387
- project="EquiHub",
388
- topic="accounting",
389
- intent="finding",
390
- confidence_level="verified",
391
- source="debugging",
392
- memory_class="canonical",
393
- tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
394
- )
395
- \`\`\`
396
-
397
- ### Also:
398
- - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
399
- - AWM is shared across all agents in real time. When any agent writes or supersedes a
400
- memory, every other agent can recall it immediately.
401
-
402
- ### Output compression (token efficiency, output-only)
403
- When a tool returns a LARGE STRUCTURED result you need to keep in context — a JSON
404
- array of records, query rows, a log dump, an API response pass it through
405
- \`compress_output\` first. It re-encodes the data as TOON (a compact, lossless,
406
- schema-aware tabular form of JSON), cutting ~50-65% of the tokens at no
407
- comprehension cost. This is output-only: it never changes the data or your memories.
408
- - Use it on big STRUCTURED outputs, not on prose. Prose is returned unchanged —
409
- for trimming memory prose, use recall \`granularity: 'compact'\` instead.
410
- - It returns a \`ref\`; call \`retrieve_original(ref)\` if you later need the exact
411
- verbatim source (e.g. to hand it to another tool unchanged).
412
- - Don't bother for small outputs — it only compresses when the saving is worthwhile
413
- and falls back to plain JSON if TOON wouldn't reproduce the data exactly.
414
-
415
- ### Backend (SQLite vs PGlite, 0.8.x)
416
- AWM ships two storage backends. The installer picks SQLite by default; both
417
- are functionally equivalent for cognitive workloads, but differ in operational
418
- guarantees:
419
-
420
- - **SQLite** (default) — embedded, **multi-process safe** via WAL mode. Best
421
- for single-machine setups and MCP scenarios where multiple Claude Code
422
- sessions may open the same database concurrently.
423
- - **PGlite** embedded Postgres (WASM) with pgvector. **Single-process only**
424
- two MCP processes against the same \`memory-pglite/\` directory will
425
- abort the second. Pick via \`AWM_STORE_BACKEND=pglite\` and
426
- \`AWM_DB_PATH=path/to/memory-pglite\`.
427
- - **Auto-detect** if \`AWM_DB_PATH\` points to a directory that already
428
- exists, AWM detects PGlite; a file SQLite. No explicit
429
- \`AWM_STORE_BACKEND\` needed when an existing DB is present.
430
-
431
- For the comparison table (recall quality parity, BM25 vs \`ts_rank_cd\`,
432
- multi-process guarantees), see \`docs/pglite-feature-parity.md\`.
433
-
434
- ### Diagnostics / escape hatches (env vars, only if you know why)
435
- The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. The 0.8.x work
436
- added the write-path rewrite (per-write 300+ ms → under 10ms) and PGlite
437
- parity tuning. Each optimization is gated by an env-var so it can be disabled
438
- for A/B testing if a regression appears in your workload:
439
-
440
- Recall pipeline (0.7.x):
441
- - \`AWM_DISABLE_POOL_FILTER=1\`disables the candidate pool reduction
442
- pre-filter in recall. Reverts to scoring all active candidates.
443
- - \`AWM_DISABLE_SLIM_CACHE=1\` disables the in-memory slim cache.
444
- Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
445
- - \`AWM_DISABLE_RERANK_SKIP=1\` disables the cross-encoder skip on
446
- clear-winner queries. Forces every recall through the reranker.
447
- - \`AWM_DISABLE_EXPANSION_CACHE=1\` disables the query expansion skip
448
- heuristic + LRU cache. Forces every recall through flan-t5-small.
449
-
450
- Write pipeline + lifecycle (0.8.x):
451
- - \`AWM_REINFORCE_MAX_CONTENT_LEN=1500\` — max chars an engram's content
452
- can grow to via merge-on-reinforce (drop-oldest on overflow). Higher =
453
- preserves more reinforced detail; lower = leaner recall output.
454
- - \`AWM_REINFORCE_MERGE_CONTENT=0\` disable content merge on reinforce.
455
- Reverts to pre-0.8.5 behavior (discard new content, only bump confidence).
456
- - \`AWM_NOVELTY_EMBED=0\` disable the cosine channel in novelty
457
- computation. BM25-only fallback. Reverts to pre-0.8.5 novelty.
458
- - \`AWM_GRANULARITY_COMPACT_LEN=200\` — char budget for query-aware snippet
459
- in \`granularity: 'compact'\` mode.
460
- - \`AWM_GRANULARITY_FULL_LEN=1000\` char budget for the top result in
461
- \`granularity: 'auto'\` mode when there's a clear winner.
462
-
463
- PGlite backend (0.8.x):
464
- - \`AWM_PGLITE_BM25_M=1\` multiplier on PGlite \`ts_rank_cd\` to calibrate
465
- against SQLite FTS5 BM25 distribution. M=1 (default) is passthrough;
466
- higher M boosts PGlite scores at the cost of recall-ranking precision
467
- (see CHANGELOG 0.8.5 follow-up).
468
- - \`AWM_IVFFLAT_PROBES=5\` — pgvector ivfflat probes per query. Higher =
469
- more accurate, slower.
470
-
471
- In production, leave these all unset. Use only when diagnosing a suspected
472
- recall-quality regression.
167
+ export const AWM_INSTRUCTION_CONTENT = `
168
+ ## Memory (AWM) — MANDATORY
169
+
170
+ **AWM is THE memory system.** Use it via the \`agent-working-memory\` MCP server
171
+ (preferred) or HTTP at \`http://127.0.0.1:8400\` (fallback). The file-based
172
+ auto-memory at \`~/.claude/projects/.../memory/*.md\` is a LEGACY bootstrap path —
173
+ **do not write new memories to it.** All persistent knowledge goes through AWM.
174
+
175
+ If MCP tools aren't loaded at session start, use ToolSearch with
176
+ \`select:mcp__agent-working-memory__memory_recall,mcp__agent-working-memory__memory_write\`
177
+ to load them. If the MCP server isn't responsive, restart with \`/mcp\` or use
178
+ the HTTP endpoints (\`POST /memory/write-batch\`, \`POST /memory/activate\`)
179
+ directly — but **DO NOT fall back to markdown files**. Files drift the moment
180
+ you write them; AWM stays current because every agent reads + writes the same store.
181
+
182
+ ### Lifecycle (always do these, in this order)
183
+ 1. **Session start**: call \`memory_restore\` to recover previous context. If it reports the
184
+ store is empty/new (or recall keeps returning nothing), **warm-start first**: recall the
185
+ \`onboard a new project\` skill and follow it — or call \`onboard_scan\` on the project's
186
+ docs/repo, refine the candidates, run \`onboard_questions\`, and save the good ones with
187
+ \`memory_write\` (canonical). A cold store is nearly useless until it's seeded.
188
+ 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
189
+ 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
190
+ the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
191
+ than one filesystem search.
192
+ 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
193
+ 5. **Finishing a task**: call \`memory_task_end\` with a summary.
194
+ 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
195
+
196
+ ### Write memory when:
197
+ - A project decision is made or changed
198
+ - A root cause is discovered after debugging
199
+ - A reusable implementation pattern is established
200
+ - A user preference, constraint, or requirement is clarified
201
+ - A prior assumption is found to be wrong
202
+ - A significant piece of work is completed
203
+
204
+ ### Writing for recall (the highest-leverage section)
205
+ A memory's recall quality is set the moment you write it. AWM is fast at
206
+ finding what's findable — but if the write is shaped wrong, no retriever
207
+ can rescue it. Be slightly more verbose at the front than feels natural:
208
+ the first 1-2 sentences are what BM25, the embedding model, and concept
209
+ extraction all see most strongly.
210
+
211
+ - **Lead with the rule or fact.** Don't open with context or backstory.
212
+ "Don't mock the database in integration tests." comes first; the reason
213
+ comes second. Recall scans the head of the body, not the tail.
214
+ - **Pick the most specific topic.** Not \`auth\` — \`auth-magic-link-rate-limit\`.
215
+ Topic is a hard filter at recall time. Generic topics hide the memory in
216
+ a noisy bucket where it competes with everything else in the area.
217
+ - **Include 2+ retrievable identifiers.** File paths, function names, table
218
+ columns, ticket IDs, exact error strings, the literal terms a future query
219
+ will use. \`AccountingService.closePeriod()\` beats "the accounting code."
220
+ \`tblMemberDetails.activation_date\` beats "the activation column."
221
+ \`schema/072-period-close.sql\` beats "the migration."
222
+ - **Write in the vocabulary of the future question.** When you imagine asking
223
+ this in three months, what nouns will you use? Use those nouns. Don't
224
+ paraphrase the user's domain language into your own neutral summary.
225
+ - **Reserve canonical for stable invariants.** Decisions, requirements,
226
+ hard facts, cross-agent shared context. Working class (default) is correct
227
+ for findings, observations, and progress notes. The canonical floor is
228
+ 0.7 salience — overusing it pollutes the canonical layer and the floor
229
+ loses meaning.
230
+ - **Include the why for feedback memories.** A rule without a reason can't
231
+ be applied to edge cases. "Don't mock the database" is brittle. "Don't
232
+ mock the database — last quarter mocked tests masked a broken migration"
233
+ is portable to new situations.
234
+
235
+ ### Tagging rules (REQUIRED — AWM's prefix-tag retrieval boost depends on these)
236
+
237
+ Every \`memory_write\` should pass these structured fields. AWM stores each as a
238
+ prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
239
+ and entity-bridge boosts at recall time.
240
+
241
+ | Field | Required? | Format | Example |
242
+ |---|---|---|---|
243
+ | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
244
+ | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
245
+ | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
246
+ | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
247
+ | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
248
+ | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
249
+ | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
250
+ | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
251
+
252
+ **Always add identifier tags when present in the content:**
253
+ - \`ticket=<id>\` for Freshdesk tickets
254
+ - \`member=<id>\` for member IDs
255
+ - \`horse=<id>\` for horse_member_id
256
+ - \`usef=<id>\` for USEF lookups
257
+ - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
258
+ - \`person=<Name>\` for stakeholder quotes / decisions
259
+ - \`version=<X.Y.Z>\` for release-specific findings
260
+
261
+ ### Memory classes (controls how strictly the salience filter gates the write)
262
+ - \`memory_class: canonical\` — source-of-truth memories. Floor 0.7 salience, never staged.
263
+ Use for: user-stated decisions, project requirements, verified architectural facts,
264
+ cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
265
+ for writes that other agents must be able to recall** — the default \`working\` class
266
+ may get filtered.
267
+ - \`memory_class: working\` (default) — observations and findings. Salience-gated.
268
+ - \`memory_class: ephemeral\` — short-lived context that should decay quickly.
269
+
270
+ ### Salience auto-promotion (defense in depth)
271
+ The salience filter automatically promotes certain content patterns even if you forget
272
+ to set \`memory_class\` explicitly:
273
+ - **User feedback** — content starting with "Robert said…", "Katherine directed…",
274
+ "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
275
+ always preserves the decision.
276
+ - **Verified operational records** — content with an action verb (Submitted, Finalized,
277
+ Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
278
+ Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
279
+ or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
280
+ a 0.45 salience floor. So batch summaries with real IDs survive even when topic
281
+ terms repeat.
282
+
283
+ If neither pattern applies and you want a memory to definitely survive, set
284
+ \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
285
+
286
+ ### Recall memory when:
287
+ - **BEFORE stating ANY fact about how a system works** — recall first; if AWM doesn't
288
+ have it, read the code. Never guess and present it as fact.
289
+ - **BEFORE searching the filesystem** — recall first; AWM is faster and has cross-session
290
+ knowledge that file search doesn't.
291
+ - Starting work on a new task or subsystem
292
+ - Re-entering code you haven't touched recently
293
+ - After a failed attempt — check if there's prior knowledge
294
+ - Before refactoring or making architectural changes
295
+ - When a topic comes up that you might have prior context on
296
+
297
+ Recall is fast (~300ms typical). Use it freely.
298
+
299
+ ### Recall strategy (when one query isn't enough)
300
+ AWM's adaptive retrieval handles most query variations natively — synonym
301
+ expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
302
+ A single recall is usually enough.
303
+
304
+ When it isn't:
305
+ - **If the first recall returns nothing or returns the wrong things, reformulate.**
306
+ Try a second query with different phrasing — synonyms, more specific nouns,
307
+ the exact identifier from the code rather than the conceptual name. Two or
308
+ three recalls cost less than one filesystem search.
309
+ - **Use the words a domain expert would use, not generic English.** "Period
310
+ close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
311
+ - **For broad exploration, pass \`mode: "exploratory"\`** — wider candidate
312
+ pool, lower precision floor. For specific lookups, leave mode unset (auto).
313
+ - **Don't ensemble more than 3 reformulations.** If three different phrasings
314
+ return nothing, the memory probably isn't there — read the code instead of
315
+ burning more recalls.
316
+
317
+ ### Recall tuning (0.8.x — opt-in parameters for higher-quality recall)
318
+ Default \`memory_recall\` is tuned for the common case. The 0.8.x recall pipeline
319
+ exposes four opt-in parameters that change the cost/quality tradeoff. Use them
320
+ when the default doesn't match what you actually need.
321
+
322
+ - **\`granularity: 'compact'\`** — every result carries a 200-char \`summary\`
323
+ field with a query-aware snippet (the densest window of query terms in the
324
+ content). Use this when you expect to scan 5+ results to find one — saves
325
+ ~70% of recall output tokens. The full content stays available in
326
+ \`engram.content\` if you want to drill into a specific result.
327
+ - **\`granularity: 'auto'\`** — confidence-adaptive. If the top result is a clear
328
+ winner, it gets a longer summary while the rest are compact. If confidence
329
+ is uniform across results, everything is compact. Use when you don't know
330
+ in advance whether one result will dominate.
331
+ - **\`require_confidence: 0.10 | 0.25 | 0.40\`** — opt-in abstention. AWM
332
+ returns \`[]\` instead of low-confidence noise. Use when you're about to ACT
333
+ on the recalled fact (grounding a decision, citing the memory verbatim,
334
+ contradicting a prior assumption). Thresholds: \`0.10\` strict — only abstain
335
+ on garbage; \`0.25\` balanced; \`0.40\` aggressive — prefer "I don't know"
336
+ over "best of bad." When abstention fires (empty result), treat it as a
337
+ signal — either the memory genuinely isn't there (read the code) or your
338
+ query missed (reformulate). Don't retry without the threshold.
339
+ - **\`workspace: "<name>"\`** — hive-mode recall across all agents in the
340
+ workspace. Use when other agents may have written canonical knowledge you
341
+ need. Default is agent-scoped (your own memories only). Can also be set
342
+ globally via the \`AWM_WORKSPACE\` env var.
343
+
344
+ ### Keep memory fresh
345
+ - After recalling a memory, if you observe the real state is different → call
346
+ \`memory_supersede\` immediately with the corrected version.
347
+ - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
348
+ activation engine learns what's valuable.
349
+ - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
350
+ - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
351
+ drifts out of date. The system relies on you to keep it current. This is the #1
352
+ failure mode.**
353
+
354
+ ### Cognition recipesYOU do the thinking, AWM keeps the result (0.11.x)
355
+ AWM contains no LLM. When memory needs real thinking — distilling a repeatable
356
+ procedure, reflecting on a failure AWM hands YOU a versioned recipe (prompt +
357
+ strict output shape) and you run it as a SEPARATE focused pass, then write the
358
+ result back as an ordinary memory with provenance.
359
+
360
+ - \`memory_task_end\` responses include the recipe invitations. Honor the gates:
361
+ skill-derivation only after a genuinely procedural task (3+ tool calls or a
362
+ delegated sub-task); friction-lesson only after a failure/retry/wrong assumption.
363
+ - Run each recipe as its own focused pass do NOT bundle it with other
364
+ reasoning; bundled passes reliably drop the output.
365
+ - Write back exactly per the recipe's contract: \`origin_class: 'recipe'\` +
366
+ \`recipe_id\` (e.g. \`skill-derivation@1\`), concept prefixed \`skill: \` or
367
+ \`lesson: \`. AWM validates the shape and rejects malformed or unknown-recipe
368
+ writes with the contract echoed back fix and retry, don't drop the insight.
369
+ - Re-deriving the same skill name reinforces the existing memory instead of
370
+ duplicating it, so don't fear writing a skill you may have written before.
371
+
372
+ ### Content fade write-and-forget is safe (0.8.x)
373
+ Un-recalled engrams gradually fade their content while preserving cue pathways
374
+ (concept + tags + embedding stay intact). This is Paper 1 — storage
375
+ degradation. Practical implications:
376
+
377
+ - **Don't manually purge memories** to "save space." The system already
378
+ compresses unused content. Old memories stay findable via cue match even
379
+ when their body has decayed.
380
+ - **Don't over-pin with \`memory_class: canonical\`** to fight fade. Canonical
381
+ only changes salience gating at write time, not fade behavior. Fade
382
+ affects un-recalled engrams of any class.
383
+ - **Recall keeps content alive.** Every recall touches the engram and resets
384
+ its fade clock. Frequently-recalled memories stay full-fidelity automatically.
385
+ - **Supersede is the right tool for stale facts.** When you observe a memory
386
+ is outdated, call \`memory_supersede\` the new version inherits the old
387
+ one's coherent associations (counter-narrative replacement, 0.8.x) so cue
388
+ pathways carry forward to the replacement.
389
+
390
+ ### Example — good vs bad memory_write
391
+
392
+ **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
393
+ \`\`\`
394
+ memory_write(
395
+ concept="found a bug",
396
+ content="The thing I was looking at was broken so I fixed it."
397
+ )
398
+ \`\`\`
399
+
400
+ **GOOD** (rich identifiers, structured metadata, prefix tags):
401
+ \`\`\`
402
+ memory_write(
403
+ concept="EquiHub period-close BLOCKED check missing server-side",
404
+ content="apps/web/app/(accounting)/accounting/period-close/page.tsx had client-only BLOCKED enforcement. Fixed by adding server-side check in AccountingService.closePeriod() per schema/072-period-close.sql. Without server-side check a malicious request could bypass via direct API call.",
405
+ project="EquiHub",
406
+ topic="accounting",
407
+ intent="finding",
408
+ confidence_level="verified",
409
+ source="debugging",
410
+ memory_class="canonical",
411
+ tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
412
+ )
413
+ \`\`\`
414
+
415
+ ### Also:
416
+ - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
417
+ - AWM is shared across all agents in real time. When any agent writes or supersedes a
418
+ memory, every other agent can recall it immediately.
419
+
420
+ ### Output compression (token efficiency, output-only)
421
+ When a tool returns a LARGE STRUCTURED result you need to keep in context — a JSON
422
+ array of records, query rows, a log dump, an API response — pass it through
423
+ \`compress_output\` first. It re-encodes the data as TOON (a compact, lossless,
424
+ schema-aware tabular form of JSON), cutting ~50-65% of the tokens at no
425
+ comprehension cost. This is output-only: it never changes the data or your memories.
426
+ - Use it on big STRUCTURED outputs, not on prose. Prose is returned unchanged —
427
+ for trimming memory prose, use recall \`granularity: 'compact'\` instead.
428
+ - It returns a \`ref\`; call \`retrieve_original(ref)\` if you later need the exact
429
+ verbatim source (e.g. to hand it to another tool unchanged).
430
+ - Don't bother for small outputs — it only compresses when the saving is worthwhile
431
+ and falls back to plain JSON if TOON wouldn't reproduce the data exactly.
432
+
433
+ ### Backend (SQLite vs PGlite, 0.8.x)
434
+ AWM ships two storage backends. The installer picks SQLite by default; both
435
+ are functionally equivalent for cognitive workloads, but differ in operational
436
+ guarantees:
437
+
438
+ - **SQLite** (default) embedded, **multi-process safe** via WAL mode. Best
439
+ for single-machine setups and MCP scenarios where multiple Claude Code
440
+ sessions may open the same database concurrently.
441
+ - **PGlite**embedded Postgres (WASM) with pgvector. **Single-process only**
442
+ two MCP processes against the same \`memory-pglite/\` directory will
443
+ abort the second. Pick via \`AWM_STORE_BACKEND=pglite\` and
444
+ \`AWM_DB_PATH=path/to/memory-pglite\`.
445
+ - **Auto-detect** — if \`AWM_DB_PATH\` points to a directory that already
446
+ exists, AWM detects PGlite; a file SQLite. No explicit
447
+ \`AWM_STORE_BACKEND\` needed when an existing DB is present.
448
+
449
+ For the comparison table (recall quality parity, BM25 vs \`ts_rank_cd\`,
450
+ multi-process guarantees), see \`docs/pglite-feature-parity.md\`.
451
+
452
+ ### Diagnostics / escape hatches (env vars, only if you know why)
453
+ The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. The 0.8.x work
454
+ added the write-path rewrite (per-write 300+ ms under 10ms) and PGlite
455
+ parity tuning. Each optimization is gated by an env-var so it can be disabled
456
+ for A/B testing if a regression appears in your workload:
457
+
458
+ Recall pipeline (0.7.x):
459
+ - \`AWM_DISABLE_POOL_FILTER=1\` — disables the candidate pool reduction
460
+ pre-filter in recall. Reverts to scoring all active candidates.
461
+ - \`AWM_SLOW_WRITE_MS\` slow-write telemetry threshold in ms (default 250;
462
+ 0 disables the always-on slow-write stderr line).
463
+ - \`memory_whoami\` (MCP) / \`GET /whoami\` — identify the instance (agent, mode,
464
+ backend, store path, code provenance, sibling agent spaces) when unsure
465
+ which AWM you are talking to.
466
+ - \`AWM_DISABLE_SLIM_CACHE=1\` disables the in-memory slim cache.
467
+ Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
468
+ - \`AWM_DISABLE_RERANK_SKIP=1\` — disables the cross-encoder skip on
469
+ clear-winner queries. Forces every recall through the reranker.
470
+ - \`AWM_DISABLE_EXPANSION_CACHE=1\` — disables the query expansion skip
471
+ heuristic + LRU cache. Forces every recall through flan-t5-small.
472
+
473
+ Write pipeline + lifecycle (0.8.x):
474
+ - \`AWM_REINFORCE_MAX_CONTENT_LEN=1500\` — max chars an engram's content
475
+ can grow to via merge-on-reinforce (drop-oldest on overflow). Higher =
476
+ preserves more reinforced detail; lower = leaner recall output.
477
+ - \`AWM_REINFORCE_MERGE_CONTENT=0\` — disable content merge on reinforce.
478
+ Reverts to pre-0.8.5 behavior (discard new content, only bump confidence).
479
+ - \`AWM_NOVELTY_EMBED=0\` — disable the cosine channel in novelty
480
+ computation. BM25-only fallback. Reverts to pre-0.8.5 novelty.
481
+ - \`AWM_GRANULARITY_COMPACT_LEN=200\` — char budget for query-aware snippet
482
+ in \`granularity: 'compact'\` mode.
483
+ - \`AWM_GRANULARITY_FULL_LEN=1000\` — char budget for the top result in
484
+ \`granularity: 'auto'\` mode when there's a clear winner.
485
+
486
+ PGlite backend (0.8.x):
487
+ - \`AWM_PGLITE_BM25_M=1\` — multiplier on PGlite \`ts_rank_cd\` to calibrate
488
+ against SQLite FTS5 BM25 distribution. M=1 (default) is passthrough;
489
+ higher M boosts PGlite scores at the cost of recall-ranking precision
490
+ (see CHANGELOG 0.8.5 follow-up).
491
+ - \`AWM_IVFFLAT_PROBES=5\` — pgvector ivfflat probes per query. Higher =
492
+ more accurate, slower.
493
+
494
+ In production, leave these all unset. Use only when diagnosing a suspected
495
+ recall-quality regression.
473
496
  `.trimStart();
474
497
  //# sourceMappingURL=common.js.map