mandrel 2.111.0 → 2.113.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 (183) 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 +367 -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/merge-envelopes.js +46 -1
  38. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  39. package/.agents/scripts/lib/baselines/reader.js +36 -9
  40. package/.agents/scripts/lib/baselines/refresh-service.js +93 -21
  41. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  42. package/.agents/scripts/lib/baselines/writer.js +36 -21
  43. package/.agents/scripts/lib/changed-files.js +70 -6
  44. package/.agents/scripts/lib/child-exec.js +10 -0
  45. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  46. package/.agents/scripts/lib/close-lock-events.js +8 -3
  47. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  48. package/.agents/scripts/lib/close-validation/gates.js +111 -35
  49. package/.agents/scripts/lib/close-validation/process.js +16 -7
  50. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  51. package/.agents/scripts/lib/close-validation/runner.js +55 -23
  52. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  53. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  54. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  55. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  56. package/.agents/scripts/lib/config/explain.js +5 -2
  57. package/.agents/scripts/lib/config/gates/coverage.schema.js +45 -1
  58. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  59. package/.agents/scripts/lib/config/git-roots.js +38 -4
  60. package/.agents/scripts/lib/config/handoff.js +24 -0
  61. package/.agents/scripts/lib/config/quality.js +26 -13
  62. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  63. package/.agents/scripts/lib/config-resolver.js +22 -2
  64. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  65. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  66. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  67. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  68. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  69. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  70. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  71. package/.agents/scripts/lib/coverage-capture.js +15 -0
  72. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  73. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  74. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  75. package/.agents/scripts/lib/crap-engine.js +3 -3
  76. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  77. package/.agents/scripts/lib/error-redactor.js +20 -0
  78. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  79. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  80. package/.agents/scripts/lib/failure-rows.js +121 -0
  81. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  82. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  83. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  84. package/.agents/scripts/lib/gh-env.js +3 -6
  85. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  86. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  87. package/.agents/scripts/lib/git/baseline-conflict-rows.js +60 -0
  88. package/.agents/scripts/lib/git/sync-from-base.js +18 -9
  89. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  90. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  91. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  92. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  93. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  94. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  95. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  96. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  97. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  102. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  103. package/.agents/scripts/lib/orchestration/handoff-gates.js +129 -62
  104. package/.agents/scripts/lib/orchestration/handoff-rescore.js +170 -0
  105. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  106. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  107. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  108. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  109. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  110. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  111. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +41 -12
  112. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +90 -39
  113. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  114. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +102 -3
  115. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  116. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  117. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  118. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  119. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  120. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  121. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  122. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  123. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +16 -3
  124. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  125. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  127. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +9 -12
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +26 -12
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-gate-steps.js +2 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -2
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +50 -17
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  140. package/.agents/scripts/lib/orchestration/single-story-close/result.js +30 -13
  141. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  142. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -3
  143. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  144. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +77 -15
  145. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  146. package/.agents/scripts/lib/orchestration/story-handoff.js +796 -196
  147. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  148. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  149. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  150. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  151. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  152. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  153. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  154. package/.agents/scripts/lib/suite-admission.js +20 -8
  155. package/.agents/scripts/lib/suite-sizing.js +146 -0
  156. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  157. package/.agents/scripts/merge-baseline.js +14 -3
  158. package/.agents/scripts/providers/github/comments.js +19 -3
  159. package/.agents/scripts/providers/github.js +1 -0
  160. package/.agents/scripts/review-dispositions-report.js +1 -1
  161. package/.agents/scripts/role-scope-guard.js +267 -0
  162. package/.agents/scripts/single-story-close.js +4 -4
  163. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  164. package/.agents/scripts/single-story-init.js +24 -4
  165. package/.agents/scripts/story-handoff.js +3 -3
  166. package/.agents/scripts/story-outcomes-report.js +231 -0
  167. package/.agents/scripts/story-review-compute.js +9 -5
  168. package/.agents/scripts/update-coverage-baseline.js +12 -2
  169. package/.agents/scripts/update-crap-baseline.js +9 -1
  170. package/.agents/workflows/helpers/code-review.md +63 -9
  171. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  172. package/.agents/workflows/helpers/deliver-reference.md +233 -67
  173. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  174. package/.agents/workflows/helpers/deliver-story.md +7 -2
  175. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  176. package/docs/CHANGELOG.md +55 -0
  177. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  178. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  179. package/lib/cli/doctor-checks/llm-review.js +2 -11
  180. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  181. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  182. package/lib/cli/registry.js +5 -0
  183. 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,171 @@ 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 finding = preflightFinding(check, run);
493
+ if (check.key === 'lint') pass.lint = finding ? 'failed' : 'passed';
494
+ if (!finding) {
495
+ creditCheck(ctx, check);
496
+ return null;
497
+ }
498
+ const detail = finding + seatHint(ctx, check);
499
+ return { check: check.key, detail, evidencePath: run.evidencePath };
500
+ }
501
+
502
+ /**
503
+ * A failed lint on a change set that adds files may be a missing coverage or
504
+ * CRAP row the seat writes only after preflight: name the downgrade contract.
505
+ */
506
+ function seatHint(ctx, check) {
507
+ if (check.key !== 'lint') return '';
508
+ const added = gitLine(ctx.git, ctx.cwd, [
509
+ 'diff',
510
+ '--name-only',
511
+ '--diff-filter=A',
512
+ `origin/${ctx.baseBranch}...HEAD`,
513
+ ]);
514
+ if (!added) return '';
515
+ return (
516
+ '\n hint: this change set adds files, whose coverage and CRAP rows are seated after preflight; ' +
517
+ 'a check refusing a missing row for a change-set file must downgrade under ' +
518
+ 'MANDREL_HANDOFF_STEP=preflight and be declared in delivery.handoff.postSeatChecks ' +
519
+ '(.agents/docs/configuration.md § delivery.handoff.postSeatChecks)'
520
+ );
521
+ }
522
+
523
+ /**
524
+ * Why a covered ratchet does not spawn: `covered` once this pass's whole-tree
525
+ * lint exited 0, `lint-failed` once it failed (its finding stands). Anything
526
+ * else — no such lint, or not yet reached — runs the ratchet.
527
+ *
528
+ * @param {{ key: string, coveredByLint?: boolean }} check
529
+ * @param {{ checks: Array<{ key: string, wholeTree?: boolean }>, lint: 'passed'|'failed'|null }} pass
530
+ * @returns {'covered'|'lint-failed'|null}
531
+ */
532
+ function lintCovers(check, { checks, lint }) {
533
+ if (!check.coveredByLint || lint === null) return null;
534
+ if (!checks.some((c) => c.key === 'lint' && c.wholeTree)) return null;
535
+ return lint === 'passed' ? 'covered' : 'lint-failed';
536
+ }
537
+
538
+ /** The clean checks, then the ratchets lint covered, named apart. */
539
+ function preflightSummary({ checks, covered }) {
540
+ const clean = checks.map((c) => c.key).filter((k) => !covered.includes(k));
541
+ const note =
542
+ covered.length > 0 ? `; covered by lint: ${covered.join(', ')}` : '';
543
+ return `${clean.join(', ')} clean${note}`;
544
+ }
545
+
546
+ /** A held `lint` waits for the post-seat checks; any other check credits now. */
547
+ function creditCheck(ctx, check) {
548
+ if (!check.held) return recordPreflightCredit(ctx, check);
549
+ ctx.state.heldLint = {
550
+ head: ctx.head,
551
+ configHash: hashCommandConfig({ ...check.deposit, cwd: ctx.cwd }),
552
+ };
553
+ }
554
+
555
+ /** A baselines-only seat commit re-keys a held `lint`; any other commit drops it. */
556
+ function carryHeldLint(state, priorHead, head) {
557
+ if (state.heldLint?.head === priorHead) state.heldLint.head = head;
558
+ }
559
+
560
+ /** Record a held `lint` once every post-seat check passed at HEAD. */
561
+ function releaseHeldLint(ctx) {
562
+ const held = ctx.state.heldLint;
563
+ if (held?.head !== ctx.head) return;
564
+ ctx.state.preflightCredits.lint = carryCredit(ctx, 'lint', held);
565
+ delete ctx.state.heldLint;
419
566
  }
