claude-code-session-manager 0.131.0 → 0.133.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 (90) hide show
  1. package/README.md +3 -3
  2. package/dist/assets/{AgentLibrary-CYXre0J-.js → AgentLibrary-DOAG-mcG.js} +1 -1
  3. package/dist/assets/{AppSettings-xNSfCj8e.js → AppSettings-BHKM_AKh.js} +2 -2
  4. package/dist/assets/{Button-BWljh5IK.js → Button-CmO1wmPw.js} +1 -1
  5. package/dist/assets/{DocumentEditorPane-FUC2hZlp.js → DocumentEditorPane-8QMNrNRt.js} +1 -1
  6. package/dist/assets/{Extensions-CsyUoklz.js → Extensions-Boo21B3b.js} +2 -2
  7. package/dist/assets/{History-BvNmY9OQ.js → History-C4epd1hp.js} +1 -1
  8. package/dist/assets/{Library-DVXk77zA.js → Library-CrgzRQzL.js} +1 -1
  9. package/dist/assets/{ListDetail-DAAx__24.js → ListDetail-DA7y1DQ-.js} +1 -1
  10. package/dist/assets/{Panel-g2D-e-RM.js → Panel-D-WMBhKH.js} +1 -1
  11. package/dist/assets/{ProjectClaudeConfig-BDuHJwaO.js → ProjectClaudeConfig-CuUADpIu.js} +1 -1
  12. package/dist/assets/{ProvenanceBadge-wew4_nf3.js → ProvenanceBadge-B7AsoRk6.js} +1 -1
  13. package/dist/assets/{Scheduler-CbeUIqD-.js → Scheduler-C86gRh51.js} +1 -1
  14. package/dist/assets/{Settings-B23RsRfm.js → Settings-B4Q9DwVS.js} +1 -1
  15. package/dist/assets/{SkillReferenceGraph-BxQPCfsg.js → SkillReferenceGraph-DX4ZgvlY.js} +1 -1
  16. package/dist/assets/{Skills-4AR2FQrI.js → Skills-DqKI37yi.js} +1 -1
  17. package/dist/assets/{SourceChip-jrC0vjfw.js → SourceChip-C974LROr.js} +1 -1
  18. package/dist/assets/{SystemPrompt-hHoBEnYb.js → SystemPrompt-C502jIwO.js} +1 -1
  19. package/dist/assets/{TiptapBody-FkUqxO9u.js → TiptapBody-DwNXN6Ki.js} +1 -1
  20. package/dist/assets/{Toggle-DQMNWZKT.js → Toggle-C2OsxnPK.js} +1 -1
  21. package/dist/assets/{ViewTabs-DGU0ZuxB.js → ViewTabs-DBxKGbAK.js} +1 -1
  22. package/dist/assets/{VoiceButton-BPPvDllh.js → VoiceButton-C680wpmX.js} +1 -1
  23. package/dist/assets/{historyTotals-D8Oc3wUK.js → historyTotals-Cz-VYPEc.js} +1 -1
  24. package/dist/assets/{index-oXqzajWV.css → index-CMwAikUb.css} +1 -1
  25. package/dist/assets/index-Dh5geJe3.js +3111 -0
  26. package/dist/index.html +2 -2
  27. package/dist-web/app.css +1 -1
  28. package/dist-web/app.js +428 -414
  29. package/package.json +1 -1
  30. package/scripts/scheduler-mcp-server.cjs +12 -4
  31. package/src/main/build-info.json +4 -4
  32. package/src/main/chatRunner.cjs +77 -14
  33. package/src/main/index.cjs +15 -0
  34. package/src/main/ipcSchemas.cjs +54 -0
  35. package/src/main/lib/CLAUDE.md +2 -0
  36. package/src/main/lib/agent-cli/adapters/antigravity.cjs +147 -0
  37. package/src/main/lib/agent-cli/adapters/codex.cjs +170 -0
  38. package/src/main/lib/agent-cli/adapters/cursor.cjs +138 -0
  39. package/src/main/lib/agent-cli/adapters/gemini.cjs +119 -0
  40. package/src/main/lib/agent-cli/adapters/opencode.cjs +117 -0
  41. package/src/main/lib/agent-cli/agentCliEvents.cjs +94 -0
  42. package/src/main/lib/agent-cli/agentCliIpc.cjs +109 -0
  43. package/src/main/lib/agent-cli/agentCliRegistry.cjs +213 -0
  44. package/src/main/lib/agent-cli/agentCliSessionStore.cjs +152 -0
  45. package/src/main/lib/agent-cli/agentCliTurn.cjs +99 -0
  46. package/src/main/lib/app-preview/appPreviewIpc.cjs +125 -0
  47. package/src/main/lib/app-preview/appPreviewManager.cjs +317 -0
  48. package/src/main/lib/app-preview/appPreviewScripts.cjs +106 -0
  49. package/src/main/lib/app-preview/appPreviewSweep.cjs +92 -0
  50. package/src/main/lib/chatBootRecovery.cjs +41 -1
  51. package/src/main/lib/claude/agentEffortResolve.cjs +11 -3
  52. package/src/main/lib/epic/activeIndexMerge.cjs +25 -2
  53. package/src/main/lib/epic/archivedTranscript.cjs +39 -6
  54. package/src/main/lib/epic/epicChanges.cjs +466 -0
  55. package/src/main/lib/epic/epicMint.cjs +45 -1
  56. package/src/main/lib/epic/epicReopen.cjs +8 -2
  57. package/src/main/lib/epic/epicSpawnPlan.cjs +12 -0
  58. package/src/main/lib/epic/epicWorktreeMerge.cjs +39 -4
  59. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +9 -4
  60. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +36 -13
  61. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  62. package/src/main/lib/git/gitExec.cjs +9 -1
  63. package/src/main/lib/git/gitWorktree.cjs +94 -0
  64. package/src/main/lib/git/unifiedDiff.cjs +207 -0
  65. package/src/main/lib/mcpToolCatalog.cjs +15 -6
  66. package/src/main/lib/mdDocCensus.cjs +364 -0
  67. package/src/main/lib/mdDocRefs.cjs +249 -0
  68. package/src/main/lib/mdNetworkScan.cjs +158 -15
  69. package/src/main/lib/persona-macro/builtinMacros.cjs +17 -0
  70. package/src/main/lib/persona-macro/macroJobDispatch.cjs +4 -1
  71. package/src/main/lib/persona-macro/macroJobIpc.cjs +57 -11
  72. package/src/main/lib/persona-macro/macroLibrary.cjs +40 -10
  73. package/src/main/lib/prd/prdCreate.cjs +7 -2
  74. package/src/main/lib/prd/prdFrontmatter.cjs +10 -3
  75. package/src/main/lib/promptSessionSchema.cjs +6 -0
  76. package/src/main/lib/remoteTranscriptTail.cjs +23 -4
  77. package/src/main/lib/scheduler/landedSinceRun.cjs +2 -1
  78. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  79. package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
  80. package/src/main/projectPages.cjs +19 -4
  81. package/src/main/promptSessionEvents.cjs +10 -6
  82. package/src/main/scheduler/gitTreeGuard.cjs +2 -1
  83. package/src/main/scheduler/prdParser.cjs +2 -1
  84. package/src/main/scheduler.cjs +7 -2
  85. package/src/main/transcripts.cjs +18 -4
  86. package/src/main/webRemote.cjs +10 -5
  87. package/src/preload/api.d.ts +150 -3
  88. package/src/preload/apiSurface.json +56 -0
  89. package/src/preload/index.cjs +22 -0
  90. package/dist/assets/index-9ajPMXBg.js +0 -3097
