agent-working-memory 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (104) hide show
  1. package/README.md +200 -238
  2. package/dist/adapters/common.d.ts +6 -0
  3. package/dist/adapters/common.d.ts.map +1 -1
  4. package/dist/adapters/common.js +457 -362
  5. package/dist/adapters/common.js.map +1 -1
  6. package/dist/api/routes.d.ts.map +1 -1
  7. package/dist/api/routes.js +24 -8
  8. package/dist/api/routes.js.map +1 -1
  9. package/dist/core/alias-map.d.ts +16 -0
  10. package/dist/core/alias-map.d.ts.map +1 -0
  11. package/dist/core/alias-map.js +102 -0
  12. package/dist/core/alias-map.js.map +1 -0
  13. package/dist/core/embeddings.d.ts +17 -0
  14. package/dist/core/embeddings.d.ts.map +1 -1
  15. package/dist/core/embeddings.js +52 -1
  16. package/dist/core/embeddings.js.map +1 -1
  17. package/dist/core/model-cache.d.ts +28 -0
  18. package/dist/core/model-cache.d.ts.map +1 -0
  19. package/dist/core/model-cache.js +50 -0
  20. package/dist/core/model-cache.js.map +1 -0
  21. package/dist/core/query-expander.d.ts.map +1 -1
  22. package/dist/core/query-expander.js +2 -0
  23. package/dist/core/query-expander.js.map +1 -1
  24. package/dist/core/recall-config.d.ts +52 -0
  25. package/dist/core/recall-config.d.ts.map +1 -0
  26. package/dist/core/recall-config.js +110 -0
  27. package/dist/core/recall-config.js.map +1 -0
  28. package/dist/core/rerank-window.d.ts +61 -0
  29. package/dist/core/rerank-window.d.ts.map +1 -0
  30. package/dist/core/rerank-window.js +153 -0
  31. package/dist/core/rerank-window.js.map +1 -0
  32. package/dist/core/rerank2.d.ts +62 -0
  33. package/dist/core/rerank2.d.ts.map +1 -0
  34. package/dist/core/rerank2.js +75 -0
  35. package/dist/core/rerank2.js.map +1 -0
  36. package/dist/core/reranker.d.ts.map +1 -1
  37. package/dist/core/reranker.js +2 -0
  38. package/dist/core/reranker.js.map +1 -1
  39. package/dist/core/retrieval-text.d.ts +55 -0
  40. package/dist/core/retrieval-text.d.ts.map +1 -0
  41. package/dist/core/retrieval-text.js +87 -0
  42. package/dist/core/retrieval-text.js.map +1 -0
  43. package/dist/core/temporal-query.d.ts +61 -0
  44. package/dist/core/temporal-query.d.ts.map +1 -0
  45. package/dist/core/temporal-query.js +168 -0
  46. package/dist/core/temporal-query.js.map +1 -0
  47. package/dist/core/token-budget.d.ts +75 -0
  48. package/dist/core/token-budget.d.ts.map +1 -0
  49. package/dist/core/token-budget.js +136 -0
  50. package/dist/core/token-budget.js.map +1 -0
  51. package/dist/core/whoami.d.ts +11 -0
  52. package/dist/core/whoami.d.ts.map +1 -1
  53. package/dist/core/whoami.js +10 -0
  54. package/dist/core/whoami.js.map +1 -1
  55. package/dist/core/write-pipeline.d.ts.map +1 -1
  56. package/dist/core/write-pipeline.js +6 -3
  57. package/dist/core/write-pipeline.js.map +1 -1
  58. package/dist/engine/activation.d.ts.map +1 -1
  59. package/dist/engine/activation.js +135 -32
  60. package/dist/engine/activation.js.map +1 -1
  61. package/dist/hooks/prime.d.ts +77 -0
  62. package/dist/hooks/prime.d.ts.map +1 -0
  63. package/dist/hooks/prime.js +92 -0
  64. package/dist/hooks/prime.js.map +1 -0
  65. package/dist/hooks/sidecar.d.ts.map +1 -1
  66. package/dist/hooks/sidecar.js +39 -0
  67. package/dist/hooks/sidecar.js.map +1 -1
  68. package/dist/mcp.js +134 -102
  69. package/dist/mcp.js.map +1 -1
  70. package/dist/storage/pglite.d.ts.map +1 -1
  71. package/dist/storage/pglite.js +10 -2
  72. package/dist/storage/pglite.js.map +1 -1
  73. package/dist/storage/postgres.d.ts.map +1 -1
  74. package/dist/storage/postgres.js +10 -2
  75. package/dist/storage/postgres.js.map +1 -1
  76. package/dist/storage/sqlite.d.ts.map +1 -1
  77. package/dist/storage/sqlite.js +12 -2
  78. package/dist/storage/sqlite.js.map +1 -1
  79. package/dist/types/engram.d.ts +7 -0
  80. package/dist/types/engram.d.ts.map +1 -1
  81. package/package.json +3 -2
  82. package/src/adapters/common.ts +666 -567
  83. package/src/api/routes.ts +1015 -999
  84. package/src/core/alias-map.ts +97 -0
  85. package/src/core/embeddings.ts +172 -113
  86. package/src/core/model-cache.ts +51 -0
  87. package/src/core/query-expander.ts +2 -0
  88. package/src/core/recall-config.ts +115 -0
  89. package/src/core/rerank-window.ts +158 -0
  90. package/src/core/rerank2.ts +82 -0
  91. package/src/core/reranker.ts +2 -0
  92. package/src/core/retrieval-text.ts +82 -0
  93. package/src/core/temporal-query.ts +193 -0
  94. package/src/core/token-budget.ts +160 -0
  95. package/src/core/whoami.ts +110 -92
  96. package/src/core/write-pipeline.ts +6 -3
  97. package/src/engine/activation.ts +1568 -1468
  98. package/src/hooks/prime.ts +136 -0
  99. package/src/hooks/sidecar.ts +43 -0
  100. package/src/mcp.ts +1422 -1387
  101. package/src/storage/pglite.ts +10 -2
  102. package/src/storage/postgres.ts +10 -2
  103. package/src/storage/sqlite.ts +12 -2
  104. package/src/types/engram.ts +7 -0
