claude-code-session-manager 0.137.0 → 0.139.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 (101) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +339 -82
  3. package/dist/assets/{AppSettings-l7NTc0yu.js → AppSettings-CUfWY9vN.js} +2 -2
  4. package/dist/assets/History-DDnqaLyw.js +2 -0
  5. package/dist/assets/HomeClaudeConfig-CGD2Onjv.js +3 -0
  6. package/dist/assets/{Panel-BuInRmA0.js → Panel-Csyd9HbD.js} +1 -1
  7. package/dist/assets/ProjectClaudeConfig-C-jlYpC_.js +26 -0
  8. package/dist/assets/{Scheduler-B7sn2mUw.js → Scheduler-NLs08fx7.js} +9 -9
  9. package/dist/assets/{SkillReferenceGraph-DwV0Ueyc.js → SkillReferenceGraph-DcscPXAG.js} +1 -1
  10. package/dist/assets/Skills-BpGRKOcY.js +67 -0
  11. package/dist/assets/{TiptapBody-Bl8hDhhS.js → TiptapBody-DSU3769X.js} +60 -54
  12. package/dist/assets/ViewTabs-C0PRZx4_.js +1 -0
  13. package/dist/assets/{VoiceButton-DJx-jY4r.js → VoiceButton-D2rMurNg.js} +1 -1
  14. package/dist/assets/{historyTotals-Cgjm5q24.js → historyTotals-TcIQs2sh.js} +1 -1
  15. package/dist/assets/{index-62tyjEQB.css → index-BCySPdtU.css} +1 -1
  16. package/dist/assets/index-C-d0DCre.js +3124 -0
  17. package/dist/index.html +2 -2
  18. package/dist-web/app.css +1 -1
  19. package/dist-web/app.js +471 -452
  20. package/package.json +13 -5
  21. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  22. package/plugins/session-manager-dev/skills/builder/SKILL.md +12 -4
  23. package/plugins/session-manager-dev/skills/builder/scripts/publish-preflight.cjs +255 -0
  24. package/plugins/session-manager-dev/skills/develop/SKILL.md +12 -5
  25. package/scripts/README.md +1 -0
  26. package/scripts/scheduler-mcp-server.cjs +161 -18
  27. package/src/main/build-info.json +4 -4
  28. package/src/main/chatRunner.cjs +53 -2
  29. package/src/main/exchanges.cjs +70 -5
  30. package/src/main/historyAggregator.cjs +84 -58
  31. package/src/main/historyDashboard.cjs +18 -13
  32. package/src/main/index.cjs +35 -9
  33. package/src/main/ipcSchemas.cjs +133 -5
  34. package/src/main/lib/claude/effectiveModelInfo.cjs +2 -2
  35. package/src/main/lib/claude/modelPricing.cjs +148 -0
  36. package/src/main/lib/demo-video-kit/checks.cjs +16 -0
  37. package/src/main/lib/epic/epicAdminRoutes.cjs +101 -0
  38. package/src/main/lib/epic/epicAttachments.cjs +143 -0
  39. package/src/main/lib/epic/epicJobReceipt.cjs +87 -0
  40. package/src/main/lib/epic/epicMint.cjs +4 -0
  41. package/src/main/lib/epic/epicOutsideRead.cjs +306 -0
  42. package/src/main/lib/epic/epicOutsideState.cjs +233 -0
  43. package/src/main/lib/epic/epicSettle.cjs +1 -1
  44. package/src/main/lib/epic/epicStateWatcher.cjs +157 -0
  45. package/src/main/lib/epic/externalRef.cjs +37 -0
  46. package/src/main/lib/epic/externalRefIndex.cjs +136 -0
  47. package/src/main/lib/epic/restorableSessions.cjs +151 -17
  48. package/src/main/lib/epic/transcriptUsage.cjs +197 -0
  49. package/src/main/lib/externalContract.cjs +111 -0
  50. package/src/main/lib/feedback-remote/crossProjectFeedback.cjs +121 -4
  51. package/src/main/lib/feedback-remote/crossProjectReply.cjs +83 -1
  52. package/src/main/lib/feedback-remote/customerFeedbackAdminRoutes.cjs +16 -6
  53. package/src/main/lib/feedback-remote/customerFeedbackClient.cjs +50 -8
  54. package/src/main/lib/feedback-remote/customerFeedbackInbox.cjs +218 -4
  55. package/src/main/lib/feedback-remote/customerFeedbackIpc.cjs +19 -3
  56. package/src/main/lib/feedback-remote/feedbackImages.cjs +171 -0
  57. package/src/main/lib/feedback-remote/localAdminHttp.cjs +11 -10
  58. package/src/main/lib/feedback-remote/macroAdminRoutes.cjs +287 -1
  59. package/src/main/lib/feedback-remote/needsYouAdminRoutes.cjs +133 -0
  60. package/src/main/lib/feedback-remote/needsYouIpc.cjs +50 -0
  61. package/src/main/lib/feedback-remote/needsYouStore.cjs +281 -0
  62. package/src/main/lib/feedback-remote/remoteFrameAssembler.cjs +113 -0
  63. package/src/main/lib/historyRollup.cjs +32 -5
  64. package/src/main/lib/mcpToolCatalog.cjs +111 -14
  65. package/src/main/lib/persona-macro/agentAdminRoutes.cjs +121 -0
  66. package/src/main/lib/persona-macro/macroLibrary.cjs +7 -0
  67. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +11 -0
  68. package/src/main/lib/process/bootStdioGuard.cjs +32 -0
  69. package/src/main/lib/process/stdioGuard.cjs +115 -0
  70. package/src/main/lib/promptSessionSchema.cjs +4 -0
  71. package/src/main/lib/remoteTranscriptTail.cjs +32 -1
  72. package/src/main/lib/scheduler/schedulerPaths.cjs +9 -0
  73. package/src/main/lib/telemetry/auditEvents.cjs +176 -0
  74. package/src/main/lib/telemetry/eventsAdminRoutes.cjs +45 -0
  75. package/src/main/loopEfficiencyHandlers.cjs +1 -1
  76. package/src/main/scheduler.cjs +29 -0
  77. package/src/main/templates/PRD_AUTHORING.md +1 -0
  78. package/src/main/transcripts.cjs +62 -7
  79. package/src/main/webRemote.cjs +122 -18
  80. package/src/preload/api.d.ts +98 -9
  81. package/src/preload/apiSurface.cjs +7 -0
  82. package/src/preload/apiSurface.json +415 -83
  83. package/src/preload/index.cjs +17 -3
  84. package/src/seed/agents/demo-video-builder.md +10 -7
  85. package/dist/assets/AgentLibrary-DV0DTZDC.js +0 -2
  86. package/dist/assets/Button-Cmfkgjfa.js +0 -1
  87. package/dist/assets/DocumentEditorPane-MTljV-Uw.js +0 -1
  88. package/dist/assets/Extensions-Cc1Q_8id.js +0 -2
  89. package/dist/assets/History-CFo-1DHo.js +0 -2
  90. package/dist/assets/Library-C_ibFiOx.js +0 -32
  91. package/dist/assets/ListDetail-ByULG209.js +0 -1
  92. package/dist/assets/ProjectClaudeConfig-yqqVtHY7.js +0 -25
  93. package/dist/assets/ProvenanceBadge-CJvnQReI.js +0 -1
  94. package/dist/assets/Settings-DRRSJksU.js +0 -2
  95. package/dist/assets/Skills-DVYHA9gV.js +0 -29
  96. package/dist/assets/SourceChip-DfJ5_5rV.js +0 -1
  97. package/dist/assets/SystemPrompt-f11wGllK.js +0 -1
  98. package/dist/assets/Toggle-DaxeFDFp.js +0 -1
  99. package/dist/assets/ViewTabs-DRtgFKRw.js +0 -1
  100. package/dist/assets/claude-settings-schema-COigsajx.js +0 -3
  101. package/dist/assets/index-iQ6pdyuS.js +0 -3116