@@ -11,12 +11,20 @@
11
11
  * (git only lists the files), and it does I/O, so it is not util/. It sits
12
12
  * beside memoryMdNetwork.cjs, the other reader of the same docs network.
13
13
  *
14
- * - buildMdNetwork({ files, root, exists }) — pure graph builder over in-memory docs.
15
- * - scanMdNetwork(cwd, deps) — thin I/O wrapper: one `git ls-files -z`, at most
16
- * MAX_DOCS docs read (the root, then breadth-first along its links, then the
17
- * rest shallowest-first, so the cap drops unreachable docs before reachable
14
+ * - buildMdNetwork({ files, root, exists, records }) — pure graph builder over
15
+ * in-memory docs; `records` paths never appear in orphan findings.
16
+ * - scanMdNetwork(cwd, deps, opts) — thin I/O wrapper: one `git ls-files -z`, at
17
+ * most MAX_DOCS docs read (the root, then breadth-first along its links, then
18
+ * the rest shallowest-first, so the cap drops unreachable docs before reachable
18
19
  * ones), at most MAX_DOC_BYTES each, READ_BATCH reads in parallel, async fs only.
19
20
  * Untracked link targets (e.g. gitignored files) are checked on disk.
21
+ * It also attaches a per-doc census (mdDocCensus.cjs + mdDocRefs.cjs) over
22
+ * every tracked .md: one `git log --max-count=2000 --name-only` (64 MB buffer)
23
+ * for recency, one `git grep -F -o` over non-.md files (16 MB buffer) for code
24
+ * mentions, and at most MAX_REF_PROBES on-disk probes (READ_BATCH at a time)
25
+ * for backticked paths git does not vouch for — unprobed ones count as
26
+ * existing. A failing git call degrades to a census warning, never an error.
27
+ * Docs in record collections (opts.recordFolders / heuristic) leave orphans.
20
28
  *
21
29
  * Followed: inline `[text](target)` links (images too) and `<target.md>`
22
30
  * autolinks, outside code fences, inline code and HTML comments. Ignored: any
@@ -29,6 +37,8 @@
29
37
  const fs = require('node:fs');
30
38
  const path = require('node:path');
31
39
  const { execGit } = require('./git/gitExec.cjs');
40
+ const { censusMdDocs, parseGitLog } = require('./mdDocCensus.cjs');
41
+ const { backtickPaths, assessRefs, mentionPatterns, parseMentions } = require('./mdDocRefs.cjs');
32
42
 
33
43
  const ROOT_DOC = 'CLAUDE.md';
34
44
  const MAX_DOCS = 2000;
@@ -38,6 +48,11 @@ const READ_BATCH = 32;
38
48
  const MAX_LINK_CHARS = 1024;
39
49
  /** `git ls-files -z` stdout cap; node's 1 MB default overflows near 15k tracked files. */
40
50
  const LS_FILES_MAX_BUFFER = 64 * 1024 * 1024;
51
+ const LOG_ARGS = ['log', '--max-count=2000', '--no-renames', '--format=%x01%ct', '--name-only', '-z'];
52
+ const LOG_MAX_BUFFER = 64 * 1024 * 1024;
53
+ const GREP_MAX_BUFFER = 16 * 1024 * 1024;
54
+ /** On-disk probes for backticked paths git does not vouch for, per scan. */
55
+ const MAX_REF_PROBES = 500;
41
56
  const OWNER_NAMES = new Set(['CLAUDE.md', 'README.md', 'AGENTS.md']);
42
57
  const MISSING_CODES = new Set(['ENOENT', 'ENOTDIR', 'EISDIR']);
43
58
  const DETAIL_MISSING = 'The link target doesn’t exist.';
@@ -60,8 +75,12 @@ const AUTOLINK_RE = /<([^<>\s]{1,1024})>/g;
60
75
  * @typedef {{ type: 'broken-link', file: string, line: number, target: string, to: string, where: string, detail: string }} MdNetworkBrokenLink
61
76
  * @typedef {{ type: 'orphan', where: string, count: number, paths: string[], detail: string }} MdNetworkOrphan
62
77
  * @typedef {MdNetworkBrokenLink | MdNetworkOrphan} MdNetworkFinding
63
- * @typedef {{ ok: true, root: string, nodes: MdNetworkNode[], edges: MdNetworkEdge[], findings: MdNetworkFinding[], docs: number, links: number, scopes: string[] }} MdNetwork
78
+ * @typedef {{ ok: true, root: string, nodes: MdNetworkNode[], edges: MdNetworkEdge[], findings: MdNetworkFinding[], docs: number, links: number, scopes: string[] }} MdLinkNetwork
79
+ * @typedef {MdLinkNetwork | { ok: false, error: string }} MdLinkNetworkResult
80
+ * @typedef {import('./mdDocCensus.cjs').MdCensus} MdCensus
81
+ * @typedef {MdLinkNetwork & { census: MdCensus }} MdNetwork
64
82
  * @typedef {MdNetwork | { ok: false, error: string }} MdNetworkResult
83
+ * @typedef {{ recordFolders?: string[], docFolders?: string[] }} ScanOpts
65
84
  * @typedef {{ fence: string, inComment: boolean }} LineState an open code fence / HTML comment
66
85
  */
67
86
 
@@ -289,7 +308,7 @@ function orphanDetail(root, count) {
289
308
  : `No link path from ${root} reaches these ${count} docs, so agents starting there never find them.`;
290
309
  }
291
310
 
292
- /** @param {string} root @returns {MdNetworkResult} */
311
+ /** @param {string} root @returns {{ ok: false, error: string }} */
293
312
  function missingRoot(root) {
294
313
  return { ok: false, error: `no ${root} at the project root` };
295
314
  }
@@ -298,11 +317,12 @@ function missingRoot(root) {
298
317
  * Pure: the link network reachable from `root` over in-memory docs.
299
318
  * `exists(relPath)` vouches for link targets that are neither one of `files`
300
319
  * nor a folder holding one (code files, docs left unread, untracked files);
301
- * without it such targets are missing.
302
- * @param {{ files?: MdFile[], root?: string, exists?: (relPath: string) => boolean }} [input]
303
- * @returns {MdNetworkResult}
320
+ * without it such targets are missing. `records` (record-collection docs, not
321
+ * meant to be linked) are left out of orphan groups.
322
+ * @param {{ files?: MdFile[], root?: string, exists?: (relPath: string) => boolean, records?: ReadonlySet<string> }} [input]
323
+ * @returns {MdLinkNetworkResult}
304
324
  */
305
- function buildMdNetwork({ files = [], root = ROOT_DOC, exists } = {}) {
325
+ function buildMdNetwork({ files = [], root = ROOT_DOC, exists, records } = {}) {
306
326
  try {
307
327
  const rootPath = toRepoPath(root);
308
328
  /** @type {Map<string, MdFile>} */
@@ -367,7 +387,7 @@ function buildMdNetwork({ files = [], root = ROOT_DOC, exists } = {}) {
367
387
  /** @type {Map<string, string[]>} */
368
388
  const orphans = new Map();
369
389
  for (const p of docs.keys()) {
370
- if (depth.has(p)) continue;
390
+ if (depth.has(p) || (records !== undefined && records.has(p))) continue;
371
391
  const top = topFolder(p);
372
392
  const group = orphans.get(top);
373
393
  if (group) group.push(p);
@@ -429,9 +449,10 @@ function gitFailure(err) {
429
449
  * I/O: scans the git project at `cwd` and builds its network. Never throws.
430
450
  * @param {string} cwd the project root (`git ls-files` paths are relative to it)
431
451
  * @param {ScanDeps} [deps] injectable I/O; defaults are git + async fs
452
+ * @param {ScanOpts} [opts] record-collection overrides for the census
432
453
  * @returns {Promise<MdNetworkResult>}
433
454
  */
434
- async function scanMdNetwork(cwd, deps = {}) {
455
+ async function scanMdNetwork(cwd, deps = {}, opts = {}) {
435
456
  try {
436
457
  if (typeof cwd !== 'string' || cwd === '') return { ok: false, error: 'cwd must be a non-empty path' };
437
458
  /** @type {NonNullable<ScanDeps['execGit']>} */
@@ -542,11 +563,133 @@ async function scanMdNetwork(cwd, deps = {}) {
542
563
  });
543
564
  }
544
565
 
545
- return buildMdNetwork({
546
- files,
566
+ /** @param {string} p */
567
+ const vouched = (p) => !gone.has(p) && (trackedSet.has(p) || trackedFolders.has(p));
568
+ /** @param {string} p */
569
+ const present = (p) => onDisk.has(p) || vouched(p);
570
+ const network = buildMdNetwork({ files, root: ROOT_DOC, exists: present });
571
+ if (!network.ok) return network;
572
+
573
+ // ── Census ──
574
+ /** @type {string[]} */
575
+ const warnings = [];
576
+
577
+ // Recency: one capped git log; newest first, so the first sighting wins.
578
+ /** @type {import('./mdDocCensus.cjs').GitLogEntry[]} */
579
+ let log = [];
580
+ try {
581
+ const out = String(await runGit(cwd, LOG_ARGS, { maxBuffer: LOG_MAX_BUFFER }));
582
+ log = parseGitLog(out);
583
+ if (log.length === 0 && out.trim() !== '') warnings.push('git history unavailable: unparseable git log output');
584
+ } catch (err) {
585
+ warnings.push(`git history unavailable: ${gitFailure(err)}`);
586
+ }
587
+ /** @type {Map<string, number>} */
588
+ const lastCommit = new Map();
589
+ for (const entry of log) {
590
+ for (const f of entry.files) if (!lastCommit.has(f)) lastCommit.set(f, entry.ms);
591
+ }
592
+ /** @param {string} p */
593
+ const lastCommitOf = (p) => lastCommit.get(p) ?? null;
594
+
595
+ /** @type {Map<string, { depth: number, linkedFrom: number }>} */
596
+ const reachable = new Map(network.nodes.map((n) => [n.path, { depth: n.depth, linkedFrom: n.linkedFrom }]));
597
+ /** @type {Map<string, MdFile>} */
598
+ const readByPath = new Map(files.map((f) => [f.path, f]));
599
+
600
+ // Backticked paths git does not vouch for: probed on disk, capped; the rest count as existing.
601
+ /** @type {Map<string, boolean>} */
602
+ const probed = new Map();
603
+ /** @type {string[]} */
604
+ const toProbe = [];
605
+ const queuedProbes = new Set();
606
+ /** @type {Map<MdFile, string[]>} */
607
+ const tokensOf = new Map();
608
+ for (const file of files) {
609
+ const tokens = backtickPaths(file.text);
610
+ tokensOf.set(file, tokens);
611
+ const dir = path.posix.dirname(file.path);
612
+ for (const tok of tokens) {
613
+ const rootForm = toRepoPath(tok);
614
+ const forms = dir === '.' ? [rootForm] : [rootForm, toRepoPath(path.posix.join(dir, tok))];
615
+ for (const rel of forms) {
616
+ if (rel === '.' || rel === '..' || rel.startsWith('../')) continue;
617
+ if (vouched(rel)) break; // assessRefs takes the first existing form
618
+ if (onDisk.has(rel) || queuedProbes.has(rel) || toProbe.length >= MAX_REF_PROBES) continue;
619
+ queuedProbes.add(rel);
620
+ toProbe.push(rel);
621
+ }
622
+ }
623
+ }
624
+ for (let i = 0; i < toProbe.length; i += READ_BATCH) {
625
+ const batch = toProbe.slice(i, i + READ_BATCH);
626
+ const hits = await Promise.all(batch.map(probe));
627
+ batch.forEach((rel, k) => probed.set(rel, hits[k]));
628
+ }
629
+ /** @param {string} p */
630
+ const refExists = (p) => {
631
+ if (present(p)) return true;
632
+ if (gone.has(p)) return false;
633
+ const hit = probed.get(p);
634
+ return hit === undefined ? true : hit;
635
+ };
636
+
637
+ /** @type {Map<string, import('./mdDocCensus.cjs').MdDocRefs>} */
638
+ const refs = new Map();
639
+ for (const file of files) {
640
+ const linkTargets = linksOf(file)
641
+ .filter((l) => !l.escapes && present(l.to))
642
+ .map((l) => l.to);
643
+ refs.set(
644
+ file.path,
645
+ assessRefs({
646
+ docPath: file.path,
647
+ linkTargets,
648
+ tokens: tokensOf.get(file) ?? [],
649
+ docMs: lastCommitOf(file.path),
650
+ exists: refExists,
651
+ lastCommitOf,
652
+ }),
653
+ );
654
+ }
655
+
656
+ // Code mentions: one git grep over every non-.md tracked file.
657
+ /** @type {Map<string, string[]>} */
658
+ let codeMentions = new Map();
659
+ const { patterns, owner } = mentionPatterns(docPaths);
660
+ if (patterns.length > 0) {
661
+ const grepArgs = ['grep', '--no-color', '-I', '-F', '-o', '--null', ...patterns.flatMap((p) => ['-e', p]), '--', '.', ':(exclude)*.md'];
662
+ try {
663
+ codeMentions = parseMentions(String(await runGit(cwd, grepArgs, { maxBuffer: GREP_MAX_BUFFER })), owner);
664
+ } catch (err) {
665
+ const stderr = errorField(err, 'stderrText');
666
+ const noMatches = errorField(err, 'code') === 1 && !(typeof stderr === 'string' && stderr.trim() !== '');
667
+ if (!noMatches) warnings.push(`code mentions unavailable: ${gitFailure(err)}`);
668
+ }
669
+ }
670
+
671
+ const docs = docPaths.map((p) => {
672
+ const file = readByPath.get(p);
673
+ if (!file) return { path: p, text: null, lines: null, bytes: null };
674
+ const { text } = file;
675
+ return { path: p, text, lines: text === '' ? 0 : text.split('\n').length, bytes: Buffer.byteLength(text) };
676
+ });
677
+ const census = censusMdDocs({
547
678
  root: ROOT_DOC,
548
- exists: (p) => onDisk.has(p) || (!gone.has(p) && (trackedSet.has(p) || trackedFolders.has(p))),
679
+ docs,
680
+ reachable,
681
+ log,
682
+ refs,
683
+ codeMentions,
684
+ recordFolders: opts.recordFolders,
685
+ docFolders: opts.docFolders,
549
686
  });
687
+ census.warnings.unshift(...warnings);
688
+
689
+ const records = new Set(census.docs.filter((d) => d.role === 'record').map((d) => d.path));
690
+ if (records.size === 0) return { ...network, census };
691
+ const pruned = buildMdNetwork({ files, root: ROOT_DOC, exists: present, records });
692
+ return pruned.ok ? { ...pruned, census } : pruned;
550
693
  } catch (err) {
551
694
  return { ok: false, error: errorText(err) };
552
695
  }
@@ -107,6 +107,23 @@ const BUILTIN_MACROS = Object.freeze([
107
107
  prompt:
108
108
  "Build this project's competitor feature matrix: how this product compares to its top 4 competitors. The competitors are named on a 'Competitors:' line in the additional instructions — up to 4 semicolon-separated slots, each a product name or 'auto' (an 'auto' slot means pick the most popular remaining competitor in this product's category, with cited popularity evidence); with no Competitors line, reuse the saved matrix's competitors, or make 4 auto picks when there is no saved matrix. Warm-start first: call project_matrix_read and, when a matrix exists, keep its feature, group and competitor ids stable and research only what is new since its last run plus unknown cells. Then fan out Haiku competitive-researcher subagents, one per competitor plus one user-voice sweep, collecting official announcements, dev blogs, changelogs, docs and what users rave about or ask for, with a source URL for every claim. Compare their findings against this repository's real features (read from the README, docs, manifest, source tree and git log, each backed by a path) and merge everything into 6-12 logical feature groups; for every feature record a stable id, title, detailed description, support per product (yes/partial/no/unknown with evidence), user sentiment, priority, rationale, and a ready-to-run sessionGoal where this project lacks or only partly has it. Append a runs[] entry and save the whole matrix with one project_matrix_write call.",
109
109
  }),
110
+ Object.freeze({
111
+ id: 'builtin-cpu-audit',
112
+ label: 'CPU audit & fixes',
113
+ agentName: 'architect',
114
+ tag: 'feature',
115
+ surface: 'project-home',
116
+ projects: ['*'],
117
+ builtinVersion: 1,
118
+ inputs: Object.freeze([
119
+ Object.freeze({ name: 'scope', label: 'Scope', default: 'the whole project', required: true }),
120
+ Object.freeze({ name: 'scenario', label: 'Run scenario', default: 'idle, then its typical everyday load', required: true }),
121
+ ]),
122
+ supersedes: Object.freeze(['cpu-audit-fixes-8bd5d1']),
123
+ priorPrompts: Object.freeze([]),
124
+ prompt:
125
+ "Critically evaluate how much CPU this project uses while it runs, then get the recommended changes built. Primary goal: it consumes fewer resources while it runs — CPU first, then memory, disk I/O, network and process count. Secondary goal: it gets faster. Behavior stays the same. Scope: {{scope}}. Run scenario to measure: {{scenario}}. The project's CLAUDE.md and AGENTS.md laws override this prompt.\n\n1. Learn how it really runs. Read the README, manifests and start scripts. List every long-running process and everything it starts: workers, child CLIs, MCP servers, file watchers, timers, cron entries. If the project has no long-running process (a library, CLI or static site), measure its main commands instead (build, test, a typical run).\n\n2. Measure a baseline before you look for fixes. If the project is already running on this machine, measure that instance; never start a second copy beside a live one (ports, locks and shared state clash). Put a hard timeout on every command. Measure each state of the run scenario over a fixed window of at least 5 minutes. Record per process: average and peak CPU %, RSS, threads, child processes started per minute, and wakeups or syscalls where you can (pidstat, ps, top -b, /proc/<pid>/stat deltas, strace -c -f). Then profile the top consumers so cost is attributed to functions, not guessed: attach a sampling profiler to the running process where the runtime allows it (perf, py-spy, the Node inspector, DevTools for renderer processes), and restart a process under a profiler only when nothing live depends on it. Save the exact commands so the after-measurement repeats them.\n\n3. Review the code critically, starting from the hottest profiled paths. Look for: polling and timers that fire while nothing changes (idle should be near 0% CPU); busy loops; full rescans or re-parses of large files and directories; recursive watchers on big trees; a process spawned per tick or per request; unbounded concurrency; work redone on every request or render instead of cached; UI re-render storms and animations running while hidden; sync I/O on hot paths; chatty logging; large JSON stringify/parse; retries without backoff; over-frequent heartbeats; leaks (listeners, intervals, caches that only grow). For each one, first ask whether the work needs to run at all, then how to make it cheaper. Prefer structural fixes (event-driven instead of polling, incremental instead of full rescans, one shared process instead of many) over micro-tuning.\n\n4. Rank findings by measured cost × confidence ÷ risk, and drop anything without a measurable cost. Show them as a table: rank | where (file:line) | what burns the resource | measured cost (CPU share, RSS, spawns/min) | recommended change | expected saving | risk or tradeoff. Name every tradeoff plainly, such as a slower refresh. If the project is already lean, say so with the numbers and stop; do not invent work.\n\n5. Build the changes through /develop, highest impact first. Each PRD carries its measured evidence, the change, and acceptance criteria a headless run can check: deterministic tests (fake timers proving nothing polls while idle, call or spawn counts, bounded work per tick) or a bounded micro-benchmark with a before number and a target. Never use \"launch the app and watch top\" as a criterion. Every fix gets a regression guard so the waste cannot quietly return, and existing tests stay green.\n\n6. Track the PRDs to a validated finish, then re-measure live with the same commands, window and scenario. Report a before/after table per process: average and peak CPU, RSS, spawns/min. If the running copy is an installed or released build rather than this tree, the after-measurement waits for that release: say exactly what has landed but is not live yet, and never claim a saving from tests alone.",
126
+ }),
110
127
  ]);
111
128
 
112
129
  module.exports = { BUILTIN_MACROS };
@@ -5,6 +5,7 @@
5
5
  * scheduler PRD inside an existing Epic, so the build runs headless as the
6
6
  * macro's persona under the scheduler's budget instead of a chat turn.
7
7
  * Never mints an Epic (single-creator law): the caller supplies epicId.
8
+ * A press may carry a lower per-run effort, written as the PRD's `effort` frontmatter.
8
9
  *
9
10
  * Plain Node, no Electron imports; all I/O is injected.
10
11
  */
@@ -12,6 +13,7 @@
12
13
  const path = require('node:path');
13
14
  const { BUILTIN_MACROS } = require('./builtinMacros.cjs');
14
15
  const { kebabCase } = require('../util/kebabCase.cjs');
16
+ const { PRD_EFFORT_LEVELS } = require('../prd/prdFrontmatter.cjs');
15
17
 
16
18
  const ACTIVE = new Set(['pending', 'held', 'running']);
17
19
  const RETRYABLE = new Set(['needs_review', 'failed']);
@@ -54,7 +56,7 @@ function rawEntryIdFor(kind, extra, t) {
54
56
  }
55
57
 
56
58
  async function dispatchMacroJob(
57
- { cwd, macroId, epicId, extraInstructions } = {},
59
+ { cwd, macroId, epicId, extraInstructions, effort } = {},
58
60
  { createPrd, listRows, archivePrd, builtins = BUILTIN_MACROS, now = Date.now } = {},
59
61
  ) {
60
62
  const macro = (builtins || []).find((m) => m && m.id === macroId);
@@ -117,6 +119,7 @@ async function dispatchMacroJob(
117
119
  + 'Build outside the repository (mktemp -d under ~/.cache). SM_PROJECT_ROOT is the project main checkout; the save tool writes there, so omit its cwd.',
118
120
  gate: absPaths.map((p) => buildGate(p, t)),
119
121
  };
122
+ if (typeof effort === 'string' && PRD_EFFORT_LEVELS.includes(effort)) input.effort = effort;
120
123
 
121
124
  let res;
122
125
  try {
@@ -6,17 +6,48 @@
6
6
  * injected (index.cjs passes the real scheduler, createPrd and archive).
7
7
  *
8
8
  * deps: { schemas, validatePath, readActiveIndex, createPrd, loadJobs,
9
- * archivePrd, dispatchMacroJob?, macroJobStatuses?, readHistoryTail? }
9
+ * archivePrd, appendResponseEventWithReason?, dispatchMacroJob?,
10
+ * macroJobStatuses?, readHistoryTail?, builtins? }
11
+ *
12
+ * When a dispatch returns ok:false for an Epic that exists in the cwd's
13
+ * active-index.json (and no build is already running for it — `activeSlug`),
14
+ * one durable 'response' event marked `notice: 'job-not-queued'` is appended
15
+ * to that Epic naming the macro, the error and the retry path (PRD 2950), so
16
+ * a job-macro Epic whose build never queued cannot read as a silently running
17
+ * session. The append is best effort: it never changes the returned result.
10
18
  * `createPrd` is called as `chat:create-prd` calls it, so its own
11
19
  * remote.requestReconcile() queues the row at once — no second rescan here.
12
20
  */
13
21
 
14
22
  const { dispatchMacroJob: realDispatch } = require('./macroJobDispatch.cjs');
15
23
  const { macroJobStatuses: realStatuses } = require('./macroJobStatus.cjs');
24
+ const { BUILTIN_MACROS } = require('./builtinMacros.cjs');
25
+
26
+ const JOB_NOT_QUEUED_NOTICE = 'job-not-queued';
27
+
28
+ function noticeText(label, error) {
29
+ return `${label} background build was not queued: ${error} — press it again in Project Home ▸ Tools to retry.`;
30
+ }
16
31
 
17
32
  function registerMacroJobIpc(ipcMain, deps = {}) {
18
33
  const dispatch = deps.dispatchMacroJob || realDispatch;
19
34
  const statuses = deps.macroJobStatuses || realStatuses;
35
+ const builtins = deps.builtins || BUILTIN_MACROS;
36
+
37
+ async function appendNotice(cwd, macroId, epicId, error) {
38
+ if (typeof deps.appendResponseEventWithReason !== 'function') return;
39
+ try {
40
+ const macro = (builtins || []).find((m) => m && m.id === macroId);
41
+ const label = (macro && macro.label) || macroId;
42
+ const res = await deps.appendResponseEventWithReason(
43
+ cwd, epicId, noticeText(label, error),
44
+ { notice: JOB_NOT_QUEUED_NOTICE, allowInactive: true },
45
+ );
46
+ if (res && res.ok === false) console.warn('[macroJobIpc] job-not-queued notice not appended', epicId, res.reason);
47
+ } catch (e) {
48
+ console.warn('[macroJobIpc] job-not-queued notice append failed', epicId, e?.message ?? e);
49
+ }
50
+ }
20
51
 
21
52
  ipcMain.handle('macros:dispatch-job', async (_event, rawPayload) => {
22
53
  const payload = deps.schemas.macrosDispatchJob.parse(rawPayload);
@@ -24,17 +55,32 @@ function registerMacroJobIpc(ipcMain, deps = {}) {
24
55
  const index = deps.readActiveIndex(cwd);
25
56
  const sessions = index && index.sessions ? index.sessions : {};
26
57
  const entry = Object.prototype.hasOwnProperty.call(sessions, payload.epicId) ? sessions[payload.epicId] : null;
27
- if (!entry || entry.status !== 'active') {
58
+ if (!entry) {
28
59
  return { ok: false, error: `epic ${payload.epicId} is not an active session in this project` };
29
60
  }
30
- return dispatch(
31
- { cwd, macroId: payload.macroId, epicId: payload.epicId, extraInstructions: payload.extraInstructions },
32
- {
33
- createPrd: deps.createPrd,
34
- listRows: async () => deps.loadJobs(),
35
- archivePrd: (slug, rowCwd) => deps.archivePrd(slug, rowCwd),
36
- },
37
- );
61
+ if (entry.status !== 'active') {
62
+ const refused = { ok: false, error: `epic ${payload.epicId} is not an active session in this project` };
63
+ await appendNotice(cwd, payload.macroId, payload.epicId, refused.error);
64
+ return refused;
65
+ }
66
+ let result;
67
+ try {
68
+ result = await dispatch(
69
+ { cwd, macroId: payload.macroId, epicId: payload.epicId, extraInstructions: payload.extraInstructions, effort: payload.effort },
70
+ {
71
+ createPrd: deps.createPrd,
72
+ listRows: async () => deps.loadJobs(),
73
+ archivePrd: (slug, rowCwd) => deps.archivePrd(slug, rowCwd),
74
+ },
75
+ );
76
+ } catch (e) {
77
+ await appendNotice(cwd, payload.macroId, payload.epicId, e?.message ?? String(e));
78
+ throw e;
79
+ }
80
+ if (result && result.ok === false && !result.activeSlug) {
81
+ await appendNotice(cwd, payload.macroId, payload.epicId, result.error || 'unknown error');
82
+ }
83
+ return result;
38
84
  });
39
85
 
40
86
  ipcMain.handle('macros:job-status', async (_event, rawPayload) => {
@@ -47,4 +93,4 @@ function registerMacroJobIpc(ipcMain, deps = {}) {
47
93
  });
48
94
  }
49
95
 
50
- module.exports = { registerMacroJobIpc };
96
+ module.exports = { registerMacroJobIpc, JOB_NOT_QUEUED_NOTICE };
@@ -31,6 +31,10 @@
31
31
  * project). setMacroProject cannot narrow a '*' macro: it returns
32
32
  * `{ ok: false, error: 'macro is shown in every project' }`.
33
33
  *
34
+ * A surface 'project-home' macro is shown in every project (only its generated
35
+ * artifacts are per project); this module enforces that on load (a narrowed
36
+ * stored entry is widened to ['*']) and on save (projects forced to ['*']).
37
+ *
34
38
  * Plain Node, no Electron imports.
35
39
  */
36
40
 
@@ -394,16 +398,35 @@ function ensureBuiltins(macros, builtins) {
394
398
  return { macros: next, changed, retired };
395
399
  }
396
400
 
397
- /** Apply builtin seeding/upgrades, writing only when something changed. */
401
+ /**
402
+ * Pure. A 'project-home' macro is shown in every project, so any such entry
403
+ * whose `projects` is not exactly ['*'] comes back with ['*']. Every other
404
+ * field — notably `updatedAt` — is left as is: ensureBuiltins reads
405
+ * `updatedAt !== createdAt` as a human edit and would freeze a built-in.
406
+ * Returns `{ macros, changed }`.
407
+ */
408
+ function widenProjectHomeScope(macros) {
409
+ let changed = false;
410
+ const next = macros.map((m) => {
411
+ if (m.surface !== 'project-home') return m;
412
+ if (m.projects.length === 1 && m.projects[0] === ALL_PROJECTS) return m;
413
+ changed = true;
414
+ return { ...m, projects: [ALL_PROJECTS] };
415
+ });
416
+ return { macros: changed ? next : macros, changed };
417
+ }
418
+
419
+ /** Apply project-home widening + builtin seeding/upgrades, writing only when something changed. */
398
420
  async function applyBuiltins(filePath, macros, opts) {
399
421
  const builtins = resolveBuiltins(opts);
400
- const { macros: next, changed, retired } = ensureBuiltins(macros, builtins);
401
- if (!changed) return { macros, failed: false };
422
+ const widened = widenProjectHomeScope(macros);
423
+ const { macros: next, changed: builtinsChanged, retired } = ensureBuiltins(widened.macros, builtins);
424
+ if (!builtinsChanged && !widened.changed) return { macros, failed: false };
402
425
  try {
403
426
  await writeStore(filePath, next);
404
427
  } catch (err) {
405
- console.warn('[macroLibrary] could not persist built-in macro seeding:', err && err.message);
406
- return { macros, failed: false };
428
+ console.warn('[macroLibrary] could not persist built-in macro seeding / project-home widening:', err && err.message);
429
+ return { macros: widened.macros, failed: false };
407
430
  }
408
431
  for (const id of retired) {
409
432
  const by = (builtins || []).find((b) => Array.isArray(b.supersedes) && b.supersedes.includes(id));
@@ -528,7 +551,7 @@ async function listMacrosRaw(opts) {
528
551
  const first = await readStore(filePath);
529
552
  if (first.state === 'ok') {
530
553
  const { changed } = ensureBuiltins(first.macros, resolveBuiltins(opts));
531
- if (!changed) return first.macros;
554
+ if (!changed && !widenProjectHomeScope(first.macros).changed) return first.macros;
532
555
  }
533
556
  // Missing/corrupt/needs-seeding: repair inside the write chain so racing callers don't double-seed.
534
557
  return serialize(async () => (await loadStore(filePath, opts)).macros);
@@ -566,7 +589,10 @@ async function saveMacro(input, opts = {}) {
566
589
  if (macros[idx].builtin && parsed.surface !== undefined && parsed.surface !== macros[idx].surface) {
567
590
  throw new Error('built-in macro surface cannot be changed');
568
591
  }
569
- const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : macros[idx].projects;
592
+ const surface = parsed.surface ?? macros[idx].surface;
593
+ const projects = surface === 'project-home'
594
+ ? [ALL_PROJECTS]
595
+ : parsed.projects !== undefined ? normalizeProjects(parsed.projects) : macros[idx].projects;
570
596
  saved = {
571
597
  ...macros[idx],
572
598
  label: parsed.label,
@@ -574,7 +600,7 @@ async function saveMacro(input, opts = {}) {
574
600
  tag: parsed.tag,
575
601
  prompt: parsed.prompt,
576
602
  projects,
577
- surface: parsed.surface ?? macros[idx].surface,
603
+ surface,
578
604
  updatedAt: now,
579
605
  };
580
606
  if (parsed.inputs === undefined) {
@@ -594,7 +620,10 @@ async function saveMacro(input, opts = {}) {
594
620
  assertPlaceholdersDeclared(saved);
595
621
  macros[idx] = saved;
596
622
  } else {
597
- const projects = parsed.projects !== undefined ? normalizeProjects(parsed.projects) : [];
623
+ const surface = parsed.surface ?? 'sessions';
624
+ const projects = surface === 'project-home'
625
+ ? [ALL_PROJECTS]
626
+ : parsed.projects !== undefined ? normalizeProjects(parsed.projects) : [];
598
627
  saved = {
599
628
  id: newId(parsed.label, new Set(macros.map((m) => m.id))),
600
629
  label: parsed.label,
@@ -602,7 +631,7 @@ async function saveMacro(input, opts = {}) {
602
631
  tag: parsed.tag,
603
632
  prompt: parsed.prompt,
604
633
  projects,
605
- surface: parsed.surface ?? 'sessions',
634
+ surface,
606
635
  createdAt: now,
607
636
  updatedAt: now,
608
637
  };
@@ -718,4 +747,5 @@ module.exports = {
718
747
  removeMacroFromProject,
719
748
  defaultFilePath,
720
749
  ensureBuiltins,
750
+ widenProjectHomeScope,
721
751
  };
@@ -32,7 +32,7 @@ const { resolveDepSlug, findNearMatches } = require('./depSlugResolve.cjs');
32
32
  const { resolveEpicPrdWriteDir } = require('./prdLocations.cjs');
33
33
  const { isFixPlanSlug } = require('../scheduler/fixPlanSlug.cjs');
34
34
  const { isIncomplete, resolveChainTerminals, isValidPlanId, mintPlanId, resolveInheritedPlanId } = require('./prdDisposition.cjs');
35
- const { splitFrontmatter } = require('./prdFrontmatter.cjs');
35
+ const { splitFrontmatter, PRD_EFFORT_LEVELS } = require('./prdFrontmatter.cjs');
36
36
  const { sizingWarnings } = require('./prdSizing.cjs');
37
37
  const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
38
38
  const { execGit } = require('../git/gitExec.cjs');
@@ -89,7 +89,7 @@ function isValidMacroId(id) {
89
89
  function buildPrdBody(input) {
90
90
  const {
91
91
  title, cwd, estimateMinutes, goal, acceptanceCriteria,
92
- implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId,
92
+ implementationNotes, outOfScope, sourcePromptId, sourceTabId, tag, agentType, dependsOn, quietMachine, disposition, deliverable, artifactPaths, planId, macroId, effort,
93
93
  gate, files, budgetExempt,
94
94
  } = input;
95
95
 
@@ -143,6 +143,7 @@ function buildPrdBody(input) {
143
143
  // sibling jobs would otherwise invalidate. Only emitted when true — see
144
144
  // prdFrontmatter.cjs's applyKey for the matching "only true opts in" parse.
145
145
  if (isValidMacroId(macroId)) fmLines.push(`macroId: ${macroId}`);
146
+ if (PRD_EFFORT_LEVELS.includes(effort)) fmLines.push(`effort: ${effort}`);
146
147
  if (quietMachine === true) fmLines.push('quietMachine: true');
147
148
  // Budget exemption is for a sweep validator that cannot be split further;
148
149
  // every other caller's budgetExempt is ignored.
@@ -429,6 +430,10 @@ async function createPrdInner(input, remote, ctl, opts = {}) {
429
430
  if (input.macroId != null && !isValidMacroId(input.macroId)) {
430
431
  return { ok: false, applied: false, status: 400, error: 'macroId must match /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/ when given' };
431
432
  }
433
+ // effort (in-process callers only: macroJobDispatch.cjs)
434
+ if (input.effort != null && !PRD_EFFORT_LEVELS.includes(input.effort)) {
435
+ return { ok: false, applied: false, status: 400, error: 'effort must be one of low, medium, high, xhigh, max when given' };
436
+ }
432
437
 
433
438
  // Fake-heading guard (gate-and-files-in-PRD-body unit): a caller-supplied
434
439
  // free-text field that itself contains a "# Gate" or "# Files" heading line
@@ -77,8 +77,11 @@ function splitFrontmatter(raw) {
77
77
  * never emitted, which is how `scheduler_update_prd` clears a dependency.
78
78
  */
79
79
 
80
- const RECOGNIZED_KEYS = new Set(['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId']);
81
- const EMIT_ORDER = ['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId'];
80
+ const RECOGNIZED_KEYS = new Set(['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort']);
81
+ const EMIT_ORDER = ['title', 'cwd', 'estimateMinutes', 'parallelGroup', 'sourcePromptId', 'sourceTabId', 'tag', 'agentType', 'createdVia', 'issuedAt', 'dependsOn', 'quietMachine', 'disposition', 'planId', 'deliverable', 'artifactPaths', 'macroId', 'effort'];
82
+ // Mirrors modelCatalog.cjs CATALOG_FLOOR.effortLevels. A closed set so the
83
+ // value is always safe as a frontmatter line and as a --effort argv token.
84
+ const PRD_EFFORT_LEVELS = Object.freeze(['low', 'medium', 'high', 'xhigh', 'max']);
82
85
  const MACRO_ID_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
83
86
  const FRONTMATTER_RE = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
84
87
 
@@ -199,6 +202,10 @@ function applyKey(fm, key, after) {
199
202
  // Id of the macro whose press dispatched this PRD; anything off-pattern is dropped.
200
203
  if (typeof v === 'string' && MACRO_ID_RE.test(v.trim())) fm.macroId = v.trim();
201
204
  return;
205
+ case 'effort':
206
+ // In-process-only per-PRD effort override; anything outside PRD_EFFORT_LEVELS is dropped.
207
+ if (typeof v === 'string' && PRD_EFFORT_LEVELS.includes(v.trim())) fm.effort = v.trim();
208
+ return;
202
209
  case 'artifactPaths': {
203
210
  // Inline `[a, b]` list, same shape as dependsOn.
204
211
  const list = parseInlineList(after);
@@ -315,4 +322,4 @@ function serializePrdFile(fm, body) {
315
322
  return `---\n${fmText}\n---\n${body}`;
316
323
  }
317
324
 
318
- module.exports = { splitFrontmatter, parsePrdFile, serializePrdFile, RECOGNIZED_KEYS };
325
+ module.exports = { splitFrontmatter, parsePrdFile, serializePrdFile, RECOGNIZED_KEYS, PRD_EFFORT_LEVELS };
@@ -97,6 +97,12 @@ const PromptSessionSchema = z.object({
97
97
  // false = started with the develop loop (/develop skill, delegation guard, PRD queueing) switched off;
98
98
  // fixed for the life of its session; absent = on; only false is ever written.
99
99
  developLoop: z.boolean().optional(),
100
+ // The agent CLI that runs this Epic's session; absent = Claude Code. Fixed for the life of the
101
+ // session. Deliberately a bounded string, not an enum: a row written by a newer build naming a CLI
102
+ // this build doesn't know must never be dropped by dropInvalidSessions (ipcSchemas.cjs).
103
+ agentCli: z.string().max(32).optional(),
104
+ // Optional model string passed to that CLI; absent = the CLI's own default.
105
+ agentCliModel: z.string().max(128).optional(),
100
106
  // true = this Epic adopted an existing CLI session as its claudeSessionId
101
107
  // (ensureEpic's restoreSessionId) instead of a fresh one; absent otherwise.
102
108
  // Only true is ever written: a false would fail here, and dropInvalidSessions
@@ -6,6 +6,7 @@
6
6
  // Top-level (no domain fits: epic/ transcripts are path-only; util/ is domain-free).
7
7
  // Transcripts reach hundreds of MB, so cost is O(maxBytes), never O(file).
8
8
 
9
+ const fs = require('node:fs');
9
10
  const fsp = require('node:fs/promises');
10
11
 
11
12
  const DEFAULT_LIMIT = 30;
@@ -58,12 +59,30 @@ function toChatMessage(line) {
58
59
  }
59
60
 
60
61
  /**
61
- * @param {string} filePath
62
- * @param {{ limit?: number, maxBytes?: number }} [opts]
62
+ * Agent-CLI (non-Claude) Epics write a Claude-compatible transcript under
63
+ * agentCliSessionStore instead of ~/.claude/projects.
64
+ * @param {unknown} claudeSessionId
65
+ * @returns {string|null} that file's path when it exists; null otherwise,
66
+ * including for a non-UUID id (the store's validation error is swallowed).
67
+ */
68
+ function agentCliTranscriptPath(claudeSessionId) {
69
+ if (typeof claudeSessionId !== 'string' || !claudeSessionId) return null;
70
+ try {
71
+ const p = require('./agent-cli/agentCliSessionStore.cjs').transcriptPathFor(claudeSessionId);
72
+ return fs.existsSync(p) ? p : null;
73
+ } catch {
74
+ return null;
75
+ }
76
+ }
77
+
78
+ /**
79
+ * @param {string} filePath the Claude transcript path (used when no agent-CLI file exists)
80
+ * @param {{ limit?: number, maxBytes?: number, claudeSessionId?: string }} [opts]
63
81
  * @returns {Promise<Array<{ role: 'user'|'assistant', text: string, ts: string|null, uuid: string|null }>>}
64
82
  * oldest first; [] on any read failure.
65
83
  */
66
- async function readRecentChatMessages(filePath, { limit = DEFAULT_LIMIT, maxBytes = DEFAULT_MAX_BYTES } = {}) {
84
+ async function readRecentChatMessages(filePath, { limit = DEFAULT_LIMIT, maxBytes = DEFAULT_MAX_BYTES, claudeSessionId } = {}) {
85
+ filePath = agentCliTranscriptPath(claudeSessionId) ?? filePath;
67
86
  if (typeof filePath !== 'string' || !filePath) return [];
68
87
  const n = Math.floor(Number(limit));
69
88
  const lim = Number.isFinite(n) ? Math.min(MAX_LIMIT, Math.max(1, n)) : DEFAULT_LIMIT;
@@ -154,4 +173,4 @@ function buildRemoteConversation({ exchanges = [], tail = [], limit = 10, before
154
173
  return { messages: [...history, ...live], hasMore, nextBefore: hasMore ? b + returned : null };
155
174
  }
156
175
 
157
- module.exports = { readRecentChatMessages, buildRemoteConversation };
176
+ module.exports = { readRecentChatMessages, buildRemoteConversation, agentCliTranscriptPath };