420
567
 
421
568
  /** A baseline-only conflict the shared sync resolved is named. */
@@ -431,13 +578,20 @@ function mergedDetail(sync, baseBranch) {
431
578
  /** @param {object} ctx @returns {Promise<StepResult>} */
432
579
  async function stepBaseMerge(ctx) {
433
580
  const name = 'base-merge';
581
+ const skip = await handoffRerunSkip(ctx);
582
+ if (skip) {
583
+ startReview(ctx);
584
+ return skipped(name, skip);
585
+ }
434
586
  const sync = await ctx.syncFromBase({
435
587
  cwd: ctx.cwd,
436
588
  baseBranch: ctx.baseBranch,
437
589
  log: ctx.progress,
438
590
  });
439
591
  if (sync.synced) {
592
+ ctx.state.baseMergeSettled = true;
440
593
  ctx.head = headSha(ctx) ?? ctx.head;
594
+ startReview(ctx);
441
595
  return sync.kind === 'noop-already-current'
442
596
  ? skipped(name, `origin/${ctx.baseBranch} already merged`)
443
597
  : ran(name, mergedDetail(sync, ctx.baseBranch));
@@ -456,17 +610,19 @@ async function stepBaseMerge(ctx) {
456
610
  return fixRequired(
457
611
  name,
458
612
  `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 },
613
+ { conflictFiles: sync.conflictFiles, cause: 'base-merge-conflict' },
460
614
  );
461
615
  }
462
- return fixRequired(name, `merge failed: ${sync.stderr}`.trim());
616
+ return fixRequired(name, `merge failed: ${sync.stderr}`.trim(), {
617
+ cause: 'base-merge-failed',
618
+ });
463
619
  }
464
620
 
465
621
  /**
466
622
  * The depositor close will credit, from the one shared predicate.
467
623
  *
468
624
  * @param {{ config: object, scripts: Record<string, string>|null, cwd: string, getChangedFilesImpl?: Function }} args
469
- * @returns {'coverage-capture'|'test'}
625
+ * @returns {{ depositor: 'coverage-capture'|'test', skipBranch: boolean }}
470
626
  */
471
627
  function selectCreditedDepositor({ config, ...probe }) {
472
628
  const baseBranch = config?.project?.baseBranch ?? 'main';
@@ -474,40 +630,61 @@ function selectCreditedDepositor({ config, ...probe }) {
474
630
  }
475
631
 
476
632
  /**
477
- * @param {object|null|undefined} config
478
- * @returns {string[]}
633
+ * The `test` deposit's evidence-gate argv tail and step label: on the skip
634
+ * branch the scoped run (or the full suite, naming why), else close's argv.
479
635
  */
480
- function testGateArgv(config) {
481
- const { cmd, args } = resolveTestGateArgv(config);
482
- return [cmd, ...args];
636
+ function testDeposit(ctx) {
637
+ if (!ctx.skipBranch) {
638
+ const { cmd, args } = resolveTestGateArgv(ctx.config);
639
+ return { argv: ['--', cmd, ...args], label: ctx.depositor };
640
+ }
641
+ const deposit = skipBranchDeposit({
642
+ config: ctx.config,
643
+ cwd: ctx.cwd,
644
+ baseBranch: ctx.baseBranch,
645
+ gitSpawnImpl: ctx.git,
646
+ });
647
+ if (deposit.fallback)
648
+ ctx.progress('credited-run', `full suite: ${deposit.fallback}`);
649
+ return deposit;
650
+ }
651
+
652
+ /** The depositor's node argv and its step label. */
653
+ function depositorArgv(ctx) {
654
+ if (ctx.depositor === 'coverage-capture') {
655
+ const script = path.join(SCRIPTS_DIR, 'coverage-capture.js');
656
+ return { args: [script, '--cwd', ctx.cwd], label: ctx.depositor };
657
+ }
658
+ const deposit = testDeposit(ctx);
659
+ const args = [
660
+ path.join(SCRIPTS_DIR, 'evidence-gate.js'),
661
+ '--standalone',
662
+ '--scope-id',
663
+ String(ctx.storyId),
664
+ '--gate',
665
+ 'test',
666
+ '--worktree',
667
+ ctx.cwd,
668
+ // Credited under close's `test` identity, whichever argv runs.
669
+ ...deposit.argv,
670
+ ];
671
+ return { args, label: deposit.label };
483
672
  }
484
673
 
485
674
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
486
675
  async function creditedRun(ctx, signal) {
487
676
  const name = 'credited-run';
488
677
  if (ctx.state.creditHead === ctx.head) {
489
- return skipped(
678
+ return creditSkip(
490
679
  name,
491
680
  `${ctx.depositor} credit already deposited at ${ctx.head.slice(0, 12)}`,
492
681
  { depositor: ctx.depositor },
493
682
  );
494
683
  }
684
+ const ciOwned = settleSuiteOfRecord(ctx, name);
685
+ if (ciOwned) return ciOwned;
495
686
  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
- ];
687
+ const { args, label } = depositorArgv(ctx);
511
688
  const { result: run, timings } = await withLockProgress(ctx, (env) =>
512
689
  runLogged(ctx, 'credited-run', 'node', args, env, signal),
513
690
  );
@@ -526,31 +703,141 @@ async function creditedRun(ctx, signal) {
526
703
  ...extra,
527
704
  };
528
705
  }
529
- if (run.status !== 0) return settleSuiteExit(ctx, name, run.status, extra);
706
+ if (run.status !== 0) return settleSuiteExit(ctx, name, run, extra);
530
707
  const [ranSignal, freshSignal] = capture
531
708
  ? [SIGNALS.captureRan, SIGNALS.captureFresh]
532
709
  : [SIGNALS.testRan, SIGNALS.testFresh];
533
710
  const credit = { head: ctx.head, lockWait, suiteTimings, spawns };
534
711
  if (ranSignal.test(run.output)) {
535
712
  recordCredit(ctx, credit);
536
- return ran(name, `${ctx.depositor} deposited credit`, extra);
713
+ return ran(name, `${label} deposited credit`, extra);
537
714
  }
538
715
  if (freshSignal.test(run.output)) {
539
716
  recordCredit(ctx, credit);
540
- return skipped(name, `${ctx.depositor} credit already fresh`, extra);
717
+ return creditSkip(name, `${label} credit already fresh`, extra);
541
718
  }
542
719
  return fixRequired(
543
720
  name,
544
721
  `${ctx.depositor} exited 0 but printed no credit signal, so it deposited nothing`,
545
- extra,
722
+ { ...extra, cause: 'no-credit-signal' },
546
723
  );
547
724
  }
548
725
 
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)
726
+ const HOST_COUNT_KEYS = Object.freeze([
727
+ 'testsPassed',
728
+ 'testsFailed',
729
+ 'workersLost',
730
+ 'peakWorkerRssMb',
731
+ ]);
732
+
733
+ const isPlainObject = (v) =>
734
+ v !== null && typeof v === 'object' && !Array.isArray(v);
735
+
736
+ /** One output line's `hostResources` object, else `null`; never throws. */
737
+ function hostResourcesFromLine(line) {
738
+ try {
739
+ const parsed = JSON.parse(line);
740
+ return isPlainObject(parsed) && isPlainObject(parsed.hostResources)
741
+ ? parsed.hostResources
742
+ : null;
743
+ } catch {
744
+ return null;
745
+ }
746
+ }
747
+
748
+ /**
749
+ * The consumer's optional counts: the last output line that parses as a JSON
750
+ * object with an object-valued `hostResources` key.
751
+ *
752
+ * @param {string} output
753
+ * @returns {object|null}
754
+ */
755
+ function parseHostResources(output) {
756
+ const lines = String(output ?? '').split(/\r?\n/);
757
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
758
+ const line = lines[i].trim();
759
+ if (!line.startsWith('{')) continue;
760
+ const found = hostResourcesFromLine(line);
761
+ if (found) return found;
762
+ }
763
+ return null;
764
+ }
765
+
766
+ /** @param {object|null} counts */
767
+ function countsSuffix(counts) {
768
+ const parts = HOST_COUNT_KEYS.filter((k) => Number.isFinite(counts?.[k])).map(
769
+ (k) => `${k}: ${counts[k]}`,
770
+ );
771
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
772
+ }
773
+
774
+ /**
775
+ * A credited run that lost workers to host memory (exit 77): `blocked`, no
776
+ * credit, one `host-resources` friction record. `ctx.hostResources` carries
777
+ * the consumer's counts to the envelope.
778
+ *
779
+ * @param {object} ctx @param {string} name @param {string} output @param {object} extra
780
+ * @returns {Promise<object>}
781
+ */
782
+ async function settleHostResources(ctx, name, output, extra) {
783
+ const counts = parseHostResources(output);
784
+ if (counts) ctx.hostResources = counts;
785
+ try {
786
+ await ctx.emitFriction({
787
+ storyId: ctx.storyId,
788
+ category: RUNTIME_FRICTION_CATEGORIES.HOST_RESOURCES,
789
+ tool: 'story-handoff',
790
+ details: {
791
+ exitCode: COVERAGE_HOST_RESOURCES_EXIT_CODE,
792
+ depositor: ctx.depositor,
793
+ head: ctx.head?.slice(0, 12) ?? null,
794
+ ...(counts ? { hostResources: counts } : {}),
795
+ },
796
+ config: ctx.config,
797
+ });
798
+ } catch {
799
+ // Telemetry never changes the envelope.
800
+ }
801
+ return {
802
+ name,
803
+ outcome: 'failed',
804
+ 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"`,
805
+ reason: 'host-resources',
806
+ stop: 'blocked',
807
+ ...extra,
808
+ };
809
+ }
810
+
811
+ /** The envelope's `hostResources` field, present only when the consumer reported counts. */
812
+ function hostResourcesEnvelope(ctx) {
813
+ return ctx.hostResources ? { hostResources: ctx.hostResources } : {};
814
+ }
815
+
816
+ /** A non-zero depositor exit: lost workers block, else {@link settleCodeExit}. */
817
+ function settleSuiteExit(ctx, name, { status, output }, extra) {
818
+ return status === COVERAGE_HOST_RESOURCES_EXIT_CODE
819
+ ? settleHostResources(ctx, name, output, extra)
820
+ : settleCodeExit(ctx, name, status, extra);
821
+ }
822
+
823
+ /** An over-budget depositor settles by policy, anything else is a fix. */
824
+ function settleCodeExit(ctx, name, status, extra) {
825
+ return isOverBudgetExit(status)
552
826
  ? settleOverBudget(ctx, name, extra)
553
- : fixRequired(name, describeSuiteFailure(status), extra);
827
+ : fixRequired(name, suiteFailureDetail(ctx, status), {
828
+ ...extra,
829
+ cause: SUITE_FAILURE_CAUSES[status] ?? 'red-suite',
830
+ });
831
+ }
832
+
833
+ /** A 124 records its HEAD, so a second one there stops recommending a re-run. */
834
+ function suiteFailureDetail(ctx, status) {
835
+ if (status !== TIMEOUT_EXIT_CODE) return describeSuiteFailure(status);
836
+ const repeated = ctx.state.timeoutHead === ctx.head;
837
+ ctx.state.timeoutHead = ctx.head;
838
+ return repeated
839
+ ? `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`
840
+ : describeSuiteFailure(status);
554
841
  }
555
842
 
556
843
  /** Credit and its run's figures move together, keyed by the credited head. */
@@ -577,9 +864,17 @@ function changedPaths(git, cwd) {
577
864
  .filter((p) => p.length > 0);
578
865
  }
579
866
 
580
- /** @param {object} ctx @returns {Promise<StepResult>} */
581
- async function commitSeatedRows(ctx, total, evidencePath) {
582
- const name = 'seat';
867
+ /**
868
+ * @param {object} ctx
869
+ * @param {{ total: number, evidencePath: string|null }} seated
870
+ * @param {{ name: string, headKey: string }} step whose idempotency key it sets.
871
+ * @returns {Promise<StepResult>}
872
+ */
873
+ async function commitSeatedRows(
874
+ ctx,
875
+ { total, evidencePath },
876
+ { name, headKey },
877
+ ) {
583
878
  const paths = changedPaths(ctx.git, ctx.cwd);
584
879
  const add = ctx.git(ctx.cwd, 'add', '--', ...paths);
585
880
  const commit =
@@ -596,49 +891,102 @@ async function commitSeatedRows(ctx, total, evidencePath) {
596
891
  return fixRequired(
597
892
  name,
598
893
  `committing the seated rows failed: ${detail}`.trim(),
599
- { evidencePath: ctx.writeEvidence('seat-commit', detail) },
894
+ {
895
+ evidencePath: ctx.writeEvidence('seat-commit', detail),
896
+ cause: 'seat-commit-failed',
897
+ },
600
898
  );
601
899
  }
602
900
  const priorHead = ctx.head;
603
901
  const creditedPrior = ctx.state.creditHead === priorHead;
604
902
  ctx.head = headSha(ctx) ?? ctx.head;
605
903
  carryCoverageDeferral(ctx.state, priorHead, ctx.head);
606
- ctx.state.seatHead = ctx.head;
904
+ ctx.state[headKey] = ctx.head;
607
905
  // Both capture-stamp digests leave `baselines/` out, so a baseline-JSON-only
608
906
  // commit keeps the credit it already holds.
609
907
  if (creditedPrior && ctx.depositor === 'coverage-capture') {
610
908
  recordCredit(ctx, { ...ctx.state.creditTimings, head: ctx.head });
611
909
  }
612
910
  if (paths.every((p) => p.startsWith('baselines/'))) {
613
- carryLintCredit(ctx, priorHead);
911
+ carryPreflightCredits(ctx, priorHead);
912
+ carryHeldLint(ctx.state, priorHead, ctx.head);
614
913
  }
615
914
  return ran(name, `seated ${total} row(s) and committed them`, {
616
915
  evidencePath,
617
916
  });
618
917
  }
619
918
 
919
+ /** A coverage gate block that is present and not disabled, as close reads it. */
920
+ function isCoverageGateEnabled(config) {
921
+ const block = config?.delivery?.quality?.gates?.coverage;
922
+ return Boolean(block) && typeof block === 'object' && block.enabled !== false;
923
+ }
924
+
620
925
  /**
621
- * The gates whose baselines take a `--seat-missing` pass: CRAP by close's own
622
- * predicate, MI unless explicitly disabled (both default on).
926
+ * The post-capture seat's kinds: CRAP by close's own predicate, coverage
927
+ * when the capture deposits the artifact and its gate is enabled.
623
928
  *
624
- * @param {object} config
929
+ * @param {object} ctx
625
930
  * @returns {Array<keyof typeof SEAT_SCRIPTS>}
626
931
  */
627
- function seatKinds(config) {
628
- const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
932
+ function seatKinds(ctx) {
629
933
  return [
630
- ...(isCrapGateEnabled(config) ? ['crap'] : []),
631
- ...(mi === false ? [] : ['maintainability']),
934
+ ...(isCrapGateEnabled(ctx.config) ? ['crap'] : []),
935
+ ...(seatsCoverage(ctx) ? ['coverage'] : []),
632
936
  ];
633
937
  }
634
938
 
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)}`);
939
+ /** The capture deposits the artifact the coverage seat reads. */
940
+ function seatsCoverage(ctx) {
941
+ return (
942
+ ctx.depositor === 'coverage-capture' && isCoverageGateEnabled(ctx.config)
943
+ );
944
+ }
945
+
946
+ /** Static MI needs no capture, so its seat runs before preflight. */
947
+ function staticSeatKinds(config) {
948
+ const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
949
+ return mi === false ? [] : ['maintainability'];
950
+ }
951
+
952
+ /** Seat `kinds` and commit any rows under `step.name`, keyed by `step.headKey`. */
953
+ async function seatAndCommit(ctx, kinds, step) {
954
+ if (ctx.state[step.headKey] === ctx.head) {
955
+ return creditSkip(step.name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
956
+ }
957
+ const seated = await runSeats(ctx, step.name, kinds);
958
+ if (seated.stop) return seated;
959
+ if (seated.total === 0) {
960
+ ctx.state[step.headKey] = ctx.head;
961
+ return skipped(step.name, 'seated: 0 — nothing to seat', {
962
+ evidencePath: seated.evidencePath,
963
+ });
640
964
  }
641
- const kinds = seatableKinds(ctx, seatKinds(ctx.config));
965
+ return commitSeatedRows(ctx, seated, step);
966
+ }
967
+
968
+ /** @param {object} ctx @returns {Promise<StepResult>} */
969
+ function stepSeatStatic(ctx) {
970
+ return seatAndCommit(ctx, staticSeatKinds(ctx.config), {
971
+ name: 'seat-static',
972
+ headKey: 'staticSeatHead',
973
+ });
974
+ }
975
+
976
+ /** @param {object} ctx @returns {Promise<StepResult>} */
977
+ function stepSeat(ctx) {
978
+ return seatAndCommit(ctx, seatableKinds(ctx, seatKinds(ctx)), {
979
+ name: 'seat',
980
+ headKey: 'seatHead',
981
+ });
982
+ }
983
+
984
+ /**
985
+ * Each kind's `--seat-missing` pass; a refusal or a missing `seated: N` stops.
986
+ *
987
+ * @returns {Promise<StepResult|{ total: number, evidencePath: string|null }>}
988
+ */
989
+ async function runSeats(ctx, name, kinds) {
642
990
  let total = 0;
643
991
  let evidencePath = null;
644
992
  for (const kind of kinds) {
@@ -652,59 +1000,41 @@ async function stepSeat(ctx) {
652
1000
  return fixRequired(
653
1001
  name,
654
1002
  `${kind} --seat-missing ${run.status !== 0 ? `refused (exit ${run.status})` : 'printed no `seated: N`'} — read the log for the fix`,
655
- { evidencePath: run.evidencePath },
1003
+ { evidencePath: run.evidencePath, cause: 'seat-refused' },
656
1004
  );
657
1005
  }
658
1006
  total += Number(match[1]);
659
1007
  }
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: '' };
1008
+ return { total, evidencePath };
687
1009
  }
688
1010
 
689
1011
  const PORCELAIN_STATUS = /^\s*[ MADRCUT?!]{1,2}\s/;
690
1012
 
1013
+ // GitHub's ruleset engine failing mid-evaluation; it prints a `[remote
1014
+ // rejected]` line too, so it must match first.
1015
+ const RULESET_EVAL_FAILED = /fatal error in commit_refs_rules/i;
691
1016
  const REMOTE_REJECTED =
692
1017
  /\[remote rejected\]|permission to \S+ denied|returned error: 403/i;
693
1018
  const REF_BEHIND = /\[rejected\].*\((non-fast-forward|fetch first)\)/;
694
1019
  const REMOTE_UNREACHABLE =
695
1020
  /could not resolve host|unable to access|could not read from remote|connection (refused|timed out|reset)|network is unreachable/i;
696
1021
  const PUSH_FAILURES = [
1022
+ [RULESET_EVAL_FAILED, 'ruleset-eval-failed'],
697
1023
  [REMOTE_REJECTED, 'push-rejected'],
698
1024
  [REMOTE_UNREACHABLE, 'remote-unreachable'],
699
1025
  [REF_BEHIND, 'ref-behind'],
700
1026
  ];
1027
+ // shortcut: a fixed stride (every 3-4 first-parent commits passed in the
1028
+ // field); make it configurable only if a consumer needs a different one.
1029
+ const PUSH_STRIDE = 3;
701
1030
 
702
1031
  /**
703
1032
  * 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.
1033
+ * behind its remote, a ruleset-evaluation failure or a failing `pre-push`
1034
+ * hook is the worker's to fix.
705
1035
  *
706
1036
  * @param {string} output
707
- * @returns {'push-rejected'|'remote-unreachable'|'ref-behind'|null}
1037
+ * @returns {'ruleset-eval-failed'|'push-rejected'|'remote-unreachable'|'ref-behind'|null}
708
1038
  */
709
1039
  function classifyPushFailure(output) {
710
1040
  for (const [pattern, reason] of PUSH_FAILURES) {
@@ -713,48 +1043,150 @@ function classifyPushFailure(output) {
713
1043
  return null;
714
1044
  }
715
1045
 
1046
+ /** @param {object} ctx @param {object} evidence @returns {StepResult} */
1047
+ function refBehind(ctx, evidence) {
1048
+ return fixRequired(
1049
+ 'push',
1050
+ `origin/${ctx.branch} has commits HEAD lacks — git fetch origin ${ctx.branch}, git merge origin/${ctx.branch}, re-run`,
1051
+ { ...evidence, cause: 'ref-behind' },
1052
+ );
1053
+ }
1054
+
1055
+ /** @param {object} ctx @param {string} sha */
1056
+ const refPush = (ctx, sha) => [
1057
+ 'push',
1058
+ 'origin',
1059
+ `${sha}:refs/heads/${ctx.branch}`,
1060
+ ];
1061
+
1062
+ /** @param {object} ctx @param {string[]} range @param {object} evidence */
1063
+ function rulesetFailure(ctx, range, evidence) {
1064
+ const shas = range.length > 0 ? range : ['<sha>'];
1065
+ const recipe = shas.map((sha) => `git ${refPush(ctx, sha).join(' ')}`);
1066
+ return fixRequired(
1067
+ 'push',
1068
+ `GitHub ruleset evaluation failed (commit_refs_rules) even when stepped — push each first-parent commit oldest first: ${recipe.join('; ')}; then re-run`,
1069
+ { ...evidence, reason: 'ruleset-eval-failed' },
1070
+ );
1071
+ }
1072
+
1073
+ /**
1074
+ * Every PUSH_STRIDE-th commit of the range before HEAD (each one in a short
1075
+ * range).
1076
+ *
1077
+ * @param {string[]} range
1078
+ * @returns {string[]}
1079
+ */
1080
+ function stepTargets(range) {
1081
+ const last = range.length - 1;
1082
+ return range.filter(
1083
+ (_, i) => i < last && (last < PUSH_STRIDE || (i + 1) % PUSH_STRIDE === 0),
1084
+ );
1085
+ }
1086
+
1087
+ const FIXABLE_PUSH = Object.freeze({
1088
+ 'ref-behind': (ctx, evidence) => refBehind(ctx, evidence),
1089
+ 'ruleset-eval-failed': (ctx, ev, range) => rulesetFailure(ctx, range, ev),
1090
+ });
1091
+
716
1092
  /**
717
1093
  * @param {object} ctx
718
1094
  * @param {{ output: string, evidencePath: string|null }} push
1095
+ * @param {string[]} [range] first-parent commits, oldest first.
719
1096
  * @returns {StepResult}
720
1097
  */
721
- function pushFailure(ctx, push) {
1098
+ function pushFailure(ctx, push, range = []) {
722
1099
  const reason = classifyPushFailure(push.output);
723
1100
  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
- }
1101
+ const fixable = FIXABLE_PUSH[reason];
1102
+ if (fixable) return fixable(ctx, evidence, range);
731
1103
  return reason
732
1104
  ? blocked('push', reason, `git push failed (${reason})`, evidence)
733
1105
  : fixRequired(
734
1106
  'push',
735
1107
  'git push failed locally (a pre-push hook?) — fix the cause with a NEW commit, re-run',
736
- evidence,
1108
+ { ...evidence, cause: 'push-hook' },
737
1109
  );
738
1110
  }
739
1111
 
1112
+ /**
1113
+ * HEAD's first-parent commits, oldest first, on neither the base nor the
1114
+ * remote Story branch tip.
1115
+ *
1116
+ * @param {object} ctx
1117
+ * @param {string|null} tip
1118
+ * @returns {string[]}
1119
+ */
1120
+ function firstParentRange(ctx, tip) {
1121
+ const res = ctx.git(
1122
+ ctx.cwd,
1123
+ 'rev-list',
1124
+ '--first-parent',
1125
+ '--reverse',
1126
+ 'HEAD',
1127
+ `^origin/${ctx.baseBranch}`,
1128
+ ...(tip ? [`^${tip}`] : []),
1129
+ );
1130
+ if (res?.status !== 0) return [];
1131
+ return `${res.stdout ?? ''}`.split(/\s+/).filter(Boolean);
1132
+ }
1133
+
1134
+ /**
1135
+ * Retry a ruleset-evaluation failure as a stepped push: the step targets,
1136
+ * then the branch itself.
1137
+ *
1138
+ * @param {object} ctx
1139
+ * @param {string|null} tip the remote Story branch sha before the push.
1140
+ * @param {{ evidencePath: string|null }} first the failed first push.
1141
+ * @returns {Promise<{ failure: StepResult }|{ evidencePath: string, how: string }>}
1142
+ */
1143
+ async function steppedPush(ctx, tip, first) {
1144
+ if (
1145
+ tip &&
1146
+ ctx.git(ctx.cwd, 'merge-base', '--is-ancestor', tip, 'HEAD')?.status !== 0
1147
+ ) {
1148
+ return { failure: refBehind(ctx, { evidencePath: first.evidencePath }) };
1149
+ }
1150
+ const range = firstParentRange(ctx, tip);
1151
+ const pushes = [
1152
+ ...stepTargets(range).map((sha) => refPush(ctx, sha)),
1153
+ ['push', '-u', 'origin', ctx.branch],
1154
+ ];
1155
+ let push;
1156
+ for (const [i, args] of pushes.entries()) {
1157
+ push = await runLogged(ctx, `push-step-${i + 1}`, 'git', args);
1158
+ if (push.status !== 0) return { failure: pushFailure(ctx, push, range) };
1159
+ }
1160
+ return {
1161
+ evidencePath: push.evidencePath,
1162
+ how: ` in a stepped push of ${pushes.length} step(s) after a ruleset-evaluation failure`,
1163
+ };
1164
+ }
1165
+
1166
+ /** The branch push, retried stepped on a ruleset-evaluation failure. */
1167
+ async function pushOrStep(ctx, tip) {
1168
+ const args = ['push', '-u', 'origin', ctx.branch];
1169
+ const push = await runLogged(ctx, 'push', 'git', args);
1170
+ if (push.status === 0) return { evidencePath: push.evidencePath, how: '' };
1171
+ if (classifyPushFailure(push.output) !== 'ruleset-eval-failed') {
1172
+ return { failure: pushFailure(ctx, push) };
1173
+ }
1174
+ return steppedPush(ctx, tip, push);
1175
+ }
1176
+
740
1177
  /** @param {object} ctx @returns {Promise<StepResult>} */
741
1178
  async function stepPush(ctx) {
742
1179
  const name = 'push';
743
- const before = remoteBranchSha(ctx);
1180
+ const before = remoteBranchSha(ctx.cwd, ctx.branch, ctx.git);
744
1181
  if (!before.reachable) {
745
1182
  return blocked(name, 'remote-unreachable', before.detail);
746
1183
  }
747
1184
  if (before.sha === ctx.head) {
748
1185
  return skipped(name, `origin/${ctx.branch} already at HEAD`);
749
1186
  }
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);
1187
+ const push = await pushOrStep(ctx, before.sha);
1188
+ if (push.failure) return push.failure;
1189
+ const after = remoteBranchSha(ctx.cwd, ctx.branch, ctx.git);
758
1190
  if (after.sha !== ctx.head) {
759
1191
  return blocked(
760
1192
  name,
@@ -763,9 +1195,8 @@ async function stepPush(ctx) {
763
1195
  { evidencePath: push.evidencePath },
764
1196
  );
765
1197
  }
766
- return ran(name, `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}`, {
767
- evidencePath: push.evidencePath,
768
- });
1198
+ const detail = `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}${push.how}`;
1199
+ return ran(name, detail, { evidencePath: push.evidencePath });
769
1200
  }
770
1201
 
771
1202
  /**
@@ -775,16 +1206,24 @@ async function stepPush(ctx) {
775
1206
  * @returns {StepResult}
776
1207
  */
777
1208
  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
- }
1209
+ if (deposit?.halted) return haltedReview(deposit, depositPath);
785
1210
  return settled;
786
1211
  }
787
1212
 
1213
+ /** No code change resolves a missing verdict, so that halt is blocked. */
1214
+ function haltedReview(deposit, depositPath) {
1215
+ if (deposit.haltCause === 'no-verdict') {
1216
+ return blocked('review', 'review-no-verdict', deposit.blockerReason, {
1217
+ evidencePath: depositPath,
1218
+ });
1219
+ }
1220
+ return fixRequired(
1221
+ 'review',
1222
+ 'held review found a CRITICAL — fix, commit, re-run the handoff',
1223
+ { evidencePath: depositPath, cause: 'review-critical' },
1224
+ );
1225
+ }
1226
+
788
1227
  /** @param {object} ctx @returns {Promise<StepResult>} */
789
1228
  async function computeHeldReview(ctx) {
790
1229
  const name = 'review';
@@ -801,7 +1240,7 @@ async function computeHeldReview(ctx) {
801
1240
  return reviewVerdict(
802
1241
  held.deposit,
803
1242
  ctx.reviewPath,
804
- skipped(name, 'held review already matches this diff'),
1243
+ creditSkip(name, 'held review already matches this diff'),
805
1244
  );
806
1245
  }
807
1246
  let outcome;
@@ -844,8 +1283,10 @@ function startReview(ctx) {
844
1283
  outcome: 'error',
845
1284
  detail: `held review failed (${err?.message ?? err}); close computes the review itself`,
846
1285
  }))
847
- .finally(() => {
1286
+ .then((result) => {
848
1287
  ctx.reviewMs = ctx.now() - startedAt;
1288
+ ctx.reviewSettled = result;
1289
+ return result;
849
1290
  });
850
1291
  return ctx.reviewPending;
851
1292
  }
@@ -854,7 +1295,7 @@ function startReview(ctx) {
854
1295
  async function stepCreditedRun(ctx) {
855
1296
  const abort = new AbortController();
856
1297
  let halted = null;
857
- startReview(ctx).then((result) => {
1298
+ ctx.reviewPending?.then((result) => {
858
1299
  if (!result.stop) return;
859
1300
  halted = result;
860
1301
  abort.abort();
@@ -867,6 +1308,17 @@ function stepReview(ctx) {
867
1308
  return ctx.reviewPending;
868
1309
  }
869
1310
 
1311
+ /**
1312
+ * Close's own duplication re-score, before any credit is minted, so close's
1313
+ * re-score no-ops on the handed-off tree. Best-effort: never stops the run.
1314
+ *
1315
+ * @param {object} ctx @returns {Promise<StepResult>}
1316
+ */
1317
+ async function stepDuplicationRescore(ctx) {
1318
+ const settled = await rescoreDuplication(ctx, () => headSha(ctx));
1319
+ return { name: 'duplication-rescore', ...settled };
1320
+ }
1321
+
870
1322
  /**
871
1323
  * Pure scoring after depositor and seat: no lock, no suite, no evidence, so
872
1324
  * close re-scores them and stays authoritative.
@@ -877,29 +1329,97 @@ async function stepPostCapture(ctx) {
877
1329
  const name = 'post-capture';
878
1330
  const { postCaptureHead } = ctx.state;
879
1331
  if (postCaptureHead === ctx.head && postCaptureSettled(ctx)) {
880
- return skipped(name, `already clean at ${ctx.head.slice(0, 12)}`);
1332
+ return creditSkip(name, `already clean at ${ctx.head.slice(0, 12)}`);
881
1333
  }
882
1334
  const { gates, failed } = await scorePostCapture(ctx, (...a) =>
883
1335
  runLogged(ctx, ...a),
884
1336
  );
885
1337
  if (failed) {
886
- return fixRequired(name, failed.finding, {
1338
+ const rows = raisedDuplicationSuffix(ctx, failed, MAX_OFFENDING_LINES);
1339
+ return fixRequired(name, `${failed.finding}${rows}`, {
887
1340
  evidencePath: failed.evidencePath,
888
1341
  gate: failed.gate,
1342
+ cause: 'post-capture',
889
1343
  });
890
1344
  }
1345
+ const post = await runPostSeatChecks(ctx, (...a) => runLogged(ctx, ...a));
1346
+ if (post.failed) return postSeatFixRequired(name, post.failed);
891
1347
  ctx.state.postCaptureHead = ctx.head;
892
- return gates.length > 0
893
- ? ran(name, `${gates.map((g) => g.name).join(', ')} clean`)
1348
+ return settledPostCapture(name, gates, post);
1349
+ }
1350
+
1351
+ /**
1352
+ * Run each `delivery.handoff.postSeatChecks` entry through `run`; the first
1353
+ * non-zero exit is the finding. Skipped under a coverage deferral.
1354
+ *
1355
+ * @returns {Promise<{ checks: object[], skipped?: boolean, failed: object|null }>}
1356
+ */
1357
+ async function runPostSeatChecks(ctx, run) {
1358
+ const checks = getPostSeatChecks(ctx.config);
1359
+ if (checks.length === 0) return { checks, failed: null };
1360
+ if (isCoverageDeferred(ctx)) return { checks, skipped: true, failed: null };
1361
+ for (const [i, check] of checks.entries()) {
1362
+ const res = await run(`post-seat-${i + 1}`, check.cmd, check.args);
1363
+ if (res.status !== 0)
1364
+ return { checks, failed: postSeatFailure(check, res) };
1365
+ }
1366
+ releaseHeldLint(ctx);
1367
+ return { checks, failed: null };
1368
+ }
1369
+
1370
+ /** A failed post-seat check as the handoff's finding. */
1371
+ function postSeatFailure(check, res) {
1372
+ const label = [check.cmd, ...check.args].join(' ');
1373
+ return {
1374
+ gate: 'post-seat',
1375
+ finding: `post-seat check \`${label}\` failed (exit ${res.status}) — fix and commit, then re-run`,
1376
+ evidencePath: res.evidencePath,
1377
+ };
1378
+ }
1379
+
1380
+ /** @param {string} name @param {{ finding: string, evidencePath: string, gate: string }} failed */
1381
+ function postSeatFixRequired(name, failed) {
1382
+ return fixRequired(name, failed.finding, {
1383
+ evidencePath: failed.evidencePath,
1384
+ gate: failed.gate,
1385
+ cause: 'post-capture',
1386
+ });
1387
+ }
1388
+
1389
+ /** The clean post-capture result, naming the post-seat checks' outcome. */
1390
+ function settledPostCapture(name, gates, post) {
1391
+ const names = gates.map((g) => g.name);
1392
+ if (post.checks.length > 0) {
1393
+ names.push(
1394
+ post.skipped
1395
+ ? 'post-seat checks skipped (coverage deferred)'
1396
+ : `${post.checks.length} post-seat check(s)`,
1397
+ );
1398
+ }
1399
+ return names.length > 0
1400
+ ? ran(name, `${names.join(', ')} clean`)
894
1401
  : skipped(name, 'no post-capture gate registered');
895
1402
  }
896
1403
 
1404
+ /** `step`, unless the review has already halted: then the halt is its result. */
1405
+ function beforeRun(step) {
1406
+ const guarded = (ctx) =>
1407
+ ctx.reviewSettled?.stop ? ctx.reviewSettled : step(ctx);
1408
+ return Object.defineProperty(guarded, 'name', { value: step.name });
1409
+ }
1410
+
1411
+ /** Append the settled review unless a step already recorded it. */
1412
+ function appendReview(steps, review) {
1413
+ if (review && !steps.some((s) => s.name === 'review')) steps.push(review);
1414
+ }
1415
+
897
1416
  /**
898
1417
  * 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.
1418
+ * tree that is pushed. Static MI seats before preflight, so no check refuses
1419
+ * a new file for a row the handoff can derive. On the evidence-gate path the
1420
+ * `test` credit is keyed on the tree, so the seat goes first and cannot void
1421
+ * it; the capture stamp's digests leave `baselines/` out, so the CRAP and
1422
+ * coverage seat after the capture keeps the stamp fresh.
903
1423
  *
904
1424
  * @param {'coverage-capture'|'test'} depositor
905
1425
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
@@ -907,10 +1427,12 @@ async function stepPostCapture(ctx) {
907
1427
  function stepOrder(depositor) {
908
1428
  const middle =
909
1429
  depositor === 'test'
910
- ? [stepSeat, stepCreditedRun]
911
- : [stepCreditedRun, stepSeat];
1430
+ ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1431
+ : [beforeRun(stepCreditedRun), stepSeat];
912
1432
  return [
913
1433
  stepBaseMerge,
1434
+ stepDuplicationRescore,
1435
+ stepSeatStatic,
914
1436
  stepPreflight,
915
1437
  ...middle,
916
1438
  stepPostCapture,
@@ -919,6 +1441,22 @@ function stepOrder(depositor) {
919
1441
  ];
920
1442
  }
921
1443
 
1444
+ /** `run`'s results, each carrying the call's wall time as `durationMs`. */
1445
+ async function timed(ctx, run) {
1446
+ const startedAt = ctx.now();
1447
+ const results = await run();
1448
+ const durationMs = ctx.now() - startedAt;
1449
+ return results.map((r) => ({ ...r, durationMs }));
1450
+ }
1451
+
1452
+ /**
1453
+ * The review ran concurrently with the credited run: its own wall time is
1454
+ * `ctx.reviewMs`, not the time spent awaiting it.
1455
+ */
1456
+ function envelopeStep(ctx, { stop: _stop, ...rest }) {
1457
+ return rest.name === 'review' ? { ...rest, durationMs: ctx.reviewMs } : rest;
1458
+ }
1459
+
922
1460
  /**
923
1461
  * Run the steps in order into `steps`; a step may settle several results.
924
1462
  *
@@ -926,8 +1464,9 @@ function stepOrder(depositor) {
926
1464
  */
927
1465
  async function runSteps(ctx, steps) {
928
1466
  for (const step of stepOrder(ctx.depositor)) {
929
- ctx.storyProgress.phase(handoffStepName(step));
930
- const results = [await step(ctx)].flat();
1467
+ ctx.stepName = handoffStepName(step);
1468
+ ctx.storyProgress.phase(ctx.stepName);
1469
+ const results = await timed(ctx, async () => [await step(ctx)].flat());
931
1470
  for (const result of results) {
932
1471
  steps.push(result);
933
1472
  ctx.progress(result.name, `${result.outcome} — ${result.detail}`);
@@ -938,6 +1477,8 @@ async function runSteps(ctx, steps) {
938
1477
  return null;
939
1478
  }
940
1479
 
1480
+ const PRECHECK = Object.freeze({ cause: 'precheck' });
1481
+
941
1482
  /**
942
1483
  * Refusals before any step: the handoff runs on the Story branch with the
943
1484
  * implementation committed.
@@ -951,16 +1492,18 @@ function precheck(ctx) {
951
1492
  return fixRequired(
952
1493
  'precheck',
953
1494
  `checked-out branch is ${current || 'unknown'}, not ${ctx.branch} — re-run single-story-init.js (idempotent) and work in its workCwd`,
1495
+ PRECHECK,
954
1496
  );
955
1497
  }
956
1498
  if (!ctx.head) {
957
- return fixRequired('precheck', 'HEAD does not resolve');
1499
+ return fixRequired('precheck', 'HEAD does not resolve', PRECHECK);
958
1500
  }
959
1501
  const dirty = changedPaths(ctx.git, ctx.cwd);
960
1502
  if (dirty.length > 0) {
961
1503
  return fixRequired(
962
1504
  'precheck',
963
1505
  `uncommitted changes (${dirty.slice(0, 5).join(', ')}) — commit the implementation, then re-run`,
1506
+ PRECHECK,
964
1507
  );
965
1508
  }
966
1509
  return null;
@@ -971,7 +1514,7 @@ function precheck(ctx) {
971
1514
  *
972
1515
  * @param {string} statePath
973
1516
  * @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 }}
1517
+ * @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
1518
  */
976
1519
  function readState(statePath, progress) {
977
1520
  let raw;
@@ -1006,7 +1549,13 @@ async function defaultBlock({
1006
1549
  createProviderFn,
1007
1550
  warn,
1008
1551
  }) {
1009
- const provider = createProviderFn(config);
1552
+ let provider;
1553
+ try {
1554
+ provider = createProviderFn(config);
1555
+ } catch (err) {
1556
+ warn(`failed to create provider: ${err?.message ?? err}`);
1557
+ return;
1558
+ }
1010
1559
  try {
1011
1560
  await upsertStructuredComment(
1012
1561
  provider,
@@ -1030,6 +1579,7 @@ async function defaultBlock({
1030
1579
  * git?: typeof gitSpawn,
1031
1580
  * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string, timedOut?: boolean }>,
1032
1581
  * syncFromBase?: typeof syncBranchFromBase,
1582
+ * probeBaseSync?: typeof import('../git/base-sync-probe.js').probeBaseSync,
1033
1583
  * probeReview?: typeof probeHeldReviewDiff,
1034
1584
  * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
1035
1585
  * readPackageScriptsFn?: typeof readPackageScripts,
@@ -1051,6 +1601,10 @@ async function defaultBlock({
1051
1601
  * evidenceCwd?: string,
1052
1602
  * scopeGate?: typeof applyChangedFileScope,
1053
1603
  * presentBaselines?: string[],
1604
+ * runDuplicationRescore?: typeof runDuplicationCloseRescore,
1605
+ * emitFriction?: typeof emitRuntimeFriction,
1606
+ * writeSignal?: typeof import('../signals/write.js').appendSignal,
1607
+ * readSignals?: typeof import('../signals/write.js').forEachLine,
1054
1608
  * }} deps `evidenceCwd` anchors close's evidence store (the main checkout);
1055
1609
  * `runCommand` receives `onChunk`, `signal` and (when set)
1056
1610
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
@@ -1082,6 +1636,11 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1082
1636
  evidenceCwd = PROJECT_ROOT,
1083
1637
  scopeGate = applyChangedFileScope,
1084
1638
  presentBaselines,
1639
+ runDuplicationRescore = runDuplicationCloseRescore,
1640
+ emitFriction = emitRuntimeFriction,
1641
+ admitSuite = withSuiteAdmission,
1642
+ writeSignal,
1643
+ readSignals,
1085
1644
  } = deps;
1086
1645
  const block =
1087
1646
  deps.block ??
@@ -1110,6 +1669,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1110
1669
  git,
1111
1670
  runCommand,
1112
1671
  syncFromBase,
1672
+ probeBaseSync: deps.probeBaseSync,
1113
1673
  probeReview,
1114
1674
  computeReview,
1115
1675
  progress,
@@ -1122,9 +1682,13 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1122
1682
  scopeGate,
1123
1683
  presentBaselines,
1124
1684
  getChangedFilesFn,
1685
+ runDuplicationRescore,
1686
+ emitFriction,
1687
+ admitSuite,
1125
1688
  state: readState(statePath, progress),
1126
1689
  review: null,
1127
1690
  reviewPending: null,
1691
+ reviewSettled: null,
1128
1692
  reviewMs: null,
1129
1693
  reviewPath: storyReviewDepositPath(storyId, config),
1130
1694
  scripts: readPackageScriptsFn(cwd),
@@ -1144,24 +1708,49 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1144
1708
  return file;
1145
1709
  },
1146
1710
  };
1147
- ctx.depositor = selectCreditedDepositor({
1711
+ const plan = selectCreditedDepositor({
1148
1712
  config,
1149
1713
  scripts: ctx.scripts,
1150
1714
  cwd,
1151
1715
  getChangedFilesImpl: getChangedFilesFn,
1152
1716
  });
1717
+ ctx.depositor = plan.depositor;
1718
+ ctx.skipBranch = plan.skipBranch;
1153
1719
  ctx.head = headSha(ctx);
1154
1720
 
1155
1721
  const steps = [];
1156
- let stop = precheck(ctx);
1157
- if (stop) steps.push(stop);
1158
- else stop = await runSteps(ctx, steps);
1159
- await ctx.reviewPending;
1722
+ let stop;
1723
+ try {
1724
+ [stop] = await timed(ctx, async () => [precheck(ctx)].filter(Boolean));
1725
+ if (stop) steps.push(stop);
1726
+ else stop = await runSteps(ctx, steps);
1727
+ } catch (err) {
1728
+ // A runner fault is re-runnable, so it never flips agent::blocked.
1729
+ stop = fixRequired(
1730
+ ctx.stepName ?? 'precheck',
1731
+ `threw: ${err?.message ?? err}`,
1732
+ {
1733
+ cause: 'other',
1734
+ },
1735
+ );
1736
+ steps.push(stop);
1737
+ progress(stop.name, `${stop.outcome} — ${stop.detail}`);
1738
+ }
1739
+ appendReview(steps, await ctx.reviewPending);
1160
1740
 
1161
1741
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1162
1742
  const credited = steps.find((s) => s.name === 'credited-run');
1163
1743
  if (status === HANDOFF_STATUS.BLOCKED) {
1164
- await block({ storyId, config, reason: stop.reason, detail: stop.detail });
1744
+ try {
1745
+ await block({
1746
+ storyId,
1747
+ config,
1748
+ reason: stop.reason,
1749
+ detail: stop.detail,
1750
+ });
1751
+ } catch (err) {
1752
+ progress('BLOCK', `block failed: ${err?.message ?? err}`);
1753
+ }
1165
1754
  }
1166
1755
  const envelope = {
1167
1756
  kind: 'story-handoff',
@@ -1170,24 +1759,35 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1170
1759
  headSha: ctx.head,
1171
1760
  status,
1172
1761
  depositor: ctx.depositor,
1173
- steps: steps.map(({ stop: _stop, ...rest }) => rest),
1762
+ steps: steps.map((step) => envelopeStep(ctx, step)),
1174
1763
  review: ctx.review,
1175
1764
  lockWait: credited?.lockWait ?? null,
1176
1765
  suiteTimings: credited?.suiteTimings ?? null,
1177
1766
  reviewMs: ctx.reviewMs,
1178
1767
  ...coverageEnvelope(ctx),
1768
+ ...hostResourcesEnvelope(ctx),
1769
+ ...ctx.baseMergeEnvelope,
1179
1770
  ...(stop
1180
1771
  ? {
1181
1772
  failedStep: stop.name,
1773
+ cause: handoffCause(stop.cause),
1182
1774
  evidencePath: stop.evidencePath ?? null,
1183
1775
  ...(stop.reason ? { reason: stop.reason } : {}),
1184
1776
  ...(stop.conflictFiles ? { conflictFiles: stop.conflictFiles } : {}),
1185
1777
  }
1186
1778
  : {}),
1779
+ attempt: await nextHandoffAttempt({ storyId, config, readFn: readSignals }),
1187
1780
  };
1188
1781
  writeFileAtomic(
1189
1782
  statePath,
1190
1783
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
1191
1784
  );
1785
+ await emitHandoffRecord({
1786
+ storyId,
1787
+ envelope,
1788
+ config,
1789
+ writeFn: writeSignal,
1790
+ warn: (m) => progress('TELEMETRY', m),
1791
+ });
1192
1792
  return { envelope, exitCode: EXIT_CODES[status] };
1193
1793
  }