coucou-brain 0.0.0-stage → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +156 -2
- package/brain.config.json +25 -0
- package/dist/archive.d.ts +20 -0
- package/dist/archive.js +131 -0
- package/dist/chunk.d.ts +14 -0
- package/dist/chunk.js +59 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +1915 -0
- package/dist/collect.d.ts +84 -0
- package/dist/collect.js +592 -0
- package/dist/config.d.ts +41 -0
- package/dist/config.js +65 -0
- package/dist/coverage.d.ts +22 -0
- package/dist/coverage.js +120 -0
- package/dist/desktop-routing.d.ts +25 -0
- package/dist/desktop-routing.js +70 -0
- package/dist/digest.d.ts +183 -0
- package/dist/digest.js +458 -0
- package/dist/elements.d.ts +144 -0
- package/dist/elements.js +363 -0
- package/dist/fts.d.ts +46 -0
- package/dist/fts.js +364 -0
- package/dist/galaxy-layout.d.ts +45 -0
- package/dist/galaxy-layout.js +302 -0
- package/dist/graph.d.ts +25 -0
- package/dist/graph.js +341 -0
- package/dist/manifest.d.ts +65 -0
- package/dist/manifest.js +220 -0
- package/dist/mask.d.ts +21 -0
- package/dist/mask.js +164 -0
- package/dist/mcp/server.d.ts +1 -0
- package/dist/mcp/server.js +296 -0
- package/dist/mochis.d.ts +142 -0
- package/dist/mochis.js +662 -0
- package/dist/node-page.d.ts +29 -0
- package/dist/node-page.js +132 -0
- package/dist/patterns.d.ts +130 -0
- package/dist/patterns.js +553 -0
- package/dist/project-files.d.ts +27 -0
- package/dist/project-files.js +215 -0
- package/dist/rawindex.d.ts +108 -0
- package/dist/rawindex.js +454 -0
- package/dist/records.d.ts +24 -0
- package/dist/records.js +92 -0
- package/dist/recurrences.d.ts +24 -0
- package/dist/recurrences.js +139 -0
- package/dist/stats.d.ts +16 -0
- package/dist/stats.js +143 -0
- package/dist/suggest.d.ts +28 -0
- package/dist/suggest.js +59 -0
- package/dist/usage.d.ts +60 -0
- package/dist/usage.js +219 -0
- package/dist/utils.d.ts +23 -0
- package/dist/utils.js +88 -0
- package/dist/write.d.ts +43 -0
- package/dist/write.js +830 -0
- package/hooks/brain-prompt.js +472 -0
- package/hooks/brain-session-start.js +334 -0
- package/hooks/package.json +1 -0
- package/package.json +59 -4
- package/scripts/pin-node.cjs +17 -0
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1915 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* brain CLI — entry point
|
|
4
|
+
*
|
|
5
|
+
* brain ingest [--since YYYY-MM-DD] [--project <name>] [--limit <n>] [--dry-run] [--include-subagents]
|
|
6
|
+
* [--session <id...>] [--repo <name...>] [--repos-only] [--sessions-only]
|
|
7
|
+
* brain stats
|
|
8
|
+
*/
|
|
9
|
+
import { Command } from "commander";
|
|
10
|
+
import crypto from "node:crypto";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import { spawnSync as _spawnSync } from "node:child_process";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import os from "node:os";
|
|
15
|
+
import { loadConfig } from "./config.js";
|
|
16
|
+
import { expandHome, toSlug } from "./utils.js";
|
|
17
|
+
import { discoverSessions, discoverRepos, readSession, collectRepo, collectClaudeExport, formatConversationAsSessionCondensed, } from "./collect.js";
|
|
18
|
+
import { Manifest } from "./manifest.js";
|
|
19
|
+
import { digestSessionWithRetry, digestRepo, digestPromptHash } from "./digest.js";
|
|
20
|
+
import { ensureBrainDir, writeRecord, recordFilePath, updateProjectFromSession, updateProjectFromRepo, updateLessons, updateLouis, updatePeople, validateAllLinks, collectAllIds, rebuildIndex, rebuildAllPages, gitCommit, getOpenElements, } from "./write.js";
|
|
21
|
+
import { computeStats } from "./stats.js";
|
|
22
|
+
import { runCoverage, formatCoverageResult } from "./coverage.js";
|
|
23
|
+
import { rebuildFts, writeHooksConfig, appendCorrection } from "./fts.js";
|
|
24
|
+
import { maskSecrets } from "./mask.js";
|
|
25
|
+
import { FIXED_DOMAINS, getKnownProjectSlugs, remapDesktopProjects, } from "./desktop-routing.js";
|
|
26
|
+
const program = new Command();
|
|
27
|
+
program
|
|
28
|
+
.name("brain")
|
|
29
|
+
.description("Coucou Brain — digest Claude Code sessions and repos into a Markdown knowledge base")
|
|
30
|
+
.version("0.7.0");
|
|
31
|
+
// ── safety guard ──────────────────────────────────────────────────────────────
|
|
32
|
+
function assertNoRemote(brainPath) {
|
|
33
|
+
const expanded = expandHome(brainPath);
|
|
34
|
+
const result = _spawnSync("git", ["-C", expanded, "remote"], { encoding: "utf8" });
|
|
35
|
+
if (result.stdout?.trim()) {
|
|
36
|
+
console.error("❌ CoucouBrain a un remote git configuré (" +
|
|
37
|
+
result.stdout.trim().split("\n").join(", ") +
|
|
38
|
+
").\n" +
|
|
39
|
+
" Ce repo contient de la mémoire de travail en clair — retire le remote avant de continuer :\n" +
|
|
40
|
+
" git -C " + expanded + " remote remove <nom>");
|
|
41
|
+
process.exit(1);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
// ── ingest ────────────────────────────────────────────────────────────────────
|
|
45
|
+
program
|
|
46
|
+
.command("ingest")
|
|
47
|
+
.description("Digest sessions and repos into ~/CoucouBrain/")
|
|
48
|
+
.option("--since <date>", "Only sessions after this date (YYYY-MM-DD)")
|
|
49
|
+
.option("--project <name>", "Only process sessions matching this project name")
|
|
50
|
+
.option("--session <id...>", "Only process these session UUIDs (space-separated or repeated)")
|
|
51
|
+
.option("--repo <name...>", "Only process repos whose path contains this name")
|
|
52
|
+
.option("--limit <n>", "Max number of sessions to process", parseInt)
|
|
53
|
+
.option("--dry-run", "Show what would be processed without calling the model")
|
|
54
|
+
.option("--include-subagents", "Also process subagent sessions")
|
|
55
|
+
.option("--repos-only", "Only process repos, skip sessions")
|
|
56
|
+
.option("--sessions-only", "Only process sessions, skip repos")
|
|
57
|
+
.option("--force", "Re-digest sessions even if already processed with the same prompt version")
|
|
58
|
+
.option("--claude-export <path>", "Ingest a Claude.ai data export (zip or folder with conversations.json)")
|
|
59
|
+
.action(async (opts) => {
|
|
60
|
+
const config = loadConfig();
|
|
61
|
+
assertNoRemote(config.brainPath);
|
|
62
|
+
const manifest = new Manifest(config.brainPath);
|
|
63
|
+
const currentPromptHash = digestPromptHash();
|
|
64
|
+
if (!opts.dryRun) {
|
|
65
|
+
ensureBrainDir(config);
|
|
66
|
+
}
|
|
67
|
+
// Collect repo paths for file normalization
|
|
68
|
+
const allRepoPaths = [
|
|
69
|
+
...config.repoPaths.map((p) => expandHome(p)),
|
|
70
|
+
...(config.additionalRepoPaths ?? []).map((p) => expandHome(p)),
|
|
71
|
+
];
|
|
72
|
+
// ── Sessions ──────────────────────────────────────────────────────────────
|
|
73
|
+
if (!opts.reposOnly && !opts.claudeExport) {
|
|
74
|
+
const allDiscovered = discoverSessions(config, {
|
|
75
|
+
includeSubagents: opts.includeSubagents,
|
|
76
|
+
sinceDate: opts.since,
|
|
77
|
+
projectFilter: opts.project,
|
|
78
|
+
});
|
|
79
|
+
const activeSessions = allDiscovered.filter((s) => s.isActive);
|
|
80
|
+
const discovered = allDiscovered.filter((s) => !s.isActive);
|
|
81
|
+
if (activeSessions.length > 0) {
|
|
82
|
+
console.log(`\n ⏭ ${activeSessions.length} session(s) active(s) ignorée(s) (modifiée(s) il y a < ${config.activeSessionMinutes ?? 30} min) :`);
|
|
83
|
+
for (const s of activeSessions) {
|
|
84
|
+
console.log(` ${s.id.slice(0, 8)}… ${s.projectPath.slice(-40)}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
for (const s of discovered) {
|
|
88
|
+
manifest.upsertSession({
|
|
89
|
+
id: s.id,
|
|
90
|
+
project_path: s.projectPath,
|
|
91
|
+
jsonl_path: s.jsonlPath,
|
|
92
|
+
hash: s.hash,
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
const discoveredIds = new Set(discovered.map((d) => d.id));
|
|
96
|
+
// Date lookup for chronological sort (oldest→newest so latest session wins etatActuel)
|
|
97
|
+
const discoveredDateById = new Map(discovered.map((d) => [d.id, d.date]));
|
|
98
|
+
let pending = manifest
|
|
99
|
+
.getPendingSessions()
|
|
100
|
+
.filter((s) => discoveredIds.has(s.id))
|
|
101
|
+
.sort((a, b) => {
|
|
102
|
+
const da = discoveredDateById.get(a.id) ?? "0";
|
|
103
|
+
const db = discoveredDateById.get(b.id) ?? "0";
|
|
104
|
+
return da.localeCompare(db);
|
|
105
|
+
});
|
|
106
|
+
// --session filter
|
|
107
|
+
if (opts.session?.length) {
|
|
108
|
+
const ids = opts.session;
|
|
109
|
+
pending = pending.filter((s) => ids.some((id) => s.id === id || s.id.startsWith(id)));
|
|
110
|
+
for (const id of ids) {
|
|
111
|
+
const done = manifest.getAllSessions().find((s) => (s.id === id || s.id.startsWith(id)) && s.status === "done");
|
|
112
|
+
if (done && !pending.find((p) => p.id === done.id)) {
|
|
113
|
+
// Skip if prompt unchanged and not --force
|
|
114
|
+
if (!opts.force && manifest.isUpToDate(done.id, currentPromptHash)) {
|
|
115
|
+
console.log(` ⏭ ${done.id.slice(0, 8)}… déjà digéré avec le même prompt (--force pour forcer)`);
|
|
116
|
+
continue;
|
|
117
|
+
}
|
|
118
|
+
manifest.resetSessionToPending(done.id);
|
|
119
|
+
pending.push({ ...done, status: "pending" });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const toProcess = opts.limit ? pending.slice(0, opts.limit) : pending;
|
|
124
|
+
console.log("\n📚 Sessions");
|
|
125
|
+
console.log(` Découvertes : ${discovered.length}`);
|
|
126
|
+
console.log(` À traiter : ${pending.length}`);
|
|
127
|
+
if (opts.limit)
|
|
128
|
+
console.log(` Limitées à : ${toProcess.length}`);
|
|
129
|
+
if (opts.dryRun) {
|
|
130
|
+
console.log("\n--- DRY RUN : sessions ---");
|
|
131
|
+
let totalTokens = 0;
|
|
132
|
+
for (const s of toProcess) {
|
|
133
|
+
const disc = discovered.find((d) => d.id === s.id);
|
|
134
|
+
try {
|
|
135
|
+
const condensed = readSession(s.jsonl_path);
|
|
136
|
+
totalTokens += condensed.estimatedTokens;
|
|
137
|
+
const maskedCount = condensed.masked.reduce((n, m) => n + m.count, 0);
|
|
138
|
+
const rawKb = (disc.sizeBytes / 1024).toFixed(0);
|
|
139
|
+
const tokens = condensed.estimatedTokens.toLocaleString();
|
|
140
|
+
console.log(` ${disc.date} ${s.project_path.slice(-45).padEnd(47)}` +
|
|
141
|
+
` ~${tokens} tokens ${rawKb}KB raw` +
|
|
142
|
+
(maskedCount > 0 ? ` 🔒 ${maskedCount} masqués` : ""));
|
|
143
|
+
}
|
|
144
|
+
catch (e) {
|
|
145
|
+
console.log(` ${s.id.slice(0, 8)} [erreur: ${e.message.slice(0, 60)}]`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
console.log(`\n Total estimé : ~${totalTokens.toLocaleString()} tokens condensés`);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
const maskedByType = {};
|
|
152
|
+
let doneCount = 0;
|
|
153
|
+
let failCount = 0;
|
|
154
|
+
for (const s of toProcess) {
|
|
155
|
+
const idx = doneCount + failCount + 1;
|
|
156
|
+
console.log(`\n [${idx}/${toProcess.length}] ${s.project_path.slice(-50)} / ${s.id.slice(0, 8)}…`);
|
|
157
|
+
// Track record file path so we can delete it on failure
|
|
158
|
+
let recordFileCreated = null;
|
|
159
|
+
try {
|
|
160
|
+
const condensed = readSession(s.jsonl_path);
|
|
161
|
+
console.log(` ~${condensed.estimatedTokens.toLocaleString()} tokens condensés`);
|
|
162
|
+
// Skip near-empty sessions — not enough content for meaningful digest
|
|
163
|
+
if (condensed.estimatedTokens < 30) {
|
|
164
|
+
console.log(` ⏭ session quasi vide, ignorée`);
|
|
165
|
+
manifest.markSessionIgnored(s.id);
|
|
166
|
+
continue;
|
|
167
|
+
}
|
|
168
|
+
for (const m of condensed.masked) {
|
|
169
|
+
maskedByType[m.type] = (maskedByType[m.type] ?? 0) + m.count;
|
|
170
|
+
}
|
|
171
|
+
const openElements = getOpenElements(config);
|
|
172
|
+
if (openElements.length > 0) {
|
|
173
|
+
console.log(` ${openElements.length} éléments ouverts transmis au modèle`);
|
|
174
|
+
}
|
|
175
|
+
const digest = await digestSessionWithRetry(condensed, config, openElements);
|
|
176
|
+
// Fallback: if LLM returned no projects, use the session's project path hint
|
|
177
|
+
if (digest.projects.length === 0) {
|
|
178
|
+
digest.projects = [condensed.projectNameHint];
|
|
179
|
+
}
|
|
180
|
+
const primaryProject = digest.projects[0];
|
|
181
|
+
// Build current valid IDs (before writing this record)
|
|
182
|
+
const allIds = collectAllIds(config);
|
|
183
|
+
const recordId = writeRecord(condensed, digest, config, allRepoPaths);
|
|
184
|
+
recordFileCreated = recordFilePath(config, condensed.id, condensed.date, primaryProject);
|
|
185
|
+
// Pre-register all IDs this session will produce
|
|
186
|
+
allIds.add(recordId);
|
|
187
|
+
for (const proj of digest.projects) {
|
|
188
|
+
allIds.add(`proj_${toSlug(proj)}`);
|
|
189
|
+
}
|
|
190
|
+
for (const name of (digest.people ?? [])) {
|
|
191
|
+
allIds.add(`people_${toSlug(name)}`);
|
|
192
|
+
}
|
|
193
|
+
allIds.add("lessons");
|
|
194
|
+
allIds.add("louis");
|
|
195
|
+
// Merge into project pages
|
|
196
|
+
for (const proj of digest.projects) {
|
|
197
|
+
const slug = toSlug(proj);
|
|
198
|
+
console.log(` → merge dans projects/${slug}.md`);
|
|
199
|
+
updateProjectFromSession(slug, digest, condensed.date, recordId, config, allIds);
|
|
200
|
+
}
|
|
201
|
+
// Update global pages
|
|
202
|
+
updateLessons(digest, condensed.date, recordId, config, allIds);
|
|
203
|
+
updateLouis(digest, condensed.date, recordId, config, allIds);
|
|
204
|
+
updatePeople(digest, condensed.date, recordId, config, allIds);
|
|
205
|
+
manifest.markSessionDone(s.id, recordId, digest.projects, currentPromptHash);
|
|
206
|
+
doneCount++;
|
|
207
|
+
console.log(` ✓ ${recordId}`);
|
|
208
|
+
}
|
|
209
|
+
catch (e) {
|
|
210
|
+
console.error(` ✗ Échec: ${e.message.slice(0, 200)}`);
|
|
211
|
+
manifest.markSessionFailed(s.id);
|
|
212
|
+
failCount++;
|
|
213
|
+
// Clean up: delete record file if it was created before the failure
|
|
214
|
+
if (recordFileCreated && fs.existsSync(recordFileCreated)) {
|
|
215
|
+
fs.unlinkSync(recordFileCreated);
|
|
216
|
+
console.log(` 🗑 fiche supprimée (échec propre)`);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
console.log(`\n Sessions : ${doneCount} OK, ${failCount} échec(s)`);
|
|
221
|
+
if (Object.keys(maskedByType).length > 0) {
|
|
222
|
+
console.log(" Secrets masqués :", JSON.stringify(maskedByType));
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
// ── Repos ─────────────────────────────────────────────────────────────────
|
|
227
|
+
if (!opts.sessionsOnly && !opts.claudeExport) {
|
|
228
|
+
const repos = discoverRepos(config);
|
|
229
|
+
console.log(`\n🗂 Repos : ${repos.length} découverts`);
|
|
230
|
+
for (const repoPath of repos) {
|
|
231
|
+
manifest.upsertRepo({ path: repoPath, last_commit: "unknown" });
|
|
232
|
+
}
|
|
233
|
+
const repoSet = new Set(repos);
|
|
234
|
+
let pendingRepos = manifest.getPendingRepos().filter((r) => repoSet.has(r.path));
|
|
235
|
+
if (opts.repo?.length) {
|
|
236
|
+
const names = opts.repo;
|
|
237
|
+
pendingRepos = pendingRepos.filter((r) => names.some((name) => r.path.toLowerCase().includes(name.toLowerCase())));
|
|
238
|
+
}
|
|
239
|
+
if (opts.dryRun) {
|
|
240
|
+
console.log("\n--- DRY RUN : repos ---");
|
|
241
|
+
for (const r of pendingRepos)
|
|
242
|
+
console.log(` ${r.path}`);
|
|
243
|
+
}
|
|
244
|
+
else {
|
|
245
|
+
let repoDone = 0;
|
|
246
|
+
for (const r of pendingRepos) {
|
|
247
|
+
console.log(`\n Repo: ${r.path}`);
|
|
248
|
+
try {
|
|
249
|
+
const condensed = collectRepo(r.path, config.repoAliases);
|
|
250
|
+
if (!condensed) {
|
|
251
|
+
console.log(" pas un repo git, skip");
|
|
252
|
+
continue;
|
|
253
|
+
}
|
|
254
|
+
if (condensed.isDataless) {
|
|
255
|
+
console.log(" ☁️ déchargé par iCloud (dataless) — ignoré");
|
|
256
|
+
manifest.markRepoFailed(r.path);
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
const repoDigest = await digestRepo(condensed, config);
|
|
260
|
+
const allIds = collectAllIds(config);
|
|
261
|
+
allIds.add(`proj_${toSlug(repoDigest.slug)}`);
|
|
262
|
+
const pageId = updateProjectFromRepo(condensed, repoDigest, config, allIds);
|
|
263
|
+
manifest.markRepoDone(r.path, pageId);
|
|
264
|
+
repoDone++;
|
|
265
|
+
console.log(` ✓ ${pageId}`);
|
|
266
|
+
}
|
|
267
|
+
catch (e) {
|
|
268
|
+
console.error(` ✗ ${e.message.slice(0, 200)}`);
|
|
269
|
+
manifest.markRepoFailed(r.path);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
console.log(`\n Repos : ${repoDone} OK`);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
// ── Claude Desktop export (--claude-export) ───────────────────────────────
|
|
276
|
+
if (opts.claudeExport) {
|
|
277
|
+
// Fail fast if the path doesn't exist
|
|
278
|
+
const exportResolved = expandHome(opts.claudeExport);
|
|
279
|
+
if (!fs.existsSync(exportResolved)) {
|
|
280
|
+
console.error(`\n✗ Export introuvable : ${exportResolved}`);
|
|
281
|
+
manifest.close();
|
|
282
|
+
process.exit(1);
|
|
283
|
+
}
|
|
284
|
+
console.log("\n💬 Conversations Claude Desktop");
|
|
285
|
+
let conversations = [];
|
|
286
|
+
try {
|
|
287
|
+
conversations = collectClaudeExport(opts.claudeExport);
|
|
288
|
+
}
|
|
289
|
+
catch (e) {
|
|
290
|
+
console.error(` ✗ Lecture export échouée : ${e.message}`);
|
|
291
|
+
manifest.close();
|
|
292
|
+
process.exit(1);
|
|
293
|
+
}
|
|
294
|
+
console.log(` Découvertes : ${conversations.length}`);
|
|
295
|
+
for (const conv of conversations) {
|
|
296
|
+
manifest.upsertDesktopConversation({
|
|
297
|
+
uuid: conv.uuid,
|
|
298
|
+
updated_at: conv.updated_at ?? conv.created_at ?? "",
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
// Sort newest→oldest so recent conversations are processed first; apply --limit
|
|
302
|
+
const pendingDesktop = manifest.getPendingDesktopConversations()
|
|
303
|
+
.filter((e) => conversations.some((c) => c.uuid === e.uuid))
|
|
304
|
+
.sort((a, b) => b.updated_at.localeCompare(a.updated_at));
|
|
305
|
+
const toProcessDesktop = opts.limit ? pendingDesktop.slice(0, opts.limit) : pendingDesktop;
|
|
306
|
+
console.log(` En attente : ${pendingDesktop.length}`);
|
|
307
|
+
console.log(` À traiter : ${toProcessDesktop.length}${opts.limit ? ` (limité à ${opts.limit})` : ""}`);
|
|
308
|
+
if (opts.dryRun) {
|
|
309
|
+
console.log("\n--- DRY RUN : conversations ---");
|
|
310
|
+
for (const e of toProcessDesktop) {
|
|
311
|
+
const conv = conversations.find((c) => c.uuid === e.uuid);
|
|
312
|
+
console.log(` ${e.updated_at.slice(0, 10)} ${(conv.name ?? e.uuid).slice(0, 70)}`);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
else {
|
|
316
|
+
let desktopDone = 0;
|
|
317
|
+
let desktopFail = 0;
|
|
318
|
+
// Sonnet alias + compute valid projects list once (known slugs + fixed domains)
|
|
319
|
+
const desktopConfig = { ...config, mergeModel: "sonnet" };
|
|
320
|
+
const knownSlugs = getKnownProjectSlugs(config.brainPath);
|
|
321
|
+
const validProjects = [...knownSlugs, ...FIXED_DOMAINS];
|
|
322
|
+
for (const entry of toProcessDesktop) {
|
|
323
|
+
const conv = conversations.find((c) => c.uuid === entry.uuid);
|
|
324
|
+
const idx = desktopDone + desktopFail + 1;
|
|
325
|
+
console.log(`\n [${idx}/${toProcessDesktop.length}] ${(conv.name ?? entry.uuid).slice(0, 70)}`);
|
|
326
|
+
let recordFileCreated = null;
|
|
327
|
+
try {
|
|
328
|
+
const condensed = formatConversationAsSessionCondensed(conv);
|
|
329
|
+
console.log(` ~${condensed.estimatedTokens.toLocaleString()} tokens condensés`);
|
|
330
|
+
if (condensed.estimatedTokens < 30) {
|
|
331
|
+
console.log(` ⏭ conversation quasi vide, ignorée`);
|
|
332
|
+
manifest.markDesktopConversationFailed(entry.uuid);
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
let digest;
|
|
336
|
+
if (condensed.estimatedTokens < 300) {
|
|
337
|
+
// Minimal record: no LLM call, default domain "perso", 0 elements
|
|
338
|
+
console.log(` ⚡ minimal (${condensed.estimatedTokens} tokens) → perso`);
|
|
339
|
+
digest = {
|
|
340
|
+
title: (conv.name ?? conv.uuid).slice(0, 60),
|
|
341
|
+
summary: condensed.messages
|
|
342
|
+
.slice(0, 3)
|
|
343
|
+
.map((m) => `${m.role === "human" ? "Q" : "R"}: ${m.text.slice(0, 200)}`)
|
|
344
|
+
.join("\n"),
|
|
345
|
+
projects: ["perso"],
|
|
346
|
+
elements: [],
|
|
347
|
+
taches_faites: [],
|
|
348
|
+
taches_abandonnees: [],
|
|
349
|
+
remplacees: [],
|
|
350
|
+
project_states: [],
|
|
351
|
+
files_touched: [],
|
|
352
|
+
people: [],
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
// Full LLM digest — LLM picks projects from validProjects list
|
|
357
|
+
// 10-min timeout per chunk to handle large conversations (multi-chunk via chunking)
|
|
358
|
+
const openElements = getOpenElements(desktopConfig);
|
|
359
|
+
digest = await digestSessionWithRetry(condensed, desktopConfig, openElements, {
|
|
360
|
+
timeoutMs: 900_000,
|
|
361
|
+
validProjects,
|
|
362
|
+
});
|
|
363
|
+
if (digest.projects.length === 0) {
|
|
364
|
+
digest.projects = ["perso"];
|
|
365
|
+
}
|
|
366
|
+
// Post-validate: enforce LLM stayed within knownSlugs ∪ FIXED_DOMAINS;
|
|
367
|
+
// extract people slugs; fall back to "perso" if nothing valid survived
|
|
368
|
+
const { projects: remapped, extraPeople } = remapDesktopProjects(digest.projects, knownSlugs, conv.name ?? "", condensed.messages);
|
|
369
|
+
digest.projects = remapped;
|
|
370
|
+
if (extraPeople.length > 0) {
|
|
371
|
+
digest.people = [...(digest.people ?? []), ...extraPeople];
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
const primaryProject = digest.projects[0];
|
|
375
|
+
const allIds = collectAllIds(config);
|
|
376
|
+
const recordId = writeRecord(condensed, digest, config, allRepoPaths);
|
|
377
|
+
recordFileCreated = recordFilePath(config, condensed.id, condensed.date, primaryProject);
|
|
378
|
+
allIds.add(recordId);
|
|
379
|
+
for (const proj of digest.projects) {
|
|
380
|
+
allIds.add(`proj_${toSlug(proj)}`);
|
|
381
|
+
}
|
|
382
|
+
for (const name of (digest.people ?? [])) {
|
|
383
|
+
allIds.add(`people_${toSlug(name)}`);
|
|
384
|
+
}
|
|
385
|
+
allIds.add("lessons");
|
|
386
|
+
allIds.add("louis");
|
|
387
|
+
for (const proj of digest.projects) {
|
|
388
|
+
const slug = toSlug(proj);
|
|
389
|
+
console.log(` → ${slug}`);
|
|
390
|
+
updateProjectFromSession(slug, digest, condensed.date, recordId, config, allIds, {
|
|
391
|
+
sourceType: "desktop",
|
|
392
|
+
});
|
|
393
|
+
}
|
|
394
|
+
updateLessons(digest, condensed.date, recordId, config, allIds);
|
|
395
|
+
updateLouis(digest, condensed.date, recordId, config, allIds);
|
|
396
|
+
updatePeople(digest, condensed.date, recordId, config, allIds);
|
|
397
|
+
manifest.markDesktopConversationDone(entry.uuid, recordId, digest.projects, currentPromptHash);
|
|
398
|
+
desktopDone++;
|
|
399
|
+
console.log(` ✓ ${recordId}`);
|
|
400
|
+
}
|
|
401
|
+
catch (e) {
|
|
402
|
+
console.error(` ✗ Échec: ${e.message.slice(0, 200)}`);
|
|
403
|
+
manifest.markDesktopConversationFailed(entry.uuid);
|
|
404
|
+
desktopFail++;
|
|
405
|
+
if (recordFileCreated && fs.existsSync(recordFileCreated)) {
|
|
406
|
+
fs.unlinkSync(recordFileCreated);
|
|
407
|
+
console.log(` 🗑 fiche supprimée (échec propre)`);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
console.log(`\n Conversations : ${desktopDone} OK, ${desktopFail} échec(s)`);
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
if (!opts.dryRun) {
|
|
415
|
+
// Final link validation pass
|
|
416
|
+
const allIds = collectAllIds(config);
|
|
417
|
+
allIds.add("lessons");
|
|
418
|
+
allIds.add("louis");
|
|
419
|
+
allIds.add("index");
|
|
420
|
+
const fixed = validateAllLinks(config, allIds);
|
|
421
|
+
if (fixed.length > 0) {
|
|
422
|
+
console.log(`\n 🔗 Liens corrigés dans : ${fixed.join(", ")}`);
|
|
423
|
+
}
|
|
424
|
+
rebuildIndex(config);
|
|
425
|
+
const doneCount = manifest.getAllSessions().filter((s) => s.status === "done").length;
|
|
426
|
+
gitCommit(config, `brain: ingestion — ${doneCount} fiches`);
|
|
427
|
+
// Rebuild FTS index and write hooks config
|
|
428
|
+
try {
|
|
429
|
+
process.stdout.write("\n 🔍 Reconstruction de l'index FTS…");
|
|
430
|
+
const { elements, corrections } = rebuildFts(config);
|
|
431
|
+
console.log(` ${elements} éléments + ${corrections} corrections`);
|
|
432
|
+
writeHooksConfig(config);
|
|
433
|
+
console.log(" ✓ Hooks config écrite dans ~/.claude/brain-hooks.json");
|
|
434
|
+
}
|
|
435
|
+
catch (e) {
|
|
436
|
+
console.warn(` ⚠️ FTS rebuild failed (non bloquant) : ${e.message}`);
|
|
437
|
+
}
|
|
438
|
+
// Save graph.json for instant Coucou reads
|
|
439
|
+
try {
|
|
440
|
+
const { buildGraph, saveGraphJson } = await import("./graph.js");
|
|
441
|
+
saveGraphJson(config, buildGraph(config));
|
|
442
|
+
console.log(" ✓ graph.json sauvegardé");
|
|
443
|
+
}
|
|
444
|
+
catch (e) {
|
|
445
|
+
console.warn(` ⚠️ graph.json save failed : ${e.message}`);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
manifest.close();
|
|
449
|
+
});
|
|
450
|
+
// ── rebuild ───────────────────────────────────────────────────────────────────
|
|
451
|
+
program
|
|
452
|
+
.command("rebuild")
|
|
453
|
+
.description("Re-render all pages from state files (no LLM calls)")
|
|
454
|
+
.action(() => {
|
|
455
|
+
const config = loadConfig();
|
|
456
|
+
const rebuilt = rebuildAllPages(config);
|
|
457
|
+
console.log(`Rebuilt ${rebuilt.length} pages:`);
|
|
458
|
+
rebuilt.forEach((p) => console.log(` ${p}`));
|
|
459
|
+
try {
|
|
460
|
+
process.stdout.write("🔍 Reconstruction de l'index FTS… ");
|
|
461
|
+
const { elements, corrections } = rebuildFts(config);
|
|
462
|
+
console.log(`${elements} éléments + ${corrections} corrections`);
|
|
463
|
+
writeHooksConfig(config);
|
|
464
|
+
console.log("✓ Hooks config écrite dans ~/.claude/brain-hooks.json");
|
|
465
|
+
}
|
|
466
|
+
catch (e) {
|
|
467
|
+
console.warn(`⚠️ FTS rebuild failed : ${e.message}`);
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
// ── stats ─────────────────────────────────────────────────────────────────────
|
|
471
|
+
program
|
|
472
|
+
.command("stats")
|
|
473
|
+
.description("Compute stats from ~/CoucouBrain/ and output JSON")
|
|
474
|
+
.option("--pretty", "Pretty-print JSON")
|
|
475
|
+
.action((opts) => {
|
|
476
|
+
const config = loadConfig();
|
|
477
|
+
const stats = computeStats(config);
|
|
478
|
+
console.log(opts.pretty ? JSON.stringify(stats, null, 2) : JSON.stringify(stats));
|
|
479
|
+
});
|
|
480
|
+
// ── coverage ──────────────────────────────────────────────────────────────────
|
|
481
|
+
program
|
|
482
|
+
.command("coverage")
|
|
483
|
+
.description("Compare brain pages to golden set and report missing elements")
|
|
484
|
+
.option("--golden <path>", "Path to golden set JSON file")
|
|
485
|
+
.action((opts) => {
|
|
486
|
+
const config = loadConfig();
|
|
487
|
+
// Priority: --golden flag > local state file (private, gitignored) > example file
|
|
488
|
+
const localGoldenPath = path.join(expandHome(config.brainPath), ".state", "golden-set.json");
|
|
489
|
+
const exampleGoldenPath = path.join(path.dirname(new URL(import.meta.url).pathname), "..", "tests", "golden-set.example.json");
|
|
490
|
+
const goldenPath = opts.golden
|
|
491
|
+
? path.resolve(opts.golden)
|
|
492
|
+
: fs.existsSync(localGoldenPath)
|
|
493
|
+
? localGoldenPath
|
|
494
|
+
: exampleGoldenPath;
|
|
495
|
+
try {
|
|
496
|
+
const result = runCoverage(config, goldenPath);
|
|
497
|
+
console.log(formatCoverageResult(result));
|
|
498
|
+
if (result.missing.length > 0) {
|
|
499
|
+
process.exitCode = 1;
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
catch (e) {
|
|
503
|
+
console.error(`Coverage error: ${e.message}`);
|
|
504
|
+
process.exitCode = 1;
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
// ── correct ───────────────────────────────────────────────────────────────────
|
|
508
|
+
program
|
|
509
|
+
.command("correct <texte>")
|
|
510
|
+
.description("Append a correction to ~/CoucouBrain/corrections.md under a named scope section")
|
|
511
|
+
.option("--scope <scope>", "Section cible : 'global' ou slug de projet (ex: reels, sbe-hub)", "global")
|
|
512
|
+
.action((texte, opts) => {
|
|
513
|
+
const config = loadConfig();
|
|
514
|
+
try {
|
|
515
|
+
appendCorrection(config, texte, opts.scope);
|
|
516
|
+
console.log(`✓ Correction ajoutée sous §${opts.scope} dans corrections.md`);
|
|
517
|
+
}
|
|
518
|
+
catch (e) {
|
|
519
|
+
console.error(`Erreur : ${e.message}`);
|
|
520
|
+
process.exitCode = 1;
|
|
521
|
+
}
|
|
522
|
+
});
|
|
523
|
+
// ── ignore ────────────────────────────────────────────────────────────────────
|
|
524
|
+
program
|
|
525
|
+
.command("ignore <session-id>")
|
|
526
|
+
.description("Mark a session as ignored — it will never be digested")
|
|
527
|
+
.option("--raison <text>", "Reason for ignoring (stored in manifest)")
|
|
528
|
+
.action((sessionId, opts) => {
|
|
529
|
+
const config = loadConfig();
|
|
530
|
+
const manifest = new Manifest(config.brainPath);
|
|
531
|
+
const existing = manifest.getSession(sessionId);
|
|
532
|
+
if (!existing) {
|
|
533
|
+
// Session not yet collected — upsert it as ignored
|
|
534
|
+
// Find the JSONL file by scanning Claude projects dirs
|
|
535
|
+
const { claudeProjectsPath } = config;
|
|
536
|
+
const claudeBase = expandHome(claudeProjectsPath);
|
|
537
|
+
let jsonlPath = null;
|
|
538
|
+
let projectPath = null;
|
|
539
|
+
try {
|
|
540
|
+
for (const proj of fs.readdirSync(claudeBase)) {
|
|
541
|
+
const candidate = path.join(claudeBase, proj, `${sessionId}.jsonl`);
|
|
542
|
+
if (fs.existsSync(candidate)) {
|
|
543
|
+
jsonlPath = candidate;
|
|
544
|
+
projectPath = proj;
|
|
545
|
+
break;
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
catch { }
|
|
550
|
+
if (!jsonlPath || !projectPath) {
|
|
551
|
+
console.error(`Session ${sessionId} introuvable dans ${claudeBase}`);
|
|
552
|
+
process.exitCode = 1;
|
|
553
|
+
manifest.close();
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
const hash = crypto.createHash("sha256")
|
|
557
|
+
.update(fs.readFileSync(jsonlPath))
|
|
558
|
+
.digest("hex")
|
|
559
|
+
.slice(0, 16);
|
|
560
|
+
manifest.upsertSession({ id: sessionId, project_path: projectPath, jsonl_path: jsonlPath, hash });
|
|
561
|
+
}
|
|
562
|
+
manifest.markSessionIgnored(sessionId, opts.raison);
|
|
563
|
+
const reason = opts.raison ? ` (${opts.raison})` : "";
|
|
564
|
+
console.log(`✓ Session ${sessionId} marquée 'ignored'${reason}`);
|
|
565
|
+
manifest.close();
|
|
566
|
+
});
|
|
567
|
+
// ── enrich ────────────────────────────────────────────────────────────────────
|
|
568
|
+
program
|
|
569
|
+
.command("enrich")
|
|
570
|
+
.description("Add keywords to existing elements that don't have them, then rebuild FTS")
|
|
571
|
+
.option("--dry-run", "Show counts but don't write")
|
|
572
|
+
.option("--project <slug>", "Restrict to one project")
|
|
573
|
+
.option("--batch <n>", "Elements per LLM call (default 15)", "15")
|
|
574
|
+
.action(async (opts) => {
|
|
575
|
+
const config = loadConfig();
|
|
576
|
+
assertNoRemote(config.brainPath);
|
|
577
|
+
const { spawnSync } = await import("node:child_process");
|
|
578
|
+
const stateDir = path.join(expandHome(config.brainPath), ".state", "proj");
|
|
579
|
+
if (!fs.existsSync(stateDir)) {
|
|
580
|
+
console.error("No state dir found. Run brain ingest first.");
|
|
581
|
+
process.exitCode = 1;
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
if (!opts.dryRun) {
|
|
585
|
+
const { gitCommit } = await import("./write.js");
|
|
586
|
+
gitCommit(config, "brain: snapshot pré-enrich");
|
|
587
|
+
}
|
|
588
|
+
const batchSize = Math.max(1, Math.min(50, parseInt(opts.batch, 10) || 15));
|
|
589
|
+
let totalMissing = 0;
|
|
590
|
+
let totalWritten = 0;
|
|
591
|
+
for (const f of fs.readdirSync(stateDir)) {
|
|
592
|
+
if (!f.endsWith(".json"))
|
|
593
|
+
continue;
|
|
594
|
+
const stateFile = path.join(stateDir, f);
|
|
595
|
+
let state;
|
|
596
|
+
try {
|
|
597
|
+
state = JSON.parse(fs.readFileSync(stateFile, "utf8"));
|
|
598
|
+
}
|
|
599
|
+
catch {
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
if (opts.project && !state.id.includes(opts.project))
|
|
603
|
+
continue;
|
|
604
|
+
const missing = state.elements.filter((e) => !e.keywords || e.keywords.length === 0);
|
|
605
|
+
if (missing.length === 0)
|
|
606
|
+
continue;
|
|
607
|
+
totalMissing += missing.length;
|
|
608
|
+
console.log(`${state.id}: ${missing.length} elements sans keywords`);
|
|
609
|
+
if (opts.dryRun)
|
|
610
|
+
continue;
|
|
611
|
+
// Process in batches
|
|
612
|
+
let changed = false;
|
|
613
|
+
for (let i = 0; i < missing.length; i += batchSize) {
|
|
614
|
+
const batch = missing.slice(i, i + batchSize);
|
|
615
|
+
const maskedBatch = batch.map((e) => ({
|
|
616
|
+
id: e.id,
|
|
617
|
+
kind: e.kind,
|
|
618
|
+
texte: maskSecrets(e.texte).text,
|
|
619
|
+
}));
|
|
620
|
+
// the marker keeps this run out of the index (it is brain talking to Claude, not you)
|
|
621
|
+
const prompt = `<!-- coucou-brain-internal -->
|
|
622
|
+
Génère 6 à 10 keywords de recherche FR+EN pour chaque élément.
|
|
623
|
+
Inclure les racines des mots composés (ex "Redesign" → "design"), synonymes, domaine, verbes d'action.
|
|
624
|
+
|
|
625
|
+
Éléments :
|
|
626
|
+
${JSON.stringify(maskedBatch, null, 2)}
|
|
627
|
+
|
|
628
|
+
Réponds UNIQUEMENT avec le JSON :
|
|
629
|
+
[{"id": "...", "keywords": ["k1", "k2", "k3", "k4", "k5", "k6"]}]`;
|
|
630
|
+
const result = spawnSync(process.execPath, ["-e", `
|
|
631
|
+
const { spawnSync } = require('child_process');
|
|
632
|
+
const r = spawnSync('claude', [
|
|
633
|
+
'--print', '--model', 'claude-haiku-4-5-20251001',
|
|
634
|
+
'--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',
|
|
635
|
+
'--tools', '', '--disallowed-tools', 'LSP',
|
|
636
|
+
], {
|
|
637
|
+
input: process.argv[1], encoding: 'utf8', timeout: 60000,
|
|
638
|
+
env: { ...process.env, COUCOU_BRAIN_INTERNAL: '1' }
|
|
639
|
+
});
|
|
640
|
+
process.stdout.write(r.stdout || '');
|
|
641
|
+
process.stderr.write(r.stderr || '');
|
|
642
|
+
process.exitCode = r.status || 0;
|
|
643
|
+
`, prompt], { encoding: "utf8", timeout: 90000 });
|
|
644
|
+
const raw = (result.stdout ?? "").trim();
|
|
645
|
+
if (!raw) {
|
|
646
|
+
console.error(` Batch ${i}-${i + batch.length}: no output`);
|
|
647
|
+
continue;
|
|
648
|
+
}
|
|
649
|
+
let parsed;
|
|
650
|
+
try {
|
|
651
|
+
// Strip markdown code fences if present
|
|
652
|
+
const json = raw.replace(/^```[a-z]*\n?/, "").replace(/\n?```$/, "");
|
|
653
|
+
parsed = JSON.parse(json);
|
|
654
|
+
}
|
|
655
|
+
catch {
|
|
656
|
+
console.error(` Batch ${i}-${i + batch.length}: invalid JSON`);
|
|
657
|
+
continue;
|
|
658
|
+
}
|
|
659
|
+
for (const item of parsed) {
|
|
660
|
+
const elem = state.elements.find((e) => e.id === item.id);
|
|
661
|
+
if (elem && Array.isArray(item.keywords) && item.keywords.length > 0) {
|
|
662
|
+
elem.keywords = item.keywords.map((k) => String(k)).slice(0, 10);
|
|
663
|
+
changed = true;
|
|
664
|
+
totalWritten++;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
process.stdout.write(` ${Math.min(i + batchSize, missing.length)}/${missing.length} enrichis\r`);
|
|
668
|
+
}
|
|
669
|
+
process.stdout.write("\n");
|
|
670
|
+
if (changed) {
|
|
671
|
+
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), "utf8");
|
|
672
|
+
}
|
|
673
|
+
}
|
|
674
|
+
console.log(`\nTotal : ${totalMissing} sans keywords, ${totalWritten} enrichis`);
|
|
675
|
+
if (!opts.dryRun && totalWritten > 0) {
|
|
676
|
+
console.log("Rebuilding FTS...");
|
|
677
|
+
const { rebuildFts: rebuild, writeHooksConfig: writeHooks } = await import("./fts.js");
|
|
678
|
+
const result = rebuild(config);
|
|
679
|
+
writeHooks(config);
|
|
680
|
+
console.log(`FTS rebuilt: ${result.elements} elements`);
|
|
681
|
+
}
|
|
682
|
+
});
|
|
683
|
+
// ── dedup ─────────────────────────────────────────────────────────────────────
|
|
684
|
+
program
|
|
685
|
+
.command("dedup")
|
|
686
|
+
.description("Merge near-duplicate elements across all project state files, then rebuild FTS")
|
|
687
|
+
.option("--dry-run", "Show counts but don't write")
|
|
688
|
+
.option("--threshold <n>", "Jaccard similarity threshold (default: 0.7)", "0.7")
|
|
689
|
+
.action(async (opts) => {
|
|
690
|
+
const config = loadConfig();
|
|
691
|
+
assertNoRemote(config.brainPath);
|
|
692
|
+
const { dedupElements } = await import("./elements.js");
|
|
693
|
+
const brainBase = expandHome(config.brainPath);
|
|
694
|
+
const stateDir = path.join(brainBase, ".state", "proj");
|
|
695
|
+
if (!fs.existsSync(stateDir)) {
|
|
696
|
+
console.error("State dir not found:", stateDir);
|
|
697
|
+
process.exitCode = 1;
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
const threshold = parseFloat(opts.threshold);
|
|
701
|
+
const allJournal = [];
|
|
702
|
+
let totalMerged = 0;
|
|
703
|
+
if (!opts.dryRun) {
|
|
704
|
+
// Git snapshot before any writes — allows `git checkout` restore
|
|
705
|
+
const { gitCommit } = await import("./write.js");
|
|
706
|
+
gitCommit(config, "brain: snapshot pré-dedup");
|
|
707
|
+
}
|
|
708
|
+
for (const f of fs.readdirSync(stateDir)) {
|
|
709
|
+
if (!f.endsWith(".json"))
|
|
710
|
+
continue;
|
|
711
|
+
const stateFile = path.join(stateDir, f);
|
|
712
|
+
let state;
|
|
713
|
+
try {
|
|
714
|
+
state = JSON.parse(fs.readFileSync(stateFile, "utf8"));
|
|
715
|
+
}
|
|
716
|
+
catch {
|
|
717
|
+
continue;
|
|
718
|
+
}
|
|
719
|
+
const before = state.elements.length;
|
|
720
|
+
const { elements, merged, journal } = dedupElements(state.elements, threshold);
|
|
721
|
+
if (merged === 0)
|
|
722
|
+
continue;
|
|
723
|
+
console.log(`${state.id}: ${before} → ${elements.length} (${merged} merged)`);
|
|
724
|
+
for (const entry of journal) {
|
|
725
|
+
allJournal.push({ ...entry, stateFile: f });
|
|
726
|
+
}
|
|
727
|
+
totalMerged += merged;
|
|
728
|
+
if (!opts.dryRun) {
|
|
729
|
+
state.elements = elements;
|
|
730
|
+
fs.writeFileSync(stateFile, JSON.stringify(state, null, 2), "utf8");
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
if (totalMerged === 0) {
|
|
734
|
+
console.log("No duplicates found.");
|
|
735
|
+
return;
|
|
736
|
+
}
|
|
737
|
+
console.log(`\nTotal merged: ${totalMerged}`);
|
|
738
|
+
if (!opts.dryRun) {
|
|
739
|
+
// Append to journal
|
|
740
|
+
const journalPath = path.join(brainBase, ".state", "dedup-journal.json");
|
|
741
|
+
const existing = fs.existsSync(journalPath)
|
|
742
|
+
? JSON.parse(fs.readFileSync(journalPath, "utf8"))
|
|
743
|
+
: [];
|
|
744
|
+
fs.writeFileSync(journalPath, JSON.stringify([...existing, ...allJournal], null, 2), "utf8");
|
|
745
|
+
console.log(`Journal: ${journalPath} (${allJournal.length} entries)`);
|
|
746
|
+
console.log("Rebuilding FTS...");
|
|
747
|
+
const { rebuildFts: rebuild, writeHooksConfig: writeHooks } = await import("./fts.js");
|
|
748
|
+
const result = rebuild(config);
|
|
749
|
+
writeHooks(config);
|
|
750
|
+
console.log(`FTS rebuilt: ${result.elements} elements`);
|
|
751
|
+
}
|
|
752
|
+
else {
|
|
753
|
+
// Show up to 10 sample merges in dry-run
|
|
754
|
+
console.log("\nSample merges (dry-run):");
|
|
755
|
+
allJournal.slice(0, 10).forEach((e, i) => {
|
|
756
|
+
console.log(` ${i + 1}. ${e.from} → ${e.into} (sim=${e.similarity.toFixed(2)}) [${e.stateFile}]`);
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
});
|
|
760
|
+
// ── reset ─────────────────────────────────────────────────────────────────────
|
|
761
|
+
program
|
|
762
|
+
.command("reset")
|
|
763
|
+
.description("Reset all done/failed sessions and repos to pending for full re-ingestion. Keeps 'ignored' sessions.")
|
|
764
|
+
.option("--confirm", "Required to actually run the reset")
|
|
765
|
+
.action((opts) => {
|
|
766
|
+
if (!opts.confirm) {
|
|
767
|
+
console.log("Ajoute --confirm pour effectuer le reset.");
|
|
768
|
+
console.log("Les sessions 'ignored' (fiches de test, digestions internes) sont conservées.");
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
const config = loadConfig();
|
|
772
|
+
assertNoRemote(config.brainPath);
|
|
773
|
+
const manifest = new Manifest(config.brainPath);
|
|
774
|
+
const { sessions, repos } = manifest.resetForReingestion();
|
|
775
|
+
manifest.close();
|
|
776
|
+
console.log(`Reset : ${sessions} session(s), ${repos} repo(s) remis en pending.`);
|
|
777
|
+
});
|
|
778
|
+
// ── mcp ───────────────────────────────────────────────────────────────────────
|
|
779
|
+
program
|
|
780
|
+
.command("mcp")
|
|
781
|
+
.description("Start the CoucouBrain MCP server (stdio transport)")
|
|
782
|
+
.action(async () => {
|
|
783
|
+
const { startMcpServer } = await import("./mcp/server.js");
|
|
784
|
+
await startMcpServer();
|
|
785
|
+
});
|
|
786
|
+
// ── pause / resume ────────────────────────────────────────────────────────────
|
|
787
|
+
program
|
|
788
|
+
.command("pause")
|
|
789
|
+
.description("Suspend hook injections (useful for Twitch live / recording sessions)")
|
|
790
|
+
.action(() => {
|
|
791
|
+
const config = loadConfig();
|
|
792
|
+
const flagPath = path.join(expandHome(config.brainPath), ".state", "paused");
|
|
793
|
+
fs.mkdirSync(path.dirname(flagPath), { recursive: true });
|
|
794
|
+
fs.writeFileSync(flagPath, new Date().toISOString(), "utf8");
|
|
795
|
+
console.log("⏸ Brain hooks en pause. Les sessions Claude Code ne recevront plus de contexte brain.");
|
|
796
|
+
console.log(" Relancer avec : brain resume");
|
|
797
|
+
});
|
|
798
|
+
program
|
|
799
|
+
.command("resume")
|
|
800
|
+
.description("Re-enable hook injections after a pause")
|
|
801
|
+
.action(() => {
|
|
802
|
+
const config = loadConfig();
|
|
803
|
+
const flagPath = path.join(expandHome(config.brainPath), ".state", "paused");
|
|
804
|
+
if (fs.existsSync(flagPath)) {
|
|
805
|
+
fs.unlinkSync(flagPath);
|
|
806
|
+
console.log("▶️ Brain hooks réactivés.");
|
|
807
|
+
}
|
|
808
|
+
else {
|
|
809
|
+
console.log("(Pas en pause — rien à faire.)");
|
|
810
|
+
}
|
|
811
|
+
});
|
|
812
|
+
// ── index (Level 1 — raw FTS, no LLM) ────────────────────────────────────────
|
|
813
|
+
program
|
|
814
|
+
.command("index")
|
|
815
|
+
.description("Index conversations and sessions as raw text (no LLM). Enables `brain search`.")
|
|
816
|
+
.option("--claude-export <path>", "Path to Claude.ai export zip or folder (overrides config)")
|
|
817
|
+
.action(async (opts) => {
|
|
818
|
+
const config = loadConfig();
|
|
819
|
+
assertNoRemote(config.brainPath);
|
|
820
|
+
const { rebuildRawIndex } = await import("./rawindex.js");
|
|
821
|
+
console.log("\n📑 Indexation brut (niveau 1 — sans LLM)\n");
|
|
822
|
+
const result = rebuildRawIndex(config, {
|
|
823
|
+
claudeExportPath: opts.claudeExport,
|
|
824
|
+
onProgress: (msg) => console.log(msg),
|
|
825
|
+
});
|
|
826
|
+
const secs = (result.durationMs / 1000).toFixed(1);
|
|
827
|
+
console.log(`\n✓ Index raw construit en ${secs}s`);
|
|
828
|
+
console.log(` Conversations claude.ai : ${result.conversations}`);
|
|
829
|
+
console.log(` Sessions Claude Code : ${result.sessions}`);
|
|
830
|
+
console.log(` Messages indexés : ${result.messages.toLocaleString()}`);
|
|
831
|
+
// Save graph.json for instant Coucou reads
|
|
832
|
+
try {
|
|
833
|
+
const { buildGraph, saveGraphJson } = await import("./graph.js");
|
|
834
|
+
saveGraphJson(config, buildGraph(config));
|
|
835
|
+
console.log(` ✓ graph.json sauvegardé`);
|
|
836
|
+
}
|
|
837
|
+
catch (e) {
|
|
838
|
+
console.warn(` ⚠️ graph.json save failed : ${e.message}`);
|
|
839
|
+
}
|
|
840
|
+
console.log(`\n Utilisez "brain search <texte>" pour chercher.`);
|
|
841
|
+
});
|
|
842
|
+
// ── search (Level 1 — raw FTS) ────────────────────────────────────────────────
|
|
843
|
+
program
|
|
844
|
+
.command("search <query>")
|
|
845
|
+
.description("Search indexed conversations and sessions (raw text, no LLM)")
|
|
846
|
+
.option("--limit <n>", "Max results per page (default 10)", parseInt)
|
|
847
|
+
.option("--offset <n>", "Skip first N conversations", parseInt)
|
|
848
|
+
.option("--source <src>", "Filter by source: claude (claude.ai) or code (Claude Code sessions)")
|
|
849
|
+
.option("--json", "Output raw JSON for programmatic use (Coucou app)")
|
|
850
|
+
.action(async (query, opts) => {
|
|
851
|
+
const config = loadConfig();
|
|
852
|
+
const { searchRaw, getRawStats, rawDbPath } = await import("./rawindex.js");
|
|
853
|
+
const dbPath = rawDbPath(config);
|
|
854
|
+
if (!fs.existsSync(expandHome(dbPath))) {
|
|
855
|
+
if (opts.json) {
|
|
856
|
+
console.log(JSON.stringify({ error: "index_missing", total: 0, results: [] }));
|
|
857
|
+
}
|
|
858
|
+
else {
|
|
859
|
+
console.error('Index raw introuvable. Lance "brain index" d\'abord.');
|
|
860
|
+
process.exitCode = 1;
|
|
861
|
+
}
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
if (query.trim().length < 3) {
|
|
865
|
+
if (opts.json) {
|
|
866
|
+
console.log(JSON.stringify({ error: "query_too_short", total: 0, results: [] }));
|
|
867
|
+
}
|
|
868
|
+
else {
|
|
869
|
+
console.error("Requête trop courte (minimum 3 caractères).");
|
|
870
|
+
process.exitCode = 1;
|
|
871
|
+
}
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
// Map --source flag to internal source filter
|
|
875
|
+
let sourceFilter;
|
|
876
|
+
if (opts.source === "claude")
|
|
877
|
+
sourceFilter = "desktop";
|
|
878
|
+
else if (opts.source === "code")
|
|
879
|
+
sourceFilter = "session";
|
|
880
|
+
const limit = opts.limit ?? 10;
|
|
881
|
+
const offset = opts.offset ?? 0;
|
|
882
|
+
const { results, total } = searchRaw(config, query, limit, offset, sourceFilter);
|
|
883
|
+
if (opts.json) {
|
|
884
|
+
console.log(JSON.stringify({
|
|
885
|
+
total,
|
|
886
|
+
results: results.map((r) => ({
|
|
887
|
+
id: r.convId,
|
|
888
|
+
titre: r.convTitle,
|
|
889
|
+
source: r.source === "desktop" ? "claude" : "code",
|
|
890
|
+
date: r.convDate,
|
|
891
|
+
extrait: r.excerpt,
|
|
892
|
+
lien: r.convLink,
|
|
893
|
+
projet: r.project,
|
|
894
|
+
nbMentions: r.nbMentions,
|
|
895
|
+
})),
|
|
896
|
+
}));
|
|
897
|
+
return;
|
|
898
|
+
}
|
|
899
|
+
if (total === 0) {
|
|
900
|
+
console.log(`Aucun résultat pour "${query}".`);
|
|
901
|
+
const stats = getRawStats(config);
|
|
902
|
+
if (stats) {
|
|
903
|
+
console.log(` (index: ${stats.messages.toLocaleString()} messages, ${stats.conversations} conversations, ${stats.sessions} sessions)`);
|
|
904
|
+
}
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
const showing = offset + results.length;
|
|
908
|
+
const more = total > showing ? ` (--offset ${showing} pour la suite)` : "";
|
|
909
|
+
console.log(`\n🔍 "${query}" — ${total} conversation(s) [${offset + 1}-${showing}]${more}\n`);
|
|
910
|
+
for (let i = 0; i < results.length; i++) {
|
|
911
|
+
const r = results[i];
|
|
912
|
+
const num = `[${offset + i + 1}]`;
|
|
913
|
+
const source = r.source === "desktop" ? `claude.ai` : `session:${r.project}`;
|
|
914
|
+
const link = r.convLink ? `\n ${r.convLink}` : "";
|
|
915
|
+
const role = r.role === "human" ? "Human" : "Claude";
|
|
916
|
+
const excerpt = r.excerpt.length > 180 ? r.excerpt.slice(0, 177) + "…" : r.excerpt;
|
|
917
|
+
console.log(`${num} "${r.convTitle}" ${r.convDate} (${source})`);
|
|
918
|
+
console.log(` ${role}: ${excerpt}`);
|
|
919
|
+
if (link)
|
|
920
|
+
console.log(link);
|
|
921
|
+
console.log();
|
|
922
|
+
}
|
|
923
|
+
});
|
|
924
|
+
// ── page ──────────────────────────────────────────────────────────────────────
|
|
925
|
+
program
|
|
926
|
+
.command("page <id>")
|
|
927
|
+
.description("Everything memory knows about one node of the graph (Memory › Graph page)")
|
|
928
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
929
|
+
.action(async (id, opts) => {
|
|
930
|
+
const config = loadConfig();
|
|
931
|
+
const { nodePage } = await import("./node-page.js");
|
|
932
|
+
try {
|
|
933
|
+
const page = nodePage(config, id);
|
|
934
|
+
if (opts.json) {
|
|
935
|
+
console.log(JSON.stringify(page ?? { error: "not_found", id }));
|
|
936
|
+
return;
|
|
937
|
+
}
|
|
938
|
+
if (!page) {
|
|
939
|
+
console.error(`✗ introuvable : ${id}`);
|
|
940
|
+
process.exitCode = 1;
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
console.log(`\n ${page.title} (${page.kind}${page.date ? ", " + page.date : ""})`);
|
|
944
|
+
if (page.summary)
|
|
945
|
+
console.log(`\n ${page.summary}`);
|
|
946
|
+
for (const s of page.sections) {
|
|
947
|
+
console.log(`\n ${s.title}`);
|
|
948
|
+
for (const it of s.items)
|
|
949
|
+
console.log(` - ${it}`);
|
|
950
|
+
}
|
|
951
|
+
console.log();
|
|
952
|
+
}
|
|
953
|
+
catch (e) {
|
|
954
|
+
if (opts.json) {
|
|
955
|
+
console.log(JSON.stringify({ error: e.message, id }));
|
|
956
|
+
return;
|
|
957
|
+
}
|
|
958
|
+
console.error(`✗ ${e.message}`);
|
|
959
|
+
process.exitCode = 1;
|
|
960
|
+
}
|
|
961
|
+
});
|
|
962
|
+
// ── suggest ───────────────────────────────────────────────────────────────────
|
|
963
|
+
program
|
|
964
|
+
.command("suggest")
|
|
965
|
+
.description("Recent conversations and searches worth trying (Memory › Search before typing)")
|
|
966
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
967
|
+
.action(async (opts) => {
|
|
968
|
+
const config = loadConfig();
|
|
969
|
+
const { suggestions } = await import("./suggest.js");
|
|
970
|
+
try {
|
|
971
|
+
const s = suggestions(config);
|
|
972
|
+
if (opts.json) {
|
|
973
|
+
console.log(JSON.stringify(s));
|
|
974
|
+
return;
|
|
975
|
+
}
|
|
976
|
+
console.log(`\n À chercher : ${s.searches.join(" · ") || "—"}\n`);
|
|
977
|
+
for (const c of s.recent)
|
|
978
|
+
console.log(` ${c.date} ${c.titre}${c.projet ? ` (${c.projet})` : ""}`);
|
|
979
|
+
console.log();
|
|
980
|
+
}
|
|
981
|
+
catch (e) {
|
|
982
|
+
if (opts.json) {
|
|
983
|
+
console.log(JSON.stringify({ error: e.message, recent: [], searches: [] }));
|
|
984
|
+
return;
|
|
985
|
+
}
|
|
986
|
+
console.error(`✗ ${e.message}`);
|
|
987
|
+
process.exitCode = 1;
|
|
988
|
+
}
|
|
989
|
+
});
|
|
990
|
+
// ── show (Level 1 — raw FTS) ──────────────────────────────────────────────────
|
|
991
|
+
program
|
|
992
|
+
.command("show <id>")
|
|
993
|
+
.description("Show full conversation by ID, with digested elements if available")
|
|
994
|
+
.option("--json", "Output raw JSON for programmatic use (Coucou app)")
|
|
995
|
+
.action(async (id, opts) => {
|
|
996
|
+
const config = loadConfig();
|
|
997
|
+
const { getConversationMessages, rawDbPath } = await import("./rawindex.js");
|
|
998
|
+
const dbPath = rawDbPath(config);
|
|
999
|
+
if (!fs.existsSync(expandHome(dbPath))) {
|
|
1000
|
+
if (opts.json) {
|
|
1001
|
+
console.log(JSON.stringify({ error: "index_missing" }));
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
console.error('Index raw introuvable. Lance "brain index" d\'abord.');
|
|
1005
|
+
process.exitCode = 1;
|
|
1006
|
+
}
|
|
1007
|
+
return;
|
|
1008
|
+
}
|
|
1009
|
+
const conv = getConversationMessages(config, id);
|
|
1010
|
+
if (!conv) {
|
|
1011
|
+
if (opts.json) {
|
|
1012
|
+
console.log(JSON.stringify({ error: "not_found", id }));
|
|
1013
|
+
}
|
|
1014
|
+
else {
|
|
1015
|
+
console.error(`Conversation introuvable : ${id}`);
|
|
1016
|
+
process.exitCode = 1;
|
|
1017
|
+
}
|
|
1018
|
+
return;
|
|
1019
|
+
}
|
|
1020
|
+
let elements = null;
|
|
1021
|
+
let projets = [];
|
|
1022
|
+
try {
|
|
1023
|
+
// Check manifest for record_id
|
|
1024
|
+
const { Manifest } = await import("./manifest.js");
|
|
1025
|
+
const manifest = new Manifest(config.brainPath);
|
|
1026
|
+
const session = manifest.getSession(id);
|
|
1027
|
+
const desktopEntry = !session ? manifest.getDesktopConversation(id) : null;
|
|
1028
|
+
const recordId = session?.record_id ?? desktopEntry?.record_id ?? null;
|
|
1029
|
+
projets = JSON.parse(session?.projects ?? desktopEntry?.projects ?? "[]");
|
|
1030
|
+
manifest.close();
|
|
1031
|
+
if (recordId) {
|
|
1032
|
+
// Scan state files for elements belonging to this record
|
|
1033
|
+
const stateDir = path.join(expandHome(config.brainPath), ".state", "proj");
|
|
1034
|
+
if (fs.existsSync(stateDir)) {
|
|
1035
|
+
elements = [];
|
|
1036
|
+
for (const file of fs.readdirSync(stateDir)) {
|
|
1037
|
+
if (!file.endsWith(".json"))
|
|
1038
|
+
continue;
|
|
1039
|
+
try {
|
|
1040
|
+
const raw = fs.readFileSync(path.join(stateDir, file), "utf8");
|
|
1041
|
+
const state = JSON.parse(raw);
|
|
1042
|
+
for (const elem of state.elements) {
|
|
1043
|
+
if (elem.sources.includes(recordId)) {
|
|
1044
|
+
elements.push({ kind: elem.kind, texte: elem.texte, statut: elem.statut ?? null });
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
}
|
|
1048
|
+
catch { }
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
catch { }
|
|
1054
|
+
if (opts.json) {
|
|
1055
|
+
console.log(JSON.stringify({
|
|
1056
|
+
id: conv.id,
|
|
1057
|
+
titre: conv.titre,
|
|
1058
|
+
source: conv.source === "desktop" ? "claude" : "code",
|
|
1059
|
+
date: conv.date,
|
|
1060
|
+
lien: conv.lien,
|
|
1061
|
+
projet: conv.projet,
|
|
1062
|
+
projets,
|
|
1063
|
+
messages: conv.messages,
|
|
1064
|
+
elements,
|
|
1065
|
+
}));
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
// Human-readable output
|
|
1069
|
+
console.log(`\n📄 "${conv.titre}" ${conv.date} (${conv.source})`);
|
|
1070
|
+
if (conv.lien)
|
|
1071
|
+
console.log(` ${conv.lien}`);
|
|
1072
|
+
console.log(` Projet: ${conv.projet || "(inconnu)"}`);
|
|
1073
|
+
console.log(`\n${conv.messages.length} messages:\n`);
|
|
1074
|
+
for (const msg of conv.messages.slice(0, 5)) {
|
|
1075
|
+
const role = msg.role === "human" ? "Human" : "Claude";
|
|
1076
|
+
console.log(` [${role}] ${msg.text.slice(0, 200)}`);
|
|
1077
|
+
}
|
|
1078
|
+
if (conv.messages.length > 5)
|
|
1079
|
+
console.log(` … (+${conv.messages.length - 5} messages)`);
|
|
1080
|
+
if (elements === null) {
|
|
1081
|
+
console.log("\n (pas encore digérée par le LLM)");
|
|
1082
|
+
}
|
|
1083
|
+
else if (elements.length > 0) {
|
|
1084
|
+
console.log(`\n${elements.length} éléments retenus:`);
|
|
1085
|
+
for (const e of elements) {
|
|
1086
|
+
console.log(` [${e.kind}${e.statut ? " " + e.statut : ""}] ${e.texte.slice(0, 100)}`);
|
|
1087
|
+
}
|
|
1088
|
+
}
|
|
1089
|
+
console.log();
|
|
1090
|
+
});
|
|
1091
|
+
// ── graph (Level 1+) ──────────────────────────────────────────────────────────
|
|
1092
|
+
program
|
|
1093
|
+
.command("graph")
|
|
1094
|
+
.description("Build a knowledge graph (nodes + edges) from indexed conversations and LLM state")
|
|
1095
|
+
.option("--json", "Output raw JSON for programmatic use (Coucou app)")
|
|
1096
|
+
.option("--limit <n>", "Max nodes (default 5000)", parseInt)
|
|
1097
|
+
.action(async (opts) => {
|
|
1098
|
+
const config = loadConfig();
|
|
1099
|
+
const { buildGraph, saveGraphJson } = await import("./graph.js");
|
|
1100
|
+
// Fast path: graph.json already computed by brain index / brain ingest
|
|
1101
|
+
if (opts.json && !opts.limit) {
|
|
1102
|
+
const { expandHome } = await import("./utils.js");
|
|
1103
|
+
const graphJsonPath = path.join(expandHome(config.brainPath), ".state", "graph.json");
|
|
1104
|
+
if (fs.existsSync(graphJsonPath)) {
|
|
1105
|
+
process.stdout.write(fs.readFileSync(graphJsonPath, "utf8"));
|
|
1106
|
+
return;
|
|
1107
|
+
}
|
|
1108
|
+
}
|
|
1109
|
+
const data = buildGraph(config, { limit: opts.limit ?? 5000 });
|
|
1110
|
+
// Save for next time (so subsequent calls go through the fast path)
|
|
1111
|
+
if (!opts.limit)
|
|
1112
|
+
saveGraphJson(config, data);
|
|
1113
|
+
if (opts.json) {
|
|
1114
|
+
console.log(JSON.stringify(data));
|
|
1115
|
+
return;
|
|
1116
|
+
}
|
|
1117
|
+
console.log(`\n🕸 Graphe : ${data.nodes.length} nœuds, ${data.edges.length} liens`);
|
|
1118
|
+
const byKind = {};
|
|
1119
|
+
for (const n of data.nodes)
|
|
1120
|
+
byKind[n.kind] = (byKind[n.kind] ?? 0) + 1;
|
|
1121
|
+
for (const [kind, count] of Object.entries(byKind)) {
|
|
1122
|
+
console.log(` ${kind}: ${count}`);
|
|
1123
|
+
}
|
|
1124
|
+
console.log(`\n Utilisez --json pour l'export complet.`);
|
|
1125
|
+
});
|
|
1126
|
+
// ── recurrences ───────────────────────────────────────────────────────────────
|
|
1127
|
+
program
|
|
1128
|
+
.command("recurrences")
|
|
1129
|
+
.description("Detect recurring topics, repeated errors, and artifact counts")
|
|
1130
|
+
.option("--json", "Output raw JSON for programmatic use (Coucou app)")
|
|
1131
|
+
.action(async (opts) => {
|
|
1132
|
+
const config = loadConfig();
|
|
1133
|
+
const { computeRecurrences } = await import("./recurrences.js");
|
|
1134
|
+
const data = computeRecurrences(config);
|
|
1135
|
+
if (opts.json) {
|
|
1136
|
+
console.log(JSON.stringify(data));
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
if (data.groupes.length > 0) {
|
|
1140
|
+
console.log(`\n🔁 Sujets récurrents (${data.groupes.length}):`);
|
|
1141
|
+
for (const g of data.groupes.slice(0, 10)) {
|
|
1142
|
+
const freq = g.freqJours !== null ? ` · tous les ~${g.freqJours}j` : "";
|
|
1143
|
+
console.log(` "${g.titre}" ${g.count} fois${freq}`);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
else {
|
|
1147
|
+
console.log("\n Aucun sujet récurrent (minimum 5 conversations similaires).");
|
|
1148
|
+
}
|
|
1149
|
+
if (data.erreurs.length > 0) {
|
|
1150
|
+
console.log(`\n⚠️ Erreurs répétées (${data.erreurs.length}):`);
|
|
1151
|
+
for (const e of data.erreurs.slice(0, 5)) {
|
|
1152
|
+
console.log(` ${e.statut} ×${e.count} ${e.texte.slice(0, 80)}`);
|
|
1153
|
+
}
|
|
1154
|
+
}
|
|
1155
|
+
if (data.artifacts.length > 0) {
|
|
1156
|
+
console.log(`\n📦 Éléments par type:`);
|
|
1157
|
+
for (const a of data.artifacts) {
|
|
1158
|
+
console.log(` ${a.kind}: ${a.count}`);
|
|
1159
|
+
}
|
|
1160
|
+
}
|
|
1161
|
+
console.log();
|
|
1162
|
+
});
|
|
1163
|
+
// ── patterns / skill / install-skill ──────────────────────────────────────────
|
|
1164
|
+
program
|
|
1165
|
+
.command("patterns")
|
|
1166
|
+
.description("Find the tasks you keep asking Claude to do, that could become skills")
|
|
1167
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1168
|
+
.option("--cached", "Only read the last analysis, no LLM call")
|
|
1169
|
+
.option("--force", "Analyse every project again")
|
|
1170
|
+
.action(async (opts) => {
|
|
1171
|
+
const config = loadConfig();
|
|
1172
|
+
const { findPatterns, readPatterns } = await import("./patterns.js");
|
|
1173
|
+
const { runClaude } = await import("./digest.js");
|
|
1174
|
+
let result;
|
|
1175
|
+
try {
|
|
1176
|
+
result = opts.cached
|
|
1177
|
+
? readPatterns(config)
|
|
1178
|
+
: findPatterns(config, (prompt, model) => runClaude(prompt, model), {
|
|
1179
|
+
force: opts.force,
|
|
1180
|
+
onProgress: (done, total, projet) => {
|
|
1181
|
+
if (opts.json)
|
|
1182
|
+
process.stderr.write(`PROGRESS ${done}/${total} ${projet}\n`);
|
|
1183
|
+
else
|
|
1184
|
+
console.log(` [${done + 1}/${total}] ${projet}…`);
|
|
1185
|
+
},
|
|
1186
|
+
});
|
|
1187
|
+
}
|
|
1188
|
+
catch (e) {
|
|
1189
|
+
if (opts.json) {
|
|
1190
|
+
console.log(JSON.stringify({ error: e.message }));
|
|
1191
|
+
return;
|
|
1192
|
+
} // the app shows the message
|
|
1193
|
+
console.error(`✗ ${e.message}`);
|
|
1194
|
+
process.exitCode = 1;
|
|
1195
|
+
return;
|
|
1196
|
+
}
|
|
1197
|
+
if (opts.json) {
|
|
1198
|
+
console.log(JSON.stringify(result));
|
|
1199
|
+
return;
|
|
1200
|
+
}
|
|
1201
|
+
if (result.patterns.length === 0) {
|
|
1202
|
+
console.log("\n Aucune tâche répétée trouvée pour l'instant.");
|
|
1203
|
+
}
|
|
1204
|
+
else {
|
|
1205
|
+
console.log(`\n🔁 Ce qui pourrait devenir un skill (${result.patterns.length}) :`);
|
|
1206
|
+
for (const p of result.patterns) {
|
|
1207
|
+
const vu = [p.count ? `${p.count} fois` : "", p.sources?.length ? `fichiers : ${p.sources.join(", ")}` : ""].filter(Boolean).join(" · ");
|
|
1208
|
+
console.log(` ${p.nom} — ${vu} · ${p.projet}${p.installe ? " · installé" : p.skillPath ? " · brouillon" : ""}`);
|
|
1209
|
+
console.log(` id : ${p.id}`);
|
|
1210
|
+
}
|
|
1211
|
+
}
|
|
1212
|
+
if (result.running)
|
|
1213
|
+
console.log("\n Une analyse est déjà en cours (l'app ou un autre terminal).");
|
|
1214
|
+
else if (result.stale > 0)
|
|
1215
|
+
console.log(`\n ${result.stale} projet(s) ont changé : « brain patterns » pour les relire.`);
|
|
1216
|
+
console.log();
|
|
1217
|
+
});
|
|
1218
|
+
program
|
|
1219
|
+
.command("usage")
|
|
1220
|
+
.description("Which memories your agents use the most, the most useful ones, the ones that never served")
|
|
1221
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1222
|
+
.action(async (opts) => {
|
|
1223
|
+
const config = loadConfig();
|
|
1224
|
+
const { usageReport } = await import("./usage.js");
|
|
1225
|
+
const r = usageReport(config);
|
|
1226
|
+
if (opts.json) {
|
|
1227
|
+
console.log(JSON.stringify(r));
|
|
1228
|
+
return;
|
|
1229
|
+
}
|
|
1230
|
+
console.log(`\n📊 Mémoire utilisée : ${r.used}/${r.memories} souvenirs ont déjà servi`);
|
|
1231
|
+
console.log(` 30 derniers jours : ${r.uses30} utilisations dans ${r.sessions30} sessions (${r.picks30} cherchées par l'agent lui-même)`);
|
|
1232
|
+
const list = (title, items, what) => {
|
|
1233
|
+
if (!items.length)
|
|
1234
|
+
return;
|
|
1235
|
+
console.log(`\n${title}`);
|
|
1236
|
+
for (const u of items)
|
|
1237
|
+
console.log(` ${what(u).padEnd(14)} [${u.project}] ${u.text.slice(0, 90)}`);
|
|
1238
|
+
};
|
|
1239
|
+
list("Les plus utilisés (30 jours)", r.top.month, u => `${u.uses}×`);
|
|
1240
|
+
list("Les plus utiles", r.useful, u => `${u.sessions} sessions`);
|
|
1241
|
+
list(`Jamais utilisés (${r.unusedCount})`, r.unused.slice(0, 10), u => u.date);
|
|
1242
|
+
if (r.archivedCount)
|
|
1243
|
+
console.log(`\n ${r.archivedCount} souvenir(s) archivé(s) : « brain restore <id> » pour en ramener un.`);
|
|
1244
|
+
console.log();
|
|
1245
|
+
});
|
|
1246
|
+
/** After memories leave or come back: pages, search index, hooks and the galaxy follow. */
|
|
1247
|
+
async function refreshAfterArchive(config, message) {
|
|
1248
|
+
rebuildAllPages(config);
|
|
1249
|
+
try {
|
|
1250
|
+
rebuildFts(config);
|
|
1251
|
+
writeHooksConfig(config);
|
|
1252
|
+
}
|
|
1253
|
+
catch { /* the next ingest rebuilds it */ }
|
|
1254
|
+
try {
|
|
1255
|
+
const { buildGraph, saveGraphJson } = await import("./graph.js");
|
|
1256
|
+
saveGraphJson(config, buildGraph(config));
|
|
1257
|
+
}
|
|
1258
|
+
catch { /* the next index rebuilds it */ }
|
|
1259
|
+
gitCommit(config, message);
|
|
1260
|
+
}
|
|
1261
|
+
program
|
|
1262
|
+
.command("archive <ids...>")
|
|
1263
|
+
.description("Take memories out of what the agents read (kept aside: « brain restore » brings them back)")
|
|
1264
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1265
|
+
.action(async (ids, opts) => {
|
|
1266
|
+
const config = loadConfig();
|
|
1267
|
+
const { archiveMemories } = await import("./archive.js");
|
|
1268
|
+
const n = archiveMemories(config, ids);
|
|
1269
|
+
if (n)
|
|
1270
|
+
await quiet(opts.json, () => refreshAfterArchive(config, `brain: ${n} souvenir(s) archivé(s)`));
|
|
1271
|
+
if (opts.json) {
|
|
1272
|
+
console.log(JSON.stringify({ archived: n }));
|
|
1273
|
+
return;
|
|
1274
|
+
}
|
|
1275
|
+
console.log(n ? `✓ ${n} souvenir(s) archivé(s). « brain restore <id> » pour en ramener.` : "Aucun de ces ids dans la mémoire.");
|
|
1276
|
+
});
|
|
1277
|
+
program
|
|
1278
|
+
.command("restore <ids...>")
|
|
1279
|
+
.description("Bring archived memories back")
|
|
1280
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1281
|
+
.action(async (ids, opts) => {
|
|
1282
|
+
const config = loadConfig();
|
|
1283
|
+
const { restoreMemories } = await import("./archive.js");
|
|
1284
|
+
const n = restoreMemories(config, ids);
|
|
1285
|
+
if (n)
|
|
1286
|
+
await quiet(opts.json, () => refreshAfterArchive(config, `brain: ${n} souvenir(s) restauré(s)`));
|
|
1287
|
+
if (opts.json) {
|
|
1288
|
+
console.log(JSON.stringify({ restored: n }));
|
|
1289
|
+
return;
|
|
1290
|
+
}
|
|
1291
|
+
console.log(n ? `✓ ${n} souvenir(s) de retour dans la mémoire.` : "Aucun de ces ids dans les archives.");
|
|
1292
|
+
});
|
|
1293
|
+
/** With --json, stdout is for the app's JSON only: the logs of a step go to stderr. */
|
|
1294
|
+
async function quiet(json, fn) {
|
|
1295
|
+
if (!json)
|
|
1296
|
+
return fn();
|
|
1297
|
+
const log = console.log;
|
|
1298
|
+
console.log = (...a) => process.stderr.write(a.join(" ") + "\n");
|
|
1299
|
+
try {
|
|
1300
|
+
await fn();
|
|
1301
|
+
}
|
|
1302
|
+
finally {
|
|
1303
|
+
console.log = log;
|
|
1304
|
+
}
|
|
1305
|
+
}
|
|
1306
|
+
// ── mochis ───────────────────────────────────────────────────────────────────
|
|
1307
|
+
const mochi = program.command("mochi").description("Mochis: small agents that work from your memory");
|
|
1308
|
+
const cliPath = () => new URL(import.meta.url).pathname;
|
|
1309
|
+
mochi
|
|
1310
|
+
.command("list")
|
|
1311
|
+
.description("The Mochis, their schedule and their last run")
|
|
1312
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1313
|
+
.action(async (opts) => {
|
|
1314
|
+
const config = loadConfig();
|
|
1315
|
+
const { mochiStatuses, schedulerInstalled } = await import("./mochis.js");
|
|
1316
|
+
const list = mochiStatuses(config);
|
|
1317
|
+
if (opts.json) {
|
|
1318
|
+
console.log(JSON.stringify({ scheduler: schedulerInstalled(), mochis: list }));
|
|
1319
|
+
return;
|
|
1320
|
+
}
|
|
1321
|
+
for (const m of list) {
|
|
1322
|
+
const last = m.last ? `${m.last.status} ${m.last.t.slice(0, 16).replace("T", " ")}` : "jamais lancé";
|
|
1323
|
+
console.log(`${m.enabled ? "●" : "○"} ${m.name} (${m.id}) · ${m.schedule} · ${m.level} · ${last}`);
|
|
1324
|
+
}
|
|
1325
|
+
});
|
|
1326
|
+
mochi
|
|
1327
|
+
.command("run <id>")
|
|
1328
|
+
.description("Run a Mochi now")
|
|
1329
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1330
|
+
.option("--scheduled", "Count it as a scheduled run (Coucou shows it in the notch when it ends)")
|
|
1331
|
+
.option("--mail <base64>", "For a mail Mochi: the mail, as JSON in base64 {from, subject, date, text, account, mailbox, messageId}")
|
|
1332
|
+
.action(async (id, opts) => {
|
|
1333
|
+
const config = loadConfig();
|
|
1334
|
+
const { runMochi } = await import("./mochis.js");
|
|
1335
|
+
let r;
|
|
1336
|
+
try {
|
|
1337
|
+
const mail = opts.mail ? JSON.parse(Buffer.from(opts.mail, "base64").toString("utf8")) : undefined;
|
|
1338
|
+
r = runMochi(config, id, { trigger: mail ? "mail" : opts.scheduled ? "schedule" : "manual", mail });
|
|
1339
|
+
}
|
|
1340
|
+
catch (e) {
|
|
1341
|
+
if (opts.json) {
|
|
1342
|
+
console.log(JSON.stringify({ status: "error", error: e.message }));
|
|
1343
|
+
return;
|
|
1344
|
+
}
|
|
1345
|
+
throw e;
|
|
1346
|
+
}
|
|
1347
|
+
if (opts.json) {
|
|
1348
|
+
console.log(JSON.stringify(r));
|
|
1349
|
+
return;
|
|
1350
|
+
}
|
|
1351
|
+
if (r.status === "ok")
|
|
1352
|
+
console.log(r.output);
|
|
1353
|
+
else
|
|
1354
|
+
console.error(`✗ ${r.status} : ${r.error ?? ""}`);
|
|
1355
|
+
});
|
|
1356
|
+
mochi
|
|
1357
|
+
.command("runs <id>")
|
|
1358
|
+
.description("The last runs of a Mochi")
|
|
1359
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1360
|
+
.action(async (id, opts) => {
|
|
1361
|
+
const config = loadConfig();
|
|
1362
|
+
const { readRuns } = await import("./mochis.js");
|
|
1363
|
+
const runs = readRuns(config, id).slice(-30).reverse();
|
|
1364
|
+
if (opts.json) {
|
|
1365
|
+
console.log(JSON.stringify(runs));
|
|
1366
|
+
return;
|
|
1367
|
+
}
|
|
1368
|
+
for (const r of runs)
|
|
1369
|
+
console.log(`${r.t.slice(0, 16).replace("T", " ")} ${r.status} ${r.trigger} ${(r.ms / 1000).toFixed(0)} s ${r.error ?? r.file ?? ""}`);
|
|
1370
|
+
});
|
|
1371
|
+
mochi
|
|
1372
|
+
.command("enable <id> <state>")
|
|
1373
|
+
.description("Turn a Mochi on or off (on|off); wakes or stops the scheduler")
|
|
1374
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1375
|
+
.action(async (id, state, opts) => {
|
|
1376
|
+
const config = loadConfig();
|
|
1377
|
+
const { setEnabled, syncScheduler } = await import("./mochis.js");
|
|
1378
|
+
const ok = setEnabled(config, id, state === "on");
|
|
1379
|
+
let scheduler = false, error;
|
|
1380
|
+
try {
|
|
1381
|
+
scheduler = syncScheduler(config, cliPath());
|
|
1382
|
+
}
|
|
1383
|
+
catch (e) {
|
|
1384
|
+
error = e.message;
|
|
1385
|
+
}
|
|
1386
|
+
if (opts.json) {
|
|
1387
|
+
console.log(JSON.stringify({ ok, scheduler, error }));
|
|
1388
|
+
return;
|
|
1389
|
+
}
|
|
1390
|
+
console.log(ok ? `✓ ${id} : ${state}${scheduler ? " · planification active" : ""}` : `Mochi introuvable : ${id}`);
|
|
1391
|
+
if (error)
|
|
1392
|
+
console.error(`⚠️ ${error}`);
|
|
1393
|
+
});
|
|
1394
|
+
mochi
|
|
1395
|
+
.command("show <id>")
|
|
1396
|
+
.description("A Mochi's settings and instructions")
|
|
1397
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1398
|
+
.action(async (id, opts) => {
|
|
1399
|
+
const config = loadConfig();
|
|
1400
|
+
const { loadMochi } = await import("./mochis.js");
|
|
1401
|
+
const m = loadMochi(config, id);
|
|
1402
|
+
if (opts.json) {
|
|
1403
|
+
console.log(JSON.stringify(m ?? { error: `Mochi introuvable : ${id}` }));
|
|
1404
|
+
return;
|
|
1405
|
+
}
|
|
1406
|
+
if (!m) {
|
|
1407
|
+
console.error(`Mochi introuvable : ${id}`);
|
|
1408
|
+
process.exitCode = 1;
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
console.log(fs.readFileSync(m.file, "utf8"));
|
|
1412
|
+
});
|
|
1413
|
+
mochi
|
|
1414
|
+
.command("save")
|
|
1415
|
+
.description("Create or rewrite a Mochi from JSON (base64): {id?, name, instructions, schedule, color, outfit, budget, access}")
|
|
1416
|
+
.requiredOption("--data <base64>", "The Mochi, as JSON in base64")
|
|
1417
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1418
|
+
.action(async (opts) => {
|
|
1419
|
+
const config = loadConfig();
|
|
1420
|
+
const { saveMochi, syncScheduler } = await import("./mochis.js");
|
|
1421
|
+
try {
|
|
1422
|
+
const m = saveMochi(config, JSON.parse(Buffer.from(opts.data, "base64").toString("utf8")));
|
|
1423
|
+
let scheduler = false;
|
|
1424
|
+
try {
|
|
1425
|
+
scheduler = syncScheduler(config, cliPath());
|
|
1426
|
+
}
|
|
1427
|
+
catch { /* shown by enable */ }
|
|
1428
|
+
if (opts.json) {
|
|
1429
|
+
console.log(JSON.stringify({ id: m.id, scheduler }));
|
|
1430
|
+
return;
|
|
1431
|
+
}
|
|
1432
|
+
console.log(`✓ ${m.name} (${m.id})`);
|
|
1433
|
+
}
|
|
1434
|
+
catch (e) {
|
|
1435
|
+
if (opts.json) {
|
|
1436
|
+
console.log(JSON.stringify({ error: e.message }));
|
|
1437
|
+
return;
|
|
1438
|
+
}
|
|
1439
|
+
console.error(`✗ ${e.message}`);
|
|
1440
|
+
process.exitCode = 1;
|
|
1441
|
+
}
|
|
1442
|
+
});
|
|
1443
|
+
mochi
|
|
1444
|
+
.command("from-pattern <id>")
|
|
1445
|
+
.description("Draft a Mochi from one pattern (see brain patterns); nothing is saved")
|
|
1446
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1447
|
+
.action(async (id, opts) => {
|
|
1448
|
+
const config = loadConfig();
|
|
1449
|
+
const { mochiFromPattern } = await import("./mochis.js");
|
|
1450
|
+
const { runClaude } = await import("./digest.js");
|
|
1451
|
+
if (!opts.json)
|
|
1452
|
+
console.log("\n Claude relit les conversations de cette tâche et écrit le Mochi (1 à 2 minutes)…");
|
|
1453
|
+
try {
|
|
1454
|
+
const r = mochiFromPattern(config, id, (prompt, model) => runClaude(prompt, model));
|
|
1455
|
+
if (opts.json) {
|
|
1456
|
+
console.log(JSON.stringify(r));
|
|
1457
|
+
return;
|
|
1458
|
+
}
|
|
1459
|
+
console.log(`\n${r.name} · ${r.schedule}\n\n${r.instructions}\n`);
|
|
1460
|
+
}
|
|
1461
|
+
catch (e) {
|
|
1462
|
+
if (opts.json) {
|
|
1463
|
+
console.log(JSON.stringify({ error: e.message }));
|
|
1464
|
+
return;
|
|
1465
|
+
}
|
|
1466
|
+
console.error(`✗ ${e.message}`);
|
|
1467
|
+
process.exitCode = 1;
|
|
1468
|
+
}
|
|
1469
|
+
});
|
|
1470
|
+
mochi
|
|
1471
|
+
.command("remove <id>")
|
|
1472
|
+
.description("Remove a Mochi (its file goes to .state/mochis-trash/)")
|
|
1473
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1474
|
+
.action(async (id, opts) => {
|
|
1475
|
+
const config = loadConfig();
|
|
1476
|
+
const { removeMochi, syncScheduler } = await import("./mochis.js");
|
|
1477
|
+
const ok = removeMochi(config, id);
|
|
1478
|
+
try {
|
|
1479
|
+
syncScheduler(config, cliPath());
|
|
1480
|
+
}
|
|
1481
|
+
catch { /* nothing left to schedule */ }
|
|
1482
|
+
if (opts.json) {
|
|
1483
|
+
console.log(JSON.stringify({ ok }));
|
|
1484
|
+
return;
|
|
1485
|
+
}
|
|
1486
|
+
console.log(ok ? `✓ ${id} retiré` : `Mochi introuvable : ${id}`);
|
|
1487
|
+
});
|
|
1488
|
+
mochi
|
|
1489
|
+
.command("due")
|
|
1490
|
+
.description("Run the Mochis whose time has come (launchd calls this every 15 minutes)")
|
|
1491
|
+
.action(async () => {
|
|
1492
|
+
const config = loadConfig();
|
|
1493
|
+
const { runDue } = await import("./mochis.js");
|
|
1494
|
+
for (const r of runDue(config))
|
|
1495
|
+
console.log(`${new Date().toISOString()} ${r.status} ${r.file ?? r.error ?? ""}`);
|
|
1496
|
+
});
|
|
1497
|
+
mochi
|
|
1498
|
+
.command("key")
|
|
1499
|
+
.description("Store an Anthropic API key in the macOS Keychain, for the Mochis set to access: api")
|
|
1500
|
+
.action(async () => {
|
|
1501
|
+
const { storeApiKeyInteractive } = await import("./mochis.js");
|
|
1502
|
+
console.log("Colle ta clé API Anthropic (elle ne s'affiche pas) :");
|
|
1503
|
+
console.log(storeApiKeyInteractive() ? "✓ Clé rangée dans le Trousseau (« Coucou Mochis »)." : "✗ La clé n'a pas été enregistrée.");
|
|
1504
|
+
});
|
|
1505
|
+
program
|
|
1506
|
+
.command("skill <id>")
|
|
1507
|
+
.description("Write a skill draft from the conversations of one pattern (see brain patterns)")
|
|
1508
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1509
|
+
.action(async (id, opts) => {
|
|
1510
|
+
const config = loadConfig();
|
|
1511
|
+
const { generateSkill } = await import("./patterns.js");
|
|
1512
|
+
const { runClaude } = await import("./digest.js");
|
|
1513
|
+
if (!opts.json)
|
|
1514
|
+
console.log("\n Claude relit les conversations de cette tâche et écrit le skill (1 à 3 minutes)…");
|
|
1515
|
+
try {
|
|
1516
|
+
const r = generateSkill(config, id, (prompt, model) => runClaude(prompt, model));
|
|
1517
|
+
if (opts.json) {
|
|
1518
|
+
console.log(JSON.stringify(r));
|
|
1519
|
+
return;
|
|
1520
|
+
}
|
|
1521
|
+
console.log(`\n✓ Brouillon écrit : ${r.path}\n Relis-le, puis « brain install-skill ${id} ».\n`);
|
|
1522
|
+
}
|
|
1523
|
+
catch (e) {
|
|
1524
|
+
if (opts.json) {
|
|
1525
|
+
console.log(JSON.stringify({ error: e.message }));
|
|
1526
|
+
return;
|
|
1527
|
+
} // the app shows the message
|
|
1528
|
+
console.error(`✗ ${e.message}`);
|
|
1529
|
+
process.exitCode = 1;
|
|
1530
|
+
}
|
|
1531
|
+
});
|
|
1532
|
+
program
|
|
1533
|
+
.command("install-skill <id>")
|
|
1534
|
+
.description("Install a reviewed skill draft in ~/.claude/skills (an existing one is backed up first)")
|
|
1535
|
+
.option("--json", "Output JSON (Coucou app)")
|
|
1536
|
+
.action(async (id, opts) => {
|
|
1537
|
+
const config = loadConfig();
|
|
1538
|
+
const { installSkill } = await import("./patterns.js");
|
|
1539
|
+
try {
|
|
1540
|
+
const r = installSkill(config, id);
|
|
1541
|
+
if (opts.json) {
|
|
1542
|
+
console.log(JSON.stringify(r));
|
|
1543
|
+
return;
|
|
1544
|
+
}
|
|
1545
|
+
console.log(`\n✓ Installé : ${r.path}${r.backup ? `\n Ancienne version gardée : ${r.backup}` : ""}\n`);
|
|
1546
|
+
}
|
|
1547
|
+
catch (e) {
|
|
1548
|
+
if (opts.json) {
|
|
1549
|
+
console.log(JSON.stringify({ error: e.message }));
|
|
1550
|
+
return;
|
|
1551
|
+
} // the app shows the message
|
|
1552
|
+
console.error(`✗ ${e.message}`);
|
|
1553
|
+
process.exitCode = 1;
|
|
1554
|
+
}
|
|
1555
|
+
});
|
|
1556
|
+
// ── status ────────────────────────────────────────────────────────────────────
|
|
1557
|
+
program
|
|
1558
|
+
.command("status")
|
|
1559
|
+
.description("Show current brain status: depth, raw index, manifest progress, pause")
|
|
1560
|
+
.option("--json", "Output raw JSON for programmatic use (Coucou app)")
|
|
1561
|
+
.action(async (opts) => {
|
|
1562
|
+
const config = loadConfig();
|
|
1563
|
+
const { getRawStats, rawDbPath } = await import("./rawindex.js");
|
|
1564
|
+
const brainBase = expandHome(config.brainPath);
|
|
1565
|
+
// Raw index stats
|
|
1566
|
+
const rawIndex = getRawStats(config);
|
|
1567
|
+
// Manifest stats (optional — may not exist at Level 1)
|
|
1568
|
+
let manifestStats = null;
|
|
1569
|
+
const manifestPath = path.join(brainBase, ".state", "manifest.db");
|
|
1570
|
+
if (fs.existsSync(manifestPath)) {
|
|
1571
|
+
try {
|
|
1572
|
+
const { Manifest } = await import("./manifest.js");
|
|
1573
|
+
const manifest = new Manifest(config.brainPath);
|
|
1574
|
+
const sessions = manifest.getAllSessions();
|
|
1575
|
+
const convs = manifest.getAllDesktopConversations?.() ?? [];
|
|
1576
|
+
manifest.close();
|
|
1577
|
+
manifestStats = {
|
|
1578
|
+
sessions: {
|
|
1579
|
+
total: sessions.length,
|
|
1580
|
+
done: sessions.filter((s) => s.status === "done").length,
|
|
1581
|
+
pending: sessions.filter((s) => s.status === "pending").length,
|
|
1582
|
+
failed: sessions.filter((s) => s.status === "failed").length,
|
|
1583
|
+
ignored: sessions.filter((s) => s.status === "ignored").length,
|
|
1584
|
+
},
|
|
1585
|
+
conversations: {
|
|
1586
|
+
total: convs.length,
|
|
1587
|
+
done: convs.filter((c) => c.status === "done").length,
|
|
1588
|
+
},
|
|
1589
|
+
};
|
|
1590
|
+
}
|
|
1591
|
+
catch { }
|
|
1592
|
+
}
|
|
1593
|
+
// Pause status
|
|
1594
|
+
const pausedFlag = path.join(brainBase, ".state", "paused");
|
|
1595
|
+
const pause = fs.existsSync(pausedFlag)
|
|
1596
|
+
? fs.readFileSync(pausedFlag, "utf8").trim()
|
|
1597
|
+
: null;
|
|
1598
|
+
const status = {
|
|
1599
|
+
depth: config.depth ?? "search",
|
|
1600
|
+
rawIndex,
|
|
1601
|
+
manifest: manifestStats,
|
|
1602
|
+
pause,
|
|
1603
|
+
dailyLimit: config.dailyLimit ?? 50,
|
|
1604
|
+
concurrency: config.concurrency ?? 3,
|
|
1605
|
+
};
|
|
1606
|
+
if (opts.json) {
|
|
1607
|
+
console.log(JSON.stringify(status));
|
|
1608
|
+
return;
|
|
1609
|
+
}
|
|
1610
|
+
console.log(`\n🧠 Brain status`);
|
|
1611
|
+
console.log(` Depth: ${status.depth}`);
|
|
1612
|
+
if (rawIndex) {
|
|
1613
|
+
console.log(` Raw index: ${rawIndex.messages.toLocaleString()} messages · ${rawIndex.conversations} conversations · ${rawIndex.sessions} sessions`);
|
|
1614
|
+
}
|
|
1615
|
+
else {
|
|
1616
|
+
console.log(` Raw index: absent (lance "brain index")`);
|
|
1617
|
+
}
|
|
1618
|
+
if (manifestStats) {
|
|
1619
|
+
const s = manifestStats.sessions;
|
|
1620
|
+
console.log(` Sessions: ${s.total} total · ${s.done} digérées · ${s.pending} pending · ${s.failed} échouées`);
|
|
1621
|
+
}
|
|
1622
|
+
if (pause) {
|
|
1623
|
+
console.log(` ⏸ En pause depuis ${pause.slice(0, 16)} UTC`);
|
|
1624
|
+
}
|
|
1625
|
+
else {
|
|
1626
|
+
console.log(` Pause: non`);
|
|
1627
|
+
}
|
|
1628
|
+
console.log();
|
|
1629
|
+
});
|
|
1630
|
+
// ── import (Level 1 — raw FTS, alias for index --claude-export) ───────────────
|
|
1631
|
+
program
|
|
1632
|
+
.command("import <zip>")
|
|
1633
|
+
.description("Import a Claude.ai conversations export (zip or folder) into the raw FTS index")
|
|
1634
|
+
.option("--json", "Output result as JSON")
|
|
1635
|
+
.action(async (zip, opts) => {
|
|
1636
|
+
const config = loadConfig();
|
|
1637
|
+
assertNoRemote(config.brainPath);
|
|
1638
|
+
const { rebuildRawIndex } = await import("./rawindex.js");
|
|
1639
|
+
const resolved = expandHome(zip);
|
|
1640
|
+
if (!fs.existsSync(resolved)) {
|
|
1641
|
+
if (opts.json) {
|
|
1642
|
+
console.log(JSON.stringify({ error: "file_not_found", path: resolved }));
|
|
1643
|
+
}
|
|
1644
|
+
else {
|
|
1645
|
+
console.error(`Fichier introuvable : ${resolved}`);
|
|
1646
|
+
process.exitCode = 1;
|
|
1647
|
+
}
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
const result = rebuildRawIndex(config, {
|
|
1651
|
+
claudeExportPath: zip,
|
|
1652
|
+
onProgress: opts.json ? undefined : (msg) => console.log(msg),
|
|
1653
|
+
});
|
|
1654
|
+
if (opts.json) {
|
|
1655
|
+
console.log(JSON.stringify({
|
|
1656
|
+
ok: true,
|
|
1657
|
+
conversations: result.conversations,
|
|
1658
|
+
sessions: result.sessions,
|
|
1659
|
+
messages: result.messages,
|
|
1660
|
+
durationMs: result.durationMs,
|
|
1661
|
+
}));
|
|
1662
|
+
}
|
|
1663
|
+
else {
|
|
1664
|
+
const secs = (result.durationMs / 1000).toFixed(1);
|
|
1665
|
+
console.log(`\n✓ Import terminé en ${secs}s`);
|
|
1666
|
+
console.log(` Conversations : ${result.conversations}`);
|
|
1667
|
+
console.log(` Sessions : ${result.sessions}`);
|
|
1668
|
+
console.log(` Messages : ${result.messages.toLocaleString()}`);
|
|
1669
|
+
}
|
|
1670
|
+
});
|
|
1671
|
+
// ── config set ────────────────────────────────────────────────────────────────
|
|
1672
|
+
{
|
|
1673
|
+
const configCmd = program
|
|
1674
|
+
.command("config")
|
|
1675
|
+
.description("Read or modify brain configuration");
|
|
1676
|
+
configCmd
|
|
1677
|
+
.command("set <key> <value>")
|
|
1678
|
+
.description("Set a config value in ~/CoucouBrain/.state/config.json (keys: depth, dailyLimit, concurrency)")
|
|
1679
|
+
.option("--json", "Output result as JSON")
|
|
1680
|
+
.action(async (key, value, opts) => {
|
|
1681
|
+
const validKeys = ["depth", "dailyLimit", "concurrency"];
|
|
1682
|
+
if (!validKeys.includes(key)) {
|
|
1683
|
+
if (opts.json) {
|
|
1684
|
+
console.log(JSON.stringify({ error: "invalid_key", key, validKeys }));
|
|
1685
|
+
}
|
|
1686
|
+
else {
|
|
1687
|
+
console.error(`Clé invalide : ${key}. Valeurs acceptées : ${validKeys.join(", ")}`);
|
|
1688
|
+
process.exitCode = 1;
|
|
1689
|
+
}
|
|
1690
|
+
return;
|
|
1691
|
+
}
|
|
1692
|
+
// Type coerce
|
|
1693
|
+
let coerced;
|
|
1694
|
+
if (key === "depth") {
|
|
1695
|
+
if (!["search", "live", "full"].includes(value)) {
|
|
1696
|
+
if (opts.json) {
|
|
1697
|
+
console.log(JSON.stringify({ error: "invalid_value", key, value }));
|
|
1698
|
+
}
|
|
1699
|
+
else {
|
|
1700
|
+
console.error(`Valeur invalide pour depth : ${value}. Valeurs acceptées : search, live, full`);
|
|
1701
|
+
process.exitCode = 1;
|
|
1702
|
+
}
|
|
1703
|
+
return;
|
|
1704
|
+
}
|
|
1705
|
+
coerced = value;
|
|
1706
|
+
}
|
|
1707
|
+
else {
|
|
1708
|
+
coerced = parseInt(value, 10);
|
|
1709
|
+
if (isNaN(coerced) || coerced < 0) {
|
|
1710
|
+
if (opts.json) {
|
|
1711
|
+
console.log(JSON.stringify({ error: "invalid_value", key, value }));
|
|
1712
|
+
}
|
|
1713
|
+
else {
|
|
1714
|
+
console.error(`Valeur invalide : ${value} (attendu nombre positif)`);
|
|
1715
|
+
process.exitCode = 1;
|
|
1716
|
+
}
|
|
1717
|
+
return;
|
|
1718
|
+
}
|
|
1719
|
+
}
|
|
1720
|
+
// Write to the user's ~/CoucouBrain/.state/config.json (kept across npm updates)
|
|
1721
|
+
const { userConfigPath } = await import("./config.js");
|
|
1722
|
+
const localPath = userConfigPath(loadConfig().brainPath);
|
|
1723
|
+
fs.mkdirSync(path.dirname(localPath), { recursive: true });
|
|
1724
|
+
let local = {};
|
|
1725
|
+
if (fs.existsSync(localPath)) {
|
|
1726
|
+
try {
|
|
1727
|
+
local = JSON.parse(fs.readFileSync(localPath, "utf8"));
|
|
1728
|
+
}
|
|
1729
|
+
catch { }
|
|
1730
|
+
}
|
|
1731
|
+
local[key] = coerced;
|
|
1732
|
+
fs.writeFileSync(localPath, JSON.stringify(local, null, 2) + "\n", "utf8");
|
|
1733
|
+
if (opts.json) {
|
|
1734
|
+
console.log(JSON.stringify({ ok: true, key, value: coerced }));
|
|
1735
|
+
}
|
|
1736
|
+
else {
|
|
1737
|
+
console.log(`✓ ${key} = ${coerced} (${localPath.replace(os.homedir(), "~")})`);
|
|
1738
|
+
}
|
|
1739
|
+
});
|
|
1740
|
+
}
|
|
1741
|
+
// ── wipe ──────────────────────────────────────────────────────────────────────
|
|
1742
|
+
program
|
|
1743
|
+
.command("wipe")
|
|
1744
|
+
.description("Delete the raw FTS index (raw.db). Does not affect LLM digestion state.")
|
|
1745
|
+
.option("--yes", "Required to actually run the wipe")
|
|
1746
|
+
.option("--json", "Output result as JSON")
|
|
1747
|
+
.action(async (opts) => {
|
|
1748
|
+
const config = loadConfig();
|
|
1749
|
+
const { rawDbPath } = await import("./rawindex.js");
|
|
1750
|
+
if (!opts.yes) {
|
|
1751
|
+
if (opts.json) {
|
|
1752
|
+
console.log(JSON.stringify({ error: "confirm_required", hint: "add --yes" }));
|
|
1753
|
+
}
|
|
1754
|
+
else {
|
|
1755
|
+
console.log("Ajoute --yes pour effectuer la suppression de raw.db.");
|
|
1756
|
+
console.log("Cela efface l'index de recherche brut. Lance 'brain index' pour le reconstruire.");
|
|
1757
|
+
}
|
|
1758
|
+
return;
|
|
1759
|
+
}
|
|
1760
|
+
const dbPath = rawDbPath(config);
|
|
1761
|
+
const resolved = expandHome(dbPath);
|
|
1762
|
+
if (!fs.existsSync(resolved)) {
|
|
1763
|
+
if (opts.json) {
|
|
1764
|
+
console.log(JSON.stringify({ ok: true, wiped: false, hint: "index_already_absent" }));
|
|
1765
|
+
}
|
|
1766
|
+
else {
|
|
1767
|
+
console.log("Index raw déjà absent.");
|
|
1768
|
+
}
|
|
1769
|
+
return;
|
|
1770
|
+
}
|
|
1771
|
+
fs.unlinkSync(resolved);
|
|
1772
|
+
if (opts.json) {
|
|
1773
|
+
console.log(JSON.stringify({ ok: true, wiped: true }));
|
|
1774
|
+
}
|
|
1775
|
+
else {
|
|
1776
|
+
console.log("✓ raw.db supprimé. Lance 'brain index' pour reconstruire.");
|
|
1777
|
+
}
|
|
1778
|
+
});
|
|
1779
|
+
// ── fts ───────────────────────────────────────────────────────────────────────
|
|
1780
|
+
program
|
|
1781
|
+
.command("fts <query>")
|
|
1782
|
+
.description("Test FTS search directly (debug)")
|
|
1783
|
+
.option("--project <slug>", "Current project slug for boost")
|
|
1784
|
+
.option("--limit <n>", "Max results", parseInt)
|
|
1785
|
+
.action(async (query, opts) => {
|
|
1786
|
+
const config = loadConfig();
|
|
1787
|
+
const { searchFts: sfts, buildFtsQuery } = await import("./fts.js");
|
|
1788
|
+
const ftsQuery = buildFtsQuery(query);
|
|
1789
|
+
console.log("FTS query:", ftsQuery ?? "(vide — pas assez de termes)");
|
|
1790
|
+
if (!ftsQuery)
|
|
1791
|
+
return;
|
|
1792
|
+
const results = sfts(config, query, { project: opts.project, limit: opts.limit ?? 10, threshold: -0.1 });
|
|
1793
|
+
if (results.length === 0) {
|
|
1794
|
+
console.log("Aucun résultat.");
|
|
1795
|
+
return;
|
|
1796
|
+
}
|
|
1797
|
+
for (const r of results) {
|
|
1798
|
+
const mark = r.isCorrection ? "CORRECTION" : r.kind;
|
|
1799
|
+
const warn = r.statut === "❌" || r.statut === "⚠️" ? ` ${r.statut}` : "";
|
|
1800
|
+
console.log(` [${mark}${warn}] ${r.sourceProject.replace(/^proj_/, "")} score=${r.score.toFixed(3)}`);
|
|
1801
|
+
console.log(` ${r.texte.slice(0, 120)}`);
|
|
1802
|
+
}
|
|
1803
|
+
});
|
|
1804
|
+
// ── doctor ────────────────────────────────────────────────────────────────────
|
|
1805
|
+
program
|
|
1806
|
+
.command("doctor")
|
|
1807
|
+
.description("Health check: MCP server, hooks, launchd, last ingest, pause status")
|
|
1808
|
+
.action(async () => {
|
|
1809
|
+
const config = loadConfig();
|
|
1810
|
+
const base = expandHome(config.brainPath);
|
|
1811
|
+
const { spawnSync } = await import("node:child_process");
|
|
1812
|
+
console.log("\n🩺 CoucouBrain Doctor\n");
|
|
1813
|
+
// ── 1. MCP server ─────────────────────────────────────────────────────────
|
|
1814
|
+
// Registered via `claude mcp add --scope user` → stored in ~/.claude.json (not settings.json)
|
|
1815
|
+
let hasMcp = false;
|
|
1816
|
+
const claudeJsonPath = path.join(process.env.CLAUDE_CONFIG_DIR ?? path.join(process.env.HOME ?? "~", ".claude"), "..", ".claude.json");
|
|
1817
|
+
try {
|
|
1818
|
+
const claudeJson = JSON.parse(fs.readFileSync(claudeJsonPath, "utf8"));
|
|
1819
|
+
const servers = claudeJson?.mcpServers ?? {};
|
|
1820
|
+
hasMcp = "coucou-brain" in servers;
|
|
1821
|
+
if (!hasMcp) {
|
|
1822
|
+
// Also try via `claude mcp list` output as fallback
|
|
1823
|
+
const mcpCheck = spawnSync("claude", ["mcp", "list"], { encoding: "utf8", timeout: 5000 });
|
|
1824
|
+
hasMcp = (mcpCheck.stdout ?? "").includes("coucou-brain");
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
catch { }
|
|
1828
|
+
console.log(hasMcp
|
|
1829
|
+
? " [✓] MCP server : coucou-brain enregistré (~/.claude.json)"
|
|
1830
|
+
: " [✗] MCP server : coucou-brain ABSENT — lancez :\n claude mcp add --scope user coucou-brain -- brain mcp");
|
|
1831
|
+
// ── 2. FTS index ─────────────────────────────────────────────────────────
|
|
1832
|
+
const ftsPath = path.join(base, ".state", "fts.db");
|
|
1833
|
+
if (fs.existsSync(ftsPath)) {
|
|
1834
|
+
const stat = fs.statSync(ftsPath);
|
|
1835
|
+
const ageMin = Math.round((Date.now() - stat.mtimeMs) / 60000);
|
|
1836
|
+
console.log(` [✓] Index FTS : ${ftsPath} (${ageMin} min)`);
|
|
1837
|
+
}
|
|
1838
|
+
else {
|
|
1839
|
+
console.log(" [✗] Index FTS : absent — lancez `brain rebuild` ou `brain ingest`");
|
|
1840
|
+
}
|
|
1841
|
+
// ── 3. Hooks config ───────────────────────────────────────────────────────
|
|
1842
|
+
const claudeDir = process.env.CLAUDE_CONFIG_DIR ?? `${process.env.HOME}/.claude`;
|
|
1843
|
+
const hooksConfigPath = `${claudeDir}/brain-hooks.json`;
|
|
1844
|
+
if (fs.existsSync(hooksConfigPath)) {
|
|
1845
|
+
const cfg = JSON.parse(fs.readFileSync(hooksConfigPath, "utf8"));
|
|
1846
|
+
console.log(` [✓] Hooks config : ${hooksConfigPath} (${cfg.updatedAt?.slice(0, 16) ?? "?"} UTC)`);
|
|
1847
|
+
}
|
|
1848
|
+
else {
|
|
1849
|
+
console.log(" [✗] Hooks config : absente — lancez `brain rebuild`");
|
|
1850
|
+
}
|
|
1851
|
+
// ── 4. Hook smoke test ────────────────────────────────────────────────────
|
|
1852
|
+
const hooksDir = path.join(path.dirname(new URL(import.meta.url).pathname), "..", "hooks");
|
|
1853
|
+
const hookScript = path.join(hooksDir, "brain-session-start.js");
|
|
1854
|
+
if (fs.existsSync(hookScript)) {
|
|
1855
|
+
const fakeInput = JSON.stringify({ session_id: "test-doctor", cwd: process.cwd() });
|
|
1856
|
+
const hookRun = spawnSync("node", [hookScript], {
|
|
1857
|
+
input: fakeInput,
|
|
1858
|
+
encoding: "utf8",
|
|
1859
|
+
timeout: 8000,
|
|
1860
|
+
env: { ...process.env, COUCOU_BRAIN_INTERNAL: undefined },
|
|
1861
|
+
});
|
|
1862
|
+
if (hookRun.status === 0) {
|
|
1863
|
+
const tokens = Math.round((hookRun.stdout ?? "").length / 4);
|
|
1864
|
+
console.log(` [✓] SessionStart hook : OK (${tokens} tokens injectés)`);
|
|
1865
|
+
}
|
|
1866
|
+
else {
|
|
1867
|
+
console.log(` [✗] SessionStart hook : ERREUR (exit ${hookRun.status})\n ${hookRun.stderr?.slice(0, 200)}`);
|
|
1868
|
+
}
|
|
1869
|
+
}
|
|
1870
|
+
else {
|
|
1871
|
+
console.log(` [✗] SessionStart hook : ${hookScript} introuvable`);
|
|
1872
|
+
}
|
|
1873
|
+
// ── 5. LaunchD ────────────────────────────────────────────────────────────
|
|
1874
|
+
const launchd = spawnSync("launchctl", ["list", "fr.louisraille.brain-ingest"], {
|
|
1875
|
+
encoding: "utf8", timeout: 5000,
|
|
1876
|
+
});
|
|
1877
|
+
if (launchd.status === 0) {
|
|
1878
|
+
console.log(" [✓] LaunchD : fr.louisraille.brain-ingest chargé");
|
|
1879
|
+
}
|
|
1880
|
+
else {
|
|
1881
|
+
console.log(" [✗] LaunchD : non chargé — voir brain/launchd/fr.louisraille.brain-ingest.plist");
|
|
1882
|
+
}
|
|
1883
|
+
// ── 6. Last ingest ────────────────────────────────────────────────────────
|
|
1884
|
+
const dbPath = path.join(base, ".state", "manifest.db");
|
|
1885
|
+
if (fs.existsSync(dbPath)) {
|
|
1886
|
+
const stat = fs.statSync(dbPath);
|
|
1887
|
+
const ageH = Math.round((Date.now() - stat.mtimeMs) / 3600000);
|
|
1888
|
+
console.log(` [✓] Dernière ingestion : il y a ${ageH}h (${stat.mtime.toISOString().slice(0, 16)} UTC)`);
|
|
1889
|
+
}
|
|
1890
|
+
else {
|
|
1891
|
+
console.log(" [✗] manifest.db absent — aucune ingestion effectuée");
|
|
1892
|
+
}
|
|
1893
|
+
// ── 7. Pause status ───────────────────────────────────────────────────────
|
|
1894
|
+
const pausedFlag = path.join(base, ".state", "paused");
|
|
1895
|
+
if (fs.existsSync(pausedFlag)) {
|
|
1896
|
+
const since = fs.readFileSync(pausedFlag, "utf8").slice(0, 16);
|
|
1897
|
+
console.log(` [⏸] Brain en PAUSE depuis ${since} UTC — lancez 'brain resume' pour réactiver`);
|
|
1898
|
+
}
|
|
1899
|
+
else {
|
|
1900
|
+
console.log(" [✓] Pause : désactivée (hooks actifs)");
|
|
1901
|
+
}
|
|
1902
|
+
// ── 8. Hook log ───────────────────────────────────────────────────────────
|
|
1903
|
+
const logPath = path.join(base, ".state", "logs", "hooks.log");
|
|
1904
|
+
if (fs.existsSync(logPath)) {
|
|
1905
|
+
const lines = fs.readFileSync(logPath, "utf8").split("\n").filter(Boolean);
|
|
1906
|
+
const last10 = lines.slice(-10);
|
|
1907
|
+
console.log(`\n Journal hooks (dernières ${last10.length} lignes) :`);
|
|
1908
|
+
last10.forEach((l) => console.log(` ${l}`));
|
|
1909
|
+
}
|
|
1910
|
+
else {
|
|
1911
|
+
console.log("\n Journal hooks : absent (aucun hook n'a encore tourné)");
|
|
1912
|
+
}
|
|
1913
|
+
console.log();
|
|
1914
|
+
});
|
|
1915
|
+
program.parse();
|