mandrel 2.87.0 → 2.89.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 (170) hide show
  1. package/.agents/README.md +29 -0
  2. package/.agents/agents/auditor.md +4 -3
  3. package/.agents/docs/agentrc-reference.json +5 -2
  4. package/.agents/docs/configuration.md +14 -8
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +24 -5
  7. package/.agents/schemas/story-deliver-terminal.schema.json +1 -1
  8. package/.agents/schemas/story-progress.schema.json +5 -0
  9. package/.agents/scripts/audit-to-stories.js +3 -2
  10. package/.agents/scripts/boot-sweep.js +3 -2
  11. package/.agents/scripts/check-arch-cycles.js +19 -41
  12. package/.agents/scripts/check-context-budget.js +16 -44
  13. package/.agents/scripts/check-cyclomatic.js +13 -37
  14. package/.agents/scripts/check-dead-exports.js +16 -46
  15. package/.agents/scripts/clean-worktrees.js +1 -6
  16. package/.agents/scripts/coverage-capture.js +32 -49
  17. package/.agents/scripts/deliver-run.js +11 -0
  18. package/.agents/scripts/diagnose-friction.js +3 -3
  19. package/.agents/scripts/lib/audit-baselines/gate-surface.js +24 -11
  20. package/.agents/scripts/lib/audit-baselines/read.js +4 -2
  21. package/.agents/scripts/lib/audit-baselines/surface-entry.js +95 -11
  22. package/.agents/scripts/lib/baselines/coverage-updater-cli.js +6 -14
  23. package/.agents/scripts/lib/baselines/crap-preview-scan.js +3 -1
  24. package/.agents/scripts/lib/baselines/crap-updater-cli.js +38 -26
  25. package/.agents/scripts/lib/baselines/duplication-scanner.js +20 -1
  26. package/.agents/scripts/lib/baselines/env-overrides.js +39 -34
  27. package/.agents/scripts/lib/baselines/kernel.js +3 -2
  28. package/.agents/scripts/lib/baselines/kinds/crap.js +50 -53
  29. package/.agents/scripts/lib/baselines/preview-gates.js +5 -1
  30. package/.agents/scripts/lib/baselines/refresh-service.js +65 -22
  31. package/.agents/scripts/lib/baselines/writer.js +5 -1
  32. package/.agents/scripts/lib/bdd-runner-detect.js +7 -10
  33. package/.agents/scripts/lib/child-exec.js +14 -1
  34. package/.agents/scripts/lib/child-stream.js +122 -0
  35. package/.agents/scripts/lib/clean-temp.js +19 -13
  36. package/.agents/scripts/lib/cli-args.js +49 -0
  37. package/.agents/scripts/lib/close-validation/gates.js +40 -9
  38. package/.agents/scripts/lib/codex/skills-projection.js +1 -12
  39. package/.agents/scripts/lib/config/gates/crap.schema.js +15 -0
  40. package/.agents/scripts/lib/config/gates/mutation.schema.js +2 -2
  41. package/.agents/scripts/lib/config/gh-config-dir.js +63 -0
  42. package/.agents/scripts/lib/config/github.js +2 -0
  43. package/.agents/scripts/lib/config/paths.js +14 -3
  44. package/.agents/scripts/lib/config/quality.js +49 -1
  45. package/.agents/scripts/lib/config-resolver.js +78 -64
  46. package/.agents/scripts/lib/config-settings-schema-delivery.js +4 -3
  47. package/.agents/scripts/lib/config-settings-schema.js +7 -0
  48. package/.agents/scripts/lib/coverage-baseline.js +2 -2
  49. package/.agents/scripts/lib/coverage-capture-affected.js +2 -1
  50. package/.agents/scripts/lib/coverage-capture-fullscope.js +2 -2
  51. package/.agents/scripts/lib/coverage-capture-incremental.js +1 -1
  52. package/.agents/scripts/lib/coverage-capture-passes.js +143 -0
  53. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  54. package/.agents/scripts/lib/coverage-capture.js +45 -15
  55. package/.agents/scripts/lib/crap-utils.js +65 -49
  56. package/.agents/scripts/lib/full-suite-lock.js +1 -10
  57. package/.agents/scripts/lib/gates/baseline-store.js +10 -0
  58. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  59. package/.agents/scripts/lib/gh-exec.js +45 -2
  60. package/.agents/scripts/lib/gh-transport.js +27 -0
  61. package/.agents/scripts/lib/git-utils.js +16 -9
  62. package/.agents/scripts/lib/maintainability-engine.js +27 -6
  63. package/.agents/scripts/lib/maintainability-utils.js +20 -2
  64. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +4 -1
  65. package/.agents/scripts/lib/orchestration/evidence-stream.js +186 -0
  66. package/.agents/scripts/lib/orchestration/file-assumptions.js +2 -19
  67. package/.agents/scripts/lib/orchestration/git-cleanup/phases/branches-reap.js +3 -7
  68. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes-ff.js +34 -40
  69. package/.agents/scripts/lib/orchestration/git-cleanup/phases/git-probes.js +4 -3
  70. package/.agents/scripts/lib/orchestration/plan-persist/persist-helpers.js +2 -19
  71. package/.agents/scripts/lib/orchestration/pr-watch.js +1 -5
  72. package/.agents/scripts/lib/orchestration/project-meta-cache.js +17 -4
  73. package/.agents/scripts/lib/orchestration/reassert-status-column.js +1 -8
  74. package/.agents/scripts/lib/orchestration/resolve-stories.js +1 -0
  75. package/.agents/scripts/lib/orchestration/review-providers/native.js +2 -2
  76. package/.agents/scripts/lib/orchestration/single-story-close/phase-timer.js +43 -0
  77. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +37 -13
  78. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +264 -0
  79. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +68 -0
  80. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +106 -0
  81. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +43 -35
  82. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +52 -0
  83. package/.agents/scripts/lib/orchestration/single-story-close/result.js +273 -0
  84. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +68 -776
  85. package/.agents/scripts/lib/orchestration/story-close/context-budget-writeback.js +20 -9
  86. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +2 -2
  87. package/.agents/scripts/lib/orchestration/story-close/ratchet-shrink-writeback.js +20 -12
  88. package/.agents/scripts/lib/orchestration/story-handoff.js +50 -21
  89. package/.agents/scripts/lib/orchestration/story-progress.js +32 -12
  90. package/.agents/scripts/lib/orchestration/ticket-validator.js +3 -13
  91. package/.agents/scripts/lib/orchestration/verify-credit.js +4 -1
  92. package/.agents/scripts/lib/qa/resolve-selection.js +1 -8
  93. package/.agents/scripts/lib/single-story/confirm-and-land.js +33 -0
  94. package/.agents/scripts/lib/single-story-sweep/reconcile-closing.js +43 -11
  95. package/.agents/scripts/lib/single-story-sweep/sweep-lock.js +130 -30
  96. package/.agents/scripts/lib/skills/parse-skill.js +1 -4
  97. package/.agents/scripts/lib/story-body/story-body.js +12 -1
  98. package/.agents/scripts/lib/suite-admission.js +3 -11
  99. package/.agents/scripts/lib/temp-retention.js +25 -11
  100. package/.agents/scripts/lib/test-run-credit.js +2 -5
  101. package/.agents/scripts/lib/transpile.js +193 -31
  102. package/.agents/scripts/lib/util/paths.js +31 -0
  103. package/.agents/scripts/lib/util/sleep.js +15 -0
  104. package/.agents/scripts/lib/validation-evidence.js +29 -3
  105. package/.agents/scripts/lib/wave-runner/live-probe.js +24 -0
  106. package/.agents/scripts/lib/workers/crap-worker.js +23 -12
  107. package/.agents/scripts/lib/workers/maintainability-report-worker.js +18 -12
  108. package/.agents/scripts/lib/workflow-closure.js +1 -8
  109. package/.agents/scripts/notify.js +83 -90
  110. package/.agents/scripts/plan-context.js +8 -4
  111. package/.agents/scripts/providers/github/auth.js +14 -30
  112. package/.agents/scripts/providers/github/blocked-by-add.js +11 -27
  113. package/.agents/scripts/providers/github/compose.js +1 -0
  114. package/.agents/scripts/providers/github/gh-token-diagnostics.js +130 -0
  115. package/.agents/scripts/providers/github/identity.js +158 -0
  116. package/.agents/scripts/providers/github/issues.js +2 -2
  117. package/.agents/scripts/providers/github/mappers.js +16 -19
  118. package/.agents/scripts/providers/github/projects-v2-graphql.js +4 -36
  119. package/.agents/scripts/providers/github/request-helpers.js +44 -0
  120. package/.agents/scripts/providers/github/sub-issue-add.js +11 -28
  121. package/.agents/scripts/providers/github.js +10 -2
  122. package/.agents/scripts/quality-preview.js +6 -19
  123. package/.agents/scripts/single-story-confirm-merge.js +8 -20
  124. package/.agents/scripts/single-story-init.js +0 -1
  125. package/.agents/scripts/stories-wave-tick.js +60 -46
  126. package/.agents/scripts/story-handoff.js +2 -23
  127. package/.agents/scripts/story-review-compute.js +3 -22
  128. package/.agents/scripts/sync-claude-agents.js +1 -12
  129. package/.agents/scripts/sync-claude-commands.js +1 -12
  130. package/.agents/scripts/update-crap-baseline.js +11 -20
  131. package/.agents/scripts/update-ticket-state.js +44 -45
  132. package/.agents/templates/docs/audit-sweep-runbook.md +1 -1
  133. package/.agents/workflows/audit-accessibility.md +1 -1
  134. package/.agents/workflows/audit-adrs.md +1 -1
  135. package/.agents/workflows/audit-architecture.md +1 -1
  136. package/.agents/workflows/audit-baselines.md +9 -4
  137. package/.agents/workflows/audit-clean-code.md +1 -1
  138. package/.agents/workflows/audit-data-model.md +1 -1
  139. package/.agents/workflows/audit-dependencies.md +1 -1
  140. package/.agents/workflows/audit-devops.md +1 -1
  141. package/.agents/workflows/audit-documentation.md +1 -1
  142. package/.agents/workflows/audit-exceptions.md +2 -2
  143. package/.agents/workflows/audit-mobile.md +1 -1
  144. package/.agents/workflows/audit-navigability.md +1 -1
  145. package/.agents/workflows/audit-performance.md +1 -1
  146. package/.agents/workflows/audit-privacy.md +1 -1
  147. package/.agents/workflows/audit-quality.md +1 -1
  148. package/.agents/workflows/audit-security.md +1 -1
  149. package/.agents/workflows/audit-seo.md +1 -1
  150. package/.agents/workflows/audit-sre.md +1 -1
  151. package/.agents/workflows/audit-to-stories.md +9 -7
  152. package/.agents/workflows/audit-ux-ui.md +1 -1
  153. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  154. package/.agents/workflows/helpers/deliver-digest.md +4 -5
  155. package/.agents/workflows/helpers/deliver-story-reference.md +4 -4
  156. package/.agents/workflows/mandrel-deliver.md +3 -1
  157. package/README.md +6 -3
  158. package/docs/CHANGELOG.md +42 -0
  159. package/lib/cli/doctor-checks/codex.js +240 -0
  160. package/lib/cli/doctor-checks/merge-driver.js +79 -0
  161. package/lib/cli/doctor-checks/payload.js +201 -0
  162. package/lib/cli/doctor-checks/read-json.js +16 -0
  163. package/lib/cli/doctor-checks/runtime-deps.js +146 -0
  164. package/lib/cli/doctor-checks/spawn.js +18 -0
  165. package/lib/cli/doctor-checks/sync-parity.js +205 -0
  166. package/lib/cli/doctor-checks/test-credit-path.js +270 -0
  167. package/lib/cli/doctor-checks/toolchain.js +137 -0
  168. package/lib/cli/doctor-checks/version-current.js +82 -0
  169. package/lib/cli/registry.js +40 -1330
  170. package/package.json +1 -1
