claude-code-session-manager 0.130.3 → 0.132.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-C09MlPFx.js} +2 -2
  2. package/dist/assets/AppSettings-DvDKsCnD.js +2 -0
  3. package/dist/assets/{Button-UUr5giu8.js → Button-BzG_KdBC.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-fm6zsnLM.js} +1 -1
  5. package/dist/assets/Extensions-DgxKT_OZ.js +2 -0
  6. package/dist/assets/{History-Bndupj87.js → History-Nd3bKjBq.js} +2 -2
  7. package/dist/assets/{Library-DFn0YPIW.js → Library-R71t6VAB.js} +12 -12
  8. package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-CG50Ul7c.js} +1 -1
  9. package/dist/assets/{Panel-CIvb-XXN.js → Panel-C7EFG4eU.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-J92iNEGC.js} +7 -7
  11. package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-C3KB3ILO.js} +1 -1
  12. package/dist/assets/Scheduler-DeYBA7uc.js +16 -0
  13. package/dist/assets/{Settings-DqxUna06.js → Settings-B6r7N4v-.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-D7bt3fyB.js} +1 -1
  15. package/dist/assets/Skills-GpxtUrFP.js +29 -0
  16. package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-uyVMCZc7.js} +1 -1
  17. package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-Cv25uFSM.js} +1 -1
  18. package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-uP8fJkbM.js} +1 -1
  19. package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DRs80cX-.js} +1 -1
  20. package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-BDkvvzJ8.js} +1 -1
  21. package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-Cmtz2sQt.js} +1 -1
  22. package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-DHwAXunq.js} +1 -1
  23. package/dist/assets/index-CBCdyHbZ.js +3097 -0
  24. package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +414 -390
  28. package/package.json +1 -1
  29. package/scripts/scheduler-mcp-server.cjs +83 -4
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/index.cjs +11 -0
  32. package/src/main/ipcSchemas.cjs +28 -1
  33. package/src/main/lib/epic/epicMint.cjs +61 -6
  34. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  35. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  36. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  37. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
  38. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  39. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  40. package/src/main/lib/git/branchSweep.cjs +9 -3
  41. package/src/main/lib/git/gitExec.cjs +8 -1
  42. package/src/main/lib/git/gitWorktree.cjs +564 -62
  43. package/src/main/lib/git/jobWorktree.cjs +3 -0
  44. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  45. package/src/main/lib/mcpToolCatalog.cjs +43 -6
  46. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  47. package/src/main/lib/persona-macro/builtinMacros.cjs +33 -0
  48. package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
  49. package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
  50. package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
  51. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  52. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  53. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  54. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  55. package/src/main/lib/promptSessionSchema.cjs +5 -0
  56. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  57. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  58. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  59. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  60. package/src/main/projectPages.cjs +25 -2
  61. package/src/main/promptSessionEvents.cjs +10 -6
  62. package/src/main/runVerify.cjs +8 -3
  63. package/src/main/scheduler/budget.cjs +146 -7
  64. package/src/main/scheduler/gitTreeGuard.cjs +10 -11
  65. package/src/main/scheduler/reviewLadder.cjs +60 -0
  66. package/src/main/scheduler.cjs +461 -48
  67. package/src/main/seedAgentPersonas.cjs +1 -1
  68. package/src/preload/api.d.ts +162 -2
  69. package/src/preload/apiSurface.json +21 -0
  70. package/src/preload/index.cjs +5 -0
  71. package/src/seed/agents/competitive-analyst.md +69 -0
  72. package/src/seed/agents/competitive-researcher.md +75 -0
  73. package/src/seed/agents/validator.md +2 -2
  74. package/dist/assets/AppSettings-Cs4POznd.js +0 -2
  75. package/dist/assets/Extensions-B9QdiNOV.js +0 -2
  76. package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
  77. package/dist/assets/Skills-DTXehVS7.js +0 -12
  78. package/dist/assets/index-C9w-dVzo.js +0 -3090