@@ -1,567 +1,666 @@
1
- // Copyright 2026 Robert Winter / Complete Ideas
2
- // SPDX-License-Identifier: Apache-2.0
3
-
4
- /**
5
- * Shared utilities for CLI adapters.
6
- *
7
- * Extracted from the original setup() in cli.ts — path resolution, secrets,
8
- * environment variables, MCP command building, and the AWM instruction snippet.
9
- */
10
-
11
- import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
12
- import { resolve, join, dirname, basename } from 'node:path';
13
- import { randomBytes } from 'node:crypto';
14
- import { homedir as osHomedir } from 'node:os';
15
- import { fileURLToPath } from 'node:url';
16
- import type { SetupContext } from './types.js';
17
-
18
- const __filename = fileURLToPath(import.meta.url);
19
- const __dirname = dirname(__filename);
20
-
21
- /** Resolve the AWM package root (where src/ and dist/ live). */
22
- export function resolvePackageRoot(): string {
23
- // __dirname is src/adapters/ at dev time, dist/adapters/ at build time
24
- return resolve(__dirname, '..', '..');
25
- }
26
-
27
- /** Resolve the database path — default to <packageRoot>/data/memory.db. */
28
- export function resolveDbPath(packageRoot: string, explicit?: string | null): string {
29
- const dbPath = explicit ?? join(packageRoot, 'data', 'memory.db');
30
- const dbDir = dirname(dbPath);
31
- if (!existsSync(dbDir)) {
32
- mkdirSync(dbDir, { recursive: true });
33
- }
34
- return dbPath;
35
- }
36
-
37
- /** Read or generate the hook secret token. */
38
- export function resolveHookSecret(dbPath: string): string {
39
- const secretPath = join(dirname(dbPath), '.awm-hook-secret');
40
- if (existsSync(secretPath)) {
41
- const existing = readFileSync(secretPath, 'utf-8').trim();
42
- if (existing) return existing;
43
- }
44
- const secret = randomBytes(32).toString('hex');
45
- mkdirSync(dirname(secretPath), { recursive: true });
46
- writeFileSync(secretPath, secret + '\n');
47
- return secret;
48
- }
49
-
50
- /** Build environment variables for the MCP server process. */
51
- export function buildEnvVars(
52
- dbPath: string,
53
- agentId: string,
54
- hookPort: string,
55
- hookSecret: string,
56
- isWindows: boolean,
57
- ): Record<string, string> {
58
- return {
59
- AWM_DB_PATH: isWindows ? dbPath.replace(/\\/g, '/') : dbPath,
60
- AWM_AGENT_ID: agentId,
61
- AWM_HOOK_PORT: hookPort,
62
- AWM_HOOK_SECRET: hookSecret,
63
- };
64
- }
65
-
66
- /**
67
- * Resolve the MCP server command + args.
68
- *
69
- * Prefers absolute path to dist/mcp.js (works from any cwd).
70
- * Falls back to npx tsx src/mcp.ts for dev mode.
71
- */
72
- export function resolveMcpCommand(ctx: SetupContext): {
73
- command: string;
74
- args: string[];
75
- } {
76
- if (ctx.hasDist) {
77
- return {
78
- command: 'node',
79
- args: [ctx.mcpDist.replace(/\\/g, '/')],
80
- };
81
- }
82
- // Dev fallback
83
- if (ctx.isWindows) {
84
- return {
85
- command: 'cmd',
86
- args: ['/c', 'npx', 'tsx', ctx.mcpScript.replace(/\\/g, '/')],
87
- };
88
- }
89
- return {
90
- command: 'npx',
91
- args: ['tsx', ctx.mcpScript],
92
- };
93
- }
94
-
95
- /** Build a full SetupContext from parsed CLI flags. */
96
- export function buildSetupContext(opts: {
97
- agentId?: string;
98
- dbPath?: string | null;
99
- isGlobal: boolean;
100
- hookPort: string;
101
- }): SetupContext {
102
- const cwd = process.cwd();
103
- const projectName = basename(cwd).toLowerCase().replace(/[^a-z0-9-]/g, '-');
104
- const packageRoot = resolvePackageRoot();
105
- const mcpScript = join(packageRoot, 'src', 'mcp.ts');
106
- const mcpDist = join(packageRoot, 'dist', 'mcp.js');
107
- const hasDist = existsSync(mcpDist);
108
- const isWindows = process.platform === 'win32';
109
-
110
- const agentId = opts.agentId ?? (opts.isGlobal ? 'claude' : projectName);
111
- const dbPath = resolveDbPath(packageRoot, opts.dbPath);
112
- const hookSecret = resolveHookSecret(dbPath);
113
- const envVars = buildEnvVars(dbPath, agentId, opts.hookPort, hookSecret, isWindows);
114
-
115
- return {
116
- cwd,
117
- projectName,
118
- agentId,
119
- dbPath,
120
- packageRoot,
121
- mcpDist,
122
- mcpScript,
123
- hasDist,
124
- hookSecret,
125
- hookPort: opts.hookPort,
126
- isGlobal: opts.isGlobal,
127
- isWindows,
128
- envVars,
129
- };
130
- }
131
-
132
- /** Home directory. */
133
- export function homedir(): string {
134
- return osHomedir();
135
- }
136
-
137
- // ─── Instruction content ────────────────────────────────
138
-
139
- /**
140
- * Core AWM instruction snippet — shared across all adapters.
141
- * Each adapter wraps this in the appropriate file format.
142
- */
143
- /**
144
- * Upsert the AWM section into an instruction file (CLAUDE.md, AGENTS.md, .cursorrules).
145
- *
146
- * Behavior:
147
- * - File doesn't exist -> create with title + AWM_INSTRUCTION_CONTENT
148
- * - Section absent -> append
149
- * - Section present + identical -> skip
150
- * - Section present + stale -> REPLACE in place, preserve content above/below
151
- *
152
- * Section is bounded by `## Memory (AWM)` (with optional trailing modifier) at the
153
- * start, and the next `## ` heading or EOF at the end.
154
- *
155
- * Returns a short human-readable status string for the setup command output.
156
- */
157
- export function upsertAwmSection(
158
- filePath: string,
159
- newContent: string,
160
- options: { titleIfNew?: string; suffix?: string } = {},
161
- ): string {
162
- const fname = basename(filePath);
163
- const suffix = options.suffix ?? '';
164
-
165
- if (!existsSync(filePath)) {
166
- const title = options.titleIfNew ?? `# ${basename(dirname(filePath))}`;
167
- mkdirSync(dirname(filePath), { recursive: true });
168
- writeFileSync(filePath, `${title}\n\n${newContent}${suffix}`);
169
- return `${fname}: created with AWM workflow section`;
170
- }
171
-
172
- const existing = readFileSync(filePath, 'utf-8');
173
-
174
- // Find section bounds: `## Memory (AWM)` (possibly with ` — MANDATORY` etc.) until next `## ` or EOF
175
- const startRegex = /^## Memory \(AWM\)[^\n]*$/m;
176
- const startMatch = startRegex.exec(existing);
177
-
178
- if (!startMatch) {
179
- // Section not present — append
180
- writeFileSync(filePath, existing.trimEnd() + '\n\n' + newContent + suffix);
181
- return `${fname}: appended AWM workflow section`;
182
- }
183
-
184
- // Find end: next `## ` heading after the section start, or EOF
185
- const afterStart = startMatch.index + startMatch[0].length;
186
- const nextHeadingRegex = /^## (?!Memory \(AWM\))/m;
187
- nextHeadingRegex.lastIndex = afterStart;
188
- const tail = existing.slice(afterStart);
189
- const nextMatch = nextHeadingRegex.exec(tail);
190
- const sectionEnd = nextMatch ? afterStart + nextMatch.index : existing.length;
191
-
192
- const currentSection = existing.slice(startMatch.index, sectionEnd).trimEnd();
193
- const desiredSection = (newContent + suffix).trimEnd();
194
-
195
- if (currentSection === desiredSection) {
196
- return `${fname}: AWM section already up-to-date (skipped)`;
197
- }
198
-
199
- const before = existing.slice(0, startMatch.index).trimEnd();
200
- const after = existing.slice(sectionEnd).replace(/^\s*\n/, '');
201
- const rebuilt =
202
- (before ? before + '\n\n' : '') +
203
- desiredSection +
204
- (after ? '\n\n' + after : '\n');
205
- writeFileSync(filePath, rebuilt);
206
- return `${fname}: AWM section updated (preserved surrounding content)`;
207
- }
208
-
209
- export const AWM_INSTRUCTION_CONTENT = `
210
- ## Memory (AWM) — MANDATORY
211
-
212
- **AWM is THE memory system.** Use it via the \`agent-working-memory\` MCP server
213
- (preferred) or HTTP at \`http://127.0.0.1:8400\` (fallback). The file-based
214
- auto-memory at \`~/.claude/projects/.../memory/*.md\` is a LEGACY bootstrap path —
215
- **do not write new memories to it.** All persistent knowledge goes through AWM.
216
-
217
- If MCP tools aren't loaded at session start, use ToolSearch with
218
- \`select:mcp__agent-working-memory__memory_recall,mcp__agent-working-memory__memory_write\`
219
- to load them. If the MCP server isn't responsive, restart with \`/mcp\` or use
220
- the HTTP endpoints (\`POST /memory/write-batch\`, \`POST /memory/activate\`)
221
- directly but **DO NOT fall back to markdown files**. Files drift the moment
222
- you write them; AWM stays current because every agent reads + writes the same store.
223
-
224
- ### Lifecycle (always do these, in this order)
225
- 1. **Session start**: call \`memory_restore\` to recover previous context. If it reports the
226
- store is empty/new (or recall keeps returning nothing), **warm-start first**: recall the
227
- \`onboard a new project\` skill and follow it — or call \`onboard_scan\` on the project's
228
- docs/repo, refine the candidates, run \`onboard_questions\`, and save the good ones with
229
- \`memory_write\` (canonical). A cold store is nearly useless until it's seeded.
230
- 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
231
- 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
232
- the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
233
- than one filesystem search.
234
- 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
235
- 5. **Finishing a task**: call \`memory_task_end\` with a summary.
236
- 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
237
-
238
- ### Write memory when:
239
- - A project decision is made or changed
240
- - A root cause is discovered after debugging
241
- - A reusable implementation pattern is established
242
- - A user preference, constraint, or requirement is clarified
243
- - A prior assumption is found to be wrong
244
- - A significant piece of work is completed
245
-
246
- ### Writing for recall (the highest-leverage section)
247
- A memory's recall quality is set the moment you write it. AWM is fast at
248
- finding what's findable — but if the write is shaped wrong, no retriever
249
- can rescue it. Be slightly more verbose at the front than feels natural:
250
- the first 1-2 sentences are what BM25, the embedding model, and concept
251
- extraction all see most strongly.
252
-
253
- - **Lead with the rule or fact.** Don't open with context or backstory.
254
- "Don't mock the database in integration tests." comes first; the reason
255
- comes second. Recall scans the head of the body, not the tail.
256
- - **Pick the most specific topic.** Not \`auth\` — \`auth-magic-link-rate-limit\`.
257
- Topic is a hard filter at recall time. Generic topics hide the memory in
258
- a noisy bucket where it competes with everything else in the area.
259
- - **Include 2+ retrievable identifiers.** File paths, function names, table
260
- columns, ticket IDs, exact error strings, the literal terms a future query
261
- will use. \`AccountingService.closePeriod()\` beats "the accounting code."
262
- \`tblMemberDetails.activation_date\` beats "the activation column."
263
- \`schema/072-period-close.sql\` beats "the migration."
264
- - **Write in the vocabulary of the future question.** When you imagine asking
265
- this in three months, what nouns will you use? Use those nouns. Don't
266
- paraphrase the user's domain language into your own neutral summary.
267
- - **Reserve canonical for stable invariants.** Decisions, requirements,
268
- hard facts, cross-agent shared context. Working class (default) is correct
269
- for findings, observations, and progress notes. The canonical floor is
270
- 0.7 salience overusing it pollutes the canonical layer and the floor
271
- loses meaning.
272
- - **Include the why for feedback memories.** A rule without a reason can't
273
- be applied to edge cases. "Don't mock the database" is brittle. "Don't
274
- mock the database last quarter mocked tests masked a broken migration"
275
- is portable to new situations.
276
-
277
- ### Tagging rules (REQUIRED AWM's prefix-tag retrieval boost depends on these)
278
-
279
- Every \`memory_write\` should pass these structured fields. AWM stores each as a
280
- prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
281
- and entity-bridge boosts at recall time.
282
-
283
- | Field | Required? | Format | Example |
284
- |---|---|---|---|
285
- | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
286
- | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
287
- | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
288
- | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
289
- | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
290
- | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
291
- | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
292
- | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
293
-
294
- **Always add identifier tags when present in the content:**
295
- - \`ticket=<id>\` for Freshdesk tickets
296
- - \`member=<id>\` for member IDs
297
- - \`horse=<id>\` for horse_member_id
298
- - \`usef=<id>\` for USEF lookups
299
- - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
300
- - \`person=<Name>\` for stakeholder quotes / decisions
301
- - \`version=<X.Y.Z>\` for release-specific findings
302
-
303
- ### Entity index exact-match recall for named things (default off)
304
- Structured identifier tags (\`ticket=\`, \`person=\`, \`horse=\`, \`member=\`, bare 4+ digit
305
- ids, etc.) feed a dedicated entity inverted index, separate from BM25/embedding scoring.
306
- A query naming an entity ("ticket 19252", "Kaleigh Collett") can reach the memory through
307
- this index even when the wording doesn't lexically match it's a deterministic exact
308
- lookup, immune to vocabulary mismatch. Keep identifier tags exact and consistent for
309
- this reason, not just for the BM25 boost described above.
310
-
311
- Off by default; opt in with \`AWM_ENTITY_INDEX_FETCH=1\` (bounded by
312
- \`AWM_ENTITY_INDEX_CAP\`, default 12). Matched entities get no score boost — they're
313
- guaranteed a reranker audition instead, so the cross-encoder alone decides whether they
314
- surface. Worth trialing on identifier-heavy workloads (ticket/event numbers, named
315
- people/things you refer to by name often); not yet the default pending evaluation.
316
-
317
- ### Temporal validity memories that expire or start in the future
318
- \`memory_write\` accepts \`valid_from\` / \`valid_to\` (ISO dates). Use \`valid_to\` on
319
- **operational** facts with a real shelf life — a deploy state, "waiting on X's reply",
320
- a ticket status so the memory expires instead of relying on you to remember it's
321
- stale. Recall renders \`[valid until …]\` on results carrying this field. Use
322
- \`valid_from\` for a fact that becomes true on a known future date (a policy change, a
323
- season that hasn't started yet). Don't set either for durable facts — most memories
324
- don't need them.
325
-
326
- ### Memory classes (controls how strictly the salience filter gates the write)
327
- - \`memory_class: canonical\` source-of-truth memories. Floor 0.7 salience, never staged.
328
- Use for: user-stated decisions, project requirements, verified architectural facts,
329
- cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
330
- for writes that other agents must be able to recall** — the default \`working\` class
331
- may get filtered.
332
- - \`memory_class: working\` (default) observations and findings. Salience-gated.
333
- - \`memory_class: ephemeral\` short-lived context that should decay quickly.
334
-
335
- ### Salience auto-promotion (defense in depth)
336
- The salience filter automatically promotes certain content patterns even if you forget
337
- to set \`memory_class\` explicitly:
338
- - **User feedback** content starting with "Robert said…", "Katherine directed…",
339
- "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
340
- always preserves the decision.
341
- - **Verified operational records** content with an action verb (Submitted, Finalized,
342
- Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
343
- Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
344
- or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
345
- a 0.45 salience floor. So batch summaries with real IDs survive even when topic
346
- terms repeat.
347
-
348
- If neither pattern applies and you want a memory to definitely survive, set
349
- \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
350
-
351
- ### Recall memory when:
352
- - **BEFORE stating ANY fact about how a system works** — recall first; if AWM doesn't
353
- have it, read the code. Never guess and present it as fact.
354
- - **BEFORE searching the filesystem** recall first; AWM is faster and has cross-session
355
- knowledge that file search doesn't.
356
- - Starting work on a new task or subsystem
357
- - Re-entering code you haven't touched recently
358
- - After a failed attempt check if there's prior knowledge
359
- - Before refactoring or making architectural changes
360
- - When a topic comes up that you might have prior context on
361
-
362
- Recall is fast (~300ms typical). Use it freely.
363
-
364
- ### Recall strategy (when one query isn't enough)
365
- AWM's adaptive retrieval handles most query variations natively — synonym
366
- expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
367
- A single recall is usually enough.
368
-
369
- When it isn't:
370
- - **If the first recall returns nothing or returns the wrong things, reformulate.**
371
- Try a second query with different phrasing synonyms, more specific nouns,
372
- the exact identifier from the code rather than the conceptual name. Two or
373
- three recalls cost less than one filesystem search.
374
- - **Use the words a domain expert would use, not generic English.** "Period
375
- close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
376
- - **For broad exploration, pass \`mode: "exploratory"\`** wider candidate
377
- pool, lower precision floor. For specific lookups, leave mode unset (auto).
378
- - **Don't ensemble more than 3 reformulations.** If three different phrasings
379
- return nothing, the memory probably isn't there read the code instead of
380
- burning more recalls.
381
-
382
- ### Recall tuning (0.8.x — opt-in parameters for higher-quality recall)
383
- Default \`memory_recall\` is tuned for the common case. The 0.8.x recall pipeline
384
- exposes four opt-in parameters that change the cost/quality tradeoff. Use them
385
- when the default doesn't match what you actually need.
386
-
387
- - **\`granularity: 'compact'\`** every result carries a 200-char \`summary\`
388
- field with a query-aware snippet (the densest window of query terms in the
389
- content). Use this when you expect to scan 5+ results to find one — saves
390
- ~70% of recall output tokens. The full content stays available in
391
- \`engram.content\` if you want to drill into a specific result.
392
- - **\`granularity: 'auto'\`** confidence-adaptive. If the top result is a clear
393
- winner, it gets a longer summary while the rest are compact. If confidence
394
- is uniform across results, everything is compact. Use when you don't know
395
- in advance whether one result will dominate.
396
- - **\`require_confidence: 0.10 | 0.25 | 0.40\`** opt-in abstention. AWM
397
- returns \`[]\` instead of low-confidence noise. Use when you're about to ACT
398
- on the recalled fact (grounding a decision, citing the memory verbatim,
399
- contradicting a prior assumption). Thresholds: \`0.10\` strict — only abstain
400
- on garbage; \`0.25\` balanced; \`0.40\` aggressiveprefer "I don't know"
401
- over "best of bad." When abstention fires (empty result), treat it as a
402
- signal — either the memory genuinely isn't there (read the code) or your
403
- query missed (reformulate). Don't retry without the threshold.
404
- - **\`workspace: "<name>"\`** hive-mode recall across all agents in the
405
- workspace. Use when other agents may have written canonical knowledge you
406
- need. Default is agent-scoped (your own memories only). Can also be set
407
- globally via the \`AWM_WORKSPACE\` env var.
408
-
409
- ### Keep memory fresh
410
- - After recalling a memory, if you observe the real state is different → call
411
- \`memory_supersede\` immediately with the corrected version.
412
- - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
413
- activation engine learns what's valuable.
414
- - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
415
- - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
416
- drifts out of date. The system relies on you to keep it current. This is the #1
417
- failure mode.**
418
-
419
- ### Cognition recipes — YOU do the thinking, AWM keeps the result (0.11.x)
420
- AWM contains no LLM. When memory needs real thinkingdistilling a repeatable
421
- procedure, reflecting on a failure AWM hands YOU a versioned recipe (prompt +
422
- strict output shape) and you run it as a SEPARATE focused pass, then write the
423
- result back as an ordinary memory with provenance.
424
-
425
- - \`memory_task_end\` responses include the recipe invitations. Honor the gates:
426
- skill-derivation only after a genuinely procedural task (3+ tool calls or a
427
- delegated sub-task); friction-lesson only after a failure/retry/wrong assumption.
428
- - Run each recipe as its own focused pass do NOT bundle it with other
429
- reasoning; bundled passes reliably drop the output.
430
- - Write back exactly per the recipe's contract: \`origin_class: 'recipe'\` +
431
- \`recipe_id\` (e.g. \`skill-derivation@1\`), concept prefixed \`skill: \` or
432
- \`lesson: \`. AWM validates the shape and rejects malformed or unknown-recipe
433
- writes with the contract echoed back — fix and retry, don't drop the insight.
434
- - Re-deriving the same skill name reinforces the existing memory instead of
435
- duplicating it, so don't fear writing a skill you may have written before.
436
-
437
- ### Content fade write-and-forget is safe (0.8.x)
438
- Un-recalled engrams gradually fade their content while preserving cue pathways
439
- (concept + tags + embedding stay intact). This is Paper 1 storage
440
- degradation. Practical implications:
441
-
442
- - **Don't manually purge memories** to "save space." The system already
443
- compresses unused content. Old memories stay findable via cue match even
444
- when their body has decayed.
445
- - **Don't over-pin with \`memory_class: canonical\`** to fight fade. Canonical
446
- only changes salience gating at write time, not fade behavior. Fade
447
- affects un-recalled engrams of any class.
448
- - **Recall keeps content alive.** Every recall touches the engram and resets
449
- its fade clock. Frequently-recalled memories stay full-fidelity automatically.
450
- - **Supersede is the right tool for stale facts.** When you observe a memory
451
- is outdated, call \`memory_supersede\` the new version inherits the old
452
- one's coherent associations (counter-narrative replacement, 0.8.x) so cue
453
- pathways carry forward to the replacement.
454
-
455
- ### Example — good vs bad memory_write
456
-
457
- **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
458
- \`\`\`
459
- memory_write(
460
- concept="found a bug",
461
- content="The thing I was looking at was broken so I fixed it."
462
- )
463
- \`\`\`
464
-
465
- **GOOD** (rich identifiers, structured metadata, prefix tags):
466
- \`\`\`
467
- memory_write(
468
- concept="EquiHub period-close BLOCKED check missing server-side",
469
- 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.",
470
- project="EquiHub",
471
- topic="accounting",
472
- intent="finding",
473
- confidence_level="verified",
474
- source="debugging",
475
- memory_class="canonical",
476
- tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
477
- )
478
- \`\`\`
479
-
480
- ### Also:
481
- - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
482
- - \`memory_whoami\` (MCP tool) / \`GET /whoami\` identify the instance you're actually
483
- talking to: agent id, workspace, mode, backend, store path, code provenance, sibling
484
- agent spaces sharing the store. Call this FIRST whenever you're unsure which store,
485
- which agent identity, or which running code you're dealing with — before reasoning
486
- about AWM's own state from a stale memory or an assumed port number.
487
- - AWM is shared across all agents in real time. When any agent writes or supersedes a
488
- memory, every other agent can recall it immediately but only within the same
489
- workspace and agent scope.
490
-
491
- ### Output compression (token efficiency, output-only)
492
- When a tool returns a LARGE STRUCTURED result you need to keep in context — a JSON
493
- array of records, query rows, a log dump, an API response pass it through
494
- \`compress_output\` first. It re-encodes the data as TOON (a compact, lossless,
495
- schema-aware tabular form of JSON), cutting ~50-65% of the tokens at no
496
- comprehension cost. This is output-only: it never changes the data or your memories.
497
- - Use it on big STRUCTURED outputs, not on prose. Prose is returned unchanged —
498
- for trimming memory prose, use recall \`granularity: 'compact'\` instead.
499
- - It returns a \`ref\`; call \`retrieve_original(ref)\` if you later need the exact
500
- verbatim source (e.g. to hand it to another tool unchanged).
501
- - Don't bother for small outputs it only compresses when the saving is worthwhile
502
- and falls back to plain JSON if TOON wouldn't reproduce the data exactly.
503
-
504
- ### Backend (SQLite vs PGlite, 0.8.x)
505
- AWM ships two storage backends. The installer picks SQLite by default; both
506
- are functionally equivalent for cognitive workloads, but differ in operational
507
- guarantees:
508
-
509
- - **SQLite** (default) embedded, **multi-process safe** via WAL mode. Best
510
- for single-machine setups and MCP scenarios where multiple Claude Code
511
- sessions may open the same database concurrently.
512
- - **PGlite** embedded Postgres (WASM) with pgvector. **Single-process only**
513
- two MCP processes against the same \`memory-pglite/\` directory will
514
- abort the second. Pick via \`AWM_STORE_BACKEND=pglite\` and
515
- \`AWM_DB_PATH=path/to/memory-pglite\`.
516
- - **Auto-detect** — if \`AWM_DB_PATH\` points to a directory that already
517
- exists, AWM detects PGlite; a file → SQLite. No explicit
518
- \`AWM_STORE_BACKEND\` needed when an existing DB is present.
519
-
520
- For the comparison table (recall quality parity, BM25 vs \`ts_rank_cd\`,
521
- multi-process guarantees), see \`docs/pglite-feature-parity.md\`.
522
-
523
- ### Diagnostics / escape hatches (env vars, only if you know why)
524
- The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. The 0.8.x work
525
- added the write-path rewrite (per-write 300+ ms under 10ms) and PGlite
526
- parity tuning. Each optimization is gated by an env-var so it can be disabled
527
- for A/B testing if a regression appears in your workload:
528
-
529
- Recall pipeline (0.7.x):
530
- - \`AWM_DISABLE_POOL_FILTER=1\` disables the candidate pool reduction
531
- pre-filter in recall. Reverts to scoring all active candidates.
532
- - \`AWM_ENTITY_INDEX_FETCH=1\` see "Entity index" above (0.12.x, default off).
533
- - \`AWM_DISABLE_SLIM_CACHE=1\` disables the in-memory slim cache.
534
- Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
535
- - \`AWM_DISABLE_RERANK_SKIP=1\` — disables the cross-encoder skip on
536
- clear-winner queries. Forces every recall through the reranker.
537
- - \`AWM_DISABLE_EXPANSION_CACHE=1\` disables the query expansion skip
538
- heuristic + LRU cache. Forces every recall through flan-t5-small.
539
-
540
- Write pipeline + lifecycle (0.8.x, plus 0.12.x telemetry):
541
- - \`AWM_SLOW_WRITE_MS=250\` (0.12.x) any write slower than this logs one stderr
542
- line with a phase-time breakdown (embed/novelty/persist, event-loop lag,
543
- embed-model cold-load ms). \`0\` disables. Useful for diagnosing why a session's
544
- first write/recall feels slow.
545
- - \`AWM_REINFORCE_MAX_CONTENT_LEN=1500\` max chars an engram's content
546
- can grow to via merge-on-reinforce (drop-oldest on overflow). Higher =
547
- preserves more reinforced detail; lower = leaner recall output.
548
- - \`AWM_REINFORCE_MERGE_CONTENT=0\` disable content merge on reinforce.
549
- Reverts to pre-0.8.5 behavior (discard new content, only bump confidence).
550
- - \`AWM_NOVELTY_EMBED=0\` — disable the cosine channel in novelty
551
- computation. BM25-only fallback. Reverts to pre-0.8.5 novelty.
552
- - \`AWM_GRANULARITY_COMPACT_LEN=200\` char budget for query-aware snippet
553
- in \`granularity: 'compact'\` mode.
554
- - \`AWM_GRANULARITY_FULL_LEN=1000\`char budget for the top result in
555
- \`granularity: 'auto'\` mode when there's a clear winner.
556
-
557
- PGlite backend (0.8.x):
558
- - \`AWM_PGLITE_BM25_M=1\` — multiplier on PGlite \`ts_rank_cd\` to calibrate
559
- against SQLite FTS5 BM25 distribution. M=1 (default) is passthrough;
560
- higher M boosts PGlite scores at the cost of recall-ranking precision
561
- (see CHANGELOG 0.8.5 follow-up).
562
- - \`AWM_IVFFLAT_PROBES=5\` — pgvector ivfflat probes per query. Higher =
563
- more accurate, slower.
564
-
565
- In production, leave these all unset. Use only when diagnosing a suspected
566
- recall-quality regression.
567
- `.trimStart();
1
+ // Copyright 2026 Robert Winter / Complete Ideas
2
+ // SPDX-License-Identifier: Apache-2.0
3
+
4
+ /**
5
+ * Shared utilities for CLI adapters.
6
+ *
7
+ * Extracted from the original setup() in cli.ts — path resolution, secrets,
8
+ * environment variables, MCP command building, and the AWM instruction snippet.
9
+ */
10
+
11
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
12
+ import { resolve, join, dirname, basename } from 'node:path';
13
+ import { randomBytes } from 'node:crypto';
14
+ import { homedir as osHomedir } from 'node:os';
15
+ import { fileURLToPath } from 'node:url';
16
+ import type { SetupContext } from './types.js';
17
+
18
+ const __filename = fileURLToPath(import.meta.url);
19
+ const __dirname = dirname(__filename);
20
+
21
+ /** Resolve the AWM package root (where src/ and dist/ live). */
22
+ export function resolvePackageRoot(): string {
23
+ // __dirname is src/adapters/ at dev time, dist/adapters/ at build time
24
+ return resolve(__dirname, '..', '..');
25
+ }
26
+
27
+ /** Resolve the database path — default to <packageRoot>/data/memory.db. */
28
+ export function resolveDbPath(packageRoot: string, explicit?: string | null): string {
29
+ const dbPath = explicit ?? join(packageRoot, 'data', 'memory.db');
30
+ const dbDir = dirname(dbPath);
31
+ if (!existsSync(dbDir)) {
32
+ mkdirSync(dbDir, { recursive: true });
33
+ }
34
+ return dbPath;
35
+ }
36
+
37
+ /** Read or generate the hook secret token. */
38
+ export function resolveHookSecret(dbPath: string): string {
39
+ const secretPath = join(dirname(dbPath), '.awm-hook-secret');
40
+ if (existsSync(secretPath)) {
41
+ const existing = readFileSync(secretPath, 'utf-8').trim();
42
+ if (existing) return existing;
43
+ }
44
+ const secret = randomBytes(32).toString('hex');
45
+ mkdirSync(dirname(secretPath), { recursive: true });
46
+ writeFileSync(secretPath, secret + '\n');
47
+ return secret;
48
+ }
49
+
50
+ /** Build environment variables for the MCP server process. */
51
+ export function buildEnvVars(
52
+ dbPath: string,
53
+ agentId: string,
54
+ hookPort: string,
55
+ hookSecret: string,
56
+ isWindows: boolean,
57
+ ): Record<string, string> {
58
+ return {
59
+ AWM_DB_PATH: isWindows ? dbPath.replace(/\\/g, '/') : dbPath,
60
+ AWM_AGENT_ID: agentId,
61
+ AWM_HOOK_PORT: hookPort,
62
+ AWM_HOOK_SECRET: hookSecret,
63
+ };
64
+ }
65
+
66
+ /**
67
+ * Resolve the MCP server command + args.
68
+ *
69
+ * Prefers absolute path to dist/mcp.js (works from any cwd).
70
+ * Falls back to npx tsx src/mcp.ts for dev mode.
71
+ */
72
+ export function resolveMcpCommand(ctx: SetupContext): {
73
+ command: string;
74
+ args: string[];
75
+ } {
76
+ if (ctx.hasDist) {
77
+ return {
78
+ command: 'node',
79
+ args: [ctx.mcpDist.replace(/\\/g, '/')],
80
+ };
81
+ }
82
+ // Dev fallback
83
+ if (ctx.isWindows) {
84
+ return {
85
+ command: 'cmd',
86
+ args: ['/c', 'npx', 'tsx', ctx.mcpScript.replace(/\\/g, '/')],
87
+ };
88
+ }
89
+ return {
90
+ command: 'npx',
91
+ args: ['tsx', ctx.mcpScript],
92
+ };
93
+ }
94
+
95
+ /** Build a full SetupContext from parsed CLI flags. */
96
+ export function buildSetupContext(opts: {
97
+ agentId?: string;
98
+ dbPath?: string | null;
99
+ isGlobal: boolean;
100
+ hookPort: string;
101
+ }): SetupContext {
102
+ const cwd = process.cwd();
103
+ const projectName = basename(cwd).toLowerCase().replace(/[^a-z0-9-]/g, '-');
104
+ const packageRoot = resolvePackageRoot();
105
+ const mcpScript = join(packageRoot, 'src', 'mcp.ts');
106
+ const mcpDist = join(packageRoot, 'dist', 'mcp.js');
107
+ const hasDist = existsSync(mcpDist);
108
+ const isWindows = process.platform === 'win32';
109
+
110
+ const agentId = opts.agentId ?? (opts.isGlobal ? 'claude' : projectName);
111
+ const dbPath = resolveDbPath(packageRoot, opts.dbPath);
112
+ const hookSecret = resolveHookSecret(dbPath);
113
+ const envVars = buildEnvVars(dbPath, agentId, opts.hookPort, hookSecret, isWindows);
114
+
115
+ return {
116
+ cwd,
117
+ projectName,
118
+ agentId,
119
+ dbPath,
120
+ packageRoot,
121
+ mcpDist,
122
+ mcpScript,
123
+ hasDist,
124
+ hookSecret,
125
+ hookPort: opts.hookPort,
126
+ isGlobal: opts.isGlobal,
127
+ isWindows,
128
+ envVars,
129
+ };
130
+ }
131
+
132
+ /** Home directory. */
133
+ export function homedir(): string {
134
+ return osHomedir();
135
+ }
136
+
137
+ // ─── Instruction content ────────────────────────────────
138
+
139
+ /**
140
+ * Core AWM instruction snippet — shared across all adapters.
141
+ * Each adapter wraps this in the appropriate file format.
142
+ */
143
+ /**
144
+ * Upsert the AWM section into an instruction file (CLAUDE.md, AGENTS.md, .cursorrules).
145
+ *
146
+ * Behavior:
147
+ * - File doesn't exist -> create with title + AWM_INSTRUCTION_CONTENT
148
+ * - Section absent -> append
149
+ * - Section present + identical -> skip
150
+ * - Section present + stale -> REPLACE in place, preserve content above/below
151
+ *
152
+ * Section is bounded by `## Memory (AWM)` (with optional trailing modifier) at the
153
+ * start, and the next `## ` heading or EOF at the end.
154
+ *
155
+ * Returns a short human-readable status string for the setup command output.
156
+ */
157
+ /** Opening marker for the generated block. Everything between the markers is replaced
158
+ * on upgrade; anything outside them is preserved. The text is deliberately addressed to
159
+ * whoever opens the file, because that is who needs to know. */
160
+ export const AWM_GEN_BEGIN =
161
+ '<!-- AWM:GENERATED:BEGIN this block is REPLACED by `awm setup`. ' +
162
+ 'Put your own notes OUTSIDE these markers and they will survive upgrades. -->';
163
+ export const AWM_GEN_END = '<!-- AWM:GENERATED:END -->';
164
+
165
+ /** Wrap generated content in the markers. */
166
+ function wrapGenerated(content: string): string {
167
+ return `${AWM_GEN_BEGIN}\n${content.trim()}\n${AWM_GEN_END}`;
168
+ }
169
+
170
+ export function upsertAwmSection(
171
+ filePath: string,
172
+ newContent: string,
173
+ options: { titleIfNew?: string; suffix?: string; force?: boolean } = {},
174
+ ): string {
175
+ const fname = basename(filePath);
176
+ const suffix = options.suffix ?? '';
177
+ const force = options.force ?? false;
178
+
179
+ if (!existsSync(filePath)) {
180
+ const title = options.titleIfNew ?? `# ${basename(dirname(filePath))}`;
181
+ mkdirSync(dirname(filePath), { recursive: true });
182
+ writeFileSync(filePath, `${title}\n\n${wrapGenerated(newContent)}${suffix}`);
183
+ return `${fname}: created with AWM workflow section`;
184
+ }
185
+
186
+ const existing = readFileSync(filePath, 'utf-8');
187
+
188
+ // ---- Preferred path: the file already carries generated markers, so the boundary
189
+ // between "ours" and "theirs" is explicit and only our block is touched.
190
+ const gb = existing.indexOf(AWM_GEN_BEGIN);
191
+ const ge = existing.indexOf(AWM_GEN_END);
192
+ if (gb !== -1 && ge > gb) {
193
+ const current = existing.slice(gb, ge + AWM_GEN_END.length);
194
+ const desired = wrapGenerated(newContent);
195
+ if (current.trimEnd() === desired.trimEnd()) {
196
+ return `${fname}: AWM section already up-to-date (skipped)`;
197
+ }
198
+ writeFileSync(filePath, existing.slice(0, gb) + desired + existing.slice(ge + AWM_GEN_END.length));
199
+ return `${fname}: AWM generated block updated (content outside the markers preserved)`;
200
+ }
201
+
202
+ // Find section bounds: `## Memory (AWM)` (possibly with ` MANDATORY` etc.) until next `## ` or EOF
203
+ const startRegex = /^## Memory \(AWM\)[^\n]*$/m;
204
+ const startMatch = startRegex.exec(existing);
205
+
206
+ if (!startMatch) {
207
+ // Section not present — append
208
+ writeFileSync(filePath, existing.trimEnd() + '\n\n' + wrapGenerated(newContent) + suffix);
209
+ return `${fname}: appended AWM workflow section`;
210
+ }
211
+
212
+ // Find end: next `## ` heading after the section start, or EOF
213
+ const afterStart = startMatch.index + startMatch[0].length;
214
+ const nextHeadingRegex = /^## (?!Memory \(AWM\))/m;
215
+ nextHeadingRegex.lastIndex = afterStart;
216
+ const tail = existing.slice(afterStart);
217
+ const nextMatch = nextHeadingRegex.exec(tail);
218
+ const sectionEnd = nextMatch ? afterStart + nextMatch.index : existing.length;
219
+
220
+ const currentSection = existing.slice(startMatch.index, sectionEnd).trimEnd();
221
+ const desiredSection = (newContent + suffix).trimEnd();
222
+
223
+ if (currentSection === desiredSection) {
224
+ return `${fname}: AWM section already up-to-date (skipped)`;
225
+ }
226
+
227
+ // ---- LEGACY, UNMARKED SECTION.
228
+ // Written before generated markers existed, so hand-added notes inside it are
229
+ // indistinguishable from generated text. Replacing would silently delete them on a
230
+ // real install this measured 169 of 381 lines (44%), every one an operational finding
231
+ // that cost real debugging. Back up and refuse; the caller opts in explicitly.
232
+ if (!force) {
233
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-').replace('Z', '');
234
+ const backup = `${filePath}.awm-backup-${stamp}`;
235
+ try {
236
+ writeFileSync(backup, existing);
237
+ } catch {
238
+ return `${fname}: AWM section is out of date, but it has no generated markers and the ` +
239
+ `backup could not be written REFUSING to touch it. Copy the file yourself, then re-run.`;
240
+ }
241
+ return `${fname}: NOT updated the AWM section predates generated markers, so your own ` +
242
+ `notes inside it cannot be told apart from generated text and would be lost. ` +
243
+ `Backup written to ${basename(backup)}. To upgrade: move any notes you want to keep ` +
244
+ `ABOVE the '## Memory (AWM)' heading (content outside the section is always preserved), ` +
245
+ `then re-run with force. Nothing has been changed.`;
246
+ }
247
+
248
+ const before = existing.slice(0, startMatch.index).trimEnd();
249
+ const after = existing.slice(sectionEnd).replace(/^\s*\n/, '');
250
+ const rebuilt =
251
+ (before ? before + '\n\n' : '') +
252
+ wrapGenerated(newContent) + suffix +
253
+ (after ? '\n\n' + after : '\n');
254
+ writeFileSync(filePath, rebuilt);
255
+ return `${fname}: AWM section replaced with a marked generated block (force)`;
256
+ }
257
+
258
+ export const AWM_INSTRUCTION_CONTENT = `
259
+ ## Memory (AWM) MANDATORY
260
+
261
+ **AWM is THE memory system.** Use it via the \`agent-working-memory\` MCP server
262
+ (preferred) or HTTP at \`http://127.0.0.1:8400\` (fallback). The file-based
263
+ auto-memory at \`~/.claude/projects/.../memory/*.md\` is a LEGACY bootstrap path —
264
+ **do not write new memories to it.** All persistent knowledge goes through AWM.
265
+
266
+ If MCP tools aren't loaded at session start, use ToolSearch with
267
+ \`select:mcp__agent-working-memory__memory_recall,mcp__agent-working-memory__memory_write\`
268
+ to load them. If the MCP server isn't responsive, restart with \`/mcp\` or use
269
+ the HTTP endpoints (\`POST /memory/write-batch\`, \`POST /memory/activate\`)
270
+ directlybut **DO NOT fall back to markdown files**. Files drift the moment
271
+ you write them; AWM stays current because every agent reads + writes the same store.
272
+
273
+ ### Lifecycle (always do these, in this order)
274
+ 1. **Session start**: call \`memory_restore\` to recover previous context. If it reports the
275
+ store is empty/new (or recall keeps returning nothing), **warm-start first**: recall the
276
+ \`onboard a new project\` skill and follow it — or call \`onboard_scan\` on the project's
277
+ docs/repo, refine the candidates, run \`onboard_questions\`, and save the good ones with
278
+ \`memory_write\` (canonical). A cold store is nearly useless until it's seeded.
279
+ 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
280
+ 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
281
+ the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
282
+ than one filesystem search.
283
+ 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
284
+ 5. **Finishing a task**: call \`memory_task_end\` with a summary.
285
+ 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
286
+
287
+ ### Write memory when:
288
+ - A project decision is made or changed
289
+ - A root cause is discovered after debugging
290
+ - A reusable implementation pattern is established
291
+ - A user preference, constraint, or requirement is clarified
292
+ - A prior assumption is found to be wrong
293
+ - A significant piece of work is completed
294
+
295
+ ### Writing for recall (the highest-leverage section)
296
+ A memory's recall quality is set the moment you write it. AWM is fast at
297
+ finding what's findable — but if the write is shaped wrong, no retriever
298
+ can rescue it. Be slightly more verbose at the front than feels natural:
299
+ the first 1-2 sentences are what BM25, the embedding model, and concept
300
+ extraction all see most strongly.
301
+
302
+ - **Lead with the rule or fact.** Don't open with context or backstory.
303
+ "Don't mock the database in integration tests." comes first; the reason
304
+ comes second. Recall scans the head of the body, not the tail.
305
+ - **Pick the most specific topic.** Not \`auth\` \`auth-magic-link-rate-limit\`.
306
+ Topic is a hard filter at recall time. Generic topics hide the memory in
307
+ a noisy bucket where it competes with everything else in the area.
308
+ - **Include 2+ retrievable identifiers.** File paths, function names, table
309
+ columns, ticket IDs, exact error strings, the literal terms a future query
310
+ will use. \`AccountingService.closePeriod()\` beats "the accounting code."
311
+ \`tblMemberDetails.activation_date\` beats "the activation column."
312
+ \`schema/072-period-close.sql\` beats "the migration."
313
+ - **Write in the vocabulary of the future question.** When you imagine asking
314
+ this in three months, what nouns will you use? Use those nouns. Don't
315
+ paraphrase the user's domain language into your own neutral summary.
316
+ - **Name the CATEGORY as well as the specifics — both, always.** Specifics
317
+ make a memory precise; category words make it *reachable*. A memory that
318
+ says "private plan memory peaked 88%, scale P1v3 -> P2v3" never says
319
+ "Azure" or "App Service Plan", so a question asked in those words cannot
320
+ find itmeasured on a real store, that memory was not in the top 40
321
+ candidates for "azure app service plan capacity increase". Write the
322
+ system / product / domain nouns (Azure App Service Plan, Freshdesk ticket,
323
+ MySQL connection pool, ShowConnect scoring) NEXT TO the identifiers.
324
+ Note this cuts against "pick the most specific topic" above: that rule is
325
+ about the \`topic\` TAG, not a licence to omit the category from the body.
326
+ Measured on an 11k-engram store: 94% of tagged memories are missing at
327
+ least one of their own topical terms from the body, and 66% of those
328
+ terms never appear in the text at all.
329
+ - **Tags are NOT a substitute for body text.** Only BM25 indexes tags. The
330
+ embedding is built from \`concept + content\` and the cross-encoder rerank
331
+ passage is built from \`concept + content\` — neither sees tags. So a word
332
+ that exists only as a tag is invisible to two of the three retrieval
333
+ channels, including the one that decides final ordering. Tag it *and*
334
+ write it.
335
+ - **Reserve canonical for stable invariants.** Decisions, requirements,
336
+ hard facts, cross-agent shared context. Working class (default) is correct
337
+ for findings, observations, and progress notes. The canonical floor is
338
+ 0.7 salienceoverusing it pollutes the canonical layer and the floor
339
+ loses meaning.
340
+ - **Include the why for feedback memories.** A rule without a reason can't
341
+ be applied to edge cases. "Don't mock the database" is brittle. "Don't
342
+ mock the database last quarter mocked tests masked a broken migration"
343
+ is portable to new situations.
344
+
345
+ ### Tagging rules (REQUIRED AWM's prefix-tag retrieval boost depends on these)
346
+
347
+ Every \`memory_write\` should pass these structured fields. AWM stores each as a
348
+ prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
349
+ and entity-bridge boosts at recall time.
350
+
351
+ | Field | Required? | Format | Example |
352
+ |---|---|---|---|
353
+ | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
354
+ | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
355
+ | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
356
+ | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
357
+ | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
358
+ | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
359
+ | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
360
+ | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
361
+
362
+ **Always add identifier tags when present in the content:**
363
+ - \`ticket=<id>\` for Freshdesk tickets
364
+ - \`member=<id>\` for member IDs
365
+ - \`horse=<id>\` for horse_member_id
366
+ - \`usef=<id>\` for USEF lookups
367
+ - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
368
+ - \`person=<Name>\` for stakeholder quotes / decisions
369
+ - \`version=<X.Y.Z>\` for release-specific findings
370
+
371
+ ### Entity index exact-match recall for named things (default off)
372
+ Structured identifier tags (\`ticket=\`, \`person=\`, \`horse=\`, \`member=\`, bare 4+ digit
373
+ ids, etc.) feed a dedicated entity inverted index, separate from BM25/embedding scoring.
374
+ A query naming an entity ("ticket 19252", "Kaleigh Collett") can reach the memory through
375
+ this index even when the wording doesn't lexically match it's a deterministic exact
376
+ lookup, immune to vocabulary mismatch. Keep identifier tags exact and consistent for
377
+ this reason, not just for the BM25 boost described above.
378
+
379
+ Off by default; opt in with \`AWM_ENTITY_INDEX_FETCH=1\` (bounded by
380
+ \`AWM_ENTITY_INDEX_CAP\`, default 12). Matched entities get no score boost — they're
381
+ guaranteed a reranker audition instead, so the cross-encoder alone decides whether they
382
+ surface. Worth trialing on identifier-heavy workloads (ticket/event numbers, named
383
+ people/things you refer to by name often); not yet the default pending evaluation.
384
+
385
+ ### Temporal validity memories that expire or start in the future
386
+ \`memory_write\` accepts \`valid_from\` / \`valid_to\` (ISO dates). Use \`valid_to\` on
387
+ **operational** facts with a real shelf life a deploy state, "waiting on X's reply",
388
+ a ticket status so the memory expires instead of relying on you to remember it's
389
+ stale. Recall renders \`[valid until …]\` on results carrying this field. Use
390
+ \`valid_from\` for a fact that becomes true on a known future date (a policy change, a
391
+ season that hasn't started yet). Don't set either for durable facts most memories
392
+ don't need them.
393
+
394
+ ### Memory classes (controls how strictly the salience filter gates the write)
395
+ - \`memory_class: canonical\` source-of-truth memories. Floor 0.7 salience, never staged.
396
+ Use for: user-stated decisions, project requirements, verified architectural facts,
397
+ cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
398
+ for writes that other agents must be able to recall** — the default \`working\` class
399
+ may get filtered.
400
+ - \`memory_class: working\` (default)observations and findings. Salience-gated.
401
+ - \`memory_class: ephemeral\` short-lived context that should decay quickly.
402
+
403
+ ### Salience auto-promotion (defense in depth)
404
+ The salience filter automatically promotes certain content patterns even if you forget
405
+ to set \`memory_class\` explicitly:
406
+ - **User feedback** content starting with "Robert said…", "Katherine directed…",
407
+ "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
408
+ always preserves the decision.
409
+ - **Verified operational records** — content with an action verb (Submitted, Finalized,
410
+ Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
411
+ Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
412
+ or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
413
+ a 0.45 salience floor. So batch summaries with real IDs survive even when topic
414
+ terms repeat.
415
+
416
+ If neither pattern applies and you want a memory to definitely survive, set
417
+ \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
418
+
419
+ ### Recall memory when:
420
+ - **BEFORE stating ANY fact about how a system works** recall first; if AWM doesn't
421
+ have it, read the code. Never guess and present it as fact.
422
+ - **BEFORE searching the filesystem** recall first; AWM is faster and has cross-session
423
+ knowledge that file search doesn't.
424
+ - Starting work on a new task or subsystem
425
+ - Re-entering code you haven't touched recently
426
+ - After a failed attempt check if there's prior knowledge
427
+ - Before refactoring or making architectural changes
428
+ - When a topic comes up that you might have prior context on
429
+
430
+ Recall is fast (~300ms typical). Use it freely.
431
+
432
+ ### Chain recalls one hop per call
433
+
434
+ AWM returns what matches your query. It does **not** walk from that answer to the next
435
+ fact, and it is not meant to: it is active memory, holding what you need right now.
436
+ Following a chain to the next thing is **your** job — recall, read, recall again, each
437
+ result becoming the cue for the next query.
438
+
439
+ So when a question refers to something **by its role instead of its name**, you have a
440
+ chain, not a query:
441
+
442
+ > *"What is the codename of the project owned by my scheduler?"*
443
+
444
+ That is three lookups, not one:
445
+
446
+ 1. recall \`who is my scheduler\` a name
447
+ 2. recall \`what project does <that name> own\` → a project
448
+ 3. recall \`<that project> codename\` the answer
449
+
450
+ **The failure mode is answering from the first recall.** A single query blending all
451
+ three terms returns the most *salient* related memory, not the correct one — measured,
452
+ that returns the main project's codename with complete confidence, and it is wrong.
453
+ Each hop on its own is an ordinary, reliable recall; the chain only breaks when you stop
454
+ asking.
455
+
456
+ Tells that you are looking at a chain: a possessive or relative clause naming an entity
457
+ by role rather than identity (\`my scheduler\`, \`the owner of X\`, \`whoever signed
458
+ off on Y\`), or a rule that operates on an attribute you have not looked up yet (\`the
459
+ release tag of the project we discussed\` needs that project's codename first). If
460
+ resolving the question requires a fact you would have to *derive*, recall the fact
461
+ instead.
462
+
463
+ ### Recall strategy (when one query isn't enough)
464
+ AWM's adaptive retrieval handles most query variations natively — synonym
465
+ expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
466
+ A single recall is usually enough.
467
+
468
+ When it isn't:
469
+ - **If the first recall returns nothing or returns the wrong things, reformulate.**
470
+ Try a second query with different phrasing — synonyms, more specific nouns,
471
+ the exact identifier from the code rather than the conceptual name. Two or
472
+ three recalls cost less than one filesystem search.
473
+ - **Use the words a domain expert would use, not generic English.** "Period
474
+ close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
475
+ - **For broad exploration, pass \`mode: "exploratory"\`** — wider candidate
476
+ pool, lower precision floor. For specific lookups, leave mode unset (auto).
477
+ - **Don't ensemble more than 3 reformulations.** If three different phrasings
478
+ return nothing, the memory probably isn't there — read the code instead of
479
+ burning more recalls.
480
+
481
+ ### Recall tuning (0.8.x opt-in parameters for higher-quality recall)
482
+ Default \`memory_recall\` is tuned for the common case. The 0.8.x recall pipeline
483
+ exposes four opt-in parameters that change the cost/quality tradeoff. Use them
484
+ when the default doesn't match what you actually need.
485
+
486
+ - **\`granularity: 'compact'\`** every result carries a 200-char \`summary\`
487
+ field with a query-aware snippet (the densest window of query terms in the
488
+ content). Use this when you expect to scan 5+ results to find one — saves
489
+ ~70% of recall output tokens. The full content stays available in
490
+ \`engram.content\` if you want to drill into a specific result.
491
+ - **\`granularity: 'auto'\`** confidence-adaptive. If the top result is a clear
492
+ winner, it gets a longer summary while the rest are compact. If confidence
493
+ is uniform across results, everything is compact. Use when you don't know
494
+ in advance whether one result will dominate.
495
+ - **\`require_confidence: 0.10 | 0.25 | 0.40\`** opt-in abstention. AWM
496
+ returns \`[]\` instead of low-confidence noise. Use when you're about to ACT
497
+ on the recalled fact (grounding a decision, citing the memory verbatim,
498
+ contradicting a prior assumption). Thresholds: \`0.10\` strict — only abstain
499
+ on garbage; \`0.25\` balanced; \`0.40\` aggressive prefer "I don't know"
500
+ over "best of bad." When abstention fires (empty result), treat it as a
501
+ signal either the memory genuinely isn't there (read the code) or your
502
+ query missed (reformulate). Don't retry without the threshold.
503
+ - **\`workspace: "<name>"\`** — hive-mode recall across all agents in the
504
+ workspace. Use when other agents may have written canonical knowledge you
505
+ need. Default is agent-scoped (your own memories only). Can also be set
506
+ globally via the \`AWM_WORKSPACE\` env var.
507
+
508
+ ### Keep memory fresh
509
+ - After recalling a memory, if you observe the real state is different → call
510
+ \`memory_supersede\` immediately with the corrected version.
511
+ - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
512
+ activation engine learns what's valuable.
513
+ - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
514
+ - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
515
+ drifts out of date. The system relies on you to keep it current. This is the #1
516
+ failure mode.**
517
+
518
+ ### Cognition recipes YOU do the thinking, AWM keeps the result (0.11.x)
519
+ AWM contains no LLM. When memory needs real thinking — distilling a repeatable
520
+ procedure, reflecting on a failure AWM hands YOU a versioned recipe (prompt +
521
+ strict output shape) and you run it as a SEPARATE focused pass, then write the
522
+ result back as an ordinary memory with provenance.
523
+
524
+ - \`memory_task_end\` responses include the recipe invitations. Honor the gates:
525
+ skill-derivation only after a genuinely procedural task (3+ tool calls or a
526
+ delegated sub-task); friction-lesson only after a failure/retry/wrong assumption.
527
+ - Run each recipe as its own focused pass — do NOT bundle it with other
528
+ reasoning; bundled passes reliably drop the output.
529
+ - Write back exactly per the recipe's contract: \`origin_class: 'recipe'\` +
530
+ \`recipe_id\` (e.g. \`skill-derivation@1\`), concept prefixed \`skill: \` or
531
+ \`lesson: \`. AWM validates the shape and rejects malformed or unknown-recipe
532
+ writes with the contract echoed back fix and retry, don't drop the insight.
533
+ - Re-deriving the same skill name reinforces the existing memory instead of
534
+ duplicating it, so don't fear writing a skill you may have written before.
535
+
536
+ ### Content fade write-and-forget is safe (0.8.x)
537
+ Un-recalled engrams gradually fade their content while preserving cue pathways
538
+ (concept + tags + embedding stay intact). This is Paper 1 — storage
539
+ degradation. Practical implications:
540
+
541
+ - **Don't manually purge memories** to "save space." The system already
542
+ compresses unused content. Old memories stay findable via cue match even
543
+ when their body has decayed.
544
+ - **Don't over-pin with \`memory_class: canonical\`** to fight fade. Canonical
545
+ only changes salience gating at write time, not fade behavior. Fade
546
+ affects un-recalled engrams of any class.
547
+ - **Recall keeps content alive.** Every recall touches the engram and resets
548
+ its fade clock. Frequently-recalled memories stay full-fidelity automatically.
549
+ - **Supersede is the right tool for stale facts.** When you observe a memory
550
+ is outdated, call \`memory_supersede\` — the new version inherits the old
551
+ one's coherent associations (counter-narrative replacement, 0.8.x) so cue
552
+ pathways carry forward to the replacement.
553
+
554
+ ### Examplegood vs bad memory_write
555
+
556
+ **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
557
+ \`\`\`
558
+ memory_write(
559
+ concept="found a bug",
560
+ content="The thing I was looking at was broken so I fixed it."
561
+ )
562
+ \`\`\`
563
+
564
+ **GOOD** (rich identifiers, structured metadata, prefix tags):
565
+ \`\`\`
566
+ memory_write(
567
+ concept="EquiHub period-close BLOCKED check missing server-side",
568
+ 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.",
569
+ project="EquiHub",
570
+ topic="accounting",
571
+ intent="finding",
572
+ confidence_level="verified",
573
+ source="debugging",
574
+ memory_class="canonical",
575
+ tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
576
+ )
577
+ \`\`\`
578
+
579
+ ### Also:
580
+ - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
581
+ - \`memory_whoami\` (MCP tool) / \`GET /whoami\` — identify the instance you're actually
582
+ talking to: agent id, workspace, mode, backend, store path, code provenance, sibling
583
+ agent spaces sharing the store. Call this FIRST whenever you're unsure which store,
584
+ which agent identity, or which running code you're dealing with — before reasoning
585
+ about AWM's own state from a stale memory or an assumed port number.
586
+ - AWM is shared across all agents in real time. When any agent writes or supersedes a
587
+ memory, every other agent can recall it immediately — but only within the same
588
+ workspace and agent scope.
589
+
590
+ ### Output compression (token efficiency, output-only)
591
+ When a tool returns a LARGE STRUCTURED result you need to keep in context — a JSON
592
+ array of records, query rows, a log dump, an API response — pass it through
593
+ \`compress_output\` first. It re-encodes the data as TOON (a compact, lossless,
594
+ schema-aware tabular form of JSON), cutting ~50-65% of the tokens at no
595
+ comprehension cost. This is output-only: it never changes the data or your memories.
596
+ - Use it on big STRUCTURED outputs, not on prose. Prose is returned unchanged —
597
+ for trimming memory prose, use recall \`granularity: 'compact'\` instead.
598
+ - It returns a \`ref\`; call \`retrieve_original(ref)\` if you later need the exact
599
+ verbatim source (e.g. to hand it to another tool unchanged).
600
+ - Don't bother for small outputs — it only compresses when the saving is worthwhile
601
+ and falls back to plain JSON if TOON wouldn't reproduce the data exactly.
602
+
603
+ ### Backend (SQLite vs PGlite, 0.8.x)
604
+ AWM ships two storage backends. The installer picks SQLite by default; both
605
+ are functionally equivalent for cognitive workloads, but differ in operational
606
+ guarantees:
607
+
608
+ - **SQLite** (default) — embedded, **multi-process safe** via WAL mode. Best
609
+ for single-machine setups and MCP scenarios where multiple Claude Code
610
+ sessions may open the same database concurrently.
611
+ - **PGlite** — embedded Postgres (WASM) with pgvector. **Single-process only**
612
+ — two MCP processes against the same \`memory-pglite/\` directory will
613
+ abort the second. Pick via \`AWM_STORE_BACKEND=pglite\` and
614
+ \`AWM_DB_PATH=path/to/memory-pglite\`.
615
+ - **Auto-detect** — if \`AWM_DB_PATH\` points to a directory that already
616
+ exists, AWM detects PGlite; a file → SQLite. No explicit
617
+ \`AWM_STORE_BACKEND\` needed when an existing DB is present.
618
+
619
+ For the comparison table (recall quality parity, BM25 vs \`ts_rank_cd\`,
620
+ multi-process guarantees), see \`docs/pglite-feature-parity.md\`.
621
+
622
+ ### Diagnostics / escape hatches (env vars, only if you know why)
623
+ The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. The 0.8.x work
624
+ added the write-path rewrite (per-write 300+ ms → under 10ms) and PGlite
625
+ parity tuning. Each optimization is gated by an env-var so it can be disabled
626
+ for A/B testing if a regression appears in your workload:
627
+
628
+ Recall pipeline (0.7.x):
629
+ - \`AWM_DISABLE_POOL_FILTER=1\` — disables the candidate pool reduction
630
+ pre-filter in recall. Reverts to scoring all active candidates.
631
+ - \`AWM_ENTITY_INDEX_FETCH=1\` — see "Entity index" above (0.12.x, default off).
632
+ - \`AWM_DISABLE_SLIM_CACHE=1\` — disables the in-memory slim cache.
633
+ Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
634
+ - \`AWM_DISABLE_RERANK_SKIP=1\` — disables the cross-encoder skip on
635
+ clear-winner queries. Forces every recall through the reranker.
636
+ - \`AWM_DISABLE_EXPANSION_CACHE=1\` — disables the query expansion skip
637
+ heuristic + LRU cache. Forces every recall through flan-t5-small.
638
+
639
+ Write pipeline + lifecycle (0.8.x, plus 0.12.x telemetry):
640
+ - \`AWM_SLOW_WRITE_MS=250\` (0.12.x) — any write slower than this logs one stderr
641
+ line with a phase-time breakdown (embed/novelty/persist, event-loop lag,
642
+ embed-model cold-load ms). \`0\` disables. Useful for diagnosing why a session's
643
+ first write/recall feels slow.
644
+ - \`AWM_REINFORCE_MAX_CONTENT_LEN=1500\` — max chars an engram's content
645
+ can grow to via merge-on-reinforce (drop-oldest on overflow). Higher =
646
+ preserves more reinforced detail; lower = leaner recall output.
647
+ - \`AWM_REINFORCE_MERGE_CONTENT=0\` — disable content merge on reinforce.
648
+ Reverts to pre-0.8.5 behavior (discard new content, only bump confidence).
649
+ - \`AWM_NOVELTY_EMBED=0\` — disable the cosine channel in novelty
650
+ computation. BM25-only fallback. Reverts to pre-0.8.5 novelty.
651
+ - \`AWM_GRANULARITY_COMPACT_LEN=200\` — char budget for query-aware snippet
652
+ in \`granularity: 'compact'\` mode.
653
+ - \`AWM_GRANULARITY_FULL_LEN=1000\` — char budget for the top result in
654
+ \`granularity: 'auto'\` mode when there's a clear winner.
655
+
656
+ PGlite backend (0.8.x):
657
+ - \`AWM_PGLITE_BM25_M=1\` — multiplier on PGlite \`ts_rank_cd\` to calibrate
658
+ against SQLite FTS5 BM25 distribution. M=1 (default) is passthrough;
659
+ higher M boosts PGlite scores at the cost of recall-ranking precision
660
+ (see CHANGELOG 0.8.5 follow-up).
661
+ - \`AWM_IVFFLAT_PROBES=5\` — pgvector ivfflat probes per query. Higher =
662
+ more accurate, slower.
663
+
664
+ In production, leave these all unset. Use only when diagnosing a suspected
665
+ recall-quality regression.
666
+ `.trimStart();