claude-code-session-manager 0.132.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.
- package/README.md +3 -3
- package/dist/assets/{AgentLibrary-C09MlPFx.js → AgentLibrary-DOAG-mcG.js} +1 -1
- package/dist/assets/{AppSettings-DvDKsCnD.js → AppSettings-BHKM_AKh.js} +2 -2
- package/dist/assets/{Button-BzG_KdBC.js → Button-CmO1wmPw.js} +1 -1
- package/dist/assets/{DocumentEditorPane-fm6zsnLM.js → DocumentEditorPane-8QMNrNRt.js} +1 -1
- package/dist/assets/{Extensions-DgxKT_OZ.js → Extensions-Boo21B3b.js} +2 -2
- package/dist/assets/{History-Nd3bKjBq.js → History-C4epd1hp.js} +1 -1
- package/dist/assets/{Library-R71t6VAB.js → Library-CrgzRQzL.js} +1 -1
- package/dist/assets/{ListDetail-CG50Ul7c.js → ListDetail-DA7y1DQ-.js} +1 -1
- package/dist/assets/{Panel-C7EFG4eU.js → Panel-D-WMBhKH.js} +1 -1
- package/dist/assets/{ProjectClaudeConfig-J92iNEGC.js → ProjectClaudeConfig-CuUADpIu.js} +1 -1
- package/dist/assets/{ProvenanceBadge-C3KB3ILO.js → ProvenanceBadge-B7AsoRk6.js} +1 -1
- package/dist/assets/{Scheduler-DeYBA7uc.js → Scheduler-C86gRh51.js} +1 -1
- package/dist/assets/{Settings-B6r7N4v-.js → Settings-B4Q9DwVS.js} +1 -1
- package/dist/assets/{SkillReferenceGraph-D7bt3fyB.js → SkillReferenceGraph-DX4ZgvlY.js} +1 -1
- package/dist/assets/{Skills-GpxtUrFP.js → Skills-DqKI37yi.js} +1 -1
- package/dist/assets/{SourceChip-uyVMCZc7.js → SourceChip-C974LROr.js} +1 -1
- package/dist/assets/{SystemPrompt-Cv25uFSM.js → SystemPrompt-C502jIwO.js} +1 -1
- package/dist/assets/{TiptapBody-uP8fJkbM.js → TiptapBody-DwNXN6Ki.js} +1 -1
- package/dist/assets/{Toggle-DRs80cX-.js → Toggle-C2OsxnPK.js} +1 -1
- package/dist/assets/{ViewTabs-BDkvvzJ8.js → ViewTabs-DBxKGbAK.js} +1 -1
- package/dist/assets/{VoiceButton-Cmtz2sQt.js → VoiceButton-C680wpmX.js} +1 -1
- package/dist/assets/{historyTotals-DHwAXunq.js → historyTotals-Cz-VYPEc.js} +1 -1
- package/dist/assets/{index-oXqzajWV.css → index-CMwAikUb.css} +1 -1
- package/dist/assets/index-Dh5geJe3.js +3111 -0
- package/dist/index.html +2 -2
- package/dist-web/app.css +1 -1
- package/dist-web/app.js +427 -413
- package/package.json +1 -1
- package/src/main/build-info.json +4 -4
- package/src/main/chatRunner.cjs +77 -14
- package/src/main/index.cjs +13 -0
- package/src/main/ipcSchemas.cjs +54 -0
- package/src/main/lib/CLAUDE.md +2 -0
- package/src/main/lib/agent-cli/adapters/antigravity.cjs +147 -0
- package/src/main/lib/agent-cli/adapters/codex.cjs +170 -0
- package/src/main/lib/agent-cli/adapters/cursor.cjs +138 -0
- package/src/main/lib/agent-cli/adapters/gemini.cjs +119 -0
- package/src/main/lib/agent-cli/adapters/opencode.cjs +117 -0
- package/src/main/lib/agent-cli/agentCliEvents.cjs +94 -0
- package/src/main/lib/agent-cli/agentCliIpc.cjs +109 -0
- package/src/main/lib/agent-cli/agentCliRegistry.cjs +213 -0
- package/src/main/lib/agent-cli/agentCliSessionStore.cjs +152 -0
- package/src/main/lib/agent-cli/agentCliTurn.cjs +99 -0
- package/src/main/lib/app-preview/appPreviewIpc.cjs +125 -0
- package/src/main/lib/app-preview/appPreviewManager.cjs +317 -0
- package/src/main/lib/app-preview/appPreviewScripts.cjs +106 -0
- package/src/main/lib/app-preview/appPreviewSweep.cjs +92 -0
- package/src/main/lib/chatBootRecovery.cjs +41 -1
- package/src/main/lib/claude/agentEffortResolve.cjs +11 -3
- package/src/main/lib/epic/activeIndexMerge.cjs +25 -2
- package/src/main/lib/epic/archivedTranscript.cjs +39 -6
- package/src/main/lib/epic/epicChanges.cjs +466 -0
- package/src/main/lib/epic/epicMint.cjs +45 -1
- package/src/main/lib/epic/epicReopen.cjs +8 -2
- package/src/main/lib/epic/epicSpawnPlan.cjs +12 -0
- package/src/main/lib/epic/epicWorktreeMerge.cjs +39 -4
- package/src/main/lib/epic/promptSessionsCreateEpic.cjs +9 -4
- package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
- package/src/main/lib/git/gitExec.cjs +9 -1
- package/src/main/lib/git/gitWorktree.cjs +94 -0
- package/src/main/lib/git/unifiedDiff.cjs +207 -0
- package/src/main/lib/mdDocCensus.cjs +364 -0
- package/src/main/lib/mdDocRefs.cjs +249 -0
- package/src/main/lib/mdNetworkScan.cjs +158 -15
- package/src/main/lib/persona-macro/macroJobDispatch.cjs +4 -1
- package/src/main/lib/persona-macro/macroJobIpc.cjs +1 -1
- package/src/main/lib/prd/prdCreate.cjs +7 -2
- package/src/main/lib/prd/prdFrontmatter.cjs +10 -3
- package/src/main/lib/promptSessionSchema.cjs +6 -0
- package/src/main/lib/remoteTranscriptTail.cjs +23 -4
- package/src/main/lib/scheduler/landedSinceRun.cjs +2 -1
- package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
- package/src/main/lib/scheduler/schedulerPaths.cjs +3 -0
- package/src/main/projectPages.cjs +14 -3
- package/src/main/scheduler/gitTreeGuard.cjs +2 -1
- package/src/main/scheduler/prdParser.cjs +2 -1
- package/src/main/scheduler.cjs +7 -2
- package/src/main/transcripts.cjs +18 -4
- package/src/main/webRemote.cjs +10 -5
- package/src/preload/api.d.ts +147 -2
- package/src/preload/apiSurface.json +56 -0
- package/src/preload/index.cjs +22 -0
- package/dist/assets/index-CBCdyHbZ.js +0 -3097
|
@@ -0,0 +1,466 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* epicChanges.cjs — the single main-process read API behind an Epic's Changes
|
|
5
|
+
* view: getEpicChanges({ cwd, epicId }) → { ok, epicId, status, sections, truncated }.
|
|
6
|
+
*
|
|
7
|
+
* Sections are built per kind by SECTION_BUILDERS. This module builds the
|
|
8
|
+
* 'session' kind:
|
|
9
|
+
* - session:live — active worktree: diff <fork> (working tree, committed +
|
|
10
|
+
* uncommitted) plus untracked files, minus base-tree WIP
|
|
11
|
+
* carried in at mint and still unchanged.
|
|
12
|
+
* - session:branch — checkout removed but sm-epic/<id> still alive.
|
|
13
|
+
* - session:<head> — one per pinned review range (refs/sm-epic-review/).
|
|
14
|
+
* and the 'prd' kind — one section per PRD of the Epic that landed a commit.
|
|
15
|
+
* Scheduled PRD jobs fork from and land on the project's base branch, not on
|
|
16
|
+
* sm-epic/<id>, so a develop-loop Epic's work shows up only here. PRD slugs
|
|
17
|
+
* come only from this Epic's own prds/ + prds-archived/ dirs (plus ancestor
|
|
18
|
+
* Epic dirs); landedCommit only from THIS project's queue shard + history
|
|
19
|
+
* tail, filtered to this Epic — never a machine-wide scan.
|
|
20
|
+
*
|
|
21
|
+
* Every git call goes through gitExec.execGit with an argv array, a bounded
|
|
22
|
+
* timeout and a 32 MiB maxBuffer; every diff uses fixed flags so user config
|
|
23
|
+
* (quotepath, color, external diff, textconv, prefixes) cannot break parsing.
|
|
24
|
+
* Commands run inside a live worktree carry --no-optional-locks so they never
|
|
25
|
+
* take index.lock under the agent working there. Worktree dirs come only from
|
|
26
|
+
* the Epic record — never from joining a caller-supplied cwd.
|
|
27
|
+
*
|
|
28
|
+
* Never throws: every failure is { ok: false, reason } or a section `error`.
|
|
29
|
+
*/
|
|
30
|
+
|
|
31
|
+
const fs = require('node:fs');
|
|
32
|
+
const fsp = require('node:fs/promises');
|
|
33
|
+
const path = require('node:path');
|
|
34
|
+
const gitExec = require('../git/gitExec.cjs');
|
|
35
|
+
const gitWorktree = require('../git/gitWorktree.cjs');
|
|
36
|
+
const { parseUnifiedDiff } = require('../git/unifiedDiff.cjs');
|
|
37
|
+
const {
|
|
38
|
+
isSafeEpicId, resolveEpicsRoot, ancestorEpicPrdDirs, ancestorEpicArchivedPrdDirs,
|
|
39
|
+
} = require('../prd/prdLocations.cjs');
|
|
40
|
+
const { parsePrdFile } = require('../prd/prdFrontmatter.cjs');
|
|
41
|
+
|
|
42
|
+
const GIT_TIMEOUT_MS = 20_000;
|
|
43
|
+
const GIT_MAX_BUFFER = 32 * 1024 * 1024;
|
|
44
|
+
const MAX_FILES_PER_SECTION = 300;
|
|
45
|
+
const MAX_TOTAL_LINES = 20_000;
|
|
46
|
+
const MAX_UNTRACKED = 200;
|
|
47
|
+
const MAX_UNTRACKED_BYTES = 1024 * 1024;
|
|
48
|
+
const LIVE_WORKTREE_STATUSES = new Set(['active', 'needs_merge_resolution']);
|
|
49
|
+
const PRD_DIFF_CONCURRENCY = 4;
|
|
50
|
+
const EMPTY_TREE = '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
|
|
51
|
+
const TERMINAL_JOB_STATUSES = new Set(['completed', 'skipped', 'failed', 'quarantined']);
|
|
52
|
+
const HISTORY_TAIL = { maxRows: 5000, maxBytes: 8388608 };
|
|
53
|
+
const DIFF_FLAGS = ['--no-color', '--no-ext-diff', '--no-textconv', '-M', '--src-prefix=a/', '--dst-prefix=b/'];
|
|
54
|
+
|
|
55
|
+
/** Default record lookup: the active index entry, else the archived record. */
|
|
56
|
+
function defaultLoadEpic(cwd, epicId) {
|
|
57
|
+
const { loadActiveIndex, readArchived } = require('../../promptSessionsIpc.cjs');
|
|
58
|
+
const idx = loadActiveIndex(cwd);
|
|
59
|
+
const sessions = idx && idx.data && idx.data.sessions;
|
|
60
|
+
if (sessions && typeof sessions === 'object' && sessions[epicId]) return sessions[epicId];
|
|
61
|
+
const arch = readArchived(cwd, epicId);
|
|
62
|
+
return arch && arch.exists && arch.data ? arch.data : null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function resolveDeps(deps = {}) {
|
|
66
|
+
return {
|
|
67
|
+
loadEpic: deps.loadEpic || defaultLoadEpic,
|
|
68
|
+
listEpicPrds: deps.listEpicPrds || defaultListEpicPrds,
|
|
69
|
+
landedCommitFor: deps.landedCommitFor || defaultLandedCommitFor,
|
|
70
|
+
listEpicReviewRanges: deps.listEpicReviewRanges || gitWorktree.listEpicReviewRanges,
|
|
71
|
+
resolveForkSha: deps.resolveForkSha || gitWorktree.resolveForkSha,
|
|
72
|
+
unchangedCarriedPaths: deps.unchangedCarriedPaths || gitWorktree.unchangedCarriedPaths,
|
|
73
|
+
resolveDefaultBranch: deps.resolveDefaultBranch || gitWorktree.resolveDefaultBranch,
|
|
74
|
+
execGit: deps.execGit || gitExec.execGit,
|
|
75
|
+
validatePath: deps.validatePath || require('../../config.cjs').validatePath,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
function errText(err) {
|
|
80
|
+
const e = /** @type {any} */ (err);
|
|
81
|
+
return String((e && (e.stderrText || e.message)) || e || 'git failure').trim().split('\n')[0] || 'git failure';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Run git with the fixed limits. `live` adds --no-optional-locks. */
|
|
85
|
+
function git(d, cwd, args, { live = false } = {}) {
|
|
86
|
+
const pre = ['-c', 'core.quotepath=off'];
|
|
87
|
+
if (live) pre.push('--no-optional-locks');
|
|
88
|
+
return d.execGit(cwd, [...pre, ...args], { timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** `git diff` with the fixed flags → parsed files (throws on git failure). */
|
|
92
|
+
async function runDiff(d, cwd, revArgs, opts = {}) {
|
|
93
|
+
const pre = ['-c', 'core.quotepath=off'];
|
|
94
|
+
if (opts.live) pre.push('--no-optional-locks');
|
|
95
|
+
const out = await d.execGit(cwd, [...pre, 'diff', ...DIFF_FLAGS, ...revArgs], { timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER });
|
|
96
|
+
return parseUnifiedDiff(out).map((f) => ({ ...f, tooLarge: false }));
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** A section whose diff came from `produce()`; a git failure becomes `error`. */
|
|
100
|
+
async function makeSection(meta, produce) {
|
|
101
|
+
try {
|
|
102
|
+
return { kind: 'session', ...meta, files: await produce() };
|
|
103
|
+
} catch (err) {
|
|
104
|
+
return { kind: 'session', ...meta, files: [], error: errText(err) };
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function tryCommit(d, cwd, rev) {
|
|
109
|
+
try {
|
|
110
|
+
const sha = String(await git(d, cwd, ['rev-parse', '--verify', '--quiet', `${rev}^{commit}`])).trim();
|
|
111
|
+
return /^[0-9a-f]{40,64}$/.test(sha) ? sha : null;
|
|
112
|
+
} catch {
|
|
113
|
+
return null;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Fork point of `branch`: resolveForkSha, else merge-base with the default branch. */
|
|
118
|
+
async function forkPoint(d, cwd, forkCwd, branch) {
|
|
119
|
+
let fork = null;
|
|
120
|
+
try { fork = await d.resolveForkSha({ cwd: forkCwd, branch }); } catch { fork = null; }
|
|
121
|
+
if (fork) return fork;
|
|
122
|
+
try {
|
|
123
|
+
const base = await d.resolveDefaultBranch(cwd);
|
|
124
|
+
const out = String(await git(d, cwd, ['merge-base', `refs/heads/${base}`, `refs/heads/${branch}`])).trim();
|
|
125
|
+
return /^[0-9a-f]{40,64}$/.test(out) ? out : null;
|
|
126
|
+
} catch {
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Untracked files in a live worktree as 'added' diff files. */
|
|
132
|
+
async function untrackedFiles(d, dir, state) {
|
|
133
|
+
const out = String(await git(d, dir, ['ls-files', '--others', '--exclude-standard', '-z'], { live: true }));
|
|
134
|
+
const all = out.split('\0').filter(Boolean);
|
|
135
|
+
if (all.length > MAX_UNTRACKED) state.truncated = true;
|
|
136
|
+
const files = [];
|
|
137
|
+
for (const rel of all.slice(0, MAX_UNTRACKED)) {
|
|
138
|
+
let st = null;
|
|
139
|
+
try { st = await fsp.lstat(path.join(dir, rel)); } catch { continue; }
|
|
140
|
+
if (st.isFile() && st.size > MAX_UNTRACKED_BYTES) {
|
|
141
|
+
state.truncated = true;
|
|
142
|
+
files.push({ path: rel, oldPath: null, status: 'added', binary: false, additions: 0, deletions: 0, hunks: [], truncated: true, tooLarge: true });
|
|
143
|
+
continue;
|
|
144
|
+
}
|
|
145
|
+
let text = '';
|
|
146
|
+
try {
|
|
147
|
+
text = await git(d, dir, ['diff', ...DIFF_FLAGS, '--no-index', '--', '/dev/null', rel], { live: true });
|
|
148
|
+
} catch (err) {
|
|
149
|
+
const e = /** @type {any} */ (err);
|
|
150
|
+
if (!e || e.code !== 1) throw err; // exit 1 = "has differences"
|
|
151
|
+
text = e.stdoutText || '';
|
|
152
|
+
}
|
|
153
|
+
for (const f of parseUnifiedDiff(text)) files.push({ ...f, path: f.path || rel, tooLarge: false });
|
|
154
|
+
}
|
|
155
|
+
return files;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The 'session' sections for an Epic record. */
|
|
159
|
+
async function buildSessionSections({ cwd, epicId, record, deps: d, state }) {
|
|
160
|
+
const sections = [];
|
|
161
|
+
const wt = record && record.worktree && typeof record.worktree === 'object' ? record.worktree : null;
|
|
162
|
+
const branch = wt && typeof wt.branch === 'string' && wt.branch && !wt.branch.startsWith('-') ? wt.branch : null;
|
|
163
|
+
const dir = wt && typeof wt.dir === 'string' && path.isAbsolute(wt.dir) ? wt.dir : null;
|
|
164
|
+
const baseCwd = wt && typeof wt.baseCwd === 'string' && wt.baseCwd ? wt.baseCwd : cwd;
|
|
165
|
+
|
|
166
|
+
if (branch) {
|
|
167
|
+
const dirExists = !!dir && fs.existsSync(dir);
|
|
168
|
+
if (dirExists && LIVE_WORKTREE_STATUSES.has(wt.status)) {
|
|
169
|
+
const fork = await forkPoint(d, cwd, baseCwd, branch);
|
|
170
|
+
const meta = { key: 'session:live', label: 'Session edits (not yet merged)', base: fork, head: null, live: true };
|
|
171
|
+
sections.push(await makeSection(meta, async () => {
|
|
172
|
+
if (!fork) throw new Error('no fork point');
|
|
173
|
+
const files = [...await runDiff(d, dir, [fork, '--'], { live: true }), ...await untrackedFiles(d, dir, state)];
|
|
174
|
+
const carried = Array.isArray(wt.carriedPaths) ? wt.carriedPaths.filter((p) => typeof p === 'string' && p) : [];
|
|
175
|
+
if (!carried.length) return files;
|
|
176
|
+
const unchanged = new Set(await d.unchangedCarriedPaths({ cwd: baseCwd, dir, paths: carried }));
|
|
177
|
+
return files.filter((f) => !unchanged.has(f.path));
|
|
178
|
+
}));
|
|
179
|
+
} else if (!dirExists) {
|
|
180
|
+
const tip = await tryCommit(d, cwd, `refs/heads/${branch}`);
|
|
181
|
+
if (tip) {
|
|
182
|
+
const fork = await forkPoint(d, cwd, baseCwd, branch);
|
|
183
|
+
const meta = { key: 'session:branch', label: 'Session edits (committed; checkout removed)', base: fork, head: tip, live: false };
|
|
184
|
+
sections.push(await makeSection(meta, async () => {
|
|
185
|
+
if (!fork) throw new Error('no fork point');
|
|
186
|
+
return runDiff(d, cwd, [fork, `refs/heads/${branch}`, '--']);
|
|
187
|
+
}));
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
let ranges = [];
|
|
193
|
+
try { ranges = await d.listEpicReviewRanges({ cwd, epicId }); } catch { ranges = []; }
|
|
194
|
+
for (const r of Array.isArray(ranges) ? ranges : []) {
|
|
195
|
+
if (!r || !r.base || !r.head) continue;
|
|
196
|
+
const day = typeof r.headCommittedAt === 'string' ? r.headCommittedAt.slice(0, 10) : '';
|
|
197
|
+
const meta = { key: `session:${r.head}`, label: `Session edits landed ${day}`.trim(), base: r.base, head: r.head, live: false };
|
|
198
|
+
sections.push(await makeSection(meta, () => runDiff(d, cwd, [r.base, r.head, '--'])));
|
|
199
|
+
}
|
|
200
|
+
return sections;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// ---------- 'prd' sections ----------
|
|
204
|
+
|
|
205
|
+
/** `<slug>.md` files directly in `dir` → [{ slug, title }]. Never throws. */
|
|
206
|
+
function prdFilesIn(dir) {
|
|
207
|
+
let names = [];
|
|
208
|
+
try { names = fs.readdirSync(dir); } catch { return []; }
|
|
209
|
+
const out = [];
|
|
210
|
+
for (const name of names) {
|
|
211
|
+
if (!name.endsWith('.md')) continue;
|
|
212
|
+
const file = path.join(dir, name);
|
|
213
|
+
let title = '';
|
|
214
|
+
try {
|
|
215
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
216
|
+
const t = parsePrdFile(fs.readFileSync(file, 'utf8')).frontmatter.title;
|
|
217
|
+
title = typeof t === 'string' ? t.trim() : '';
|
|
218
|
+
} catch { continue; }
|
|
219
|
+
const slug = name.slice(0, -3);
|
|
220
|
+
out.push({ slug, title: title || slug });
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Immediate subdirectories of `dir` (prds-archived/<ISO>/). Never throws. */
|
|
226
|
+
function subdirsOf(dir) {
|
|
227
|
+
try {
|
|
228
|
+
return fs.readdirSync(dir, { withFileTypes: true }).filter((e) => e.isDirectory()).map((e) => path.join(dir, e.name));
|
|
229
|
+
} catch {
|
|
230
|
+
return [];
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* The Epic's PRDs → [{ slug, title }], first occurrence of a slug winning.
|
|
236
|
+
* Reads only <epicsRoot>/<epicId>/prds/ and both archived layouts —
|
|
237
|
+
* flat prds-archived/<NN>-<slug>.md (how the scheduler archives today) and
|
|
238
|
+
* nested prds-archived/<ISO>/<NN>-<slug>.md — plus the ancestor Epic dirs of
|
|
239
|
+
* the same id. Order: prds/ dirs, then each prds-archived root followed by
|
|
240
|
+
* its immediate subfolders. Never throws.
|
|
241
|
+
*/
|
|
242
|
+
function defaultListEpicPrds(cwd, epicId) {
|
|
243
|
+
const liveDirs = [];
|
|
244
|
+
const archivedRoots = [];
|
|
245
|
+
try {
|
|
246
|
+
const epicDir = path.join(resolveEpicsRoot(cwd), epicId);
|
|
247
|
+
liveDirs.push(path.join(epicDir, 'prds'));
|
|
248
|
+
archivedRoots.push(path.join(epicDir, 'prds-archived'));
|
|
249
|
+
} catch { /* unresolvable ops root: ancestors only */ }
|
|
250
|
+
try { liveDirs.push(...ancestorEpicPrdDirs(cwd, epicId)); } catch { /* none */ }
|
|
251
|
+
try { archivedRoots.push(...ancestorEpicArchivedPrdDirs(cwd, epicId)); } catch { /* none */ }
|
|
252
|
+
const dirs = [...liveDirs, ...archivedRoots.flatMap((root) => [root, ...subdirsOf(root)])];
|
|
253
|
+
const seen = new Map();
|
|
254
|
+
for (const dir of dirs) {
|
|
255
|
+
for (const p of prdFilesIn(dir)) if (!seen.has(p.slug)) seen.set(p.slug, p);
|
|
256
|
+
}
|
|
257
|
+
return [...seen.values()];
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Queue shard rows (`{ jobs: [...] }`) from one file. Missing/corrupt → []. */
|
|
261
|
+
function readQueueRows(file) {
|
|
262
|
+
try {
|
|
263
|
+
const data = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
264
|
+
return Array.isArray(data && data.jobs) ? data.jobs : [];
|
|
265
|
+
} catch {
|
|
266
|
+
return [];
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* readLandedCommits({ queuePath, historyPath, epicId, slugs }) →
|
|
272
|
+
* Map slug -> { sha, cwd }
|
|
273
|
+
* Considers only terminal rows of this Epic ((row.epicId || row.sourcePromptId)
|
|
274
|
+
* === epicId) whose slug is in `slugs`. The newest terminal row per slug wins
|
|
275
|
+
* (by finishedAt; on a tie, queue rows beat history, newer history lines beat
|
|
276
|
+
* older); a winner without landedCommit drops the slug. Never throws.
|
|
277
|
+
*/
|
|
278
|
+
function readLandedCommits({ queuePath, historyPath, epicId, slugs }) {
|
|
279
|
+
const want = new Set(slugs);
|
|
280
|
+
/** @type {Map<string, { row: any, at: string }>} */
|
|
281
|
+
const best = new Map();
|
|
282
|
+
const consider = (row) => {
|
|
283
|
+
if (!row || typeof row !== 'object' || typeof row.slug !== 'string' || !want.has(row.slug)) return;
|
|
284
|
+
if ((row.epicId || row.sourcePromptId) !== epicId) return;
|
|
285
|
+
if (row.kind && row.kind !== 'terminal') return;
|
|
286
|
+
if (!TERMINAL_JOB_STATUSES.has(row.status)) return;
|
|
287
|
+
const at = typeof row.finishedAt === 'string' ? row.finishedAt : '';
|
|
288
|
+
const cur = best.get(row.slug);
|
|
289
|
+
if (!cur || at >= cur.at) best.set(row.slug, { row, at });
|
|
290
|
+
};
|
|
291
|
+
let history = [];
|
|
292
|
+
try {
|
|
293
|
+
const { readHistoryFileTailSync } = require('../scheduler/queueHistory.cjs');
|
|
294
|
+
history = historyPath ? readHistoryFileTailSync(historyPath, HISTORY_TAIL) : [];
|
|
295
|
+
} catch { history = []; }
|
|
296
|
+
// Tail is newest-first: walk oldest → newest, then the live queue shard.
|
|
297
|
+
for (let i = history.length - 1; i >= 0; i -= 1) consider(history[i]);
|
|
298
|
+
if (queuePath) for (const row of readQueueRows(queuePath)) consider(row);
|
|
299
|
+
const out = new Map();
|
|
300
|
+
for (const [slug, { row }] of best) {
|
|
301
|
+
const sha = typeof row.landedCommit === 'string' ? row.landedCommit.trim() : '';
|
|
302
|
+
if (!/^[0-9a-f]{7,64}$/.test(sha)) continue;
|
|
303
|
+
out.set(slug, { sha, cwd: typeof row.cwd === 'string' && path.isAbsolute(row.cwd) ? row.cwd : null });
|
|
304
|
+
}
|
|
305
|
+
return out;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/** Default landedCommitFor: this project's queue shard + history file only. */
|
|
309
|
+
function defaultLandedCommitFor(cwd, slugs, epicId) {
|
|
310
|
+
const { projectQueuePath, projectHistoryPath } = require('../scheduler/queueStore.cjs');
|
|
311
|
+
let queuePath = null;
|
|
312
|
+
let historyPath = null;
|
|
313
|
+
try { queuePath = projectQueuePath(cwd); } catch { queuePath = null; }
|
|
314
|
+
try { historyPath = projectHistoryPath(cwd); } catch { historyPath = null; }
|
|
315
|
+
if (!queuePath && !historyPath) return new Map();
|
|
316
|
+
return readLandedCommits({ queuePath, historyPath, epicId, slugs });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** Run `fn` over `items` with at most `limit` in flight; results in input order. */
|
|
320
|
+
async function mapLimit(items, limit, fn) {
|
|
321
|
+
const out = new Array(items.length);
|
|
322
|
+
let next = 0;
|
|
323
|
+
const worker = async () => {
|
|
324
|
+
while (next < items.length) {
|
|
325
|
+
const i = next++;
|
|
326
|
+
out[i] = await fn(items[i], i);
|
|
327
|
+
}
|
|
328
|
+
};
|
|
329
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
|
330
|
+
return out;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
const prdNumber = (slug) => {
|
|
334
|
+
const m = /^(\d+)/.exec(slug);
|
|
335
|
+
return m ? Number(m[1]) : Number.POSITIVE_INFINITY;
|
|
336
|
+
};
|
|
337
|
+
|
|
338
|
+
/** The 'prd' sections: one per PRD of this Epic with a resolvable landedCommit. */
|
|
339
|
+
async function buildPrdSections({ cwd, epicId, deps: d }) {
|
|
340
|
+
let prds = [];
|
|
341
|
+
try { prds = await d.listEpicPrds(cwd, epicId); } catch { prds = []; }
|
|
342
|
+
prds = (Array.isArray(prds) ? prds : []).filter((p) => p && typeof p.slug === 'string' && p.slug);
|
|
343
|
+
if (!prds.length) return [];
|
|
344
|
+
let landed;
|
|
345
|
+
try { landed = await d.landedCommitFor(cwd, prds.map((p) => p.slug), epicId); } catch { landed = null; }
|
|
346
|
+
if (!(landed instanceof Map)) return [];
|
|
347
|
+
const todo = [];
|
|
348
|
+
for (const p of prds) {
|
|
349
|
+
const v = landed.get(p.slug);
|
|
350
|
+
const sha = typeof v === 'string' ? v : v && typeof v.sha === 'string' ? v.sha : '';
|
|
351
|
+
if (!/^[0-9a-f]{7,64}$/.test(sha)) continue;
|
|
352
|
+
const rowCwd = v && typeof v === 'object' && typeof v.cwd === 'string' && path.isAbsolute(v.cwd) ? v.cwd : null;
|
|
353
|
+
todo.push({ slug: p.slug, title: typeof p.title === 'string' && p.title ? p.title : p.slug, sha, gitCwd: rowCwd || cwd });
|
|
354
|
+
}
|
|
355
|
+
todo.sort((a, b) => (prdNumber(a.slug) - prdNumber(b.slug)) || a.slug.localeCompare(b.slug));
|
|
356
|
+
const built = await mapLimit(todo, PRD_DIFF_CONCURRENCY, async (t) => {
|
|
357
|
+
try {
|
|
358
|
+
await git(d, t.gitCwd, ['cat-file', '-e', `${t.sha}^{commit}`]);
|
|
359
|
+
} catch {
|
|
360
|
+
return null; // unknown sha: skip silently
|
|
361
|
+
}
|
|
362
|
+
const head = t.sha;
|
|
363
|
+
const meta = { kind: 'prd', key: `prd:${t.slug}`, label: t.title, slug: t.slug, base: `${head}^1`, head, live: false };
|
|
364
|
+
try {
|
|
365
|
+
const hasParent = !!(await tryCommit(d, t.gitCwd, `${head}^1`));
|
|
366
|
+
const files = await runDiff(d, t.gitCwd, [hasParent ? `${head}^1` : EMPTY_TREE, head, '--']);
|
|
367
|
+
return { ...meta, files };
|
|
368
|
+
} catch (err) {
|
|
369
|
+
return { ...meta, files: [], error: errText(err) };
|
|
370
|
+
}
|
|
371
|
+
});
|
|
372
|
+
return built.filter(Boolean);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Section builders by kind, in display order. */
|
|
376
|
+
const SECTION_BUILDERS = { session: buildSessionSections, prd: buildPrdSections };
|
|
377
|
+
|
|
378
|
+
/** Enforce the per-section file cap and the total line cap in place. */
|
|
379
|
+
function applyCaps(sections, state) {
|
|
380
|
+
let lines = 0;
|
|
381
|
+
for (const s of sections) {
|
|
382
|
+
s.files.forEach((f, i) => {
|
|
383
|
+
// Real diff size: the parser keeps at most 3000 lines per file, so the
|
|
384
|
+
// kept-hunk count alone would under-count a huge file.
|
|
385
|
+
const kept = (f.hunks || []).reduce((acc, h) => acc + ((h && h.lines) ? h.lines.length : 0), 0);
|
|
386
|
+
const n = Math.max(kept, (f.additions || 0) + (f.deletions || 0));
|
|
387
|
+
if (f.tooLarge) return;
|
|
388
|
+
if (f.truncated) state.truncated = true;
|
|
389
|
+
if (i >= MAX_FILES_PER_SECTION || lines + n > MAX_TOTAL_LINES) {
|
|
390
|
+
f.hunks = [];
|
|
391
|
+
f.tooLarge = true;
|
|
392
|
+
state.truncated = true;
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
lines += n;
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/**
|
|
401
|
+
* getEpicChanges({ cwd, epicId }, deps?) → Promise<
|
|
402
|
+
* { ok: true, epicId, status, sections, truncated } | { ok: false, reason }>
|
|
403
|
+
* deps (all optional, for tests): loadEpic, listEpicPrds, landedCommitFor,
|
|
404
|
+
* listEpicReviewRanges,
|
|
405
|
+
* resolveForkSha, unchangedCarriedPaths, resolveDefaultBranch, execGit,
|
|
406
|
+
* validatePath. Never throws.
|
|
407
|
+
*/
|
|
408
|
+
async function getEpicChanges(input, deps) {
|
|
409
|
+
try {
|
|
410
|
+
const { cwd, epicId } = input || {};
|
|
411
|
+
const d = resolveDeps(deps);
|
|
412
|
+
if (typeof cwd !== 'string' || !cwd || !path.isAbsolute(cwd)) return { ok: false, reason: 'cwd must be an absolute path' };
|
|
413
|
+
try { d.validatePath(cwd); } catch (err) { return { ok: false, reason: errText(err) }; }
|
|
414
|
+
if (!isSafeEpicId(epicId)) return { ok: false, reason: 'invalid epicId' };
|
|
415
|
+
let record;
|
|
416
|
+
try { record = await d.loadEpic(cwd, epicId); } catch (err) { return { ok: false, reason: errText(err) }; }
|
|
417
|
+
if (!record || typeof record !== 'object') return { ok: false, reason: 'epic not found' };
|
|
418
|
+
const state = { truncated: false };
|
|
419
|
+
const sections = [];
|
|
420
|
+
for (const build of Object.values(SECTION_BUILDERS)) {
|
|
421
|
+
sections.push(...await build({ cwd, epicId, record, deps: d, state }));
|
|
422
|
+
}
|
|
423
|
+
applyCaps(sections, state);
|
|
424
|
+
return { ok: true, epicId, status: record.status ?? null, sections, truncated: state.truncated };
|
|
425
|
+
} catch (err) {
|
|
426
|
+
return { ok: false, reason: errText(err) };
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
/**
|
|
431
|
+
* Register 'epicChanges:get'. Concurrent calls for the same (cwd, epicId)
|
|
432
|
+
* share one in-flight getEpicChanges run; the entry is dropped once it
|
|
433
|
+
* settles, so nothing is cached across calls. deps.getEpicChanges is a test seam.
|
|
434
|
+
*/
|
|
435
|
+
function registerEpicChangesHandlers(ipcMain = require('electron').ipcMain, deps = {}) {
|
|
436
|
+
const { schemas: s, validated: v } = require('../../ipcSchemas.cjs');
|
|
437
|
+
const run = deps.getEpicChanges || getEpicChanges;
|
|
438
|
+
/** @type {Map<string, Promise<unknown>>} */
|
|
439
|
+
const inFlight = new Map();
|
|
440
|
+
ipcMain.handle('epicChanges:get', v(s.epicChangesGet, ({ cwd, epicId }) => {
|
|
441
|
+
const key = `${cwd}\u0000${epicId}`;
|
|
442
|
+
const existing = inFlight.get(key);
|
|
443
|
+
if (existing) return existing;
|
|
444
|
+
let started;
|
|
445
|
+
try { started = Promise.resolve(run({ cwd, epicId })); } catch (err) { started = Promise.reject(err); }
|
|
446
|
+
const p = started.finally(() => { if (inFlight.get(key) === p) inFlight.delete(key); });
|
|
447
|
+
inFlight.set(key, p);
|
|
448
|
+
return p;
|
|
449
|
+
}));
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
module.exports = {
|
|
453
|
+
getEpicChanges,
|
|
454
|
+
registerEpicChangesHandlers,
|
|
455
|
+
SECTION_BUILDERS,
|
|
456
|
+
buildSessionSections,
|
|
457
|
+
buildPrdSections,
|
|
458
|
+
defaultListEpicPrds,
|
|
459
|
+
defaultLandedCommitFor,
|
|
460
|
+
readLandedCommits,
|
|
461
|
+
runDiff,
|
|
462
|
+
applyCaps,
|
|
463
|
+
defaultLoadEpic,
|
|
464
|
+
MAX_FILES_PER_SECTION,
|
|
465
|
+
MAX_TOTAL_LINES,
|
|
466
|
+
};
|
|
@@ -42,6 +42,44 @@ const telemetryCounters = require('../telemetry/telemetryCounters.cjs');
|
|
|
42
42
|
// simulate a corrupted construction — the real construction below is
|
|
43
43
|
// hardcoded and always valid.
|
|
44
44
|
const promptSessionSchema = require('../promptSessionSchema.cjs');
|
|
45
|
+
// Agent-CLI id helpers come from the shared adapter contract
|
|
46
|
+
// (lib/agent-cli/agentCliEvents.cjs, which exists in this tree) — not a local
|
|
47
|
+
// copy of the id list, so the two can never drift.
|
|
48
|
+
const { isAgentCliId, isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
|
|
49
|
+
|
|
50
|
+
const AGENT_CLI_MODEL_RE = /^[A-Za-z0-9._:/@+\[\]-]{1,128}$/;
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* agentCliMintFields(agentCli, agentCliModel, restoreSessionId) — validate the
|
|
54
|
+
* Epic's agent-CLI options and return the record keys they add ({} for a
|
|
55
|
+
* Claude Code Epic, so its on-disk shape is unchanged). Throws on any bad
|
|
56
|
+
* combination. The develop loop (dev plugin, /develop, PRD API) and Restore a
|
|
57
|
+
* session only work with Claude Code, so a non-Claude Epic is always
|
|
58
|
+
* developLoop:false and can never adopt a CLI session.
|
|
59
|
+
*/
|
|
60
|
+
function agentCliMintFields(agentCli, agentCliModel, restoreSessionId) {
|
|
61
|
+
const absent = agentCli === undefined || agentCli === null || agentCli === 'claude';
|
|
62
|
+
if (!absent && !isAgentCliId(agentCli)) {
|
|
63
|
+
throw new Error(`ensureEpic: unknown agentCli '${String(agentCli)}' — expected one of claude, codex, gemini, antigravity, cursor, opencode`);
|
|
64
|
+
}
|
|
65
|
+
const modelGiven = agentCliModel !== undefined && agentCliModel !== null;
|
|
66
|
+
if (absent || !isNonClaudeAgentCli(agentCli)) {
|
|
67
|
+
if (modelGiven) throw new Error('ensureEpic: agentCliModel requires a non-Claude agentCli');
|
|
68
|
+
return {};
|
|
69
|
+
}
|
|
70
|
+
if (restoreSessionId !== null && restoreSessionId !== undefined) {
|
|
71
|
+
throw new Error(`ensureEpic: Restore a session is Claude Code only — cannot restore into a '${agentCli}' Epic`);
|
|
72
|
+
}
|
|
73
|
+
const fields = { agentCli };
|
|
74
|
+
if (modelGiven) {
|
|
75
|
+
const trimmed = typeof agentCliModel === 'string' ? agentCliModel.trim() : '';
|
|
76
|
+
if (!trimmed || !AGENT_CLI_MODEL_RE.test(trimmed)) {
|
|
77
|
+
throw new Error(`ensureEpic: invalid agentCliModel ${JSON.stringify(agentCliModel)} — must match ${AGENT_CLI_MODEL_RE}`);
|
|
78
|
+
}
|
|
79
|
+
fields.agentCliModel = trimmed;
|
|
80
|
+
}
|
|
81
|
+
return fields;
|
|
82
|
+
}
|
|
45
83
|
|
|
46
84
|
// The one token that unlocks ensureEpic's mint branch. Held by
|
|
47
85
|
// lib/epic/promptSessionsCreateEpic.cjs (the New Epic card's IPC handler) and
|
|
@@ -265,7 +303,7 @@ function restoreRefusal(cwd, index, restoreSessionId, mintAuthority, deps) {
|
|
|
265
303
|
* The Epic's id doubles as its directory name under scheduler/epics/, so the
|
|
266
304
|
* PromptSession ↔ on-disk Epic mapping is 1:1 with no lookup table.
|
|
267
305
|
*/
|
|
268
|
-
function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'proposed', openingPrompt = null, sections = null, source = null, agentType = null, model = null, effort = null, developLoop = null, mintAuthority = null, restoreSessionId = null } = {}, deps = {}) {
|
|
306
|
+
function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'proposed', openingPrompt = null, sections = null, source = null, agentType = null, model = null, effort = null, developLoop = null, mintAuthority = null, restoreSessionId = null, agentCli = null, agentCliModel = null } = {}, deps = {}) {
|
|
269
307
|
if (!cwd || typeof cwd !== 'string') throw new Error('ensureEpic: cwd is required');
|
|
270
308
|
// A relative cwd (e.g. a caller passing '.') would otherwise get stored
|
|
271
309
|
// verbatim on the minted Epic's `cwd` field — the renderer's EpicsWorkspace
|
|
@@ -274,6 +312,10 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
|
|
|
274
312
|
// Epic that exists on disk but never renders in any project's queue.
|
|
275
313
|
cwd = path.resolve(cwd);
|
|
276
314
|
return withPathLock(activeIndexPath(cwd), () => {
|
|
315
|
+
// Agent-CLI rules run first — a bad id or combination throws before
|
|
316
|
+
// anything (index, mirror, audit, PRD dir) is written.
|
|
317
|
+
const cliFields = agentCliMintFields(agentCli, agentCliModel, restoreSessionId);
|
|
318
|
+
if (cliFields.agentCli) developLoop = false;
|
|
277
319
|
const index = readActiveIndex(cwd);
|
|
278
320
|
|
|
279
321
|
// A dispatch that already knows its Epic (sourcePromptId frontmatter from
|
|
@@ -393,6 +435,8 @@ function ensureEpic(cwd, { goalText, tag, epicId: explicitEpicId, status = 'prop
|
|
|
393
435
|
...(typeof effort === 'string' && effort ? { effort } : {}),
|
|
394
436
|
// Only false is persisted: absent = develop loop on (byte-identical legacy shape).
|
|
395
437
|
...(developLoop === false ? { developLoop: false } : {}),
|
|
438
|
+
// Non-Claude agent CLI only (absent = Claude Code, legacy shape).
|
|
439
|
+
...cliFields,
|
|
396
440
|
};
|
|
397
441
|
|
|
398
442
|
// Validate the constructed record against the canonical PromptSession
|
|
@@ -15,6 +15,7 @@ const { assertOpsWrite } = require('../opsOwnership.cjs');
|
|
|
15
15
|
const atomicFs = require('../util/atomicFs.cjs');
|
|
16
16
|
const { hasTranscriptSource, ensureEpicTranscriptReachable } = require('./epicTranscriptRestore.cjs');
|
|
17
17
|
const { restoreEpicWorktree } = require('./epicSpawnCwd.cjs');
|
|
18
|
+
const { isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
|
|
18
19
|
|
|
19
20
|
const inFlight = new Map();
|
|
20
21
|
|
|
@@ -83,8 +84,11 @@ async function doReopen({ cwd, epicId, deps }) {
|
|
|
83
84
|
}
|
|
84
85
|
|
|
85
86
|
const claudeSessionId = arch.claudeSessionId;
|
|
87
|
+
// A non-Claude agent-CLI Epic has no Claude JSONL to restore: its transcript lives in
|
|
88
|
+
// agentCliSessionStore and its CLI resumes from its own native session id.
|
|
89
|
+
const claudeTranscript = !isNonClaudeAgentCli(arch.agentCli);
|
|
86
90
|
const tDeps = deps.homeDir || deps.statSync ? { homeDir: deps.homeDir, statSync: deps.statSync } : {};
|
|
87
|
-
if (!hasTranscriptSource({ cwd, epicId, claudeSessionId, deps: tDeps })) {
|
|
91
|
+
if (claudeTranscript && !hasTranscriptSource({ cwd, epicId, claudeSessionId, deps: tDeps })) {
|
|
88
92
|
// No source anywhere, so this never writes; it only names the failure.
|
|
89
93
|
const r = ensureEpicTranscriptReachable({ cwd, epicId, claudeSessionId, deps: tDeps });
|
|
90
94
|
return r.ok ? fail('transcript_missing', 'No saved transcript.') : r;
|
|
@@ -92,7 +96,9 @@ async function doReopen({ cwd, epicId, deps }) {
|
|
|
92
96
|
|
|
93
97
|
const { worktree, created } = await provisionWorktree({ cwd, epicId, archived: arch.worktree, deps });
|
|
94
98
|
const spawnCwd = usableDir(worktree, deps) || cwd;
|
|
95
|
-
const reach =
|
|
99
|
+
const reach = claudeTranscript
|
|
100
|
+
? ensureEpicTranscriptReachable({ cwd, epicId, claudeSessionId, spawnCwd, deps: tDeps })
|
|
101
|
+
: { ok: true };
|
|
96
102
|
if (!reach.ok) {
|
|
97
103
|
if (created && worktree && worktree.dir) {
|
|
98
104
|
try {
|
|
@@ -35,6 +35,7 @@ const { projectRootOf } = require('../activeSessions.cjs');
|
|
|
35
35
|
const { readActiveIndex } = require('./epicMint.cjs');
|
|
36
36
|
const { resolveEpicSpawnCwd } = require('./epicSpawnCwd.cjs');
|
|
37
37
|
const { resolveEpicTranscriptPath } = require('./epicTranscriptPath.cjs');
|
|
38
|
+
const { isNonClaudeAgentCli } = require('../agent-cli/agentCliEvents.cjs');
|
|
38
39
|
|
|
39
40
|
/** Map<sessionId, { dir, message }> — sessions found unreachable; valid while `dir` stays missing. */
|
|
40
41
|
const unreachable = new Map();
|
|
@@ -108,6 +109,17 @@ function planEpicSpawn({ cwd, claudeSessionId, fallbackResume = false, worktreeD
|
|
|
108
109
|
|
|
109
110
|
let execCwd = (deps.resolveSpawnCwd || resolveEpicSpawnCwd)({ cwd, claudeSessionId, deps: { restore: true, readActiveIndex: deps.readActiveIndex, statSync: deps.statSync, restoreWorktree: deps.restoreWorktree } });
|
|
110
111
|
|
|
112
|
+
// Non-Claude agent CLIs never write a Claude JSONL, so the reachability guard below never fires
|
|
113
|
+
// for them. A recorded worktree that is still missing after the restore attempt must be refused
|
|
114
|
+
// here, or the turn silently runs in the shared project checkout instead of the Epic's worktree.
|
|
115
|
+
if (isNonClaudeAgentCli(epic?.agentCli) && brokenDir && !isDir(brokenDir, statSync)) {
|
|
116
|
+
return {
|
|
117
|
+
ok: false,
|
|
118
|
+
code: 'spawn_cwd_missing',
|
|
119
|
+
message: `Cannot spawn session ${claudeSessionId} (${epic.agentCli}): its worktree ${brokenDir} is gone and could not be re-attached. Recreate it (git worktree add "${brokenDir}" ${epic.worktree?.branch || '<sm-epic branch>'}) or start a new Epic — refusing to run in the shared project checkout.`,
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
111
123
|
if (resolved && resolved.existsAnywhere) {
|
|
112
124
|
const projectsDir = path.join(deps.homeDir || os.homedir(), '.claude', 'projects');
|
|
113
125
|
// O(candidates × existingPaths); both are tiny. Candidate order: chosen execCwd, then project cwd.
|
|
@@ -24,13 +24,33 @@
|
|
|
24
24
|
* re-attach and fall back to the project cwd) and resolve it manually — the
|
|
25
25
|
* branch and worktree dir are deliberately left intact so the human can merge
|
|
26
26
|
* them from the command line.
|
|
27
|
+
*
|
|
28
|
+
* Before integrating, the Epic's dev-server preview (app-preview/) is stopped
|
|
29
|
+
* — a backstop for any caller, since the renderer's markCompleted already
|
|
30
|
+
* stops it — so no preview process outlives the worktree it runs in. A
|
|
31
|
+
* failing stop is logged and never fails the merge.
|
|
32
|
+
*
|
|
33
|
+
* Also before integrating — whatever the outcome — the Epic's fork point and
|
|
34
|
+
* tip (or a snapshot of its uncommitted edits) are pinned under
|
|
35
|
+
* refs/sm-epic-review/ (pinEpicReviewRange), so the Changes view can still diff
|
|
36
|
+
* the Epic after cleanupEpicWorktree or the boot reaper deletes its branch. A
|
|
37
|
+
* pin failure is logged and never changes the merge result.
|
|
27
38
|
*/
|
|
28
39
|
|
|
29
|
-
const { integrateEpicBranch, cleanupEpicWorktree, reconcileWorktreeHead } = require('../git/gitWorktree.cjs');
|
|
40
|
+
const { integrateEpicBranch, cleanupEpicWorktree, reconcileWorktreeHead, pinEpicReviewRange } = require('../git/gitWorktree.cjs');
|
|
30
41
|
const { validatePath } = require('../../config.cjs');
|
|
31
42
|
|
|
43
|
+
// Lazy require: keeps app-preview (and electron) out of this module's load path.
|
|
44
|
+
async function defaultStopPreview(epicId) {
|
|
45
|
+
const { getAppPreviewManager } = require('../app-preview/appPreviewIpc.cjs');
|
|
46
|
+
await getAppPreviewManager().stop(epicId);
|
|
47
|
+
}
|
|
48
|
+
|
|
32
49
|
/**
|
|
33
|
-
* mergeEpicToMainViaIpc(cwd, epicId, branch, dir) → Promise<MergeOutcome>
|
|
50
|
+
* mergeEpicToMainViaIpc(cwd, epicId, branch, dir, carriedPaths?, deps?) → Promise<MergeOutcome>
|
|
51
|
+
*
|
|
52
|
+
* `deps.stopPreview(epicId)` is injectable for tests; defaults to the app
|
|
53
|
+
* preview manager's stop.
|
|
34
54
|
*
|
|
35
55
|
* `MergeOutcome` is `{ ok: true, status: 'merged', integrated: boolean }` on
|
|
36
56
|
* a clean merge (or a legitimate no-new-commits no-op — either way nothing
|
|
@@ -39,10 +59,25 @@ const { validatePath } = require('../../config.cjs');
|
|
|
39
59
|
* real conflict — never throws (integrateEpicBranch/cleanupEpicWorktree
|
|
40
60
|
* never do either).
|
|
41
61
|
*/
|
|
42
|
-
async function mergeEpicToMainViaIpc(cwd, epicId, branch, dir, carriedPaths) {
|
|
62
|
+
async function mergeEpicToMainViaIpc(cwd, epicId, branch, dir, carriedPaths, deps = {}) {
|
|
43
63
|
validatePath(cwd);
|
|
64
|
+
const stopPreview = deps.stopPreview || defaultStopPreview;
|
|
65
|
+
try {
|
|
66
|
+
await stopPreview(epicId);
|
|
67
|
+
} catch (err) {
|
|
68
|
+
console.log(`[epicWorktreeMerge] ${epicId}: preview stop failed, merging anyway (${err && err.message ? err.message : err})`);
|
|
69
|
+
}
|
|
70
|
+
let rec = null;
|
|
71
|
+
if (dir) rec = await reconcileWorktreeHead({ cwd, dir, branch, key: epicId });
|
|
72
|
+
try {
|
|
73
|
+
const pin = await pinEpicReviewRange({ cwd, branch, dir });
|
|
74
|
+
if (!pin.ok && pin.reason !== 'no changes') {
|
|
75
|
+
console.log(`[epicWorktreeMerge] ${epicId}: review range not pinned (${pin.reason})`);
|
|
76
|
+
}
|
|
77
|
+
} catch (err) {
|
|
78
|
+
console.log(`[epicWorktreeMerge] ${epicId}: review range not pinned (${err && err.message ? err.message : err})`);
|
|
79
|
+
}
|
|
44
80
|
if (dir) {
|
|
45
|
-
const rec = await reconcileWorktreeHead({ cwd, dir, branch, key: epicId });
|
|
46
81
|
if (rec && rec.action === 'diverged') {
|
|
47
82
|
const reason = `worktree HEAD ${rec.finalHead} is not on ${branch}; commit pinned at ${rec.pinnedRef || 'no ref'} — resolve manually`;
|
|
48
83
|
console.log(`[epicWorktreeMerge] ${epicId}: needs manual resolution (${reason})`);
|