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