claude-code-session-manager 0.130.2 → 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 (88) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/bin/cli.cjs +19 -2
  3. package/dist/assets/AgentLibrary-CYXre0J-.js +2 -0
  4. package/dist/assets/{AppSettings-Bpwynea4.js → AppSettings-xNSfCj8e.js} +2 -2
  5. package/dist/assets/{Button-DSoqrxCB.js → Button-BWljh5IK.js} +1 -1
  6. package/dist/assets/DocumentEditorPane-FUC2hZlp.js +1 -0
  7. package/dist/assets/Extensions-CsyUoklz.js +2 -0
  8. package/dist/assets/{History-DzMo9Otn.js → History-BvNmY9OQ.js} +2 -2
  9. package/dist/assets/{Library-C5wKMTSn.js → Library-DVXk77zA.js} +12 -12
  10. package/dist/assets/{ListDetail-DDQ1S0yu.js → ListDetail-DAAx__24.js} +1 -1
  11. package/dist/assets/{Panel-B-3NWUlv.js → Panel-g2D-e-RM.js} +1 -1
  12. package/dist/assets/ProjectClaudeConfig-BDuHJwaO.js +25 -0
  13. package/dist/assets/{ProvenanceBadge-CUChwz4Z.js → ProvenanceBadge-wew4_nf3.js} +1 -1
  14. package/dist/assets/Scheduler-CbeUIqD-.js +16 -0
  15. package/dist/assets/Settings-B23RsRfm.js +2 -0
  16. package/dist/assets/{SkillReferenceGraph-C6JEdypC.js → SkillReferenceGraph-BxQPCfsg.js} +1 -1
  17. package/dist/assets/Skills-4AR2FQrI.js +29 -0
  18. package/dist/assets/{SourceChip-DcBNYYhe.js → SourceChip-jrC0vjfw.js} +1 -1
  19. package/dist/assets/SystemPrompt-hHoBEnYb.js +1 -0
  20. package/dist/assets/{TiptapBody-DiVYC-_O.js → TiptapBody-FkUqxO9u.js} +1 -1
  21. package/dist/assets/{Toggle-Cs3k6I96.js → Toggle-DQMNWZKT.js} +1 -1
  22. package/dist/assets/ViewTabs-DGU0ZuxB.js +1 -0
  23. package/dist/assets/{VoiceButton-C3NLotUZ.js → VoiceButton-BPPvDllh.js} +1 -1
  24. package/dist/assets/{historyTotals-f-E0L9Xw.js → historyTotals-D8Oc3wUK.js} +1 -1
  25. package/dist/assets/index-9ajPMXBg.js +3097 -0
  26. package/dist/assets/{index-Bp8XE9A6.css → index-oXqzajWV.css} +1 -1
  27. package/dist/index.html +2 -2
  28. package/dist-web/app.css +1 -1
  29. package/dist-web/app.js +455 -427
  30. package/package.json +1 -1
  31. package/plugins/session-manager-dev/.claude-plugin/plugin.json +1 -1
  32. package/plugins/session-manager-dev/skills/maintaining-md-network/drift-check.md +15 -5
  33. package/plugins/session-manager-dev/skills/maintaining-md-network/scripts/drift-check.cjs +8 -4
  34. package/scripts/scheduler-mcp-server.cjs +71 -0
  35. package/src/main/agentLibrary.cjs +81 -29
  36. package/src/main/agentsIpc.cjs +21 -16
  37. package/src/main/build-info.json +4 -4
  38. package/src/main/index.cjs +9 -0
  39. package/src/main/ipcSchemas.cjs +35 -2
  40. package/src/main/lib/epic/epicMint.cjs +61 -6
  41. package/src/main/lib/epic/epicWorktreeMerge.cjs +11 -9
  42. package/src/main/lib/epic/epicWorktreeMint.cjs +45 -4
  43. package/src/main/lib/epic/promptSessionsCreateEpic.cjs +32 -5
  44. package/src/main/lib/epic/restorableSessions.cjs +749 -0
  45. package/src/main/lib/feedback-remote/projectHomeAdminRoutes.cjs +61 -0
  46. package/src/main/lib/feedback-remote/remoteIpcDispatch.cjs +4 -0
  47. package/src/main/lib/git/branchSweep.cjs +9 -3
  48. package/src/main/lib/git/gitExec.cjs +8 -1
  49. package/src/main/lib/git/gitWorktree.cjs +771 -96
  50. package/src/main/lib/git/jobWorktree.cjs +3 -0
  51. package/src/main/lib/git/jobWorktreeBootLive.cjs +14 -2
  52. package/src/main/lib/mcpToolCatalog.cjs +28 -0
  53. package/src/main/lib/mcpToolsProbe.cjs +831 -0
  54. package/src/main/lib/mdNetworkScan.cjs +555 -0
  55. package/src/main/lib/persona-macro/agentPersonaSchema.cjs +18 -5
  56. package/src/main/lib/persona-macro/builtinMacros.cjs +22 -4
  57. package/src/main/lib/persona-macro/macroJobDispatch.cjs +17 -2
  58. package/src/main/lib/persona-macro/shippedPersonaSeeds.cjs +38 -0
  59. package/src/main/lib/project-pages/competitiveMatrix.cjs +258 -0
  60. package/src/main/lib/project-pages/matrixHtml.cjs +239 -0
  61. package/src/main/lib/project-pages/matrixStore.cjs +112 -0
  62. package/src/main/lib/promptSessionSchema.cjs +5 -0
  63. package/src/main/lib/scheduler/fixPlanSlug.cjs +15 -1
  64. package/src/main/lib/scheduler/reaperHelpers.cjs +35 -0
  65. package/src/main/lib/scheduler/scheduleJobSchema.cjs +2 -0
  66. package/src/main/lib/scheduler/scheduleJobTransitions.cjs +8 -7
  67. package/src/main/lib/scheduler/terminalRunOutcome.cjs +61 -15
  68. package/src/main/projectPages.cjs +51 -7
  69. package/src/main/runVerify.cjs +8 -3
  70. package/src/main/scheduler/budget.cjs +146 -7
  71. package/src/main/scheduler/gitTreeGuard.cjs +92 -20
  72. package/src/main/scheduler/reviewLadder.cjs +60 -0
  73. package/src/main/scheduler.cjs +477 -53
  74. package/src/main/seedAgentPersonas.cjs +1 -1
  75. package/src/preload/api.d.ts +250 -7
  76. package/src/preload/apiSurface.json +28 -0
  77. package/src/preload/index.cjs +6 -0
  78. package/src/seed/agents/competitive-analyst.md +69 -0
  79. package/src/seed/agents/competitive-researcher.md +75 -0
  80. package/src/seed/agents/validator.md +2 -2
  81. package/dist/assets/AgentLibrary-Bfj862qf.js +0 -2
  82. package/dist/assets/Extensions-BziIutWV.js +0 -13
  83. package/dist/assets/Memory-Bq5T33d2.js +0 -25
  84. package/dist/assets/Scheduler-CkGHMXvo.js +0 -16
  85. package/dist/assets/Settings-DGxvyajs.js +0 -2
  86. package/dist/assets/SystemPrompt-CfozyVQx.js +0 -1
  87. package/dist/assets/ViewTabs-DFXH03tb.js +0 -1
  88. package/dist/assets/index-CuAfFXNd.js +0 -3086
@@ -72,11 +72,11 @@ const { shouldRunFlatSweep, FLAT_SWEEP_INTERVAL_MS } = require('./lib/scheduler/
72
72
  const { appendError } = require('./lib/telemetry/opsErrorLog.cjs');
73
73
  const { readTail } = require('./lib/util/fileTail.cjs');
74
74
  const {
75
- claudePidAlive, classifyRunOutcome, mapOutcomeToGateOutcome, ORPHAN_REQUEUE_CAP, selectReapableJobs,
75
+ claudePidAlive, classifyRunOutcome, resolveReapGateOutcome, ORPHAN_REQUEUE_CAP, selectReapableJobs,
76
76
  findLiveProcessForJob, logHasOutput, resolvePidlessGateOutcome, resolveCommitGuardOutcome,
77
77
  readSpawnedPidFromLog, readLogMtimeMs, isClaudeArgv,
78
78
  } = require('./lib/scheduler/reaperHelpers.cjs');
79
- const { resolveProjectRoot, ensureRuntimeIgnores } = require('./lib/opsOwnership.cjs');
79
+ const { resolveProjectRoot, ensureRuntimeIgnores, RUNTIME_NAMESPACES } = require('./lib/opsOwnership.cjs');
80
80
  const { sweepStrandedJobBranches } = require('./lib/git/branchSweep.cjs');
81
81
  const { detectRateLimitInLog } = require('./lib/claude/rateLimitDetect.cjs');
82
82
  const { stripAppOwnedChurn } = require('./lib/scheduler/jobDirtFilter.cjs');
@@ -116,7 +116,7 @@ const { hasDownstreamValidator } = require('./lib/prd/planValidator.cjs');
116
116
  const promptSessionTranscript = require('./promptSessionTranscript.cjs');
117
117
  const { verifyRun, parseLog, scanSentinel, scanForeignWipPathsClaim } = require('./runVerify.cjs');
118
118
  const { latestTerminalOutcomeForSlug, COMPLETED_EQUIVALENT_VERDICTS } = require('./lib/scheduler/terminalRunOutcome.cjs');
119
- const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan } = require('./lib/scheduler/fixPlanSlug.cjs');
119
+ const { isFixPlanSlug, classifyDiscoveredFixPlan, resolveIsFixPlan, fixPlanRecordPath } = require('./lib/scheduler/fixPlanSlug.cjs');
120
120
  const { landedSinceRun, landedOnMainSince } = require('./lib/scheduler/landedSinceRun.cjs');
