agent-working-memory 0.7.17 → 0.8.5

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 (186) hide show
  1. package/README.md +156 -15
  2. package/dist/adapters/common.js +202 -202
  3. package/dist/adapters/http.js +22 -22
  4. package/dist/api/routes.d.ts +1 -1
  5. package/dist/api/routes.d.ts.map +1 -1
  6. package/dist/api/routes.js +258 -79
  7. package/dist/api/routes.js.map +1 -1
  8. package/dist/cli/migrate.d.ts +42 -0
  9. package/dist/cli/migrate.d.ts.map +1 -0
  10. package/dist/cli/migrate.js +268 -0
  11. package/dist/cli/migrate.js.map +1 -0
  12. package/dist/cli.js +147 -103
  13. package/dist/cli.js.map +1 -1
  14. package/dist/coordination/circuit-breaker.d.ts +24 -0
  15. package/dist/coordination/circuit-breaker.d.ts.map +1 -0
  16. package/dist/coordination/circuit-breaker.js +70 -0
  17. package/dist/coordination/circuit-breaker.js.map +1 -0
  18. package/dist/coordination/failure-modes.d.ts +21 -0
  19. package/dist/coordination/failure-modes.d.ts.map +1 -0
  20. package/dist/coordination/failure-modes.js +49 -0
  21. package/dist/coordination/failure-modes.js.map +1 -0
  22. package/dist/coordination/peer-decisions.js +7 -7
  23. package/dist/coordination/routes.d.ts.map +1 -1
  24. package/dist/coordination/routes.js +44 -1
  25. package/dist/coordination/routes.js.map +1 -1
  26. package/dist/coordination/schema.d.ts.map +1 -1
  27. package/dist/coordination/schema.js +18 -0
  28. package/dist/coordination/schema.js.map +1 -1
  29. package/dist/coordination/schemas.d.ts +9 -9
  30. package/dist/coordination/stale.d.ts +9 -1
  31. package/dist/coordination/stale.d.ts.map +1 -1
  32. package/dist/coordination/stale.js +53 -9
  33. package/dist/coordination/stale.js.map +1 -1
  34. package/dist/core/embeddings.d.ts +16 -10
  35. package/dist/core/embeddings.d.ts.map +1 -1
  36. package/dist/core/embeddings.js +54 -38
  37. package/dist/core/embeddings.js.map +1 -1
  38. package/dist/core/ml-worker-entry.d.ts +17 -0
  39. package/dist/core/ml-worker-entry.d.ts.map +1 -0
  40. package/dist/core/ml-worker-entry.js +193 -0
  41. package/dist/core/ml-worker-entry.js.map +1 -0
  42. package/dist/core/ml-worker.d.ts +59 -0
  43. package/dist/core/ml-worker.d.ts.map +1 -0
  44. package/dist/core/ml-worker.js +253 -0
  45. package/dist/core/ml-worker.js.map +1 -0
  46. package/dist/core/query-expander.d.ts +13 -15
  47. package/dist/core/query-expander.d.ts.map +1 -1
  48. package/dist/core/query-expander.js +48 -54
  49. package/dist/core/query-expander.js.map +1 -1
  50. package/dist/core/reranker.d.ts +9 -19
  51. package/dist/core/reranker.d.ts.map +1 -1
  52. package/dist/core/reranker.js +33 -35
  53. package/dist/core/reranker.js.map +1 -1
  54. package/dist/core/salience.d.ts +32 -5
  55. package/dist/core/salience.d.ts.map +1 -1
  56. package/dist/core/salience.js +201 -28
  57. package/dist/core/salience.js.map +1 -1
  58. package/dist/core/write-pipeline.d.ts +10 -2
  59. package/dist/core/write-pipeline.d.ts.map +1 -1
  60. package/dist/core/write-pipeline.js +218 -49
  61. package/dist/core/write-pipeline.js.map +1 -1
  62. package/dist/engine/activation.d.ts +2 -2
  63. package/dist/engine/activation.d.ts.map +1 -1
  64. package/dist/engine/activation.js +238 -115
  65. package/dist/engine/activation.js.map +1 -1
  66. package/dist/engine/confidence.d.ts +62 -0
  67. package/dist/engine/confidence.d.ts.map +1 -0
  68. package/dist/engine/confidence.js +100 -0
  69. package/dist/engine/confidence.js.map +1 -0
  70. package/dist/engine/connections.d.ts +47 -8
  71. package/dist/engine/connections.d.ts.map +1 -1
  72. package/dist/engine/connections.js +83 -22
  73. package/dist/engine/connections.js.map +1 -1
  74. package/dist/engine/consolidation-scheduler.d.ts +46 -10
  75. package/dist/engine/consolidation-scheduler.d.ts.map +1 -1
  76. package/dist/engine/consolidation-scheduler.js +170 -50
  77. package/dist/engine/consolidation-scheduler.js.map +1 -1
  78. package/dist/engine/consolidation.d.ts +16 -2
  79. package/dist/engine/consolidation.d.ts.map +1 -1
  80. package/dist/engine/consolidation.js +143 -44
  81. package/dist/engine/consolidation.js.map +1 -1
  82. package/dist/engine/eval.d.ts +2 -2
  83. package/dist/engine/eval.d.ts.map +1 -1
  84. package/dist/engine/eval.js +9 -9
  85. package/dist/engine/eval.js.map +1 -1
  86. package/dist/engine/eviction.d.ts +4 -4
  87. package/dist/engine/eviction.d.ts.map +1 -1
  88. package/dist/engine/eviction.js +15 -15
  89. package/dist/engine/eviction.js.map +1 -1
  90. package/dist/engine/retraction.d.ts +93 -5
  91. package/dist/engine/retraction.d.ts.map +1 -1
  92. package/dist/engine/retraction.js +238 -19
  93. package/dist/engine/retraction.js.map +1 -1
  94. package/dist/engine/staging.d.ts +1 -1
  95. package/dist/engine/staging.d.ts.map +1 -1
  96. package/dist/engine/staging.js +3 -3
  97. package/dist/engine/staging.js.map +1 -1
  98. package/dist/hooks/sidecar.d.ts +1 -1
  99. package/dist/hooks/sidecar.d.ts.map +1 -1
  100. package/dist/hooks/sidecar.js +4 -4
  101. package/dist/hooks/sidecar.js.map +1 -1
  102. package/dist/index.js +48 -31
  103. package/dist/index.js.map +1 -1
  104. package/dist/mcp.js +167 -141
  105. package/dist/mcp.js.map +1 -1
  106. package/dist/storage/factory.d.ts +55 -0
  107. package/dist/storage/factory.d.ts.map +1 -0
  108. package/dist/storage/factory.js +135 -0
  109. package/dist/storage/factory.js.map +1 -0
  110. package/dist/storage/pglite-schema.d.ts +20 -0
  111. package/dist/storage/pglite-schema.d.ts.map +1 -0
  112. package/dist/storage/pglite-schema.js +165 -0
  113. package/dist/storage/pglite-schema.js.map +1 -0
  114. package/dist/storage/pglite.d.ts +187 -0
  115. package/dist/storage/pglite.d.ts.map +1 -0
  116. package/dist/storage/pglite.js +1114 -0
  117. package/dist/storage/pglite.js.map +1 -0
  118. package/dist/storage/sqlite.d.ts +117 -0
  119. package/dist/storage/sqlite.d.ts.map +1 -1
  120. package/dist/storage/sqlite.js +357 -8
  121. package/dist/storage/sqlite.js.map +1 -1
  122. package/dist/storage/store.d.ts +63 -0
  123. package/dist/storage/store.d.ts.map +1 -0
  124. package/dist/storage/store.js +27 -0
  125. package/dist/storage/store.js.map +1 -0
  126. package/dist/types/engram.d.ts +92 -2
  127. package/dist/types/engram.d.ts.map +1 -1
  128. package/dist/types/engram.js.map +1 -1
  129. package/package.json +3 -1
  130. package/src/adapters/claude-code.ts +218 -218
  131. package/src/adapters/codex.ts +252 -252
  132. package/src/adapters/common.ts +411 -411
  133. package/src/adapters/cursor.ts +135 -135
  134. package/src/adapters/http.ts +93 -93
  135. package/src/adapters/index.ts +31 -31
  136. package/src/adapters/types.ts +75 -75
  137. package/src/api/index.ts +3 -3
  138. package/src/api/routes.ts +970 -714
  139. package/src/cli/migrate.ts +307 -0
  140. package/src/cli.ts +755 -719
  141. package/src/coordination/circuit-breaker.ts +83 -0
  142. package/src/coordination/events.ts +90 -90
  143. package/src/coordination/failure-modes.ts +50 -0
  144. package/src/coordination/peer-decisions.ts +105 -105
  145. package/src/coordination/plugin-loader.ts +60 -60
  146. package/src/coordination/plugin.ts +44 -44
  147. package/src/coordination/routes.ts +56 -1
  148. package/src/coordination/schema.ts +13 -0
  149. package/src/coordination/stale.ts +80 -11
  150. package/src/coordination/types.ts +311 -311
  151. package/src/coordination/write-mutex.ts +69 -69
  152. package/src/core/auto-tagger.ts +168 -168
  153. package/src/core/decay.ts +63 -63
  154. package/src/core/embeddings.ts +110 -93
  155. package/src/core/index.ts +5 -5
  156. package/src/core/logger.ts +36 -36
  157. package/src/core/ml-worker-entry.ts +194 -0
  158. package/src/core/ml-worker.ts +281 -0
  159. package/src/core/query-expander.ts +122 -128
  160. package/src/core/reranker.ts +119 -125
  161. package/src/core/salience.ts +200 -33
  162. package/src/core/write-pipeline.ts +521 -343
  163. package/src/engine/activation.ts +235 -109
  164. package/src/engine/confidence.ts +120 -0
  165. package/src/engine/connections.ts +162 -103
  166. package/src/engine/consolidation-scheduler.ts +242 -125
  167. package/src/engine/consolidation.ts +138 -45
  168. package/src/engine/eval.ts +102 -102
  169. package/src/engine/eviction.ts +101 -101
  170. package/src/engine/index.ts +8 -8
  171. package/src/engine/retraction.ts +366 -116
  172. package/src/engine/staging.ts +74 -74
  173. package/src/hooks/sidecar.ts +5 -5
  174. package/src/index.ts +226 -212
  175. package/src/mcp.ts +1145 -1121
  176. package/src/storage/factory.ts +147 -0
  177. package/src/storage/index.ts +3 -3
  178. package/src/storage/pglite-schema.ts +166 -0
  179. package/src/storage/pglite.ts +1363 -0
  180. package/src/storage/sqlite.ts +402 -7
  181. package/src/storage/store.ts +80 -0
  182. package/src/types/agent.ts +67 -67
  183. package/src/types/checkpoint.ts +46 -46
  184. package/src/types/engram.ts +101 -3
  185. package/src/types/eval.ts +100 -100
  186. package/src/types/index.ts +6 -6