@@ -0,0 +1,749 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * restorableSessions.cjs — which Claude Code CLI sessions already on disk for
5
+ * ONE project could a new Epic adopt? Powers the New Session card's "Restore a
6
+ * session" option, so a first-time Session Manager user can carry on a
7
+ * conversation they started in the plain CLI.
8
+ *
9
+ * A transcript `~/.claude/projects/<encodeCwd(cwd)>/<id>.jsonl` is restorable when:
10
+ * - `<id>` is a session UUID (SESSION_ID_RE). It becomes a filename and a
11
+ * `--resume` argument, so nothing else is ever joined into a path;
12
+ * - its first recorded `cwd` is exactly this project's. encodeCwd is lossy
13
+ * (`/a/b-c` and `/a/b/c` share a dir), so the transcript itself decides;
14
+ * - its head holds a real user prompt (not a sidechain, meta, slash-command
15
+ * or tool_result row);
16
+ * - no Epic owns it (EPIC : claude-session is 1:1): the id is not a
17
+ * `claudeSessionId` in active-index.json or in any archived
18
+ * prompt-sessions/<id>.json (claimedClaudeSessionIds).
19
+ *
20
+ * Bounded on purpose. One project dir on the author's machine holds 1,500+
21
+ * transcripts (p50 800 KB, max 14 MB), and walking all of ~/.claude/projects is
22
+ * a known main-process OOM hazard. So this module:
23
+ * - reads ONE project dir and never enumerates ~/.claude/projects itself;
24
+ * - reads at most the first and the last 64 KiB of a transcript through fixed
25
+ * buffers (never readFile) and parses only complete lines;
26
+ * - head-reads at most 400 transcripts per call, newest first, and reports
27
+ * `truncated` when unread candidates remained;
28
+ * - fills two budgets of `limit` rows, interactive and headless, so a headless
29
+ * row never takes an interactive row's place. Per-kind budgets exist because
30
+ * a project with claude -p automation has ~98% headless transcripts: one
31
+ * shared budget listed 48 headless + 2 interactive rows on this repo;
32
+ * - memoises the claimed-id scan per cwd on each ops file's mtimeMs:size, so
33
+ * an unchanged Epic file is never re-read (epicTranscriptPath.cjs's shape).
34
+ * The list path scans through fs.promises (claimedClaudeSessionIdsAsync): a
35
+ * cold scan reads every archived Epic file, which blocked 191 ms when sync.
36
+ *
37
+ * Read-only: never writes, never spawns. listRestorableSessions is async (it
38
+ * backs a picker IPC); checkRestorableSessionSync is the sync single-id gate
39
+ * the mint path reuses. It re-derives every fact from disk instead of trusting
40
+ * an earlier list.
41
+ */
42
+
43
+ const fs = require('node:fs');
44
+ const os = require('node:os');
45
+ const path = require('node:path');
46
+ const { encodeCwd } = require('../util/encodeCwd.cjs');
47
+ // Module object, not destructured: the memo test spies on readJsonOrSync.
48
+ const atomicFs = require('../util/atomicFs.cjs');
49
+ const { readActiveIndex } = require('./epicMint.cjs');
50
+
51
+ /** A Claude Code session id: hex UUID 8-4-4-4-12, either case. */
52
+ const SESSION_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
53
+
54
+ const HEAD_BYTES = 64 * 1024;
55
+ const TAIL_BYTES = 64 * 1024;
56
+ const MAX_HEAD_READS = 400;
57
+ const DEFAULT_LIMIT = 50;
58
+ const MAX_TEXT = 300;
59
+ const RECENT_MS = 120 * 1000;
60
+ const STAT_CONCURRENCY = 16;
61
+ const NEWLINE = 0x0a;
62
+ const JSONL = '.jsonl';
63
+ // Once a head's early facts are known, a line holding none of these strings is never parsed.
64
+ const LATE_ROW_HINTS = ['"last-prompt"', '"custom-title"', '"summary"'];
65
+
66
+ /**
67
+ * @typedef {object} RestorableDeps
68
+ * @property {string} [homeDir] Home dir holding `.claude/projects` (default os.homedir()).
69
+ * @property {() => number} [now] Clock for `recentlyActive` (default Date.now).
70
+ * @property {(cwd: string) => { sessions?: Record<string, unknown> }} [readActiveIndex] Test seam (default epicMint's).
71
+ */
72
+
73
+ /**
74
+ * @typedef {object} RestorableSession
75
+ * @property {string} sessionId
76
+ * @property {string|null} title Last `custom-title` row, else last `summary` row.
77
+ * @property {string} firstPrompt First real user prompt in the head.
78
+ * @property {string|null} lastPrompt Last `last-prompt` row read (the tail; the whole file when it fits the head).
79
+ * @property {string|null} gitBranch First `gitBranch` recorded.
80
+ * @property {boolean} headless First recorded `entrypoint` is `sdk-*` (a `claude -p` / SDK run).
81
+ * @property {number} mtimeMs
82
+ * @property {number} sizeBytes
83
+ * @property {boolean} recentlyActive Written in the last 120 s, so it may still be open in a terminal.
84
+ */
85
+
86
+ /**
87
+ * @typedef {object} RestorableList
88
+ * @property {RestorableSession[]} sessions Newest first by mtime. The limit is per kind: up to `limit`
89
+ * interactive rows plus, on a separate budget, up to `limit` headless rows.
90
+ * @property {number} hiddenClaimed Transcripts left out because an Epic owns them.
91
+ * @property {number} scanned Transcript heads read by this call (at most 400).
92
+ * @property {boolean} truncated Unread unclaimed candidates remained: the walk stopped with both per-kind
93
+ * budgets full, or at the 400-read cap.
94
+ */
95
+
96
+ /** @typedef {'invalid_id'|'not_found'|'cwd_mismatch'|'claimed'} RefusalCode */
97
+ /** @typedef {{ ok: true, transcriptPath: string }} RestorableOk */
98
+ /** @typedef {{ ok: false, code: RefusalCode, message: string }} RestorableRefusal */
99
+
100
+ /** @typedef {Record<string, unknown>} Row */
101
+
102
+ /**
103
+ * What one transcript's head (and tail) windows say. Text fields are clipped;
104
+ * '' means "no such row seen".
105
+ * @typedef {object} TranscriptFacts
106
+ * @property {string|null} recordedCwd First string `cwd` (raw).
107
+ * @property {string|null} firstPrompt
108
+ * @property {string|null} entrypoint First `entrypoint` (raw).
109
+ * @property {string|null} gitBranch First `gitBranch`.
110
+ * @property {string} lastPrompt
111
+ * @property {string} customTitle
112
+ * @property {string} summary
113
+ */
114
+
115
+ /** @typedef {{ name: string, sessionId: string, mtimeMs: number, sizeBytes: number }} Candidate */
116
+
117
+ /** @typedef {{ key: string, sid: string|null }} ArchiveRec */
118
+
119
+ /**
120
+ * One cwd's claimed-id memo. The sync and the async reader both read and write it.
121
+ * @typedef {{ indexKey: string, indexIds: string[], files: Map<string, ArchiveRec> }} ClaimedEntry
122
+ */
123
+
124
+ /** @type {Map<string, ClaimedEntry>} */
125
+ const claimedCache = new Map();
126
+
127
+ function __resetCacheForTests() {
128
+ claimedCache.clear();
129
+ }
130
+
131
+ /**
132
+ * The memo key. One formatter for both stat paths, so each reader can reuse
133
+ * the records the other wrote.
134
+ * @param {import('node:fs').Stats} s
135
+ * @returns {string} `mtimeMs:size`
136
+ */
137
+ function keyOf(s) {
138
+ return `${s.mtimeMs}:${s.size}`;
139
+ }
140
+
141
+ /**
142
+ * @param {string} file
143
+ * @returns {string} `mtimeMs:size`, or 'missing'
144
+ */
145
+ function statKey(file) {
146
+ try {
147
+ return keyOf(fs.statSync(file));
148
+ } catch {
149
+ return 'missing';
150
+ }
151
+ }
152
+
153
+ /**
154
+ * statKey through fs.promises.
155
+ * @param {string} file
156
+ * @returns {Promise<string>} `mtimeMs:size`, or 'missing'
157
+ */
158
+ async function statKeyAsync(file) {
159
+ try {
160
+ return keyOf(await fs.promises.stat(file));
161
+ } catch {
162
+ return 'missing';
163
+ }
164
+ }
165
+
166
+ /**
167
+ * Run `task(0)` … `task(count - 1)` with at most 16 in flight, so a dir of
168
+ * 1,500 files does not flood libuv's threadpool. `task` must not reject.
169
+ * @param {number} count
170
+ * @param {(index: number) => Promise<void>} task
171
+ * @returns {Promise<void>}
172
+ */
173
+ async function forEachBounded(count, task) {
174
+ let next = 0;
175
+ const worker = async () => {
176
+ while (next < count) await task(next++);
177
+ };
178
+ await Promise.all(Array.from({ length: Math.min(STAT_CONCURRENCY, count) }, worker));
179
+ }
180
+
181
+ /**
182
+ * Absolute, normalized project cwd, or null. A relative cwd would resolve
183
+ * against the main process's own cwd, which names no project.
184
+ * @param {unknown} cwd
185
+ * @returns {string|null}
186
+ */
187
+ function normalizeCwd(cwd) {
188
+ return typeof cwd === 'string' && path.isAbsolute(cwd) ? path.resolve(cwd) : null;
189
+ }
190
+
191
+ /**
192
+ * `~/.claude/projects/<encodeCwd(projectCwd)>`, the one dir this module reads.
193
+ * @param {string} projectCwd
194
+ * @param {RestorableDeps} deps
195
+ */
196
+ function projectDirOf(projectCwd, deps) {
197
+ return path.join(deps.homeDir || os.homedir(), '.claude', 'projects', encodeCwd(projectCwd));
198
+ }
199
+
200
+ /**
201
+ * @param {unknown} session
202
+ * @returns {string|null}
203
+ */
204
+ function sessionIdOf(session) {
205
+ if (!session || typeof session !== 'object') return null;
206
+ const sid = /** @type {Row} */ (session).claudeSessionId;
207
+ return typeof sid === 'string' && sid ? sid : null;
208
+ }
209
+
210
+ const ACTIVE_INDEX = 'active-index.json';
211
+
212
+ /**
213
+ * This cwd's prompt-sessions dir, or null when the cwd has no ops root
214
+ * (relative, tmpdir or linked worktree) and so cannot hold Epics.
215
+ * @param {unknown} cwd
216
+ * @returns {string|null}
217
+ */
218
+ function promptSessionsDirOf(cwd) {
219
+ if (typeof cwd !== 'string' || !cwd) return null;
220
+ try {
221
+ // Lazy, as in epicMint.cjs: opsOwnership → ephemeralCwd → activeSessions.
222
+ const { opsPath } = require('../opsOwnership.cjs');
223
+ return opsPath(cwd, 'prompt-sessions');
224
+ } catch {
225
+ return null;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * claudeSessionIds in active-index.json: one small file, read through
231
+ * readActiveIndex by both readers.
232
+ * @param {string} cwd
233
+ * @param {RestorableDeps} d
234
+ * @returns {string[]}
235
+ */
236
+ function readIndexIds(cwd, d) {
237
+ /** @type {Record<string, unknown>} */
238
+ let sessions = {};
239
+ try {
240
+ sessions = (d.readActiveIndex || readActiveIndex)(cwd).sessions || {};
241
+ } catch {
242
+ sessions = {};
243
+ }
244
+ /** @type {string[]} */
245
+ const out = [];
246
+ for (const s of Object.values(sessions)) {
247
+ const sid = sessionIdOf(s);
248
+ if (sid) out.push(sid);
249
+ }
250
+ return out;
251
+ }
252
+
253
+ /** @param {string} name An archived Epic file: any `.json` but the index. */
254
+ function isArchiveName(name) {
255
+ return name.endsWith('.json') && name !== ACTIVE_INDEX;
256
+ }
257
+
258
+ /**
259
+ * First half of the per-file archive-record update both readers share: the
260
+ * memo's record while the file's mtimeMs:size is unchanged, else null.
261
+ * @param {Map<string, ArchiveRec>} prevFiles
262
+ * @param {string} name
263
+ * @param {string} key
264
+ * @returns {ArchiveRec|null}
265
+ */
266
+ function memoHit(prevFiles, name, key) {
267
+ const hit = prevFiles.get(name);
268
+ return hit && hit.key === key ? hit : null;
269
+ }
270
+
271
+ /**
272
+ * Second half: the record for an archived Epic file read at `key`. A missing,
273
+ * empty or malformed file (`doc` null) owns nothing.
274
+ * @param {string} key
275
+ * @param {unknown} doc
276
+ * @returns {ArchiveRec}
277
+ */
278
+ function archiveRec(key, doc) {
279
+ return { key, sid: doc && typeof doc === 'object' ? sessionIdOf(/** @type {Row} */ (doc).session) : null };
280
+ }
281
+
282
+ /**
283
+ * Store `entry` as `cwd`'s memo and return the ids it claims.
284
+ * @param {string} cwd
285
+ * @param {ClaimedEntry} entry
286
+ * @returns {Set<string>}
287
+ */
288
+ function commitClaimed(cwd, entry) {
289
+ claimedCache.set(cwd, entry);
290
+ /** @type {Set<string>} */
291
+ const ids = new Set(entry.indexIds);
292
+ for (const rec of entry.files.values()) if (rec.sid) ids.add(rec.sid);
293
+ return ids;
294
+ }
295
+
296
+ /**
297
+ * Every claudeSessionId an Epic of this project owns: active-index.json plus
298
+ * each archived prompt-sessions/<id>.json. Memoised per cwd on each file's
299
+ * mtimeMs:size, so an unchanged file is never re-read (one statSync per file per
300
+ * call); the memo is shared with claimedClaudeSessionIdsAsync. A cwd with no ops
301
+ * root (relative, tmpdir or linked worktree) cannot hold Epics, so it owns
302
+ * nothing. Sync, for the mint gate (checkRestorableSessionSync).
303
+ * @param {string} cwd Project cwd (mapped to its ops root by opsPath).
304
+ * @param {RestorableDeps} [deps]
305
+ * @returns {Set<string>}
306
+ */
307
+ function claimedClaudeSessionIds(cwd, deps) {
308
+ const dir = promptSessionsDirOf(cwd);
309
+ if (!dir) return new Set();
310
+ const d = deps || {};
311
+ const prev = claimedCache.get(cwd);
312
+ const indexKey = statKey(path.join(dir, ACTIVE_INDEX));
313
+ const indexIds = prev && prev.indexKey === indexKey ? prev.indexIds : readIndexIds(cwd, d);
314
+ const prevFiles = prev ? prev.files : new Map();
315
+ /** @type {string[]} */
316
+ let names = [];
317
+ try {
318
+ names = fs.readdirSync(dir).filter(isArchiveName);
319
+ } catch {
320
+ names = [];
321
+ }
322
+ /** @type {Map<string, ArchiveRec>} */
323
+ const files = new Map();
324
+ for (const name of names) {
325
+ const file = path.join(dir, name);
326
+ const key = statKey(file);
327
+ files.set(name, memoHit(prevFiles, name, key) || archiveRec(key, atomicFs.readJsonOrSync(file, null)));
328
+ }
329
+ return commitClaimed(cwd, { indexKey, indexIds, files });
330
+ }
331
+
332
+ /**
333
+ * claimedClaudeSessionIds through fs.promises (readdir, stat and readFile, at
334
+ * most 16 files in flight), for the list path. A cold scan reads every archived
335
+ * Epic file; done sync it blocked the main loop for 191 ms. Same memo as the
336
+ * sync reader, so either one re-reads only the files whose mtimeMs:size changed
337
+ * since the last scan by either. active-index.json stays a readActiveIndex read,
338
+ * memoised on its own key as in the sync reader.
339
+ * @param {string} cwd Project cwd (mapped to its ops root by opsPath).
340
+ * @param {RestorableDeps} [deps]
341
+ * @returns {Promise<Set<string>>}
342
+ */
343
+ async function claimedClaudeSessionIdsAsync(cwd, deps) {
344
+ const dir = promptSessionsDirOf(cwd);
345
+ if (!dir) return new Set();
346
+ const d = deps || {};
347
+ const prev = claimedCache.get(cwd);
348
+ const indexKey = await statKeyAsync(path.join(dir, ACTIVE_INDEX));
349
+ const indexIds = prev && prev.indexKey === indexKey ? prev.indexIds : readIndexIds(cwd, d);
350
+ const prevFiles = prev ? prev.files : new Map();
351
+ /** @type {string[]} */
352
+ let names = [];
353
+ try {
354
+ names = (await fs.promises.readdir(dir)).filter(isArchiveName);
355
+ } catch {
356
+ names = [];
357
+ }
358
+ /** @type {ArchiveRec[]} */
359
+ const recs = new Array(names.length);
360
+ await forEachBounded(names.length, async (k) => {
361
+ const file = path.join(dir, names[k]);
362
+ const key = await statKeyAsync(file);
363
+ // atomicFs.readJsonOr is fs.promises.readFile + JSON.parse; malformed → null.
364
+ recs[k] = memoHit(prevFiles, names[k], key) || archiveRec(key, await atomicFs.readJsonOr(file, null));
365
+ });
366
+ /** @type {Map<string, ArchiveRec>} */
367
+ const files = new Map();
368
+ names.forEach((name, k) => files.set(name, recs[k])); // readdir order, as the sync reader
369
+ return commitClaimed(cwd, { indexKey, indexIds, files });
370
+ }
371
+
372
+ /**
373
+ * Case-folded copy: a case-insensitive filesystem (macOS) maps `ABC….jsonl`
374
+ * and `abc….jsonl` to one transcript, so ownership is compared folded.
375
+ * @param {Set<string>} set
376
+ * @returns {Set<string>}
377
+ */
378
+ function lowerSet(set) {
379
+ /** @type {Set<string>} */
380
+ const out = new Set();
381
+ for (const s of set) out.add(s.toLowerCase());
382
+ return out;
383
+ }
384
+
385
+ /**
386
+ * Trimmed and capped at 300 chars without splitting a surrogate pair; '' for
387
+ * a non-string.
388
+ * @param {unknown} value
389
+ * @returns {string}
390
+ */
391
+ function clip(value) {
392
+ if (typeof value !== 'string') return '';
393
+ const t = value.trim();
394
+ if (t.length <= MAX_TEXT) return t;
395
+ let cut = t.slice(0, MAX_TEXT);
396
+ const last = cut.charCodeAt(MAX_TEXT - 1);
397
+ if (last >= 0xd800 && last <= 0xdbff) cut = cut.slice(0, -1);
398
+ return cut.trimEnd();
399
+ }
400
+
401
+ /**
402
+ * Complete lines of a window. The text after the last newline is always
403
+ * dropped (a head cut mid-row, or a row still being written); `dropFirst`
404
+ * also drops a tail window's leading partial line. Cutting at newline bytes
405
+ * keeps the UTF-8 decode aligned, since 0x0a never occurs inside a multibyte
406
+ * character.
407
+ * @param {Buffer} buf
408
+ * @param {boolean} dropFirst
409
+ * @returns {string[]}
410
+ */
411
+ function completeLines(buf, dropFirst) {
412
+ const end = buf.lastIndexOf(NEWLINE);
413
+ if (end < 0) return [];
414
+ const start = dropFirst ? buf.indexOf(NEWLINE) + 1 : 0;
415
+ if (start > end) return [];
416
+ return buf.toString('utf8', start, end).split('\n');
417
+ }
418
+
419
+ /**
420
+ * @param {string} line
421
+ * @returns {Row|null}
422
+ */
423
+ function parseRow(line) {
424
+ if (!line) return null;
425
+ try {
426
+ const row = JSON.parse(line);
427
+ return row && typeof row === 'object' && !Array.isArray(row) ? row : null;
428
+ } catch {
429
+ return null;
430
+ }
431
+ }
432
+
433
+ /** @param {string} line */
434
+ function mayBeLateRow(line) {
435
+ return LATE_ROW_HINTS.some((hint) => line.includes(hint));
436
+ }
437
+
438
+ /**
439
+ * Fold a title / last-prompt row into `facts`; the last row of each kind wins.
440
+ * @param {Row} row
441
+ * @param {TranscriptFacts} facts
442
+ */
443
+ function noteLateRow(row, facts) {
444
+ if (row.type === 'last-prompt' && typeof row.lastPrompt === 'string') facts.lastPrompt = clip(row.lastPrompt);
445
+ else if (row.type === 'custom-title' && typeof row.customTitle === 'string') facts.customTitle = clip(row.customTitle);
446
+ else if (row.type === 'summary' && typeof row.summary === 'string') facts.summary = clip(row.summary);
447
+ }
448
+
449
+ /**
450
+ * @param {string} text
451
+ * @returns {string|null}
452
+ */
453
+ function promptOrNull(text) {
454
+ const t = text.trim();
455
+ if (!t || t.startsWith('<command-') || t.startsWith('<local-command-')) return null;
456
+ return clip(t);
457
+ }
458
+
459
+ /**
460
+ * The row's prompt when it is a real user prompt: not a sidechain or meta row,
461
+ * not a slash-command / local-command echo, not tool_result-only content.
462
+ * @param {Row} row
463
+ * @returns {string|null}
464
+ */
465
+ function userPromptText(row) {
466
+ if (row.type !== 'user' || row.isSidechain === true || row.isMeta === true) return null;
467
+ const message = row.message;
468
+ const content = message && typeof message === 'object' ? /** @type {Row} */ (message).content : undefined;
469
+ if (typeof content === 'string') return promptOrNull(content);
470
+ if (!Array.isArray(content)) return null;
471
+ for (const block of content) {
472
+ if (block && block.type === 'text' && typeof block.text === 'string') {
473
+ const text = promptOrNull(block.text);
474
+ if (text) return text;
475
+ }
476
+ }
477
+ return null;
478
+ }
479
+
480
+ /**
481
+ * @param {string|null} recorded
482
+ * @param {string} projectCwd Normalized absolute project cwd.
483
+ */
484
+ function sameCwd(recorded, projectCwd) {
485
+ return typeof recorded === 'string' && path.isAbsolute(recorded) && path.resolve(recorded) === projectCwd;
486
+ }
487
+
488
+ /**
489
+ * One pass over a head window. Returns as soon as the first recorded cwd is
490
+ * known when `cwdOnly`, or when that cwd is not the project's. Once the early
491
+ * facts are in, only lines that can be title / last-prompt rows are parsed.
492
+ * @param {Buffer} head
493
+ * @param {string} projectCwd
494
+ * @param {boolean} cwdOnly
495
+ * @returns {TranscriptFacts}
496
+ */
497
+ function scanHead(head, projectCwd, cwdOnly) {
498
+ /** @type {TranscriptFacts} */
499
+ const facts = { recordedCwd: null, firstPrompt: null, entrypoint: null, gitBranch: null, lastPrompt: '', customTitle: '', summary: '' };
500
+ for (const line of completeLines(head, false)) {
501
+ const early = facts.recordedCwd === null || facts.firstPrompt === null || facts.entrypoint === null || facts.gitBranch === null;
502
+ if (!early && !mayBeLateRow(line)) continue;
503
+ const row = parseRow(line);
504
+ if (!row) continue;
505
+ if (facts.recordedCwd === null && typeof row.cwd === 'string') {
506
+ facts.recordedCwd = row.cwd;
507
+ if (cwdOnly || !sameCwd(row.cwd, projectCwd)) return facts;
508
+ }
509
+ if (facts.entrypoint === null && typeof row.entrypoint === 'string') facts.entrypoint = row.entrypoint;
510
+ if (facts.gitBranch === null && typeof row.gitBranch === 'string') facts.gitBranch = clip(row.gitBranch);
511
+ if (facts.firstPrompt === null) facts.firstPrompt = userPromptText(row);
512
+ noteLateRow(row, facts);
513
+ }
514
+ return facts;
515
+ }
516
+
517
+ /**
518
+ * Fold a tail window's title / last-prompt rows into `facts`; they are the
519
+ * file's latest, so they override the head's.
520
+ * @param {Buffer} tail
521
+ * @param {TranscriptFacts} facts
522
+ */
523
+ function scanTail(tail, facts) {
524
+ for (const line of completeLines(tail, true)) {
525
+ if (!mayBeLateRow(line)) continue;
526
+ const row = parseRow(line);
527
+ if (row) noteLateRow(row, facts);
528
+ }
529
+ }
530
+
531
+ /**
532
+ * Picker fields for one transcript, or null when it is not restorable here
533
+ * (foreign or missing cwd, no real prompt in the head, unreadable). The tail is
534
+ * read only for a keeper larger than the head window.
535
+ * @param {string} file
536
+ * @param {number} size Size from the walk's stat.
537
+ * @param {string} projectCwd
538
+ * @param {{ head: Buffer, tail: Buffer }} bufs Reused across the sequential walk.
539
+ * @returns {Promise<Omit<RestorableSession, 'sessionId'|'mtimeMs'|'sizeBytes'|'recentlyActive'>|null>}
540
+ */
541
+ async function inspectTranscript(file, size, projectCwd, bufs) {
542
+ /** @type {import('node:fs/promises').FileHandle|undefined} */
543
+ let fh;
544
+ try {
545
+ fh = await fs.promises.open(file, 'r');
546
+ const { bytesRead } = await fh.read(bufs.head, 0, HEAD_BYTES, 0);
547
+ const facts = scanHead(bufs.head.subarray(0, bytesRead), projectCwd, false);
548
+ if (!sameCwd(facts.recordedCwd, projectCwd) || !facts.firstPrompt) return null;
549
+ if (size > HEAD_BYTES) {
550
+ const tail = await fh.read(bufs.tail, 0, TAIL_BYTES, size - TAIL_BYTES);
551
+ scanTail(bufs.tail.subarray(0, tail.bytesRead), facts);
552
+ }
553
+ return {
554
+ title: facts.customTitle || facts.summary || null,
555
+ firstPrompt: facts.firstPrompt,
556
+ lastPrompt: facts.lastPrompt || null,
557
+ gitBranch: facts.gitBranch || null,
558
+ headless: typeof facts.entrypoint === 'string' && facts.entrypoint.startsWith('sdk-'),
559
+ };
560
+ } catch {
561
+ return null; // vanished or unreadable mid-walk
562
+ } finally {
563
+ if (fh) await fh.close().catch(() => {});
564
+ }
565
+ }
566
+
567
+ /** @param {string} name */
568
+ function isTranscriptName(name) {
569
+ return name.endsWith(JSONL) && SESSION_ID_RE.test(name.slice(0, -JSONL.length));
570
+ }
571
+
572
+ /**
573
+ * Regular-file transcripts among `names`, stat'ed with bounded concurrency
574
+ * (forEachBounded) so a 1,500-file dir does not flood libuv's threadpool.
575
+ * @param {string} dir
576
+ * @param {string[]} names Already filtered to `<uuid>.jsonl`.
577
+ * @returns {Promise<Candidate[]>}
578
+ */
579
+ async function statCandidates(dir, names) {
580
+ /** @type {Candidate[]} */
581
+ const out = [];
582
+ await forEachBounded(names.length, async (k) => {
583
+ const name = names[k];
584
+ try {
585
+ const st = await fs.promises.stat(path.join(dir, name));
586
+ if (st.isFile()) out.push({ name, sessionId: name.slice(0, -JSONL.length), mtimeMs: st.mtimeMs, sizeBytes: st.size });
587
+ } catch {
588
+ // vanished between readdir and stat
589
+ }
590
+ });
591
+ return out;
592
+ }
593
+
594
+ /**
595
+ * CLI sessions in this project's transcript dir that no Epic owns, newest
596
+ * first, for the "Restore a session" picker. The limit is per kind: up to
597
+ * `limit` interactive rows and, on a separate budget, up to `limit` headless
598
+ * rows, so a headless run never takes an interactive row's place. The walk
599
+ * stops once both budgets are full or after 400 head reads. Reads only that one
600
+ * dir; a missing dir lists nothing. Never throws (the `{ cwd: '' }` default
601
+ * makes a bare call list nothing).
602
+ * @param {{ cwd: string, limit?: number, deps?: RestorableDeps }} opts `limit` is per kind
603
+ * (default 50, at most 400).
604
+ * @returns {Promise<RestorableList>}
605
+ */
606
+ async function listRestorableSessions({ cwd, limit = DEFAULT_LIMIT, deps } = { cwd: '' }) {
607
+ /** @type {RestorableList} */
608
+ const result = { sessions: [], hiddenClaimed: 0, scanned: 0, truncated: false };
609
+ const projectCwd = normalizeCwd(cwd);
610
+ if (!projectCwd) return result;
611
+ const d = deps || {};
612
+ const dir = projectDirOf(projectCwd, d);
613
+ /** @type {string[]} */
614
+ let names;
615
+ try {
616
+ names = await fs.promises.readdir(dir);
617
+ } catch {
618
+ return result; // no CLI history for this project
619
+ }
620
+ const candidates = await statCandidates(dir, names.filter(isTranscriptName));
621
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs || (a.sessionId < b.sessionId ? -1 : a.sessionId > b.sessionId ? 1 : 0));
622
+
623
+ const claimed = lowerSet(await claimedClaudeSessionIdsAsync(projectCwd, d));
624
+ /** @type {Candidate[]} */
625
+ const open = [];
626
+ for (const c of candidates) {
627
+ if (claimed.has(c.sessionId.toLowerCase())) result.hiddenClaimed += 1;
628
+ else open.push(c);
629
+ }
630
+
631
+ const max = Number.isInteger(limit) && limit > 0 ? Math.min(limit, MAX_HEAD_READS) : DEFAULT_LIMIT;
632
+ const now = d.now ? d.now() : Date.now();
633
+ const bufs = { head: Buffer.allocUnsafe(HEAD_BYTES), tail: Buffer.allocUnsafe(TAIL_BYTES) };
634
+ // Only a head says which kind a row is, so a full budget drops that kind's
635
+ // later rows while the walk reads on for the other kind.
636
+ let interactive = 0;
637
+ let headless = 0;
638
+ let i = 0;
639
+ for (; i < open.length; i += 1) {
640
+ if ((interactive >= max && headless >= max) || result.scanned >= MAX_HEAD_READS) break;
641
+ const c = open[i];
642
+ result.scanned += 1;
643
+ const fields = await inspectTranscript(path.join(dir, c.name), c.sizeBytes, projectCwd, bufs);
644
+ if (!fields || (fields.headless ? headless : interactive) >= max) continue;
645
+ if (fields.headless) headless += 1;
646
+ else interactive += 1;
647
+ result.sessions.push({
648
+ sessionId: c.sessionId,
649
+ title: fields.title,
650
+ firstPrompt: fields.firstPrompt,
651
+ lastPrompt: fields.lastPrompt,
652
+ gitBranch: fields.gitBranch,
653
+ headless: fields.headless,
654
+ mtimeMs: c.mtimeMs,
655
+ sizeBytes: c.sizeBytes,
656
+ recentlyActive: now - c.mtimeMs < RECENT_MS,
657
+ });
658
+ }
659
+ result.truncated = i < open.length;
660
+ return result;
661
+ }
662
+
663
+ /**
664
+ * First ≤ 64 KiB of `file`, through a fixed buffer.
665
+ * @param {string} file
666
+ * @returns {Buffer}
667
+ */
668
+ function readHeadSync(file) {
669
+ const fd = fs.openSync(file, 'r');
670
+ try {
671
+ const buf = Buffer.allocUnsafe(HEAD_BYTES);
672
+ return buf.subarray(0, fs.readSync(fd, buf, 0, HEAD_BYTES, 0));
673
+ } finally {
674
+ fs.closeSync(fd);
675
+ }
676
+ }
677
+
678
+ /**
679
+ * @param {RefusalCode} code
680
+ * @param {string} message
681
+ * @returns {RestorableRefusal}
682
+ */
683
+ function refuse(code, message) {
684
+ return { ok: false, code, message };
685
+ }
686
+
687
+ /** @param {unknown} id */
688
+ function showId(id) {
689
+ if (typeof id !== 'string') return `(${id === null ? 'null' : typeof id})`;
690
+ return JSON.stringify(id.length > 80 ? `${id.slice(0, 80)}…` : id);
691
+ }
692
+
693
+ /**
694
+ * Can `sessionId` be adopted by a new Epic of this project? The single-id gate
695
+ * for the mint path: id format first (before any path exists), then the
696
+ * transcript file, its recorded cwd, and Epic ownership.
697
+ * @param {string} cwd Project cwd (absolute).
698
+ * @param {string} sessionId
699
+ * @param {RestorableDeps} [deps]
700
+ * @returns {RestorableOk|RestorableRefusal}
701
+ */
702
+ function checkRestorableSessionSync(cwd, sessionId, deps) {
703
+ const d = deps || {};
704
+ const valid = typeof sessionId === 'string' && SESSION_ID_RE.test(sessionId);
705
+ const projectCwd = normalizeCwd(cwd);
706
+ if (!valid) {
707
+ const where = projectCwd ? projectDirOf(projectCwd, d) : 'any project dir';
708
+ return refuse('invalid_id', `Refused session id ${showId(sessionId)} for ${where}: not a Claude session UUID, so no path was built from it.`);
709
+ }
710
+ if (!projectCwd) {
711
+ return refuse('not_found', `Cannot look up session ${sessionId}: project cwd ${showId(cwd)} is not an absolute path, so there is no project dir to search.`);
712
+ }
713
+ const dir = projectDirOf(projectCwd, d);
714
+ const transcriptPath = path.join(dir, `${sessionId}${JSONL}`);
715
+ let isFile = false;
716
+ try {
717
+ isFile = fs.statSync(transcriptPath).isFile();
718
+ } catch {
719
+ isFile = false;
720
+ }
721
+ if (!isFile) return refuse('not_found', `No CLI transcript for session ${sessionId} in ${dir}.`);
722
+
723
+ /** @type {string|null} */
724
+ let recordedCwd = null;
725
+ try {
726
+ recordedCwd = scanHead(readHeadSync(transcriptPath), projectCwd, true).recordedCwd;
727
+ } catch (err) {
728
+ const why = err instanceof Error ? err.message : String(err);
729
+ return refuse('not_found', `Session ${sessionId} in ${dir} could not be read: ${why}`);
730
+ }
731
+ if (!sameCwd(recordedCwd, projectCwd)) {
732
+ return refuse('cwd_mismatch', recordedCwd === null
733
+ ? `Session ${sessionId} in ${dir} records no cwd in its first 64 KiB, so it cannot be shown to belong to ${projectCwd}.`
734
+ : `Session ${sessionId} in ${dir} was recorded in ${recordedCwd}, not ${projectCwd}.`);
735
+ }
736
+ if (lowerSet(claimedClaudeSessionIds(projectCwd, d)).has(sessionId.toLowerCase())) {
737
+ return refuse('claimed', `Session ${sessionId} in ${dir} already belongs to an Epic in this project.`);
738
+ }
739
+ return { ok: true, transcriptPath };
740
+ }
741
+
742
+ module.exports = {
743
+ SESSION_ID_RE,
744
+ claimedClaudeSessionIds,
745
+ claimedClaudeSessionIdsAsync,
746
+ listRestorableSessions,
747
+ checkRestorableSessionSync,
748
+ __resetCacheForTests,
749
+ };