humemory 0.2.1

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 (81) hide show
  1. package/.githooks/post-commit +22 -0
  2. package/AGENTS.md +328 -0
  3. package/CHANGELOG.md +198 -0
  4. package/LICENSE +21 -0
  5. package/README.md +488 -0
  6. package/bin/humemory.js +19 -0
  7. package/dist/agent/claude-hook.d.ts +15 -0
  8. package/dist/agent/claude-hook.js +38 -0
  9. package/dist/agent/commit-closer.d.ts +60 -0
  10. package/dist/agent/commit-closer.js +125 -0
  11. package/dist/agent/learning-extractor.d.ts +10 -0
  12. package/dist/agent/learning-extractor.js +75 -0
  13. package/dist/agent/session-context.d.ts +63 -0
  14. package/dist/agent/session-context.js +216 -0
  15. package/dist/agent/session-parser.d.ts +12 -0
  16. package/dist/agent/session-parser.js +85 -0
  17. package/dist/api/dream-routes.d.ts +7 -0
  18. package/dist/api/dream-routes.js +40 -0
  19. package/dist/api/intentions-routes.d.ts +23 -0
  20. package/dist/api/intentions-routes.js +252 -0
  21. package/dist/api/memory-routes.d.ts +10 -0
  22. package/dist/api/memory-routes.js +277 -0
  23. package/dist/api/scripts-routes.d.ts +13 -0
  24. package/dist/api/scripts-routes.js +129 -0
  25. package/dist/api/server.d.ts +33 -0
  26. package/dist/api/server.js +157 -0
  27. package/dist/cli/index.d.ts +2 -0
  28. package/dist/cli/index.js +798 -0
  29. package/dist/core/clock.d.ts +38 -0
  30. package/dist/core/clock.js +52 -0
  31. package/dist/core/cue-arg.d.ts +19 -0
  32. package/dist/core/cue-arg.js +72 -0
  33. package/dist/core/cues.d.ts +138 -0
  34. package/dist/core/cues.js +372 -0
  35. package/dist/core/decay.d.ts +49 -0
  36. package/dist/core/decay.js +157 -0
  37. package/dist/core/dreamer.d.ts +114 -0
  38. package/dist/core/dreamer.js +427 -0
  39. package/dist/core/embeddings.d.ts +79 -0
  40. package/dist/core/embeddings.js +133 -0
  41. package/dist/core/event-bus.d.ts +71 -0
  42. package/dist/core/event-bus.js +67 -0
  43. package/dist/core/hybrid.d.ts +33 -0
  44. package/dist/core/hybrid.js +63 -0
  45. package/dist/core/llm-generator.d.ts +18 -0
  46. package/dist/core/llm-generator.js +69 -0
  47. package/dist/core/sanitize.d.ts +57 -0
  48. package/dist/core/sanitize.js +87 -0
  49. package/dist/core/scripts.d.ts +55 -0
  50. package/dist/core/scripts.js +96 -0
  51. package/dist/core/search.d.ts +42 -0
  52. package/dist/core/search.js +173 -0
  53. package/dist/core/trust.d.ts +48 -0
  54. package/dist/core/trust.js +57 -0
  55. package/dist/core/types.d.ts +333 -0
  56. package/dist/core/types.js +1 -0
  57. package/dist/core/vector-clusterer.d.ts +53 -0
  58. package/dist/core/vector-clusterer.js +113 -0
  59. package/dist/index.d.ts +28 -0
  60. package/dist/index.js +18 -0
  61. package/dist/mcp/server.d.ts +22 -0
  62. package/dist/mcp/server.js +158 -0
  63. package/dist/store/sqlite.d.ts +240 -0
  64. package/dist/store/sqlite.js +1653 -0
  65. package/docs/TESTING.md +244 -0
  66. package/package.json +95 -0
  67. package/public/app/galaxy-f42190mq.js +10 -0
  68. package/public/app/index-2cf31xxn.css +1 -0
  69. package/public/app/index-epqg22cp.js +1 -0
  70. package/public/app/index-f9h80bzq.js +12 -0
  71. package/public/app/index-gbfwa9vq.js +2 -0
  72. package/public/app/index-kvhc17mz.js +2 -0
  73. package/public/app/index-pbd5t4dj.js +2 -0
  74. package/public/app/index.html +12 -0
  75. package/public/app/promenade-cnzzpm73.js +4111 -0
  76. package/public/app/river-tyawhh8w.js +13 -0
  77. package/public/session.html +659 -0
  78. package/scripts/consolidate.js +46 -0
  79. package/scripts/hook-post-commit.ts +80 -0
  80. package/scripts/hook-session-start.ts +92 -0
  81. package/scripts/hook-session.ts +60 -0