121
121
  const { declaredPathsForPrd, issuedAtForPrd } = require('./lib/prd/prdDeclaredPaths.cjs');
122
122
  const { identity: procIdentityOf, isDifferentProcess } = require('./lib/process/procIdentity.cjs');
@@ -244,6 +244,8 @@ const RESULT_TAIL_BYTES = 8 * 1024;
244
244
  // boundary) — a real `result` string can be a full paragraph, so
245
245
  // extractResultTextFromLog scans more of the tail to find it whole.
246
246
  const RESULT_TEXT_TAIL_BYTES = 64 * 1024;
247
+ // Budget-kill context scan (describeBudgetKillContext) reads at most this much run log.
248
+ const BUDGET_KILL_LOG_TAIL_BYTES = 2 * 1024 * 1024;
247
249
 
248
250
  // Idle-output watchdog: if the log file mtime stops advancing for this long
249
251
  // while the process is still alive, the agent is hung mid-work (network
@@ -299,7 +301,10 @@ const BASH_MAX_TIMEOUT_MS = 900_000; // 15 min — must stay below IDLE_OUTPUT_K
299
301
  // Plain words on purpose: short sentences, one rule each, rule first, then
300
302
  // "Why:". Tests pin the load-bearing tokens (SYNCHRONOUSLY, background Bash,
301
303
  // Monitor, TaskOutput, ScheduleWakeup, "no later turn", `timeout <n>`,
302
- // `git add <path>`, the SCHEDULER_VERDICT lines) — keep them exact. No line
304
+ // `git add <path>`, the SCHEDULER_VERDICT lines, `/code-review medium --fix`
305
+ // and the "Never call /code-review with no level, or at xhigh, max or ultra"
306
+ // ban — PRD 2887: a level-less call took the session's max effort and outlived
307
+ // the job budget) — keep them exact. No line
303
308
  // of this text may START with SCHEDULER_VERDICT: or FOREIGN_WIP_PATHS: —
304
309
  // runVerify's scanners are line-anchored.
305
310
  function buildFinishHead(verifyStepNum) {
@@ -331,19 +336,40 @@ It covers every test, typecheck, lint and build command, while you build and whi
331
336
  `;
332
337
  }
333
338
 
334
- const FINISH_REVIEW_STEPS_IN_RUN = `1. CODE REVIEW — run \`/code-review --fix\` on your changes. Apply the fixes it finds,
335
- correctness first. If you think a finding is wrong, say why in your final report.
339
+ const FINISH_REVIEW_STEPS_IN_RUN = `1. CODE REVIEW — run \`/code-review medium --fix\` on your changes.
340
+ Always pass the level word medium.
341
+ Never call /code-review with no level, or at xhigh, max or ultra, in this run.
342
+ Why: with no level the skill uses this run's effort, and at max it starts 10 or
343
+ more review agents and runs 30+ minutes, longer than the job budget. The run is
344
+ killed before your verdict line.
345
+ Apply the fixes it finds, correctness first. If you think a finding is wrong, say why in your final report.
336
346
  Do not skip a finding silently. If \`/code-review\` is not available here,
337
347
  review your own diff with the same care.
338
348
  2. SECURITY REVIEW — run \`/security-review\` and fix every finding, or explain
339
349
  why it is safe. If it is not available, check your diff yourself for
340
350
  injection, secrets, path traversal and unsafe input handling.
351
+ A review command may tell you its report must be your final reply. In this run it is not.
352
+ Carry its findings into your final report and go on to the next step.
341
353
  `;
342
354
 
343
355
  const FINISH_REVIEW_STEP_DEFERRED = `1. REVIEW — skip it in this run. The plan's trailing validator job reviews code and security once, for the whole plan. Do NOT run /code-review or /security-review here.
344
356
  `;
345
357
 
346
- function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum }) {
358
+ // Runtime folders the COMMIT step bans outright, built from opsOwnership's
359
+ // RUNTIME_NAMESPACES so a new runtime namespace is banned with no edit here.
360
+ const FINISH_RUNTIME_FOLDERS = RUNTIME_NAMESPACES
361
+ .map((ns) => `session-manager-operations/${ns}/`).join(', ');
362
+
363
+ // Fix-plan-only VERDICT bullet: the scheduler already accepts a zero-edit fix
364
+ // plan's PASS (runVerify commitGuardVerdict's isFixPlanJob), so tell the
365
+ // executor so — otherwise "PASS needs a landed commit" pushes it into
366
+ // force-adding an ignored runtime record just to have something to commit.
367
+ const FINISH_FIX_PLAN_VERDICT_LINE = `
368
+ - This job is an auto fix plan.
369
+ An auto fix plan whose steps changed no file has nothing to commit
370
+ and prints PASS when the gate is green. Do not invent a commit to have one.`;
371
+
372
+ function buildFinishTail({ verifyStepNum, commitStepNum, verdictStepNum, isFixPlan = false }) {
347
373
  return `${verifyStepNum}. VERIFY — run every command in the PRD's \`# Gate\` section, in order, in the
348
374
  foreground. Each must exit 0. If the PRD has no \`# Gate\` section, run the
349
375
  project's own typecheck, lint and test commands instead. The project's
@@ -356,12 +382,20 @@ ${commitStepNum}. COMMIT — stage only the exact paths you created or changed f
356
382
  A blanket add puts their half-done work in your commit and breaks both
357
383
  jobs' verdicts. Always commit your own work: this rule changes what you
358
384
  stage, never whether you commit.
385
+ Never run \`git add -f\` or \`git add --force\` on a path git ignores, unless the
386
+ PRD's # Files section names that exact path. If git add refuses a path as
387
+ ignored, leave it out of the commit and name it in your final report.
388
+ Why: an ignored path is usually live runtime state, not work product.
389
+ Never commit any file under these folders, even when the PRD names it:
390
+ ${FINISH_RUNTIME_FOLDERS}
391
+ Why: those folders hold the app's live state. A commit of them breaks the
392
+ running scheduler for every checkout that pulls it.
359
393
  ${verdictStepNum}. VERDICT LINE — end your final report with exactly one of these lines.
360
394
  Put nothing after it, except the FOREIGN_WIP_PATHS line described below.
361
395
  SCHEDULER_VERDICT: PASS
362
396
  SCHEDULER_VERDICT: FAIL <one-line reason>
363
397
  SCHEDULER_VERDICT: BLOCKED_BY_FOREIGN_WIP
364
- - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.
398
+ - Print PASS only when the gate is green AND the commit from step ${commitStepNum} landed.${isFixPlan ? FINISH_FIX_PLAN_VERDICT_LINE : ''}
365
399
  - Print FAIL when the gate is red or the commit could not land. Also print
366
400
  FAIL when a step needs something this run cannot reach (live runtime
367
401
  state, credentials, an account or dashboard action, a host install): do
@@ -401,14 +435,17 @@ in your final report.`;
401
435
  * be re-reviewed once by the plan's own trailing validator job, so asking
402
436
  * every work-item to also run /code-review + /security-review inline is
403
437
  * redundant review work.
438
+ * `isFixPlan: true` (auto fix-plan jobs only) adds one VERDICT bullet: a fix
439
+ * plan that changed no file has nothing to commit and prints PASS on a green
440
+ * gate. Omitted/false leaves the text unchanged.
404
441
  */
405
- function buildFinishProtocol({ reviewInRun = true } = {}) {
442
+ function buildFinishProtocol({ reviewInRun = true, isFixPlan = false } = {}) {
406
443
  if (reviewInRun) {
407
444
  return buildFinishHead(3) + FINISH_REVIEW_STEPS_IN_RUN
408
- + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5 });
445
+ + buildFinishTail({ verifyStepNum: 3, commitStepNum: 4, verdictStepNum: 5, isFixPlan });
409
446
  }
410
447
  return buildFinishHead(2) + FINISH_REVIEW_STEP_DEFERRED
411
- + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4 });
448
+ + buildFinishTail({ verifyStepNum: 2, commitStepNum: 3, verdictStepNum: 4, isFixPlan });
412
449
  }
