humemory 0.2.7 → 0.2.8

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 (94) hide show
  1. package/AGENTS.md +8 -4
  2. package/CHANGELOG.md +6 -0
  3. package/README.md +22 -10
  4. package/dist/agent/kimi-import.d.ts +19 -0
  5. package/dist/agent/kimi-import.js +111 -0
  6. package/dist/agent/kimi-session-parser.d.ts +3 -0
  7. package/dist/agent/kimi-session-parser.js +102 -0
  8. package/dist/agent/maintenance-queue.d.ts +2 -0
  9. package/dist/agent/maintenance-queue.js +36 -61
  10. package/dist/agent/maintenance-runner.d.ts +17 -4
  11. package/dist/agent/maintenance-runner.js +45 -10
  12. package/dist/agent/mcp-client-setup.d.ts +16 -0
  13. package/dist/agent/mcp-client-setup.js +108 -0
  14. package/dist/agent/opencode-import.d.ts +22 -0
  15. package/dist/agent/opencode-import.js +71 -0
  16. package/dist/agent/opencode-session-parser.d.ts +3 -0
  17. package/dist/agent/opencode-session-parser.js +35 -0
  18. package/dist/agent/session-parser.d.ts +8 -0
  19. package/dist/agent/session-parser.js +18 -0
  20. package/dist/agent/source-registry.js +1 -1
  21. package/dist/api/server.js +3 -2
  22. package/dist/cli/index.js +96 -4
  23. package/dist/core/cues.d.ts +1 -0
  24. package/dist/core/cues.js +19 -7
  25. package/dist/core/embeddings.d.ts +0 -10
  26. package/dist/core/embeddings.js +2 -1
  27. package/dist/core/llm-generator.d.ts +2 -10
  28. package/dist/core/paths.d.ts +5 -0
  29. package/dist/core/paths.js +27 -0
  30. package/dist/core/project-path.d.ts +3 -0
  31. package/dist/core/project-path.js +14 -0
  32. package/dist/core/search.d.ts +1 -1
  33. package/dist/core/search.js +7 -9
  34. package/dist/core/types.d.ts +13 -1
  35. package/dist/index.d.ts +5 -0
  36. package/dist/index.js +5 -0
  37. package/dist/store/sqlite.d.ts +37 -0
  38. package/dist/store/sqlite.js +94 -42
  39. package/package.json +4 -3
  40. package/public/app/{index-95ffty7j.js → index-n2qg9hyr.js} +6 -6
  41. package/public/app/index.html +1 -1
  42. package/scripts/consolidate.js +4 -4
  43. package/scripts/hook-post-commit.ts +2 -1
  44. package/scripts/hook-session-start.ts +2 -1
  45. package/scripts/hook-session.ts +2 -1
  46. package/src/agent/claude-hook.ts +126 -0
  47. package/src/agent/codex-import.ts +129 -0
  48. package/src/agent/codex-rollout-parser.ts +121 -0
  49. package/src/agent/commit-closer.ts +173 -0
  50. package/src/agent/kimi-import.ts +128 -0
  51. package/src/agent/kimi-session-parser.ts +127 -0
  52. package/src/agent/learning-extractor.ts +128 -0
  53. package/src/agent/maintenance-queue.ts +546 -0
  54. package/src/agent/maintenance-runner.ts +322 -0
  55. package/src/agent/maintenance-state.ts +168 -0
  56. package/src/agent/mcp-client-setup.ts +125 -0
  57. package/src/agent/opencode-import.ts +96 -0
  58. package/src/agent/opencode-session-parser.ts +53 -0
  59. package/src/agent/session-context.ts +302 -0
  60. package/src/agent/session-parser.ts +155 -0
  61. package/src/agent/source-registry.ts +135 -0
  62. package/src/api/cors.ts +42 -0
  63. package/src/api/dream-routes.ts +46 -0
  64. package/src/api/errors.ts +45 -0
  65. package/src/api/intentions-routes.ts +348 -0
  66. package/src/api/limits.ts +90 -0
  67. package/src/api/maintenance-routes.ts +73 -0
  68. package/src/api/memory-routes.ts +391 -0
  69. package/src/api/scripts-routes.ts +176 -0
  70. package/src/api/security-headers.ts +54 -0
  71. package/src/api/server.ts +292 -0
  72. package/src/cli/index.ts +1175 -0
  73. package/src/core/clock.ts +64 -0
  74. package/src/core/cue-arg.ts +79 -0
  75. package/src/core/cues.ts +511 -0
  76. package/src/core/decay.ts +198 -0
  77. package/src/core/dreamer.ts +494 -0
  78. package/src/core/embeddings.ts +157 -0
  79. package/src/core/event-bus.ts +100 -0
  80. package/src/core/hybrid.ts +78 -0
  81. package/src/core/llm-cli-client.ts +118 -0
  82. package/src/core/llm-generator.ts +90 -0
  83. package/src/core/paths.ts +28 -0
  84. package/src/core/project-path.ts +14 -0
  85. package/src/core/sanitize.ts +116 -0
  86. package/src/core/scripts.ts +112 -0
  87. package/src/core/search.ts +189 -0
  88. package/src/core/trust.ts +67 -0
  89. package/src/core/types.ts +393 -0
  90. package/src/core/vector-clusterer.ts +131 -0
  91. package/src/index.ts +40 -0
  92. package/src/mcp/HTTP_TRANSPORT.md +359 -0
  93. package/src/mcp/server.ts +202 -0
  94. package/src/store/sqlite.ts +1958 -0
