claude-code-session-manager 0.130.3 → 0.131.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 (72) hide show
  1. package/dist/assets/{AgentLibrary-BmrXNwK8.js → AgentLibrary-CYXre0J-.js} +2 -2
  2. package/dist/assets/{AppSettings-Cs4POznd.js → AppSettings-xNSfCj8e.js} +2 -2
  3. package/dist/assets/{Button-UUr5giu8.js → Button-BWljh5IK.js} +1 -1
  4. package/dist/assets/{DocumentEditorPane-C46Hj0lz.js → DocumentEditorPane-FUC2hZlp.js} +1 -1
  5. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  6. package/dist/assets/{History-Bndupj87.js → History-BvNmY9OQ.js} +2 -2
  7. package/dist/assets/{Library-DFn0YPIW.js → Library-DVXk77zA.js} +12 -12
  8. package/dist/assets/{ListDetail-DjMn8a_3.js → ListDetail-DAAx__24.js} +1 -1
  9. package/dist/assets/{Panel-CIvb-XXN.js → Panel-g2D-e-RM.js} +1 -1
  10. package/dist/assets/{ProjectClaudeConfig-BQQRtMdK.js → ProjectClaudeConfig-BDuHJwaO.js} +7 -7
  11. package/dist/assets/{ProvenanceBadge-ej8W2ZIK.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  12. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  13. package/dist/assets/{Settings-DqxUna06.js → Settings-B23RsRfm.js} +1 -1
  14. package/dist/assets/{SkillReferenceGraph-BEMTdxdD.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  15. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  16. package/dist/assets/{SourceChip-BrPci8FX.js → SourceChip-jrC0vjfw.js} +1 -1
  17. package/dist/assets/{SystemPrompt-B43hNP0X.js → SystemPrompt-hHoBEnYb.js} +1 -1
  18. package/dist/assets/{TiptapBody-B-R2Bpda.js → TiptapBody-FkUqxO9u.js} +1 -1
  19. package/dist/assets/{Toggle-DKb4x1BP.js → Toggle-DQMNWZKT.js} +1 -1
  20. package/dist/assets/{ViewTabs-CcJdFZgv.js → ViewTabs-DGU0ZuxB.js} +1 -1
  21. package/dist/assets/{VoiceButton-BSH0UI3u.js → VoiceButton-BPPvDllh.js} +1 -1
  22. package/dist/assets/{historyTotals-5oUEu_fe.js → historyTotals-D8Oc3wUK.js} +1 -1
  23. package/dist/assets/{index-C9w-dVzo.js → index-9ajPMXBg.js} +1031 -1024
  24. package/dist/assets/{index-CMCcT2yg.css → index-oXqzajWV.css} +1 -1
  25. package/dist/index.html +2 -2
  26. package/dist-web/app.css +1 -1
  27. package/dist-web/app.js +414 -390
  28. package/package.json +1 -1
  29. package/scripts/scheduler-mcp-server.cjs +71 -0
  30. package/src/main/build-info.json +4 -4
  31. package/src/main/index.cjs +9 -0
  32. package/src/main/ipcSchemas.cjs +28 -1
  33. package/src/main/lib/epic/epicMint.cjs +61 -6
  34. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  35. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  36. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  37. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  38. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +2 -0
  39. package/src/main/lib/git/branchSweep.cjs +9 -3
  40. package/src/main/lib/git/gitExec.cjs +8 -1
  41. package/src/main/lib/git/gitWorktree.cjs +564 -62
  42. package/src/main/lib/git/jobWorktree.cjs +3 -0
  43. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  44. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  45. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  46. package/src/main/lib/persona-macro/builtinMacros.cjs +16 -0
  47. package/src/main/lib/persona-macro/macroJobDispatch.cjs +8 -0
  48. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  49. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  50. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  51. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  52. package/src/main/lib/promptSessionSchema.cjs +5 -0
  53. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  54. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  55. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  56. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  57. package/src/main/projectPages.cjs +20 -1
  58. package/src/main/runVerify.cjs +8 -3
  59. package/src/main/scheduler/budget.cjs +146 -7
  60. package/src/main/scheduler/gitTreeGuard.cjs +10 -11
  61. package/src/main/scheduler/reviewLadder.cjs +60 -0
  62. package/src/main/scheduler.cjs +461 -48
  63. package/src/main/seedAgentPersonas.cjs +1 -1
  64. package/src/preload/api.d.ts +159 -1
  65. package/src/preload/apiSurface.json +21 -0
  66. package/src/preload/index.cjs +5 -0
  67. package/src/seed/agents/competitive-analyst.md +69 -0
  68. package/src/seed/agents/competitive-researcher.md +75 -0
  69. package/src/seed/agents/validator.md +2 -2
  70. package/dist/assets/Extensions-B9QdiNOV.js +0 -2
  71. package/dist/assets/Scheduler-DSVBWqRK.js +0 -16
  72. package/dist/assets/Skills-DTXehVS7.js +0 -12
@@ -0,0 +1,112 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * matrixStore.cjs — the one sanctioned writer of the Competitor matrix state
5
+ * (writer 'project-home', namespace project-pages). writeMatrix() validates,
6
+ * archives the previous valid matrix.json into history/ (newest HISTORY_KEEP
7
+ * kept), writes matrix.json + matrix.schema.json, and refreshes the HTML
8
+ * snapshot as the Pages library entry knowledge/competitive-matrix.
9
+ */
10
+
11
+ const fsp = require('node:fs/promises');
12
+ const path = require('node:path');
13
+ const config = require('../../config.cjs');
14
+ const { opsPath, assertOpsWrite } = require('../opsOwnership.cjs');
15
+ const { validateMatrix, matrixJsonSchema, matrixPaths } = require('./competitiveMatrix.cjs');
16
+ const { renderMatrixHtml } = require('./matrixHtml.cjs');
17
+
18
+ const WRITER = 'project-home';
19
+ const HISTORY_KEEP = 50;
20
+ const PAGE_ID = 'competitive-matrix';
21
+ const HISTORY_NAME_RE = /^\d{8}T\d{6}Z\.json$/;
22
+
23
+ /** '2026-11-08T12:00:00.000Z' -> '20261108T120000Z'. */
24
+ function historyStamp(iso) {
25
+ const d = new Date(iso);
26
+ return d.toISOString().slice(0, 19).replace(/[-:]/g, '') + 'Z';
27
+ }
28
+
29
+ function write(abs, text) {
30
+ return config.writeTextAtomic(abs, text, { writer: WRITER });
31
+ }
32
+
33
+ /** Copy the current matrix.json into history/ if it is a valid matrix; -> path or null. */
34
+ async function archivePrevious(paths) {
35
+ let buf;
36
+ try {
37
+ buf = await fsp.readFile(paths.matrix);
38
+ } catch (e) {
39
+ if (e && e.code === 'ENOENT') return null;
40
+ throw e;
41
+ }
42
+ let value;
43
+ try {
44
+ value = JSON.parse(buf.toString('utf8'));
45
+ } catch {
46
+ return null;
47
+ }
48
+ const v = validateMatrix(value);
49
+ if (!v.ok) return null;
50
+ const dest = path.join(paths.history, `${historyStamp(v.matrix.updatedAt)}.json`);
51
+ await write(dest, buf.toString('utf8'));
52
+ return dest;
53
+ }
54
+
55
+ /** Remove all but the newest HISTORY_KEEP history files, through the same checks renameMigrated uses. */
56
+ async function pruneHistory(historyDir) {
57
+ let names;
58
+ try {
59
+ names = await fsp.readdir(historyDir);
60
+ } catch (e) {
61
+ if (e && e.code === 'ENOENT') return;
62
+ throw e;
63
+ }
64
+ const files = names.filter((n) => HISTORY_NAME_RE.test(n)).sort();
65
+ for (const name of files.slice(0, Math.max(0, files.length - HISTORY_KEEP))) {
66
+ const real = config.validatePath(path.join(historyDir, name));
67
+ config.validateWrite(real);
68
+ assertOpsWrite(real, WRITER);
69
+ await fsp.unlink(real);
70
+ }
71
+ }
72
+
73
+ /**
74
+ * writeMatrix(realCwd, value, { model, renderHtml }) ->
75
+ * { ok: true, path, htmlPath, historyPath } | { ok: false, error }.
76
+ * Nothing is written when validation fails — of the matrix, or of the rendered
77
+ * HTML snapshot against validateHomeHtml (fail closed). renderHtml is a test seam.
78
+ */
79
+ async function writeMatrix(realCwd, value, { model = '', renderHtml = renderMatrixHtml } = {}) {
80
+ const v = validateMatrix(value);
81
+ if (!v.ok) return { ok: false, error: v.error };
82
+ const paths = matrixPaths(realCwd);
83
+ if (!paths) return { ok: false, error: 'not a project' };
84
+ const matrix = v.matrix;
85
+ const { schemas } = require('../../ipcSchemas.cjs');
86
+ const topic = `${matrix.product.name} vs ${matrix.competitors.map((c) => c.name).join(', ')}`.slice(0, 120);
87
+ const meta = schemas.projectPageMeta.parse({
88
+ id: PAGE_ID,
89
+ title: 'Competitor matrix',
90
+ topic,
91
+ createdAt: new Date().toISOString(),
92
+ model: String(model || '').slice(0, 60),
93
+ });
94
+ const html = renderHtml(matrix);
95
+ // Lazy: projectHomeAdminRoutes.cjs requires this module (circular at top level).
96
+ const { validateHomeHtml } = require('../feedback-remote/projectHomeAdminRoutes.cjs');
97
+ const rejection = validateHomeHtml(html);
98
+ if (rejection) return { ok: false, error: `matrix page rejected: ${rejection}` };
99
+
100
+ const historyPath = await archivePrevious(paths);
101
+ if (historyPath) await pruneHistory(paths.history);
102
+
103
+ await write(paths.matrix, JSON.stringify(value, null, 2) + '\n');
104
+ await write(paths.schema, JSON.stringify(matrixJsonSchema(), null, 2) + '\n');
105
+ const pageDir = opsPath(realCwd, 'project-pages', 'knowledge', PAGE_ID);
106
+ const htmlPath = path.join(pageDir, 'index.html');
107
+ await write(htmlPath, html);
108
+ await write(path.join(pageDir, 'meta.json'), JSON.stringify(meta, null, 2) + '\n');
109
+ return { ok: true, path: paths.matrix, htmlPath, historyPath };
110
+ }
111
+
112
+ module.exports = { writeMatrix, HISTORY_KEEP, PAGE_ID };
@@ -97,6 +97,11 @@ 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
+ // true = this Epic adopted an existing CLI session as its claudeSessionId
101
+ // (ensureEpic's restoreSessionId) instead of a fresh one; absent otherwise.
102
+ // Only true is ever written: a false would fail here, and dropInvalidSessions
103
+ // (ipcSchemas.cjs) would then drop the whole stored row.
104
+ restoredSession: z.literal(true).optional(),
100
105
  // Absent on Epics minted before this field existed — those fall back to
101
106
  // rendering the flat `openingPrompt` as a single block (see
102
107
  // ChatTranscriptTurn.tsx's EpicIntakeCard).
@@ -32,6 +32,8 @@
32
32
  */
33
33
  'use strict';
34
34
 
35
+ const { isSafeEpicId } = require('../prd/prdLocations.cjs');
36
+
35
37
  function isFixPlanSlug(slug) {
36
38
  return /^\d+-fix-/.test(slug);
37
39
  }
@@ -59,4 +61,16 @@ function resolveIsFixPlan(slug, isFixPlan) {
59
61
  return isFixPlanSlug(slug);
60
62
  }
61
63
 
62
- module.exports = { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan };
64
+ /**
65
+ * The ONE repo-relative path a fix plan may name for a validation record
66
+ * (PRD 2883). Lives under the authored `reviews/` namespace — never under the
67
+ * gitignored `scheduler/` runtime folder, where the fix-plan PRD file itself
68
+ * sits. An unsafe/missing epicId drops the epic segment rather than
69
+ * concatenating it into a path.
70
+ */
71
+ function fixPlanRecordPath(epicId, fixSlug) {
72
+ const base = 'session-manager-operations/reviews/validation';
73
+ return isSafeEpicId(epicId) ? `${base}/${epicId}/${fixSlug}.md` : `${base}/${fixSlug}.md`;
74
+ }
75
+
76
+ module.exports = { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath };
@@ -279,6 +279,40 @@ function mapOutcomeToGateOutcome(outcome) {
279
279
  }
280
280
  }
281
281
 
282
+ /**
283
+ * resolveReapGateOutcome(outcome, resultText) → 'passed'|'failed'|'never_ran'|'unknown'
284
+ *
285
+ * The reaper's gateOutcome for a non-pidless dead row. Unlike
286
+ * mapOutcomeToGateOutcome, 'passed' is NOT inferred from the CLI result
287
+ * event's subtype=success — that only says the session ended cleanly, not
288
+ * that a gate ran (Bilko job 1685 never ran its gate, printed no verdict, and
289
+ * was stamped 'passed'). 'passed' requires the run's own LAST
290
+ * `SCHEDULER_VERDICT:` line to say PASS. Each line is classified by
291
+ * runVerify.cjs's scanSentinel (the one SCHEDULER_VERDICT parser), scanned
292
+ * from the end so the final say wins.
293
+ */
294
+ function lastVerdictLine(resultText) {
295
+ if (typeof resultText !== 'string' || !resultText) return null;
296
+ // Lazy require: runVerify.cjs is a larger module; keep this lib cheap to load.
297
+ const { scanSentinel } = require('../../runVerify.cjs');
298
+ const lines = resultText.split('\n');
299
+ for (let i = lines.length - 1; i >= 0; i--) {
300
+ const v = scanSentinel({ resultText: lines[i].replace(/\r$/, '') }, []);
301
+ if (v) return v;
302
+ }
303
+ return null;
304
+ }
305
+
306
+ function resolveReapGateOutcome(outcome, resultText) {
307
+ if (outcome === 'failed') return 'failed';
308
+ if (outcome === 'no_result') return 'never_ran';
309
+ if (outcome !== 'success') return 'unknown';
310
+ const verdict = lastVerdictLine(resultText);
311
+ if (verdict === 'pass') return 'passed';
312
+ if (verdict === 'fail') return 'failed';
313
+ return 'unknown';
314
+ }
315
+
282
316
  // Max times an orphaned job may be re-queued before giving up (marking failed).
283
317
  // Single source of truth: both the in-app reaper (scheduler.cjs) and the external
284
318
  // offline watchdog (watchdogHelpers.cjs) import this so their give-up budgets can
@@ -527,6 +561,7 @@ module.exports = {
527
561
  isClaudeArgv,
528
562
  classifyRunOutcome,
529
563
  mapOutcomeToGateOutcome,
564
+ resolveReapGateOutcome,
530
565
  ORPHAN_REQUEUE_CAP,
531
566
  selectReapableJobs,
532
567
  findLiveProcessForJob,
@@ -107,6 +107,8 @@ const ScheduleJobSchema = z
107
107
  quietLeaseDegraded: z.boolean().optional(),
108
108
  // Salvaged uncommitted diff patch path (PRD 1098).
109
109
  salvagePatch: z.string().nullable().optional(),
110
+ // Pin of a dead run's uncommitted checkout work (refs/sm-uncommitted/...), PRD 2892.
111
+ uncommittedSnapshot: z.object({ sha: z.string(), ref: z.string() }).optional(),
110
112
  // Leftover-attribution fields: the newly-dirty paths a terminal run left
111
113
  // uncommitted, diffed against the persisted pre-run baseline
112
114
  // (guardBaseline/guardHeadBefore below). Set on EVERY terminal outcome
@@ -63,13 +63,14 @@ const STATUS_HISTORY_CAP = 20;
63
63
  * executor ever ran; kept distinct from 'completed' so unrun work can't
64
64
  * read as shipped), running->pending (halt/rate-limit reset,
65
65
  * transient-failure retry). Also reached with verdict
66
- * 'reaped_without_integration' (source 'reapDeadRunningJobs', PRD 1133): a
67
- * reaped job whose result event looked successful but whose work cannot
68
- * be shown to have landed — a worktree branch still holding unmerged
69
- * commits, or an in-place run whose HEAD never advanced during the run
70
- * window — is parked here instead of 'completed', naming the branch (or
71
- * the lack of any commit) so the stranded work is never silently treated
72
- * as shipped.
66
+ * 'reaped_without_integration' (source 'reapDeadRunningJobs', PRD 1133):
67
+ * the reaper lands a run that printed its own SCHEDULER_VERDICT: PASS
68
+ * line (integrating its worktree branch) and parks here only a run
69
+ * without one whose work cannot be shown to have landed — a worktree
70
+ * branch still holding unmerged commits, or an in-place run whose HEAD
71
+ * never advanced during the run window — naming the branch (or the lack
72
+ * of any commit) so the stranded work is never silently treated as
73
+ * shipped.
73
74
  * - investigating->failed|needs_review (restore prior status once the
74
75
  * investigation probe exits), investigating->completed (defensive: the
75
76
  * restored prior status could in principle be 'completed' if a caller
@@ -11,7 +11,8 @@
11
11
  * refcounted per-cwd watcher pushes `project-pages:changed` for either. It
12
12
  * never writes content (watch()'s mkdir creates an empty directory only).
13
13
  * mdNetwork() maps the project's markdown link network on demand
14
- * (lib/mdNetworkScan.cjs) for the Tools pane.
14
+ * (lib/mdNetworkScan.cjs) for the Tools pane. matrix() reads the saved
15
+ * Competitor matrix (lib/project-pages/competitiveMatrix.cjs readMatrix).
15
16
  */
16
17
 
17
18
  const { ipcMain } = require('electron');
@@ -23,6 +24,7 @@ const { opsPath, assertOpsWrite, resolveProjectRoot } = require('./lib/opsOwners
23
24
  const { sendIfAlive } = require('./lib/sendToRenderer.cjs');
24
25
  const { listLibrary, migrateLegacy } = require('./lib/project-pages/pagesLibrary.cjs');
25
26
  const { scanMdNetwork } = require('./lib/mdNetworkScan.cjs');
27
+ const { readMatrix } = require('./lib/project-pages/competitiveMatrix.cjs');
26
28
 
27
29
  let mainWindow = null;
28
30
  function attachWindow(window) {
@@ -103,6 +105,21 @@ async function mdNetwork({ cwd }) {
103
105
  return scanMdNetwork(root);
104
106
  }
105
107
 
108
+ const MATRIX_EPHEMERAL = 'refusing an ephemeral cwd (tmpdir or linked git worktree): no project matrix';
109
+
110
+ /**
111
+ * -> CompetitorMatrixResult: the saved Competitor matrix, read once per call.
112
+ * Resolves the project root like mdNetwork(); `{ ok: true, matrix, error }`
113
+ * from readMatrix (matrix null when none / invalid, error set when invalid),
114
+ * or `{ ok: false, error }` when the cwd has no project root.
115
+ */
116
+ async function matrix({ cwd }) {
117
+ const { root, ephemeral } = tryProjectRoot(config.validatePath(cwd));
118
+ if (ephemeral) return { ok: false, error: MATRIX_EPHEMERAL };
119
+ const { matrix: m, error } = await readMatrix(root);
120
+ return { ok: true, matrix: m, error };
121
+ }
122
+
106
123
  /** True for paths whose change should refresh the library (relative to project-pages/). */
107
124
  function isLibraryPath(rel) {
108
125
  const parts = rel.split(path.sep);
@@ -275,6 +292,7 @@ function registerProjectPagesIpc() {
275
292
  const { schemas: s, validated: v } = require('./ipcSchemas.cjs');
276
293
  ipcMain.handle('project-pages:get', v(s.projectPagesCwd, get));
277
294
  ipcMain.handle('project-pages:md-network', v(s.projectPagesCwd, mdNetwork));
295
+ ipcMain.handle('project-pages:matrix', v(s.projectPagesCwd, matrix));
278
296
  ipcMain.handle('project-pages:watch', v(s.projectPagesCwd, ({ cwd }) => watchOutput(cwd)));
279
297
  ipcMain.handle('project-pages:rename', v(s.projectPagesRename, renameEntry));
280
298
  ipcMain.handle('project-pages:delete', v(s.projectPagesDelete, deleteEntry));
@@ -289,6 +307,7 @@ module.exports = {
289
307
  registerProjectPagesIpc,
290
308
  get,
291
309
  mdNetwork,
310
+ matrix,
292
311
  renameEntry,
293
312
  deleteEntry,
294
313
  watchOutput,
@@ -809,8 +809,10 @@ async function verifyRun({
809
809
  // bare PASS with no commit from one is still a strong silent-failure
810
810
  // signal and stays covered by this check.
811
811
  const isFixPlanJob = /^\d+-fix-/.test(queueEntry?.slug || '');
812
- // A transcript-reported commit that is not reachable from the repo was
813
- // dropped (detached HEAD, off-branch); no no-commit exemption may excuse it.
812
+ // A transcript-reported commit that exists in the repo but never landed
813
+ // on the checkout's HEAD (on no ref, for -merge-main slugs) was dropped
814
+ // (detached HEAD, off-branch, rewritten base); no no-commit exemption may
815
+ // excuse it.
814
816
  let unlandedTranscriptShas = [];
815
817
  if (sentinel === 'pass' && !commitEvidence && cwdIsGitRepo) {
816
818
  unlandedTranscriptShas = (transcriptCommitShas || [])
@@ -822,7 +824,10 @@ async function verifyRun({
822
824
  if (unlandedTranscriptShas.length > 0) {
823
825
  issues.push({
824
826
  verdict: 'run_commit_not_landed',
825
- reason: 'SCHEDULER_VERDICT: PASS but the transcript reports a commit that is not reachable from the repo: '
827
+ reason: 'SCHEDULER_VERDICT: PASS but the transcript reports a commit that '
828
+ + (isMergeMainSlug(queueEntry?.slug)
829
+ ? 'is on no ref: '
830
+ : "exists in the repo but never landed on the checkout's HEAD: ")
826
831
  + unlandedTranscriptShas.join(', '),
827
832
  priority: 1,
828
833
  downgradeTo: 'needs_review',
@@ -195,7 +195,7 @@ function computeJobBudgetMs(estimateMinutes, { factor, floorMs, ceilingMs } = {}
195
195
  }
196
196
 
197
197
  /**
198
- * classifyBudgetKill(res, landedCommitEvidence) → { status, reason, landedCommit } | null
198
+ * classifyBudgetKill(res, landedCommitEvidence, context?) → { status, reason, landedCommit } | null
199
199
  *
200
200
  * Pure. `res` is executeJob's resolved outcome — only fires when
201
201
  * `res.killedByWatchdog === 'budget'` (stamped by the budget watchdog inside
@@ -212,14 +212,151 @@ function computeJobBudgetMs(estimateMinutes, { factor, floorMs, ceilingMs } = {}
212
212
  * commit-guard evidence check the plain sigterm/exit paths already use, is
213
213
  * threaded onto the row as `landedCommit` so a job that HAD already
214
214
  * committed before overrunning is still adjudicated on its git evidence.
215
+ *
216
+ * `context` (optional) is describeBudgetKillContext's output plus an optional
217
+ * `commits` list ({ sha, subject }[], the run's own commits, read by the
218
+ * caller). Only when `context.inFinishReview` is true does the reason change:
219
+ * it names the review call the kill landed in, what had already landed, and
220
+ * which push/publish side effects had already run. Otherwise the reason is
221
+ * byte-identical to the context-less one.
222
+ *
223
+ * @param {any} res
224
+ * @param {string|null|undefined} landedCommitEvidence
225
+ * @param {{ inFinishReview?: boolean, reviewSkill?: string|null, sideEffects?: string[], commits?: Array<{ sha: string, subject: string }>|null }|null} [context]
215
226
  */
216
- function classifyBudgetKill(res, landedCommitEvidence) {
227
+ function classifyBudgetKill(res, landedCommitEvidence, context) {
217
228
  if (!res || res.killedByWatchdog !== 'budget') return null;
218
- return {
219
- status: 'needs_review',
220
- reason: res.budgetKillReason || `wall-clock budget exceeded (exit ${res.exitCode})`,
221
- landedCommit: landedCommitEvidence || null,
222
- };
229
+ const baseReason = res.budgetKillReason || `wall-clock budget exceeded (exit ${res.exitCode})`;
230
+ const landedCommit = landedCommitEvidence || null;
231
+ if (!context || context.inFinishReview !== true) {
232
+ return { status: 'needs_review', reason: baseReason, landedCommit };
233
+ }
234
+ // Keep the ran/budget/estimate figures: everything after the generic prefix.
235
+ const figures = baseReason.replace(/^wall-clock budget exceeded:?\s*/, '');
236
+ const skillLabel = String(context.reviewSkill || 'code-review');
237
+ const skillShown = skillLabel.length > REVIEW_SKILL_MAX_CHARS ? `${skillLabel.slice(0, REVIEW_SKILL_MAX_CHARS)}…` : skillLabel;
238
+ let reason = `wall-clock budget exceeded inside the finish-protocol review (/${skillShown} never returned)`;
239
+ if (figures) reason += `: ${figures}`;
240
+ const commits = Array.isArray(context.commits) ? context.commits.slice(0, 5) : [];
241
+ if (commits.length > 0) {
242
+ reason += `; work already landed: ${commits.map((c) => `${String(c.sha).slice(0, 7)} ${c.subject}`.trim()).join(', ')}`;
243
+ } else if (landedCommit) {
244
+ reason += `; work already landed: ${String(landedCommit).slice(0, 7)}`;
245
+ } else {
246
+ reason += '; no commit landed on the job branch';
247
+ }
248
+ const sideEffects = Array.isArray(context.sideEffects) ? context.sideEffects : [];
249
+ if (sideEffects.length > 0) reason += `; side effects already run: ${sideEffects.join(' | ')}`;
250
+ return { status: 'needs_review', reason, landedCommit };
251
+ }
252
+
253
+ const REVIEW_SKILL_PREFIXES = ['code-review', 'security-review'];
254
+ const SIDE_EFFECT_MAX = 5;
255
+ const SIDE_EFFECT_MAX_CHARS = 120;
256
+ const REVIEW_SKILL_MAX_CHARS = 80;
257
+ const SIDE_EFFECT_PATTERNS = ['git push', 'npm publish'];
258
+
259
+ /**
260
+ * sideEffectSegments(command) → string[]
261
+ *
262
+ * Pure. Splits a Bash command on &&, ||, ;, | and newlines (no shell parser —
263
+ * a split inside a quoted string is acceptable), trims each segment and keeps
264
+ * the ones naming `git push` / `npm publish`, each cut to 120 chars. So a real
265
+ * executor's `cd /tmp/x && git add a && git commit -m y && git push origin
266
+ * HEAD:main` is labelled by its push, not by its leading `cd`.
267
+ *
268
+ * @param {string} command
269
+ * @returns {string[]}
270
+ */
271
+ function sideEffectSegments(command) {
272
+ return String(command)
273
+ .split(/&&|\|\||;|\||\n/)
274
+ .map((seg) => seg.trim())
275
+ .filter((seg) => SIDE_EFFECT_PATTERNS.some((p) => seg.includes(p)))
276
+ .map((seg) => seg.slice(0, SIDE_EFFECT_MAX_CHARS));
277
+ }
278
+
279
+ /**
280
+ * describeBudgetKillContext(logText) → { inFinishReview, reviewSkill, sideEffects }
281
+ *
282
+ * Pure, never throws. Parses a `claude -p --output-format stream-json` run log
283
+ * (or its tail — a torn first line is just skipped) and answers: was the
284
+ * executor's LAST top-level tool call a review Skill (/code-review,
285
+ * /security-review) that never got its tool_result — i.e. did the budget kill
286
+ * land inside the finish-protocol review? `sideEffects` lists the `git push` /
287
+ * `npm publish` command segments (see sideEffectSegments) of Bash calls that had already succeeded (a matching
288
+ * tool_result with is_error !== true), deduped, at most 5, each ≤ 120 chars.
289
+ * Subagent events (non-null parent_tool_use_id) never count as the last
290
+ * top-level tool_use.
291
+ *
292
+ * @param {string} logText
293
+ * @returns {{ inFinishReview: boolean, reviewSkill: string|null, sideEffects: string[] }}
294
+ */
295
+ function describeBudgetKillContext(logText) {
296
+ const empty = { inFinishReview: false, reviewSkill: null, sideEffects: [] };
297
+ try {
298
+ if (typeof logText !== 'string' || !logText) return empty;
299
+ /** @type {any} */
300
+ let lastTopToolUse = null;
301
+ /** @type {Map<string, boolean>} tool_use_id → is_error */
302
+ const results = new Map();
303
+ // true once a tool_result answers the current lastTopToolUse
304
+ let answeredAfterLast = false;
305
+ /** @type {Array<{ id: string, command: string }>} */
306
+ const bashCalls = [];
307
+ for (const raw of logText.split('\n')) {
308
+ const line = raw.trim();
309
+ if (!line || line[0] !== '{') continue;
310
+ let ev;
311
+ try { ev = JSON.parse(line); } catch { continue; }
312
+ if (!ev || typeof ev !== 'object') continue;
313
+ const content = ev.message && Array.isArray(ev.message.content) ? ev.message.content : null;
314
+ if (!content) continue;
315
+ const topLevel = ev.parent_tool_use_id == null;
316
+ if (ev.type === 'assistant') {
317
+ for (const block of content) {
318
+ if (!block || block.type !== 'tool_use') continue;
319
+ if (block.name === 'Bash' && block.input && typeof block.input.command === 'string' && typeof block.id === 'string') {
320
+ bashCalls.push({ id: block.id, command: block.input.command });
321
+ }
322
+ if (topLevel) {
323
+ lastTopToolUse = block;
324
+ answeredAfterLast = false;
325
+ }
326
+ }
327
+ } else if (ev.type === 'user') {
328
+ for (const block of content) {
329
+ if (!block || block.type !== 'tool_result' || typeof block.tool_use_id !== 'string') continue;
330
+ results.set(block.tool_use_id, block.is_error === true);
331
+ if (lastTopToolUse && block.tool_use_id === lastTopToolUse.id) answeredAfterLast = true;
332
+ }
333
+ }
334
+ }
335
+ let inFinishReview = false;
336
+ let reviewSkill = null;
337
+ if (lastTopToolUse && lastTopToolUse.name === 'Skill' && !answeredAfterLast) {
338
+ const input = lastTopToolUse.input || {};
339
+ const skill = typeof input.skill === 'string' ? input.skill.trim() : '';
340
+ if (REVIEW_SKILL_PREFIXES.some((p) => skill.startsWith(p))) {
341
+ inFinishReview = true;
342
+ const args = typeof input.args === 'string' ? input.args.trim() : '';
343
+ reviewSkill = args ? `${skill} ${args}` : skill;
344
+ }
345
+ }
346
+ /** @type {string[]} */
347
+ const sideEffects = [];
348
+ for (const call of bashCalls) {
349
+ if (sideEffects.length >= SIDE_EFFECT_MAX) break;
350
+ if (!results.has(call.id) || results.get(call.id) === true) continue;
351
+ for (const seg of module.exports.sideEffectSegments(call.command)) {
352
+ if (sideEffects.length >= SIDE_EFFECT_MAX) break;
353
+ if (!sideEffects.includes(seg)) sideEffects.push(seg);
354
+ }
355
+ }
356
+ return { inFinishReview, reviewSkill, sideEffects };
357
+ } catch {
358
+ return empty;
359
+ }
223
360
  }
224
361
 
225
362
  /**
@@ -598,6 +735,8 @@ module.exports = {
598
735
  findOverrunningJobs,
599
736
  computeJobBudgetMs,
600
737
  classifyBudgetKill,
738
+ describeBudgetKillContext,
739
+ sideEffectSegments,
601
740
  isJobBudgetExempt,
602
741
  shouldKillForBudget,
603
742
  resolveBudgetKillOutcome,
@@ -518,20 +518,19 @@ function gitRangeCommits(cwd, before, after) {
518
518
  * 1. Ancestry: the branch tip is an ancestor of (or equal to) HEAD, the
519
519
  * same `mergeBase === branchHead` test as integrateBranch()'s no-op
520
520
  * detection.
521
- * 2. Content: `gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch })`.
521
+ * 2. Content: `gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch, sinceSha: forkSha })`.
522
522
  * Linear landing (PRDs 2743, 2825) replays the branch onto the base, so a
523
523
  * landed branch's own commits never become ancestors of HEAD. Proof 1
524
524
  * alone made the reaper park a landed job as "still holds unintegrated
525
525
  * work — never merged" (validator finding I-2). The helper also accepts
526
526
  * patch-equivalent commits on HEAD, or a merge that would change nothing.
527
- * Deliberately never calls integrateBranch itself: this is used by
528
- * reapDeadRunningJobs to PROVE a dead job's work already landed, never to
529
- * perform the landing — attempting a real merge from an audit check is a
530
- * mutating action with its own conflict/timing risk, and "land the still-
531
- * stranded branch" is explicitly a separate, later decision (mechanical
532
- * recovery, or a human), not something a reap pass should do on its own
533
- * initiative. See reapDeadRunningJobs's own header comment for why the
534
- * conservative failure direction here is needs_review, never a silent merge.
527
+ * `forkSha` (the branch's fork point) is passed as `sinceSha`, bounding
528
+ * the proof to the job's own commits — a base rebased after the fork
529
+ * never makes the base's rewritten commits read as unlanded job work.
530
+ * This check itself never calls integrateBranch: it is read-only proof.
531
+ * The landing decision belongs to reapDeadRunningJobs, which integrates a
532
+ * `false` branch only when the run printed its own SCHEDULER_VERDICT: PASS
533
+ * line; any other outcome parks needs_review, never a silent merge.
535
534
  *
536
535
  * Returns:
537
536
  * - true — branch exists and its content is already in HEAD (integrated by
@@ -543,7 +542,7 @@ function gitRangeCommits(cwd, before, after) {
543
542
  * in-place run, or SM_JOB_WORKTREE_DISABLE), or `rev-parse` errored.
544
543
  * Never throws.
545
544
  */
546
- function isBranchAlreadyIntegrated(cwd, branch) {
545
+ function isBranchAlreadyIntegrated(cwd, branch, forkSha = null) {
547
546
  return new Promise((resolve) => {
548
547
  if (!cwd || !branch) { resolve(null); return; }
549
548
  execFile(
@@ -558,7 +557,7 @@ function isBranchAlreadyIntegrated(cwd, branch) {
558
557
  (mbErr, mbOut) => {
559
558
  const mergeBase = mbErr ? '' : String(mbOut || '').trim();
560
559
  if (mergeBase !== '' && mergeBase === branchHead) { resolve(true); return; }
561
- gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch })
560
+ gitWorktree.isBranchContentLanded({ cwd, base: 'HEAD', branch, sinceSha: forkSha || undefined })
562
561
  .then((landed) => resolve(landed === true), () => resolve(false));
563
562
  },
564
563
  );
@@ -122,6 +122,7 @@ function selectMechanicalRecoveryTarget(job, currentHeadSha = null) {
122
122
  branch: jobWorktree.branchNameFor(job.slug),
123
123
  carriedPaths: job.carriedPaths || [],
124
124
  baseBranch: job.worktreeBaseBranch || null,
125
+ forkSha: job.worktreeForkSha || null,
125
126
  };
126
127
  }
127
128
 
@@ -187,9 +188,59 @@ const RESCAN_EXCLUDED_VERDICTS = new Set([
187
188
  // Its damage IS a commit stranded on an unmerged sm-job branch — a landedCommit restates it; selectMechanicalRecoveryTarget owns the real re-merge.
188
189
  'worktree_integration_failed',
189
190
  // The run overran its own time/cost estimate; no transcript or git evidence can un-overrun it (selectAutoFixTargets excludes it too).
191
+ // Carve-out (isFinishReviewKillHealEligible): a kill inside the finish-protocol review AFTER the commit
192
+ // integrated left only the review + verdict undone, so a green re-run of the PRD's own gate is the proof.
190
193
  'budget_exceeded',
191
194
  ]);
192
195
 
196
+ /**
197
+ * Finish-review budget-kill heal (one attempt). The ONLY budget_exceeded rows
198
+ * any self-heal rung may touch: the kill hit inside the finish-protocol review
199
+ * (budgetKillPhase 'finish-review', stamped at finalize) after the run landed
200
+ * a commit. Everything else budget_exceeded stays excluded (above).
201
+ *
202
+ * Pure. Integration into the main checkout is only partly provable here: a
203
+ * row carrying an integrationFailureKind (stampIntegrationFailure — commit
204
+ * stranded on an unmerged sm-job branch) is refused outright; the rung in
205
+ * scheduler.cjs additionally requires landedCommit to be an ancestor of the
206
+ * main checkout's HEAD before it runs the gate.
207
+ *
208
+ * Bounded to one attempt by finishReviewHealAttemptedAt, stamped by the rung
209
+ * whatever the outcome (red, unrunnable, not integrated) — so a red gate never
210
+ * loops. Kill-switch: SM_FINISH_REVIEW_HEAL_DISABLE=1.
211
+ */
212
+ function isFinishReviewKillHealEligible(job) {
213
+ if (process.env.SM_FINISH_REVIEW_HEAL_DISABLE === '1') return false;
214
+ if (!job || job.status !== 'needs_review') return false;
215
+ if (job.verifierVerdict !== 'budget_exceeded') return false;
216
+ if (job.budgetKillPhase !== 'finish-review') return false;
217
+ if (typeof job.landedCommit !== 'string' || job.landedCommit.length === 0) return false;
218
+ if (job.finishReviewHealAttemptedAt) return false;
219
+ if (job.integrationFailureKind) return false;
220
+ if (isCancelledJob(job) || isRefireCapped(job)) return false;
221
+ return true;
222
+ }
223
+
224
+ /**
225
+ * Pure decision for the finish-review heal, from ground truth the rung
226
+ * computed: evidenceOk (landedCommit is git-verified evidence from THIS
227
+ * dispatch), integratedOk (landedCommit is an ancestor of the main
228
+ * checkout's HEAD), setupOk (scratch worktree's declared setup settled), the
229
+ * resolved gate, and runGateSequence's outcome. First failed check names the
230
+ * reason. Mirrors decideGateAuthority's trusted-gate rule ('ac-line-guess'
231
+ * never counts).
232
+ */
233
+ function decideFinishReviewKillHeal({ evidenceOk, integratedOk, gate, setupOk, outcome } = {}) {
234
+ if (evidenceOk !== true) return { complete: false, reason: 'commit-not-from-this-run' };
235
+ if (integratedOk !== true) return { complete: false, reason: 'commit-not-integrated' };
236
+ const hasGate = (gate?.source === 'explicit' || gate?.source === 'ac-line')
237
+ && Array.isArray(gate?.sequence) && gate.sequence.length > 0;
238
+ if (!hasGate) return { complete: false, reason: 'no-gate' };
239
+ if (setupOk !== true) return { complete: false, reason: 'setup-not-settled' };
240
+ if (outcome?.status !== 'green') return { complete: false, reason: outcome?.status === 'red' ? 'gate-red' : 'gate-not-runnable' };
241
+ return { complete: true, reason: 'gate-green' };
242
+ }
243
+
193
244
  // Per-pass / per-row bounds on the evidence-only rung (the widened candidate
194
245
  // set). Each scan costs one computeLooksDone: a per-cwd-deduped `git fetch`
195
246
  // (<=~20s) + a git log. Unbounded, a backlog of N parked rows would pay N of
@@ -879,6 +930,8 @@ function selectAutoFixTargets(jobs, { fixSlugExists, resolveJobRunId = resolveRu
879
930
  // auto-fix investigation or auto-retry — the run didn't fail, it simply
880
931
  // overran its own estimate; there's no code defect to diagnose (Out of
881
932
  // scope: "retrying or auto-resuming a budget-killed job" for this PRD).
933
+ // The finish-review carve-out (isFinishReviewKillHealEligible) heals via a gate
934
+ // re-run, never via auto-fix — so this exclusion holds for every budget_exceeded row.
882
935
  if (job.verifierVerdict === 'budget_exceeded') return false;
883
936
  // A stale re-run whose work already shipped (rcaReport's 'already-shipped'
884
937
  // class) must never buy a fix-plan PRD — there is nothing to fix, and the
@@ -970,6 +1023,11 @@ function selectGateShadowTarget(jobs, headByCwd, { authorityDisabled = false, ba
970
1023
  return typeof head === 'string' && head.length > 0;
971
1024
  });
972
1025
 
1026
+ // Tier 0: a finish-review budget kill's one-shot heal (bounded by its own
1027
+ // attempt stamp, so it can win the pick at most once per row).
1028
+ const finishReviewHeal = eligible.find((j) => isFinishReviewKillHealEligible(j));
1029
+ if (finishReviewHeal) return finishReviewHeal;
1030
+
973
1031
  const isStale = (j) => {
974
1032
  const head = headByCwd.get(j.cwd);
975
1033
  return !j.gateShadow || j.gateShadow.head !== head || j.gateShadow.definitive !== true;
@@ -1074,4 +1132,6 @@ module.exports = {
1074
1132
  selectAutoFixTargets,
1075
1133
  isEligibleForImmediateAutoFix,
1076
1134
  selectGateShadowTarget,
1135
+ isFinishReviewKillHealEligible,
1136
+ decideFinishReviewKillHeal,
1077
1137
  };