@@ -81,19 +81,27 @@ function precheck({ workTree, storyBranch, git, relPath }) {
81
81
  }
82
82
 
83
83
  /**
84
- * Write the envelope and fold it into one commit. On a rejected commit the
85
- * file is restored so the gates score the tree the close found.
84
+ * Write the envelope and fold it into one commit; a throw at any step restores
85
+ * the file, then re-throws.
86
86
  *
87
- * @param {{ workTree: string, git: Function, relPath: string, envelope: object, storyId: number|string, shrunk: object[] }} args
87
+ * @param {object} args
88
88
  * @returns {{ sha: string }}
89
89
  */
90
- function commitBaseline({ workTree, git, relPath, envelope, storyId, shrunk }) {
91
- fs.writeFileSync(
92
- path.join(workTree, relPath),
93
- `${JSON.stringify(envelope, null, 2)}\n`,
94
- );
95
- git(['add', '--', relPath], { cwd: workTree });
90
+ function commitBaseline({
91
+ workTree,
92
+ git,
93
+ relPath,
94
+ envelope,
95
+ storyId,
96
+ shrunk,
97
+ writeFile,
98
+ }) {
96
99
  try {
100
+ writeFile(
101
+ path.join(workTree, relPath),
102
+ `${JSON.stringify(envelope, null, 2)}\n`,
103
+ );
104
+ git(['add', '--', relPath], { cwd: workTree });
97
105
  git(
98
106
  [
99
107
  'commit',
@@ -126,6 +134,7 @@ function commitBaseline({ workTree, git, relPath, envelope, storyId, shrunk }) {
126
134
  * loadBaselineImpl?: typeof defaultLoadBaseline,
127
135
  * diffBudgetImpl?: typeof defaultDiffBudget,
128
136
  * buildBaselineImpl?: typeof defaultBuildBaseline,
137
+ * writeFile?: typeof fs.writeFileSync,
129
138
  * }} opts
130
139
  * @returns {{ ran: boolean, committed: boolean, sha?: string, tiers?: string[], reason?: string }}
131
140
  */
@@ -141,6 +150,7 @@ export function runContextBudgetWriteback({
141
150
  loadBaselineImpl = defaultLoadBaseline,
142
151
  diffBudgetImpl = defaultDiffBudget,
143
152
  buildBaselineImpl = defaultBuildBaseline,
153
+ writeFile = fs.writeFileSync,
144
154
  } = {}) {
145
155
  if (!cwd || !storyBranch) return skip(logger, 'missing-context');
146
156
  const workTree = worktreePath || cwd;
@@ -171,6 +181,7 @@ export function runContextBudgetWriteback({
171
181
  envelope: buildBaselineImpl(tierMap, tolerance),
172
182
  storyId,
173
183
  shrunk: diff.shrunk,
184
+ writeFile,
174
185
  });
175
186
  const tiers = diff.shrunk.map((s) => s.tier);
176
187
  logger.warn?.(
@@ -6,7 +6,7 @@
6
6
  * commit would acknowledge the very rise it exists to expose, so a Story that
7
7
  * adds clones to a file it changed fails the head-vs-base compare at close.
8
8
  * The scan covers the whole tree (clones are pairwise); only changed-file rows
9
- * are written. Every failure is a named skip, never a failed close.
9
+ * and their clone partners' rows are written. Every failure is a named skip, never a failed close.
10
10
  */
11
11
 
12
12
  import fs from 'node:fs';
@@ -233,7 +233,7 @@ export async function runDuplicationCloseRescore({
233
233
  if (!refreshed.value?.wrote) return skip(logger, 'unchanged');
234
234
 
235
235
  const moved = diffScopedRows({
236
- files,
236
+ files: refreshed.value.scope?.files ?? files,
237
237
  priorRows,
238
238
  nextRows: refreshed.value.envelope?.rows,
239
239
  });
@@ -207,22 +207,22 @@ function safePlan(relPath, plan) {
207
207
  }
208
208
 
209
209
  /**
210
- * Write every shrunk envelope and fold them into one commit. On a rejected
211
- * commit the files are restored so the gates score the tree the close found.
210
+ * Write every shrunk envelope and fold them into one commit; a throw at any
211
+ * step restores every path, then re-throws.
212
212
  *
213
- * @param {{ workTree: string, git: Function, shrinks: object[], storyId: number|string }} args
213
+ * @param {object} args
214
214
  * @returns {string} the short sha
215
215
  */
216
- function commitShrinks({ workTree, git, shrinks, storyId }) {
216
+ function commitShrinks({ workTree, git, shrinks, storyId, writeFile }) {
217
217
  const paths = shrinks.map((s) => s.relPath);
218
- for (const s of shrinks) {
219
- fs.writeFileSync(
220
- path.join(workTree, s.relPath),
221
- `${JSON.stringify(s.envelope, null, 2)}\n`,
222
- );
223
- }
224
- git(['add', '--', ...paths], { cwd: workTree });
225
218
  try {
219
+ for (const s of shrinks) {
220
+ writeFile(
221
+ path.join(workTree, s.relPath),
222
+ `${JSON.stringify(s.envelope, null, 2)}\n`,
223
+ );
224
+ }
225
+ git(['add', '--', ...paths], { cwd: workTree });
226
226
  git(
227
227
  [
228
228
  'commit',
@@ -267,6 +267,7 @@ function bindGit(gitSync, workTree) {
267
267
  * runKnip?: typeof defaultRunKnip,
268
268
  * scanCyclomatic?: typeof defaultScanCyclomatic,
269
269
  * resolveScanScope?: typeof defaultResolveScanScope,
270
+ * writeFile?: typeof fs.writeFileSync,
270
271
  * }} opts
271
272
  * @returns {{ ran: boolean, committed: boolean, sha?: string, baselines?: string[], skipped?: Record<string, string>, reason?: string }}
272
273
  */
@@ -281,6 +282,7 @@ export function runRatchetShrinkWriteback({
281
282
  runKnip = defaultRunKnip,
282
283
  scanCyclomatic = defaultScanCyclomatic,
283
284
  resolveScanScope = defaultResolveScanScope,
285
+ writeFile = fs.writeFileSync,
284
286
  } = {}) {
285
287
  if (!cwd || !storyBranch) return skip(logger, 'missing-context');
286
288
  const workTree = worktreePath || cwd;
@@ -329,7 +331,13 @@ export function runRatchetShrinkWriteback({
329
331
  return { ...skip(logger, `no-shrink: ${detail}`), skipped };
330
332
  }
331
333
  try {
332
- const sha = commitShrinks({ workTree, git, shrinks, storyId });
334
+ const sha = commitShrinks({
335
+ workTree,
336
+ git,
337
+ shrinks,
338
+ storyId,
339
+ writeFile,
340
+ });
333
341
  const baselines = shrinks.map((s) => s.relPath);
334
342
  logger.warn?.(
335
343
  `${TAG} dropped burnt-down rows from ${baselines.join(', ')} on story #${storyId}; committed as ${sha}.`,
@@ -22,7 +22,7 @@ import fs from 'node:fs';
22
22
  import path from 'node:path';
23
23
  import { fileURLToPath } from 'node:url';
24
24
 
25
- import { spawnCaptureAsync } from '../child-exec.js';
25
+ import { spawnStreamAsync } from '../child-exec.js';
26
26
  import { createLockEventChannel } from '../close-lock-events.js';
27
27
  import {
28
28
  resolveLintCommand,
@@ -45,6 +45,8 @@ import { getStoryBranch, gitSpawn } from '../git-utils.js';
45
45
  import { readPackageScripts } from '../npm-scripts.js';
46
46
  import { TIMEOUT_EXIT_CODE } from '../process-group.js';
47
47
  import { describeBlocking } from '../suite-admission.js';
48
+ import { defaultSleep } from '../util/sleep.js';
49
+ import { runStreamed } from './evidence-stream.js';
48
50
  import { probeHeldReviewDiff } from './review-deposit.js';
49
51
  import { createStoryProgress, handoffStepName } from './story-progress.js';
50
52
  import {
@@ -116,12 +118,6 @@ const MAX_OFFENDING_LINES = 10;
116
118
 
117
119
  const LOCK_POLL_MS = 1_000;
118
120
 
119
- function defaultSleep(ms) {
120
- return new Promise((resolve) => {
121
- setTimeout(resolve, ms).unref?.();
122
- });
123
- }
124
-
125
121
  const SEAT_SCRIPTS = Object.freeze({
126
122
  crap: 'update-crap-baseline.js',
127
123
  maintainability: 'update-maintainability-baseline.js',
@@ -181,7 +177,8 @@ function headSha(ctx) {
181
177
  }
182
178
 
183
179
  /**
184
- * Run one child, write its combined output to the step's evidence log.
180
+ * Run one child with its combined output streamed live into the step's
181
+ * evidence log (announced, and recorded in story-progress, before it spawns).
185
182
  *
186
183
  * @param {object} ctx
187
184
  * @param {string} logName
@@ -192,10 +189,18 @@ function headSha(ctx) {
192
189
  */
193
190
  async function runLogged(ctx, logName, cmd, args, env) {
194
191
  ctx.progress(logName, `${cmd} ${args.join(' ')}`);
195
- const res = await ctx.runCommand(cmd, args, { cwd: ctx.cwd, env });
196
- const output = [res.stdout, res.stderr].filter(Boolean).join('\n');
197
- const evidencePath = ctx.writeEvidence(logName, output);
198
- return { status: res.status, output, evidencePath };
192
+ const file = ctx.evidencePathFor(logName);
193
+ ctx.storyProgress.evidence(file);
194
+ return runStreamed({
195
+ ...ctx.stream,
196
+ runCommand: ctx.runCommand,
197
+ progress: ctx.progress,
198
+ cmd,
199
+ args,
200
+ opts: { cwd: ctx.cwd, env },
201
+ file,
202
+ tag: logName,
203
+ });
199
204
  }
200
205
 
201
206
  const LOCK_PHASE_TEXT = Object.freeze({
@@ -839,7 +844,7 @@ async function defaultBlock({
839
844
  * @param {{ storyId: number, cwd: string, config: object }} input
840
845
  * @param {{
841
846
  * git?: typeof gitSpawn,
842
- * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string }>,
847
+ * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string, timedOut?: boolean }>,
843
848
  * syncFromBase?: typeof syncBranchFromBase,
844
849
  * probeReview?: typeof probeHeldReviewDiff,
845
850
  * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
@@ -853,13 +858,20 @@ async function defaultBlock({
853
858
  * sleep?: (ms: number) => Promise<void>,
854
859
  * lockPollMs?: number,
855
860
  * env?: Record<string, string|undefined>,
856
- * }} deps
861
+ * heartbeatMs?: number,
862
+ * commandTimeoutMs?: number|null,
863
+ * signalTarget?: import('node:events').EventEmitter,
864
+ * reraise?: (signal: string) => void,
865
+ * evidenceFs?: typeof fs,
866
+ * }} deps `runCommand` receives `onChunk`, `signal` and (when set)
867
+ * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
868
+ * still gets its whole output written at settle.
857
869
  * @returns {Promise<{ envelope: object, exitCode: number }>}
858
870
  */
859
871
  export async function runStoryHandoff({ storyId, cwd, config }, deps) {
860
872
  const {
861
873
  git = gitSpawn,
862
- runCommand = spawnCaptureAsync,
874
+ runCommand = spawnStreamAsync,
863
875
  syncFromBase = syncBranchFromBase,
864
876
  probeReview = probeHeldReviewDiff,
865
877
  computeReview,
@@ -872,6 +884,11 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
872
884
  sleep = defaultSleep,
873
885
  lockPollMs = LOCK_POLL_MS,
874
886
  env = process.env,
887
+ heartbeatMs,
888
+ commandTimeoutMs,
889
+ signalTarget,
890
+ reraise,
891
+ evidenceFs,
875
892
  } = deps;
876
893
  const block =
877
894
  deps.block ??
@@ -884,6 +901,13 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
884
901
  fs.mkdirSync(logDir, { recursive: true });
885
902
  const statePath = path.join(logDir, `story-handoff-${storyId}.json`);
886
903
  const branch = getStoryBranch(storyId);
904
+ const evidencePathFor = (name) =>
905
+ path.join(logDir, `story-handoff-${storyId}-${name}.log`);
906
+ const storyProgress = createStoryProgress({
907
+ storyId,
908
+ stage: 'handoff',
909
+ config,
910
+ });
887
911
  const ctx = {
888
912
  storyId,
889
913
  cwd,
@@ -909,8 +933,18 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
909
933
  cwd,
910
934
  getChangedFilesImpl: getChangedFilesFn,
911
935
  }),
936
+ storyProgress,
937
+ // Undefined fields take runStreamed's defaults.
938
+ stream: {
939
+ heartbeatMs,
940
+ timeoutMs: commandTimeoutMs,
941
+ signalTarget,
942
+ reraise,
943
+ fsImpl: evidenceFs,
944
+ },
945
+ evidencePathFor,
912
946
  writeEvidence: (name, text) => {
913
- const file = path.join(logDir, `story-handoff-${storyId}-${name}.log`);
947
+ const file = evidencePathFor(name);
914
948
  fs.writeFileSync(file, text ?? '', 'utf8');
915
949
  return file;
916
950
  },
@@ -920,11 +954,6 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
920
954
  const steps = [];
921
955
  let stop = precheck(ctx);
922
956
  if (stop) steps.push(stop);
923
- const storyProgress = createStoryProgress({
924
- storyId,
925
- stage: 'handoff',
926
- config,
927
- });
928
957
  for (const step of stop ? [] : stepOrder(ctx.depositor)) {
929
958
  storyProgress.phase(handoffStepName(step));
930
959
  const result = await step(ctx);
@@ -60,17 +60,39 @@ function writeStoryProgress(file, record, deps = {}) {
60
60
  }
61
61
  }
62
62
 
63
+ /**
64
+ * The configured progress path, or `null` when it cannot be resolved.
65
+ *
66
+ * @param {number} storyId
67
+ * @param {object|undefined} config
68
+ * @param {((msg: string) => void)|undefined} debug
69
+ * @returns {string|null}
70
+ */
71
+ function resolveProgressPath(storyId, config, debug) {
72
+ try {
73
+ return storyProgressPath(storyId, config);
74
+ } catch (err) {
75
+ (debug ?? ((msg) => Logger.debug(msg)))(
76
+ `[story-progress] no progress path: ${err?.message ?? err}`,
77
+ );
78
+ return null;
79
+ }
80
+ }
81
+
63
82
  /**
64
83
  * A per-run recorder: `stageStartedAt` is fixed at creation, `phaseStartedAt`
65
84
  * resets on each `phase()`, and `prNumber()` re-writes the current phase with
66
- * the PR number once known. Nothing is written until the first `phase()`.
85
+ * the PR number once known. `evidence()` records the current phase's live
86
+ * evidence log, cleared by the next `phase()`. Nothing is written until the
87
+ * first `phase()`.
67
88
  * Construction never throws either: a bad Story id or config degrades to a
68
89
  * recorder that writes nothing.
69
90
  *
70
91
  * @param {{ storyId: number, stage: 'handoff'|'close', config?: object,
71
92
  * file?: string, now?: () => Date, fsImpl?: typeof fs,
72
93
  * debug?: (msg: string) => void }} args
73
- * @returns {{ phase: (name: string) => boolean, prNumber: (n: number|null) => boolean, file: string|null }}
94
+ * @returns {{ phase: (name: string) => boolean, prNumber: (n: number|null) => boolean,
95
+ * evidence: (file: string) => boolean, file: string|null }}
74
96
  */
75
97
  export function createStoryProgress({
76
98
  storyId,
@@ -81,20 +103,12 @@ export function createStoryProgress({
81
103
  fsImpl,
82
104
  debug,
83
105
  }) {
84
- let target = file ?? null;
85
- if (!target) {
86
- try {
87
- target = storyProgressPath(storyId, config);
88
- } catch (err) {
89
- (debug ?? ((msg) => Logger.debug(msg)))(
90
- `[story-progress] no progress path: ${err?.message ?? err}`,
91
- );
92
- }
93
- }
106
+ const target = file ?? resolveProgressPath(storyId, config, debug);
94
107
  const stageStartedAt = now().toISOString();
95
108
  let current = null;
96
109
  let phaseStartedAt = stageStartedAt;
97
110
  let pr = null;
111
+ let extra = {};
98
112
  const write = () => {
99
113
  if (!target || current === null) return false;
100
114
  return writeStoryProgress(
@@ -107,6 +121,7 @@ export function createStoryProgress({
107
121
  stageStartedAt,
108
122
  phaseStartedAt,
109
123
  prNumber: pr,
124
+ ...extra,
110
125
  updatedAt: now().toISOString(),
111
126
  },
112
127
  { fsImpl, debug },
@@ -117,6 +132,11 @@ export function createStoryProgress({
117
132
  phase(name) {
118
133
  current = name;
119
134
  phaseStartedAt = now().toISOString();
135
+ extra = {};
136
+ return write();
137
+ },
138
+ evidence(file) {
139
+ extra = { evidencePath: file };
120
140
  return write();
121
141
  },
122
142
  prNumber(n) {
@@ -1,7 +1,7 @@
1
1
  import { ValidationError } from '../errors/index.js';
2
2
  import { normalizeOwnedProvenance } from '../findings/provenance-field.js';
3
3
  import { detectCycle } from '../Graph.js';
4
- import { gitSpawn } from '../git-utils.js';
4
+ import { pathExistsAtBase } from '../git-utils.js';
5
5
 
6
6
  import { validateStoryFileAssumptions } from './file-assumptions.js';
7
7
  import { isExternalDependencyRef } from './plan-persist/external-deps.js';
@@ -105,16 +105,6 @@ function collectChangesItem(item, paths) {
105
105
  }
106
106
  }
107
107
 
108
- function defaultGitRunner({ baseBranchRef, path, cwd }) {
109
- const result = gitSpawn(
110
- cwd ?? process.cwd(),
111
- 'cat-file',
112
- '-e',
113
- `${baseBranchRef}:${path}`,
114
- );
115
- return result.status === 0;
116
- }
117
-
118
108
  /**
119
109
  * One cache shared by the freshness and file-assumption gates.
120
110
  *
@@ -149,7 +139,7 @@ function makeMemoizedGitRunner(runner) {
149
139
  export function validateAcFreshness({
150
140
  tickets,
151
141
  baseBranchRef,
152
- gitRunner = defaultGitRunner,
142
+ gitRunner = pathExistsAtBase,
153
143
  cwd,
154
144
  }) {
155
145
  if (!baseBranchRef || typeof baseBranchRef !== 'string') {
@@ -367,7 +357,7 @@ export function validateAndNormalizeTickets(tickets, opts = {}) {
367
357
  assertStoryBodiesParse({ tickets });
368
358
 
369
359
  const sharedGitRunner = opts.baseBranchRef
370
- ? makeMemoizedGitRunner(opts.gitRunner ?? defaultGitRunner)
360
+ ? makeMemoizedGitRunner(opts.gitRunner ?? pathExistsAtBase)
371
361
  : null;
372
362
 
373
363
  const warnings = [...collectMissingVerifyWarnings(stories)];
@@ -139,7 +139,10 @@ export function resolveVerifyCredit(
139
139
  const { crap } = getQualityImpl(config);
140
140
  const mode =
141
141
  crap?.enabled !== false &&
142
- hasNpmScriptImpl(readPackageScriptsImpl(worktree), 'test:coverage')
142
+ hasNpmScriptImpl(
143
+ readPackageScriptsImpl(worktree),
144
+ crap?.captureScript ?? 'test:coverage',
145
+ )
143
146
  ? 'capture'
144
147
  : 'evidence';
145
148
 
@@ -14,14 +14,7 @@
14
14
  import path from 'node:path';
15
15
 
16
16
  import { listFeatureFiles, scanBddScenarios } from '../bdd-scenario-scanner.js';
17
-
18
- /**
19
- * @param {string} p
20
- * @returns {string}
21
- */
22
- function toPosix(p) {
23
- return p.split(path.sep).join('/');
24
- }
17
+ import { toPosix } from '../util/paths.js';
25
18
 
26
19
  /**
27
20
  * @param {string} featureRoot - Absolute path to the feature root.
@@ -0,0 +1,33 @@
1
+ import { runPostLandTail as defaultRunPostLandTail } from '../orchestration/single-story-close/phases/post-land.js';
2
+ import { confirmStoryMerged } from './confirm-merge.js';
3
+
4
+ /**
5
+ * Confirm, then the land tail when merged — shared by every merged-Story
6
+ * path, since a flip alone strands the lease and worktree.
7
+ *
8
+ * @param {object} args {@link confirmStoryMerged}'s arguments, plus:
9
+ * @param {string} args.storyBranch
10
+ * @param {string} [args.baseBranch] Defaults to `project.baseBranch`.
11
+ * @param {Function} [args.runPostLandTailFn] Test seam.
12
+ * @returns {Promise<{ confirmation: object, tail: object|null }>}
13
+ */
14
+ export async function confirmAndLand({
15
+ storyBranch,
16
+ baseBranch,
17
+ runPostLandTailFn = defaultRunPostLandTail,
18
+ ...confirmArgs
19
+ }) {
20
+ const confirmation = await confirmStoryMerged(confirmArgs);
21
+ if (confirmation.merged !== true) return { confirmation, tail: null };
22
+ const { storyId, cwd, provider, config, progress } = confirmArgs;
23
+ const tail = await runPostLandTailFn({
24
+ storyId,
25
+ storyBranch,
26
+ baseBranch: baseBranch ?? config?.project?.baseBranch ?? 'main',
27
+ cwd,
28
+ provider,
29
+ config,
30
+ progress,
31
+ });
32
+ return { confirmation, tail };
33
+ }
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Only a live close flips `agent::done`; a PR that merges after it is gone
3
- * closes the issue at `agent::closing`. Boot finishes the flip via
2
+ * A PR that merges after close is gone closes its issue at `agent::closing`
3
+ * or `agent::blocked`. Boot finishes the flip and land tail via
4
4
  * `reconcileDoneLabel` (MERGED PR required). Bounded; never throws.
5
5
  */
6
6
 
@@ -8,9 +8,18 @@ import { getStoryBranch } from '../git-utils.js';
8
8
  import { AGENT_LABELS, TYPE_LABELS } from '../label-constants.js';
9
9
  import { reconcileDoneLabel as defaultReconcile } from '../orchestration/single-story-close/phases/reconcile-done.js';
10
10
 
11
- /** Candidates processed per sweep; a larger backlog drains across boots. */
11
+ /**
12
+ * Candidates per sweep, most recently closed first: an unmerged closed Story
13
+ * stays a candidate forever and must not starve a newly stranded one.
14
+ */
12
15
  export const DEFAULT_RECONCILE_LIMIT = 10;
13
16
 
17
+ /** Lifecycle labels a closed Story can strand at; one listing each. */
18
+ const STRANDED_LABELS = Object.freeze([
19
+ AGENT_LABELS.CLOSING,
20
+ AGENT_LABELS.BLOCKED,
21
+ ]);
22
+
14
23
  function isStrandedStory(ticket) {
15
24
  const labels = Array.isArray(ticket?.labels) ? ticket.labels : [];
16
25
  return (
@@ -38,6 +47,30 @@ async function reconcileOne({ story, cwd, deps, logger, reconcileFn }) {
38
47
  }
39
48
  }
40
49
 
50
+ function closedAtMs(ticket) {
51
+ const ms = Date.parse(ticket?.closedAt ?? '');
52
+ return Number.isFinite(ms) ? ms : 0;
53
+ }
54
+
55
+ function byClosedAtDesc(a, b) {
56
+ return closedAtMs(b) - closedAtMs(a);
57
+ }
58
+
59
+ /** Closed Stories at any stranded label, de-duplicated by id. */
60
+ async function listStranded(provider) {
61
+ const byId = new Map();
62
+ for (const labels of STRANDED_LABELS) {
63
+ const tickets = await provider.listTicketsByLabel({
64
+ state: 'closed',
65
+ labels,
66
+ });
67
+ for (const ticket of Array.isArray(tickets) ? tickets : []) {
68
+ if (!byId.has(ticket?.id)) byId.set(ticket?.id, ticket);
69
+ }
70
+ }
71
+ return [...byId.values()];
72
+ }
73
+
41
74
  export async function reconcileStrandedClosing({
42
75
  provider,
43
76
  config,
@@ -45,6 +78,7 @@ export async function reconcileStrandedClosing({
45
78
  gh,
46
79
  notify,
47
80
  sleep,
81
+ runPostLandTail,
48
82
  logger = {},
49
83
  limit = DEFAULT_RECONCILE_LIMIT,
50
84
  reconcileFn = defaultReconcile,
@@ -53,21 +87,19 @@ export async function reconcileStrandedClosing({
53
87
  if (typeof provider?.listTicketsByLabel !== 'function') return outcome;
54
88
  let tickets;
55
89
  try {
56
- tickets = await provider.listTicketsByLabel({
57
- state: 'closed',
58
- labels: AGENT_LABELS.CLOSING,
59
- });
90
+ tickets = await listStranded(provider);
60
91
  } catch (err) {
61
92
  const msg = err?.message ?? String(err);
62
93
  logger.warn?.(
63
- `closed agent::closing listing failed (host continues): ${msg}`,
94
+ `closed agent::closing / agent::blocked listing failed (host continues): ${msg}`,
64
95
  );
65
96
  return { ...outcome, ok: false, error: msg };
66
97
  }
67
- const candidates = (Array.isArray(tickets) ? tickets : [])
98
+ const candidates = tickets
68
99
  .filter(isStrandedStory)
100
+ .sort(byClosedAtDesc)
69
101
  .slice(0, limit);
70
- const deps = { provider, config, gh, notify, sleep };
102
+ const deps = { provider, config, gh, notify, sleep, runPostLandTail };
71
103
  for (const story of candidates) {
72
104
  const storyId = story.id;
73
105
  const result = await reconcileOne({
@@ -82,7 +114,7 @@ export async function reconcileStrandedClosing({
82
114
  }
83
115
  if (outcome.reconciled.length > 0) {
84
116
  logger.info?.(
85
- `🏷️ reconciled ${outcome.reconciled.length} closed Story(ies) stranded at agent::closing → agent::done.`,
117
+ `🏷️ reconciled ${outcome.reconciled.length} closed Story(ies) stranded at agent::closing / agent::blocked → agent::done.`,
86
118
  );
87
119
  }
88
120
  return outcome;