@@ -0,0 +1,143 @@
1
+ 'use strict';
2
+ // @ts-check
3
+
4
+ /**
5
+ * epicAttachments.cjs — validate + save base64 images sent from the phone
6
+ * remote into the same dir the desktop Epic composer uses
7
+ * (<project>/session-manager-operations/prompt-sessions/attachments/), and
8
+ * compose the prompt with the same `Attached: <abs path>` lines
9
+ * (EpicComposer.tsx) so Claude reads them with its Read tool.
10
+ *
11
+ * Writes go through config.cjs writeBinaryAtomic under writer 'epics'
12
+ * (single-writer law). config.cjs is required lazily — it pulls Electron.
13
+ */
14
+
15
+ const path = require('node:path');
16
+ const crypto = require('node:crypto');
17
+ const fsp = require('node:fs/promises');
18
+ const { opsPath } = require('../opsOwnership.cjs');
19
+
20
+ const ATTACHMENT_MIMES = Object.freeze({
21
+ 'image/png': '.png',
22
+ 'image/jpeg': '.jpg',
23
+ 'image/gif': '.gif',
24
+ 'image/webp': '.webp',
25
+ });
26
+ const MAX_IMAGES = 6;
27
+ const MAX_IMAGE_BYTES = 3 * 1024 * 1024;
28
+ const MAX_TOTAL_BYTES = 12 * 1024 * 1024;
29
+ const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
30
+
31
+ /** sniffImageMime(buf) → one of ATTACHMENT_MIMES' keys, or null. */
32
+ function sniffImageMime(buf) {
33
+ if (!Buffer.isBuffer(buf)) return null;
34
+ if (buf.length >= 8 && buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47
35
+ && buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return 'image/png';
36
+ if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return 'image/jpeg';
37
+ if (buf.length >= 6) {
38
+ const sig = buf.subarray(0, 6).toString('latin1');
39
+ if (sig === 'GIF87a' || sig === 'GIF89a') return 'image/gif';
40
+ }
41
+ if (buf.length >= 12 && buf.subarray(0, 4).toString('latin1') === 'RIFF'
42
+ && buf.subarray(8, 12).toString('latin1') === 'WEBP') return 'image/webp';
43
+ return null;
44
+ }
45
+
46
+ /** safeAttachmentName(name, mime) → sanitized basename with the mime's extension. */
47
+ function safeAttachmentName(name, mime) {
48
+ const ext = ATTACHMENT_MIMES[mime] || '';
49
+ let base = typeof name === 'string' ? name : '';
50
+ base = base.split(/[\\/]/).pop() || '';
51
+ const dot = base.lastIndexOf('.');
52
+ if (dot > 0) base = base.slice(0, dot);
53
+ else if (dot === 0) base = base.slice(1);
54
+ base = base.replace(/[^A-Za-z0-9._-]/g, '-').slice(0, 60);
55
+ if (!base || /^[.-]+$/.test(base)) base = 'image';
56
+ return `${base}${ext}`;
57
+ }
58
+
59
+ function attachmentsDir(projectCwd) {
60
+ return opsPath(projectCwd, 'prompt-sessions', 'attachments');
61
+ }
62
+
63
+ /**
64
+ * saveChatImages({ projectCwd, images }, deps?) →
65
+ * { ok: true, paths, names } | { ok: false, reason }
66
+ * images: [{ name, mime, data (base64) }]. Validates all before writing any.
67
+ */
68
+ async function saveChatImages({ projectCwd, images }, deps = {}) {
69
+ const list = Array.isArray(images) ? images : [];
70
+ if (list.length > MAX_IMAGES) return { ok: false, reason: 'too-many' };
71
+ const decoded = [];
72
+ let total = 0;
73
+ for (const img of list) {
74
+ if (!img || typeof img !== 'object') return { ok: false, reason: 'bad-data' };
75
+ const { name, mime, data } = img;
76
+ if (typeof mime !== 'string' || !Object.prototype.hasOwnProperty.call(ATTACHMENT_MIMES, mime)) {
77
+ return { ok: false, reason: 'bad-type' };
78
+ }
79
+ if (typeof data !== 'string' || data.length === 0 || data.length % 4 !== 0 || !BASE64_RE.test(data)) {
80
+ return { ok: false, reason: 'bad-data' };
81
+ }
82
+ // Cheap pre-decode size bound so a huge payload is refused before allocation.
83
+ if (Math.floor((data.length * 3) / 4) - 2 > MAX_IMAGE_BYTES) return { ok: false, reason: 'too-large' };
84
+ const buf = Buffer.from(data, 'base64');
85
+ if (buf.length === 0) return { ok: false, reason: 'bad-data' };
86
+ if (buf.length > MAX_IMAGE_BYTES) return { ok: false, reason: 'too-large' };
87
+ total += buf.length;
88
+ if (total > MAX_TOTAL_BYTES) return { ok: false, reason: 'too-large' };
89
+ if (sniffImageMime(buf) !== mime) return { ok: false, reason: 'bad-type' };
90
+ decoded.push({ buf, fileName: `${crypto.randomUUID().slice(0, 8)}-${safeAttachmentName(name, mime)}` });
91
+ }
92
+
93
+ const writeBinary = deps.writeBinary || require('../../config.cjs').writeBinaryAtomic;
94
+ const paths = [];
95
+ try {
96
+ const dir = attachmentsDir(projectCwd);
97
+ for (const { buf, fileName } of decoded) {
98
+ const dest = path.join(dir, fileName);
99
+ await writeBinary(dest, buf, { writer: 'epics' });
100
+ paths.push(dest);
101
+ }
102
+ } catch {
103
+ await removeSavedAttachments(projectCwd, paths, deps);
104
+ return { ok: false, reason: 'write-failed' };
105
+ }
106
+ return { ok: true, paths, names: paths.map((p) => path.basename(p)) };
107
+ }
108
+
109
+ /** composeAttachedPrompt(text, paths) — identical to EpicComposer.tsx. */
110
+ function composeAttachedPrompt(text, paths) {
111
+ const trimmed = typeof text === 'string' ? text.trim() : '';
112
+ const list = Array.isArray(paths) ? paths : [];
113
+ if (!list.length) return trimmed;
114
+ const lines = list.map((p) => `Attached: ${p}`).join('\n');
115
+ return trimmed ? `${trimmed}\n\n${lines}` : lines;
116
+ }
117
+
118
+ /** removeSavedAttachments(projectCwd, paths, deps?) — unlinks only files inside
119
+ * the project's attachments dir; never throws. */
120
+ async function removeSavedAttachments(projectCwd, paths, deps = {}) {
121
+ const unlink = deps.unlink || fsp.unlink;
122
+ let dir;
123
+ try { dir = attachmentsDir(projectCwd); } catch { return; }
124
+ const prefix = dir + path.sep;
125
+ for (const p of Array.isArray(paths) ? paths : []) {
126
+ if (typeof p !== 'string') continue;
127
+ const abs = path.resolve(p);
128
+ if (!abs.startsWith(prefix)) continue;
129
+ try { await unlink(abs); } catch { /* already gone */ }
130
+ }
131
+ }
132
+
133
+ module.exports = {
134
+ ATTACHMENT_MIMES,
135
+ MAX_IMAGES,
136
+ MAX_IMAGE_BYTES,
137
+ MAX_TOTAL_BYTES,
138
+ sniffImageMime,
139
+ safeAttachmentName,
140
+ saveChatImages,
141
+ composeAttachedPrompt,
142
+ removeSavedAttachments,
143
+ };
@@ -0,0 +1,87 @@
1
+ /**
2
+ * epicJobReceipt.cjs — sums the scheduler run metadata (`<runId>/<slug>.meta.json`)
3
+ * of one Epic's PRDs, every attempt included, into a cost/usage receipt.
4
+ *
5
+ * Complexity: one listing per run dir since sinceMs; only wanted meta files that exist are
6
+ * opened. Never rejects: a missing runs dir, unreadable run dir or malformed meta file is skipped.
7
+ */
8
+
9
+ 'use strict';
10
+
11
+ const fsp = require('node:fs/promises');
12
+ const path = require('node:path');
13
+ const { runIdToMs } = require('../../loopEfficiencyHandlers.cjs');
14
+
15
+ const META_SUFFIX = '.meta.json';
16
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : 0);
17
+
18
+ async function readJson(p) {
19
+ try { return JSON.parse(await fsp.readFile(p, 'utf8')); } catch { return null; }
20
+ }
21
+
22
+ /**
23
+ * @param {{ cwd: string, slugs: string[], sinceMs?: number, runsRoot?: string }} opts
24
+ * @returns {Promise<{ runs: number, costUsd: number, costKnownRuns: number, outputTokens: number,
25
+ * numTurns: number, durationMs: number,
26
+ * byPrd: Array<{ slug: string, runs: number, costUsd: number, lastExitCode: number|null, lastFinishedAt: number|null }> }>}
27
+ */
28
+ async function gatherEpicJobReceipt({ cwd, slugs, sinceMs, runsRoot } = /** @type {any} */ ({})) {
29
+ const out = { runs: 0, costUsd: 0, costKnownRuns: 0, outputTokens: 0, numTurns: 0, durationMs: 0, byPrd: [] };
30
+ try {
31
+ const root = runsRoot || require('../scheduler/schedulerPaths.cjs').runsDir();
32
+ const since = typeof sinceMs === 'number' && Number.isFinite(sinceMs) ? sinceMs : -Infinity;
33
+ // Slugs name files inside a run dir — reject anything that could escape it.
34
+ const wanted = new Set((Array.isArray(slugs) ? slugs : [])
35
+ .filter((s) => typeof s === 'string' && s && !s.includes('/') && !s.includes('\\') && s !== '.' && s !== '..'));
36
+ /** @type {Map<string, { slug: string, runs: number, costUsd: number, lastExitCode: number|null, lastFinishedAt: number|null, lastAt: number }>} */
37
+ const per = new Map();
38
+
39
+ let dirs = [];
40
+ try { dirs = await fsp.readdir(root); } catch { /* no runs dir */ }
41
+
42
+ for (const runId of dirs) {
43
+ const t = runIdToMs(runId);
44
+ if (!Number.isFinite(t) || t < since) continue;
45
+ const runDir = path.join(root, runId);
46
+ let files;
47
+ try { files = await fsp.readdir(runDir); } catch { continue; }
48
+ for (const f of files) {
49
+ if (!f.endsWith(META_SUFFIX)) continue;
50
+ // Slug comes from the filename and must be in the guarded wanted set.
51
+ const slug = f.slice(0, -META_SUFFIX.length);
52
+ if (!wanted.has(slug)) continue;
53
+ const meta = await readJson(path.join(runDir, f));
54
+ if (!meta || typeof meta !== 'object' || meta.cwd !== cwd) continue;
55
+ let row = per.get(slug);
56
+ if (!row) {
57
+ row = { slug, runs: 0, costUsd: 0, lastExitCode: null, lastFinishedAt: null, lastAt: -Infinity };
58
+ per.set(slug, row);
59
+ }
60
+ out.runs += 1;
61
+ row.runs += 1;
62
+ if (typeof meta.totalCostUsd === 'number' && Number.isFinite(meta.totalCostUsd)) {
63
+ out.costUsd += meta.totalCostUsd;
64
+ out.costKnownRuns += 1;
65
+ row.costUsd += meta.totalCostUsd;
66
+ }
67
+ out.outputTokens += num(meta.outputTokens);
68
+ out.numTurns += num(meta.numTurns);
69
+ out.durationMs += num(meta.durationMs);
70
+ const finishedAt = typeof meta.finishedAt === 'number' ? meta.finishedAt : null;
71
+ const at = finishedAt != null ? finishedAt : t;
72
+ if (at >= row.lastAt) {
73
+ row.lastAt = at;
74
+ row.lastExitCode = typeof meta.exitCode === 'number' ? meta.exitCode : null;
75
+ row.lastFinishedAt = finishedAt;
76
+ }
77
+ }
78
+ }
79
+
80
+ out.byPrd = [...per.values()]
81
+ .sort((a, b) => (a.slug < b.slug ? -1 : a.slug > b.slug ? 1 : 0))
82
+ .map(({ slug, runs, costUsd, lastExitCode, lastFinishedAt }) => ({ slug, runs, costUsd, lastExitCode, lastFinishedAt }));
83
+ } catch { /* never reject — return what was gathered */ }
84
+ return out;
85
+ }
86
+
87
+ module.exports = { gatherEpicJobReceipt };
@@ -15,6 +15,10 @@
15
15
  * caller is join-only and throws rather than conjuring an Epic. Agents that