413
450
 
414
451
  const FINISH_PROTOCOL = buildFinishProtocol({ reviewInRun: true });
@@ -2976,6 +3013,8 @@ function resetJobFields(job, errorMsg, opts = {}) {
2976
3013
  // Like exitCode: this run's outcome, not durable across a reset — a stale
2977
3014
  // leak badge from a prior attempt must not linger once the job re-fires.
2978
3015
  delete job.leakedDescendants;
3016
+ // Same category — which phase a budget kill landed in is this run's outcome.
3017
+ delete job.budgetKillPhase;
2979
3018
  // A pending row is about to re-run fresh — a stale leftover badge or a
2980
3019
  // stale pre-run baseline from the attempt that just ended must not linger
2981
3020
  // and be mistaken for THIS (not-yet-run) attempt's own output. spawnJob
@@ -3131,9 +3170,24 @@ function isBootRowAlive(j, {
3131
3170
  * reconciliation even though the live reap path is now guarded. Callers
3132
3171
  * must resolve this (a git spawn) BEFORE calling mutate(), never inside it —
3133
3172
  * pass null when there is none (a 'success' then re-queues, unless artifact-only).
3173
+ *
3174
+ * `uncommittedSnapshot` ({ sha, ref } | null) is the commit the boot worktree
3175
+ * sweep pinned this row's uncommitted checkout work to before removing it
3176
+ * (PRD 2893). It is stamped on the row on every branch; a 'success' with no
3177
+ * landed commit whose only output is that snapshot parks needs_review rather
3178
+ * than re-queuing — a re-run would start from a clean tree and hide the work.
3134
3179
  */
3135
- function applyOrphanOutcome(job, outcome, killNote = '', confirmedLandedCommit = null) {
3180
+ function applyOrphanOutcome(job, outcome, killNote = '', confirmedLandedCommit = null, uncommittedSnapshot = null) {
3136
3181
  const now = new Date().toISOString();
3182
+ const snap = uncommittedSnapshot && uncommittedSnapshot.sha && uncommittedSnapshot.ref
3183
+ ? { sha: uncommittedSnapshot.sha, ref: uncommittedSnapshot.ref }
3184
+ : null;
3185
+ applyOrphanOutcomeInner(job, outcome, killNote, confirmedLandedCommit, snap, now);
3186
+ // Stamped after the branch so a reset (resetJobFields) can never drop it.
3187
+ if (snap) job.uncommittedSnapshot = snap;
3188
+ }
3189
+
3190
+ function applyOrphanOutcomeInner(job, outcome, killNote, confirmedLandedCommit, snap, now) {
3137
3191
  // A reported 'success' completes only on landed-commit evidence, or for a
3138
3192
  // DECLARED artifact-only PRD (`deliverable: artifact` + artifactPaths — same
3139
3193
  // check as runVerify's artifact exemption) where no commit is legitimate.
@@ -3149,6 +3203,13 @@ function applyOrphanOutcome(job, outcome, killNote = '', confirmedLandedCommit =
3149
3203
  job.error = null;
3150
3204
  job.finishedAt = now;
3151
3205
  delete job.runtime;
3206
+ } else if (outcome === 'success' && snap) {
3207
+ const reason = `boot orphan reconciliation: run reported success but no landed commit was found; its uncommitted worktree work was kept as ${snap.sha} (${snap.ref})${killNote}`;
3208
+ transitionJob(job, 'needs_review', { reason, source: 'applyOrphanOutcome:uncommitted' });
3209
+ job.verifierVerdict = 'uncommitted_changes';
3210
+ job.error = reason;
3211
+ job.finishedAt = now;
3212
+ delete job.runtime;
3152
3213
  } else if (outcome === 'failed') {
3153
3214
  if (confirmedLandedCommit) {
3154
3215
  transitionJob(job, 'completed', { reason: `orphaned: app restarted while running${killNote}, but landedCommit ${confirmedLandedCommit} resolves — completed on evidence`, source: 'applyOrphanOutcome:landed' });
@@ -4172,12 +4233,15 @@ function stampIntegrationFailure(row, integration) {
4172
4233
  else delete row.integrationExpectedBranch;
4173
4234
  if (integration.actualBranch) row.integrationActualBranch = integration.actualBranch;
4174
4235
  else delete row.integrationActualBranch;
4236
+ if (integration.baseRewritten) row.integrationBaseRewritten = true;
4237
+ else delete row.integrationBaseRewritten;
4175
4238
  } else {
4176
4239
  delete row.integrationFailureKind;
4177
4240
  delete row.integrationConflictPaths;
4178
4241
  delete row.integrationBaseHeadSha;
4179
4242
  delete row.integrationExpectedBranch;
4180
4243
  delete row.integrationActualBranch;
4244
+ delete row.integrationBaseRewritten;
4181
4245
  }
4182
4246
  }
4183
4247
 
@@ -4217,6 +4281,11 @@ async function resolveHeadShasForPass(jobs) {
4217
4281
  async function performMechanicalRecovery(job, target) {
4218
4282
  const integration = await jobWorktree.integrateJobBranch({
4219
4283
  cwd: target.cwd, branch: target.branch, slug: target.slug, carriedPaths: target.carriedPaths, baseBranch: target.baseBranch, allowRefLanding: true,
4284
+ // The branch's fork point, so a base rebased since the failure replays only
4285
+ // the job's own commits. Older rows fall back to the branch reflog.
4286
+ forkSha: typeof jobWorktree.resolveForkSha === 'function'
4287
+ ? await jobWorktree.resolveForkSha({ cwd: target.cwd, branch: target.branch, recorded: target.forkSha })
4288
+ : null,
4220
4289
  });
4221
4290
  if (integration.ok) {
4222
4291
  await jobWorktree.cleanupJobWorktree({ cwd: target.cwd, dir: undefined, branch: target.branch, keepBranch: false });
@@ -4811,7 +4880,7 @@ async function executeJob(job, runDir, defaultCwd, onPid, execCwd, resumeTarget
4811
4880
  // Always route through composeExecutorPrompt (even with an empty digest)
4812
4881
  // so the finish protocol is appended in the prompt's tail exactly once,
4813
4882
  // after any digest fence rather than concatenated ahead of it.
4814
- prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun }) });
4883
+ prompt = composeExecutorPrompt({ prdBody: prompt, digestText, finishProtocol: buildFinishProtocol({ reviewInRun, isFixPlan: resolveIsFixPlan(job.slug, job.isFixPlan) }) });
4815
4884
 
4816
4885
  // Foreign-WIP manifest (starry-night-ships PRD 148 postmortem): the
4817
4886
  // scheduler already knows, at spawn time, which dirty paths this job did
@@ -5292,7 +5361,22 @@ function healTargetForFix(fixSlug, jobs) {
5292
5361
  * unit-tested (no spawn, no fs). Inputs are the already-resolved values that
5293
5362
  * spawnInvestigation computes.
5294
5363
  */
5295
- function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild = null }) {
5364
+ function buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild = null, recordPath = null, recordIgnored = true }) {
5365
+ const runtimePaths = RUNTIME_NAMESPACES.map((ns) => `session-manager-operations/${ns}/`).join(', ');
5366
+ const recordRule = (recordPath && !recordIgnored)
5367
+ ? `- The only allowed record location is ${recordPath}. If the fix plan asks for a record file, it must be exactly this path.
5368
+ - Stage the record with plain \`git add ${recordPath}\`.`
5369
+ : recordPath
5370
+ ? '- This repo\'s .gitignore ignores the fix-plan record path, so the fix plan must not ask for any record file.'
5371
+ : '- No record path is available for this repo, so the fix plan must not ask for any record file.';
5372
+ const recordsSection = `
5373
+
5374
+ # Records and commits
5375
+ ${recordRule}
5376
+ - A fix plan that only confirms already-landed work changes no file and makes no commit.
5377
+ - The scheduler closes such a fix plan on a truthful SCHEDULER_VERDICT: PASS with no commit, so never add a record just so the job can close.
5378
+ - Never name any of these paths as a file to write or commit (machine-local runtime state): ${runtimePaths}
5379
+ - Never tell the executor to run \`git add -f\` or \`git add --force\`.`;
5296
5380
  const deadFixChildNote = deadChild ? `
5297
5381
 
5298
5382
  # This is a REOPENED investigation — your own prior fix plan died
@@ -5426,7 +5510,7 @@ ${logTail}
5426
5510
  In that case LEAD the fix-plan PRD by quoting VERBATIM the canonical rule from standards.md's
5427
5511
  Execution discipline section — "You ARE the executor — never re-queue or self-schedule" — rather
5428
5512
  than authoring new prose. Instruct the fix-plan's executor plainly that a queued PRD is the task,
5429
- not evidence of completion, and that the deliverable is the code diff.
5513
+ not evidence of completion, and that the deliverable is the code diff.${recordsSection}
5430
5514
 
5431
5515
  DO NOT attempt the fix. ONLY write the file. When the file exists, exit immediately.`;
5432
5516
  }
@@ -5614,7 +5698,19 @@ async function spawnInvestigation(failedJob, runDir, { deadChild = null } = {})
5614
5698
  console.warn(`[scheduler] investigation cwd is not a git repo (${cwd}); falling back to ${DEFAULT_PROJECT_CWD}`);
5615
5699
  cwd = DEFAULT_PROJECT_CWD;
5616
5700
  }
5617
- const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild });
5701
+ // The one record path a fix plan may name (PRD 2883), and whether the target
5702
+ // repo ignores it — several sibling repos ignore all of
5703
+ // session-manager-operations/, so it is checked, never assumed tracked.
5704
+ // exit 0 = ignored, exit 1 = not ignored, anything else = treat as ignored.
5705
+ const recordPath = fixPlanRecordPath(failedJob.epicId, fixSlug);
5706
+ let recordIgnored = true;
5707
+ try {
5708
+ await sharedGitExec.execGit(cwd, ['check-ignore', '-q', '--no-index', '--', recordPath], { timeout: 10000 });
5709
+ recordIgnored = true;
5710
+ } catch (err) {
5711
+ recordIgnored = !(err && err.code === 1);
5712
+ }
5713
+ const prompt = buildInvestigationPrompt({ failedJob, cwd, failedLogPath, originalBody, logTail, fixPath, group, deadChild, recordPath, recordIgnored });
5618
5714
 
5619
5715
  // Phase 1: open log fd for pre-spawn diagnostics.
5620
5716
  const { fd, safeLog, closeFd } = openLog(investigationLogPath);
@@ -5993,7 +6089,8 @@ function reportSchedulerError(message, slug, e) {
5993
6089
  * the job can never be left `running`. The branch is kept on every failure.
5994
6090
  * @returns {Promise<{worktreeLeftoverDirty: string[], salvagePatch: string|null,
5995
6091
  * worktreeIntegrationFailure: string|null, worktreeIntegrationDetail: object|null,
5996
- * mergeAutoResolved: string|null, mergeAutoResolvedPaths: string[]|null}>}
6092
+ * mergeAutoResolved: string|null, mergeAutoResolvedPaths: string[]|null,
6093
+ * uncommittedSnapshot: {sha: string, ref: string}|null}>}
5997
6094
  */
