mandrel 2.111.0 → 2.112.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 (178) hide show
  1. package/.agents/agents/acceptance-critic.md +14 -0
  2. package/.agents/agents/auditor.md +14 -0
  3. package/.agents/agents/plan-critic.md +5 -0
  4. package/.agents/agents/story-worker.md +4 -1
  5. package/.agents/docs/agentrc-reference.json +22 -10
  6. package/.agents/docs/configuration.md +351 -37
  7. package/.agents/docs/execution-reference.md +11 -0
  8. package/.agents/rules/git-conventions-reference.md +7 -0
  9. package/.agents/schemas/agentrc.schema.json +174 -14
  10. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  11. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  12. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  13. package/.agents/schemas/baselines/crap.schema.json +37 -10
  14. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  15. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  16. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  17. package/.agents/schemas/crap-report.schema.json +6 -5
  18. package/.agents/schemas/story-deliver-terminal.schema.json +41 -2
  19. package/.agents/schemas/story-progress.schema.json +1 -1
  20. package/.agents/schemas/validation-evidence.schema.json +2 -2
  21. package/.agents/scripts/boot-sweep.js +41 -3
  22. package/.agents/scripts/coverage-capture.js +37 -3
  23. package/.agents/scripts/coverage-ratchet.js +106 -0
  24. package/.agents/scripts/evidence-gate.js +84 -21
  25. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  26. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  27. package/.agents/scripts/lib/baseline-loader.js +4 -2
  28. package/.agents/scripts/lib/baselines/codec.js +57 -0
  29. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  30. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  31. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  32. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  33. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  34. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  35. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  36. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  37. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  38. package/.agents/scripts/lib/baselines/reader.js +36 -9
  39. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  40. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  41. package/.agents/scripts/lib/baselines/writer.js +36 -21
  42. package/.agents/scripts/lib/changed-files.js +70 -6
  43. package/.agents/scripts/lib/child-exec.js +10 -0
  44. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  45. package/.agents/scripts/lib/close-lock-events.js +8 -3
  46. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  47. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  48. package/.agents/scripts/lib/close-validation/process.js +16 -7
  49. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  50. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  51. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  52. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  53. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  54. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  55. package/.agents/scripts/lib/config/explain.js +5 -2
  56. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  57. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  58. package/.agents/scripts/lib/config/git-roots.js +38 -4
  59. package/.agents/scripts/lib/config/handoff.js +24 -0
  60. package/.agents/scripts/lib/config/quality.js +26 -13
  61. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  62. package/.agents/scripts/lib/config-resolver.js +22 -2
  63. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  64. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  65. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  66. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  67. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  68. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  69. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  70. package/.agents/scripts/lib/coverage-capture.js +15 -0
  71. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  72. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  73. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  74. package/.agents/scripts/lib/crap-engine.js +3 -3
  75. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  76. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  77. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  78. package/.agents/scripts/lib/failure-rows.js +121 -0
  79. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  80. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  81. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  82. package/.agents/scripts/lib/gh-env.js +3 -6
  83. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  84. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  85. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  86. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  87. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  88. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  89. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  90. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  91. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  92. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  93. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  94. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  95. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  98. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  99. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  100. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  101. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  102. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  103. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  104. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  105. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  106. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  107. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  108. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  109. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  110. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  111. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  112. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  113. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  114. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  115. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  116. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  117. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  118. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  119. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +15 -3
  120. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  121. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  135. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  136. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  137. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  138. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  139. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  140. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  141. package/.agents/scripts/lib/orchestration/story-handoff.js +774 -196
  142. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  143. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  144. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  145. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  146. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  147. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  148. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  149. package/.agents/scripts/lib/suite-admission.js +20 -8
  150. package/.agents/scripts/lib/suite-sizing.js +146 -0
  151. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  152. package/.agents/scripts/merge-baseline.js +14 -3
  153. package/.agents/scripts/providers/github/comments.js +19 -3
  154. package/.agents/scripts/providers/github.js +1 -0
  155. package/.agents/scripts/review-dispositions-report.js +1 -1
  156. package/.agents/scripts/role-scope-guard.js +267 -0
  157. package/.agents/scripts/single-story-close.js +4 -4
  158. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  159. package/.agents/scripts/single-story-init.js +24 -4
  160. package/.agents/scripts/story-handoff.js +3 -3
  161. package/.agents/scripts/story-outcomes-report.js +231 -0
  162. package/.agents/scripts/story-review-compute.js +9 -5
  163. package/.agents/scripts/update-coverage-baseline.js +12 -2
  164. package/.agents/scripts/update-crap-baseline.js +9 -1
  165. package/.agents/workflows/helpers/code-review.md +63 -9
  166. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  167. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  168. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  169. package/.agents/workflows/helpers/deliver-story.md +7 -2
  170. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  171. package/docs/CHANGELOG.md +46 -0
  172. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  173. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  174. package/lib/cli/doctor-checks/llm-review.js +2 -11
  175. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  176. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  177. package/lib/cli/registry.js +5 -0
  178. package/package.json +1 -1
@@ -1,18 +1,18 @@
1
1
  /**
2
2
  * story-handoff.js — the story-worker's whole post-implementation tail as one
3
- * deterministic sequence: base merge → blocking preflight (lint and format
4
- * deposited as close's credit, quality-preview, baselined ratchets) → the one
5
- * credited run with the held review beside it → baseline seating → close's
6
- * post-capture CRAP and baselines scoring → push + remote-ref check → review
7
- * awaited. It runs exactly what deliver-digest § 5 and deliver-reference
3
+ * deterministic sequence: base merge (starting the held review) → duplication
4
+ * re-score → blocking preflight (lint and format deposited as close's credit,
5
+ * quality-preview, baselined ratchets) → the one credited run, which a halted
6
+ * review skips or aborts → baseline seating → close's post-capture CRAP and
7
+ * baselines scoring → push + remote-ref check → review awaited. It runs exactly what deliver-digest § 5 and deliver-reference
8
8
  * define, with close's own gate identities, and settles one envelope:
9
9
  *
10
10
  * - `ready` (exit 0) — hand off.
11
11
  * - `fix-required` (exit 2) — the worker can fix it by editing the branch;
12
12
  * labels untouched.
13
13
  * - `blocked` (exit 1) — the worker cannot: a rejected push, an unreachable
14
- * remote, an unconfirmed base branch or an unregistered baseline merge
15
- * driver. Flips `agent::blocked` and posts a `friction` comment.
14
+ * remote, an unconfirmed base branch, an unregistered baseline merge
15
+ * driver or a suite that lost workers to host memory (exit 77). Flips `agent::blocked` and posts a `friction` comment.
16
16
  *
17
17
  * Idempotent: a re-run skips every step whose result is still valid for the
18
18
  * current HEAD, judged by the step's output signal, never its exit code alone.
@@ -35,38 +35,66 @@ import {
35
35
  } from '../close-validation/gates.js';
36
36
  import { isBiomeNoFilesProcessed } from '../close-validation/process.js';
37
37
  import { applyChangedFileScope } from '../close-validation/runner.js';
38
+ import { skipBranchDeposit } from '../close-validation/skip-branch-test.js';
39
+ import { getPostSeatChecks } from '../config/handoff.js';
40
+ import { getQuality } from '../config/quality.js';
38
41
  import {
39
42
  orchestrationLogDir,
40
43
  storyReviewDepositPath,
41
44
  } from '../config/temp-paths.js';
45
+ import { COVERAGE_HOST_RESOURCES_EXIT_CODE } from '../coverage-capture.js';
46
+ import { extractFailureRows } from '../failure-rows.js';
42
47
  import {
43
48
  ADMISSION_REFUSED_EXIT_CODE,
44
49
  LOCK_WAIT_EXPIRED_EXIT_CODE,
50
+ withSuiteAdmission,
45
51
  } from '../full-suite-lock.js';
52
+ import { handoffRerunSkip } from '../git/base-sync-probe.js';
46
53
  import { syncBranchFromBase } from '../git/sync-from-base.js';
54
+ import { remoteBranchSha } from '../git-branch-lifecycle.js';
47
55
  import { getStoryBranch, gitSpawn } from '../git-utils.js';
48
56
  import { readPackageScripts } from '../npm-scripts.js';
57
+ import {
58
+ emitHandoffRecord,
59
+ handoffCause,
60
+ nextHandoffAttempt,
61
+ } from '../observability/handoff-telemetry.js';
62
+ import {
63
+ emitRuntimeFriction,
64
+ RUNTIME_FRICTION_CATEGORIES,
65
+ } from '../observability/runtime-friction.js';
49
66
  import { TIMEOUT_EXIT_CODE } from '../process-group.js';
50
67
  import { PROJECT_ROOT } from '../project-root.js';
68
+ import { STANDALONE_RATCHETS } from '../standalone-ratchets.js';
51
69
  import { describeBlocking } from '../suite-admission.js';
52
70
  import { writeFileAtomic } from '../util/atomic-write.js';
53
71
  import { defaultSleep } from '../util/sleep.js';
72
+ import { hashCommandConfig } from '../validation-evidence.js';
54
73
  import { runStreamed } from './evidence-stream.js';
55
74
  import {
56
75
  carryCoverageDeferral,
57
- carryLintCredit,
76
+ carryCredit,
77
+ carryPreflightCredits,
58
78
  clearCoverageDeferral,
59
79
  coverageEnvelope,
60
80
  creditedPreflight,
61
- isOverBudgetCapture,
62
- lintCredit,
81
+ isCoverageDeferred,
82
+ isOverBudgetExit,
63
83
  postCaptureSettled,
84
+ recordPreflightCredit,
64
85
  scorePostCapture,
65
86
  seatableKinds,
66
87
  settleOverBudget,
67
88
  } from './handoff-gates.js';
89
+ import {
90
+ raisedDuplicationSuffix,
91
+ rescoreDuplication,
92
+ } from './handoff-rescore.js';
68
93
  import { handoffStatePath } from './handoff-state.js';
94
+ import { settleSuiteOfRecord } from './handoff-suite-of-record.js';
95
+ import { requestedLanes, runPreflightLanes } from './preflight-lanes.js';
69
96
  import { probeHeldReviewDiff } from './review-deposit.js';
97
+ import { runDuplicationCloseRescore } from './story-close/duplication-close-rescore.js';
70
98
  import { createStoryProgress, handoffStepName } from './story-progress.js';
71
99
  import {
72
100
  STATE_LABELS,
@@ -105,49 +133,24 @@ const SIGNALS = Object.freeze({
105
133
  offending: /^[+!] /,
106
134
  });
107
135
 
108
- /** CI's standalone ratchets; each runs only when its baseline is committed. */
109
- const RATCHETS = Object.freeze([
110
- {
111
- key: 'dead-exports',
112
- script: 'check-dead-exports.js',
113
- args: [],
114
- baseline: 'baselines/dead-exports.json',
115
- },
116
- {
117
- key: 'dead-exports-production',
118
- script: 'check-dead-exports.js',
119
- args: ['--production'],
120
- baseline: 'baselines/dead-exports-production.json',
121
- },
122
- {
123
- key: 'arch-cycles',
124
- script: 'check-arch-cycles.js',
125
- args: [],
126
- baseline: 'baselines/arch-cycles.json',
127
- },
128
- {
129
- key: 'cyclomatic',
130
- script: 'check-cyclomatic.js',
131
- args: [],
132
- baseline: 'baselines/cyclomatic.json',
133
- },
134
- ]);
135
-
136
136
  const MAX_OFFENDING_LINES = 10;
