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