5998
6095
  async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardCwd, carriedPaths, deps = {} }) {
5999
6096
  const jw = deps.jobWorktree || jobWorktree;
@@ -6007,6 +6104,15 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6007
6104
  let mergeAutoResolved = null;
6008
6105
  let mergeAutoResolvedPaths = null;
6009
6106
  let integratedSha = null;
6107
+ // The removal pins any uncommitted work as refs/sm-uncommitted/... before
6108
+ // deleting the checkout (PRD 2891); surfaced so spawnJob stamps it (PRD 2893).
6109
+ let uncommittedSnapshot = null;
6110
+ const cleanup = async (args) => {
6111
+ const res = await jw.cleanupJobWorktree(args);
6112
+ const snap = res && res.snapshot;
6113
+ if (snap && snap.sha && snap.ref) uncommittedSnapshot = { sha: snap.sha, ref: snap.ref };
6114
+ return res;
6115
+ };
6010
6116
  const worktreeHead = { action: 'unknown', finalHead: null, stranded: [] };
6011
6117
  const addStranded = (list) => {
6012
6118
  for (const c of Array.isArray(list) ? list : []) {
@@ -6050,16 +6156,16 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6050
6156
  // Cancelled mid-run: keep the commit on the job branch only.
6051
6157
  appendAuditEvent('job_cancel_integration_skipped', { slug: job.slug, runId, branch: worktree.branch });
6052
6158
  await pinUnlanded();
6053
- await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6054
- return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead };
6159
+ await cleanup({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6160
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: true, worktreeHead, uncommittedSnapshot };
6055
6161
  }
6056
6162
  if (worktreeHead.action === 'diverged') {
6057
6163
  console.error(`[scheduler] ${job.slug}: worktree HEAD diverged from ${worktree.branch} — not integrating; commit pinned`);
6058
6164
  await pinUnlanded();
6059
- await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6060
- return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: false, worktreeHead };
6165
+ await cleanup({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6166
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha: null, cancelled: false, worktreeHead, uncommittedSnapshot };
6061
6167
  }
6062
- const integration = await jw.integrateJobBranch({ cwd: guardCwd, branch: worktree.branch, slug: job.slug, carriedPaths, baseBranch: worktree.baseBranch });
6168
+ const integration = await jw.integrateJobBranch({ cwd: guardCwd, branch: worktree.branch, slug: job.slug, carriedPaths, baseBranch: worktree.baseBranch, forkSha: worktree.forkSha || null });
6063
6169
  if (integration.ok && integration.reason === 'carried-wip-only') {
6064
6170
  console.log(`[scheduler] ${job.slug}: worktree branch ${worktree.branch} touched only carried base WIP paths — skipping merge (carried-wip-only)`);
6065
6171
  }
@@ -6077,7 +6183,7 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6077
6183
  }
6078
6184
  }
6079
6185
  if (!integration.ok || !integration.integrated) await pinUnlanded();
