@tekmidian/pai 0.20.0 → 0.20.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1229 @@
1
+ import { _ as warn, c as ok, i as err, n as dim, r as encodeDir, s as now, t as bold } from "./utils-BAxjW3j8.mjs";
2
+ import { a as slugify, i as parseSessionFilename, n as decodeEncodedDir, t as buildEncodedDirMap } from "./migrate-fLD6rAdO.mjs";
3
+ import { n as ensurePaiMarker, t as discoverPaiMarkers } from "./pai-marker-B20KqhA8.mjs";
4
+ import { i as kgAdd, o as kgInvalidate, r as upsertKgEntity, s as kgQuery } from "./kg-entity-r8duqhi9.mjs";
5
+ import { existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, renameSync, statSync, writeFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { basename, join, resolve } from "node:path";
8
+
9
+ //#region src/registry/moved.ts
10
+ /**
11
+ * moved.ts — reconnect a project to transcripts that moved out from under it.
12
+ *
13
+ * The registry records an `encoded_dir`: the name Claude Code gave the folder
14
+ * holding a project's transcripts. It is written once, when the project is
15
+ * added, and nothing updates it when the project moves. So a project that has
16
+ * been relocated points at a directory that is empty or gone, and every lookup
17
+ * — checkpoints, handovers, session digests — quietly returns nothing.
18
+ *
19
+ * `resolveTranscriptDir` already re-derives the name from the project's current
20
+ * root path, which fixes the case where the encoding is stale but the path is
21
+ * right. It cannot fix the case where the ENCODING RULE itself does not
22
+ * reproduce the folder name: iCloud paths with `~` in them, emoji segments, or
23
+ * a folder Claude Code created under a path the project no longer has.
24
+ *
25
+ * This module answers that case by asking the transcripts instead of guessing.
26
+ * Every transcript entry records the `cwd` it was written in, so the mapping
27
+ * from a project root to its transcript folder is a fact sitting on disk rather
28
+ * than something to be inferred from a naming convention. Reading it is slower
29
+ * than a string transform and it is right, which is the correct trade for a
30
+ * repair that runs on demand.
31
+ */
32
+ /** Where Claude Code keeps per-project transcript folders. */
33
+ function claudeProjectsDir() {
34
+ return join(homedir(), ".claude", "projects");
35
+ }
36
+ /**
37
+ * Every transcript file for one project folder — live and archived.
38
+ *
39
+ * The archived half matters: `session-stop` moves all but the newest transcript
40
+ * into `sessions/`, so a folder whose work is finished has an empty top level
41
+ * and everything underneath. Counting only the top level reports a busy project
42
+ * as unused, which is how an earlier audit of this same problem overstated the
43
+ * breakage by a factor of three.
44
+ */
45
+ function transcriptFiles(projectDir) {
46
+ const out = [];
47
+ for (const dir of [projectDir, join(projectDir, "sessions")]) {
48
+ if (!existsSync(dir)) continue;
49
+ try {
50
+ for (const entry of readdirSync(dir)) if (entry.endsWith(".jsonl")) out.push(join(dir, entry));
51
+ } catch {}
52
+ }
53
+ return out;
54
+ }
55
+ /**
56
+ * The working directory a transcript was recorded in.
57
+ *
58
+ * Reads only the head of the file. `cwd` is present on the first entry and does
59
+ * not change within a session, so scanning further would cost time to learn
60
+ * nothing. Returns null rather than throwing: a truncated or half-written
61
+ * transcript is normal for a session that is still running.
62
+ */
63
+ function cwdOfTranscript(file, maxBytes = 64 * 1024) {
64
+ let head;
65
+ try {
66
+ head = readFileSync(file).subarray(0, maxBytes).toString("utf-8");
67
+ } catch {
68
+ return null;
69
+ }
70
+ for (const line of head.split("\n")) {
71
+ if (!line.trim()) continue;
72
+ try {
73
+ const cwd = JSON.parse(line).cwd;
74
+ if (cwd) return cwd;
75
+ } catch {
76
+ continue;
77
+ }
78
+ }
79
+ return null;
80
+ }
81
+ /**
82
+ * Map every working directory seen on disk to the folders that hold its
83
+ * transcripts.
84
+ *
85
+ * A directory can legitimately map to more than one folder — Claude Code's
86
+ * encoding is lossy, so two different paths can collide, and a project moved
87
+ * and moved back leaves both. Callers pick; this reports.
88
+ */
89
+ function scanTranscriptFolders(projectsDir = claudeProjectsDir(), sampleFilesPerFolder = 8) {
90
+ const byCwd = /* @__PURE__ */ new Map();
91
+ if (!existsSync(projectsDir)) return byCwd;
92
+ let entries;
93
+ try {
94
+ entries = readdirSync(projectsDir);
95
+ } catch {
96
+ return byCwd;
97
+ }
98
+ for (const name of entries) {
99
+ const dir = join(projectsDir, name);
100
+ try {
101
+ if (!statSync(dir).isDirectory()) continue;
102
+ } catch {
103
+ continue;
104
+ }
105
+ const files = transcriptFiles(dir);
106
+ if (files.length === 0) continue;
107
+ const mtimes = /* @__PURE__ */ new Map();
108
+ for (const f of files) try {
109
+ mtimes.set(f, statSync(f).mtimeMs);
110
+ } catch {
111
+ mtimes.set(f, 0);
112
+ }
113
+ const ordered = files.sort((a, b) => (mtimes.get(b) ?? 0) - (mtimes.get(a) ?? 0));
114
+ const newest = mtimes.get(ordered[0]) ?? 0;
115
+ const tally = /* @__PURE__ */ new Map();
116
+ let sampled = 0;
117
+ for (const f of ordered.slice(0, sampleFilesPerFolder)) {
118
+ const cwd = cwdOfTranscript(f);
119
+ if (!cwd) continue;
120
+ sampled++;
121
+ tally.set(cwd, (tally.get(cwd) ?? 0) + 1);
122
+ }
123
+ for (const [cwd, matching] of tally) {
124
+ const record = {
125
+ name,
126
+ count: files.length,
127
+ newest,
128
+ matching,
129
+ total: sampled
130
+ };
131
+ const list = byCwd.get(cwd);
132
+ if (list) list.push(record);
133
+ else byCwd.set(cwd, [record]);
134
+ }
135
+ }
136
+ return byCwd;
137
+ }
138
+ /**
139
+ * Which projects point at the wrong transcript folder, and where they belong.
140
+ *
141
+ * A project is only reported when its stored folder yields nothing AND its root
142
+ * path is recorded as a `cwd` somewhere else. Both halves matter: without the
143
+ * first this would rewrite entries that work, and without the second it would
144
+ * have nothing better to offer than the value already there.
145
+ *
146
+ * `resolvesNow` is supplied by the caller so this module does not have to
147
+ * duplicate the resolver's fallback logic — a project the shipped resolver
148
+ * already handles is not broken and must not be "repaired".
149
+ */
150
+ function findMovedProjects(rows, byCwd, resolvesNow) {
151
+ const out = [];
152
+ for (const row of rows) {
153
+ if (resolvesNow(row)) continue;
154
+ const candidates = byCwd.get(row.root_path);
155
+ if (!candidates || candidates.length === 0) continue;
156
+ const owned = candidates.filter((c) => c.matching * 2 > c.total);
157
+ if (owned.length === 0) continue;
158
+ const best = [...owned].sort((a, b) => b.count - a.count || b.newest - a.newest)[0];
159
+ if (best.name === row.encoded_dir) continue;
160
+ out.push({
161
+ id: row.id,
162
+ slug: row.slug,
163
+ rootPath: row.root_path,
164
+ storedDir: row.encoded_dir,
165
+ correctDir: best.name,
166
+ transcripts: best.count,
167
+ sessions: row.sessions
168
+ });
169
+ }
170
+ return out.sort((a, b) => b.sessions - a.sessions || b.transcripts - a.transcripts);
171
+ }
172
+
173
+ //#endregion
174
+ //#region src/cli/commands/registry/utils.ts
175
+ /**
176
+ * Upsert a project row. Returns { id, isNew }.
177
+ *
178
+ * Matching priority:
179
+ * 1. root_path — most reliable; handles slug collisions
180
+ * 2. encoded_dir — Claude project dirs are canonical
181
+ * 3. Insert with suffix-deduplication on slug collision
182
+ *
183
+ * display_name is set to basename(rootPath) on INSERT so that the unified
184
+ * listing always shows a human-readable name rather than the kebab-case slug.
185
+ */
186
+ function upsertProject(db, slug, rootPath, encodedDir) {
187
+ const ts = now();
188
+ const byPath = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
189
+ if (byPath) {
190
+ const encodedOwner = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir);
191
+ if (!encodedOwner || encodedOwner.id === byPath.id) db.prepare("UPDATE projects SET encoded_dir = ?, updated_at = ? WHERE id = ?").run(encodedDir, ts, byPath.id);
192
+ return {
193
+ id: byPath.id,
194
+ isNew: false
195
+ };
196
+ }
197
+ const byEncoded = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir);
198
+ if (byEncoded) {
199
+ const pathOwner = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
200
+ if (!pathOwner || pathOwner.id === byEncoded.id) db.prepare("UPDATE projects SET root_path = ?, updated_at = ? WHERE id = ?").run(rootPath, ts, byEncoded.id);
201
+ return {
202
+ id: byEncoded.id,
203
+ isNew: false
204
+ };
205
+ }
206
+ let finalSlug = slug;
207
+ let attempt = 0;
208
+ while (true) {
209
+ if (!db.prepare("SELECT id FROM projects WHERE slug = ?").get(finalSlug)) break;
210
+ attempt++;
211
+ finalSlug = `${slug}-${attempt}`;
212
+ }
213
+ const displayName = basename(rootPath) || finalSlug;
214
+ const result = db.prepare(`INSERT OR IGNORE INTO projects
215
+ (slug, display_name, root_path, encoded_dir, type, status, created_at, updated_at)
216
+ VALUES (?, ?, ?, ?, 'local', 'active', ?, ?)`).run(finalSlug, displayName, rootPath, encodedDir, ts, ts);
217
+ if (result.changes === 0) {
218
+ const fallback = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(encodedDir) ?? db.prepare("SELECT id FROM projects WHERE root_path = ?").get(rootPath);
219
+ if (fallback) return {
220
+ id: fallback.id,
221
+ isNew: false
222
+ };
223
+ throw new Error(`upsertProject: INSERT OR IGNORE was suppressed but no matching row found for root_path=${rootPath} encoded_dir=${encodedDir}`);
224
+ }
225
+ return {
226
+ id: result.lastInsertRowid,
227
+ isNew: true
228
+ };
229
+ }
230
+ /** Upsert a session note. Returns true if newly inserted. */
231
+ function upsertSession(db, projectId, number, date, slug, title, filename) {
232
+ if (db.prepare("SELECT id FROM sessions WHERE project_id = ? AND number = ?").get(projectId, number)) return false;
233
+ const ts = now();
234
+ db.prepare(`INSERT INTO sessions
235
+ (project_id, number, date, slug, title, filename, status, created_at)
236
+ VALUES (?, ?, ?, ?, ?, ?, 'completed', ?)`).run(projectId, number, date, slug, title, filename, ts);
237
+ return true;
238
+ }
239
+
240
+ //#endregion
241
+ //#region src/cli/commands/registry/scan.ts
242
+ /** Registry scan command: walk ~/.claude/projects/ and populate the registry. */
243
+ /**
244
+ * Build a reverse map from encoded-dir → real path using the clc session
245
+ * registry (~/.claude/session.json).
246
+ *
247
+ * The clc registry stores { sessions: [{ directory, ... }, ...] }. For each
248
+ * entry with a resolvable directory, we encode the realpath and add it to
249
+ * the map. This lets the scanner recover project paths that are not in
250
+ * Claude's session-registry.json but were registered by clc.
251
+ */
252
+ function buildClcDirMap() {
253
+ const map = /* @__PURE__ */ new Map();
254
+ const sessionFile = join(homedir(), ".claude", "session.json");
255
+ if (!existsSync(sessionFile)) return map;
256
+ try {
257
+ const raw = readFileSync(sessionFile, "utf8");
258
+ const parsed = JSON.parse(raw);
259
+ for (const entry of parsed.sessions ?? []) {
260
+ const dir = entry.directory;
261
+ if (!dir) continue;
262
+ try {
263
+ const real = realpathSync(dir);
264
+ if (!existsSync(real)) continue;
265
+ const encoded = encodeDir(real);
266
+ map.set(encoded, real);
267
+ } catch {}
268
+ }
269
+ } catch {}
270
+ return map;
271
+ }
272
+ const CLAUDE_PROJECTS_DIR = join(homedir(), ".claude", "projects");
273
+ const PAI_CONFIG_DIR = join(homedir(), ".pai");
274
+ const PAI_CONFIG_FILE = join(PAI_CONFIG_DIR, "config.json");
275
+ function loadScanConfig() {
276
+ if (!existsSync(PAI_CONFIG_FILE)) return { scan_dirs: [] };
277
+ try {
278
+ return JSON.parse(readFileSync(PAI_CONFIG_FILE, "utf8"));
279
+ } catch {
280
+ return { scan_dirs: [] };
281
+ }
282
+ }
283
+ function saveScanConfig(config) {
284
+ mkdirSync(PAI_CONFIG_DIR, { recursive: true });
285
+ writeFileSync(PAI_CONFIG_FILE, JSON.stringify(config, null, 2) + "\n", "utf8");
286
+ }
287
+ /**
288
+ * Resolve a path to its canonical form, falling back to the input.
289
+ *
290
+ * Every path that becomes a `projects.root_path` must go through this. That
291
+ * column is UNIQUE, so two spellings of one directory create two projects and
292
+ * split session history between them. The spellings are not hypothetical: a
293
+ * configured scan_dir of `~/dev/ai` (where `~/dev` is a symlink) makes every
294
+ * project under it register under the symlinked path, while a session started
295
+ * from the resolved path registers a rival row.
296
+ */
297
+ function canonicalPath(p) {
298
+ try {
299
+ return realpathSync(p);
300
+ } catch {
301
+ return p;
302
+ }
303
+ }
304
+ function resolveHome(p) {
305
+ if (p.startsWith("~/")) return join(homedir(), p.slice(2));
306
+ return resolve(p);
307
+ }
308
+ /**
309
+ * Recursively find all .md files in a directory, including YYYY/MM subdirectories.
310
+ * Returns filenames (basename only).
311
+ */
312
+ function findNoteFiles(dir) {
313
+ const results = [];
314
+ if (!existsSync(dir)) return results;
315
+ for (const entry of readdirSync(dir, { withFileTypes: true })) if (entry.isFile() && entry.name.endsWith(".md")) results.push(entry.name);
316
+ else if (entry.isDirectory() && /^\d{4}$/.test(entry.name)) {
317
+ const yearDir = join(dir, entry.name);
318
+ for (const monthEntry of readdirSync(yearDir, { withFileTypes: true })) if (monthEntry.isDirectory() && /^\d{2}$/.test(monthEntry.name)) {
319
+ const monthDir = join(yearDir, monthEntry.name);
320
+ for (const noteEntry of readdirSync(monthDir, { withFileTypes: true })) if (noteEntry.isFile() && noteEntry.name.endsWith(".md")) results.push(noteEntry.name);
321
+ }
322
+ }
323
+ return results;
324
+ }
325
+ function performScan(db) {
326
+ const result = {
327
+ projectsScanned: 0,
328
+ projectsNew: 0,
329
+ projectsUpdated: 0,
330
+ sessionsScanned: 0,
331
+ sessionsNew: 0,
332
+ skipped: []
333
+ };
334
+ if (!existsSync(CLAUDE_PROJECTS_DIR)) throw new Error(`Claude projects directory not found: ${CLAUDE_PROJECTS_DIR}`);
335
+ const entries = readdirSync(CLAUDE_PROJECTS_DIR).filter((name) => {
336
+ return statSync(join(CLAUDE_PROJECTS_DIR, name)).isDirectory();
337
+ });
338
+ const lookupMap = buildEncodedDirMap();
339
+ const clcMap = buildClcDirMap();
340
+ for (const encodedDir of entries) {
341
+ let rootPath = decodeEncodedDir(encodedDir, lookupMap);
342
+ if (!existsSync(rootPath) && clcMap.has(encodedDir)) {
343
+ const clcPath = clcMap.get(encodedDir);
344
+ if (existsSync(clcPath)) rootPath = clcPath;
345
+ }
346
+ if (!existsSync(rootPath)) {
347
+ result.skipped.push(`${encodedDir} (decoded: ${rootPath} — path not found on disk)`);
348
+ result.projectsScanned++;
349
+ continue;
350
+ }
351
+ rootPath = canonicalPath(rootPath);
352
+ const slug = slugify(basename(rootPath) || encodedDir);
353
+ const { id, isNew } = upsertProject(db, slug, rootPath, encodedDir);
354
+ result.projectsScanned++;
355
+ if (isNew) result.projectsNew++;
356
+ else result.projectsUpdated++;
357
+ try {
358
+ ensurePaiMarker(rootPath, slug);
359
+ } catch {}
360
+ const claudeNotesDir = join(CLAUDE_PROJECTS_DIR, encodedDir, "Notes");
361
+ if (existsSync(claudeNotesDir)) {
362
+ if (claudeNotesDir !== join(rootPath, "Notes")) db.prepare("UPDATE projects SET claude_notes_dir = ?, updated_at = ? WHERE id = ?").run(claudeNotesDir, Date.now(), id);
363
+ }
364
+ if (!existsSync(claudeNotesDir)) continue;
365
+ const noteFiles = findNoteFiles(claudeNotesDir);
366
+ for (const filename of noteFiles) {
367
+ const parsed = parseSessionFilename(filename);
368
+ if (!parsed) continue;
369
+ result.sessionsScanned++;
370
+ if (upsertSession(db, id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
371
+ }
372
+ }
373
+ {
374
+ const activeProjects = db.prepare("SELECT id, slug, root_path FROM projects WHERE status = 'active'").all();
375
+ for (const project of activeProjects) {
376
+ const notesDir = join(project.root_path, "Notes");
377
+ if (!existsSync(notesDir)) continue;
378
+ let files;
379
+ try {
380
+ files = findNoteFiles(notesDir);
381
+ } catch {
382
+ continue;
383
+ }
384
+ for (const filename of files) {
385
+ const parsed = parseSessionFilename(filename);
386
+ if (!parsed) continue;
387
+ result.sessionsScanned++;
388
+ if (upsertSession(db, project.id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
389
+ }
390
+ }
391
+ }
392
+ const config = loadScanConfig();
393
+ if (config.scan_dirs.length) for (const rawDir of config.scan_dirs) {
394
+ const scanDir = resolveHome(rawDir);
395
+ if (!existsSync(scanDir)) {
396
+ result.skipped.push(`${rawDir} (configured scan_dir not found)`);
397
+ continue;
398
+ }
399
+ const children = readdirSync(scanDir).filter((name) => {
400
+ if (name.startsWith(".")) return false;
401
+ const full = join(scanDir, name);
402
+ try {
403
+ return statSync(full).isDirectory();
404
+ } catch {
405
+ return false;
406
+ }
407
+ });
408
+ for (const child of children) {
409
+ const childPath = canonicalPath(join(scanDir, child));
410
+ const childSlug = slugify(child);
411
+ const childEncoded = encodeDir(childPath);
412
+ const existing = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(childPath);
413
+ if (existing) {
414
+ result.projectsScanned++;
415
+ result.projectsUpdated++;
416
+ try {
417
+ ensurePaiMarker(childPath, childSlug);
418
+ } catch {}
419
+ const notesDir = join(childPath, "Notes");
420
+ if (existsSync(notesDir)) {
421
+ const noteFiles = readdirSync(notesDir).filter((f) => f.endsWith(".md"));
422
+ for (const filename of noteFiles) {
423
+ const parsed = parseSessionFilename(filename);
424
+ if (!parsed) continue;
425
+ result.sessionsScanned++;
426
+ if (upsertSession(db, existing.id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
427
+ }
428
+ }
429
+ continue;
430
+ }
431
+ const { id, isNew } = upsertProject(db, childSlug, childPath, childEncoded);
432
+ result.projectsScanned++;
433
+ if (isNew) result.projectsNew++;
434
+ else result.projectsUpdated++;
435
+ try {
436
+ ensurePaiMarker(childPath, childSlug);
437
+ } catch {}
438
+ const notesDir = join(childPath, "Notes");
439
+ if (existsSync(notesDir)) {
440
+ const noteFiles = readdirSync(notesDir).filter((f) => f.endsWith(".md"));
441
+ for (const filename of noteFiles) {
442
+ const parsed = parseSessionFilename(filename);
443
+ if (!parsed) continue;
444
+ result.sessionsScanned++;
445
+ if (upsertSession(db, id, parsed.number, parsed.date, parsed.slug, parsed.title, parsed.filename)) result.sessionsNew++;
446
+ }
447
+ }
448
+ }
449
+ }
450
+ if (config.scan_dirs.length) {
451
+ const markers = discoverPaiMarkers(config.scan_dirs.map(resolveHome).filter(existsSync));
452
+ for (const marker of markers) {
453
+ const registeredRow = db.prepare("SELECT id, root_path, slug, encoded_dir FROM projects WHERE slug = ?").get(marker.slug);
454
+ if (!registeredRow) continue;
455
+ const markerRoot = canonicalPath(marker.projectRoot);
456
+ if (registeredRow.root_path !== markerRoot) {
457
+ const newEncoded = encodeDir(markerRoot);
458
+ const now4 = Date.now();
459
+ const encodedOwner = db.prepare("SELECT id FROM projects WHERE encoded_dir = ?").get(newEncoded);
460
+ const pathOwner = db.prepare("SELECT id FROM projects WHERE root_path = ?").get(markerRoot);
461
+ const encodedSafe = !encodedOwner || encodedOwner.id === registeredRow.id;
462
+ const pathSafe = !pathOwner || pathOwner.id === registeredRow.id;
463
+ const derivedResolves = transcriptFiles(join(claudeProjectsDir(), newEncoded)).length > 0;
464
+ const currentResolves = Boolean(registeredRow.encoded_dir) && transcriptFiles(join(claudeProjectsDir(), registeredRow.encoded_dir)).length > 0;
465
+ if (encodedSafe && pathSafe && (derivedResolves || !currentResolves)) db.prepare("UPDATE projects SET root_path = ?, encoded_dir = ?, updated_at = ? WHERE id = ?").run(markerRoot, newEncoded, now4, registeredRow.id);
466
+ else if (pathSafe) db.prepare("UPDATE projects SET root_path = ?, updated_at = ? WHERE id = ?").run(markerRoot, now4, registeredRow.id);
467
+ }
468
+ }
469
+ }
470
+ {
471
+ const stale = db.prepare("SELECT id, slug, root_path FROM projects WHERE display_name = slug AND root_path IS NOT NULL AND root_path != ''").all();
472
+ for (const row of stale) {
473
+ const name = basename(row.root_path);
474
+ if (name && name !== row.slug) db.prepare("UPDATE projects SET display_name = ?, updated_at = ? WHERE id = ?").run(name, Date.now(), row.id);
475
+ }
476
+ }
477
+ return result;
478
+ }
479
+ /**
480
+ * Run the registry scan CLI command.
481
+ *
482
+ * @param opts.quick When true, skips verbose output (same scan, less noise).
483
+ * The underlying scan is always incremental via upsert —
484
+ * this flag exists for hook/daemon-triggered invocations that
485
+ * want minimal log output.
486
+ */
487
+ function cmdScan(db, opts = {}) {
488
+ const config = loadScanConfig();
489
+ if (!opts.quick) {
490
+ console.log(dim("Scanning ~/.claude/projects/ ..."));
491
+ if (config.scan_dirs.length) console.log(dim(`Scanning ${config.scan_dirs.length} extra dir(s): ${config.scan_dirs.join(", ")}`));
492
+ console.log(dim("Scanning project-root Notes/ directories ..."));
493
+ }
494
+ let result;
495
+ try {
496
+ result = performScan(db);
497
+ } catch (e) {
498
+ console.error(err(String(e)));
499
+ process.exit(1);
500
+ }
501
+ if (!opts.quick) {
502
+ console.log(ok(`Scanned ${bold(String(result.projectsScanned))} projects, ${bold(String(result.sessionsScanned))} session notes.`));
503
+ console.log(dim(` Projects: ${result.projectsNew} new, ${result.projectsUpdated} updated`));
504
+ console.log(dim(` Sessions: ${result.sessionsNew} new`));
505
+ if (result.skipped.length) {
506
+ console.log();
507
+ console.log(warn(` ${result.skipped.length} project(s) skipped (path not found on disk):`));
508
+ for (const s of result.skipped.slice(0, 10)) console.log(dim(` ${s}`));
509
+ if (result.skipped.length > 10) console.log(dim(` ... and ${result.skipped.length - 10} more`));
510
+ }
511
+ } else process.stderr.write(`[registry-scan] ${result.projectsScanned} projects, ${result.sessionsScanned} sessions (${result.projectsNew}+${result.sessionsNew} new).\n`);
512
+ }
513
+
514
+ //#endregion
515
+ //#region src/daemon/templates/triple-extraction-prompt.ts
516
+ /**
517
+ * triple-extraction-prompt.ts — Prompt template for KG triple extraction.
518
+ *
519
+ * Used by the session-summary-worker to extract structured facts from
520
+ * a completed session summary and store them in the temporal knowledge graph.
521
+ */
522
+ function buildTripleExtractionPrompt(params) {
523
+ return `Extract structured entities and relations from this coding session.
524
+
525
+ Output a single JSON object with two arrays: "entities" and "relations".
526
+
527
+ Entity types: project | person | concept | tool | file | version | decision | technology | organization
528
+
529
+ Rules:
530
+ - Be SPECIFIC: entity names must be concrete (e.g., "FSRS", "Glidr", "Matthias")
531
+ - Use snake_case relation verb phrases (e.g., "uses_algorithm", "decided_to", "shipped_version")
532
+ - Skip opinions, speculation, and "we should" statements
533
+ - Skip entities obvious from project metadata unless they have a meaningful relation
534
+ - Maximum 15 relations per session — pick the most important
535
+ - Each entity should have a brief description (1 sentence, what it is in this context)
536
+ - Each relation must reference entity names that appear in the entities array
537
+
538
+ Example output:
539
+ {
540
+ "entities": [
541
+ {"name": "Glidr", "type": "project", "description": "Flashcard app using FSRS spaced repetition"},
542
+ {"name": "FSRS", "type": "concept", "description": "Free Spaced Repetition Scheduler algorithm"},
543
+ {"name": "Matthias", "type": "person", "description": "Developer of Glidr and Quassl"},
544
+ {"name": "Quassl", "type": "project", "description": "iOS app being rewritten in Flutter"},
545
+ {"name": "Flutter", "type": "technology", "description": "Cross-platform mobile framework"}
546
+ ],
547
+ "relations": [
548
+ {"source": "Glidr", "relation": "uses_algorithm", "target": "FSRS"},
549
+ {"source": "Glidr", "relation": "shipped_version", "target": "1.0.5"},
550
+ {"source": "Matthias", "relation": "decided_to_rewrite", "target": "Quassl"},
551
+ {"source": "Quassl", "relation": "migrating_to", "target": "Flutter"}
552
+ ]
553
+ }
554
+
555
+ PROJECT: ${params.projectSlug}
556
+
557
+ SESSION CONTENT:
558
+ ${params.sessionContent}
559
+
560
+ GIT COMMITS:
561
+ ${params.gitLog}
562
+
563
+ JSON object (entities + relations):`;
564
+ }
565
+
566
+ //#endregion
567
+ //#region src/memory/kg-extraction.ts
568
+ /**
569
+ * kg-extraction.ts — Shared KG triple extraction logic.
570
+ *
571
+ * Extracted from session-summary-worker.ts so both the worker and the
572
+ * CLI backfill (`pai kg backfill`) can use the same code path.
573
+ *
574
+ * Provides:
575
+ * - findClaudeBinary() — locate the claude CLI
576
+ * - spawnClaude() — generic prompt -> response runner (strips ANTHROPIC_API_KEY)
577
+ * - extractAndStoreTriples() — run the extractor prompt and persist triples to Postgres
578
+ */
579
+ /**
580
+ * Find the `claude` CLI binary. Checks common installation locations first
581
+ * (launchd PATH is minimal so bare "claude" often won't resolve).
582
+ */
583
+ function findClaudeBinary() {
584
+ const candidates = [
585
+ join(homedir(), ".local", "bin", "claude"),
586
+ join(homedir(), ".claude", "local", "claude"),
587
+ "/usr/local/bin/claude",
588
+ "/opt/homebrew/bin/claude"
589
+ ];
590
+ for (const candidate of candidates) try {
591
+ if (existsSync(candidate)) return candidate;
592
+ } catch {}
593
+ return "claude";
594
+ }
595
+ const CLAUDE_TIMEOUT_MS = {
596
+ haiku: 6e4,
597
+ sonnet: 12e4,
598
+ opus: 3e5
599
+ };
600
+ /**
601
+ * Spawn the claude CLI with a prompt on stdin and return stdout.
602
+ *
603
+ * IMPORTANT: ANTHROPIC_API_KEY is stripped from the spawned environment so
604
+ * the CLI uses the user's Max plan (free) instead of billing the API key.
605
+ */
606
+ async function spawnClaude(prompt, model = "sonnet") {
607
+ const claudeBin = findClaudeBinary();
608
+ if (!claudeBin) {
609
+ process.stderr.write("[kg-extraction] claude CLI not found.\n");
610
+ return null;
611
+ }
612
+ const { spawn } = await import("node:child_process");
613
+ return new Promise((resolve) => {
614
+ let timer = null;
615
+ const { ANTHROPIC_API_KEY: _drop, ...envWithoutApiKey } = process.env;
616
+ const child = spawn(claudeBin, [
617
+ "--model",
618
+ model,
619
+ "-p",
620
+ "--no-session-persistence"
621
+ ], {
622
+ env: envWithoutApiKey,
623
+ stdio: [
624
+ "pipe",
625
+ "pipe",
626
+ "pipe"
627
+ ]
628
+ });
629
+ let stdout = "";
630
+ let stderr = "";
631
+ child.stdout.on("data", (chunk) => {
632
+ stdout += chunk.toString();
633
+ });
634
+ child.stderr.on("data", (chunk) => {
635
+ stderr += chunk.toString();
636
+ });
637
+ child.on("error", (err) => {
638
+ if (timer) {
639
+ clearTimeout(timer);
640
+ timer = null;
641
+ }
642
+ process.stderr.write(`[kg-extraction] ${model} spawn error: ${err.message}\n`);
643
+ resolve(null);
644
+ });
645
+ child.on("close", (code) => {
646
+ if (timer) {
647
+ clearTimeout(timer);
648
+ timer = null;
649
+ }
650
+ if (code !== 0) {
651
+ process.stderr.write(`[kg-extraction] ${model} exited ${code}: ${stderr.slice(0, 300)}\n`);
652
+ resolve(null);
653
+ } else resolve(stdout.trim() || null);
654
+ });
655
+ timer = setTimeout(() => {
656
+ process.stderr.write(`[kg-extraction] ${model} timed out — killing process.\n`);
657
+ child.kill("SIGTERM");
658
+ resolve(null);
659
+ }, CLAUDE_TIMEOUT_MS[model] ?? 12e4);
660
+ child.stdin.write(prompt);
661
+ child.stdin.end();
662
+ });
663
+ }
664
+ /**
665
+ * Extract structured KG triples from a session summary and store them in
666
+ * Postgres. Idempotent: if a (subject, predicate) pair already has the same
667
+ * object, no new row is added; if the object differs, the old triple is
668
+ * invalidated (valid_to = NOW()) and a new one is inserted.
669
+ *
670
+ * Best-effort: per-triple errors are caught and logged but never thrown.
671
+ * Returns a small stats object so callers can report progress.
672
+ */
673
+ async function extractAndStoreTriples(pool, params) {
674
+ const stats = {
675
+ extracted: 0,
676
+ added: 0,
677
+ superseded: 0
678
+ };
679
+ const jsonOutput = await spawnClaude(buildTripleExtractionPrompt({
680
+ sessionContent: params.summaryText,
681
+ projectSlug: params.projectSlug,
682
+ gitLog: params.gitLog ?? ""
683
+ }), params.model ?? "sonnet");
684
+ if (!jsonOutput) return stats;
685
+ const cleaned = jsonOutput.replace(/^```json\s*/m, "").replace(/^```\s*/m, "").replace(/\s*```$/m, "").trim();
686
+ let triples;
687
+ try {
688
+ const parsed = JSON.parse(cleaned);
689
+ if (Array.isArray(parsed)) triples = parsed;
690
+ else if (parsed && typeof parsed === "object" && Array.isArray(parsed.relations)) {
691
+ const newFmt = parsed;
692
+ if (params.federationDb && Array.isArray(newFmt.entities)) {
693
+ const tenantId = params.tenantId ?? "default";
694
+ for (const entity of newFmt.entities) {
695
+ if (!entity.name) continue;
696
+ try {
697
+ upsertKgEntity(params.federationDb, {
698
+ name: entity.name,
699
+ type: entity.type ?? "unknown",
700
+ description: entity.description,
701
+ tenantId
702
+ });
703
+ } catch (entityErr) {
704
+ process.stderr.write(`[kg-extraction] entity upsert error (${entity.name}): ${entityErr}\n`);
705
+ }
706
+ }
707
+ }
708
+ triples = newFmt.relations.map((r) => ({
709
+ subject: r.source,
710
+ predicate: r.relation,
711
+ object: r.target
712
+ }));
713
+ } else {
714
+ process.stderr.write(`[kg-extraction] Unexpected JSON shape — neither array nor {entities,relations}\n`);
715
+ return stats;
716
+ }
717
+ } catch (e) {
718
+ process.stderr.write(`[kg-extraction] JSON parse failed: ${e}\n`);
719
+ return stats;
720
+ }
721
+ if (!Array.isArray(triples)) return stats;
722
+ stats.extracted = triples.length;
723
+ for (const t of triples) {
724
+ if (!t.subject || !t.predicate || !t.object) continue;
725
+ try {
726
+ const existing = await kgQuery(pool, {
727
+ subject: t.subject,
728
+ predicate: t.predicate,
729
+ project_id: params.projectId ?? void 0
730
+ });
731
+ if (existing.find((e) => e.object === t.object && !e.valid_to)) continue;
732
+ const supersedes = existing.find((e) => e.object !== t.object && !e.valid_to);
733
+ if (supersedes) {
734
+ await kgInvalidate(pool, supersedes.id);
735
+ stats.superseded++;
736
+ }
737
+ await kgAdd(pool, {
738
+ subject: t.subject,
739
+ predicate: t.predicate,
740
+ object: t.object,
741
+ project_id: params.projectId ?? void 0,
742
+ source_session: params.sessionId,
743
+ confidence: "EXTRACTED"
744
+ });
745
+ stats.added++;
746
+ } catch (tripleErr) {
747
+ process.stderr.write(`[kg-extraction] store error (${t.subject}): ${tripleErr}\n`);
748
+ }
749
+ }
750
+ return stats;
751
+ }
752
+
753
+ //#endregion
754
+ //#region src/session/checkpoint-block.ts
755
+ /**
756
+ * Shared "## Continue" checkpoint logic for a project's TODO.md.
757
+ *
758
+ * WHY THIS MODULE EXISTS
759
+ * ----------------------
760
+ * Before this, `pause.ts` and `handover.ts` each carried their own copy of
761
+ * findProjectTodo / stripContinueSection / block-builder. Both wrote the same
762
+ * fixed four-line block, and both stripped any existing ## Continue section
763
+ * unconditionally. The consequence was that a rich, model-authored checkpoint
764
+ * could never survive:
765
+ *
766
+ * 1. `pai pause` had no way to accept a body, so the model printed its
767
+ * checkpoint to the terminal and it was lost.
768
+ * 2. Even if a body had been written by hand, the session-stop hook runs
769
+ * `pai session handover` on every clean exit, which regenerated the
770
+ * generic block and erased it.
771
+ *
772
+ * So there are two jobs here:
773
+ *
774
+ * - AUTHORED writes (`pai pause --body-file`) carry the model's markdown
775
+ * verbatim, wrapped in explicit start/end markers.
776
+ * - AUTO writes (hooks) must never destroy an authored checkpoint belonging
777
+ * to the *same* session. They may replace a stale one left by an earlier
778
+ * session, otherwise TODO.md would show a checkpoint that no longer
779
+ * describes where the work stands.
780
+ *
781
+ * PARSING
782
+ * -------
783
+ * A rich body can legitimately contain `---` rules and `##` headings, which the
784
+ * old heuristic scanner treated as section terminators. Authored blocks are
785
+ * therefore delimited by an explicit HTML-comment pair; the legacy heuristic is
786
+ * kept only as a fallback for blocks written before this change.
787
+ */
788
+ /** Locations searched for a project TODO.md, in priority order. */
789
+ const TODO_LOCATIONS = [
790
+ "Notes/TODO.md",
791
+ ".claude/Notes/TODO.md",
792
+ "tasks/todo.md",
793
+ "TODO.md"
794
+ ];
795
+ const MARKER_OPEN = "<!-- pai:checkpoint";
796
+ const MARKER_CLOSE = "<!-- /pai:checkpoint -->";
797
+ const CONTINUE_HEADING = "## Continue";
798
+ function findProjectTodo(rootPath) {
799
+ for (const rel of TODO_LOCATIONS) {
800
+ const full = join(rootPath, rel);
801
+ if (existsSync(full)) try {
802
+ return {
803
+ path: full,
804
+ content: readFileSync(full, "utf8")
805
+ };
806
+ } catch {}
807
+ }
808
+ return null;
809
+ }
810
+ /**
811
+ * Resolve the TODO.md to write to, creating Notes/ if nothing exists yet.
812
+ * Returns null only when the directory could not be created.
813
+ */
814
+ function resolveTodoTarget(rootPath, opts = {}) {
815
+ const found = findProjectTodo(rootPath);
816
+ if (found) return found;
817
+ const notesDir = join(rootPath, "Notes");
818
+ if (opts.create !== false) try {
819
+ if (!existsSync(notesDir)) mkdirSync(notesDir, { recursive: true });
820
+ } catch {
821
+ return null;
822
+ }
823
+ return {
824
+ path: join(notesDir, "TODO.md"),
825
+ content: ""
826
+ };
827
+ }
828
+ /**
829
+ * Parse a `<!-- pai:checkpoint key="value" ... -->` marker line.
830
+ * Returns null when the line is not a marker.
831
+ */
832
+ function parseMarker(line) {
833
+ const trimmed = line.trim();
834
+ if (!trimmed.startsWith(MARKER_OPEN)) return null;
835
+ const attrs = {};
836
+ for (const m of trimmed.matchAll(/([a-zA-Z][\w-]*)="([^"]*)"/g)) attrs[m[1]] = m[2];
837
+ return {
838
+ authored: attrs.authored === "model" ? "model" : "auto",
839
+ session: attrs.session || void 0,
840
+ sessionId: attrs["session-id"] || void 0,
841
+ ts: attrs.ts || void 0
842
+ };
843
+ }
844
+ /**
845
+ * Lines an auto-generated block is made of. Anything else in a section is
846
+ * content somebody put there deliberately.
847
+ */
848
+ const BOILERPLATE_PATTERNS = [
849
+ /^##\s+Continue$/,
850
+ /^<!--\s*\/?pai:checkpoint/,
851
+ /^>\s*\*\*Last session:\*\*/,
852
+ /^>\s*\*\*Paused at:\*\*/,
853
+ /^>\s*Working directory:/,
854
+ /^>\s*Resume with:/,
855
+ /^>\s*_No checkpoint body was recorded/,
856
+ /^-{3,}$/
857
+ ];
858
+ /** A blank line, with or without a blockquote marker. */
859
+ const BLANK_LINE = /^>?\s*$/;
860
+ /**
861
+ * True when a section contains nothing but generated header lines.
862
+ *
863
+ * This is the guard that stops an auto write from destroying content it did
864
+ * not author. A session that hit the old clobbering bug may have worked around
865
+ * it by hand — writing its state into a subsection underneath the generated
866
+ * header lines, in an unmarked block. Those blocks predate the marker, so
867
+ * authorship cannot be read off them; the only safe signal is whether anything
868
+ * beyond boilerplate is present.
869
+ */
870
+ function isBoilerplateOnly(lines) {
871
+ return lines.every((line) => {
872
+ const t = line.trim();
873
+ return BLANK_LINE.test(t) || BOILERPLATE_PATTERNS.some((re) => re.test(t));
874
+ });
875
+ }
876
+ /**
877
+ * Extract the non-boilerplate content of a section, or "" if there is none.
878
+ *
879
+ * Interior blank lines are kept. They are not decoration — in Markdown they
880
+ * are what separates a paragraph from the table or list that follows, so
881
+ * dropping them (as this did while it treated every blank line as boilerplate)
882
+ * silently welds a checkpoint body into one unreadable run.
883
+ */
884
+ function extractSectionContent(lines) {
885
+ const kept = [];
886
+ for (const line of lines) {
887
+ const t = line.trim();
888
+ if (BOILERPLATE_PATTERNS.some((re) => re.test(t))) continue;
889
+ kept.push(line);
890
+ }
891
+ return trimBlankEdges(collapseBlankRuns(kept)).join("\n");
892
+ }
893
+ /** Drop leading and trailing blank lines, leaving interior spacing alone. */
894
+ function trimBlankEdges(lines) {
895
+ let start = 0;
896
+ let end = lines.length;
897
+ while (start < end && BLANK_LINE.test(lines[start].trim())) start += 1;
898
+ while (end > start && BLANK_LINE.test(lines[end - 1].trim())) end -= 1;
899
+ return lines.slice(start, end);
900
+ }
901
+ /**
902
+ * Collapse runs of blank lines to a single blank.
903
+ *
904
+ * Removing a boilerplate line leaves the blank that surrounded it behind, so
905
+ * stripping the header can open a three-line gap in the middle of the body.
906
+ * One blank line is all Markdown needs.
907
+ */
908
+ function collapseBlankRuns(lines) {
909
+ const out = [];
910
+ let lastWasBlank = false;
911
+ for (const line of lines) {
912
+ const isBlank = BLANK_LINE.test(line.trim());
913
+ if (isBlank && lastWasBlank) continue;
914
+ out.push(line);
915
+ lastWasBlank = isBlank;
916
+ }
917
+ return out;
918
+ }
919
+ /**
920
+ * Locate the existing ## Continue section.
921
+ *
922
+ * When the section carries an explicit marker pair, the close marker defines
923
+ * the end — this is what lets a rich body contain `---` and `##` safely.
924
+ * Otherwise the legacy heuristic applies: stop at the first `---` or the next
925
+ * `##` heading.
926
+ */
927
+ function locateContinue(content) {
928
+ const lines = content.split("\n");
929
+ const startIdx = lines.findIndex((l) => l.trim() === CONTINUE_HEADING);
930
+ if (startIdx === -1) return null;
931
+ let meta = null;
932
+ let markerIdx = -1;
933
+ for (let i = startIdx + 1; i < Math.min(startIdx + 6, lines.length); i++) {
934
+ const parsed = parseMarker(lines[i]);
935
+ if (parsed) {
936
+ meta = parsed;
937
+ markerIdx = i;
938
+ break;
939
+ }
940
+ if (lines[i].trim() !== "") break;
941
+ }
942
+ let endIdx = lines.length;
943
+ if (markerIdx !== -1) {
944
+ const closeIdx = lines.findIndex((l, i) => i > markerIdx && l.trim() === MARKER_CLOSE);
945
+ if (closeIdx !== -1) endIdx = closeIdx + 1;
946
+ else endIdx = heuristicEnd(lines, startIdx);
947
+ } else endIdx = heuristicEnd(lines, startIdx);
948
+ let trailingEnd = endIdx;
949
+ while (trailingEnd < lines.length && lines[trailingEnd].trim() === "") trailingEnd += 1;
950
+ if (trailingEnd < lines.length && lines[trailingEnd].trim() === "---") trailingEnd += 1;
951
+ else trailingEnd = endIdx;
952
+ return {
953
+ startIdx,
954
+ endIdx: trailingEnd,
955
+ meta,
956
+ lines: lines.slice(startIdx, trailingEnd)
957
+ };
958
+ }
959
+ /**
960
+ * Legacy scanner for blocks written before checkpoint markers existed.
961
+ *
962
+ * Terminates on a horizontal rule or the next level-2 heading. Note the
963
+ * `(?!#)` — `###` is a *subsection* of `## Continue`, not a terminator. The
964
+ * original scanner stopped at any run of `#`, which meant a `### Restored
965
+ * state` subsection fell outside the section entirely and could not be seen,
966
+ * let alone carried forward.
967
+ */
968
+ function heuristicEnd(lines, startIdx) {
969
+ for (let i = startIdx + 1; i < lines.length; i++) {
970
+ const trimmed = lines[i].trim();
971
+ if (trimmed === "---" || /^##(?!#)/.test(trimmed) && trimmed !== CONTINUE_HEADING) return i;
972
+ }
973
+ return lines.length;
974
+ }
975
+ /** Remove the ## Continue section, returning the remainder of the document. */
976
+ function stripContinue(content) {
977
+ const found = locateContinue(content);
978
+ if (!found) return content;
979
+ const lines = content.split("\n");
980
+ const before = lines.slice(0, found.startIdx);
981
+ const after = lines.slice(found.endIdx);
982
+ while (after.length > 0 && after[0].trim() === "") after.shift();
983
+ return [...before, ...after].join("\n");
984
+ }
985
+ function escapeAttr(value) {
986
+ return value.replace(/"/g, "'");
987
+ }
988
+ function buildContinueBlock(opts) {
989
+ const ts = opts.timestamp ?? (/* @__PURE__ */ new Date()).toISOString();
990
+ const attrs = [
991
+ `authored="${opts.authored}"`,
992
+ `session="${escapeAttr(opts.sessionLine)}"`,
993
+ opts.sessionId ? `session-id="${escapeAttr(opts.sessionId)}"` : null,
994
+ `ts="${ts}"`
995
+ ].filter(Boolean).join(" ");
996
+ const header = [
997
+ `> **Last session:** ${opts.sessionLine}`,
998
+ `> **Paused at:** ${ts}`,
999
+ ">",
1000
+ `> Working directory: ${opts.cwd}`
1001
+ ];
1002
+ if (opts.sessionId) header.push(">", `> Resume with: \`claude --resume ${opts.sessionId}\``);
1003
+ const body = (opts.body ?? "").trim();
1004
+ const parts = [
1005
+ CONTINUE_HEADING,
1006
+ "",
1007
+ `${MARKER_OPEN} ${attrs} -->`,
1008
+ "",
1009
+ ...header
1010
+ ];
1011
+ if (body) parts.push("", body);
1012
+ else parts.push(">", "> _No checkpoint body was recorded — see the latest session note._");
1013
+ parts.push("", MARKER_CLOSE, "", "---", "");
1014
+ return parts.join("\n");
1015
+ }
1016
+ /**
1017
+ * Write the ## Continue block, honouring the preservation rules.
1018
+ *
1019
+ * An AUTO write is unattended — it fires from the session-stop and pre-compact
1020
+ * hooks — so it operates under one governing rule: **never destroy content it
1021
+ * did not author.** Three cases follow from that:
1022
+ *
1023
+ * 1. An authored checkpoint for the SAME session is left untouched. The hooks
1024
+ * fire after the model has already recorded the real state; overwriting it
1025
+ * with metadata is the bug this module exists to fix.
1026
+ *
1027
+ * "Same session" is decided by the Claude session UUID whenever both sides
1028
+ * know it, and only falls back to the human-readable session line when one
1029
+ * of them does not. The line is derived from the session note filename,
1030
+ * and `session-stop.sh` *renames and renumbers that file* — via `session
1031
+ * slug --apply` and `session cleanup --execute` — before it reaches the
1032
+ * handover step. So the key the hook computes at exit is not the key the
1033
+ * model wrote seconds earlier, and a filename-keyed comparison mismatches
1034
+ * by construction. Observed live on 2026-08-01: notes renumbered twice
1035
+ * within a single session. The UUID is the only identifier that holds
1036
+ * still.
1037
+ * 2. An authored checkpoint from an EARLIER session is stale — TODO.md would
1038
+ * otherwise keep pointing at the wrong session — so it is replaced. Its
1039
+ * content is not lost: `pai pause` mirrors every authored body into the
1040
+ * session note.
1041
+ * 3. An UNMARKED block predates the marker, so authorship cannot be read off
1042
+ * it. If it is nothing but generated header lines it is replaced. If it
1043
+ * carries anything else, that content was put there deliberately — quite
1044
+ * possibly as a hand-rolled workaround for the very clobbering this fixes —
1045
+ * and is carried forward into the new block rather than dropped.
1046
+ *
1047
+ * A MODEL write always replaces: the model is authoring the checkpoint, and a
1048
+ * newer one supersedes an older one.
1049
+ */
1050
+ /**
1051
+ * Do an existing checkpoint and an incoming write describe the same session?
1052
+ *
1053
+ * The UUID is authoritative when both sides carry one: it is assigned by Claude
1054
+ * Code and never changes for the life of the session. The session line is a
1055
+ * derived, mutable label and is only consulted when there is no UUID to compare
1056
+ * — a checkpoint written before `--session-id` was threaded through, or an auto
1057
+ * write from a caller that was not given one.
1058
+ */
1059
+ function isSameSession(meta, opts) {
1060
+ if (meta.sessionId && opts.sessionId) return meta.sessionId === opts.sessionId;
1061
+ return meta.session === opts.sessionLine;
1062
+ }
1063
+ function applyContinue(opts) {
1064
+ const target = resolveTodoTarget(opts.rootPath, { create: !opts.dryRun });
1065
+ if (!target) return {
1066
+ action: "failed",
1067
+ path: null,
1068
+ block: buildContinueBlock(opts),
1069
+ error: "Could not resolve or create a TODO.md target"
1070
+ };
1071
+ const existing = locateContinue(target.content);
1072
+ let carriedForward = false;
1073
+ let effectiveBody = opts.body;
1074
+ if (opts.authored === "auto" && existing) {
1075
+ if (existing.meta?.authored === "model" && isSameSession(existing.meta, opts)) return {
1076
+ action: "preserved",
1077
+ path: target.path,
1078
+ block: buildContinueBlock(opts),
1079
+ preservedMeta: existing.meta
1080
+ };
1081
+ if (existing.meta && !(opts.body ?? "").trim() && !isBoilerplateOnly(existing.lines)) return {
1082
+ action: "preserved",
1083
+ path: target.path,
1084
+ block: buildContinueBlock(opts),
1085
+ preservedMeta: existing.meta ?? void 0
1086
+ };
1087
+ if (!existing.meta && !isBoilerplateOnly(existing.lines)) {
1088
+ const salvaged = extractSectionContent(existing.lines);
1089
+ if (salvaged) {
1090
+ effectiveBody = [
1091
+ "_Carried forward from the previous checkpoint (author unknown — this",
1092
+ "block predates checkpoint authorship markers):_",
1093
+ "",
1094
+ salvaged
1095
+ ].join("\n");
1096
+ carriedForward = true;
1097
+ }
1098
+ }
1099
+ }
1100
+ const block = buildContinueBlock({
1101
+ ...opts,
1102
+ body: effectiveBody
1103
+ });
1104
+ if (opts.dryRun) return {
1105
+ action: "written",
1106
+ path: target.path,
1107
+ block,
1108
+ carriedForward
1109
+ };
1110
+ const newContent = block + stripContinue(target.content).trimStart();
1111
+ const tmpPath = `${target.path}.continue.tmp`;
1112
+ try {
1113
+ writeFileSync(tmpPath, newContent, "utf8");
1114
+ renameSync(tmpPath, target.path);
1115
+ } catch (err) {
1116
+ try {
1117
+ if (existsSync(tmpPath)) renameSync(tmpPath, `${tmpPath}.dead`);
1118
+ } catch {}
1119
+ return {
1120
+ action: "failed",
1121
+ path: target.path,
1122
+ block,
1123
+ error: String(err)
1124
+ };
1125
+ }
1126
+ return {
1127
+ action: "written",
1128
+ path: target.path,
1129
+ block,
1130
+ carriedForward
1131
+ };
1132
+ }
1133
+ /** PAI_DIR — mirrors pai-paths.ts resolution. */
1134
+ function getPaiDir() {
1135
+ const envDir = process.env.PAI_DIR;
1136
+ if (envDir) try {
1137
+ return realpathSync(envDir);
1138
+ } catch {
1139
+ return envDir;
1140
+ }
1141
+ return join(homedir(), ".claude");
1142
+ }
1143
+ /**
1144
+ * Find the notes directory for a project — local first, then the central
1145
+ * ~/.claude/projects/<encoded>/Notes fallback. Never creates.
1146
+ */
1147
+ function findNotesDir(rootPath, encodedDir) {
1148
+ for (const rel of [
1149
+ "Notes",
1150
+ "notes",
1151
+ ".claude/Notes"
1152
+ ]) {
1153
+ const p = join(rootPath, rel);
1154
+ if (existsSync(p)) return p;
1155
+ }
1156
+ const central = join(getPaiDir(), "projects", encodedDir, "Notes");
1157
+ if (existsSync(central)) return central;
1158
+ return null;
1159
+ }
1160
+ /**
1161
+ * Find the current (highest-numbered) session note: current month, then the
1162
+ * previous month, then a flat notesDir as legacy fallback.
1163
+ */
1164
+ function findLatestNote(notesDir) {
1165
+ const findIn = (dir) => {
1166
+ if (!existsSync(dir)) return null;
1167
+ let files;
1168
+ try {
1169
+ files = readdirSync(dir);
1170
+ } catch {
1171
+ return null;
1172
+ }
1173
+ const notes = files.filter((f) => /^\d{3,4}[\s_-].*\.md$/.test(f)).sort((a, b) => {
1174
+ return parseInt(a.match(/^(\d+)/)?.[1] ?? "0", 10) - parseInt(b.match(/^(\d+)/)?.[1] ?? "0", 10);
1175
+ });
1176
+ return notes.length > 0 ? join(dir, notes[notes.length - 1]) : null;
1177
+ };
1178
+ const now = /* @__PURE__ */ new Date();
1179
+ const current = findIn(join(notesDir, String(now.getFullYear()), String(now.getMonth() + 1).padStart(2, "0")));
1180
+ if (current) return current;
1181
+ const prev = new Date(now.getFullYear(), now.getMonth() - 1, 1);
1182
+ const prevFound = findIn(join(notesDir, String(prev.getFullYear()), String(prev.getMonth() + 1).padStart(2, "0")));
1183
+ if (prevFound) return prevFound;
1184
+ return findIn(notesDir);
1185
+ }
1186
+ /**
1187
+ * Append the checkpoint body to a session note.
1188
+ *
1189
+ * TODO.md's ## Continue is a single slot that every later checkpoint
1190
+ * overwrites. The session note is the durable record, so the body goes to both.
1191
+ * Idempotent per timestamp: re-running with the same stamp will not duplicate.
1192
+ */
1193
+ function appendCheckpointToNote(notePath, body, timestamp) {
1194
+ const heading = `## Pause Checkpoint — ${timestamp ?? (/* @__PURE__ */ new Date()).toISOString()}`;
1195
+ let existing;
1196
+ try {
1197
+ existing = readFileSync(notePath, "utf8");
1198
+ } catch (err) {
1199
+ return {
1200
+ appended: false,
1201
+ error: String(err)
1202
+ };
1203
+ }
1204
+ if (existing.includes(heading)) return { appended: false };
1205
+ const block = `\n\n---\n\n${heading}\n\n${body.trim()}\n`;
1206
+ const tmpPath = `${notePath}.checkpoint.tmp`;
1207
+ try {
1208
+ writeFileSync(tmpPath, existing.trimEnd() + block, "utf8");
1209
+ renameSync(tmpPath, notePath);
1210
+ } catch (err) {
1211
+ try {
1212
+ if (existsSync(tmpPath)) renameSync(tmpPath, `${tmpPath}.dead`);
1213
+ } catch {}
1214
+ return {
1215
+ appended: false,
1216
+ error: String(err)
1217
+ };
1218
+ }
1219
+ return { appended: true };
1220
+ }
1221
+ /** Read a checkpoint body from a file, or from stdin when path is "-". */
1222
+ function readBodyFile(path) {
1223
+ if (path === "-") return readFileSync(0, "utf8");
1224
+ return readFileSync(path, "utf8");
1225
+ }
1226
+
1227
+ //#endregion
1228
+ export { transcriptFiles as _, readBodyFile as a, loadScanConfig as c, saveScanConfig as d, upsertProject as f, scanTranscriptFolders as g, findMovedProjects as h, findNotesDir as i, performScan as l, claudeProjectsDir as m, applyContinue as n, extractAndStoreTriples as o, upsertSession as p, findLatestNote as r, cmdScan as s, appendCheckpointToNote as t, resolveHome as u };
1229
+ //# sourceMappingURL=checkpoint-block-Cloxmin5.mjs.map