@@ -0,0 +1,798 @@
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { SQLiteStore } from '../store/sqlite.js';
4
+ import { SqliteCueResolver, loopId, matchIntentionByShortId } from '../core/cues.js';
5
+ import { parseCueArg, formatTriggerSpec } from '../core/cue-arg.js';
6
+ import { join, dirname, resolve } from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ import { readFileSync } from 'fs';
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
11
+ // Shared store. HUMEMORY_DB points at another database โ€” same convention as the
12
+ // hooks, and required to exercise the CLI without touching production.
13
+ const DB_PATH = process.env.HUMEMORY_DB ?? join(__dirname, '../../data/humemory.db');
14
+ let store;
15
+ function getStore() {
16
+ if (!store) {
17
+ store = new SQLiteStore(DB_PATH);
18
+ }
19
+ return store;
20
+ }
21
+ const program = new Command();
22
+ // Version read from the package: hard-coded, it drifted at every release.
23
+ const { version } = JSON.parse(readFileSync(join(__dirname, '../../package.json'), 'utf-8'));
24
+ program
25
+ .name('humemory')
26
+ .description('Memory palace โ€” mnemonic traces with progressive decay')
27
+ .version(version);
28
+ // === ADD ===
29
+ program
30
+ .command('encode <content>')
31
+ .alias('add')
32
+ .description('Encode a new mnemonic trace')
33
+ .option('-d, --directory <dir>', 'Mental place (project)', process.cwd())
34
+ .option('-s, --session <id>', 'Contexte d\'encodage', 'default')
35
+ .option('-k, --keywords <tags>', 'Retrieval cues (comma-separated)', '')
36
+ .option('-l1, --level1 <summary>', 'Summary for consolidation level 1')
37
+ .option('-l2, --level2 <essential>', 'Gist for consolidation level 2')
38
+ .option('-l3, --level3 <keywords>', 'Keywords for fast level 3 retrieval')
39
+ .option('-t, --type <type>', 'Memory type (episodic/semantic/procedural)', 'semantic')
40
+ .option('--auto', 'Auto-generate levels 1-3 through the LLM (needs ANTHROPIC_API_KEY)')
41
+ .option('--photographic', 'Photographic mode โ€” disable decay')
42
+ .option('--agent <name>', 'Who is encoding (claude/codex/kimi/โ€ฆ)', 'cli')
43
+ .action(async (content, options) => {
44
+ const s = getStore();
45
+ const validTypes = ['episodic', 'semantic', 'procedural'];
46
+ const memoryType = validTypes.includes(options.type) ? options.type : 'semantic';
47
+ if (options.auto) {
48
+ console.log('โณ Generating consolidation levels through the LLMโ€ฆ');
49
+ }
50
+ const memory = await s.add({
51
+ content,
52
+ // Resolved to absolute, as for intentions: the SessionStart hook filters by
53
+ // `process.cwd()`, and a relative path would never match.
54
+ directory: resolve(options.directory),
55
+ day: new Date().toISOString().split('T')[0],
56
+ keywords: options.keywords ? options.keywords.split(',').map((k) => k.trim()).filter(Boolean) : [],
57
+ sessionId: options.session,
58
+ level1Summary: options.level1,
59
+ level2Essential: options.level2,
60
+ level3Keywords: options.level3,
61
+ memoryType: memoryType,
62
+ photographic: options.photographic ?? false,
63
+ agent: options.agent,
64
+ }, { autoGenerate: options.auto });
65
+ const typeLabels = { episodic: 'Episodic', semantic: 'Semantic', procedural: 'Procedural' };
66
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
67
+ console.log(`โœ“ Trace encoded: ${memory.id}`);
68
+ console.log(` Type: ${typeLabels[memory.memoryType]}`);
69
+ console.log(` State: ${states[memory.currentLevel]}`);
70
+ console.log(` Mnemonic strength: ${memory.saillance}/100`);
71
+ });
72
+ // === SEARCH ===
73
+ program
74
+ .command('search <query>')
75
+ .alias('find')
76
+ .description('Search by retrieval cues (inverse search)')
77
+ .option('-d, --directory <dir>', 'Filter by mental place')
78
+ .option('-s, --session <id>', 'Filter by context')
79
+ .option('-l, --level <max>', 'Maximum consolidation state (0-4)', '4')
80
+ .option('-n, --limit <n>', 'Number of traces', '10')
81
+ .option('-t, --type <type>', 'Filter by type (episodic/semantic/procedural)')
82
+ .option('--from <date>', 'Start date YYYY-MM-DD')
83
+ .option('--to <date>', 'End date YYYY-MM-DD')
84
+ .option('--min-saillance <n>', 'Minimum mnemonic strength (0-100)')
85
+ .option('--min-recalls <n>', 'Minimum recall count')
86
+ .option('--semantic', 'Hybrid search: fuse BM25 with vector similarity (Phase 7.4, needs the model)')
87
+ .action(async (query, options) => {
88
+ const s = getStore();
89
+ let results;
90
+ if (options.semantic) {
91
+ const { OnnxEmbedder } = await import('../core/embeddings.js');
92
+ const { hybridSearch } = await import('../core/hybrid.js');
93
+ const embedder = new OnnxEmbedder();
94
+ results = await hybridSearch(s, embedder, query, {
95
+ directory: options.directory ? resolve(options.directory) : undefined,
96
+ limit: parseInt(options.limit),
97
+ });
98
+ }
99
+ else {
100
+ results = await s.search({
101
+ query,
102
+ directory: options.directory ? resolve(options.directory) : undefined,
103
+ sessionId: options.session,
104
+ maxLevel: parseInt(options.level),
105
+ limit: parseInt(options.limit),
106
+ memoryType: options.type,
107
+ dateFrom: options.from ? new Date(options.from) : undefined,
108
+ dateTo: options.to ? new Date(options.to) : undefined,
109
+ minSaillance: options.minSaillance ? parseInt(options.minSaillance) : undefined,
110
+ minRecalls: options.minRecalls ? parseInt(options.minRecalls) : undefined,
111
+ });
112
+ }
113
+ if (results.length === 0) {
114
+ console.log('No trace found.');
115
+ return;
116
+ }
117
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
118
+ console.log(`\n๐Ÿง  ${results.length} trace(s) found:\n`);
119
+ for (const result of results) {
120
+ console.log(`๐Ÿ” [${states[result.matchLevel]}] Score: ${Math.round(result.score)}`);
121
+ console.log(` ID: ${result.memory.id}`);
122
+ console.log(` Place: ${result.memory.directory}`);
123
+ console.log(` Context: ${result.memory.sessionId}`);
124
+ console.log(` Encoded: ${new Date(result.memory.createdAt).toLocaleDateString()}`);
125
+ console.log(` Recalls: ${result.memory.recallCount}`);
126
+ // Show the content at the level where the match happened
127
+ let displayContent = result.memory.content;
128
+ if (result.matchLevel === 4 && result.memory.level3Keywords) {
129
+ displayContent = `Trace: ${result.memory.level3Keywords}`;
130
+ }
131
+ else if (result.matchLevel === 3 && result.memory.level3Keywords) {
132
+ displayContent = `Keywords: ${result.memory.level3Keywords}`;
133
+ }
134
+ else if (result.matchLevel === 2 && result.memory.level2Essential) {
135
+ displayContent = result.memory.level2Essential;
136
+ }
137
+ else if (result.matchLevel === 1 && result.memory.level1Summary) {
138
+ displayContent = result.memory.level1Summary;
139
+ }
140
+ console.log(` Content: ${displayContent.slice(0, 200)}${displayContent.length > 200 ? '...' : ''}`);
141
+ console.log();
142
+ }
143
+ });
144
+ // === RECALL ===
145
+ program
146
+ .command('recall <id>')
147
+ .alias('reactivate')
148
+ .description('Recall a trace (mnemonic reinforcement)')
149
+ .option('--agent <name>', 'Who is recalling (earns `reused` verification across agents)')
150
+ .action(async (id, options) => {
151
+ const s = getStore();
152
+ // A human at a terminal chose this `--agent`; that is a process-level
153
+ // identity, not a request claiming one. It may earn `reused`.
154
+ const memory = await s.recall(id, options.agent, { identityTrusted: true });
155
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
156
+ console.log(`โœ“ Trace recalled: ${memory.id}`);
157
+ console.log(` Total recalls: ${memory.recallCount}`);
158
+ console.log(` Mnemonic strength: ${memory.saillance}/100`);
159
+ console.log(` State: ${states[memory.currentLevel]}`);
160
+ if (memory.verified && memory.verificationReason === 'reused') {
161
+ console.log(` Verified: earned by cross-agent reuse โœ“`);
162
+ }
163
+ });
164
+ // === VERIFY / REFUTE (Phase 6.0.1) ===
165
+ program
166
+ .command('verify <id>')
167
+ .description('Mark a trace as human-verified (prints content first โ€” no blind stamp)')
168
+ .action(async (id) => {
169
+ const s = getStore();
170
+ const memory = await s.getById(id);
171
+ if (!memory) {
172
+ console.error(`โœ— Trace ${id} not found`);
173
+ process.exit(1);
174
+ }
175
+ // Trust-theatre guard (PHASE6_PLAN risks): the human must actually read
176
+ // the trace before stamping it โ€” verify prints the content, always.
177
+ console.log(`\n๐Ÿง  ${memory.id}\n\n${memory.content}\n`);
178
+ const updated = await s.verify(id, 'human');
179
+ console.log(`โœ“ Trace verified (reason: human). Trust will reflect it.`);
180
+ void updated;
181
+ });
182
+ program
183
+ .command('refute <id>')
184
+ .description('Record a negative signal against a trace (refuted_count +1, verification revoked)')
185
+ .option('-r, --reason <text>', 'Why the trace does not hold')
186
+ .action(async (id, options) => {
187
+ const s = getStore();
188
+ const memory = await s.refute(id, options.reason);
189
+ console.log(`โœ“ Trace refuted: ${memory.id}`);
190
+ console.log(` Refuted count: ${memory.refutedCount}`);
191
+ console.log(` Verification: revoked (must be re-earned)`);
192
+ });
193
+ // === CONTRADICT (Phase 6.0.2) ===
194
+ program
195
+ .command('contradict <winnerId> <loserId>')
196
+ .description('Winner trace contradicts loser trace or script โ€” trace collapses, script archives (never deleted)')
197
+ .option('-r, --reason <text>', 'Why the loser no longer holds')
198
+ .option('--agent <name>', 'Who files the contradiction', 'cli')
199
+ .action(async (winnerId, loserId, options) => {
200
+ const s = getStore();
201
+ const result = await s.contradict(winnerId, loserId, {
202
+ reason: options.reason,
203
+ createdBy: options.agent === 'cli' ? 'human' : 'agent',
204
+ agent: options.agent,
205
+ });
206
+ if (result.proposalFiled) {
207
+ console.log(`โณ Loser is human/grounded-verified โ€” contradiction filed as a dream proposal for review.`);
208
+ return;
209
+ }
210
+ if (result.retargetedTo) {
211
+ console.log(`โš  Loser was already merged โ€” the collapse hit the merge target ${result.retargetedTo.slice(0, 8)}โ€ฆ`);
212
+ }
213
+ console.log(`โœ“ Contradiction recorded: ${result.contradiction.id}`);
214
+ if ('status' in result.loser) {
215
+ // Script loser (8.4): archived outright, not saillance-collapsed.
216
+ console.log(` Script "${result.loser.name}" archived (status: ${result.loser.status}) โ€” cues cancelled.`);
217
+ }
218
+ else {
219
+ console.log(` Loser saillance: ${result.loser.saillance}/100 (collapsed, still searchable)`);
220
+ }
221
+ });
222
+ // === LIST ===
223
+ program
224
+ .command('list')
225
+ .alias('traces')
226
+ .description('List mnemonic traces')
227
+ .option('-n, --limit <n>', 'Number of traces', '20')
228
+ .option('-l, --level <level>', 'Filter by state (0-4)')
229
+ .option('-t, --type <type>', 'Filter by type (episodic/semantic/procedural)')
230
+ .action(async (options) => {
231
+ const s = getStore();
232
+ const memories = await s.list({
233
+ limit: parseInt(options.limit),
234
+ level: options.level !== undefined ? parseInt(options.level) : undefined,
235
+ type: options.type,
236
+ });
237
+ if (memories.length === 0) {
238
+ console.log('No trace.');
239
+ return;
240
+ }
241
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
242
+ console.log(`\n๐Ÿ“‹ ${memories.length} trace(s):\n`);
243
+ for (const m of memories) {
244
+ console.log(`๐Ÿง  ${m.id.slice(0, 8)}... | ${states[m.currentLevel]} | ${m.directory}`);
245
+ console.log(` ${m.content.slice(0, 100)}${m.content.length > 100 ? '...' : ''}`);
246
+ console.log(` Recalls: ${m.recallCount} | Strength: ${m.saillance}`);
247
+ console.log();
248
+ }
249
+ });
250
+ // === DECAY ===
251
+ program
252
+ .command('decay')
253
+ .alias('consolidate')
254
+ .description('Update consolidation for every trace')
255
+ .action(async () => {
256
+ const s = getStore();
257
+ await s.updateDecay();
258
+ console.log('โœ“ Consolidation updated');
259
+ // Phase 8.4 โ€” drills rust from disuse; rusted ones archive themselves.
260
+ const { sweepDisusedScripts } = await import('../core/scripts.js');
261
+ const disuse = await sweepDisusedScripts(s);
262
+ if (disuse.archived.length || disuse.decaying.length) {
263
+ for (const { script, effective } of disuse.decaying) {
264
+ console.log(` ๐Ÿฅ€ ${script.name} โ€” disuse saillance ${effective} (stored ${script.saillance})`);
265
+ }
266
+ for (const script of disuse.archived) {
267
+ console.log(` ๐Ÿ—„๏ธ ${script.name} โ€” archived by disuse (cues cancelled, notice filed for \`dream review\`)`);
268
+ }
269
+ }
270
+ // Print a summary
271
+ const all = await s.list({ limit: 1000 });
272
+ const byLevel = [0, 0, 0, 0, 0];
273
+ for (const m of all) {
274
+ byLevel[m.currentLevel]++;
275
+ }
276
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
277
+ console.log('\nDistribution:');
278
+ console.log(` ๐ŸŸข ${states[0]}: ${byLevel[0]}`);
279
+ console.log(` ๐ŸŸก ${states[1]}: ${byLevel[1]}`);
280
+ console.log(` ๐ŸŸ  ${states[2]}: ${byLevel[2]}`);
281
+ console.log(` ๐Ÿ”ด ${states[3]}: ${byLevel[3]}`);
282
+ console.log(` โšซ ${states[4]}: ${byLevel[4]}`);
283
+ });
284
+ // === PHOTOGRAPHIC ===
285
+ program
286
+ .command('photo <id>')
287
+ .description('Toggle photographic mode (disables decay)')
288
+ .option('--off', 'Turn photographic mode off')
289
+ .action(async (id, options) => {
290
+ const s = getStore();
291
+ const memory = await s.setPhotographic(id, !options.off);
292
+ console.log(`โœ“ Photographic mode: ${memory.photographic ? '๐Ÿ”’ ON' : '๐Ÿ”“ off'}`);
293
+ console.log(` ID: ${memory.id}`);
294
+ });
295
+ // === SIMILAR ===
296
+ program
297
+ .command('similar <id>')
298
+ .description('Find similar traces to merge')
299
+ .option('-n, --limit <n>', 'Number of results', '5')
300
+ .option('-t, --threshold <n>', 'Score minimum (0-100)', '50')
301
+ .action(async (id, options) => {
302
+ const s = getStore();
303
+ const results = await s.findSimilar(id, {
304
+ limit: parseInt(options.limit),
305
+ threshold: parseInt(options.threshold),
306
+ });
307
+ if (results.length === 0) {
308
+ console.log('No similar trace found.');
309
+ return;
310
+ }
311
+ console.log(`\n๐Ÿ” ${results.length} trace(s) similaire(s):\n`);
312
+ for (const r of results) {
313
+ console.log(` ID: ${r.memory.id}`);
314
+ console.log(` Score: ${Math.round(r.score)} | Lieu: ${r.memory.directory}`);
315
+ console.log(` ${r.memory.content.slice(0, 120)}...`);
316
+ console.log();
317
+ }
318
+ });
319
+ // === MERGE ===
320
+ program
321
+ .command('merge <sourceId> <targetId>')
322
+ .description('Fusionner deux traces (source โ†’ target, source passe en niveau 4)')
323
+ .option('--auto', 'Fusionner le contenu via LLM')
324
+ .action(async (sourceId, targetId, options) => {
325
+ const s = getStore();
326
+ if (options.auto) {
327
+ console.log('โณ Fusion via LLM...');
328
+ }
329
+ const result = await s.merge(sourceId, targetId, { autoMergeContent: options.auto });
330
+ console.log(`โœ“ Merge done`);
331
+ console.log(` Source ${sourceId.slice(0, 8)}โ€ฆ โ†’ level 4 (merged)`);
332
+ console.log(` Target ${targetId.slice(0, 8)}โ€ฆ absorbed it`);
333
+ if (result.mergedContent) {
334
+ console.log(` Merged content: ${result.mergedContent.slice(0, 150)}โ€ฆ`);
335
+ }
336
+ });
337
+ // === UNMERGE (Phase 6.0.4) ===
338
+ program
339
+ .command('unmerge <sourceId>')
340
+ .description('Revert a merge: resurrect the source trace, restore the target\u2019s revised levels')
341
+ .action(async (sourceId) => {
342
+ const s = getStore();
343
+ const result = await s.unmerge(sourceId);
344
+ console.log(`โœ“ Unmerge done`);
345
+ console.log(` Source ${result.source.id.slice(0, 8)}โ€ฆ resurrected at level ${result.source.currentLevel}`);
346
+ console.log(` Target ${result.target.id.slice(0, 8)}โ€ฆ levels restored from the last revision`);
347
+ });
348
+ // === DELETE ===
349
+ program
350
+ .command('delete <id>')
351
+ .alias('forget')
352
+ .description('Forget a mnemonic trace')
353
+ .action(async (id) => {
354
+ const s = getStore();
355
+ await s.delete(id);
356
+ console.log(`โœ“ Trace forgotten: ${id}`);
357
+ });
358
+ // === STATUS ===
359
+ program
360
+ .command('status')
361
+ .description('Show the state of the memory palace')
362
+ .action(async () => {
363
+ const s = getStore();
364
+ const all = await s.list({ limit: 1000 });
365
+ console.log('\n๐Ÿง  ร‰tat de humemory:\n');
366
+ console.log(`Total traces: ${all.length}`);
367
+ const byLevel = [0, 0, 0, 0, 0];
368
+ for (const m of all) {
369
+ byLevel[m.currentLevel]++;
370
+ }
371
+ const states = ['Encoding', 'Consolidation', 'Stable', 'Fragile', 'Dormant'];
372
+ console.log('\nBy consolidation state:');
373
+ console.log(` ๐ŸŸข ${states[0]}: ${byLevel[0]}`);
374
+ console.log(` ๐ŸŸก ${states[1]}: ${byLevel[1]}`);
375
+ console.log(` ๐ŸŸ  ${states[2]}: ${byLevel[2]}`);
376
+ console.log(` ๐Ÿ”ด ${states[3]}: ${byLevel[3]}`);
377
+ console.log(` โšซ ${states[4]}: ${byLevel[4]}`);
378
+ const avgSaillance = all.reduce((sum, m) => sum + m.saillance, 0) / (all.length || 1);
379
+ const avgRecalls = all.reduce((sum, m) => sum + m.recallCount, 0) / (all.length || 1);
380
+ console.log(`\nMoyennes:`);
381
+ console.log(` Mnemonic strength: ${Math.round(avgSaillance)}/100`);
382
+ console.log(` Recalls per trace: ${avgRecalls.toFixed(1)}`);
383
+ });
384
+ // === IMPORT SESSION ===
385
+ program
386
+ .command('import-session <file>')
387
+ .description('Importer une session Claude Code et extraire les apprentissages')
388
+ .option('-d, --directory <dir>', 'Lieu mental du projet', process.cwd())
389
+ .option('-n, --max <n>', 'Maximum learnings to extract', '5')
390
+ .action(async (file, options) => {
391
+ const { readFileSync } = await import('fs');
392
+ const { processSession } = await import('../agent/claude-hook.js');
393
+ const raw = readFileSync(file, 'utf-8');
394
+ console.log('โณ Analyse de la session et extraction des apprentissages...');
395
+ const result = await processSession(raw, {
396
+ dbPath: DB_PATH,
397
+ directory: options.directory ? resolve(options.directory) : undefined,
398
+ maxLearnings: parseInt(options.max),
399
+ });
400
+ if (result.memoriesStored === 0) {
401
+ console.log('No learning found in this session.');
402
+ return;
403
+ }
404
+ console.log(`\nโœ“ ${result.memoriesStored} learning(s) stored:\n`);
405
+ for (const l of result.learnings) {
406
+ console.log(` โ€ข ${l}`);
407
+ }
408
+ });
409
+ // === INTENT (prospective memory) ===
410
+ const intent = program
411
+ .command('intent')
412
+ .description('Open loops (prospective memory) โ€” arm, list, close');
413
+ intent
414
+ .command('add <content>')
415
+ .description('Arm an open loop')
416
+ .option('-d, --directory <dir>', 'Mental place (defaults to cwd)')
417
+ .option('-c, --cue <cue...>', "Trigger โ€” 'time:2026-12-01', 'cron:0 9 * * 1', 'event:file_open:src/a.ts'")
418
+ .option('-e, --expires <date>', 'Deadline (ISO) past which the loop expires')
419
+ .action(async (content, options) => {
420
+ const s = getStore();
421
+ let cues = [];
422
+ try {
423
+ cues = (options.cue ?? []).map((raw) => parseCueArg(raw));
424
+ }
425
+ catch (err) {
426
+ console.error(`โœ— ${err instanceof Error ? err.message : err}`);
427
+ process.exitCode = 1;
428
+ return;
429
+ }
430
+ let expiresAt;
431
+ if (options.expires) {
432
+ expiresAt = new Date(options.expires);
433
+ if (Number.isNaN(expiresAt.getTime())) {
434
+ console.error(`x invalid deadline: ${options.expires}`);
435
+ process.exitCode = 1;
436
+ return;
437
+ }
438
+ }
439
+ // The mental place is resolved to absolute: the SessionStart hook looks up by
440
+ // `process.cwd()`, so a loop armed on './src/auth' would never surface โ€” a
441
+ // perfectly silent failure.
442
+ const intention = await s.addIntention({
443
+ content,
444
+ directory: resolve(options.directory ?? process.cwd()),
445
+ expiresAt,
446
+ }, cues);
447
+ console.log(`\n๐Ÿ” Loop armed โ€” ${loopId(intention.id)}`);
448
+ console.log(` ${intention.content}`);
449
+ console.log(` Place: ${intention.directory}`);
450
+ if (expiresAt)
451
+ console.log(` Due: ${expiresAt.toISOString()}`);
452
+ for (const spec of cues)
453
+ console.log(` Cue: ${formatTriggerSpec(spec)}`);
454
+ console.log(`\n To close: mention "Closes ${loopId(intention.id)}" in a commit\n`);
455
+ });
456
+ intent
457
+ .command('list')
458
+ .alias('ls')
459
+ .description('List loops')
460
+ .option('-s, --status <status>', 'armed | fired | closed | expired', 'armed')
461
+ .option('-d, --directory <dir>', 'Filter by mental place')
462
+ .option('-n, --limit <n>', 'Maximum count', '20')
463
+ .option('-a, --all', 'Every status')
464
+ .action(async (options) => {
465
+ const s = getStore();
466
+ const intentions = await s.listIntentions({
467
+ status: options.all ? undefined : options.status,
468
+ directory: options.directory ? resolve(options.directory) : undefined,
469
+ limit: parseInt(options.limit),
470
+ });
471
+ if (intentions.length === 0) {
472
+ console.log('No loop.');
473
+ return;
474
+ }
475
+ const icons = {
476
+ armed: '๐Ÿ”',
477
+ fired: 'โฐ',
478
+ closed: 'โœ…',
479
+ expired: '๐Ÿ’ค',
480
+ };
481
+ console.log(`\n${intentions.length} loop(s):\n`);
482
+ for (const i of intentions) {
483
+ const cues = await s.listCues({ intentionId: i.id });
484
+ console.log(`${icons[i.status]} ${loopId(i.id)} | ${i.status} | ${i.directory}`);
485
+ console.log(` ${i.content}`);
486
+ if (cues.length) {
487
+ console.log(` Cues: ${cues.map((c) => `${formatTriggerSpec(c.triggerSpec)} (${c.status})`).join(', ')}`);
488
+ }
489
+ if (i.expiresAt)
490
+ console.log(` Due: ${i.expiresAt.toISOString()}`);
491
+ if (i.closedByCommit)
492
+ console.log(` Closed by: ${i.closedByCommit}`);
493
+ console.log();
494
+ }
495
+ });
496
+ /** Resolves a short id (`loop-a1b2c3d4`, `a1b2c3d4`) to an intention. */
497
+ async function resolveIntentionArg(s, arg) {
498
+ const short = arg.replace(/^loop-/i, '');
499
+ const all = await s.listIntentions({ limit: 500 });
500
+ const found = matchIntentionByShortId(all, short);
501
+ if (!found) {
502
+ // Ambiguous or unknown prefix: no guessing, closing the wrong loop is worse.
503
+ console.error(`x no single loop matches "${arg}"`);
504
+ process.exitCode = 1;
505
+ }
506
+ return found;
507
+ }
508
+ intent
509
+ .command('close <id>')
510
+ .description('Close a loop (accepts loop-abc12345 or the bare prefix)')
511
+ .option('--commit <sha>', 'SHA of the commit that closed the loop')
512
+ .action(async (id, options) => {
513
+ const s = getStore();
514
+ const found = await resolveIntentionArg(s, id);
515
+ if (!found)
516
+ return;
517
+ const closed = await s.updateIntentionStatus(found.id, 'closed', { closedByCommit: options.commit });
518
+ for (const cue of await s.listCues({ intentionId: found.id, status: 'armed' })) {
519
+ await s.updateCueStatus(cue.id, 'cancelled');
520
+ }
521
+ console.log(`\nโœ… ${loopId(closed.id)} closed โ€” ${closed.content}\n`);
522
+ });
523
+ intent
524
+ .command('fire <id>')
525
+ .description('Force a loop to wake (debug)')
526
+ .action(async (id) => {
527
+ const s = getStore();
528
+ const found = await resolveIntentionArg(s, id);
529
+ if (!found)
530
+ return;
531
+ const fired = await s.updateIntentionStatus(found.id, 'fired');
532
+ console.log(`\nโฐ ${loopId(fired.id)} woken โ€” ${fired.content}\n`);
533
+ });
534
+ intent
535
+ .command('resolve')
536
+ .description('Sweep: expire overdue loops, fire deadlines that have come due')
537
+ .action(async () => {
538
+ const s = getStore();
539
+ const resolver = new SqliteCueResolver(s);
540
+ const expired = await resolver.expireStale();
541
+ const fired = [];
542
+ for (const cue of await resolver.resolveTimeCues()) {
543
+ fired.push(await resolver.fire(cue.id));
544
+ }
545
+ console.log(`\n๐Ÿ’ค ${expired} expired | โฐ ${fired.length} woken`);
546
+ for (const i of fired)
547
+ console.log(` ${loopId(i.id)} โ€” ${i.content}`);
548
+ console.log();
549
+ });
550
+ // === SCRIPT (Phase 8.3) ===
551
+ const script = program
552
+ .command('script')
553
+ .description('Cognitive scripts (drills) โ€” cue-triggered procedures');
554
+ /** Resolves an unambiguous script id prefix (same rule as dream review). */
555
+ async function findScriptByPrefix(s, prefix) {
556
+ const all = await s.listScripts({ status: ['draft', 'active', 'archived'], limit: 500 });
557
+ const hits = all.filter((x) => x.id.startsWith(prefix));
558
+ return hits.length === 1 ? hits[0] : null;
559
+ }
560
+ script
561
+ .command('add <name>')
562
+ .description('Add a drill (human-authored โ†’ active immediately, 8.3 gate)')
563
+ .requiredOption('--steps <steps...>', 'Ordered drill steps')
564
+ .option('--description <text>', 'One-line summary for the context header', '')
565
+ .option('-d, --directory <dir>', 'Mental place (defaults to cwd)')
566
+ .option('-c, --cue <cue...>', "Trigger โ€” 'cron:0 9 * * 1', 'event:branch_switch:main'")
567
+ .option('--pinned', 'Exempt from disuse decay (8.4)', false)
568
+ .action(async (name, options) => {
569
+ const s = getStore();
570
+ let cues = [];
571
+ try {
572
+ cues = (options.cue ?? []).map((raw) => parseCueArg(raw));
573
+ }
574
+ catch (err) {
575
+ console.error(`โœ— ${err instanceof Error ? err.message : err}`);
576
+ process.exitCode = 1;
577
+ return;
578
+ }
579
+ try {
580
+ const created = await s.addScript({
581
+ name,
582
+ description: options.description || name,
583
+ steps: options.steps,
584
+ directory: resolve(options.directory ?? process.cwd()),
585
+ pinned: options.pinned,
586
+ source: 'human',
587
+ }, cues);
588
+ console.log(`\n๐Ÿ“‹ Script active โ€” ${created.id.slice(0, 8)} (${created.name})`);
589
+ created.steps.forEach((step, i) => console.log(` ${i + 1}. ${step}`));
590
+ console.log(` Place: ${created.directory}${created.pinned ? ' ยท pinned' : ''}`);
591
+ for (const spec of cues)
592
+ console.log(` Cue: ${formatTriggerSpec(spec)}`);
593
+ }
594
+ catch (err) {
595
+ console.error(`โœ— ${err instanceof Error ? err.message : err}`);
596
+ process.exitCode = 1;
597
+ }
598
+ });
599
+ script
600
+ .command('list')
601
+ .alias('ls')
602
+ .description('List drills')
603
+ .option('-s, --status <status>', 'draft | active | archived', 'active')
604
+ .option('-d, --directory <dir>', 'Filter by mental place')
605
+ .option('-a, --all', 'Every status')
606
+ .action(async (options) => {
607
+ const s = getStore();
608
+ const scripts = await s.listScripts({
609
+ status: options.all ? undefined : options.status,
610
+ directory: options.directory ? resolve(options.directory) : undefined,
611
+ limit: 50,
612
+ });
613
+ if (!scripts.length) {
614
+ console.log('No script.');
615
+ return;
616
+ }
617
+ const icons = { draft: '๐Ÿ“', active: '๐Ÿ“‹', archived: '๐Ÿ—„๏ธ' };
618
+ for (const sc of scripts) {
619
+ console.log(`\n${icons[sc.status]} ${sc.id.slice(0, 8)} | ${sc.name} (${sc.status})`);
620
+ console.log(` ${sc.description}`);
621
+ console.log(` ${sc.steps.length} steps ยท fired ${sc.fireCount}ร— ยท saillance ${sc.saillance}${sc.pinned ? ' ยท pinned' : ''}`);
622
+ console.log(` ${sc.directory}`);
623
+ }
624
+ });
625
+ for (const verb of ['activate', 'archive']) {
626
+ script
627
+ .command(`${verb} <id>`)
628
+ .description(verb === 'activate' ? 'draft โ†’ active (human gate)' : 'Archive a drill (cancels its cues)')
629
+ .action(async (id) => {
630
+ const s = getStore();
631
+ const target = await findScriptByPrefix(s, id);
632
+ if (!target) {
633
+ console.error(`โœ— No script matches ${id}`);
634
+ process.exitCode = 1;
635
+ return;
636
+ }
637
+ const status = verb === 'activate' ? 'active' : 'archived';
638
+ await s.updateScriptStatus(target.id, status);
639
+ console.log(`โœ“ Script ${target.name} โ†’ ${status}`);
640
+ });
641
+ }
642
+ script
643
+ .command('fire <id>')
644
+ .description('Manually fire a drill (testing + saillance bump)')
645
+ .action(async (id) => {
646
+ const s = getStore();
647
+ const target = await findScriptByPrefix(s, id);
648
+ if (!target) {
649
+ console.error(`โœ— No script matches ${id}`);
650
+ process.exitCode = 1;
651
+ return;
652
+ }
653
+ if (target.status !== 'active') {
654
+ console.error(`โœ— Script ${target.name} is ${target.status} โ€” only active drills fire`);
655
+ process.exitCode = 1;
656
+ return;
657
+ }
658
+ const fired = await s.markScriptFired(target.id);
659
+ console.log(`\n๐Ÿ“‹ ${fired.name} โ€” fired ${fired.fireCount}ร—, saillance ${fired.saillance}`);
660
+ fired.steps.forEach((step, i) => console.log(` ${i + 1}. ${step}`));
661
+ });
662
+ // === EMBED (Phase 7.2) ===
663
+ const embed = program.command('embed').description('Vector index maintenance (Phase 7)');
664
+ embed
665
+ .command('backfill')
666
+ .description('Embed every trace missing a vector for the current model (idempotent)')
667
+ .option('-n, --limit <n>', 'Max traces per run', '500')
668
+ .option('--dtype <dtype>', 'Model quantization (q8|fp32 โ€” fp16 broken on win32)', 'q8')
669
+ .option('--model <name>', 'small|base|bge-m3 (default bge-m3 since 7.5 round 4)', 'bge-m3')
670
+ .action(async (options) => {
671
+ const s = getStore();
672
+ const { OnnxEmbedder, embeddableText, E5_MODEL_ID, E5_BASE_MODEL_ID, BGE_M3_MODEL_ID } = await import('../core/embeddings.js');
673
+ const MODELS = { small: E5_MODEL_ID, base: E5_BASE_MODEL_ID, 'bge-m3': BGE_M3_MODEL_ID };
674
+ const model = MODELS[options.model] ?? BGE_M3_MODEL_ID;
675
+ const embedder = new OnnxEmbedder({ dtype: options.dtype, model });
676
+ console.log(`โณ Model: ${embedder.modelId} (first run downloads ~120MB into data/models/)โ€ฆ`);
677
+ const missing = await s.listMissingEmbeddings(embedder.modelId, parseInt(options.limit));
678
+ if (!missing.length) {
679
+ console.log('โœ“ Nothing to embed โ€” the index is current.');
680
+ return;
681
+ }
682
+ console.log(`โณ Embedding ${missing.length} trace(s)โ€ฆ`);
683
+ const BATCH = 32;
684
+ let done = 0;
685
+ for (let i = 0; i < missing.length; i += BATCH) {
686
+ const batch = missing.slice(i, i + BATCH);
687
+ const vectors = await embedder.embed(batch.map(embeddableText));
688
+ for (let k = 0; k < batch.length; k++) {
689
+ await s.setEmbedding(batch[k].id, embedder.modelId, vectors[k]);
690
+ }
691
+ done += batch.length;
692
+ console.log(` ${done}/${missing.length}`);
693
+ }
694
+ console.log(`โœ“ Backfill complete: ${done} trace(s) embedded.`);
695
+ });
696
+ // === DREAM (Phase 6.1) ===
697
+ const dream = program.command('dream').description('Cross-session consolidation (dreaming)');
698
+ dream
699
+ .command('run', { isDefault: true })
700
+ .description('Detect recurring patterns across sessions/agents and file proposals')
701
+ .option('--clusterer <kind>', 'keyword (default โ€” 7.5 round 3: vector P 0.71 too noisy) | vector (needs the model)', 'keyword')
702
+ .option('--window <days>', 'Collection window in days (default 30; raise for old traces)', undefined)
703
+ .action(async (options) => {
704
+ const s = getStore();
705
+ const { runDreamer, KeywordClusterer } = await import('../core/dreamer.js');
706
+ let clusterer = new KeywordClusterer();
707
+ if (options.clusterer === 'vector') {
708
+ const { OnnxEmbedder } = await import('../core/embeddings.js');
709
+ const { VectorClusterer } = await import('../core/vector-clusterer.js');
710
+ clusterer = new VectorClusterer(new OnnxEmbedder(), s);
711
+ console.log('โณ Vector clustering (embeds missing traces in batch first)โ€ฆ');
712
+ }
713
+ const report = await runDreamer({
714
+ store: s,
715
+ clusterer,
716
+ windowDays: options.window ? parseInt(options.window) : undefined,
717
+ });
718
+ console.log(`\n๐ŸŒ™ Dream report`);
719
+ console.log(` Traces considered: ${report.considered}`);
720
+ console.log(` Clusters found: ${report.clusters}`);
721
+ console.log(` Proposals filed: ${report.filed} (${report.expired} expired)`);
722
+ if (report.staleLoopCandidates)
723
+ console.log(` Stale loops spotted: ${report.staleLoopCandidates}`);
724
+ if (report.scriptCandidates)
725
+ console.log(` Script candidates drafted: ${report.scriptCandidates}`);
726
+ const pending = report.proposals.length;
727
+ if (pending)
728
+ console.log(`\n ${pending} dream(s) pending โ€” run \`pnpm cli dream review\`.`);
729
+ });
730
+ dream
731
+ .command('review')
732
+ .description('List pending dream proposals')
733
+ .action(async () => {
734
+ const s = getStore();
735
+ const pending = await s.listDreamProposals({ status: 'pending' });
736
+ if (!pending.length) {
737
+ console.log('No dream pending.');
738
+ return;
739
+ }
740
+ console.log(`\n๐ŸŒ™ ${pending.length} dream(s) pending:\n`);
741
+ for (const p of pending) {
742
+ const payload = JSON.parse(p.payload);
743
+ console.log(` [${p.kind}] ${p.id.slice(0, 8)}โ€ฆ โ€” confidence ${p.confidence}`);
744
+ if (payload.samples)
745
+ for (const s2 of payload.samples)
746
+ console.log(` ยท ${s2}`);
747
+ if (payload.content)
748
+ console.log(` ยท ${payload.content}`);
749
+ if (p.kind === 'script_candidate') {
750
+ console.log(` "${payload.name}" in ${payload.directory} โ€” ${payload.description}`);
751
+ payload.steps.forEach((step, i) => console.log(` ${i + 1}. ${step}`));
752
+ if (payload.truncatedSteps)
753
+ console.log(` โ€ฆ more corrections than steps shown (capped)`);
754
+ }
755
+ if (p.kind === 'script_archived') {
756
+ if (payload.reason === 'contradiction') {
757
+ console.log(` "${payload.name}" โ€” contradicted by: ${payload.winnerContent}`);
758
+ }
759
+ else {
760
+ console.log(` "${payload.name}" โ€” saillance ${payload.storedSaillance} โ†’ effective ${payload.effectiveSaillance} (disuse)`);
761
+ }
762
+ }
763
+ if (payload.expiresAt || p.expiresAt)
764
+ console.log(` expires ${p.expiresAt?.toISOString().split('T')[0]}`);
765
+ console.log();
766
+ }
767
+ });
768
+ for (const verb of ['approve', 'reject']) {
769
+ dream
770
+ .command(`${verb} <id>`)
771
+ .description(`${verb === 'approve' ? 'Apply' : 'Archive'} a dream proposal (human gate)`)
772
+ .action(async (id) => {
773
+ const s = getStore();
774
+ const pending = await s.listDreamProposals({ status: 'pending', includeExpired: true });
775
+ const target = pending.find((p) => p.id === id || p.id.startsWith(id));
776
+ if (!target) {
777
+ console.error(`โœ— No pending dream matches ${id}`);
778
+ process.exit(1);
779
+ }
780
+ if (verb === 'approve') {
781
+ const { applyDreamProposal } = await import('../core/dreamer.js');
782
+ const effect = await applyDreamProposal(s, target);
783
+ await s.resolveDreamProposal(target.id, 'approved');
784
+ console.log(`โœ“ Dream approved โ€” ${effect}`);
785
+ }
786
+ else {
787
+ await s.resolveDreamProposal(target.id, 'rejected');
788
+ console.log(`โœ“ Dream rejected โ€” it will not resurface unless the pattern recurs.`);
789
+ }
790
+ });
791
+ }
792
+ // Parse and run
793
+ program.parse();
794
+ // Cleanup
795
+ process.on('exit', () => {
796
+ if (store)
797
+ store.close();
798
+ });