6080
- await jw.cleanupJobWorktree({
6186
+ await cleanup({
6081
6187
  cwd: guardCwd,
6082
6188
  dir: worktree.dir,
6083
6189
  branch: worktree.branch,
@@ -6088,10 +6194,10 @@ async function finalizeJobWorktree({ job, runId = null, runDir, worktree, guardC
6088
6194
  report('spawnJob worktree finalize failed', job.slug, e);
6089
6195
  // Best-effort: release the checkout + worktree-cap slot, keep the branch.
6090
6196
  try {
6091
- await jw.cleanupJobWorktree({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6197
+ await cleanup({ cwd: guardCwd, dir: worktree.dir, branch: worktree.branch, keepBranch: true });
6092
6198
  } catch { /* already reported above */ }
6093
6199
  }
6094
- return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, cancelled: false, worktreeHead };
6200
+ return { worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, cancelled: false, worktreeHead, uncommittedSnapshot };
6095
6201
  }
6096
6202
 
6097
6203
  /**
@@ -6508,12 +6614,18 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6508
6614
  // recovery retries integration against the SAME target, not whatever `cwd`
6509
6615
  // happens to sit on by then.
6510
6616
  const worktreeBaseBranch = (worktree.ok && typeof worktree.baseBranch === 'string' && worktree.baseBranch) ? worktree.baseBranch : null;
6617
+ // forkSha (createWorktree) — the exact commit the checkout forked from, so
6618
+ // a later mechanical recovery can land only the job's own commits after the
6619
+ // base branch was rewritten (rebased) while it ran.
6620
+ const worktreeForkSha = (worktree.ok && typeof worktree.forkSha === 'string' && worktree.forkSha) ? worktree.forkSha : null;
6511
6621
  await mutate((s) => {
6512
6622
  const idx = s.jobs.findIndex((x) => x.slug === job.slug);
6513
6623
  if (idx < 0) return;
6514
6624
  if (carriedPaths.length) s.jobs[idx].carriedPaths = carriedPaths;
6515
6625
  if (worktreeBaseBranch) s.jobs[idx].worktreeBaseBranch = worktreeBaseBranch;
6516
6626
  else delete s.jobs[idx].worktreeBaseBranch;
6627
+ if (worktreeForkSha) s.jobs[idx].worktreeForkSha = worktreeForkSha;
6628
+ else delete s.jobs[idx].worktreeForkSha;
6517
6629
  });
6518
6630
 
6519
6631
  // Integrate the job's branch back into guardCwd's own HEAD, THEN tear the
@@ -6545,6 +6657,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6545
6657
  // shape for the whole run). Named generically (not "worktree...") because
6546
6658
  // an in-place run salvages one too (PRD 1098).
6547
6659
  let salvagePatch = null;
6660
+ let uncommittedSnapshot = null;
6548
6661
  // Which foreign-WIP shape applies to THIS run: an isolated worktree only
6549
6662
  // ever needs to disclose carriedPaths (its checkout starts clean apart
6550
6663
  // from those carried paths); an in-place/shared-tree run discloses the
@@ -6575,7 +6688,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
6575
6688
  }, reviewInRun, worktree.ok ? worktree.setup : { ran: false, ok: false, reason: 'in-place', waitedMs: 0, ms: 0, commands: [] });
6576
6689
  } finally {
6577
6690
  if (worktree.ok) {
6578
- ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead } =
6691
+ ({ worktreeLeftoverDirty, salvagePatch, worktreeIntegrationFailure, worktreeIntegrationDetail, mergeAutoResolved, mergeAutoResolvedPaths, integratedSha, worktreeHead, uncommittedSnapshot } =
6579
6692
  await finalizeJobWorktree({ job, runId, runDir, worktree, guardCwd, carriedPaths }));
6580
6693
  } else {
6581
6694
  // In-place run (non-git cwd, cap reached, env-disabled, or a carry-over
@@ -7027,6 +7140,32 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7027
7140
  }
7028
7141
  }
7029
7142
 
7143
+ // Budget-kill context (PRD 2888): did the kill land inside the
7144
+ // finish-protocol review Skill call, and what had already landed/run?
7145
+ // IO here (bounded log tail + bounded git log); the parse is pure in
7146
+ // budget.describeBudgetKillContext. Any failure → null → today's reason.
7147
+ let budgetKillContext = null;
7148
+ if (res.killedByWatchdog === 'budget') {
7149
+ try {
7150
+ const tail = readTail(path.join(runDir, `${job.slug}.log`), BUDGET_KILL_LOG_TAIL_BYTES);
7151
+ budgetKillContext = tail ? budget.describeBudgetKillContext(tail) : null;
7152
+ } catch {
7153
+ budgetKillContext = null;
7154
+ }
7155
+ const landedForContext = sigtermLandedCommitEvidence || plainExitLandedCommitEvidence;
7156
+ if (budgetKillContext && budgetKillContext.inFinishReview && landedForContext && guardHeadBefore) {
7157
+ try {
7158
+ const out = await execGitAt(guardCwd, ['log', '-n', '5', '--format=%H %s', `${guardHeadBefore}..${landedForContext}`], { timeout: 10_000 });
7159
+ budgetKillContext.commits = String(out).split('\n').filter(Boolean).map((l) => {
7160
+ const sp = l.indexOf(' ');
7161
+ return sp < 0 ? { sha: l, subject: '' } : { sha: l.slice(0, sp), subject: l.slice(sp + 1) };
7162
+ });
7163
+ } catch {
7164
+ budgetKillContext.commits = null; // classifyBudgetKill falls back to the landed sha alone
7165
+ }
7166
+ }
7167
+ }
7168
+
7030
7169
  let actuallyFailed = false;
7031
7170
  let failedJobSnapshot = null;
7032
7171
  let needsInvestigationNow = false;
@@ -7106,7 +7245,8 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7106
7245
  // sigtermLandedCommitEvidence/plainExitLandedCommitEvidence, whichever
7107
7246
  // this exit code populated) still adjudicated on git evidence rather
7108
7247
  // than discarded. See classifyBudgetKill's own header.
7109
- const budgetKill = budget.classifyBudgetKill(res, sigtermLandedCommitEvidence || plainExitLandedCommitEvidence);
7248
+ const budgetKill = budget.classifyBudgetKill(res, sigtermLandedCommitEvidence || plainExitLandedCommitEvidence, budgetKillContext);
7249
+ delete s.jobs[i2].budgetKillPhase;
7110
7250
  const sigtermOverride = (!budgetKill && res.exitCode !== 0)
7111
7251
  ? gitTreeGuard.classifySigtermWithCommit(res.exitCode, sigtermCommitFound)
7112
7252
  : null;
@@ -7128,6 +7268,7 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7128
7268
  effectiveStatus = budgetKill.status;
7129
7269
  sigtermOverrideReason = budgetKill.reason;
7130
7270
  s.jobs[i2].verifierVerdict = 'budget_exceeded';
7271
+ if (budgetKillContext && budgetKillContext.inFinishReview) s.jobs[i2].budgetKillPhase = 'finish-review';
7131
7272
  if (budgetKill.landedCommit) jobLandedCommitThisRun = budgetKill.landedCommit;
7132
7273
  } else if (sigtermOverride) {
7133
7274
  effectiveStatus = sigtermOverride.status;
@@ -7265,6 +7406,11 @@ async function spawnJob(job, runId, runDir, defaultCwd, resumeTarget = null, sib
7265
7406
  } else {
7266
7407
  delete s.jobs[i2].salvagePatch;
7267
7408
  }
7409
+ if (uncommittedSnapshot) {
7410
+ s.jobs[i2].uncommittedSnapshot = uncommittedSnapshot;
7411
+ } else {
7412
+ delete s.jobs[i2].uncommittedSnapshot;
7413
+ }
7268
7414
  // Closed-set outcome taxonomy (issue #11 list A2) so a queue row
7269
7415
  // says WHY it ended without anyone opening the transcript.
7270
7416
  s.jobs[i2].terminalReason = launchFailure.deriveTerminalReason({
@@ -8632,7 +8778,7 @@ async function reapDeadRunningJobs() {
8632
8778
  // THIS slug have any artifact in there" — reused rather than
8633
8779
  // re-derived so a phantom link never survives the reap.
8634
8780
  const hasOwnArtifact = pidless ? logHasOutput(logPath) : true;
8635
- const gateOutcome = pidless ? resolvePidlessGateOutcome(outcome, hasOwnArtifact) : mapOutcomeToGateOutcome(outcome);
8781
+ const gateOutcome = pidless ? resolvePidlessGateOutcome(outcome, hasOwnArtifact) : resolveReapGateOutcome(outcome, extractResultTextFromLog(logPath));
8636
8782
  dead.push({ slug, pid, outcome, gateOutcome, pidless, reason, logPath, noOwnArtifact: pidless && !hasOwnArtifact, failureOverride });
8637
8783
  }
8638
8784
 
@@ -8709,12 +8855,17 @@ async function reapDeadRunningJobs() {
8709
8855
  headReconcile = await jobWorktree.reconcileWorktreeHead({ cwd: rowCwd, dir: wtDir, branch, key: d.slug });
8710
8856
  } catch { headReconcile = null; }
8711
8857
  }
8712
- const integrated = await gitTreeGuard.isBranchAlreadyIntegrated(rowCwd, branch);
8858
+ // The branch's fork point bounds the landed-content proof (and the
8859
+ // integration below) to the job's own commits, so a base rebased while
8860
+ // the run was adopted never reads the base's rewritten commits as work.
8861
+ const forkSha = await jobWorktree.resolveForkSha({ cwd: rowCwd, branch, recorded: row.worktreeForkSha || null });
8862
+ const integrated = await gitTreeGuard.isBranchAlreadyIntegrated(rowCwd, branch, forkSha);
8713
8863
  const headNow = await gitTreeGuard.gitHead(rowCwd);
8714
8864
  const guardHeadBeforeVal = row.guardHeadBefore || null;
8715
8865
  let landedCommit = null;
8716
8866
  let notLandedInfo = null;
8717
8867
  let effectiveSuccess = true;
8868
+ let integrationDetail = null;
8718
8869
  // The boot sweep runs before this reaper and removes the worktree, pinning
8719
8870
  // its unique commits; the branch then sits at the fork point and reads as
8720
8871
  // integrated. Consult the job's own pins so that case parks instead.
@@ -8725,6 +8876,50 @@ async function reapDeadRunningJobs() {
8725
8876
  cwd: rowCwd, key: d.slug, sinceMs: Number.isFinite(startedMs) ? startedMs : 0,
8726
8877
  });
8727
8878
  } catch { strandedPins = []; }
8879
+ // Commit-guard evidence for a worktree run (PRD 2892): an sm-job branch
8880
+ // that never left its base reads as integrated, so a zero-commit run
8881
+ // with real uncommitted work (Bilko 1685) would otherwise complete.
8882
+ // Mirrors finalizeJobWorktree: salvage first, then drop carried WIP the
8883
+ // run left byte-identical, then pin the work before the checkout goes.
8884
+ let dirt = null;
8885
+ let salvagePatch = null;
8886
+ let uncommittedSnapshot = null;
8887
+ let runMadeCommit = null;
8888
+ const hasCheckout = integrated !== null && typeof wtDir === 'string' && wtDir && wtDir !== rowCwd && fs.existsSync(wtDir);
8889
+ if (hasCheckout) {
8890
+ try {
8891
+ const raw = await gitTreeGuard.uncommittedChanges(wtDir);
8892
+ if (Array.isArray(raw)) {
8893
+ dirt = stripAppOwnedChurn(raw);
8894
+ if (dirt.length && Array.isArray(row.carriedPaths) && row.carriedPaths.length) {
8895
+ const same = new Set(await jobWorktree.unchangedCarriedPaths({ cwd: rowCwd, dir: wtDir, paths: row.carriedPaths }));
8896
+ if (same.size) dirt = dirt.filter((p) => !same.has(p));
8897
+ }
8898
+ }
8899
+ if (dirt && dirt.length) {
8900
+ if (row.runId) {
8901
+ const salvagePath = path.join(schedulerPaths.runsDir(), row.runId, `${d.slug}.uncommitted.patch`);
8902
+ const salvage = await jobWorktree.salvageJobWorktreeDiff({ dir: wtDir, outFile: salvagePath });
8903
+ if (salvage && salvage.ok) {
8904
+ salvagePatch = salvagePath;
8905
+ console.log(`[scheduler] reapDeadRunningJobs: salvaged ${salvage.bytes} byte(s) of uncommitted worktree diff for ${d.slug} to ${salvagePath}`);
8906
+ }
8907
+ }
8908
+ const snap = await jobWorktree.snapshotUncommittedWork({ cwd: rowCwd, dir: wtDir, key: d.slug });
8909
+ if (snap && snap.sha && snap.ref) uncommittedSnapshot = { sha: snap.sha, ref: snap.ref };
8910
+ else if (snap && snap.error) console.error(`[scheduler] reapDeadRunningJobs: uncommitted snapshot failed for ${d.slug}: ${snap.error}`);
8911
+ }
8912
+ } catch (e) {
8913
+ console.error(`[scheduler] reapDeadRunningJobs: worktree salvage failed for ${d.slug}`, e);
8914
+ }
8915
+ const commitCount = await jobWorktree.worktreeRunCommitCount({ dir: wtDir });
8916
+ if (commitCount >= 0) {
8917
+ runMadeCommit = commitCount > 0
8918
+ || headReconcile?.action === 'fast-forwarded'
8919
+ || headReconcile?.action === 'diverged'
8920
+ || strandedPins.length > 0;
8921
+ }
8922
+ }
8728
8923
  const pinVerdict = headReconcile?.action === 'diverged'
8729
8924
  ? null
8730
8925
  : gitTreeGuard.strandedCommitVerdict({ worktreeHead: { stranded: strandedPins }, landedCommit: null });
@@ -8755,19 +8950,82 @@ async function reapDeadRunningJobs() {
8755
8950
  }
8756
8951
  } else if (integrated === true) {
8757
8952
  if (guardHeadBeforeVal && headNow && headNow !== guardHeadBeforeVal) landedCommit = headNow;
8953
+ // spawnJob's commit guard, applied to the adopted run (PRD 2892). A
8954
+ // -1 commit count or a missing checkout (runMadeCommit null) or an
8955
+ // unreadable status (dirt null) keeps the pre-guard behaviour.
8956
+ if (runMadeCommit !== null && dirt !== null) {
8957
+ const artifactPaths = row.artifactPaths;
8958
+ const guardVerdict = commitGuardVerdict({
8959
+ newlyDirty: dirt,
8960
+ siblingRunning: false,
8961
+ ranInWorktree: true,
8962
+ jobSelfCommitted: runMadeCommit,
8963
+ legitimateNoOp: false,
8964
+ isFixPlanJob: resolveIsFixPlan(d.slug, row.isFixPlan),
8965
+ artifactVerified: row.deliverable === 'artifact' && Array.isArray(artifactPaths) && artifactPaths.length > 0,
8966
+ verifyResult: null,
8967
+ salvagePatch,
8968
+ });
8969
+ if (guardVerdict) {
8970
+ const satisfyingCommits = guardVerdict.verdict === 'silent_no_op'
8971
+ ? await findSatisfyingCommitOnMain(row)
8972
+ : [];
8973
+ const finalVerdict = resolveCommitGuardOutcome(guardVerdict, satisfyingCommits);
8974
+ if (finalVerdict.verdict !== 'already_satisfied_on_main') {
8975
+ effectiveSuccess = false;
8976
+ landedCommit = null;
8977
+ notLandedInfo = { verdict: finalVerdict.verdict, reason: finalVerdict.reason };
8978
+ console.log(`[scheduler] reapDeadRunningJobs commit-guard: ${d.slug} ${finalVerdict.verdict} → needs_review`);
8979
+ } else {
8980
+ console.log(`[scheduler] reapDeadRunningJobs already-satisfied-on-main: ${d.slug} → completed (${finalVerdict.satisfyingSha})`);
8981
+ }
8982
+ }
8983
+ }
8984
+ } else if (d.gateOutcome === 'passed') {
8985
+ // Branch still holds work HEAD lacks, and the run printed its own
8986
+ // SCHEDULER_VERDICT: PASS line (resolveReapGateOutcome): land it now,
8987
+ // fork-bounded, exactly as finalizeJobWorktree would have (Bilko PRD
8988
+ // 1716 committed, passed, and was parked only because its scheduler
8989
+ // restarted). Git work stays here, outside mutate(). Dirt was already
8990
+ // salvaged/snapshotted above.
8991
+ const integration = await jobWorktree.integrateJobBranch({
8992
+ cwd: rowCwd,
8993
+ branch,
8994
+ slug: d.slug,
8995
+ carriedPaths: row.carriedPaths || [],
8996
+ baseBranch: row.worktreeBaseBranch || undefined,
8997
+ forkSha,
8998
+ });
8999
+ integrationDetail = integration;
9000
+ if (integration && integration.ok) {
9001
+ landedCommit = integration.sha || (await gitTreeGuard.gitHead(rowCwd)) || null;
9002
+ notLandedInfo = null;
9003
+ effectiveSuccess = true;
9004
+ const checkoutDir = typeof wtDir === 'string' && wtDir && wtDir !== rowCwd && fs.existsSync(wtDir) ? wtDir : undefined;
9005
+ await jobWorktree.cleanupJobWorktree({ cwd: rowCwd, dir: checkoutDir, branch, keepBranch: false });
9006
+ console.log(`[scheduler] reapDeadRunningJobs: integrated ${branch} for PASS run ${d.slug} → ${landedCommit || 'HEAD'}`);
9007
+ } else {
9008
+ effectiveSuccess = false;
9009
+ const failure = (integration && integration.reason) || 'integration failed';
9010
+ notLandedInfo = {
9011
+ verdict: 'worktree_integration_failed',
9012
+ reason: worktreeIntegrationVerdict({ failure, detail: integration, slug: d.slug }).reason,
9013
+ };
9014
+ console.log(`[scheduler] reapDeadRunningJobs: integration of ${branch} failed for ${d.slug}: ${failure}`);
9015
+ }
8758
9016
  } else {
8759
- // Branch exists and still holds commits never merged into rowCwd's
8760
- // HEAD — the exact PRD 1118 shape. Never merge it here (see
8761
- // isBranchAlreadyIntegrated's header comment); park for review
8762
- // instead, naming the branch so the work is easy to find and land by
8763
- // hand or via mechanical recovery.
9017
+ // Branch still holds commits never merged into rowCwd's HEAD and the
9018
+ // run printed no PASS line of its own — the PRD 1118 shape. Land only
9019
+ // on the run's own PASS line (above); otherwise park for review,
9020
+ // naming the branch so the work is easy to find and land by hand or
9021
+ // via mechanical recovery.
8764
9022
  effectiveSuccess = false;
8765
9023
  notLandedInfo = {
8766
9024
  verdict: 'reaped_without_integration',
8767
9025
  reason: `worktree branch ${branch} still holds unintegrated work — never merged into ${rowCwd}`,
8768
9026
  };
8769
9027
  }
8770
- integrationResults.set(d.slug, { effectiveSuccess, landedCommit, notLandedInfo });
9028
+ integrationResults.set(d.slug, { effectiveSuccess, landedCommit, notLandedInfo, dirt, salvagePatch, uncommittedSnapshot, integrationDetail });
8771
9029
  }
8772
9030
 
8773
9031
  // Evidence-before-failure guard for a row about to be stamped 'failed'
@@ -8938,6 +9196,13 @@ async function reapDeadRunningJobs() {
8938
9196
  } else {
8939
9197
  delete s.jobs[idx].verifierVerdict;
8940
9198
  }
9199
+ // A PASS run whose reap-time integration failed (above) carries the
9200
+ // failure subtype + conflicted paths, so mechanical recovery can
9201
+ // retry once HEAD moves.
9202
+ const reapIntegration = integrationResults.get(slug)?.integrationDetail || null;
9203
+ if (reapIntegration && notLandedInfo?.verdict === 'worktree_integration_failed') {
9204
+ stampIntegrationFailure(s.jobs[idx], reapIntegration);
9205
+ }
8941
9206
  transitionJob(s.jobs[idx], targetStatus, { reason: transitionReason, source });
8942
9207
  s.jobs[idx].exitCode = landed ? 0 : (s.jobs[idx].exitCode ?? 1);
8943
9208
  s.jobs[idx].finishedAt = new Date().toISOString();
@@ -8966,7 +9231,16 @@ async function reapDeadRunningJobs() {
8966
9231
  delete s.jobs[idx].overrun;
8967
9232
  delete s.jobs[idx].guardBaseline;
8968
9233
  delete s.jobs[idx].guardHeadBefore;
8969
- applyLeftoverFields(s.jobs[idx], deltaPaths);
9234
+ // A worktree run's checkout dirt (PRD 2892) wins over the in-place
9235
+ // baseline delta, which only ever sees the main tree.
9236
+ const wtEvidence = success && !rateLimited ? integrationResults.get(slug) : null;
9237
+ if (wtEvidence && Array.isArray(wtEvidence.dirt) && wtEvidence.dirt.length) {
9238
+ if (wtEvidence.salvagePatch) s.jobs[idx].salvagePatch = wtEvidence.salvagePatch;
9239
+ if (wtEvidence.uncommittedSnapshot) s.jobs[idx].uncommittedSnapshot = wtEvidence.uncommittedSnapshot;
9240
+ applyLeftoverFields(s.jobs[idx], wtEvidence.dirt);
9241
+ } else {
9242
+ applyLeftoverFields(s.jobs[idx], deltaPaths);
9243
+ }
8970
9244
  runningSet.delete(slug);
8971
9245
  // A dead job reaped here never reached spawnJob's own finally block
8972
9246
  // (that's this reaper's whole reason to exist — see its header
@@ -9409,9 +9683,14 @@ function applyRcaClassification(job, report) {
9409
9683
  * independent of whether it appears in `pathCommits` — it is definitionally
9410
9684
  * this job's own work, not something discovered by scanning history.
9411
9685
  * 2. 'job branch' — a path-overlapping commit reachable from (an ancestor of
9412
- * or equal to) this job's own `sm-job/<slug>` branch tip. Still
9413
- * job-specific even though it IS a `git log` scan: a sibling's commit can
9414
- * never be an ancestor of THIS job's own branch ref. In practice this
9686
+ * or equal to) this job's own `sm-job/<slug>` branch tip, or a copy of
9687
+ * one of that branch's commits that linear landing replayed onto the
9688
+ * base: same author name, author email, author date and message as a
9689
+ * commit in `git log <sha>..sm-job/<slug>`, at most 200 of them read
9690
+ * (gitTreeGuard.commitsReplayedFromBranch). Still job-specific even
9691
+ * though it IS a `git log` scan: a sibling's commit can never be an
9692
+ * ancestor of THIS job's own branch ref, nor share all four of those
9693
+ * fields with one of its commits. In practice this
9415
9694
  * branch is deleted on successful integration (gitWorktree.cjs's
9416
9695
  * `cleanupWorktree`), so this mainly fires when integration failed and
9417
9696
  * the branch was deliberately kept for recovery, or reverify runs before
@@ -9437,13 +9716,19 @@ async function attributeLandedCommits(job, pathCommits, cwd) {
9437
9716
  }
9438
9717
 
9439
9718
  const branch = `sm-job/${job?.slug}`;
9440
- const branchCommits = [];
9719
+ const ancestors = new Set();
9441
9720
  for (const sha of pathCommits) {
9442
9721
  try {
9443
9722
  await execGitAt(cwd, ['merge-base', '--is-ancestor', sha, branch], { timeout: 10_000 });
9444
- branchCommits.push(sha);
9723
+ ancestors.add(sha);
9445
9724
  } catch { /* not an ancestor of this job's own branch, or branch doesn't exist */ }
9446
9725
  }
9726
+ // Linear landing put this job's own commits on the base as replayed copies,
9727
+ // which are never ancestors of the branch.
9728
+ const replayed = await gitTreeGuard.commitsReplayedFromBranch(
9729
+ cwd, pathCommits.filter((sha) => !ancestors.has(sha)), branch,
9730
+ );
9731
+ const branchCommits = pathCommits.filter((sha) => ancestors.has(sha) || replayed.has(sha));
9447
9732
  if (branchCommits.length) return { commits: branchCommits, rule: 'job branch' };
9448
9733
 
9449
9734
  if (job?.slug) {
@@ -9751,6 +10036,125 @@ async function runGateShadow(job) {
9751
10036
  return gateShadow;
9752
10037
  }
9753
10038
 
10039
+ /**
10040
+ * Finish-review budget-kill heal: the one rung that may complete a
10041
+ * budget_exceeded park (reviewLadder.isFinishReviewKillHealEligible). The kill
10042
+ * hit inside the finish-protocol review after the run's commit landed, so
10043
+ * only the review and the verdict line are missing. Re-runs the PRD's own
10044
+ * gate — same resolveGate + runGateSequence the shadow gate uses — in a
10045
+ * scratch detached worktree at the main checkout's HEAD (contains the landed
10046
+ * commit, untouched by foreign WIP in the main tree). Never heals on
10047
+ * transcript evidence alone.
10048
+ *
10049
+ * One attempt: finishReviewHealAttemptedAt is stamped whatever the outcome
10050
+ * (green, red, unrunnable, not integrated); only a `busy` gate slot returns
10051
+ * without stamping, since nothing was attempted. Green → completed with a
10052
+ * reason naming the skipped review; anything else leaves the row
10053
+ * needs_review with its existing reason.
10054
+ */
10055
+ async function runFinishReviewKillHeal(job) {
10056
+ if (!reviewLadder.isFinishReviewKillHealEligible(job) || !job.cwd) return null;
10057
+ const cwd = job.cwd;
10058
+ const landed7 = job.landedCommit.slice(0, 7);
10059
+ let gate = { source: 'none', sequence: [] };
10060
+ let outcome = { status: 'unavailable', reason: 'not-run', results: [] };
10061
+ let evidenceOk = false;
10062
+ let integratedOk = false;
10063
+ let setupOk = false;
10064
+ const head = await gitTreeGuard.gitHead(cwd);
10065
+ const startedAtMs = typeof job.startedAt === 'string' ? Date.parse(job.startedAt) : NaN;
10066
+ if (Number.isFinite(startedAtMs)) {
10067
+ try { evidenceOk = await resolveLandedCommitEvidence(cwd, job.landedCommit, job.startedAt); } catch { evidenceOk = false; }
10068
+ }
10069
+ if (head) {
10070
+ try {
10071
+ await execGitAt(cwd, ['merge-base', '--is-ancestor', job.landedCommit, head], { timeout: 10_000 });
10072
+ integratedOk = true;
10073
+ } catch { integratedOk = false; }
10074
+ }
10075
+ let prdText = null;
10076
+ try {
10077
+ const prdPath = (await resolveVerifyPrdPath(job)) ?? prdPaths.archivedPrdPathForJob(job);
10078
+ prdText = fs.readFileSync(prdPath, 'utf8');
10079
+ } catch { prdText = null; }
10080
+ if (prdText !== null) gate = resolveGate(prdText);
10081
+ const pre = reviewLadder.decideFinishReviewKillHeal({ evidenceOk, integratedOk, gate, setupOk: true, outcome: { status: 'green' } });
10082
+ if (pre.complete) {
10083
+ const scratch = path.join(os.tmpdir(), `sm-finish-review-heal-${process.pid}-${Date.now()}`);
10084
+ let added = false;
10085
+ try {
10086
+ await execGitAt(cwd, ['worktree', 'add', '--detach', scratch, head], { timeout: 120_000 });
10087
+ added = true;
10088
+ const deps = await linkDependencyDirs({ mainCwd: cwd, worktreeCwd: scratch });
10089
+ const setup = deps && deps.setup ? deps.setup : null;
10090
+ setupOk = setup === null || isWorktreeSetupSettled(setup);
10091
+ if (setupOk) {
10092
+ const r = await runGateSequence(gate.sequence, { cwd: scratch });
10093
+ if (r.status === 'busy') return null; // nothing attempted — leave the row eligible
10094
+ outcome = r;
10095
+ } else {
10096
+ outcome = { status: 'unavailable', reason: `setup-${setup?.reason ?? 'error'}`, results: [] };
10097
+ }
10098
+ } catch (e) {
10099
+ outcome = { status: 'unavailable', reason: `gate-error: ${e && e.message ? e.message : e}`, results: [] };
10100
+ } finally {
10101
+ if (added) {
10102
+ try { await execGitAt(cwd, ['worktree', 'remove', '--force', scratch], { timeout: 60_000 }); } catch { /* best-effort */ }
10103
+ }
10104
+ try { fs.rmSync(scratch, { recursive: true, force: true }); } catch { /* best-effort */ }
10105
+ try { await execGitAt(cwd, ['worktree', 'prune'], { timeout: 30_000 }); } catch { /* best-effort */ }
10106
+ }
10107
+ }
10108
+ const decision = reviewLadder.decideFinishReviewKillHeal({ evidenceOk, integratedOk, gate, setupOk, outcome });
10109
+ const record = {
10110
+ attemptedAt: new Date().toISOString(),
10111
+ head: head ?? null,
10112
+ landedCommit: job.landedCommit,
10113
+ gateStatus: outcome.status,
10114
+ gateReason: outcome.reason ?? null,
10115
+ complete: decision.complete,
10116
+ reason: decision.reason,
10117
+ };
10118
+ let resolved = null;
10119
+ await mutate((s) => {
10120
+ for (const j of s.jobs) {
10121
+ if (j.slug !== job.slug) continue;
10122
+ const unchanged = j.status === 'needs_review'
10123
+ && j.verifierVerdict === 'budget_exceeded'
10124
+ && j.budgetKillPhase === 'finish-review'
10125
+ && j.landedCommit === job.landedCommit
10126
+ && j.runId === job.runId
10127
+ && j.startedAt === job.startedAt;
10128
+ if (!unchanged) {
10129
+ console.log(`[scheduler] finish-review heal: ${job.slug} result dropped — row changed under the gate`);
10130
+ continue;
10131
+ }
10132
+ j.finishReviewHealAttemptedAt = record.attemptedAt;
10133
+ j.finishReviewHeal = record;
10134
+ if (!decision.complete) continue;
10135
+ transitionJob(j, 'completed', {
10136
+ reason: `finish-protocol review killed at budget; gate re-run green on ${landed7}; review skipped`,
10137
+ source: 'finishReviewKillHeal',
10138
+ });
10139
+ j.error = null;
10140
+ delete j.verifierVerdict;
10141
+ delete j.looksDone;
10142
+ resolved = { slug: j.slug, cwd: j.cwd };
10143
+ }
10144
+ });
10145
+ if (resolved) {
10146
+ try { await prdPaths.archiveCompletedPrd(resolved.slug, resolved.cwd); } catch (e) {
10147
+ console.error('[scheduler] finish-review heal archive error', resolved.slug, e);
10148
+ }
10149
+ appendAuditEvent('needs_review_finish_review_healed', { slug: resolved.slug, cwd: resolved.cwd, landedCommit: job.landedCommit, head });
10150
+ console.log(`[scheduler] finish-review heal: ${resolved.slug} completed — gate re-run green on ${landed7}, review skipped`);
10151
+ } else {
10152
+ console.log(`[scheduler] finish-review heal: ${job.slug} stays needs_review (${decision.reason})`);
10153
+ }
10154
+ await broadcast();
10155
+ return record;
10156
+ }
10157
+
9754
10158
  // Tail of the last background shadow gate — lets tests (and only tests) await it.
9755
10159
  let gateShadowPending = null;
9756
10160
  // The slug the background shadow gate is currently deciding, from the pick
@@ -9920,6 +10324,8 @@ async function reverifyNeedsReview() {
9920
10324
  .then((gateTarget) => {
9921
10325
  if (!gateTarget) return;
9922
10326
  gateShadowSlug = gateTarget.slug;
10327
+ // Tier-0 pick: a finish-review budget kill gets its one-shot heal, not a shadow run.
10328
+ if (reviewLadder.isFinishReviewKillHealEligible(gateTarget)) return runFinishReviewKillHeal(gateTarget);
9923
10329
  return runGateShadow(gateTarget);
9924
10330
  })
9925
10331
  .catch((e) => { console.error('[scheduler] gate shadow error', gateShadowSlug, e); })
@@ -10889,6 +11295,29 @@ async function init() {
10889
11295
  // classify immediately below.
10890
11296
  const bootSnap = readQueueSync();
10891
11297
  const bootLogPath = (j) => (j?.runId ? path.join(schedulerPaths.runsDir(), j.runId, `${j.slug}.log`) : null);
11298
+ // cwd + slug → { sha, ref } of the uncommitted work the boot worktree sweep
11299
+ // pinned before removing a dead job's checkout (PRD 2893). The stale-age
11300
+ // part of the sweep may not know the main tree (cwd null) — slug fallback.
11301
+ const bootUncommittedSnapshots = new Map();
11302
+ const bootSnapshotKey = (cwd, slug) => `${cwd || ''}\0${slug}`;
11303
+ const bootSnapshotFor = (j) => bootUncommittedSnapshots.get(bootSnapshotKey(j.cwd || DEFAULT_PROJECT_CWD, j.slug))
11304
+ || bootUncommittedSnapshots.get(bootSnapshotKey(null, j.slug))
11305
+ || null;
11306
+
11307
+ // Partition FIRST (PRD 2908): the job-worktree sweep below must keep every
11308
+ // checkout the partition adopts — a run that printed PASS and exited just
11309
+ // before the restart is adopted on its fresh run log, and the reaper
11310
+ // finalizes it from its intact sm-job branch.
11311
+ const { immediate: immediateSlugs, adopted: adoptedSlugs } = partitionBootOrphans(bootSnap.jobs, {
11312
+ pidAlive: claudePidAlive,
11313
+ getLogPid: (j) => readSpawnedPidFromLog(bootLogPath(j)),
11314
+ getLogMtimeMs: (j) => readLogMtimeMs(bootLogPath(j)),
11315
+ logFreshWindowMs: IDLE_OUTPUT_KILL_MS,
11316
+ findLiveProcess: (j) => findLiveProcessForJob(j, {
11317
+ worktreeDir: jobWorktree.worktreeDirFor(j.cwd || DEFAULT_PROJECT_CWD, j.slug),
11318
+ }),
11319
+ readRecord: supervisorRecord.readSupervisorRecord,
11320
+ });
10892
11321
 
10893
11322
  // Worktree boot reconciliation (PRD 994): a job worktree that survives an
10894
11323
  // app crash/host reboot must not leak disk or a dangling branch forever —
@@ -10912,8 +11341,12 @@ async function init() {
10912
11341
  hasLiveHolder: gitWorktree.hasLiveHolder,
10913
11342
  cwdHolders: gitWorktree.listCwdHolders(),
10914
11343
  rowPid: (j) => bootRowPid(j, bootLogPath),
11344
+ adoptedSlugs: new Set(adoptedSlugs),
10915
11345
  });
10916
- await jobWorktree.reconcileWorktreesOnBoot([...worktreeCwds], { isLive });
11346
+ const sweep = await jobWorktree.reconcileWorktreesOnBoot([...worktreeCwds], { isLive });
11347
+ for (const s of (sweep && Array.isArray(sweep.snapshots)) ? sweep.snapshots : []) {
11348
+ if (s && s.key && s.sha && s.ref) bootUncommittedSnapshots.set(bootSnapshotKey(s.cwd, s.key), { sha: s.sha, ref: s.ref });
11349
+ }
10917
11350
  } catch (e) {
10918
11351
  console.error('[scheduler] boot worktree reconciliation failed', e?.message);
10919
11352
  }
@@ -10931,16 +11364,6 @@ async function init() {
10931
11364
  console.error('[scheduler] boot epic-worktree reconciliation failed', e?.message);
10932
11365
  }
10933
11366
 
10934
- const { immediate: immediateSlugs, adopted: adoptedSlugs } = partitionBootOrphans(bootSnap.jobs, {
10935
- pidAlive: claudePidAlive,
10936
- getLogPid: (j) => readSpawnedPidFromLog(bootLogPath(j)),
10937
- getLogMtimeMs: (j) => readLogMtimeMs(bootLogPath(j)),
10938
- logFreshWindowMs: IDLE_OUTPUT_KILL_MS,
10939
- findLiveProcess: (j) => findLiveProcessForJob(j, {
10940
- worktreeDir: jobWorktree.worktreeDirFor(j.cwd || DEFAULT_PROJECT_CWD, j.slug),
10941
- }),
10942
- readRecord: supervisorRecord.readSupervisorRecord,
10943
- });
10944
11367
  const bootOutcomes = new Map();
10945
11368
  for (const j of bootSnap.jobs) {
10946
11369
  if (!immediateSlugs.includes(j.slug)) continue;
@@ -10974,7 +11397,7 @@ async function init() {
10974
11397
  const outcome = bootOutcomes.get(j.slug) ?? 'unknown';
10975
11398
  const pid = j.runtime?.pid;
10976
11399
  const killNote = pid ? ` (orphan pid=${pid}: dead)` : '';
10977
- applyOrphanOutcome(j, outcome, killNote, bootLandedCommitEvidence.get(j.slug) || null);
11400
+ applyOrphanOutcome(j, outcome, killNote, bootLandedCommitEvidence.get(j.slug) || null, bootSnapshotFor(j));
10978
11401
  if (j.status === 'completed') bootReconciledCompletions.push({ slug: j.slug, cwd: j.cwd });
10979
11402
  console.log(`[scheduler] boot reconcile: slug=${j.slug} outcome=${outcome} → status=${j.status}`);
10980
11403
  }
@@ -11894,6 +12317,7 @@ module.exports = {
11894
12317
  OOM_SCORE_ADJ_JOB,
11895
12318
  reverifyNeedsReview,
11896
12319
  runGateShadow,
12320
+ runFinishReviewKillHeal,
11897
12321
  awaitGateShadowIdle: async () => { while (gateShadowPending) await gateShadowPending; },
11898
12322
  applyNeedsReviewAutoResolve,
11899
12323
  applyStuckFailedAutoSkip,