@@ -0,0 +1,1175 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { databasePath, queueDirectory } from '../core/paths.js';
4
+ import { SQLiteStore } from '../store/sqlite.js';
5
+ import { calculateDecayLevel } from '../core/decay.js';
6
+ import { SqliteCueResolver, loopId, matchIntentionByShortId } from '../core/cues.js';
7
+ import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
8
+ import type { IntentionStatus, TriggerSpec } from '../core/types.js';
9
+ import { join, dirname, resolve } from 'path';
10
+ import { fileURLToPath } from 'url';
11
+ import { readFileSync } from 'fs';
12
+ import { discoverLocalAgentSources } from '../agent/source-registry.js';
13
+
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = dirname(__filename);
16
+
17
+ // Shared store. HUMEMORY_DB points at another database — same convention as the
18
+ // hooks, and required to exercise the CLI without touching production.
19
+ const DB_PATH = databasePath();
20
+ // Same inbox the agent hooks write to — the CLI only ever queues, never encodes.
21
+ const QUEUE_DIR = queueDirectory();
22
+ let store: SQLiteStore;
23
+
24
+ function getStore(): SQLiteStore {
25
+ if (!store) {
26
+ store = new SQLiteStore(DB_PATH);
27
+ }
28
+ return store;
29
+ }
30
+
31
+ const program = new Command();
32
+
33
+ // Version read from the package: hard-coded, it drifted at every release.
34
+ const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8')) as {
35
+ version: string;
36
+ };
37
+
38
+ program
39
+ .name('humemory')
40
+ .description('Memory palace — mnemonic traces with progressive decay')
41
+ .version(version);
42
+
43
+ // === ADD ===
44
+ program
45
+ .command('encode <content>')
46
+ .alias('add')
47
+ .description('Encode a new mnemonic trace')
48
+ .option('-d, --directory <dir>', 'Mental place (project)', process.cwd())
49
+ .option('-s, --session <id>', 'Contexte d\'encodage', 'default')
50
+ .option('-k, --keywords <tags>', 'Retrieval cues (comma-separated)', '')
51
+ .option('-l1, --level1 <summary>', 'Summary for consolidation level 1')
52
+ .option('-l2, --level2 <essential>', 'Gist for consolidation level 2')
53
+ .option('-l3, --level3 <keywords>', 'Keywords for fast level 3 retrieval')
54
+ .option('-t, --type <type>', 'Memory type (episodic/semantic/procedural)', 'semantic')
55
+ .option('--auto', 'Auto-generate levels 1-3 locally (an injected LLM may enhance them)')
56
+ .option('--photographic', 'Photographic mode — disable decay')
57
+ .option('--agent <name>', 'Who is encoding (claude/codex/kimi/…)', 'cli')
58
+ .action(async (content, options) => {
59
+ const s = getStore();
60
+
61
+ const validTypes = ['episodic', 'semantic', 'procedural'];
62
+ const memoryType = validTypes.includes(options.type) ? options.type : 'semantic';
63
+
64
+ if (options.auto) {
65
+ console.log('⏳ Generating consolidation levels through the LLM…');
66
+ }
67
+
68
+ const memory = await s.add({
69
+ content,
70
+ // Resolved to absolute, as for intentions: the SessionStart hook filters by
71
+ // `process.cwd()`, and a relative path would never match.
72
+ directory: resolve(options.directory),
73
+ day: new Date().toISOString().split('T')[0],
74
+ keywords: options.keywords ? options.keywords.split(',').map((k: string) => k.trim()).filter(Boolean) : [],
75
+ sessionId: options.session,
76
+ level1Summary: options.level1,
77
+ level2Essential: options.level2,
78
+ level3Keywords: options.level3,
79
+ memoryType: memoryType as 'episodic' | 'semantic' | 'procedural',
80
+ photographic: options.photographic ?? false,
81
+ agent: options.agent,
82
+ }, { autoGenerate: options.auto });
83
+
84
+ const typeLabels = { episodic: 'Episodic', semantic: 'Semantic', procedural: 'Procedural' };
85
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
86
+ console.log(`✓ Trace encoded: ${memory.id}`);
87
+ console.log(` Type: ${typeLabels[memory.memoryType]}`);
88
+ console.log(` State: ${states[memory.currentLevel]}`);
89
+ console.log(` Mnemonic strength: ${memory.saillance}/100`);
90
+ });
91
+
92
+ // === SEARCH ===
93
+ program
94
+ .command('search <query>')
95
+ .alias('find')
96
+ .description('Search by retrieval cues (inverse search)')
97
+ .option('-d, --directory <dir>', 'Filter by mental place')
98
+ .option('-s, --session <id>', 'Filter by context')
99
+ .option('-l, --level <max>', 'Maximum consolidation state (0-4)', '4')
100
+ .option('-n, --limit <n>', 'Number of traces', '10')
101
+ .option('-t, --type <type>', 'Filter by type (episodic/semantic/procedural)')
102
+ .option('--from <date>', 'Start date YYYY-MM-DD')
103
+ .option('--to <date>', 'End date YYYY-MM-DD')
104
+ .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
105
+ .option('--min-recalls <n>', 'Minimum recall count')
106
+ .option('--semantic', 'Hybrid search: fuse BM25 with vector similarity (Phase 7.4, needs the model)')
107
+ .action(async (query, options) => {
108
+ const s = getStore();
109
+
110
+ let results;
111
+ if (options.semantic) {
112
+ const { OnnxEmbedder } = await import('../core/embeddings.js');
113
+ const { hybridSearch } = await import('../core/hybrid.js');
114
+ const embedder = new OnnxEmbedder();
115
+ results = await hybridSearch(s, embedder, query, {
116
+ directory: options.directory ? resolve(options.directory) : undefined,
117
+ limit: parseInt(options.limit),
118
+ });
119
+ } else {
120
+ results = await s.search({
121
+ query,
122
+ directory: options.directory ? resolve(options.directory) : undefined,
123
+ sessionId: options.session,
124
+ maxLevel: parseInt(options.level) as 0 | 1 | 2 | 3 | 4,
125
+ limit: parseInt(options.limit),
126
+ memoryType: options.type as any,
127
+ dateFrom: options.from ? new Date(options.from) : undefined,
128
+ dateTo: options.to ? new Date(options.to) : undefined,
129
+ minSaillance: options.minSaillance ? parseInt(options.minSaillance) : undefined,
130
+ minRecalls: options.minRecalls ? parseInt(options.minRecalls) : undefined,
131
+ });
132
+ }
133
+
134
+ if (results.length === 0) {
135
+ console.log('No trace found.');
136
+ return;
137
+ }
138
+
139
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
140
+ console.log(`\n🧠 ${results.length} trace(s) found:\n`);
141
+
142
+ for (const result of results) {
143
+ console.log(`🔍 [${states[result.matchLevel]}] Score: ${Math.round(result.score)}`);
144
+ console.log(` ID: ${result.memory.id}`);
145
+ console.log(` Place: ${result.memory.directory}`);
146
+ console.log(` Context: ${result.memory.sessionId}`);
147
+ console.log(` Encoded: ${new Date(result.memory.createdAt).toLocaleDateString()}`);
148
+ console.log(` Recalls: ${result.memory.recallCount}`);
149
+
150
+ // Show the content at the level where the match happened
151
+ let displayContent = result.memory.content;
152
+ if (result.matchLevel === 4 && result.memory.level3Keywords) {
153
+ displayContent = `Trace: ${result.memory.level3Keywords}`;
154
+ } else if (result.matchLevel === 3 && result.memory.level3Keywords) {
155
+ displayContent = `Keywords: ${result.memory.level3Keywords}`;
156
+ } else if (result.matchLevel === 2 && result.memory.level2Essential) {
157
+ displayContent = result.memory.level2Essential;
158
+ } else if (result.matchLevel === 1 && result.memory.level1Summary) {
159
+ displayContent = result.memory.level1Summary;
160
+ }
161
+
162
+ console.log(` Content: ${displayContent.slice(0, 200)}${displayContent.length > 200 ? '...' : ''}`);
163
+ console.log();
164
+ }
165
+ });
166
+
167
+ // === RECALL ===
168
+ program
169
+ .command('recall <id>')
170
+ .alias('reactivate')
171
+ .description('Recall a trace (mnemonic reinforcement)')
172
+ .option('--agent <name>', 'Who is recalling (earns `reused` verification across agents)')
173
+ .action(async (id, options) => {
174
+ const s = getStore();
175
+
176
+ // A human at a terminal chose this `--agent`; that is a process-level
177
+ // identity, not a request claiming one. It may earn `reused`.
178
+ const memory = await s.recall(id, options.agent, { identityTrusted: true });
179
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
180
+ console.log(`✓ Trace recalled: ${memory.id}`);
181
+ console.log(` Total recalls: ${memory.recallCount}`);
182
+ console.log(` Mnemonic strength: ${memory.saillance}/100`);
183
+ console.log(` State: ${states[memory.currentLevel]}`);
184
+ if (memory.verified && memory.verificationReason === 'reused') {
185
+ console.log(` Verified: earned by cross-agent reuse ✓`);
186
+ }
187
+ });
188
+
189
+ // === VERIFY / REFUTE (Phase 6.0.1) ===
190
+ program
191
+ .command('verify <id>')
192
+ .description('Mark a trace as human-verified (prints content first — no blind stamp)')
193
+ .action(async (id) => {
194
+ const s = getStore();
195
+
196
+ const memory = await s.getById(id);
197
+ if (!memory) {
198
+ console.error(`✗ Trace ${id} not found`);
199
+ process.exit(1);
200
+ }
201
+ // Trust-theatre guard (PHASE6_PLAN risks): the human must actually read
202
+ // the trace before stamping it — verify prints the content, always.
203
+ console.log(`\n🧠 ${memory.id}\n\n${memory.content}\n`);
204
+ const updated = await s.verify(id, 'human');
205
+ console.log(`✓ Trace verified (reason: human). Trust will reflect it.`);
206
+ void updated;
207
+ });
208
+
209
+ program
210
+ .command('refute <id>')
211
+ .description('Record a negative signal against a trace (refuted_count +1, verification revoked)')
212
+ .option('-r, --reason <text>', 'Why the trace does not hold')
213
+ .action(async (id, options) => {
214
+ const s = getStore();
215
+
216
+ const memory = await s.refute(id, options.reason);
217
+ console.log(`✓ Trace refuted: ${memory.id}`);
218
+ console.log(` Refuted count: ${memory.refutedCount}`);
219
+ console.log(` Verification: revoked (must be re-earned)`);
220
+ });
221
+
222
+ // === CONTRADICT (Phase 6.0.2) ===
223
+ program
224
+ .command('contradict <winnerId> <loserId>')
225
+ .description('Winner trace contradicts loser trace or script — trace collapses, script archives (never deleted)')
226
+ .option('-r, --reason <text>', 'Why the loser no longer holds')
227
+ .option('--agent <name>', 'Who files the contradiction', 'cli')
228
+ .action(async (winnerId, loserId, options) => {
229
+ const s = getStore();
230
+
231
+ const result = await s.contradict!(winnerId, loserId, {
232
+ reason: options.reason,
233
+ createdBy: options.agent === 'cli' ? 'human' : 'agent',
234
+ agent: options.agent,
235
+ });
236
+ if (result.proposalFiled) {
237
+ console.log(`⏳ Loser is human/grounded-verified — contradiction filed as a dream proposal for review.`);
238
+ return;
239
+ }
240
+ if (result.retargetedTo) {
241
+ console.log(`⚠ Loser was already merged — the collapse hit the merge target ${result.retargetedTo.slice(0, 8)}…`);
242
+ }
243
+ console.log(`✓ Contradiction recorded: ${result.contradiction!.id}`);
244
+ if ('status' in result.loser) {
245
+ // Script loser (8.4): archived outright, not saillance-collapsed.
246
+ console.log(` Script "${result.loser.name}" archived (status: ${result.loser.status}) — cues cancelled.`);
247
+ } else {
248
+ console.log(` Loser saillance: ${result.loser.saillance}/100 (collapsed, still searchable)`);
249
+ }
250
+ });
251
+
252
+ // === LIST ===
253
+ program
254
+ .command('list')
255
+ .alias('traces')
256
+ .description('List mnemonic traces')
257
+ .option('-n, --limit <n>', 'Number of traces', '20')
258
+ .option('-l, --level <level>', 'Filter by state (0-4)')
259
+ .option('-t, --type <type>', 'Filter by type (episodic/semantic/procedural)')
260
+ .action(async (options) => {
261
+ const s = getStore();
262
+
263
+ const memories = await s.list({
264
+ limit: parseInt(options.limit),
265
+ level: options.level !== undefined ? parseInt(options.level) as any : undefined,
266
+ type: options.type as 'episodic' | 'semantic' | 'procedural' | undefined,
267
+ });
268
+
269
+ if (memories.length === 0) {
270
+ console.log('No trace.');
271
+ return;
272
+ }
273
+
274
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
275
+ console.log(`\n📋 ${memories.length} trace(s):\n`);
276
+
277
+ for (const m of memories) {
278
+ console.log(`🧠 ${m.id.slice(0, 8)}... | ${states[m.currentLevel]} | ${m.directory}`);
279
+ console.log(` ${m.content.slice(0, 100)}${m.content.length > 100 ? '...' : ''}`);
280
+ console.log(` Recalls: ${m.recallCount} | Strength: ${m.saillance}`);
281
+ console.log();
282
+ }
283
+ });
284
+
285
+ // === DECAY ===
286
+ program
287
+ .command('decay')
288
+ .alias('consolidate')
289
+ .description('Update consolidation for every trace')
290
+ .action(async () => {
291
+ const s = getStore();
292
+
293
+ await s.updateDecay();
294
+ console.log('✓ Consolidation updated');
295
+
296
+ // Phase 8.4 — drills rust from disuse; rusted ones archive themselves.
297
+ const { sweepDisusedScripts } = await import('../core/scripts.js');
298
+ const disuse = await sweepDisusedScripts(s);
299
+ if (disuse.archived.length || disuse.decaying.length) {
300
+ for (const { script, effective } of disuse.decaying) {
301
+ console.log(` 🥀 ${script.name} — disuse saillance ${effective} (stored ${script.saillance})`);
302
+ }
303
+ for (const script of disuse.archived) {
304
+ console.log(` 🗄️ ${script.name} — archived by disuse (cues cancelled, notice filed for \`dream review\`)`);
305
+ }
306
+ }
307
+
308
+ // Print a summary
309
+ const all = await s.list({ limit: 1000 });
310
+ const byLevel = [0, 0, 0, 0, 0];
311
+ for (const m of all) {
312
+ byLevel[m.currentLevel]++;
313
+ }
314
+
315
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
316
+ console.log('\nDistribution:');
317
+ console.log(` 🟢 ${states[0]}: ${byLevel[0]}`);
318
+ console.log(` 🟡 ${states[1]}: ${byLevel[1]}`);
319
+ console.log(` 🟠 ${states[2]}: ${byLevel[2]}`);
320
+ console.log(` 🔴 ${states[3]}: ${byLevel[3]}`);
321
+ console.log(` ⚫ ${states[4]}: ${byLevel[4]}`);
322
+ });
323
+
324
+ // === PHOTOGRAPHIC ===
325
+ program
326
+ .command('photo <id>')
327
+ .description('Toggle photographic mode (disables decay)')
328
+ .option('--off', 'Turn photographic mode off')
329
+ .action(async (id, options) => {
330
+ const s = getStore();
331
+ const memory = await s.setPhotographic(id, !options.off);
332
+ console.log(`✓ Photographic mode: ${memory.photographic ? '🔒 ON' : '🔓 off'}`);
333
+ console.log(` ID: ${memory.id}`);
334
+ });
335
+
336
+ // === SIMILAR ===
337
+ program
338
+ .command('similar <id>')
339
+ .description('Find similar traces to merge')
340
+ .option('-n, --limit <n>', 'Number of results', '5')
341
+ .option('-t, --threshold <n>', 'Score minimum (0-100)', '50')
342
+ .action(async (id, options) => {
343
+ const s = getStore();
344
+ const results = await s.findSimilar(id, {
345
+ limit: parseInt(options.limit),
346
+ threshold: parseInt(options.threshold),
347
+ });
348
+
349
+ if (results.length === 0) {
350
+ console.log('No similar trace found.');
351
+ return;
352
+ }
353
+
354
+ console.log(`\n🔍 ${results.length} trace(s) similaire(s):\n`);
355
+ for (const r of results) {
356
+ console.log(` ID: ${r.memory.id}`);
357
+ console.log(` Score: ${Math.round(r.score)} | Lieu: ${r.memory.directory}`);
358
+ console.log(` ${r.memory.content.slice(0, 120)}...`);
359
+ console.log();
360
+ }
361
+ });
362
+
363
+ // === MERGE ===
364
+ program
365
+ .command('merge <sourceId> <targetId>')
366
+ .description('Fusionner deux traces (source → target, source passe en niveau 4)')
367
+ .option('--auto', 'Fusionner le contenu via LLM')
368
+ .action(async (sourceId, targetId, options) => {
369
+ const s = getStore();
370
+
371
+ if (options.auto) {
372
+ console.log('⏳ Fusion via LLM...');
373
+ }
374
+
375
+ const result = await s.merge(sourceId, targetId, { autoMergeContent: options.auto });
376
+
377
+ console.log(`✓ Merge done`);
378
+ console.log(` Source ${sourceId.slice(0, 8)}… → level 4 (merged)`);
379
+ console.log(` Target ${targetId.slice(0, 8)}… absorbed it`);
380
+ if (result.mergedContent) {
381
+ console.log(` Merged content: ${result.mergedContent.slice(0, 150)}…`);
382
+ }
383
+ });
384
+
385
+ // === UNMERGE (Phase 6.0.4) ===
386
+ program
387
+ .command('unmerge <sourceId>')
388
+ .description('Revert a merge: resurrect the source trace, restore the target\u2019s revised levels')
389
+ .action(async (sourceId) => {
390
+ const s = getStore();
391
+
392
+ const result = await s.unmerge!(sourceId);
393
+ console.log(`✓ Unmerge done`);
394
+ console.log(` Source ${result.source.id.slice(0, 8)}… resurrected at level ${result.source.currentLevel}`);
395
+ console.log(` Target ${result.target.id.slice(0, 8)}… levels restored from the last revision`);
396
+ });
397
+
398
+ // === DELETE ===
399
+ program
400
+ .command('delete <id>')
401
+ .alias('forget')
402
+ .description('Forget a mnemonic trace')
403
+ .action(async (id) => {
404
+ const s = getStore();
405
+ await s.delete(id);
406
+ console.log(`✓ Trace forgotten: ${id}`);
407
+ });
408
+
409
+ // === STATUS ===
410
+ program
411
+ .command('status')
412
+ .description('Show the state of the memory palace')
413
+ .action(async () => {
414
+ const s = getStore();
415
+ const all = await s.list({ limit: 1000 });
416
+
417
+ console.log('\n🧠 État de humemory:\n');
418
+ console.log(`Total traces: ${all.length}`);
419
+
420
+ const byLevel = [0, 0, 0, 0, 0];
421
+ for (const m of all) {
422
+ byLevel[m.currentLevel]++;
423
+ }
424
+
425
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
426
+ console.log('\nBy consolidation state:');
427
+ console.log(` 🟢 ${states[0]}: ${byLevel[0]}`);
428
+ console.log(` 🟡 ${states[1]}: ${byLevel[1]}`);
429
+ console.log(` 🟠 ${states[2]}: ${byLevel[2]}`);
430
+ console.log(` 🔴 ${states[3]}: ${byLevel[3]}`);
431
+ console.log(` ⚫ ${states[4]}: ${byLevel[4]}`);
432
+
433
+ const avgSaillance = all.reduce((sum, m) => sum + m.saillance, 0) / (all.length || 1);
434
+ const avgRecalls = all.reduce((sum, m) => sum + m.recallCount, 0) / (all.length || 1);
435
+
436
+ console.log(`\nMoyennes:`);
437
+ console.log(` Mnemonic strength: ${Math.round(avgSaillance)}/100`);
438
+ console.log(` Recalls per trace: ${avgRecalls.toFixed(1)}`);
439
+ });
440
+
441
+ // === IMPORT SESSION ===
442
+ program
443
+ .command('import-session <file>')
444
+ .description('Importer une session Claude Code et extraire les apprentissages')
445
+ .option('-d, --directory <dir>', 'Lieu mental du projet', process.cwd())
446
+ .option('-n, --max <n>', 'Maximum learnings to extract', '5')
447
+ .action(async (file, options) => {
448
+ const { readFileSync } = await import('fs');
449
+ const { processSession } = await import('../agent/claude-hook.js');
450
+
451
+ const raw = readFileSync(file, 'utf-8');
452
+ console.log('⏳ Analyse de la session et extraction des apprentissages...');
453
+
454
+ const result = await processSession(raw, {
455
+ dbPath: DB_PATH,
456
+ directory: options.directory ? resolve(options.directory) : undefined,
457
+ maxLearnings: parseInt(options.max),
458
+ });
459
+
460
+ if (result.memoriesStored === 0) {
461
+ console.log('No learning found in this session.');
462
+ return;
463
+ }
464
+
465
+ console.log(`\n✓ ${result.memoriesStored} learning(s) stored:\n`);
466
+ for (const l of result.learnings) {
467
+ console.log(` • ${l}`);
468
+ }
469
+ });
470
+
471
+ // === INTENT (prospective memory) ===
472
+ const intent = program
473
+ .command('intent')
474
+ .description('Open loops (prospective memory) — arm, list, close');
475
+
476
+ intent
477
+ .command('add <content>')
478
+ .description('Arm an open loop')
479
+ .option('-d, --directory <dir>', 'Mental place (defaults to cwd)')
480
+ .option('-c, --cue <cue...>', "Trigger — 'time:2026-12-01', 'cron:0 9 * * 1', 'event:file_open:src/a.ts'")
481
+ .option('-e, --expires <date>', 'Deadline (ISO) past which the loop expires')
482
+ .action(async (content: string, options) => {
483
+ const s = getStore();
484
+
485
+ let cues: TriggerSpec[] = [];
486
+ try {
487
+ cues = (options.cue ?? []).map((raw: string) => parseCueArg(raw));
488
+ } catch (err) {
489
+ console.error(`✗ ${err instanceof Error ? err.message : err}`);
490
+ process.exitCode = 1;
491
+ return;
492
+ }
493
+
494
+ let expiresAt: Date | undefined;
495
+ if (options.expires) {
496
+ expiresAt = new Date(options.expires);
497
+ if (Number.isNaN(expiresAt.getTime())) {
498
+ console.error(`x invalid deadline: ${options.expires}`);
499
+ process.exitCode = 1;
500
+ return;
501
+ }
502
+ }
503
+
504
+ // The mental place is resolved to absolute: the SessionStart hook looks up by
505
+ // `process.cwd()`, so a loop armed on './src/auth' would never surface — a
506
+ // perfectly silent failure.
507
+ const intention = await s.addIntention(
508
+ {
509
+ content,
510
+ directory: resolve(options.directory ?? process.cwd()),
511
+ expiresAt,
512
+ },
513
+ cues
514
+ );
515
+
516
+ console.log(`\n🔁 Loop armed — ${loopId(intention.id)}`);
517
+ console.log(` ${intention.content}`);
518
+ console.log(` Place: ${intention.directory}`);
519
+ if (expiresAt) console.log(` Due: ${expiresAt.toISOString()}`);
520
+ for (const spec of cues) console.log(` Cue: ${formatTriggerSpec(spec)}`);
521
+ console.log(`\n To close: mention "Closes ${loopId(intention.id)}" in a commit\n`);
522
+ });
523
+
524
+ intent
525
+ .command('list')
526
+ .alias('ls')
527
+ .description('List loops')
528
+ .option('-s, --status <status>', 'armed | fired | closed | expired', 'armed')
529
+ .option('-d, --directory <dir>', 'Filter by mental place')
530
+ .option('-n, --limit <n>', 'Maximum count', '20')
531
+ .option('-a, --all', 'Every status')
532
+ .action(async (options) => {
533
+ const s = getStore();
534
+
535
+ const intentions = await s.listIntentions({
536
+ status: options.all ? undefined : (options.status as IntentionStatus),
537
+ directory: options.directory ? resolve(options.directory) : undefined,
538
+ limit: parseInt(options.limit),
539
+ });
540
+
541
+ if (intentions.length === 0) {
542
+ console.log('No loop.');
543
+ return;
544
+ }
545
+
546
+ const icons: Record<IntentionStatus, string> = {
547
+ armed: '🔁',
548
+ fired: '⏰',
549
+ closed: '✅',
550
+ expired: '💤',
551
+ };
552
+
553
+ console.log(`\n${intentions.length} loop(s):\n`);
554
+ for (const i of intentions) {
555
+ const cues = await s.listCues({ intentionId: i.id });
556
+ console.log(`${icons[i.status]} ${loopId(i.id)} | ${i.status} | ${i.directory}`);
557
+ console.log(` ${i.content}`);
558
+ if (cues.length) {
559
+ console.log(` Cues: ${cues.map((c) => `${formatTriggerSpec(c.triggerSpec)} (${c.status})`).join(', ')}`);
560
+ }
561
+ if (i.expiresAt) console.log(` Due: ${i.expiresAt.toISOString()}`);
562
+ if (i.closedByCommit) console.log(` Closed by: ${i.closedByCommit}`);
563
+ console.log();
564
+ }
565
+ });
566
+
567
+ /** Resolves a short id (`loop-a1b2c3d4`, `a1b2c3d4`) to an intention. */
568
+ async function resolveIntentionArg(s: SQLiteStore, arg: string) {
569
+ const short = arg.replace(/^loop-/i, '');
570
+ const all = await s.listIntentions({ limit: 500 });
571
+ const found = matchIntentionByShortId(all, short);
572
+
573
+ if (!found) {
574
+ // Ambiguous or unknown prefix: no guessing, closing the wrong loop is worse.
575
+ console.error(`x no single loop matches "${arg}"`);
576
+ process.exitCode = 1;
577
+ }
578
+ return found;
579
+ }
580
+
581
+ intent
582
+ .command('close <id>')
583
+ .description('Close a loop (accepts loop-abc12345 or the bare prefix)')
584
+ .option('--commit <sha>', 'SHA of the commit that closed the loop')
585
+ .action(async (id: string, options) => {
586
+ const s = getStore();
587
+ const found = await resolveIntentionArg(s, id);
588
+ if (!found) return;
589
+
590
+ const closed = await s.updateIntentionStatus(found.id, 'closed', { closedByCommit: options.commit });
591
+ for (const cue of await s.listCues({ intentionId: found.id, status: 'armed' })) {
592
+ await s.updateCueStatus(cue.id, 'cancelled');
593
+ }
594
+
595
+ console.log(`\n✅ ${loopId(closed.id)} closed — ${closed.content}\n`);
596
+ });
597
+
598
+ intent
599
+ .command('fire <id>')
600
+ .description('Force a loop to wake (debug)')
601
+ .action(async (id: string) => {
602
+ const s = getStore();
603
+ const found = await resolveIntentionArg(s, id);
604
+ if (!found) return;
605
+
606
+ const fired = await s.updateIntentionStatus(found.id, 'fired');
607
+ console.log(`\n⏰ ${loopId(fired.id)} woken — ${fired.content}\n`);
608
+ });
609
+
610
+ intent
611
+ .command('resolve')
612
+ .description('Sweep: expire overdue loops, fire deadlines that have come due')
613
+ .action(async () => {
614
+ const s = getStore();
615
+ const resolver = new SqliteCueResolver(s);
616
+
617
+ const expired = await resolver.expireStale();
618
+ const fired = [];
619
+ for (const cue of await resolver.resolveTimeCues()) {
620
+ fired.push(await resolver.fire(cue.id));
621
+ }
622
+
623
+ console.log(`\n💤 ${expired} expired | ⏰ ${fired.length} woken`);
624
+ for (const i of fired) console.log(` ${loopId(i.id)} — ${i.content}`);
625
+ console.log();
626
+ });
627
+
628
+ // === SCRIPT (Phase 8.3) ===
629
+ const script = program
630
+ .command('script')
631
+ .description('Cognitive scripts (drills) — cue-triggered procedures');
632
+
633
+ /** Resolves an unambiguous script id prefix (same rule as dream review). */
634
+ async function findScriptByPrefix(s: ReturnType<typeof getStore>, prefix: string) {
635
+ const all = await s.listScripts({ status: ['draft', 'active', 'archived'], limit: 500 });
636
+ const hits = all.filter((x) => x.id.startsWith(prefix));
637
+ return hits.length === 1 ? hits[0] : null;
638
+ }
639
+
640
+ script
641
+ .command('add <name>')
642
+ .description('Add a drill (human-authored → active immediately, 8.3 gate)')
643
+ .requiredOption('--steps <steps...>', 'Ordered drill steps')
644
+ .option('--description <text>', 'One-line summary for the context header', '')
645
+ .option('-d, --directory <dir>', 'Mental place (defaults to cwd)')
646
+ .option('-c, --cue <cue...>', "Trigger — 'cron:0 9 * * 1', 'event:branch_switch:main'")
647
+ .option('--pinned', 'Exempt from disuse decay (8.4)', false)
648
+ .action(async (name: string, options) => {
649
+ const s = getStore();
650
+
651
+ let cues: TriggerSpec[] = [];
652
+ try {
653
+ cues = (options.cue ?? []).map((raw: string) => parseCueArg(raw));
654
+ } catch (err) {
655
+ console.error(`✗ ${err instanceof Error ? err.message : err}`);
656
+ process.exitCode = 1;
657
+ return;
658
+ }
659
+
660
+ try {
661
+ const created = await s.addScript(
662
+ {
663
+ name,
664
+ description: options.description || name,
665
+ steps: options.steps,
666
+ directory: resolve(options.directory ?? process.cwd()),
667
+ pinned: options.pinned,
668
+ source: 'human',
669
+ },
670
+ cues
671
+ );
672
+ console.log(`\n📋 Script active — ${created.id.slice(0, 8)} (${created.name})`);
673
+ created.steps.forEach((step, i) => console.log(` ${i + 1}. ${step}`));
674
+ console.log(` Place: ${created.directory}${created.pinned ? ' · pinned' : ''}`);
675
+ for (const spec of cues) console.log(` Cue: ${formatTriggerSpec(spec)}`);
676
+ } catch (err) {
677
+ console.error(`✗ ${err instanceof Error ? err.message : err}`);
678
+ process.exitCode = 1;
679
+ }
680
+ });
681
+
682
+ script
683
+ .command('list')
684
+ .alias('ls')
685
+ .description('List drills')
686
+ .option('-s, --status <status>', 'draft | active | archived', 'active')
687
+ .option('-d, --directory <dir>', 'Filter by mental place')
688
+ .option('-a, --all', 'Every status')
689
+ .action(async (options) => {
690
+ const s = getStore();
691
+ const scripts = await s.listScripts({
692
+ status: options.all ? undefined : (options.status as import('../core/types.js').ScriptStatus),
693
+ directory: options.directory ? resolve(options.directory) : undefined,
694
+ limit: 50,
695
+ });
696
+
697
+ if (!scripts.length) {
698
+ console.log('No script.');
699
+ return;
700
+ }
701
+ const icons = { draft: '📝', active: '📋', archived: '🗄️' } as const;
702
+ for (const sc of scripts) {
703
+ console.log(`\n${icons[sc.status]} ${sc.id.slice(0, 8)} | ${sc.name} (${sc.status})`);
704
+ console.log(` ${sc.description}`);
705
+ console.log(` ${sc.steps.length} steps · fired ${sc.fireCount}× · saillance ${sc.saillance}${sc.pinned ? ' · pinned' : ''}`);
706
+ console.log(` ${sc.directory}`);
707
+ }
708
+ });
709
+
710
+ for (const verb of ['activate', 'archive'] as const) {
711
+ script
712
+ .command(`${verb} <id>`)
713
+ .description(verb === 'activate' ? 'draft → active (human gate)' : 'Archive a drill (cancels its cues)')
714
+ .action(async (id: string) => {
715
+ const s = getStore();
716
+ const target = await findScriptByPrefix(s, id);
717
+ if (!target) {
718
+ console.error(`✗ No script matches ${id}`);
719
+ process.exitCode = 1;
720
+ return;
721
+ }
722
+ const status = verb === 'activate' ? 'active' : 'archived';
723
+ await s.updateScriptStatus(target.id, status);
724
+ console.log(`✓ Script ${target.name} → ${status}`);
725
+ });
726
+ }
727
+
728
+ script
729
+ .command('fire <id>')
730
+ .description('Manually fire a drill (testing + saillance bump)')
731
+ .action(async (id: string) => {
732
+ const s = getStore();
733
+ const target = await findScriptByPrefix(s, id);
734
+ if (!target) {
735
+ console.error(`✗ No script matches ${id}`);
736
+ process.exitCode = 1;
737
+ return;
738
+ }
739
+ if (target.status !== 'active') {
740
+ console.error(`✗ Script ${target.name} is ${target.status} — only active drills fire`);
741
+ process.exitCode = 1;
742
+ return;
743
+ }
744
+ const fired = await s.markScriptFired(target.id);
745
+ console.log(`\n📋 ${fired.name} — fired ${fired.fireCount}×, saillance ${fired.saillance}`);
746
+ fired.steps.forEach((step, i) => console.log(` ${i + 1}. ${step}`));
747
+ });
748
+
749
+ // === EMBED (Phase 7.2) ===
750
+ const embed = program.command('embed').description('Vector index maintenance (Phase 7)');
751
+
752
+ embed
753
+ .command('backfill')
754
+ .description('Embed every trace missing a vector for the current model (idempotent)')
755
+ .option('-n, --limit <n>', 'Max traces per run', '500')
756
+ .option('--dtype <dtype>', 'Model quantization (q8|fp32 — fp16 broken on win32)', 'q8')
757
+ .option('--model <name>', 'small|base|bge-m3 (default bge-m3 since 7.5 round 4)', 'bge-m3')
758
+ .action(async (options) => {
759
+ const s = getStore();
760
+ const { OnnxEmbedder, embeddableText, E5_MODEL_ID, E5_BASE_MODEL_ID, BGE_M3_MODEL_ID } = await import('../core/embeddings.js');
761
+
762
+ const MODELS: Record<string, string> = { small: E5_MODEL_ID, base: E5_BASE_MODEL_ID, 'bge-m3': BGE_M3_MODEL_ID };
763
+ const model = MODELS[options.model] ?? BGE_M3_MODEL_ID;
764
+ const embedder = new OnnxEmbedder({ dtype: options.dtype, model });
765
+ console.log(`⏳ Model: ${embedder.modelId} (first run downloads ~120MB into data/models/)…`);
766
+
767
+ const missing = await s.listMissingEmbeddings(embedder.modelId, parseInt(options.limit));
768
+ if (!missing.length) {
769
+ console.log('✓ Nothing to embed — the index is current.');
770
+ return;
771
+ }
772
+ console.log(`⏳ Embedding ${missing.length} trace(s)…`);
773
+
774
+ const BATCH = 32;
775
+ let done = 0;
776
+ for (let i = 0; i < missing.length; i += BATCH) {
777
+ const batch = missing.slice(i, i + BATCH);
778
+ const vectors = await embedder.embed(batch.map(embeddableText));
779
+ for (let k = 0; k < batch.length; k++) {
780
+ await s.setEmbedding(batch[k].id, embedder.modelId, vectors[k]);
781
+ }
782
+ done += batch.length;
783
+ console.log(` ${done}/${missing.length}`);
784
+ }
785
+ console.log(`✓ Backfill complete: ${done} trace(s) embedded.`);
786
+ });
787
+
788
+ // === DREAM (Phase 6.1) ===
789
+ const dream = program.command('dream').description('Cross-session consolidation (dreaming)');
790
+
791
+ dream
792
+ .command('run', { isDefault: true })
793
+ .description('Detect recurring patterns across sessions/agents and file proposals')
794
+ .option('--clusterer <kind>', 'keyword (default — 7.5 round 3: vector P 0.71 too noisy) | vector (needs the model)', 'keyword')
795
+ .option('--window <days>', 'Collection window in days (default 30; raise for old traces)', undefined)
796
+ .action(async (options) => {
797
+ const s = getStore();
798
+ const { runDreamer, KeywordClusterer } = await import('../core/dreamer.js');
799
+
800
+ let clusterer: import('../core/dreamer.js').Clusterer = new KeywordClusterer();
801
+ if (options.clusterer === 'vector') {
802
+ const { OnnxEmbedder } = await import('../core/embeddings.js');
803
+ const { VectorClusterer } = await import('../core/vector-clusterer.js');
804
+ clusterer = new VectorClusterer(new OnnxEmbedder(), s);
805
+ console.log('⏳ Vector clustering (embeds missing traces in batch first)…');
806
+ }
807
+
808
+ const report = await runDreamer({
809
+ store: s,
810
+ clusterer,
811
+ windowDays: options.window ? parseInt(options.window) : undefined,
812
+ });
813
+ console.log(`\n🌙 Dream report`);
814
+ console.log(` Traces considered: ${report.considered}`);
815
+ console.log(` Clusters found: ${report.clusters}`);
816
+ console.log(` Proposals filed: ${report.filed} (${report.expired} expired)`);
817
+ if (report.staleLoopCandidates) console.log(` Stale loops spotted: ${report.staleLoopCandidates}`);
818
+ if (report.scriptCandidates) console.log(` Script candidates drafted: ${report.scriptCandidates}`);
819
+ const pending = report.proposals.length;
820
+ if (pending) console.log(`\n ${pending} dream(s) pending — run \`pnpm cli dream review\`.`);
821
+ });
822
+
823
+ dream
824
+ .command('review')
825
+ .description('List pending dream proposals')
826
+ .action(async () => {
827
+ const s = getStore();
828
+ const pending = await s.listDreamProposals!({ status: 'pending' });
829
+
830
+ if (!pending.length) {
831
+ console.log('No dream pending.');
832
+ return;
833
+ }
834
+ console.log(`\n🌙 ${pending.length} dream(s) pending:\n`);
835
+ for (const p of pending) {
836
+ const payload = JSON.parse(p.payload);
837
+ console.log(` [${p.kind}] ${p.id.slice(0, 8)}… — confidence ${p.confidence}`);
838
+ if (payload.samples) for (const s2 of payload.samples) console.log(` · ${s2}`);
839
+ if (payload.content) console.log(` · ${payload.content}`);
840
+ if (p.kind === 'script_candidate') {
841
+ console.log(` "${payload.name}" in ${payload.directory} — ${payload.description}`);
842
+ (payload.steps as string[]).forEach((step, i) => console.log(` ${i + 1}. ${step}`));
843
+ if (payload.truncatedSteps) console.log(` … more corrections than steps shown (capped)`);
844
+ }
845
+ if (p.kind === 'script_archived') {
846
+ if (payload.reason === 'contradiction') {
847
+ console.log(` "${payload.name}" — contradicted by: ${payload.winnerContent}`);
848
+ } else {
849
+ console.log(` "${payload.name}" — saillance ${payload.storedSaillance} → effective ${payload.effectiveSaillance} (disuse)`);
850
+ }
851
+ }
852
+ if (payload.expiresAt || p.expiresAt) console.log(` expires ${p.expiresAt?.toISOString().split('T')[0]}`);
853
+ console.log();
854
+ }
855
+ });
856
+
857
+ for (const verb of ['approve', 'reject'] as const) {
858
+ dream
859
+ .command(`${verb} <id>`)
860
+ .description(`${verb === 'approve' ? 'Apply' : 'Archive'} a dream proposal (human gate)`)
861
+ .action(async (id) => {
862
+ const s = getStore();
863
+
864
+ const pending = await s.listDreamProposals!({ status: 'pending', includeExpired: true });
865
+ const target = pending.find((p) => p.id === id || p.id.startsWith(id));
866
+ if (!target) {
867
+ console.error(`✗ No pending dream matches ${id}`);
868
+ process.exit(1);
869
+ }
870
+
871
+ if (verb === 'approve') {
872
+ const { applyDreamProposal } = await import('../core/dreamer.js');
873
+ const effect = await applyDreamProposal(s, target);
874
+ await s.resolveDreamProposal!(target.id, 'approved');
875
+ console.log(`✓ Dream approved — ${effect}`);
876
+ } else {
877
+ await s.resolveDreamProposal!(target.id, 'rejected');
878
+ console.log(`✓ Dream rejected — it will not resurface unless the pattern recurs.`);
879
+ }
880
+ });
881
+ }
882
+
883
+ // === MAINTENANCE ===
884
+ const maintenance = program
885
+ .command('maintenance')
886
+ .description('Health of the consolidation loop, and a way to force a pass');
887
+
888
+ maintenance
889
+ .command('status', { isDefault: true })
890
+ .description('Is consolidation still running, and when did it last succeed?')
891
+ .option('--json', 'Machine-readable output')
892
+ .option('--stale-after <minutes>', 'Staleness budget before the loop is called overdue', '60')
893
+ .action(async (options) => {
894
+ const { readMaintenanceState, assessMaintenance, defaultStatePath } = await import('../agent/maintenance-state.js');
895
+ const staleAfterMs = Math.max(1, Number(options.staleAfter)) * 60_000;
896
+ const health = assessMaintenance(await readMaintenanceState(defaultStatePath(QUEUE_DIR)), { staleAfterMs });
897
+
898
+ if (options.json) {
899
+ console.log(JSON.stringify(health, null, 2));
900
+ } else {
901
+ console.log(`\n${health.stale ? '✗' : '✓'} ${health.summary}`);
902
+ if (health.lastRunAt) console.log(` last attempt ${health.lastRunAt}`);
903
+ if (health.lastSuccessAt) console.log(` last success ${health.lastSuccessAt}`);
904
+ if (health.lastError) console.log(` last error ${health.lastError}`);
905
+ if (health.lastResult) {
906
+ const r = health.lastResult;
907
+ console.log(` last counts ${r.processed}/${r.discovered} jobs, ${r.memoriesStored} memories, ${r.failed} failed, ${r.deadLettered} dead-lettered`);
908
+ if (r.retriesRefunded) console.log(` retries kept ${r.retriesRefunded} refunded — the failures looked like the machine, not the sessions`);
909
+ if (r.aborted) console.log(' breaker pass aborted early; the untouched jobs are still queued');
910
+ }
911
+ console.log();
912
+ if (health.stale) {
913
+ console.log('The loop lives in the API process — check that it is running, then `humemory maintenance run`.\n');
914
+ }
915
+ }
916
+ // Non-zero on staleness so a checker can act on it without parsing text.
917
+ if (health.stale) process.exitCode = 1;
918
+ });
919
+
920
+ maintenance
921
+ .command('run')
922
+ .description('Force one consolidation pass here and now, in this process')
923
+ .option('--skip-imports', 'Do not import any local agent sessions first')
924
+ .option('--skip-codex', 'Do not import Codex rollouts first')
925
+ .option('--skip-kimi', 'Do not import Kimi Code sessions first')
926
+ .option('--skip-opencode', 'Do not import OpenCode sessions first')
927
+ .action(async (options) => {
928
+ const { runMaintenancePass, resolveMaintenanceClient } = await import('../agent/maintenance-runner.js');
929
+ const client = await resolveMaintenanceClient();
930
+ const { worker } = await runMaintenancePass({
931
+ client,
932
+ codexSinceDays: options.skipImports || options.skipCodex ? false : 1,
933
+ kimiSinceDays: options.skipImports || options.skipKimi ? false : 1,
934
+ opencodeSinceDays: options.skipImports || options.skipOpencode ? false : 1,
935
+ runner: 'cli',
936
+ });
937
+ console.log(
938
+ `✓ ${worker.processed}/${worker.discovered} jobs, ${worker.memoriesStored} memories, ` +
939
+ `${worker.failed} failed, ${worker.deadLettered} dead-lettered${worker.busy ? ' (another worker held the lock)' : ''}`
940
+ );
941
+ });
942
+
943
+ maintenance
944
+ .command('dead-letters')
945
+ .description('Sessions parked after exhausting their retries, newest first')
946
+ .option('--json', 'Machine-readable output')
947
+ .action(async (options) => {
948
+ const { listDeadLetters } = await import('../agent/maintenance-queue.js');
949
+ const entries = await listDeadLetters(QUEUE_DIR);
950
+
951
+ if (options.json) {
952
+ // The raw transcript is deliberately left out: this is a triage listing,
953
+ // not an export, and a dump of every session is not what a terminal wants.
954
+ console.log(JSON.stringify(entries.map(({ job, ...rest }) => rest), null, 2));
955
+ return;
956
+ }
957
+
958
+ if (entries.length === 0) {
959
+ console.log('\n✓ No dead-lettered sessions.\n');
960
+ return;
961
+ }
962
+
963
+ console.log(`\n${entries.length} dead-lettered session(s):\n`);
964
+ for (const entry of entries) {
965
+ console.log(` ${entry.id.slice(0, 12)} ${entry.sessionId ?? '(unreadable)'}${entry.source ? ` [${entry.source}]` : ''}`);
966
+ if (entry.deadLetteredAt) console.log(` parked ${entry.deadLetteredAt} after ${entry.attempts ?? '?'} attempt(s)`);
967
+ if (entry.lastError) console.log(` last error ${entry.lastError}`);
968
+ }
969
+ console.log('\nPut them back with `humemory maintenance requeue --all` once the cause is fixed.\n');
970
+ });
971
+
972
+ maintenance
973
+ .command('requeue')
974
+ .description('Put dead-lettered sessions back in the queue with a fresh retry budget')
975
+ .argument('[ids...]', 'Job ids, session ids or filenames; omit with --all for every dead-letter')
976
+ .option('--all', 'Requeue every dead-lettered session')
977
+ .option('--limit <n>', 'Stop after N sessions')
978
+ .option('--dry-run', 'Report what would be requeued, write nothing')
979
+ .action(async (ids: string[], options) => {
980
+ if (!options.all && ids.length === 0) {
981
+ console.error('Nothing selected — name at least one id, or pass --all.');
982
+ process.exitCode = 1;
983
+ return;
984
+ }
985
+
986
+ const { requeueDeadLetters } = await import('../agent/maintenance-queue.js');
987
+ const result = await requeueDeadLetters({
988
+ queueDir: QUEUE_DIR,
989
+ ids: options.all ? undefined : ids,
990
+ limit: options.limit ? parseInt(options.limit) : undefined,
991
+ dryRun: options.dryRun,
992
+ });
993
+
994
+ console.log(
995
+ `\n${options.dryRun ? 'Would requeue' : '✓ Requeued'} ${result.requeued} of ${result.scanned} dead-letter(s).`
996
+ );
997
+ for (const entry of result.entries) {
998
+ console.log(` ${entry.id.slice(0, 12)} ${entry.sessionId ?? '(unknown session)'}`);
999
+ }
1000
+ if (result.skippedLive > 0) {
1001
+ console.log(` skipped ${result.skippedLive} already superseded by a newer queued transcript`);
1002
+ }
1003
+ if (result.unreadable > 0) {
1004
+ console.log(` skipped ${result.unreadable} unreadable file(s) — inspect them in ${QUEUE_DIR}`);
1005
+ }
1006
+ if (!options.dryRun && result.requeued > 0) {
1007
+ console.log('\nRun `humemory maintenance run` to encode them (or wait for the scheduled pass).\n');
1008
+ } else {
1009
+ console.log();
1010
+ }
1011
+ });
1012
+
1013
+ // === LOCAL AGENT SOURCES ===
1014
+ const sources = program
1015
+ .command('sources')
1016
+ .description('Discover local AI agent runtimes without reading their sessions');
1017
+
1018
+ sources
1019
+ .command('import-codex')
1020
+ .description('Queue Codex CLI rollouts for maintenance (nothing is encoded until the worker runs)')
1021
+ .option('--since <days>', 'Only rollouts touched in the last N days', '7')
1022
+ .option('--all', 'Every rollout ever recorded, ignoring --since')
1023
+ .option('--limit <n>', 'Stop after N queued sessions')
1024
+ .option('--include-subagents', 'Also import threads codex spawned for itself')
1025
+ .option('--dry-run', 'Report what would be queued, write nothing')
1026
+ .option('--sessions-dir <dir>', 'Override $CODEX_HOME/sessions')
1027
+ .action(async (options) => {
1028
+ const { importCodexRollouts, defaultCodexSessionsDir } = await import('../agent/codex-import.js');
1029
+ const sessionsDir = options.sessionsDir ? resolve(options.sessionsDir) : defaultCodexSessionsDir();
1030
+ const days = Number(options.since);
1031
+ const since = options.all || !Number.isFinite(days)
1032
+ ? undefined
1033
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
1034
+
1035
+ console.log(`⏳ Scanning ${sessionsDir}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
1036
+
1037
+ const result = await importCodexRollouts({
1038
+ queueDir: QUEUE_DIR,
1039
+ sessionsDir,
1040
+ since,
1041
+ limit: options.limit ? parseInt(options.limit) : undefined,
1042
+ includeSubagents: options.includeSubagents,
1043
+ dryRun: options.dryRun,
1044
+ });
1045
+
1046
+ console.log(
1047
+ `\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
1048
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.`
1049
+ );
1050
+ console.log(
1051
+ ` skipped — ${result.skippedOld} older than the window, ` +
1052
+ `${result.skippedSubagent} subagent thread(s), ${result.skippedEmpty} without a turn, ` +
1053
+ `${result.unreadable} unreadable`
1054
+ );
1055
+ if (!options.dryRun && result.queued > 0) {
1056
+ console.log('\nRun `pnpm maintenance` to encode them (or wait for the scheduled pass).');
1057
+ }
1058
+ });
1059
+
1060
+ sources
1061
+ .command('import-kimi')
1062
+ .description('Queue Kimi Code sessions for maintenance')
1063
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
1064
+ .option('--all', 'Every session ever recorded, ignoring --since')
1065
+ .option('--limit <n>', 'Stop after N queued sessions')
1066
+ .option('--dry-run', 'Report what would be queued, write nothing')
1067
+ .option('--kimi-home <dir>', 'Override $KIMI_CODE_HOME')
1068
+ .action(async (options) => {
1069
+ const { importKimiSessions, defaultKimiHome } = await import('../agent/kimi-import.js');
1070
+ const kimiHome = options.kimiHome ? resolve(options.kimiHome) : defaultKimiHome();
1071
+ const days = Number(options.since);
1072
+ const since = options.all || !Number.isFinite(days)
1073
+ ? undefined
1074
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
1075
+ console.log(`⏳ Scanning ${kimiHome}${since ? ` (last ${days} day(s))` : ' (all)'}...`);
1076
+ const result = await importKimiSessions({
1077
+ queueDir: QUEUE_DIR,
1078
+ kimiHome,
1079
+ since,
1080
+ limit: options.limit ? parseInt(options.limit) : undefined,
1081
+ dryRun: options.dryRun,
1082
+ });
1083
+ console.log(
1084
+ `\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
1085
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
1086
+ ` skipped — ${result.skippedOld} older than the window, ${result.skippedEmpty} without a complete turn, ` +
1087
+ `${result.unreadable} unreadable`
1088
+ );
1089
+ });
1090
+
1091
+ sources
1092
+ .command('import-opencode')
1093
+ .description('Queue OpenCode session exports for maintenance')
1094
+ .option('--since <days>', 'Only sessions touched in the last N days', '7')
1095
+ .option('--all', 'Every session ever recorded, ignoring --since')
1096
+ .option('--limit <n>', 'Stop after N queued sessions')
1097
+ .option('--include-subagents', 'Also import child sessions OpenCode spawned')
1098
+ .option('--dry-run', 'Report what would be queued, write nothing')
1099
+ .option('--command <path>', 'Override the OpenCode executable')
1100
+ .action(async (options) => {
1101
+ const { importOpenCodeSessions } = await import('../agent/opencode-import.js');
1102
+ const days = Number(options.since);
1103
+ const since = options.all || !Number.isFinite(days)
1104
+ ? undefined
1105
+ : new Date(Date.now() - days * 24 * 60 * 60 * 1000);
1106
+ console.log(`⏳ Asking OpenCode for sessions${since ? ` from the last ${days} day(s)` : ' from all time'}...`);
1107
+ const result = await importOpenCodeSessions({
1108
+ queueDir: QUEUE_DIR,
1109
+ since,
1110
+ limit: options.limit ? parseInt(options.limit) : undefined,
1111
+ includeSubagents: options.includeSubagents,
1112
+ dryRun: options.dryRun,
1113
+ command: options.command,
1114
+ });
1115
+ console.log(
1116
+ `\n${options.dryRun ? 'Would queue' : '✓ Queued'} ${result.queued} session(s)` +
1117
+ `${options.dryRun ? '' : ` (${result.created} new)`} out of ${result.scanned} scanned.\n` +
1118
+ ` skipped — ${result.skippedEmpty} without a complete turn, ${result.unreadable} unreadable`
1119
+ );
1120
+ });
1121
+
1122
+ sources
1123
+ .command('setup')
1124
+ .description('Register humemory as a local MCP server in Kimi Code and OpenCode')
1125
+ .option('--kimi', 'Configure Kimi Code only')
1126
+ .option('--opencode', 'Configure OpenCode only')
1127
+ .option('--dry-run', 'Show which files would change, write nothing')
1128
+ .action(async (options) => {
1129
+ const { setupHumemoryMcpClients } = await import('../agent/mcp-client-setup.js');
1130
+ const clients = options.kimi || options.opencode
1131
+ ? [...(options.kimi ? ['kimi'] as const : []), ...(options.opencode ? ['opencode'] as const : [])]
1132
+ : ['kimi', 'opencode'] as const;
1133
+ const projectRoot = resolve(__dirname, '../..');
1134
+ const result = await setupHumemoryMcpClients({
1135
+ clients: [...clients],
1136
+ projectRoot,
1137
+ dbPath: DB_PATH,
1138
+ dryRun: options.dryRun,
1139
+ });
1140
+ for (const entry of result) {
1141
+ const verb = entry.changed ? (options.dryRun ? 'would update' : 'updated') : 'already configured';
1142
+ console.log(`✓ ${entry.client}: ${verb} ${entry.path}`);
1143
+ }
1144
+ });
1145
+
1146
+ sources
1147
+ .command('discover', { isDefault: true })
1148
+ .description('Show known runtimes and the local evidence found for each one')
1149
+ .option('--installed-only', 'Hide known runtimes that were not found')
1150
+ .action((options) => {
1151
+ const discovered = discoverLocalAgentSources()
1152
+ .filter((source) => !options.installedOnly || source.installed);
1153
+
1154
+ console.log('\nLocal AI sources (discovery only — no session was read):\n');
1155
+ for (const source of discovered) {
1156
+ console.log(`${source.installed ? '✓' : '·'} ${source.name} — ${source.vendor}`);
1157
+ for (const evidence of source.evidence) console.log(` ${evidence}`);
1158
+ }
1159
+ });
1160
+
1161
+ program.command('remap-project <from> <to>')
1162
+ .description('Preview a project root relocation; --apply requires a coherent SQLite backup')
1163
+ .option('--apply', 'Apply the previewed mapping in a transaction')
1164
+ .option('--backup <path>', 'New SQLite backup destination (required with --apply)')
1165
+ .action(async (from, to, options) => {
1166
+ console.log(JSON.stringify(await getStore().remapProjectRoot(from, to, { apply: options.apply, backupPath: options.backup }), null, 2));
1167
+ });
1168
+
1169
+ // Parse and run
1170
+ program.parse();
1171
+
1172
+ // Cleanup
1173
+ process.on('exit', () => {
1174
+ if (store) store.close();
1175
+ });