@@ -1,411 +1,411 @@
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.
226
- 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
227
- 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
228
- the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
229
- than one filesystem search.
230
- 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
231
- 5. **Finishing a task**: call \`memory_task_end\` with a summary.
232
- 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
233
-
234
- ### Write memory when:
235
- - A project decision is made or changed
236
- - A root cause is discovered after debugging
237
- - A reusable implementation pattern is established
238
- - A user preference, constraint, or requirement is clarified
239
- - A prior assumption is found to be wrong
240
- - A significant piece of work is completed
241
-
242
- ### Writing for recall (the highest-leverage section)
243
- A memory's recall quality is set the moment you write it. AWM is fast at
244
- finding what's findable — but if the write is shaped wrong, no retriever
245
- can rescue it. Be slightly more verbose at the front than feels natural:
246
- the first 1-2 sentences are what BM25, the embedding model, and concept
247
- extraction all see most strongly.
248
-
249
- - **Lead with the rule or fact.** Don't open with context or backstory.
250
- "Don't mock the database in integration tests." comes first; the reason
251
- comes second. Recall scans the head of the body, not the tail.
252
- - **Pick the most specific topic.** Not \`auth\` — \`auth-magic-link-rate-limit\`.
253
- Topic is a hard filter at recall time. Generic topics hide the memory in
254
- a noisy bucket where it competes with everything else in the area.
255
- - **Include 2+ retrievable identifiers.** File paths, function names, table
256
- columns, ticket IDs, exact error strings, the literal terms a future query
257
- will use. \`AccountingService.closePeriod()\` beats "the accounting code."
258
- \`tblMemberDetails.activation_date\` beats "the activation column."
259
- \`schema/072-period-close.sql\` beats "the migration."
260
- - **Write in the vocabulary of the future question.** When you imagine asking
261
- this in three months, what nouns will you use? Use those nouns. Don't
262
- paraphrase the user's domain language into your own neutral summary.
263
- - **Reserve canonical for stable invariants.** Decisions, requirements,
264
- hard facts, cross-agent shared context. Working class (default) is correct
265
- for findings, observations, and progress notes. The canonical floor is
266
- 0.7 salience — overusing it pollutes the canonical layer and the floor
267
- loses meaning.
268
- - **Include the why for feedback memories.** A rule without a reason can't
269
- be applied to edge cases. "Don't mock the database" is brittle. "Don't
270
- mock the database — last quarter mocked tests masked a broken migration"
271
- is portable to new situations.
272
-
273
- ### Tagging rules (REQUIRED — AWM's prefix-tag retrieval boost depends on these)
274
-
275
- Every \`memory_write\` should pass these structured fields. AWM stores each as a
276
- prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
277
- and entity-bridge boosts at recall time.
278
-
279
- | Field | Required? | Format | Example |
280
- |---|---|---|---|
281
- | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
282
- | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
283
- | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
284
- | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
285
- | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
286
- | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
287
- | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
288
- | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
289
-
290
- **Always add identifier tags when present in the content:**
291
- - \`ticket=<id>\` for Freshdesk tickets
292
- - \`member=<id>\` for member IDs
293
- - \`horse=<id>\` for horse_member_id
294
- - \`usef=<id>\` for USEF lookups
295
- - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
296
- - \`person=<Name>\` for stakeholder quotes / decisions
297
- - \`version=<X.Y.Z>\` for release-specific findings
298
-
299
- ### Memory classes (controls how strictly the salience filter gates the write)
300
- - \`memory_class: canonical\` — source-of-truth memories. Floor 0.7 salience, never staged.
301
- Use for: user-stated decisions, project requirements, verified architectural facts,
302
- cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
303
- for writes that other agents must be able to recall** — the default \`working\` class
304
- may get filtered.
305
- - \`memory_class: working\` (default) — observations and findings. Salience-gated.
306
- - \`memory_class: ephemeral\` — short-lived context that should decay quickly.
307
-
308
- ### Salience auto-promotion (defense in depth)
309
- The salience filter automatically promotes certain content patterns even if you forget
310
- to set \`memory_class\` explicitly:
311
- - **User feedback** — content starting with "Robert said…", "Katherine directed…",
312
- "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
313
- always preserves the decision.
314
- - **Verified operational records** — content with an action verb (Submitted, Finalized,
315
- Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
316
- Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
317
- or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
318
- a 0.45 salience floor. So batch summaries with real IDs survive even when topic
319
- terms repeat.
320
-
321
- If neither pattern applies and you want a memory to definitely survive, set
322
- \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
323
-
324
- ### Recall memory when:
325
- - **BEFORE stating ANY fact about how a system works** — recall first; if AWM doesn't
326
- have it, read the code. Never guess and present it as fact.
327
- - **BEFORE searching the filesystem** — recall first; AWM is faster and has cross-session
328
- knowledge that file search doesn't.
329
- - Starting work on a new task or subsystem
330
- - Re-entering code you haven't touched recently
331
- - After a failed attempt — check if there's prior knowledge
332
- - Before refactoring or making architectural changes
333
- - When a topic comes up that you might have prior context on
334
-
335
- Recall is fast (~300ms typical). Use it freely.
336
-
337
- ### Recall strategy (when one query isn't enough)
338
- AWM's adaptive retrieval handles most query variations natively — synonym
339
- expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
340
- A single recall is usually enough.
341
-
342
- When it isn't:
343
- - **If the first recall returns nothing or returns the wrong things, reformulate.**
344
- Try a second query with different phrasing — synonyms, more specific nouns,
345
- the exact identifier from the code rather than the conceptual name. Two or
346
- three recalls cost less than one filesystem search.
347
- - **Use the words a domain expert would use, not generic English.** "Period
348
- close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
349
- - **For broad exploration, pass \`mode: "exploratory"\`** — wider candidate
350
- pool, lower precision floor. For specific lookups, leave mode unset (auto).
351
- - **Don't ensemble more than 3 reformulations.** If three different phrasings
352
- return nothing, the memory probably isn't there — read the code instead of
353
- burning more recalls.
354
-
355
- ### Keep memory fresh
356
- - After recalling a memory, if you observe the real state is different → call
357
- \`memory_supersede\` immediately with the corrected version.
358
- - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
359
- activation engine learns what's valuable.
360
- - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
361
- - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
362
- drifts out of date. The system relies on you to keep it current. This is the #1
363
- failure mode.**
364
-
365
- ### Example — good vs bad memory_write
366
-
367
- **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
368
- \`\`\`
369
- memory_write(
370
- concept="found a bug",
371
- content="The thing I was looking at was broken so I fixed it."
372
- )
373
- \`\`\`
374
-
375
- **GOOD** (rich identifiers, structured metadata, prefix tags):
376
- \`\`\`
377
- memory_write(
378
- concept="EquiHub period-close BLOCKED check missing server-side",
379
- 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.",
380
- project="EquiHub",
381
- topic="accounting",
382
- intent="finding",
383
- confidence_level="verified",
384
- source="debugging",
385
- memory_class="canonical",
386
- tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
387
- )
388
- \`\`\`
389
-
390
- ### Also:
391
- - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
392
- - AWM is shared across all agents in real time. When any agent writes or supersedes a
393
- memory, every other agent can recall it immediately.
394
-
395
- ### Diagnostics / escape hatches (env vars, only if you know why)
396
- The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. Each optimization
397
- is gated by an env-var so it can be disabled for A/B testing if a regression
398
- appears in your workload:
399
-
400
- - \`AWM_DISABLE_POOL_FILTER=1\` (0.7.7+) — disables the candidate pool reduction
401
- pre-filter in recall. Reverts to scoring all active candidates.
402
- - \`AWM_DISABLE_SLIM_CACHE=1\` (0.7.10+) — disables the in-memory slim cache.
403
- Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
404
- - \`AWM_DISABLE_RERANK_SKIP=1\` (0.7.10+) — disables the cross-encoder skip on
405
- clear-winner queries. Forces every recall through the reranker.
406
- - \`AWM_DISABLE_EXPANSION_CACHE=1\` (0.7.11+) — disables the query expansion
407
- skip heuristic + LRU cache. Forces every recall through flan-t5-small.
408
-
409
- In production, leave these all unset. Use only when diagnosing a suspected
410
- recall-quality regression.
411
- `.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
+ 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.
226
+ 2. **Starting a task**: call \`memory_task_begin\` (checkpoints + recalls relevant memories).
227
+ 3. **During work**: call \`memory_recall\` BEFORE stating any fact, BEFORE searching
228
+ the filesystem, BEFORE making architectural decisions. Recall is ~300ms — cheaper
229
+ than one filesystem search.
230
+ 4. **As you learn things**: call \`memory_write\` proactively. Don't batch.
231
+ 5. **Finishing a task**: call \`memory_task_end\` with a summary.
232
+ 6. **Auto-checkpoint** is handled by hooks (compaction, session-end, 15-min timer). No action needed.
233
+
234
+ ### Write memory when:
235
+ - A project decision is made or changed
236
+ - A root cause is discovered after debugging
237
+ - A reusable implementation pattern is established
238
+ - A user preference, constraint, or requirement is clarified
239
+ - A prior assumption is found to be wrong
240
+ - A significant piece of work is completed
241
+
242
+ ### Writing for recall (the highest-leverage section)
243
+ A memory's recall quality is set the moment you write it. AWM is fast at
244
+ finding what's findable — but if the write is shaped wrong, no retriever
245
+ can rescue it. Be slightly more verbose at the front than feels natural:
246
+ the first 1-2 sentences are what BM25, the embedding model, and concept
247
+ extraction all see most strongly.
248
+
249
+ - **Lead with the rule or fact.** Don't open with context or backstory.
250
+ "Don't mock the database in integration tests." comes first; the reason
251
+ comes second. Recall scans the head of the body, not the tail.
252
+ - **Pick the most specific topic.** Not \`auth\` — \`auth-magic-link-rate-limit\`.
253
+ Topic is a hard filter at recall time. Generic topics hide the memory in
254
+ a noisy bucket where it competes with everything else in the area.
255
+ - **Include 2+ retrievable identifiers.** File paths, function names, table
256
+ columns, ticket IDs, exact error strings, the literal terms a future query
257
+ will use. \`AccountingService.closePeriod()\` beats "the accounting code."
258
+ \`tblMemberDetails.activation_date\` beats "the activation column."
259
+ \`schema/072-period-close.sql\` beats "the migration."
260
+ - **Write in the vocabulary of the future question.** When you imagine asking
261
+ this in three months, what nouns will you use? Use those nouns. Don't
262
+ paraphrase the user's domain language into your own neutral summary.
263
+ - **Reserve canonical for stable invariants.** Decisions, requirements,
264
+ hard facts, cross-agent shared context. Working class (default) is correct
265
+ for findings, observations, and progress notes. The canonical floor is
266
+ 0.7 salience — overusing it pollutes the canonical layer and the floor
267
+ loses meaning.
268
+ - **Include the why for feedback memories.** A rule without a reason can't
269
+ be applied to edge cases. "Don't mock the database" is brittle. "Don't
270
+ mock the database — last quarter mocked tests masked a broken migration"
271
+ is portable to new situations.
272
+
273
+ ### Tagging rules (REQUIRED — AWM's prefix-tag retrieval boost depends on these)
274
+
275
+ Every \`memory_write\` should pass these structured fields. AWM stores each as a
276
+ prefix-tag like \`proj=\`, \`topic=\`, \`intent=\`, etc. and uses them for BM25
277
+ and entity-bridge boosts at recall time.
278
+
279
+ | Field | Required? | Format | Example |
280
+ |---|---|---|---|
281
+ | \`project\` | **YES** | one short word matching the current project | \`"EquiHub"\`, \`"AWM"\`, \`"USEA-Agent"\` |
282
+ | \`topic\` | **YES** | one or more lowercase area words | \`"database-migration"\`, \`"benchmarks"\` |
283
+ | \`intent\` | **YES** | one of: \`decision\` / \`finding\` / \`todo\` / \`question\` / \`context\` | \`"finding"\` |
284
+ | \`confidence_level\` | **YES** | \`verified\` (tested) / \`observed\` (read in code) / \`assumed\` (reasoning) | \`"verified"\` |
285
+ | \`source\` | recommended | \`code-reading\` / \`debugging\` / \`discussion\` / \`research\` / \`testing\` / \`observation\` | \`"testing"\` |
286
+ | \`memory_class\` | when stable | \`canonical\` (source-of-truth, 0.7 floor, never staged) / \`working\` (default) / \`ephemeral\` | \`"canonical"\` |
287
+ | \`session_id\` | recommended | current conversation ID for entity-bridge boost | autogenerated |
288
+ | \`tags\` | when applicable | extra prefix-tags for IDs and dates | \`["ticket=18360", "date=2026-05-11"]\` |
289
+
290
+ **Always add identifier tags when present in the content:**
291
+ - \`ticket=<id>\` for Freshdesk tickets
292
+ - \`member=<id>\` for member IDs
293
+ - \`horse=<id>\` for horse_member_id
294
+ - \`usef=<id>\` for USEF lookups
295
+ - \`date=YYYY-MM-DD\` for temporal anchoring (ISO format)
296
+ - \`person=<Name>\` for stakeholder quotes / decisions
297
+ - \`version=<X.Y.Z>\` for release-specific findings
298
+
299
+ ### Memory classes (controls how strictly the salience filter gates the write)
300
+ - \`memory_class: canonical\` — source-of-truth memories. Floor 0.7 salience, never staged.
301
+ Use for: user-stated decisions, project requirements, verified architectural facts,
302
+ cross-agent shared context. **In a hive (multi-agent) setup, always use \`canonical\`
303
+ for writes that other agents must be able to recall** — the default \`working\` class
304
+ may get filtered.
305
+ - \`memory_class: working\` (default) — observations and findings. Salience-gated.
306
+ - \`memory_class: ephemeral\` — short-lived context that should decay quickly.
307
+
308
+ ### Salience auto-promotion (defense in depth)
309
+ The salience filter automatically promotes certain content patterns even if you forget
310
+ to set \`memory_class\` explicitly:
311
+ - **User feedback** — content starting with "Robert said…", "Katherine directed…",
312
+ "Nancy decided…" etc. auto-promotes to canonical. So quoting the user verbatim
313
+ always preserves the decision.
314
+ - **Verified operational records** — content with an action verb (Submitted, Finalized,
315
+ Completed, Reconciled, Triaged, Posted, Resolved, Stamped, Pushed, Deployed, Migrated,
316
+ Imported, Exported, Backfilled) plus 2+ concrete identifiers (ISO date \`YYYY-MM-DD\`,
317
+ or contextual numeric IDs like "event 18969", "ticket #18330", "USEF 341980") gets
318
+ a 0.45 salience floor. So batch summaries with real IDs survive even when topic
319
+ terms repeat.
320
+
321
+ If neither pattern applies and you want a memory to definitely survive, set
322
+ \`memory_class: canonical\` explicitly. Don't rely on auto-promotion for important writes.
323
+
324
+ ### Recall memory when:
325
+ - **BEFORE stating ANY fact about how a system works** — recall first; if AWM doesn't
326
+ have it, read the code. Never guess and present it as fact.
327
+ - **BEFORE searching the filesystem** — recall first; AWM is faster and has cross-session
328
+ knowledge that file search doesn't.
329
+ - Starting work on a new task or subsystem
330
+ - Re-entering code you haven't touched recently
331
+ - After a failed attempt — check if there's prior knowledge
332
+ - Before refactoring or making architectural changes
333
+ - When a topic comes up that you might have prior context on
334
+
335
+ Recall is fast (~300ms typical). Use it freely.
336
+
337
+ ### Recall strategy (when one query isn't enough)
338
+ AWM's adaptive retrieval handles most query variations natively — synonym
339
+ expansion, multi-channel scoring, embedding + BM25 + reranker agreement.
340
+ A single recall is usually enough.
341
+
342
+ When it isn't:
343
+ - **If the first recall returns nothing or returns the wrong things, reformulate.**
344
+ Try a second query with different phrasing — synonyms, more specific nouns,
345
+ the exact identifier from the code rather than the conceptual name. Two or
346
+ three recalls cost less than one filesystem search.
347
+ - **Use the words a domain expert would use, not generic English.** "Period
348
+ close lock" not "accounting feature"; "magic link rate limit" not "auth issue."
349
+ - **For broad exploration, pass \`mode: "exploratory"\`** — wider candidate
350
+ pool, lower precision floor. For specific lookups, leave mode unset (auto).
351
+ - **Don't ensemble more than 3 reformulations.** If three different phrasings
352
+ return nothing, the memory probably isn't there — read the code instead of
353
+ burning more recalls.
354
+
355
+ ### Keep memory fresh
356
+ - After recalling a memory, if you observe the real state is different → call
357
+ \`memory_supersede\` immediately with the corrected version.
358
+ - After using a recalled memory: call \`memory_feedback\` (useful/not-useful) so the
359
+ activation engine learns what's valuable.
360
+ - If you discover a memory is factually wrong: \`memory_retract\` to remove it.
361
+ - **If you bypass AWM (file-memory, in-context notes, "I'll just remember"), the memory
362
+ drifts out of date. The system relies on you to keep it current. This is the #1
363
+ failure mode.**
364
+
365
+ ### Example — good vs bad memory_write
366
+
367
+ **BAD** (no prefix tags, vague concept, can't be recalled by future queries):
368
+ \`\`\`
369
+ memory_write(
370
+ concept="found a bug",
371
+ content="The thing I was looking at was broken so I fixed it."
372
+ )
373
+ \`\`\`
374
+
375
+ **GOOD** (rich identifiers, structured metadata, prefix tags):
376
+ \`\`\`
377
+ memory_write(
378
+ concept="EquiHub period-close BLOCKED check missing server-side",
379
+ 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.",
380
+ project="EquiHub",
381
+ topic="accounting",
382
+ intent="finding",
383
+ confidence_level="verified",
384
+ source="debugging",
385
+ memory_class="canonical",
386
+ tags=["ticket=18360", "person=Robert", "date=2026-05-11", "topic=period-close", "topic=security"]
387
+ )
388
+ \`\`\`
389
+
390
+ ### Also:
391
+ - To track work items: memory_task_add, memory_task_update, memory_task_list, memory_task_next
392
+ - AWM is shared across all agents in real time. When any agent writes or supersedes a
393
+ memory, every other agent can recall it immediately.
394
+
395
+ ### Diagnostics / escape hatches (env vars, only if you know why)
396
+ The 0.7.6→0.7.14 work cut recall latency from 11s to ~300ms. Each optimization
397
+ is gated by an env-var so it can be disabled for A/B testing if a regression
398
+ appears in your workload:
399
+
400
+ - \`AWM_DISABLE_POOL_FILTER=1\` (0.7.7+) — disables the candidate pool reduction
401
+ pre-filter in recall. Reverts to scoring all active candidates.
402
+ - \`AWM_DISABLE_SLIM_CACHE=1\` (0.7.10+) — disables the in-memory slim cache.
403
+ Reverts to per-recall SQL fetch + Buffer→Float32Array conversion.
404
+ - \`AWM_DISABLE_RERANK_SKIP=1\` (0.7.10+) — disables the cross-encoder skip on
405
+ clear-winner queries. Forces every recall through the reranker.
406
+ - \`AWM_DISABLE_EXPANSION_CACHE=1\` (0.7.11+) — disables the query expansion
407
+ skip heuristic + LRU cache. Forces every recall through flan-t5-small.
408
+
409
+ In production, leave these all unset. Use only when diagnosing a suspected
410
+ recall-quality regression.
411
+ `.trimStart();