137
137
 
138
138
  const LOCK_POLL_MS = 1_000;
139
139
 
140
140
  const SEAT_SCRIPTS = Object.freeze({
141
+ coverage: 'update-coverage-baseline.js',
141
142
  crap: 'update-crap-baseline.js',
142
143
  maintainability: 'update-maintainability-baseline.js',
143
144
  });
144
145
 
145
146
  /**
146
- * A settled step. `stop` carries the envelope status that ends the run.
147
+ * A settled step. `stop` carries the envelope status that ends the run;
148
+ * `cause` its handoff-telemetry cause.
147
149
  *
148
150
  * @typedef {{ name: string, outcome: 'ran'|'skipped'|'deferred'|'failed'|'error'|'aborted',
149
151
  * detail: string, evidencePath?: string|null, conflictFiles?: string[],
150
- * stop?: 'fix-required'|'blocked', reason?: string }} StepResult
152
+ * stop?: 'fix-required'|'blocked', reason?: string, cause?: string,
153
+ * durationMs?: number|null, skippedByCredit?: boolean }} StepResult
151
154
  */
152
155
 
153
156
  const ran = (name, detail, extra = {}) => ({
@@ -162,6 +165,9 @@ const skipped = (name, detail, extra = {}) => ({
162
165
  detail,
163
166
  ...extra,
164
167
  });
168
+ /** A skip that reuses a result already recorded for this HEAD. */
169
+ const creditSkip = (name, detail, extra = {}) =>
170
+ skipped(name, detail, { ...extra, skippedByCredit: true });
165
171
  const fixRequired = (name, detail, extra = {}) => ({
166
172
  name,
167
173
  outcome: 'failed',
@@ -174,6 +180,7 @@ const blocked = (name, reason, detail, extra = {}) => ({
174
180
  outcome: 'failed',
175
181
  detail,
176
182
  reason,
183
+ cause: reason,
177
184
  stop: HANDOFF_STATUS.BLOCKED,
178
185
  ...extra,
179
186
  });
@@ -196,16 +203,21 @@ function headSha(ctx) {
196
203
  }
197
204
 
198
205
  /**
199
- * A child's env with `AP_AGENTRC_CWD` pinned to the Story worktree, layered
200
- * last so a stale inherited value cannot win: a gate judges the branch by
201
- * the branch's own `.agentrc.json`.
206
+ * A child's env with `AP_AGENTRC_CWD` pinned to the Story worktree and
207
+ * `MANDREL_HANDOFF_STEP` naming the running step, layered last so a stale
208
+ * inherited value cannot win: a gate judges the branch by the branch's own
209
+ * `.agentrc.json`, and a consumer check can key on the step.
202
210
  *
203
211
  * @param {object} ctx
204
212
  * @param {Record<string, string|undefined>} [env] defaults to `ctx.env`.
205
213
  * @returns {Record<string, string|undefined>}
206
214
  */
207
215
  function worktreeEnv(ctx, env) {
208
- return { ...(env ?? ctx.env), AP_AGENTRC_CWD: ctx.cwd };
216
+ return {
217
+ ...(env ?? ctx.env),
218
+ AP_AGENTRC_CWD: ctx.cwd,
219
+ MANDREL_HANDOFF_STEP: ctx.stepName,
220
+ };
209
221
  }
210
222
 
211
223
  /**
@@ -308,6 +320,12 @@ async function withLockProgress(ctx, run) {
308
320
  return { result, timings: summarizeLockEvents(events) };
309
321
  }
310
322
 
323
+ const SUITE_FAILURE_CAUSES = Object.freeze({
324
+ [LOCK_WAIT_EXPIRED_EXIT_CODE]: 'lock-wait-expired',
325
+ [ADMISSION_REFUSED_EXIT_CODE]: 'host-admission',
326
+ [TIMEOUT_EXIT_CODE]: 'suite-timeout',
327
+ });
328
+
311
329
  /**
312
330
  * The suite exit codes § 5 distinguishes from a red run.
313
331
  *
@@ -328,20 +346,22 @@ function describeSuiteFailure(status) {
328
346
  }
329
347
 
330
348
  /**
331
- * Lint and format (deposited), quality-preview, then each ratchet whose
349
+ * Typecheck, lint and format (deposited), quality-preview, then each ratchet whose
332
350
  * baseline is committed.
333
351
  *
334
352
  * @param {object} ctx
335
353
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean, deposit?: object }>}
336
354
  */
337
355
  function preflightChecks(ctx) {
338
- const ratchets = RATCHETS.filter((r) =>
356
+ const covered = new Set(getQuality(ctx.config).ratchets.coveredByLint);
357
+ const ratchets = STANDALONE_RATCHETS.filter((r) =>
339
358
  fs.existsSync(path.join(ctx.cwd, r.baseline)),
340
359
  ).map((r) => ({
341
360
  key: r.key,
342
361
  cmd: 'node',
343
362
  args: [path.join(SCRIPTS_DIR, r.script), ...r.args],
344
363
  gated: true,
364
+ coveredByLint: covered.has(r.key),
345
365
  }));
346
366
  return [
347
367
  ...creditedPreflight(ctx),
@@ -360,6 +380,7 @@ function preflightChecks(ctx) {
360
380
 
361
381
  /**
362
382
  * A ratchet also fails on `(gate fail)`; its finding names the `+`/`!` rows.
383
+ * Any other check quotes the failure rows its output carries.
363
384
  *
364
385
  * @param {{ key: string, gated?: boolean }} check
365
386
  * @param {{ status: number, output: string }} run
@@ -377,45 +398,149 @@ function preflightFinding(check, run) {
377
398
  .split(/\r?\n/)
378
399
  .filter((line) => SIGNALS.offending.test(line))
379
400
  .slice(0, MAX_OFFENDING_LINES)
380
- : [];
401
+ : extractFailureRows(run.output, { max: MAX_OFFENDING_LINES });
381
402
  const rows = offending.length > 0 ? `: ${offending.join('; ')}` : '';
382
403
  return `${check.key}${check.gated ? ' ratchet' : ''} finding${rows} — fix and commit, then re-run`;
383
404
  }
384
405
 
385
- /** @param {object} ctx @returns {Promise<StepResult>} */
406
+ /**
407
+ * Runs every check — serially, or over admitted lanes when
408
+ * `preflightConcurrency` asks (preflight-lanes.js) — then settles one
409
+ * `fix-required` listing each finding in check order; a passed carryable
410
+ * check keeps its credit either way.
411
+ *
412
+ * @param {object} ctx @returns {Promise<StepResult>}
413
+ */
386
414
  async function stepPreflight(ctx) {
387
415
  const name = 'preflight';
388
416
  if (ctx.state.preflightHead === ctx.head) {
389
- return skipped(
417
+ return creditSkip(
390
418
  name,
391
419
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
392
420
  );
393
421
  }
394
- ctx.state.lintCredit = null;
422
+ ctx.state.preflightCredits = {};
423
+ delete ctx.state.heldLint;
395
424
  let checks;
396
425
  try {
397
426
  checks = preflightChecks(ctx);
398
427
  } catch (err) {
399
428
  return fixRequired(
400
429
  name,
401
- `could not resolve close's lint/format gates: ${err?.message ?? err}`,
430
+ `could not resolve close's typecheck/lint/format gates: ${err?.message ?? err}`,
431
+ { cause: 'preflight-unresolved' },
402
432
  );
403
433
  }
404
- for (const check of checks) {
405
- const run = await runLogged(
406
- ctx,
407
- `preflight-${check.key}`,
408
- check.cmd,
409
- check.args,
434
+ let findings = [];
435
+ const pass = { checks, lint: null, covered: [] };
436
+ const lanes = requestedLanes(ctx);
437
+ let extra = {};
438
+ if (lanes) {
439
+ const run = await runPreflightLanes(ctx, checks, lanes, (check, env) =>
440
+ runPreflightCheck(ctx, check, pass, env),
410
441
  );
411
- const finding = preflightFinding(check, run);
412
- if (finding) {
413
- return fixRequired(name, finding, { evidencePath: run.evidencePath });
442
+ findings = run.findings;
443
+ extra = { concurrency: { requested: lanes, admitted: run.admitted } };
444
+ } else {
445
+ for (const check of checks) {
446
+ const finding = await runPreflightCheck(ctx, check, pass);
447
+ if (finding) findings.push(finding);
414
448
  }
415
- if (check.key === 'lint') ctx.state.lintCredit = lintCredit(ctx, check);
449
+ }
450
+ if (findings.length > 0) {
451
+ const { check, evidencePath } = findings[0];
452
+ return fixRequired(name, findings.map((f) => f.detail).join('\n'), {
453
+ evidencePath,
454
+ findings,
455
+ check,
456
+ cause: preflightCause(check),
457
+ ...extra,
458
+ });
416
459
  }
417
460
  ctx.state.preflightHead = ctx.head;
418
- return ran(name, `${checks.map((c) => c.key).join(', ')} clean`);
461
+ return ran(name, preflightSummary(pass), extra);
462
+ }
463
+
464
+ /** A baselined ratchet's finding is a `ratchet`; any other check is its own key. */
465
+ function preflightCause(key) {
466
+ return STANDALONE_RATCHETS.some((r) => r.key === key) ? 'ratchet' : key;
467
+ }
468
+
469
+ /**
470
+ * Runs one check unless this pass's lint covers it; records the lint result
471
+ * and credits a passed check.
472
+ *
473
+ * @returns {Promise<{ check: string, detail: string, evidencePath?: string }|null>}
474
+ */
475
+ async function runPreflightCheck(ctx, check, pass, env) {
476
+ const cover = lintCovers(check, pass);
477
+ if (cover === 'covered') {
478
+ pass.covered.push(check.key);
479
+ ctx.progress(
480
+ 'preflight',
481
+ `⏭ ${check.key} covered by lint (delivery.quality.ratchets.coveredByLint)`,
482
+ );
483
+ }
484
+ if (cover) return null;
485
+ const run = await runLogged(
486
+ ctx,
487
+ `preflight-${check.key}`,
488
+ check.cmd,
489
+ check.args,
490
+ env,
491
+ );
492
+ const detail = preflightFinding(check, run);
493
+ if (check.key === 'lint') pass.lint = detail ? 'failed' : 'passed';
494
+ if (!detail) {
495
+ creditCheck(ctx, check);
496
+ return null;
497
+ }
498
+ return { check: check.key, detail, evidencePath: run.evidencePath };
499
+ }
500
+
501
+ /**
502
+ * Why a covered ratchet does not spawn: `covered` once this pass's whole-tree
503
+ * lint exited 0, `lint-failed` once it failed (its finding stands). Anything
504
+ * else — no such lint, or not yet reached — runs the ratchet.
505
+ *
506
+ * @param {{ key: string, coveredByLint?: boolean }} check
507
+ * @param {{ checks: Array<{ key: string, wholeTree?: boolean }>, lint: 'passed'|'failed'|null }} pass
508
+ * @returns {'covered'|'lint-failed'|null}
509
+ */
510
+ function lintCovers(check, { checks, lint }) {
511
+ if (!check.coveredByLint || lint === null) return null;
512
+ if (!checks.some((c) => c.key === 'lint' && c.wholeTree)) return null;
513
+ return lint === 'passed' ? 'covered' : 'lint-failed';
514
+ }
515
+
516
+ /** The clean checks, then the ratchets lint covered, named apart. */
517
+ function preflightSummary({ checks, covered }) {
518
+ const clean = checks.map((c) => c.key).filter((k) => !covered.includes(k));
519
+ const note =
520
+ covered.length > 0 ? `; covered by lint: ${covered.join(', ')}` : '';
521
+ return `${clean.join(', ')} clean${note}`;
522
+ }
523
+
524
+ /** A held `lint` waits for the post-seat checks; any other check credits now. */
525
+ function creditCheck(ctx, check) {
526
+ if (!check.held) return recordPreflightCredit(ctx, check);
527
+ ctx.state.heldLint = {
528
+ head: ctx.head,
529
+ configHash: hashCommandConfig({ ...check.deposit, cwd: ctx.cwd }),
530
+ };
531
+ }
532
+
533
+ /** A baselines-only seat commit re-keys a held `lint`; any other commit drops it. */
534
+ function carryHeldLint(state, priorHead, head) {
535
+ if (state.heldLint?.head === priorHead) state.heldLint.head = head;
536
+ }
537
+
538
+ /** Record a held `lint` once every post-seat check passed at HEAD. */
539
+ function releaseHeldLint(ctx) {
540
+ const held = ctx.state.heldLint;
541
+ if (held?.head !== ctx.head) return;
542
+ ctx.state.preflightCredits.lint = carryCredit(ctx, 'lint', held);
543
+ delete ctx.state.heldLint;
419
544
  }
420
545
 
421
546
  /** A baseline-only conflict the shared sync resolved is named. */
@@ -431,13 +556,20 @@ function mergedDetail(sync, baseBranch) {
431
556
  /** @param {object} ctx @returns {Promise<StepResult>} */
432
557
  async function stepBaseMerge(ctx) {
433
558
  const name = 'base-merge';
559
+ const skip = await handoffRerunSkip(ctx);
560
+ if (skip) {
561
+ startReview(ctx);
562
+ return skipped(name, skip);
563
+ }
434
564
  const sync = await ctx.syncFromBase({
435
565
  cwd: ctx.cwd,
436
566
  baseBranch: ctx.baseBranch,
437
567
  log: ctx.progress,
438
568
  });
439
569
  if (sync.synced) {
570
+ ctx.state.baseMergeSettled = true;
440
571
  ctx.head = headSha(ctx) ?? ctx.head;
572
+ startReview(ctx);
441
573
  return sync.kind === 'noop-already-current'
442
574
  ? skipped(name, `origin/${ctx.baseBranch} already merged`)
443
575
  : ran(name, mergedDetail(sync, ctx.baseBranch));
@@ -456,17 +588,19 @@ async function stepBaseMerge(ctx) {
456
588
  return fixRequired(
457
589
  name,
458
590
  `merging origin/${ctx.baseBranch} conflicts; the merge was aborted, so the tree is clean — merge it yourself, resolve, commit, re-run`,
459
- { conflictFiles: sync.conflictFiles },
591
+ { conflictFiles: sync.conflictFiles, cause: 'base-merge-conflict' },
460
592
  );
461
593
  }
462
- return fixRequired(name, `merge failed: ${sync.stderr}`.trim());
594
+ return fixRequired(name, `merge failed: ${sync.stderr}`.trim(), {
595
+ cause: 'base-merge-failed',
596
+ });
463
597
  }
464
598
 
465
599
  /**
466
600
  * The depositor close will credit, from the one shared predicate.
467
601
  *
468
602
  * @param {{ config: object, scripts: Record<string, string>|null, cwd: string, getChangedFilesImpl?: Function }} args
469
- * @returns {'coverage-capture'|'test'}
603
+ * @returns {{ depositor: 'coverage-capture'|'test', skipBranch: boolean }}
470
604
  */
471
605
  function selectCreditedDepositor({ config, ...probe }) {
472
606
  const baseBranch = config?.project?.baseBranch ?? 'main';
@@ -474,40 +608,61 @@ function selectCreditedDepositor({ config, ...probe }) {
474
608
  }
475
609
 
476
610
  /**
477
- * @param {object|null|undefined} config
478
- * @returns {string[]}
611
+ * The `test` deposit's evidence-gate argv tail and step label: on the skip
612
+ * branch the scoped run (or the full suite, naming why), else close's argv.
479
613
  */
480
- function testGateArgv(config) {
481
- const { cmd, args } = resolveTestGateArgv(config);
482
- return [cmd, ...args];
614
+ function testDeposit(ctx) {
615
+ if (!ctx.skipBranch) {
616
+ const { cmd, args } = resolveTestGateArgv(ctx.config);
617
+ return { argv: ['--', cmd, ...args], label: ctx.depositor };
618
+ }
619
+ const deposit = skipBranchDeposit({
620
+ config: ctx.config,
621
+ cwd: ctx.cwd,
622
+ baseBranch: ctx.baseBranch,
623
+ gitSpawnImpl: ctx.git,
624
+ });
625
+ if (deposit.fallback)
626
+ ctx.progress('credited-run', `full suite: ${deposit.fallback}`);
627
+ return deposit;
628
+ }
629
+
630
+ /** The depositor's node argv and its step label. */
631
+ function depositorArgv(ctx) {
632
+ if (ctx.depositor === 'coverage-capture') {
633
+ const script = path.join(SCRIPTS_DIR, 'coverage-capture.js');
634
+ return { args: [script, '--cwd', ctx.cwd], label: ctx.depositor };
635
+ }
636
+ const deposit = testDeposit(ctx);
637
+ const args = [
638
+ path.join(SCRIPTS_DIR, 'evidence-gate.js'),
639
+ '--standalone',
640
+ '--scope-id',
641
+ String(ctx.storyId),
642
+ '--gate',
643
+ 'test',
644
+ '--worktree',
645
+ ctx.cwd,
646
+ // Credited under close's `test` identity, whichever argv runs.
647
+ ...deposit.argv,
648
+ ];
649
+ return { args, label: deposit.label };
483
650
  }
484
651
 
485
652
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
486
653
  async function creditedRun(ctx, signal) {
487
654
  const name = 'credited-run';
488
655
  if (ctx.state.creditHead === ctx.head) {
489
- return skipped(
656
+ return creditSkip(
490
657
  name,
491
658
  `${ctx.depositor} credit already deposited at ${ctx.head.slice(0, 12)}`,
492
659
  { depositor: ctx.depositor },
493
660
  );
494
661
  }
662
+ const ciOwned = settleSuiteOfRecord(ctx, name);
663
+ if (ciOwned) return ciOwned;
495
664
  const capture = ctx.depositor === 'coverage-capture';
496
- const args = capture
497
- ? [path.join(SCRIPTS_DIR, 'coverage-capture.js'), '--cwd', ctx.cwd]
498
- : [
499
- path.join(SCRIPTS_DIR, 'evidence-gate.js'),
500
- '--standalone',
501
- '--scope-id',
502
- String(ctx.storyId),
503
- '--gate',
504
- 'test',
505
- '--worktree',
506
- ctx.cwd,
507
- '--',
508
- // Close's `test` gate argv, so the deposit keys on its credit identity.
509
- ...testGateArgv(ctx.config),
510
- ];
665
+ const { args, label } = depositorArgv(ctx);
511
666
  const { result: run, timings } = await withLockProgress(ctx, (env) =>
512
667
  runLogged(ctx, 'credited-run', 'node', args, env, signal),
513
668
  );
@@ -526,31 +681,141 @@ async function creditedRun(ctx, signal) {
526
681
  ...extra,
527
682
  };
528
683
  }
529
- if (run.status !== 0) return settleSuiteExit(ctx, name, run.status, extra);
684
+ if (run.status !== 0) return settleSuiteExit(ctx, name, run, extra);
530
685
  const [ranSignal, freshSignal] = capture
531
686
  ? [SIGNALS.captureRan, SIGNALS.captureFresh]
532
687
  : [SIGNALS.testRan, SIGNALS.testFresh];
533
688
  const credit = { head: ctx.head, lockWait, suiteTimings, spawns };
534
689
  if (ranSignal.test(run.output)) {
535
690
  recordCredit(ctx, credit);
536
- return ran(name, `${ctx.depositor} deposited credit`, extra);
691
+ return ran(name, `${label} deposited credit`, extra);
537
692
  }
538
693
  if (freshSignal.test(run.output)) {
539
694
  recordCredit(ctx, credit);
540
- return skipped(name, `${ctx.depositor} credit already fresh`, extra);
695
+ return creditSkip(name, `${label} credit already fresh`, extra);
541
696
  }
542
697
  return fixRequired(
543
698
  name,
544
699
  `${ctx.depositor} exited 0 but printed no credit signal, so it deposited nothing`,
545
- extra,
700
+ { ...extra, cause: 'no-credit-signal' },
701
+ );
702
+ }
703
+
704
+ const HOST_COUNT_KEYS = Object.freeze([
705
+ 'testsPassed',
706
+ 'testsFailed',
707
+ 'workersLost',
708
+ 'peakWorkerRssMb',
709
+ ]);
710
+
711
+ const isPlainObject = (v) =>
712
+ v !== null && typeof v === 'object' && !Array.isArray(v);
713
+
714
+ /** One output line's `hostResources` object, else `null`; never throws. */
715
+ function hostResourcesFromLine(line) {
716
+ try {
717
+ const parsed = JSON.parse(line);
718
+ return isPlainObject(parsed) && isPlainObject(parsed.hostResources)
719
+ ? parsed.hostResources
720
+ : null;
721
+ } catch {
722
+ return null;
723
+ }
724
+ }
725
+
726
+ /**
727
+ * The consumer's optional counts: the last output line that parses as a JSON
728
+ * object with an object-valued `hostResources` key.
729
+ *
730
+ * @param {string} output
731
+ * @returns {object|null}
732
+ */
733
+ function parseHostResources(output) {
734
+ const lines = String(output ?? '').split(/\r?\n/);
735
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
736
+ const line = lines[i].trim();
737
+ if (!line.startsWith('{')) continue;
738
+ const found = hostResourcesFromLine(line);
739
+ if (found) return found;
740
+ }
741
+ return null;
742
+ }
743
+
744
+ /** @param {object|null} counts */
745
+ function countsSuffix(counts) {
746
+ const parts = HOST_COUNT_KEYS.filter((k) => Number.isFinite(counts?.[k])).map(
747
+ (k) => `${k}: ${counts[k]}`,
546
748
  );
749
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
547
750
  }
548
751
 
549
- /** A non-zero depositor exit: an over-budget capture by policy, else a fix. */
550
- function settleSuiteExit(ctx, name, status, extra) {
551
- return isOverBudgetCapture(ctx, status)
752
+ /**
753
+ * A credited run that lost workers to host memory (exit 77): `blocked`, no
754
+ * credit, one `host-resources` friction record. `ctx.hostResources` carries
755
+ * the consumer's counts to the envelope.
756
+ *
757
+ * @param {object} ctx @param {string} name @param {string} output @param {object} extra
758
+ * @returns {Promise<object>}
759
+ */
760
+ async function settleHostResources(ctx, name, output, extra) {
761
+ const counts = parseHostResources(output);
762
+ if (counts) ctx.hostResources = counts;
763
+ try {
764
+ await ctx.emitFriction({
765
+ storyId: ctx.storyId,
766
+ category: RUNTIME_FRICTION_CATEGORIES.HOST_RESOURCES,
767
+ tool: 'story-handoff',
768
+ details: {
769
+ exitCode: COVERAGE_HOST_RESOURCES_EXIT_CODE,
770
+ depositor: ctx.depositor,
771
+ head: ctx.head?.slice(0, 12) ?? null,
772
+ ...(counts ? { hostResources: counts } : {}),
773
+ },
774
+ config: ctx.config,
775
+ });
776
+ } catch {
777
+ // Telemetry never changes the envelope.
778
+ }
779
+ return {
780
+ name,
781
+ outcome: 'failed',
782
+ detail: `suite lost workers to host memory (exit ${COVERAGE_HOST_RESOURCES_EXIT_CODE})${countsSuffix(counts)} — no test failed, so do not re-run it unchanged on this host: use fewer workers, a larger host, or, when CI runs the suite with a coverage floor, have the capture script declare the slice over budget (exit 76) under delivery.quality.gates.coverage.onOverBudget: "defer-to-ci"`,
783
+ reason: 'host-resources',
784
+ stop: 'blocked',
785
+ ...extra,
786
+ };
787
+ }
788
+
789
+ /** The envelope's `hostResources` field, present only when the consumer reported counts. */
790
+ function hostResourcesEnvelope(ctx) {
791
+ return ctx.hostResources ? { hostResources: ctx.hostResources } : {};
792
+ }
793
+
794
+ /** A non-zero depositor exit: lost workers block, else {@link settleCodeExit}. */
795
+ function settleSuiteExit(ctx, name, { status, output }, extra) {
796
+ return status === COVERAGE_HOST_RESOURCES_EXIT_CODE
797
+ ? settleHostResources(ctx, name, output, extra)
798
+ : settleCodeExit(ctx, name, status, extra);
799
+ }
800
+
801
+ /** An over-budget depositor settles by policy, anything else is a fix. */
802
+ function settleCodeExit(ctx, name, status, extra) {
803
+ return isOverBudgetExit(status)
552
804
  ? settleOverBudget(ctx, name, extra)
553
- : fixRequired(name, describeSuiteFailure(status), extra);
805
+ : fixRequired(name, suiteFailureDetail(ctx, status), {
806
+ ...extra,
807
+ cause: SUITE_FAILURE_CAUSES[status] ?? 'red-suite',
808
+ });
809
+ }
810
+
811
+ /** A 124 records its HEAD, so a second one there stops recommending a re-run. */
812
+ function suiteFailureDetail(ctx, status) {
813
+ if (status !== TIMEOUT_EXIT_CODE) return describeSuiteFailure(status);
814
+ const repeated = ctx.state.timeoutHead === ctx.head;
815
+ ctx.state.timeoutHead = ctx.head;
816
+ return repeated
817
+ ? `suite timed out again at this HEAD (exit ${status}) — a plain re-run will not help: raise delivery.quality.gates.coverage.timeoutMs, have the capture script declare the slice over budget (exit 76, onOverBudget), or run on a quieter host`
818
+ : describeSuiteFailure(status);
554
819
  }
555
820
 
556
821
  /** Credit and its run's figures move together, keyed by the credited head. */
@@ -577,9 +842,17 @@ function changedPaths(git, cwd) {
577
842
  .filter((p) => p.length > 0);
578
843
  }
579
844
 
580
- /** @param {object} ctx @returns {Promise<StepResult>} */
581
- async function commitSeatedRows(ctx, total, evidencePath) {
582
- const name = 'seat';
845
+ /**
846
+ * @param {object} ctx
847
+ * @param {{ total: number, evidencePath: string|null }} seated
848
+ * @param {{ name: string, headKey: string }} step whose idempotency key it sets.
849
+ * @returns {Promise<StepResult>}
850
+ */
851
+ async function commitSeatedRows(
852
+ ctx,
853
+ { total, evidencePath },
854
+ { name, headKey },
855
+ ) {
583
856
  const paths = changedPaths(ctx.git, ctx.cwd);
584
857
  const add = ctx.git(ctx.cwd, 'add', '--', ...paths);
585
858
  const commit =
@@ -596,49 +869,102 @@ async function commitSeatedRows(ctx, total, evidencePath) {
596
869
  return fixRequired(
597
870
  name,
598
871
  `committing the seated rows failed: ${detail}`.trim(),
599
- { evidencePath: ctx.writeEvidence('seat-commit', detail) },
872
+ {
873
+ evidencePath: ctx.writeEvidence('seat-commit', detail),
874
+ cause: 'seat-commit-failed',
875
+ },
600
876
  );
601
877
  }
602
878
  const priorHead = ctx.head;
603
879
  const creditedPrior = ctx.state.creditHead === priorHead;
604
880
  ctx.head = headSha(ctx) ?? ctx.head;
605
881
  carryCoverageDeferral(ctx.state, priorHead, ctx.head);
606
- ctx.state.seatHead = ctx.head;
882
+ ctx.state[headKey] = ctx.head;
607
883
  // Both capture-stamp digests leave `baselines/` out, so a baseline-JSON-only
608
884
  // commit keeps the credit it already holds.
609
885
  if (creditedPrior && ctx.depositor === 'coverage-capture') {
610
886
  recordCredit(ctx, { ...ctx.state.creditTimings, head: ctx.head });
611
887
  }
612
888
  if (paths.every((p) => p.startsWith('baselines/'))) {
613
- carryLintCredit(ctx, priorHead);
889
+ carryPreflightCredits(ctx, priorHead);
890
+ carryHeldLint(ctx.state, priorHead, ctx.head);
614
891
  }
615
892
  return ran(name, `seated ${total} row(s) and committed them`, {
616
893
  evidencePath,
617
894
  });
618
895
  }
619
896
 
897
+ /** A coverage gate block that is present and not disabled, as close reads it. */
898
+ function isCoverageGateEnabled(config) {
899
+ const block = config?.delivery?.quality?.gates?.coverage;
900
+ return Boolean(block) && typeof block === 'object' && block.enabled !== false;
901
+ }
902
+
620
903
  /**
621
- * The gates whose baselines take a `--seat-missing` pass: CRAP by close's own
622
- * predicate, MI unless explicitly disabled (both default on).
904
+ * The post-capture seat's kinds: CRAP by close's own predicate, coverage
905
+ * when the capture deposits the artifact and its gate is enabled.
623
906
  *
624
- * @param {object} config
907
+ * @param {object} ctx
625
908
  * @returns {Array<keyof typeof SEAT_SCRIPTS>}
626
909
  */
627
- function seatKinds(config) {
628
- const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
910
+ function seatKinds(ctx) {
629
911
  return [
630
- ...(isCrapGateEnabled(config) ? ['crap'] : []),
631
- ...(mi === false ? [] : ['maintainability']),
912
+ ...(isCrapGateEnabled(ctx.config) ? ['crap'] : []),
913
+ ...(seatsCoverage(ctx) ? ['coverage'] : []),
632
914
  ];
633
915
  }
634
916
 
635
- /** @param {object} ctx @returns {Promise<StepResult>} */
636
- async function stepSeat(ctx) {
637
- const name = 'seat';
638
- if (ctx.state.seatHead === ctx.head) {
639
- return skipped(name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
917
+ /** The capture deposits the artifact the coverage seat reads. */
918
+ function seatsCoverage(ctx) {
919
+ return (
920
+ ctx.depositor === 'coverage-capture' && isCoverageGateEnabled(ctx.config)
921
+ );
922
+ }
923
+
924
+ /** Static MI needs no capture, so its seat runs before preflight. */
925
+ function staticSeatKinds(config) {
926
+ const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
927
+ return mi === false ? [] : ['maintainability'];
928
+ }
929
+
930
+ /** Seat `kinds` and commit any rows under `step.name`, keyed by `step.headKey`. */
931
+ async function seatAndCommit(ctx, kinds, step) {
932
+ if (ctx.state[step.headKey] === ctx.head) {
933
+ return creditSkip(step.name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
934
+ }
935
+ const seated = await runSeats(ctx, step.name, kinds);
936
+ if (seated.stop) return seated;
937
+ if (seated.total === 0) {
938
+ ctx.state[step.headKey] = ctx.head;
939
+ return skipped(step.name, 'seated: 0 — nothing to seat', {
940
+ evidencePath: seated.evidencePath,
941
+ });
640
942
  }
641
- const kinds = seatableKinds(ctx, seatKinds(ctx.config));
943
+ return commitSeatedRows(ctx, seated, step);
944
+ }
945
+
946
+ /** @param {object} ctx @returns {Promise<StepResult>} */
947
+ function stepSeatStatic(ctx) {
948
+ return seatAndCommit(ctx, staticSeatKinds(ctx.config), {
949
+ name: 'seat-static',
950
+ headKey: 'staticSeatHead',
951
+ });
952
+ }
953
+
954
+ /** @param {object} ctx @returns {Promise<StepResult>} */
955
+ function stepSeat(ctx) {
956
+ return seatAndCommit(ctx, seatableKinds(ctx, seatKinds(ctx)), {
957
+ name: 'seat',
958
+ headKey: 'seatHead',
959
+ });
960
+ }
961
+
962
+ /**
963
+ * Each kind's `--seat-missing` pass; a refusal or a missing `seated: N` stops.
964
+ *
965
+ * @returns {Promise<StepResult|{ total: number, evidencePath: string|null }>}
966
+ */
967
+ async function runSeats(ctx, name, kinds) {
642
968
  let total = 0;
643
969
  let evidencePath = null;
644
970
  for (const kind of kinds) {
@@ -652,59 +978,41 @@ async function stepSeat(ctx) {
652
978
  return fixRequired(
653
979
  name,
654
980
  `${kind} --seat-missing ${run.status !== 0 ? `refused (exit ${run.status})` : 'printed no `seated: N`'} — read the log for the fix`,
655
- { evidencePath: run.evidencePath },
981
+ { evidencePath: run.evidencePath, cause: 'seat-refused' },
656
982
  );
657
983
  }
658
984
  total += Number(match[1]);
659
985
  }
660
- if (total === 0) {
661
- ctx.state.seatHead = ctx.head;
662
- return skipped(name, 'seated: 0 — nothing to seat', { evidencePath });
663
- }
664
- return commitSeatedRows(ctx, total, evidencePath);
665
- }
666
-
667
- /**
668
- * @param {object} ctx
669
- * @returns {{ reachable: boolean, sha: string|null, detail: string }}
670
- */
671
- function remoteBranchSha(ctx) {
672
- const res = ctx.git(
673
- ctx.cwd,
674
- 'ls-remote',
675
- 'origin',
676
- `refs/heads/${ctx.branch}`,
677
- );
678
- if (res?.status !== 0) {
679
- return {
680
- reachable: false,
681
- sha: null,
682
- detail: `${res?.stderr ?? ''}`.trim(),
683
- };
684
- }
685
- const sha = (res.stdout ?? '').toString().trim().split(/\s+/)[0] || null;
686
- return { reachable: true, sha, detail: '' };
986
+ return { total, evidencePath };
687
987
  }
688
988
 
689
989
  const PORCELAIN_STATUS = /^\s*[ MADRCUT?!]{1,2}\s/;
690
990
 
991
+ // GitHub's ruleset engine failing mid-evaluation; it prints a `[remote
992
+ // rejected]` line too, so it must match first.
993
+ const RULESET_EVAL_FAILED = /fatal error in commit_refs_rules/i;
691
994
  const REMOTE_REJECTED =
692
995
  /\[remote rejected\]|permission to \S+ denied|returned error: 403/i;
693
996
  const REF_BEHIND = /\[rejected\].*\((non-fast-forward|fetch first)\)/;
694
997
  const REMOTE_UNREACHABLE =
695
998
  /could not resolve host|unable to access|could not read from remote|connection (refused|timed out|reset)|network is unreachable/i;
696
999
  const PUSH_FAILURES = [
1000
+ [RULESET_EVAL_FAILED, 'ruleset-eval-failed'],
697
1001
  [REMOTE_REJECTED, 'push-rejected'],
698
1002
  [REMOTE_UNREACHABLE, 'remote-unreachable'],
699
1003
  [REF_BEHIND, 'ref-behind'],
700
1004
  ];
1005
+ // shortcut: a fixed stride (every 3-4 first-parent commits passed in the
1006
+ // field); make it configurable only if a consumer needs a different one.
1007
+ const PUSH_STRIDE = 3;
701
1008
 
702
1009
  /**
703
1010
  * A push the remote refused or could not be reached is blocked; a branch
704
- * behind its remote or a failing `pre-push` hook is the worker's to fix.
1011
+ * behind its remote, a ruleset-evaluation failure or a failing `pre-push`
1012
+ * hook is the worker's to fix.
705
1013
  *
706
1014
  * @param {string} output
707
- * @returns {'push-rejected'|'remote-unreachable'|'ref-behind'|null}
1015
+ * @returns {'ruleset-eval-failed'|'push-rejected'|'remote-unreachable'|'ref-behind'|null}
708
1016
  */
709
1017
  function classifyPushFailure(output) {
710
1018
  for (const [pattern, reason] of PUSH_FAILURES) {
@@ -713,48 +1021,150 @@ function classifyPushFailure(output) {
713
1021
  return null;
714
1022
  }
715
1023
 
1024
+ /** @param {object} ctx @param {object} evidence @returns {StepResult} */
1025
+ function refBehind(ctx, evidence) {
1026
+ return fixRequired(
1027
+ 'push',
1028
+ `origin/${ctx.branch} has commits HEAD lacks — git fetch origin ${ctx.branch}, git merge origin/${ctx.branch}, re-run`,
1029
+ { ...evidence, cause: 'ref-behind' },
1030
+ );
1031
+ }
1032
+
1033
+ /** @param {object} ctx @param {string} sha */
1034
+ const refPush = (ctx, sha) => [
1035
+ 'push',
1036
+ 'origin',
1037
+ `${sha}:refs/heads/${ctx.branch}`,
1038
+ ];
1039
+
1040
+ /** @param {object} ctx @param {string[]} range @param {object} evidence */
1041
+ function rulesetFailure(ctx, range, evidence) {
1042
+ const shas = range.length > 0 ? range : ['<sha>'];
1043
+ const recipe = shas.map((sha) => `git ${refPush(ctx, sha).join(' ')}`);
1044
+ return fixRequired(
1045
+ 'push',
1046
+ `GitHub ruleset evaluation failed (commit_refs_rules) even when stepped — push each first-parent commit oldest first: ${recipe.join('; ')}; then re-run`,
1047
+ { ...evidence, reason: 'ruleset-eval-failed' },
1048
+ );
1049
+ }
1050
+
1051
+ /**
1052
+ * Every PUSH_STRIDE-th commit of the range before HEAD (each one in a short
1053
+ * range).
1054
+ *
1055
+ * @param {string[]} range
1056
+ * @returns {string[]}
1057
+ */
1058
+ function stepTargets(range) {
1059
+ const last = range.length - 1;
1060
+ return range.filter(
1061
+ (_, i) => i < last && (last < PUSH_STRIDE || (i + 1) % PUSH_STRIDE === 0),
1062
+ );
1063
+ }
1064
+
1065
+ const FIXABLE_PUSH = Object.freeze({
1066
+ 'ref-behind': (ctx, evidence) => refBehind(ctx, evidence),
1067
+ 'ruleset-eval-failed': (ctx, ev, range) => rulesetFailure(ctx, range, ev),
1068
+ });
1069
+
716
1070
  /**
717
1071
  * @param {object} ctx
718
1072
  * @param {{ output: string, evidencePath: string|null }} push
1073
+ * @param {string[]} [range] first-parent commits, oldest first.
719
1074
  * @returns {StepResult}
720
1075
  */
721
- function pushFailure(ctx, push) {
1076
+ function pushFailure(ctx, push, range = []) {
722
1077
  const reason = classifyPushFailure(push.output);
723
1078
  const evidence = { evidencePath: push.evidencePath };
724
- if (reason === 'ref-behind') {
725
- return fixRequired(
726
- 'push',
727
- `origin/${ctx.branch} has commits HEAD lacks — git fetch origin ${ctx.branch}, git merge origin/${ctx.branch}, re-run`,
728
- evidence,
729
- );
730
- }
1079
+ const fixable = FIXABLE_PUSH[reason];
1080
+ if (fixable) return fixable(ctx, evidence, range);
731
1081
  return reason
732
1082
  ? blocked('push', reason, `git push failed (${reason})`, evidence)
733
1083
  : fixRequired(
734
1084
  'push',
735
1085
  'git push failed locally (a pre-push hook?) — fix the cause with a NEW commit, re-run',
736
- evidence,
1086
+ { ...evidence, cause: 'push-hook' },
737
1087
  );
738
1088
  }
739
1089
 
1090
+ /**
1091
+ * HEAD's first-parent commits, oldest first, on neither the base nor the
1092
+ * remote Story branch tip.
1093
+ *
1094
+ * @param {object} ctx
1095
+ * @param {string|null} tip
1096
+ * @returns {string[]}
1097
+ */
1098
+ function firstParentRange(ctx, tip) {
1099
+ const res = ctx.git(
1100
+ ctx.cwd,
1101
+ 'rev-list',
1102
+ '--first-parent',
1103
+ '--reverse',
1104
+ 'HEAD',
1105
+ `^origin/${ctx.baseBranch}`,
1106
+ ...(tip ? [`^${tip}`] : []),
1107
+ );
1108
+ if (res?.status !== 0) return [];
1109
+ return `${res.stdout ?? ''}`.split(/\s+/).filter(Boolean);
1110
+ }
1111
+
1112
+ /**
1113
+ * Retry a ruleset-evaluation failure as a stepped push: the step targets,
1114
+ * then the branch itself.
1115
+ *
1116
+ * @param {object} ctx
1117
+ * @param {string|null} tip the remote Story branch sha before the push.
1118
+ * @param {{ evidencePath: string|null }} first the failed first push.
1119
+ * @returns {Promise<{ failure: StepResult }|{ evidencePath: string, how: string }>}
1120
+ */
1121
+ async function steppedPush(ctx, tip, first) {
1122
+ if (
1123
+ tip &&
1124
+ ctx.git(ctx.cwd, 'merge-base', '--is-ancestor', tip, 'HEAD')?.status !== 0
1125
+ ) {
1126
+ return { failure: refBehind(ctx, { evidencePath: first.evidencePath }) };
1127
+ }
1128
+ const range = firstParentRange(ctx, tip);
1129
+ const pushes = [
1130
+ ...stepTargets(range).map((sha) => refPush(ctx, sha)),
1131
+ ['push', '-u', 'origin', ctx.branch],
1132
+ ];
1133
+ let push;
1134
+ for (const [i, args] of pushes.entries()) {
1135
+ push = await runLogged(ctx, `push-step-${i + 1}`, 'git', args);
1136
+ if (push.status !== 0) return { failure: pushFailure(ctx, push, range) };
1137
+ }
1138
+ return {
1139
+ evidencePath: push.evidencePath,
1140
+ how: ` in a stepped push of ${pushes.length} step(s) after a ruleset-evaluation failure`,
1141
+ };
1142
+ }
1143
+
1144
+ /** The branch push, retried stepped on a ruleset-evaluation failure. */
1145
+ async function pushOrStep(ctx, tip) {
1146
+ const args = ['push', '-u', 'origin', ctx.branch];
1147
+ const push = await runLogged(ctx, 'push', 'git', args);
1148
+ if (push.status === 0) return { evidencePath: push.evidencePath, how: '' };
1149
+ if (classifyPushFailure(push.output) !== 'ruleset-eval-failed') {
1150
+ return { failure: pushFailure(ctx, push) };
1151
+ }
1152
+ return steppedPush(ctx, tip, push);
1153
+ }
1154
+
740
1155
  /** @param {object} ctx @returns {Promise<StepResult>} */
741
1156
  async function stepPush(ctx) {
742
1157
  const name = 'push';
743
- const before = remoteBranchSha(ctx);
1158
+ const before = remoteBranchSha(ctx.cwd, ctx.branch, ctx.git);
744
1159
  if (!before.reachable) {
745
1160
  return blocked(name, 'remote-unreachable', before.detail);
746
1161
  }
747
1162
  if (before.sha === ctx.head) {
748
1163
  return skipped(name, `origin/${ctx.branch} already at HEAD`);
749
1164
  }
750
- const push = await runLogged(ctx, 'push', 'git', [
751
- 'push',
752
- '-u',
753
- 'origin',
754
- ctx.branch,
755
- ]);
756
- if (push.status !== 0) return pushFailure(ctx, push);
757
- const after = remoteBranchSha(ctx);
1165
+ const push = await pushOrStep(ctx, before.sha);
1166
+ if (push.failure) return push.failure;
1167
+ const after = remoteBranchSha(ctx.cwd, ctx.branch, ctx.git);
758
1168
  if (after.sha !== ctx.head) {
759
1169
  return blocked(
760
1170
  name,
@@ -763,9 +1173,8 @@ async function stepPush(ctx) {
763
1173
  { evidencePath: push.evidencePath },
764
1174
  );
765
1175
  }
766
- return ran(name, `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}`, {
767
- evidencePath: push.evidencePath,
768
- });
1176
+ const detail = `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}${push.how}`;
1177
+ return ran(name, detail, { evidencePath: push.evidencePath });
769
1178
  }
770
1179
 
771
1180
  /**
@@ -775,16 +1184,24 @@ async function stepPush(ctx) {
775
1184
  * @returns {StepResult}
776
1185
  */
777
1186
  function reviewVerdict(deposit, depositPath, settled) {
778
- if (deposit?.halted) {
779
- return fixRequired(
780
- 'review',
781
- 'held review found a CRITICAL — fix, commit, re-run the handoff',
782
- { evidencePath: depositPath },
783
- );
784
- }
1187
+ if (deposit?.halted) return haltedReview(deposit, depositPath);
785
1188
  return settled;
786
1189
  }
787
1190
 
1191
+ /** No code change resolves a missing verdict, so that halt is blocked. */
1192
+ function haltedReview(deposit, depositPath) {
1193
+ if (deposit.haltCause === 'no-verdict') {
1194
+ return blocked('review', 'review-no-verdict', deposit.blockerReason, {
1195
+ evidencePath: depositPath,
1196
+ });
1197
+ }
1198
+ return fixRequired(
1199
+ 'review',
1200
+ 'held review found a CRITICAL — fix, commit, re-run the handoff',
1201
+ { evidencePath: depositPath, cause: 'review-critical' },
1202
+ );
1203
+ }
1204
+
788
1205
  /** @param {object} ctx @returns {Promise<StepResult>} */
789
1206
  async function computeHeldReview(ctx) {
790
1207
  const name = 'review';
@@ -801,7 +1218,7 @@ async function computeHeldReview(ctx) {
801
1218
  return reviewVerdict(
802
1219
  held.deposit,
803
1220
  ctx.reviewPath,
804
- skipped(name, 'held review already matches this diff'),
1221
+ creditSkip(name, 'held review already matches this diff'),
805
1222
  );
806
1223
  }
807
1224
  let outcome;
@@ -844,8 +1261,10 @@ function startReview(ctx) {
844
1261
  outcome: 'error',
845
1262
  detail: `held review failed (${err?.message ?? err}); close computes the review itself`,
846
1263
  }))
847
- .finally(() => {
1264
+ .then((result) => {
848
1265
  ctx.reviewMs = ctx.now() - startedAt;
1266
+ ctx.reviewSettled = result;
1267
+ return result;
849
1268
  });
850
1269
  return ctx.reviewPending;
851
1270
  }
@@ -854,7 +1273,7 @@ function startReview(ctx) {
854
1273
  async function stepCreditedRun(ctx) {
855
1274
  const abort = new AbortController();
856
1275
  let halted = null;
857
- startReview(ctx).then((result) => {
1276
+ ctx.reviewPending?.then((result) => {
858
1277
  if (!result.stop) return;
859
1278
  halted = result;
860
1279
  abort.abort();
@@ -867,6 +1286,17 @@ function stepReview(ctx) {
867
1286
  return ctx.reviewPending;
868
1287
  }
869
1288
 
1289
+ /**
1290
+ * Close's own duplication re-score, before any credit is minted, so close's
1291
+ * re-score no-ops on the handed-off tree. Best-effort: never stops the run.
1292
+ *
1293
+ * @param {object} ctx @returns {Promise<StepResult>}
1294
+ */
1295
+ async function stepDuplicationRescore(ctx) {
1296
+ const settled = await rescoreDuplication(ctx, () => headSha(ctx));
1297
+ return { name: 'duplication-rescore', ...settled };
1298
+ }
1299
+
870
1300
  /**
871
1301
  * Pure scoring after depositor and seat: no lock, no suite, no evidence, so
872
1302
  * close re-scores them and stays authoritative.
@@ -877,29 +1307,97 @@ async function stepPostCapture(ctx) {
877
1307
  const name = 'post-capture';
878
1308
  const { postCaptureHead } = ctx.state;
879
1309
  if (postCaptureHead === ctx.head && postCaptureSettled(ctx)) {
880
- return skipped(name, `already clean at ${ctx.head.slice(0, 12)}`);
1310
+ return creditSkip(name, `already clean at ${ctx.head.slice(0, 12)}`);
881
1311
  }
882
1312
  const { gates, failed } = await scorePostCapture(ctx, (...a) =>
883
1313
  runLogged(ctx, ...a),
884
1314
  );
885
1315
  if (failed) {
886
- return fixRequired(name, failed.finding, {
1316
+ const rows = raisedDuplicationSuffix(ctx, failed, MAX_OFFENDING_LINES);
1317
+ return fixRequired(name, `${failed.finding}${rows}`, {
887
1318
  evidencePath: failed.evidencePath,
888
1319
  gate: failed.gate,
1320
+ cause: 'post-capture',
889
1321
  });
890
1322
  }
1323
+ const post = await runPostSeatChecks(ctx, (...a) => runLogged(ctx, ...a));
1324
+ if (post.failed) return postSeatFixRequired(name, post.failed);
891
1325
  ctx.state.postCaptureHead = ctx.head;
892
- return gates.length > 0
893
- ? ran(name, `${gates.map((g) => g.name).join(', ')} clean`)
1326
+ return settledPostCapture(name, gates, post);
1327
+ }
1328
+
1329
+ /**
1330
+ * Run each `delivery.handoff.postSeatChecks` entry through `run`; the first
1331
+ * non-zero exit is the finding. Skipped under a coverage deferral.
1332
+ *
1333
+ * @returns {Promise<{ checks: object[], skipped?: boolean, failed: object|null }>}
1334
+ */
1335
+ async function runPostSeatChecks(ctx, run) {
1336
+ const checks = getPostSeatChecks(ctx.config);
1337
+ if (checks.length === 0) return { checks, failed: null };
1338
+ if (isCoverageDeferred(ctx)) return { checks, skipped: true, failed: null };
1339
+ for (const [i, check] of checks.entries()) {
1340
+ const res = await run(`post-seat-${i + 1}`, check.cmd, check.args);
1341
+ if (res.status !== 0)
1342
+ return { checks, failed: postSeatFailure(check, res) };
1343
+ }
1344
+ releaseHeldLint(ctx);
1345
+ return { checks, failed: null };
1346
+ }
1347
+
1348
+ /** A failed post-seat check as the handoff's finding. */
1349
+ function postSeatFailure(check, res) {
1350
+ const label = [check.cmd, ...check.args].join(' ');
1351
+ return {
1352
+ gate: 'post-seat',
1353
+ finding: `post-seat check \`${label}\` failed (exit ${res.status}) — fix and commit, then re-run`,
1354
+ evidencePath: res.evidencePath,
1355
+ };
1356
+ }
1357
+
1358
+ /** @param {string} name @param {{ finding: string, evidencePath: string, gate: string }} failed */
1359
+ function postSeatFixRequired(name, failed) {
1360
+ return fixRequired(name, failed.finding, {
1361
+ evidencePath: failed.evidencePath,
1362
+ gate: failed.gate,
1363
+ cause: 'post-capture',
1364
+ });
1365
+ }
1366
+
1367
+ /** The clean post-capture result, naming the post-seat checks' outcome. */
1368
+ function settledPostCapture(name, gates, post) {
1369
+ const names = gates.map((g) => g.name);
1370
+ if (post.checks.length > 0) {
1371
+ names.push(
1372
+ post.skipped
1373
+ ? 'post-seat checks skipped (coverage deferred)'
1374
+ : `${post.checks.length} post-seat check(s)`,
1375
+ );
1376
+ }
1377
+ return names.length > 0
1378
+ ? ran(name, `${names.join(', ')} clean`)
894
1379
  : skipped(name, 'no post-capture gate registered');
895
1380
  }
896
1381
 
1382
+ /** `step`, unless the review has already halted: then the halt is its result. */
1383
+ function beforeRun(step) {
1384
+ const guarded = (ctx) =>
1385
+ ctx.reviewSettled?.stop ? ctx.reviewSettled : step(ctx);
1386
+ return Object.defineProperty(guarded, 'name', { value: step.name });
1387
+ }
1388
+
1389
+ /** Append the settled review unless a step already recorded it. */
1390
+ function appendReview(steps, review) {
1391
+ if (review && !steps.some((s) => s.name === 'review')) steps.push(review);
1392
+ }
1393
+
897
1394
  /**
898
1395
  * The run's step order. The base merges first, so every check scores the
899
- * tree that is pushed. On the evidence-gate path the `test` credit is keyed
900
- * on the tree, so seating (static MI) goes first and cannot void it; the
901
- * capture stamp's digests leave `baselines/` out, so a baseline seat after it
902
- * keeps the stamp fresh.
1396
+ * tree that is pushed. Static MI seats before preflight, so no check refuses
1397
+ * a new file for a row the handoff can derive. On the evidence-gate path the
1398
+ * `test` credit is keyed on the tree, so the seat goes first and cannot void
1399
+ * it; the capture stamp's digests leave `baselines/` out, so the CRAP and
1400
+ * coverage seat after the capture keeps the stamp fresh.
903
1401
  *
904
1402
  * @param {'coverage-capture'|'test'} depositor
905
1403
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
@@ -907,10 +1405,12 @@ async function stepPostCapture(ctx) {
907
1405
  function stepOrder(depositor) {
908
1406
  const middle =
909
1407
  depositor === 'test'
910
- ? [stepSeat, stepCreditedRun]
911
- : [stepCreditedRun, stepSeat];
1408
+ ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1409
+ : [beforeRun(stepCreditedRun), stepSeat];
912
1410
  return [
913
1411
  stepBaseMerge,
1412
+ stepDuplicationRescore,
1413
+ stepSeatStatic,
914
1414
  stepPreflight,
915
1415
  ...middle,
916
1416
  stepPostCapture,
@@ -919,6 +1419,22 @@ function stepOrder(depositor) {
919
1419
  ];
920
1420
  }
921
1421
 
1422
+ /** `run`'s results, each carrying the call's wall time as `durationMs`. */
1423
+ async function timed(ctx, run) {
1424
+ const startedAt = ctx.now();
1425
+ const results = await run();
1426
+ const durationMs = ctx.now() - startedAt;
1427
+ return results.map((r) => ({ ...r, durationMs }));
1428
+ }
1429
+
1430
+ /**
1431
+ * The review ran concurrently with the credited run: its own wall time is
1432
+ * `ctx.reviewMs`, not the time spent awaiting it.
1433
+ */
1434
+ function envelopeStep(ctx, { stop: _stop, ...rest }) {
1435
+ return rest.name === 'review' ? { ...rest, durationMs: ctx.reviewMs } : rest;
1436
+ }
1437
+
922
1438
  /**
923
1439
  * Run the steps in order into `steps`; a step may settle several results.
924
1440
  *
@@ -926,8 +1442,9 @@ function stepOrder(depositor) {
926
1442
  */
927
1443
  async function runSteps(ctx, steps) {
928
1444
  for (const step of stepOrder(ctx.depositor)) {
929
- ctx.storyProgress.phase(handoffStepName(step));
930
- const results = [await step(ctx)].flat();
1445
+ ctx.stepName = handoffStepName(step);
1446
+ ctx.storyProgress.phase(ctx.stepName);
1447
+ const results = await timed(ctx, async () => [await step(ctx)].flat());
931
1448
  for (const result of results) {
932
1449
  steps.push(result);
933
1450
  ctx.progress(result.name, `${result.outcome} — ${result.detail}`);
@@ -938,6 +1455,8 @@ async function runSteps(ctx, steps) {
938
1455
  return null;
939
1456
  }
940
1457
 
1458
+ const PRECHECK = Object.freeze({ cause: 'precheck' });
1459
+
941
1460
  /**
942
1461
  * Refusals before any step: the handoff runs on the Story branch with the
943
1462
  * implementation committed.
@@ -951,16 +1470,18 @@ function precheck(ctx) {
951
1470
  return fixRequired(
952
1471
  'precheck',
953
1472
  `checked-out branch is ${current || 'unknown'}, not ${ctx.branch} — re-run single-story-init.js (idempotent) and work in its workCwd`,
1473
+ PRECHECK,
954
1474
  );
955
1475
  }
956
1476
  if (!ctx.head) {
957
- return fixRequired('precheck', 'HEAD does not resolve');
1477
+ return fixRequired('precheck', 'HEAD does not resolve', PRECHECK);
958
1478
  }
959
1479
  const dirty = changedPaths(ctx.git, ctx.cwd);
960
1480
  if (dirty.length > 0) {
961
1481
  return fixRequired(
962
1482
  'precheck',
963
1483
  `uncommitted changes (${dirty.slice(0, 5).join(', ')}) — commit the implementation, then re-run`,
1484
+ PRECHECK,
964
1485
  );
965
1486
  }
966
1487
  return null;
@@ -971,7 +1492,7 @@ function precheck(ctx) {
971
1492
  *
972
1493
  * @param {string} statePath
973
1494
  * @param {(tag: string, msg: string) => void} progress
974
- * @returns {{ preflightHead?: string, lintCredit?: { head: string, configHash: string }|null, creditHead?: string, creditTimings?: object, seatHead?: string, postCaptureHead?: string }}
1495
+ * @returns {{ baseMergeSettled?: boolean, preflightHead?: string, preflightCredits?: Record<string, { head: string, configHash: string }>, creditHead?: string, creditTimings?: object, seatHead?: string, staticSeatHead?: string, postCaptureHead?: string, duplicationRescore?: { head: string, partners: Record<string, string[]> } }}
975
1496
  */
976
1497
  function readState(statePath, progress) {
977
1498
  let raw;
@@ -1006,7 +1527,13 @@ async function defaultBlock({
1006
1527
  createProviderFn,
1007
1528
  warn,
1008
1529
  }) {
1009
- const provider = createProviderFn(config);
1530
+ let provider;
1531
+ try {
1532
+ provider = createProviderFn(config);
1533
+ } catch (err) {
1534
+ warn(`failed to create provider: ${err?.message ?? err}`);
1535
+ return;
1536
+ }
1010
1537
  try {
1011
1538
  await upsertStructuredComment(
1012
1539
  provider,
@@ -1030,6 +1557,7 @@ async function defaultBlock({
1030
1557
  * git?: typeof gitSpawn,
1031
1558
  * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string, timedOut?: boolean }>,
1032
1559
  * syncFromBase?: typeof syncBranchFromBase,
1560
+ * probeBaseSync?: typeof import('../git/base-sync-probe.js').probeBaseSync,
1033
1561
  * probeReview?: typeof probeHeldReviewDiff,
1034
1562
  * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
1035
1563
  * readPackageScriptsFn?: typeof readPackageScripts,
@@ -1051,6 +1579,10 @@ async function defaultBlock({
1051
1579
  * evidenceCwd?: string,
1052
1580
  * scopeGate?: typeof applyChangedFileScope,
1053
1581
  * presentBaselines?: string[],
1582
+ * runDuplicationRescore?: typeof runDuplicationCloseRescore,
1583
+ * emitFriction?: typeof emitRuntimeFriction,
1584
+ * writeSignal?: typeof import('../signals/write.js').appendSignal,
1585
+ * readSignals?: typeof import('../signals/write.js').forEachLine,
1054
1586
  * }} deps `evidenceCwd` anchors close's evidence store (the main checkout);
1055
1587
  * `runCommand` receives `onChunk`, `signal` and (when set)
1056
1588
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
@@ -1082,6 +1614,11 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1082
1614
  evidenceCwd = PROJECT_ROOT,
1083
1615
  scopeGate = applyChangedFileScope,
1084
1616
  presentBaselines,
1617
+ runDuplicationRescore = runDuplicationCloseRescore,
1618
+ emitFriction = emitRuntimeFriction,
1619
+ admitSuite = withSuiteAdmission,
1620
+ writeSignal,
1621
+ readSignals,
1085
1622
  } = deps;
1086
1623
  const block =
1087
1624
  deps.block ??
@@ -1110,6 +1647,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1110
1647
  git,
1111
1648
  runCommand,
1112
1649
  syncFromBase,
1650
+ probeBaseSync: deps.probeBaseSync,
1113
1651
  probeReview,
1114
1652
  computeReview,
1115
1653
  progress,
@@ -1122,9 +1660,13 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1122
1660
  scopeGate,
1123
1661
  presentBaselines,
1124
1662
  getChangedFilesFn,
1663
+ runDuplicationRescore,
1664
+ emitFriction,
1665
+ admitSuite,
1125
1666
  state: readState(statePath, progress),
1126
1667
  review: null,
1127
1668
  reviewPending: null,
1669
+ reviewSettled: null,
1128
1670
  reviewMs: null,
1129
1671
  reviewPath: storyReviewDepositPath(storyId, config),
1130
1672
  scripts: readPackageScriptsFn(cwd),
@@ -1144,24 +1686,49 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1144
1686
  return file;
1145
1687
  },
1146
1688
  };
1147
- ctx.depositor = selectCreditedDepositor({
1689
+ const plan = selectCreditedDepositor({
1148
1690
  config,
1149
1691
  scripts: ctx.scripts,
1150
1692
  cwd,
1151
1693
  getChangedFilesImpl: getChangedFilesFn,
1152
1694
  });
1695
+ ctx.depositor = plan.depositor;
1696
+ ctx.skipBranch = plan.skipBranch;
1153
1697
  ctx.head = headSha(ctx);
1154
1698
 
1155
1699
  const steps = [];
1156
- let stop = precheck(ctx);
1157
- if (stop) steps.push(stop);
1158
- else stop = await runSteps(ctx, steps);
1159
- await ctx.reviewPending;
1700
+ let stop;
1701
+ try {
1702
+ [stop] = await timed(ctx, async () => [precheck(ctx)].filter(Boolean));
1703
+ if (stop) steps.push(stop);
1704
+ else stop = await runSteps(ctx, steps);
1705
+ } catch (err) {
1706
+ // A runner fault is re-runnable, so it never flips agent::blocked.
1707
+ stop = fixRequired(
1708
+ ctx.stepName ?? 'precheck',
1709
+ `threw: ${err?.message ?? err}`,
1710
+ {
1711
+ cause: 'other',
1712
+ },
1713
+ );
1714
+ steps.push(stop);
1715
+ progress(stop.name, `${stop.outcome} — ${stop.detail}`);
1716
+ }
1717
+ appendReview(steps, await ctx.reviewPending);
1160
1718
 
1161
1719
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1162
1720
  const credited = steps.find((s) => s.name === 'credited-run');
1163
1721
  if (status === HANDOFF_STATUS.BLOCKED) {
1164
- await block({ storyId, config, reason: stop.reason, detail: stop.detail });
1722
+ try {
1723
+ await block({
1724
+ storyId,
1725
+ config,
1726
+ reason: stop.reason,
1727
+ detail: stop.detail,
1728
+ });
1729
+ } catch (err) {
1730
+ progress('BLOCK', `block failed: ${err?.message ?? err}`);
1731
+ }
1165
1732
  }
1166
1733
  const envelope = {
1167
1734
  kind: 'story-handoff',
@@ -1170,24 +1737,35 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1170
1737
  headSha: ctx.head,
1171
1738
  status,
1172
1739
  depositor: ctx.depositor,
1173
- steps: steps.map(({ stop: _stop, ...rest }) => rest),
1740
+ steps: steps.map((step) => envelopeStep(ctx, step)),
1174
1741
  review: ctx.review,
1175
1742
  lockWait: credited?.lockWait ?? null,
1176
1743
  suiteTimings: credited?.suiteTimings ?? null,
1177
1744
  reviewMs: ctx.reviewMs,
1178
1745
  ...coverageEnvelope(ctx),
1746
+ ...hostResourcesEnvelope(ctx),
1747
+ ...ctx.baseMergeEnvelope,
1179
1748
  ...(stop
1180
1749
  ? {
1181
1750
  failedStep: stop.name,
1751
+ cause: handoffCause(stop.cause),
1182
1752
  evidencePath: stop.evidencePath ?? null,
1183
1753
  ...(stop.reason ? { reason: stop.reason } : {}),
1184
1754
  ...(stop.conflictFiles ? { conflictFiles: stop.conflictFiles } : {}),
1185
1755
  }
1186
1756
  : {}),
1757
+ attempt: await nextHandoffAttempt({ storyId, config, readFn: readSignals }),
1187
1758
  };
1188
1759
  writeFileAtomic(
1189
1760
  statePath,
1190
1761
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
1191
1762
  );
1763
+ await emitHandoffRecord({
1764
+ storyId,
1765
+ envelope,
1766
+ config,
1767
+ writeFn: writeSignal,
1768
+ warn: (m) => progress('TELEMETRY', m),
1769
+ });
1192
1770
  return { envelope, exitCode: EXIT_CODES[status] };
1193
1771
  }