16
16
  * are sure work is needed run /develop inside the Epic they are already in;
17
17
  * agents that are not sure say so and let the human open an Epic.
18
+ * A script start of a macro a human marked 'Can be started by a script'
19
+ * (POST /admin/macros/run) reaches this mint through the renderer's New Epic
20
+ * UI path (the same IPC handler as a press) and adds no mint authority —
21
+ * MINT_AUTHORITIES stays two.
18
22
  *
19
23
  * The Epic registry is the renderer's own store: the per-cwd
20
24
  * `session-manager-operations/prompt-sessions/active-index.json`
@@ -0,0 +1,306 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * epicOutsideRead.cjs — the record an outside app reads for one Epic.
5
+ *
6
+ * Joins the project's active index (or, for a completed Epic, its archive
7
+ * file), the scheduler job rows, the awaiting-input reader and
8
+ * computeEpicOutsideState into one plain record. Read-only; every read is
9
+ * guarded so a broken file yields null or an empty list, and nothing throws.
10
+ *
11
+ * Scheduler + chat liveness come in as injected functions (listJobs,
12
+ * isTabBusy) with safe defaults (no jobs, never busy) so this module needs no
13
+ * running scheduler. Open-Epic reads (active index) skip the registration
14
+ * check: it enumerates ~/.claude/projects (11k+ dirs, ~21 s cold). Only the
15
+ * archive path checks it, because readArchived requires a registered project,
16
+ * so a completed Epic in an unregistered project reads as nothing.
17
+ */
18
+
19
+ const path = require('node:path');
20
+ const { readActiveIndex } = require('./epicMint.cjs');
21
+ const { computeEpicOutsideState, knownPrdSlugs } = require('./epicOutsideState.cjs');
22
+ const { findEpicByExternalRef } = require('./externalRefIndex.cjs');
23
+ const { awaitingInputSessions } = require('../../exchanges.cjs');
24
+ const { readArchived, defaultProjectRoots, makeRegisteredRootsCache } = require('../../promptSessionsIpc.cjs');
25
+ const { gatherEpicJobReceipt } = require('./epicJobReceipt.cjs');
26
+ const { summarizeTranscriptFile } = require('./transcriptUsage.cjs');
27
+ const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
28
+
29
+ const DEFAULT_LIMIT = 50;
30
+ const MAX_LIMIT = 200;
31
+ const OPEN_STATUSES = new Set(['proposed', 'active']);
32
+
33
+ const isObj = (v) => v != null && typeof v === 'object' && !Array.isArray(v);
34
+ const str = (v) => (typeof v === 'string' && v !== '' ? v : null);
35
+ const norm = (p) => path.resolve(String(p)).replace(/[\\/]+$/, '');
36
+
37
+ let defaultRootsCache = null;
38
+
39
+ /** Same rule as promptSessionsIpc's assertRegistered, but answers a boolean. */
40
+ function isRegistered(cwd, projectRoots) {
41
+ try {
42
+ if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return false;
43
+ const { projectRootOf } = require('../activeSessions.cjs');
44
+ const want = norm(projectRootOf(cwd) || cwd);
45
+ if (projectRoots === defaultProjectRoots) {
46
+ if (!defaultRootsCache) defaultRootsCache = makeRegisteredRootsCache(defaultProjectRoots);
47
+ return defaultRootsCache.has(want);
48
+ }
49
+ for (const r of projectRoots() || []) {
50
+ if (typeof r !== 'string' || !r) continue;
51
+ if (norm(r) === want || norm(projectRootOf(r) || r) === want) return true;
52
+ }
53
+ return false;
54
+ } catch {
55
+ return false;
56
+ }
57
+ }
58
+
59
+ async function loadJobs(listJobs) {
60
+ try {
61
+ const out = await listJobs();
62
+ if (Array.isArray(out)) return out;
63
+ if (isObj(out) && Array.isArray(out.jobs)) return out.jobs;
64
+ } catch { /* no jobs */ }
65
+ return [];
66
+ }
67
+
68
+ async function loadAwaiting(cwd) {
69
+ try {
70
+ const set = await awaitingInputSessions(cwd);
71
+ return set instanceof Set ? set : new Set();
72
+ } catch {
73
+ return new Set();
74
+ }
75
+ }
76
+
77
+ async function busy(isTabBusy, epicId) {
78
+ try {
79
+ return (await isTabBusy(epicId)) === true;
80
+ } catch {
81
+ return false;
82
+ }
83
+ }
84
+
85
+ /** goalText split at the first blank line → { title, goal }; absent parts are null. */
86
+ function splitGoal(goalText) {
87
+ if (typeof goalText !== 'string') return { title: null, goal: null };
88
+ const m = /\r?\n[ \t]*\r?\n/.exec(goalText);
89
+ const head = (m ? goalText.slice(0, m.index) : goalText).trim();
90
+ const tail = m ? goalText.slice(m.index + m[0].length).trim() : '';
91
+ return { title: head || null, goal: tail || null };
92
+ }
93
+
94
+ function buildRecord(cwd, epicId, session, events, jobs, needsInput, chatBusy) {
95
+ const computed = computeEpicOutsideState({ session: { ...session, id: epicId }, events, jobs, needsInput, chatBusy });
96
+ const source = isObj(session.source) ? session.source : {};
97
+ const { title, goal } = splitGoal(session.goalText);
98
+ return {
99
+ epicId,
100
+ cwd: str(session.cwd) || cwd,
101
+ title,
102
+ goal,
103
+ tag: str(session.tag),
104
+ agentType: str(session.agentType),
105
+ status: str(session.status),
106
+ state: computed.state,
107
+ blocked: computed.blocked,
108
+ prds: computed.prds,
109
+ verified: computed.verified,
110
+ refuted: computed.refuted,
111
+ unvalidated: computed.unvalidated,
112
+ externalRef: str(source.externalRef),
113
+ source: {
114
+ producer: str(source.producer),
115
+ fromCwd: str(source.fromCwd),
116
+ fromEpicId: str(source.fromEpicId),
117
+ macroId: str(source.macroId),
118
+ },
119
+ createdAt: str(session.createdAt),
120
+ completedAt: str(session.completedAt),
121
+ };
122
+ }
123
+
124
+ function eventsOf(index, epicId) {
125
+ const chain = isObj(index.events) ? index.events[epicId] : null;
126
+ return Array.isArray(chain) ? chain : [];
127
+ }
128
+
129
+ function openSession(index, epicId) {
130
+ const s = isObj(index.sessions) && Object.prototype.hasOwnProperty.call(index.sessions, epicId)
131
+ ? index.sessions[epicId]
132
+ : null;
133
+ return isObj(s) && OPEN_STATUSES.has(s.status) ? s : null;
134
+ }
135
+
136
+ async function openRecord(cwd, epicId, session, index, jobs, awaiting, isTabBusy) {
137
+ const claudeSessionId = str(session.claudeSessionId);
138
+ const needsInput = claudeSessionId != null && awaiting.has(claudeSessionId);
139
+ const chatBusy = await busy(isTabBusy, epicId);
140
+ return buildRecord(cwd, epicId, session, eventsOf(index, epicId), jobs, needsInput, chatBusy);
141
+ }
142
+
143
+ /** The archived (completed) session + its events, or null (also for an unregistered project). */
144
+ function archivedEntry(cwd, epicId, projectRoots) {
145
+ try {
146
+ if (!isRegistered(cwd, projectRoots)) return null;
147
+ const res = readArchived(cwd, epicId, { projectRoots });
148
+ const data = res && res.exists ? res.data : null;
149
+ if (!isObj(data) || !str(data.archivedAt) || !isObj(data.session)) return null;
150
+ return {
151
+ session: { ...data.session, status: 'completed' },
152
+ events: Array.isArray(data.events) ? data.events : [],
153
+ };
154
+ } catch {
155
+ return null;
156
+ }
157
+ }
158
+
159
+ /**
160
+ * Job-run cost for every PRD the Epic is known to have (live rows + check-ins
161
+ * on its chain, so finished PRDs whose rows are gone still count) since the
162
+ * session was created; null on failure.
163
+ */
164
+ async function jobsReceipt(cwd, epicId, session, events, jobs, runsRoot) {
165
+ try {
166
+ const slugs = knownPrdSlugs({ session: { ...session, id: epicId }, events, jobs });
167
+ const created = Date.parse(session.createdAt);
168
+ return await gatherEpicJobReceipt({
169
+ cwd,
170
+ slugs,
171
+ sinceMs: Number.isFinite(created) ? created : undefined,
172
+ runsRoot,
173
+ });
174
+ } catch {
175
+ return null;
176
+ }
177
+ }
178
+
179
+ /** Token usage of the Epic's chat transcript; null when no file is found or on failure. */
180
+ async function chatReceipt(cwd, session, resolveTranscriptPath) {
181
+ try {
182
+ const claudeSessionId = str(session.claudeSessionId);
183
+ if (!claudeSessionId) return null;
184
+ const hit = resolveTranscriptPath({ cwd, claudeSessionId });
185
+ // The real resolver hands back its first candidate even when nothing exists.
186
+ if (!isObj(hit) || !str(hit.path) || hit.existsAnywhere === false) return null;
187
+ return await summarizeTranscriptFile(hit.path);
188
+ } catch {
189
+ return null;
190
+ }
191
+ }
192
+
193
+ async function buildReceipt(cwd, epicId, session, events, jobs, runsRoot, resolveTranscriptPath) {
194
+ const [jobsPart, chatPart] = await Promise.all([
195
+ jobsReceipt(cwd, epicId, session, events, jobs, runsRoot),
196
+ chatReceipt(cwd, session, resolveTranscriptPath),
197
+ ]);
198
+ return { jobs: jobsPart, chat: chatPart };
199
+ }
200
+
201
+ /**
202
+ * One Epic by id or externalRef: open from the active index, else completed
203
+ * from its archive file (only when archivedAt is set). Null on no match.
204
+ *
205
+ * `receipt: true` adds `receipt: { jobs, chat }` — jobs = gatherEpicJobReceipt
206
+ * over the Epic's known PRD slugs (knownPrdSlugs) since createdAt, chat = summarizeTranscriptFile of
207
+ * the resolved transcript (null when none). Each part is null on failure.
208
+ * Without it no run folder or transcript is read. `runsRoot` and
209
+ * `resolveTranscriptPath` are injectable for tests.
210
+ *
211
+ * @param {string} cwd
212
+ * @param {{ id?: string, externalRef?: string, receipt?: boolean, isTabBusy?: (epicId: string) => boolean | Promise<boolean>, listJobs?: () => any, projectRoots?: () => string[], runsRoot?: string, resolveTranscriptPath?: (a: { cwd: string, claudeSessionId: string }) => any }} [opts]
213
+ */
214
+ async function getEpicRecord(cwd, opts = {}) {
215
+ try {
216
+ const {
217
+ id, externalRef, receipt,
218
+ isTabBusy = () => false,
219
+ listJobs = () => [],
220
+ projectRoots = defaultProjectRoots,
221
+ runsRoot,
222
+ resolveTranscriptPath = resolveEpicTranscriptPath,
223
+ } = isObj(opts) ? opts : {};
224
+ if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return null;
225
+
226
+ let epicId = str(id);
227
+ if (!epicId && str(externalRef)) {
228
+ const hit = await findEpicByExternalRef({ cwd, externalRef });
229
+ epicId = hit ? str(hit.epicId) : null;
230
+ }
231
+ if (!epicId) return null;
232
+
233
+ const index = readActiveIndex(cwd);
234
+ const open = openSession(index, epicId);
235
+ const jobs = await loadJobs(listJobs);
236
+ let session;
237
+ let events;
238
+ let record;
239
+ if (open) {
240
+ session = open;
241
+ events = eventsOf(index, epicId);
242
+ const awaiting = await loadAwaiting(cwd);
243
+ record = await openRecord(cwd, epicId, open, index, jobs, awaiting, isTabBusy);
244
+ } else {
245
+ const archived = archivedEntry(cwd, epicId, projectRoots);
246
+ if (!archived) return null;
247
+ session = archived.session;
248
+ events = archived.events;
249
+ record = buildRecord(cwd, epicId, session, archived.events, jobs, false, false);
250
+ }
251
+ if (receipt !== true) return record;
252
+ return { ...record, receipt: await buildReceipt(cwd, epicId, session, events, jobs, runsRoot, resolveTranscriptPath) };
253
+ } catch {
254
+ return null;
255
+ }
256
+ }
257
+
258
+ function clampInt(v, dflt, min, max) {
259
+ const n = Number(v);
260
+ if (!Number.isFinite(n)) return dflt;
261
+ return Math.min(max, Math.max(min, Math.floor(n)));
262
+ }
263
+
264
+ /**
265
+ * A project's open (proposed/active) Epics, newest createdAt first.
266
+ *
267
+ * @param {string} cwd
268
+ * @param {{ state?: string, limit?: number, offset?: number, isTabBusy?: (epicId: string) => boolean | Promise<boolean>, listJobs?: () => any, projectRoots?: () => string[] }} [opts]
269
+ */
270
+ async function listOpenEpicRecords(cwd, opts = {}) {
271
+ const o = isObj(opts) ? opts : {};
272
+ const limit = o.limit == null ? DEFAULT_LIMIT : clampInt(o.limit, DEFAULT_LIMIT, 1, MAX_LIMIT);
273
+ const offset = o.offset == null ? 0 : clampInt(o.offset, 0, 0, Number.MAX_SAFE_INTEGER);
274
+ const empty = { epics: [], total: 0, limit, offset, hasMore: false };
275
+ try {
276
+ const {
277
+ state,
278
+ isTabBusy = () => false,
279
+ listJobs = () => [],
280
+ } = o;
281
+ if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return empty;
282
+
283
+ const index = readActiveIndex(cwd);
284
+ const open = [];
285
+ for (const epicId of Object.keys(isObj(index.sessions) ? index.sessions : {})) {
286
+ const s = openSession(index, epicId);
287
+ if (s) open.push([epicId, s]);
288
+ }
289
+ const t = (s) => { const n = Date.parse(s.createdAt); return Number.isFinite(n) ? n : -Infinity; };
290
+ open.sort((a, b) => t(b[1]) - t(a[1]) || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0));
291
+
292
+ const jobs = await loadJobs(listJobs);
293
+ const awaiting = await loadAwaiting(cwd);
294
+ const records = [];
295
+ for (const [epicId, s] of open) {
296
+ records.push(await openRecord(cwd, epicId, s, index, jobs, awaiting, isTabBusy));
297
+ }
298
+ const filtered = typeof state === 'string' && state ? records.filter((r) => r.state === state) : records;
299
+ const epics = filtered.slice(offset, offset + limit);
300
+ return { epics, total: filtered.length, limit, offset, hasMore: offset + epics.length < filtered.length };
301
+ } catch {
302
+ return empty;
303
+ }
304
+ }
305
+
306
+ module.exports = { listOpenEpicRecords, getEpicRecord };