mandrel 2.110.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 (190) 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/audit-checklists/state-machines.md +21 -0
  6. package/.agents/docs/agentrc-reference.json +23 -10
  7. package/.agents/docs/configuration.md +362 -15
  8. package/.agents/docs/execution-reference.md +11 -0
  9. package/.agents/docs/workflows.md +2 -1
  10. package/.agents/rules/ci-remediation.md +28 -4
  11. package/.agents/rules/git-conventions-reference.md +7 -0
  12. package/.agents/schemas/agentrc.schema.json +179 -13
  13. package/.agents/schemas/audit-rules.json +28 -0
  14. package/.agents/schemas/baselines/baseline-envelope.schema.json +16 -4
  15. package/.agents/schemas/baselines/bundle-size.schema.json +1 -0
  16. package/.agents/schemas/baselines/coverage.schema.json +1 -0
  17. package/.agents/schemas/baselines/crap.schema.json +37 -10
  18. package/.agents/schemas/baselines/duplication.schema.json +1 -0
  19. package/.agents/schemas/baselines/maintainability.schema.json +1 -0
  20. package/.agents/schemas/baselines/mutation.schema.json +1 -0
  21. package/.agents/schemas/crap-report.schema.json +6 -5
  22. package/.agents/schemas/story-deliver-terminal.schema.json +49 -3
  23. package/.agents/schemas/story-progress.schema.json +1 -1
  24. package/.agents/schemas/validation-evidence.schema.json +2 -2
  25. package/.agents/scripts/boot-sweep.js +41 -3
  26. package/.agents/scripts/coverage-capture.js +39 -3
  27. package/.agents/scripts/coverage-ratchet.js +106 -0
  28. package/.agents/scripts/evidence-gate.js +84 -21
  29. package/.agents/scripts/file-ci-gap.js +220 -10
  30. package/.agents/scripts/lib/audit-baselines/read.js +8 -1
  31. package/.agents/scripts/lib/audit-baselines/trend.js +2 -1
  32. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  33. package/.agents/scripts/lib/baseline-loader.js +4 -2
  34. package/.agents/scripts/lib/baselines/codec.js +57 -0
  35. package/.agents/scripts/lib/baselines/crap-preview-incremental.js +8 -3
  36. package/.agents/scripts/lib/baselines/crap-preview-scan.js +10 -16
  37. package/.agents/scripts/lib/baselines/crap-updater-cli.js +4 -13
  38. package/.agents/scripts/lib/baselines/kernel.js +19 -1
  39. package/.agents/scripts/lib/baselines/kinds/_crap-codec.js +171 -0
  40. package/.agents/scripts/lib/baselines/kinds/_crap-read.js +56 -16
  41. package/.agents/scripts/lib/baselines/kinds/_shared-metric.js +0 -59
  42. package/.agents/scripts/lib/baselines/kinds/crap.js +283 -319
  43. package/.agents/scripts/lib/baselines/preview-gates.js +29 -10
  44. package/.agents/scripts/lib/baselines/reader.js +36 -9
  45. package/.agents/scripts/lib/baselines/refresh-service.js +79 -18
  46. package/.agents/scripts/lib/baselines/seat-missing.js +173 -7
  47. package/.agents/scripts/lib/baselines/writer.js +36 -21
  48. package/.agents/scripts/lib/changed-files.js +70 -6
  49. package/.agents/scripts/lib/child-exec.js +10 -0
  50. package/.agents/scripts/lib/claude/agents-projection.js +5 -5
  51. package/.agents/scripts/lib/close-lock-events.js +8 -3
  52. package/.agents/scripts/lib/close-validation/ci-deferral.js +40 -0
  53. package/.agents/scripts/lib/close-validation/gates.js +156 -32
  54. package/.agents/scripts/lib/close-validation/process.js +16 -7
  55. package/.agents/scripts/lib/close-validation/projections/crap.js +43 -10
  56. package/.agents/scripts/lib/close-validation/runner.js +160 -41
  57. package/.agents/scripts/lib/close-validation/skip-branch-test.js +144 -0
  58. package/.agents/scripts/lib/close-validation/test-delta.js +33 -8
  59. package/.agents/scripts/lib/codex/agents-projection.js +6 -0
  60. package/.agents/scripts/lib/config/agentrc-overlay.js +9 -5
  61. package/.agents/scripts/lib/config/explain.js +5 -2
  62. package/.agents/scripts/lib/config/gates/coverage.schema.js +53 -0
  63. package/.agents/scripts/lib/config/gates/crap-incremental-coverage.schema.js +1 -1
  64. package/.agents/scripts/lib/config/git-roots.js +38 -4
  65. package/.agents/scripts/lib/config/handoff.js +24 -0
  66. package/.agents/scripts/lib/config/quality.js +28 -12
  67. package/.agents/scripts/lib/config/worktree-isolation.js +2 -5
  68. package/.agents/scripts/lib/config-resolver.js +22 -2
  69. package/.agents/scripts/lib/config-settings-schema-delivery.js +87 -4
  70. package/.agents/scripts/lib/config-settings-schema-quality.js +36 -1
  71. package/.agents/scripts/lib/config-settings-schema.js +1 -1
  72. package/.agents/scripts/lib/coverage-capture-affected.js +1 -0
  73. package/.agents/scripts/lib/coverage-capture-delta.js +164 -32
  74. package/.agents/scripts/lib/coverage-capture-own-fix.js +232 -0
  75. package/.agents/scripts/lib/coverage-capture-usage.js +2 -2
  76. package/.agents/scripts/lib/coverage-capture.js +31 -0
  77. package/.agents/scripts/lib/coverage-deferral.js +96 -0
  78. package/.agents/scripts/lib/coverage-ratchet.js +187 -0
  79. package/.agents/scripts/lib/crap-baseline-join.js +5 -5
  80. package/.agents/scripts/lib/crap-engine.js +3 -3
  81. package/.agents/scripts/lib/crap-method-identity.js +104 -48
  82. package/.agents/scripts/lib/escomplex-anchor.js +135 -0
  83. package/.agents/scripts/lib/escomplex-kernel.js +30 -1
  84. package/.agents/scripts/lib/failure-rows.js +121 -0
  85. package/.agents/scripts/lib/full-suite-lock.js +44 -4
  86. package/.agents/scripts/lib/full-suite-queue.js +89 -13
  87. package/.agents/scripts/lib/generated/agentrc-validator.js +8 -2
  88. package/.agents/scripts/lib/gh-env.js +3 -6
  89. package/.agents/scripts/lib/gh-pr-rest.js +1 -0
  90. package/.agents/scripts/lib/git/base-sync-probe.js +182 -0
  91. package/.agents/scripts/lib/git-branch-lifecycle.js +9 -0
  92. package/.agents/scripts/lib/observability/close-telemetry.js +37 -2
  93. package/.agents/scripts/lib/observability/handoff-telemetry.js +170 -0
  94. package/.agents/scripts/lib/observability/review-dispositions.js +23 -6
  95. package/.agents/scripts/lib/observability/runtime-friction.js +17 -4
  96. package/.agents/scripts/lib/observability/source-classifier.js +3 -0
  97. package/.agents/scripts/lib/observability/story-outcome.js +393 -0
  98. package/.agents/scripts/lib/orchestration/check-baselines/phases/compare.js +2 -1
  99. package/.agents/scripts/lib/orchestration/check-baselines/phases/evaluate.js +19 -1
  100. package/.agents/scripts/lib/orchestration/check-baselines/phases/fail-detail.js +84 -0
  101. package/.agents/scripts/lib/orchestration/check-baselines/phases/pipeline.js +14 -5
  102. package/.agents/scripts/lib/orchestration/check-baselines/phases/refresh-ack.js +3 -2
  103. package/.agents/scripts/lib/orchestration/check-baselines/phases/report.js +26 -6
  104. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +124 -23
  105. package/.agents/scripts/lib/orchestration/code-review.js +223 -19
  106. package/.agents/scripts/lib/orchestration/handoff-gates.js +217 -44
  107. package/.agents/scripts/lib/orchestration/handoff-rescore.js +169 -0
  108. package/.agents/scripts/lib/orchestration/handoff-suite-of-record.js +45 -0
  109. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -1
  110. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +76 -4
  111. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +2 -2
  112. package/.agents/scripts/lib/orchestration/preflight-lanes.js +208 -0
  113. package/.agents/scripts/lib/orchestration/review-base-ref.js +40 -17
  114. package/.agents/scripts/lib/orchestration/review-deposit.js +38 -12
  115. package/.agents/scripts/lib/orchestration/review-depth.js +21 -0
  116. package/.agents/scripts/lib/orchestration/review-history.js +124 -20
  117. package/.agents/scripts/lib/orchestration/review-providers/claude-verdict.js +23 -8
  118. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +82 -39
  119. package/.agents/scripts/lib/orchestration/review-providers/critical-verifier.js +64 -11
  120. package/.agents/scripts/lib/orchestration/review-providers/degraded-gates.js +98 -3
  121. package/.agents/scripts/lib/orchestration/review-providers/finding-identity.js +6 -2
  122. package/.agents/scripts/lib/orchestration/review-providers/findings-renderer.js +55 -8
  123. package/.agents/scripts/lib/orchestration/review-providers/review-guidance.js +1 -0
  124. package/.agents/scripts/lib/orchestration/review-providers/review-provider-factory.js +42 -15
  125. package/.agents/scripts/lib/orchestration/review-providers/types.js +6 -0
  126. package/.agents/scripts/lib/orchestration/single-story-close/failed-terminal.js +10 -1
  127. package/.agents/scripts/lib/orchestration/single-story-close/gate-log.js +10 -0
  128. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -4
  129. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +17 -2
  130. package/.agents/scripts/lib/orchestration/single-story-close/phases/code-review.js +59 -2
  131. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +13 -1
  132. package/.agents/scripts/lib/orchestration/single-story-close/phases/finish.js +15 -4
  133. package/.agents/scripts/lib/orchestration/single-story-close/phases/land-review-record.js +213 -0
  134. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +17 -2
  135. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +42 -20
  136. package/.agents/scripts/lib/orchestration/single-story-close/phases/post-land.js +51 -26
  137. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +3 -1
  138. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +51 -15
  139. package/.agents/scripts/lib/orchestration/single-story-close/phases/push.js +59 -11
  140. package/.agents/scripts/lib/orchestration/single-story-close/phases/reconcile-done.js +1 -0
  141. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-block.js +31 -13
  142. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-halt.js +29 -6
  143. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-outcome.js +10 -12
  144. package/.agents/scripts/lib/orchestration/single-story-close/phases/review-override.js +19 -4
  145. package/.agents/scripts/lib/orchestration/single-story-close/result.js +43 -13
  146. package/.agents/scripts/lib/orchestration/single-story-close/review-overlap.js +73 -39
  147. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +11 -2
  148. package/.agents/scripts/lib/orchestration/story-close/baseline-upward-writeback.js +3 -2
  149. package/.agents/scripts/lib/orchestration/story-close/duplication-close-rescore.js +20 -8
  150. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +7 -0
  151. package/.agents/scripts/lib/orchestration/story-handoff.js +789 -196
  152. package/.agents/scripts/lib/orchestration/ticketing/reads.js +2 -0
  153. package/.agents/scripts/lib/pr-body-lines.js +32 -0
  154. package/.agents/scripts/lib/single-story/ci-ratchet-gate.js +140 -0
  155. package/.agents/scripts/lib/single-story/confirm-and-land.js +17 -7
  156. package/.agents/scripts/lib/single-story/confirm-merge.js +12 -3
  157. package/.agents/scripts/lib/single-story-sweep/report-stalled-executing.js +202 -0
  158. package/.agents/scripts/lib/standalone-ratchets.js +37 -0
  159. package/.agents/scripts/lib/suite-admission.js +20 -8
  160. package/.agents/scripts/lib/suite-sizing.js +146 -0
  161. package/.agents/scripts/lib/workspace-provisioner.js +2 -2
  162. package/.agents/scripts/merge-baseline.js +14 -3
  163. package/.agents/scripts/providers/github/comments.js +19 -3
  164. package/.agents/scripts/providers/github.js +1 -0
  165. package/.agents/scripts/review-dispositions-report.js +1 -1
  166. package/.agents/scripts/role-scope-guard.js +267 -0
  167. package/.agents/scripts/single-story-close.js +4 -4
  168. package/.agents/scripts/single-story-confirm-merge.js +31 -5
  169. package/.agents/scripts/single-story-init.js +24 -4
  170. package/.agents/scripts/story-handoff.js +3 -3
  171. package/.agents/scripts/story-outcomes-report.js +231 -0
  172. package/.agents/scripts/story-review-compute.js +9 -5
  173. package/.agents/scripts/update-coverage-baseline.js +12 -2
  174. package/.agents/scripts/update-crap-baseline.js +9 -1
  175. package/.agents/workflows/audit-state-machines.md +213 -0
  176. package/.agents/workflows/helpers/code-review.md +63 -9
  177. package/.agents/workflows/helpers/deliver-digest.md +53 -54
  178. package/.agents/workflows/helpers/deliver-reference.md +236 -63
  179. package/.agents/workflows/helpers/deliver-story-reference.md +19 -8
  180. package/.agents/workflows/helpers/deliver-story.md +7 -2
  181. package/.agents/workflows/helpers/parallel-tooling.md +29 -0
  182. package/.agents/workflows/helpers/plan-reference.md +10 -2
  183. package/docs/CHANGELOG.md +56 -0
  184. package/lib/cli/doctor-checks/coverage-ratchet.js +54 -0
  185. package/lib/cli/doctor-checks/effective-agentrc.js +23 -0
  186. package/lib/cli/doctor-checks/llm-review.js +2 -11
  187. package/lib/cli/doctor-checks/sync-parity.js +5 -1
  188. package/lib/cli/doctor-checks/test-credit-path.js +7 -2
  189. package/lib/cli/registry.js +5 -0
  190. 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,31 +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
- carryLintCredit,
75
+ carryCoverageDeferral,
76
+ carryCredit,
77
+ carryPreflightCredits,
78
+ clearCoverageDeferral,
79
+ coverageEnvelope,
57
80
  creditedPreflight,
58
- lintCredit,
81
+ isCoverageDeferred,
82
+ isOverBudgetExit,
83
+ postCaptureSettled,
84
+ recordPreflightCredit,
59
85
  scorePostCapture,
86
+ seatableKinds,
87
+ settleOverBudget,
60
88
  } from './handoff-gates.js';
89
+ import {
90
+ raisedDuplicationSuffix,
91
+ rescoreDuplication,
92
+ } from './handoff-rescore.js';
61
93
  import { handoffStatePath } from './handoff-state.js';
94
+ import { settleSuiteOfRecord } from './handoff-suite-of-record.js';
95
+ import { requestedLanes, runPreflightLanes } from './preflight-lanes.js';
62
96
  import { probeHeldReviewDiff } from './review-deposit.js';
97
+ import { runDuplicationCloseRescore } from './story-close/duplication-close-rescore.js';
63
98
  import { createStoryProgress, handoffStepName } from './story-progress.js';
64
99
  import {
65
100
  STATE_LABELS,
@@ -98,49 +133,24 @@ const SIGNALS = Object.freeze({
98
133
  offending: /^[+!] /,
99
134
  });
100
135
 
101
- /** CI's standalone ratchets; each runs only when its baseline is committed. */
102
- const RATCHETS = Object.freeze([
103
- {
104
- key: 'dead-exports',
105
- script: 'check-dead-exports.js',
106
- args: [],
107
- baseline: 'baselines/dead-exports.json',
108
- },
109
- {
110
- key: 'dead-exports-production',
111
- script: 'check-dead-exports.js',
112
- args: ['--production'],
113
- baseline: 'baselines/dead-exports-production.json',
114
- },
115
- {
116
- key: 'arch-cycles',
117
- script: 'check-arch-cycles.js',
118
- args: [],
119
- baseline: 'baselines/arch-cycles.json',
120
- },
121
- {
122
- key: 'cyclomatic',
123
- script: 'check-cyclomatic.js',
124
- args: [],
125
- baseline: 'baselines/cyclomatic.json',
126
- },
127
- ]);
128
-
129
136
  const MAX_OFFENDING_LINES = 10;
130
137
 
131
138
  const LOCK_POLL_MS = 1_000;
132
139
 
133
140
  const SEAT_SCRIPTS = Object.freeze({
141
+ coverage: 'update-coverage-baseline.js',
134
142
  crap: 'update-crap-baseline.js',
135
143
  maintainability: 'update-maintainability-baseline.js',
136
144
  });
137
145
 
138
146
  /**
139
- * 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.
140
149
  *
141
- * @typedef {{ name: string, outcome: 'ran'|'skipped'|'failed'|'error'|'aborted',
150
+ * @typedef {{ name: string, outcome: 'ran'|'skipped'|'deferred'|'failed'|'error'|'aborted',
142
151
  * detail: string, evidencePath?: string|null, conflictFiles?: string[],
143
- * stop?: 'fix-required'|'blocked', reason?: string }} StepResult
152
+ * stop?: 'fix-required'|'blocked', reason?: string, cause?: string,
153
+ * durationMs?: number|null, skippedByCredit?: boolean }} StepResult
144
154
  */
145
155
 
146
156
  const ran = (name, detail, extra = {}) => ({
@@ -155,6 +165,9 @@ const skipped = (name, detail, extra = {}) => ({
155
165
  detail,
156
166
  ...extra,
157
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 });
158
171
  const fixRequired = (name, detail, extra = {}) => ({
159
172
  name,
160
173
  outcome: 'failed',
@@ -167,6 +180,7 @@ const blocked = (name, reason, detail, extra = {}) => ({
167
180
  outcome: 'failed',
168
181
  detail,
169
182
  reason,
183
+ cause: reason,
170
184
  stop: HANDOFF_STATUS.BLOCKED,
171
185
  ...extra,
172
186
  });
@@ -189,16 +203,21 @@ function headSha(ctx) {
189
203
  }
190
204
 
191
205
  /**
192
- * A child's env with `AP_AGENTRC_CWD` pinned to the Story worktree, layered
193
- * last so a stale inherited value cannot win: a gate judges the branch by
194
- * 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.
195
210
  *
196
211
  * @param {object} ctx
197
212
  * @param {Record<string, string|undefined>} [env] defaults to `ctx.env`.
198
213
  * @returns {Record<string, string|undefined>}
199
214
  */
200
215
  function worktreeEnv(ctx, env) {
201
- 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
+ };
202
221
  }
203
222
 
204
223
  /**
@@ -301,6 +320,12 @@ async function withLockProgress(ctx, run) {
301
320
  return { result, timings: summarizeLockEvents(events) };
302
321
  }
303
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
+
304
329
  /**
305
330
  * The suite exit codes § 5 distinguishes from a red run.
306
331
  *
@@ -321,20 +346,22 @@ function describeSuiteFailure(status) {
321
346
  }
322
347
 
323
348
  /**
324
- * Lint and format (deposited), quality-preview, then each ratchet whose
349
+ * Typecheck, lint and format (deposited), quality-preview, then each ratchet whose
325
350
  * baseline is committed.
326
351
  *
327
352
  * @param {object} ctx
328
353
  * @returns {Array<{ key: string, cmd: string, args: string[], gated?: boolean, deposit?: object }>}
329
354
  */
330
355
  function preflightChecks(ctx) {
331
- const ratchets = RATCHETS.filter((r) =>
356
+ const covered = new Set(getQuality(ctx.config).ratchets.coveredByLint);
357
+ const ratchets = STANDALONE_RATCHETS.filter((r) =>
332
358
  fs.existsSync(path.join(ctx.cwd, r.baseline)),
333
359
  ).map((r) => ({
334
360
  key: r.key,
335
361
  cmd: 'node',
336
362
  args: [path.join(SCRIPTS_DIR, r.script), ...r.args],
337
363
  gated: true,
364
+ coveredByLint: covered.has(r.key),
338
365
  }));
339
366
  return [
340
367
  ...creditedPreflight(ctx),
@@ -353,6 +380,7 @@ function preflightChecks(ctx) {
353
380
 
354
381
  /**
355
382
  * A ratchet also fails on `(gate fail)`; its finding names the `+`/`!` rows.
383
+ * Any other check quotes the failure rows its output carries.
356
384
  *
357
385
  * @param {{ key: string, gated?: boolean }} check
358
386
  * @param {{ status: number, output: string }} run
@@ -370,45 +398,149 @@ function preflightFinding(check, run) {
370
398
  .split(/\r?\n/)
371
399
  .filter((line) => SIGNALS.offending.test(line))
372
400
  .slice(0, MAX_OFFENDING_LINES)
373
- : [];
401
+ : extractFailureRows(run.output, { max: MAX_OFFENDING_LINES });
374
402
  const rows = offending.length > 0 ? `: ${offending.join('; ')}` : '';
375
403
  return `${check.key}${check.gated ? ' ratchet' : ''} finding${rows} — fix and commit, then re-run`;
376
404
  }
377
405
 
378
- /** @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
+ */
379
414
  async function stepPreflight(ctx) {
380
415
  const name = 'preflight';
381
416
  if (ctx.state.preflightHead === ctx.head) {
382
- return skipped(
417
+ return creditSkip(
383
418
  name,
384
419
  `preflight already passed at ${ctx.head.slice(0, 12)}`,
385
420
  );
386
421
  }
387
- ctx.state.lintCredit = null;
422
+ ctx.state.preflightCredits = {};
423
+ delete ctx.state.heldLint;
388
424
  let checks;
389
425
  try {
390
426
  checks = preflightChecks(ctx);
391
427
  } catch (err) {
392
428
  return fixRequired(
393
429
  name,
394
- `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' },
395
432
  );
396
433
  }
397
- for (const check of checks) {
398
- const run = await runLogged(
399
- ctx,
400
- `preflight-${check.key}`,
401
- check.cmd,
402
- 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),
403
441
  );
404
- const finding = preflightFinding(check, run);
405
- if (finding) {
406
- 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);
407
448
  }
408
- 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
+ });
409
459
  }
410
460
  ctx.state.preflightHead = ctx.head;
411
- 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;
412
544
  }
413
545
 
414
546
  /** A baseline-only conflict the shared sync resolved is named. */
@@ -424,13 +556,20 @@ function mergedDetail(sync, baseBranch) {
424
556
  /** @param {object} ctx @returns {Promise<StepResult>} */
425
557
  async function stepBaseMerge(ctx) {
426
558
  const name = 'base-merge';
559
+ const skip = await handoffRerunSkip(ctx);
560
+ if (skip) {
561
+ startReview(ctx);
562
+ return skipped(name, skip);
563
+ }
427
564
  const sync = await ctx.syncFromBase({
428
565
  cwd: ctx.cwd,
429
566
  baseBranch: ctx.baseBranch,
430
567
  log: ctx.progress,
431
568
  });
432
569
  if (sync.synced) {
570
+ ctx.state.baseMergeSettled = true;
433
571
  ctx.head = headSha(ctx) ?? ctx.head;
572
+ startReview(ctx);
434
573
  return sync.kind === 'noop-already-current'
435
574
  ? skipped(name, `origin/${ctx.baseBranch} already merged`)
436
575
  : ran(name, mergedDetail(sync, ctx.baseBranch));
@@ -449,17 +588,19 @@ async function stepBaseMerge(ctx) {
449
588
  return fixRequired(
450
589
  name,
451
590
  `merging origin/${ctx.baseBranch} conflicts; the merge was aborted, so the tree is clean — merge it yourself, resolve, commit, re-run`,
452
- { conflictFiles: sync.conflictFiles },
591
+ { conflictFiles: sync.conflictFiles, cause: 'base-merge-conflict' },
453
592
  );
454
593
  }
455
- return fixRequired(name, `merge failed: ${sync.stderr}`.trim());
594
+ return fixRequired(name, `merge failed: ${sync.stderr}`.trim(), {
595
+ cause: 'base-merge-failed',
596
+ });
456
597
  }
457
598
 
458
599
  /**
459
600
  * The depositor close will credit, from the one shared predicate.
460
601
  *
461
602
  * @param {{ config: object, scripts: Record<string, string>|null, cwd: string, getChangedFilesImpl?: Function }} args
462
- * @returns {'coverage-capture'|'test'}
603
+ * @returns {{ depositor: 'coverage-capture'|'test', skipBranch: boolean }}
463
604
  */
464
605
  function selectCreditedDepositor({ config, ...probe }) {
465
606
  const baseBranch = config?.project?.baseBranch ?? 'main';
@@ -467,40 +608,61 @@ function selectCreditedDepositor({ config, ...probe }) {
467
608
  }
468
609
 
469
610
  /**
470
- * @param {object|null|undefined} config
471
- * @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.
472
613
  */
473
- function testGateArgv(config) {
474
- const { cmd, args } = resolveTestGateArgv(config);
475
- 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 };
476
650
  }
477
651
 
478
652
  /** @param {object} ctx @param {AbortSignal} signal @returns {Promise<StepResult>} */
479
653
  async function creditedRun(ctx, signal) {
480
654
  const name = 'credited-run';
481
655
  if (ctx.state.creditHead === ctx.head) {
482
- return skipped(
656
+ return creditSkip(
483
657
  name,
484
658
  `${ctx.depositor} credit already deposited at ${ctx.head.slice(0, 12)}`,
485
659
  { depositor: ctx.depositor },
486
660
  );
487
661
  }
662
+ const ciOwned = settleSuiteOfRecord(ctx, name);
663
+ if (ciOwned) return ciOwned;
488
664
  const capture = ctx.depositor === 'coverage-capture';
489
- const args = capture
490
- ? [path.join(SCRIPTS_DIR, 'coverage-capture.js'), '--cwd', ctx.cwd]
491
- : [
492
- path.join(SCRIPTS_DIR, 'evidence-gate.js'),
493
- '--standalone',
494
- '--scope-id',
495
- String(ctx.storyId),
496
- '--gate',
497
- 'test',
498
- '--worktree',
499
- ctx.cwd,
500
- '--',
501
- // Close's `test` gate argv, so the deposit keys on its credit identity.
502
- ...testGateArgv(ctx.config),
503
- ];
665
+ const { args, label } = depositorArgv(ctx);
504
666
  const { result: run, timings } = await withLockProgress(ctx, (env) =>
505
667
  runLogged(ctx, 'credited-run', 'node', args, env, signal),
506
668
  );
@@ -519,32 +681,148 @@ async function creditedRun(ctx, signal) {
519
681
  ...extra,
520
682
  };
521
683
  }
522
- if (run.status !== 0) {
523
- return fixRequired(name, describeSuiteFailure(run.status), extra);
524
- }
684
+ if (run.status !== 0) return settleSuiteExit(ctx, name, run, extra);
525
685
  const [ranSignal, freshSignal] = capture
526
686
  ? [SIGNALS.captureRan, SIGNALS.captureFresh]
527
687
  : [SIGNALS.testRan, SIGNALS.testFresh];
528
688
  const credit = { head: ctx.head, lockWait, suiteTimings, spawns };
529
689
  if (ranSignal.test(run.output)) {
530
690
  recordCredit(ctx, credit);
531
- return ran(name, `${ctx.depositor} deposited credit`, extra);
691
+ return ran(name, `${label} deposited credit`, extra);
532
692
  }
533
693
  if (freshSignal.test(run.output)) {
534
694
  recordCredit(ctx, credit);
535
- return skipped(name, `${ctx.depositor} credit already fresh`, extra);
695
+ return creditSkip(name, `${label} credit already fresh`, extra);
536
696
  }
537
697
  return fixRequired(
538
698
  name,
539
699
  `${ctx.depositor} exited 0 but printed no credit signal, so it deposited nothing`,
540
- extra,
700
+ { ...extra, cause: 'no-credit-signal' },
541
701
  );
542
702
  }
543
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]}`,
748
+ );
749
+ return parts.length > 0 ? ` (${parts.join(', ')})` : '';
750
+ }
751
+
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)
804
+ ? settleOverBudget(ctx, name, 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);
819
+ }
820
+
544
821
  /** Credit and its run's figures move together, keyed by the credited head. */
545
822
  function recordCredit(ctx, creditTimings) {
546
823
  ctx.state.creditHead = creditTimings.head;
547
824
  ctx.state.creditTimings = creditTimings;
825
+ clearCoverageDeferral(ctx.state);
548
826
  }
549
827
 
550
828
  /**
@@ -564,9 +842,17 @@ function changedPaths(git, cwd) {
564
842
  .filter((p) => p.length > 0);
565
843
  }
566
844
 
567
- /** @param {object} ctx @returns {Promise<StepResult>} */
568
- async function commitSeatedRows(ctx, total, evidencePath) {
569
- 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
+ ) {
570
856
  const paths = changedPaths(ctx.git, ctx.cwd);
571
857
  const add = ctx.git(ctx.cwd, 'add', '--', ...paths);
572
858
  const commit =
@@ -583,48 +869,102 @@ async function commitSeatedRows(ctx, total, evidencePath) {
583
869
  return fixRequired(
584
870
  name,
585
871
  `committing the seated rows failed: ${detail}`.trim(),
586
- { evidencePath: ctx.writeEvidence('seat-commit', detail) },
872
+ {
873
+ evidencePath: ctx.writeEvidence('seat-commit', detail),
874
+ cause: 'seat-commit-failed',
875
+ },
587
876
  );
588
877
  }
589
878
  const priorHead = ctx.head;
590
879
  const creditedPrior = ctx.state.creditHead === priorHead;
591
880
  ctx.head = headSha(ctx) ?? ctx.head;
592
- ctx.state.seatHead = ctx.head;
881
+ carryCoverageDeferral(ctx.state, priorHead, ctx.head);
882
+ ctx.state[headKey] = ctx.head;
593
883
  // Both capture-stamp digests leave `baselines/` out, so a baseline-JSON-only
594
884
  // commit keeps the credit it already holds.
595
885
  if (creditedPrior && ctx.depositor === 'coverage-capture') {
596
886
  recordCredit(ctx, { ...ctx.state.creditTimings, head: ctx.head });
597
887
  }
598
888
  if (paths.every((p) => p.startsWith('baselines/'))) {
599
- carryLintCredit(ctx, priorHead);
889
+ carryPreflightCredits(ctx, priorHead);
890
+ carryHeldLint(ctx.state, priorHead, ctx.head);
600
891
  }
601
892
  return ran(name, `seated ${total} row(s) and committed them`, {
602
893
  evidencePath,
603
894
  });
604
895
  }
605
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
+
606
903
  /**
607
- * The gates whose baselines take a `--seat-missing` pass: CRAP by close's own
608
- * 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.
609
906
  *
610
- * @param {object} config
907
+ * @param {object} ctx
611
908
  * @returns {Array<keyof typeof SEAT_SCRIPTS>}
612
909
  */
613
- function seatKinds(config) {
614
- const mi = config?.delivery?.quality?.gates?.maintainability?.enabled;
910
+ function seatKinds(ctx) {
615
911
  return [
616
- ...(isCrapGateEnabled(config) ? ['crap'] : []),
617
- ...(mi === false ? [] : ['maintainability']),
912
+ ...(isCrapGateEnabled(ctx.config) ? ['crap'] : []),
913
+ ...(seatsCoverage(ctx) ? ['coverage'] : []),
618
914
  ];
619
915
  }
620
916
 
621
- /** @param {object} ctx @returns {Promise<StepResult>} */
622
- async function stepSeat(ctx) {
623
- const name = 'seat';
624
- if (ctx.state.seatHead === ctx.head) {
625
- 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
+ });
626
942
  }
627
- const kinds = 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) {
628
968
  let total = 0;
629
969
  let evidencePath = null;
630
970
  for (const kind of kinds) {
@@ -638,59 +978,41 @@ async function stepSeat(ctx) {
638
978
  return fixRequired(
639
979
  name,
640
980
  `${kind} --seat-missing ${run.status !== 0 ? `refused (exit ${run.status})` : 'printed no `seated: N`'} — read the log for the fix`,
641
- { evidencePath: run.evidencePath },
981
+ { evidencePath: run.evidencePath, cause: 'seat-refused' },
642
982
  );
643
983
  }
644
984
  total += Number(match[1]);
645
985
  }
646
- if (total === 0) {
647
- ctx.state.seatHead = ctx.head;
648
- return skipped(name, 'seated: 0 — nothing to seat', { evidencePath });
649
- }
650
- return commitSeatedRows(ctx, total, evidencePath);
651
- }
652
-
653
- /**
654
- * @param {object} ctx
655
- * @returns {{ reachable: boolean, sha: string|null, detail: string }}
656
- */
657
- function remoteBranchSha(ctx) {
658
- const res = ctx.git(
659
- ctx.cwd,
660
- 'ls-remote',
661
- 'origin',
662
- `refs/heads/${ctx.branch}`,
663
- );
664
- if (res?.status !== 0) {
665
- return {
666
- reachable: false,
667
- sha: null,
668
- detail: `${res?.stderr ?? ''}`.trim(),
669
- };
670
- }
671
- const sha = (res.stdout ?? '').toString().trim().split(/\s+/)[0] || null;
672
- return { reachable: true, sha, detail: '' };
986
+ return { total, evidencePath };
673
987
  }
674
988
 
675
989
  const PORCELAIN_STATUS = /^\s*[ MADRCUT?!]{1,2}\s/;
676
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;
677
994
  const REMOTE_REJECTED =
678
995
  /\[remote rejected\]|permission to \S+ denied|returned error: 403/i;
679
996
  const REF_BEHIND = /\[rejected\].*\((non-fast-forward|fetch first)\)/;
680
997
  const REMOTE_UNREACHABLE =
681
998
  /could not resolve host|unable to access|could not read from remote|connection (refused|timed out|reset)|network is unreachable/i;
682
999
  const PUSH_FAILURES = [
1000
+ [RULESET_EVAL_FAILED, 'ruleset-eval-failed'],
683
1001
  [REMOTE_REJECTED, 'push-rejected'],
684
1002
  [REMOTE_UNREACHABLE, 'remote-unreachable'],
685
1003
  [REF_BEHIND, 'ref-behind'],
686
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;
687
1008
 
688
1009
  /**
689
1010
  * A push the remote refused or could not be reached is blocked; a branch
690
- * 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.
691
1013
  *
692
1014
  * @param {string} output
693
- * @returns {'push-rejected'|'remote-unreachable'|'ref-behind'|null}
1015
+ * @returns {'ruleset-eval-failed'|'push-rejected'|'remote-unreachable'|'ref-behind'|null}
694
1016
  */
695
1017
  function classifyPushFailure(output) {
696
1018
  for (const [pattern, reason] of PUSH_FAILURES) {
@@ -699,48 +1021,150 @@ function classifyPushFailure(output) {
699
1021
  return null;
700
1022
  }
701
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
+
702
1070
  /**
703
1071
  * @param {object} ctx
704
1072
  * @param {{ output: string, evidencePath: string|null }} push
1073
+ * @param {string[]} [range] first-parent commits, oldest first.
705
1074
  * @returns {StepResult}
706
1075
  */
707
- function pushFailure(ctx, push) {
1076
+ function pushFailure(ctx, push, range = []) {
708
1077
  const reason = classifyPushFailure(push.output);
709
1078
  const evidence = { evidencePath: push.evidencePath };
710
- if (reason === 'ref-behind') {
711
- return fixRequired(
712
- 'push',
713
- `origin/${ctx.branch} has commits HEAD lacks — git fetch origin ${ctx.branch}, git merge origin/${ctx.branch}, re-run`,
714
- evidence,
715
- );
716
- }
1079
+ const fixable = FIXABLE_PUSH[reason];
1080
+ if (fixable) return fixable(ctx, evidence, range);
717
1081
  return reason
718
1082
  ? blocked('push', reason, `git push failed (${reason})`, evidence)
719
1083
  : fixRequired(
720
1084
  'push',
721
1085
  'git push failed locally (a pre-push hook?) — fix the cause with a NEW commit, re-run',
722
- evidence,
1086
+ { ...evidence, cause: 'push-hook' },
723
1087
  );
724
1088
  }
725
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
+
726
1155
  /** @param {object} ctx @returns {Promise<StepResult>} */
727
1156
  async function stepPush(ctx) {
728
1157
  const name = 'push';
729
- const before = remoteBranchSha(ctx);
1158
+ const before = remoteBranchSha(ctx.cwd, ctx.branch, ctx.git);
730
1159
  if (!before.reachable) {
731
1160
  return blocked(name, 'remote-unreachable', before.detail);
732
1161
  }
733
1162
  if (before.sha === ctx.head) {
734
1163
  return skipped(name, `origin/${ctx.branch} already at HEAD`);
735
1164
  }
736
- const push = await runLogged(ctx, 'push', 'git', [
737
- 'push',
738
- '-u',
739
- 'origin',
740
- ctx.branch,
741
- ]);
742
- if (push.status !== 0) return pushFailure(ctx, push);
743
- 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);
744
1168
  if (after.sha !== ctx.head) {
745
1169
  return blocked(
746
1170
  name,
@@ -749,9 +1173,8 @@ async function stepPush(ctx) {
749
1173
  { evidencePath: push.evidencePath },
750
1174
  );
751
1175
  }
752
- return ran(name, `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}`, {
753
- evidencePath: push.evidencePath,
754
- });
1176
+ const detail = `pushed ${ctx.branch} → ${ctx.head.slice(0, 12)}${push.how}`;
1177
+ return ran(name, detail, { evidencePath: push.evidencePath });
755
1178
  }
756
1179
 
757
1180
  /**
@@ -761,16 +1184,24 @@ async function stepPush(ctx) {
761
1184
  * @returns {StepResult}
762
1185
  */
763
1186
  function reviewVerdict(deposit, depositPath, settled) {
764
- if (deposit?.halted) {
765
- return fixRequired(
766
- 'review',
767
- 'held review found a CRITICAL — fix, commit, re-run the handoff',
768
- { evidencePath: depositPath },
769
- );
770
- }
1187
+ if (deposit?.halted) return haltedReview(deposit, depositPath);
771
1188
  return settled;
772
1189
  }
773
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
+
774
1205
  /** @param {object} ctx @returns {Promise<StepResult>} */
775
1206
  async function computeHeldReview(ctx) {
776
1207
  const name = 'review';
@@ -787,7 +1218,7 @@ async function computeHeldReview(ctx) {
787
1218
  return reviewVerdict(
788
1219
  held.deposit,
789
1220
  ctx.reviewPath,
790
- skipped(name, 'held review already matches this diff'),
1221
+ creditSkip(name, 'held review already matches this diff'),
791
1222
  );
792
1223
  }
793
1224
  let outcome;
@@ -830,8 +1261,10 @@ function startReview(ctx) {
830
1261
  outcome: 'error',
831
1262
  detail: `held review failed (${err?.message ?? err}); close computes the review itself`,
832
1263
  }))
833
- .finally(() => {
1264
+ .then((result) => {
834
1265
  ctx.reviewMs = ctx.now() - startedAt;
1266
+ ctx.reviewSettled = result;
1267
+ return result;
835
1268
  });
836
1269
  return ctx.reviewPending;
837
1270
  }
@@ -840,7 +1273,7 @@ function startReview(ctx) {
840
1273
  async function stepCreditedRun(ctx) {
841
1274
  const abort = new AbortController();
842
1275
  let halted = null;
843
- startReview(ctx).then((result) => {
1276
+ ctx.reviewPending?.then((result) => {
844
1277
  if (!result.stop) return;
845
1278
  halted = result;
846
1279
  abort.abort();
@@ -853,6 +1286,17 @@ function stepReview(ctx) {
853
1286
  return ctx.reviewPending;
854
1287
  }
855
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
+
856
1300
  /**
857
1301
  * Pure scoring after depositor and seat: no lock, no suite, no evidence, so
858
1302
  * close re-scores them and stays authoritative.
@@ -861,31 +1305,99 @@ function stepReview(ctx) {
861
1305
  */
862
1306
  async function stepPostCapture(ctx) {
863
1307
  const name = 'post-capture';
864
- const { postCaptureHead, creditHead } = ctx.state;
865
- if (postCaptureHead === ctx.head && creditHead === ctx.head) {
866
- return skipped(name, `already clean at ${ctx.head.slice(0, 12)}`);
1308
+ const { postCaptureHead } = ctx.state;
1309
+ if (postCaptureHead === ctx.head && postCaptureSettled(ctx)) {
1310
+ return creditSkip(name, `already clean at ${ctx.head.slice(0, 12)}`);
867
1311
  }
868
1312
  const { gates, failed } = await scorePostCapture(ctx, (...a) =>
869
1313
  runLogged(ctx, ...a),
870
1314
  );
871
1315
  if (failed) {
872
- return fixRequired(name, failed.finding, {
1316
+ const rows = raisedDuplicationSuffix(ctx, failed, MAX_OFFENDING_LINES);
1317
+ return fixRequired(name, `${failed.finding}${rows}`, {
873
1318
  evidencePath: failed.evidencePath,
874
1319
  gate: failed.gate,
1320
+ cause: 'post-capture',
875
1321
  });
876
1322
  }
1323
+ const post = await runPostSeatChecks(ctx, (...a) => runLogged(ctx, ...a));
1324
+ if (post.failed) return postSeatFixRequired(name, post.failed);
877
1325
  ctx.state.postCaptureHead = ctx.head;
878
- return gates.length > 0
879
- ? 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`)
880
1379
  : skipped(name, 'no post-capture gate registered');
881
1380
  }
882
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
+
883
1394
  /**
884
1395
  * The run's step order. The base merges first, so every check scores the
885
- * tree that is pushed. On the evidence-gate path the `test` credit is keyed
886
- * on the tree, so seating (static MI) goes first and cannot void it; the
887
- * capture stamp's digests leave `baselines/` out, so a baseline seat after it
888
- * 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.
889
1401
  *
890
1402
  * @param {'coverage-capture'|'test'} depositor
891
1403
  * @returns {Array<(ctx: object) => Promise<StepResult>>}
@@ -893,10 +1405,12 @@ async function stepPostCapture(ctx) {
893
1405
  function stepOrder(depositor) {
894
1406
  const middle =
895
1407
  depositor === 'test'
896
- ? [stepSeat, stepCreditedRun]
897
- : [stepCreditedRun, stepSeat];
1408
+ ? [beforeRun(stepSeat), beforeRun(stepCreditedRun)]
1409
+ : [beforeRun(stepCreditedRun), stepSeat];
898
1410
  return [
899
1411
  stepBaseMerge,
1412
+ stepDuplicationRescore,
1413
+ stepSeatStatic,
900
1414
  stepPreflight,
901
1415
  ...middle,
902
1416
  stepPostCapture,
@@ -905,6 +1419,22 @@ function stepOrder(depositor) {
905
1419
  ];
906
1420
  }
907
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
+
908
1438
  /**
909
1439
  * Run the steps in order into `steps`; a step may settle several results.
910
1440
  *
@@ -912,8 +1442,9 @@ function stepOrder(depositor) {
912
1442
  */
913
1443
  async function runSteps(ctx, steps) {
914
1444
  for (const step of stepOrder(ctx.depositor)) {
915
- ctx.storyProgress.phase(handoffStepName(step));
916
- 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());
917
1448
  for (const result of results) {
918
1449
  steps.push(result);
919
1450
  ctx.progress(result.name, `${result.outcome} — ${result.detail}`);
@@ -924,6 +1455,8 @@ async function runSteps(ctx, steps) {
924
1455
  return null;
925
1456
  }
926
1457
 
1458
+ const PRECHECK = Object.freeze({ cause: 'precheck' });
1459
+
927
1460
  /**
928
1461
  * Refusals before any step: the handoff runs on the Story branch with the
929
1462
  * implementation committed.
@@ -937,16 +1470,18 @@ function precheck(ctx) {
937
1470
  return fixRequired(
938
1471
  'precheck',
939
1472
  `checked-out branch is ${current || 'unknown'}, not ${ctx.branch} — re-run single-story-init.js (idempotent) and work in its workCwd`,
1473
+ PRECHECK,
940
1474
  );
941
1475
  }
942
1476
  if (!ctx.head) {
943
- return fixRequired('precheck', 'HEAD does not resolve');
1477
+ return fixRequired('precheck', 'HEAD does not resolve', PRECHECK);
944
1478
  }
945
1479
  const dirty = changedPaths(ctx.git, ctx.cwd);
946
1480
  if (dirty.length > 0) {
947
1481
  return fixRequired(
948
1482
  'precheck',
949
1483
  `uncommitted changes (${dirty.slice(0, 5).join(', ')}) — commit the implementation, then re-run`,
1484
+ PRECHECK,
950
1485
  );
951
1486
  }
952
1487
  return null;
@@ -957,7 +1492,7 @@ function precheck(ctx) {
957
1492
  *
958
1493
  * @param {string} statePath
959
1494
  * @param {(tag: string, msg: string) => void} progress
960
- * @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[]> } }}
961
1496
  */
962
1497
  function readState(statePath, progress) {
963
1498
  let raw;
@@ -992,7 +1527,13 @@ async function defaultBlock({
992
1527
  createProviderFn,
993
1528
  warn,
994
1529
  }) {
995
- 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
+ }
996
1537
  try {
997
1538
  await upsertStructuredComment(
998
1539
  provider,
@@ -1016,6 +1557,7 @@ async function defaultBlock({
1016
1557
  * git?: typeof gitSpawn,
1017
1558
  * runCommand?: (cmd: string, args: string[], opts: { cwd: string }) => Promise<{ status: number, stdout: string, stderr: string, timedOut?: boolean }>,
1018
1559
  * syncFromBase?: typeof syncBranchFromBase,
1560
+ * probeBaseSync?: typeof import('../git/base-sync-probe.js').probeBaseSync,
1019
1561
  * probeReview?: typeof probeHeldReviewDiff,
1020
1562
  * computeReview: (input: { storyId: number, cwd: string, config: object }) => Promise<{ written: boolean, path?: string, reason?: string, deposit?: object }>,
1021
1563
  * readPackageScriptsFn?: typeof readPackageScripts,
@@ -1037,6 +1579,10 @@ async function defaultBlock({
1037
1579
  * evidenceCwd?: string,
1038
1580
  * scopeGate?: typeof applyChangedFileScope,
1039
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,
1040
1586
  * }} deps `evidenceCwd` anchors close's evidence store (the main checkout);
1041
1587
  * `runCommand` receives `onChunk`, `signal` and (when set)
1042
1588
  * `timeoutMs` beside `cwd`/`env`; a runner that never calls `onChunk`
@@ -1068,6 +1614,11 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1068
1614
  evidenceCwd = PROJECT_ROOT,
1069
1615
  scopeGate = applyChangedFileScope,
1070
1616
  presentBaselines,
1617
+ runDuplicationRescore = runDuplicationCloseRescore,
1618
+ emitFriction = emitRuntimeFriction,
1619
+ admitSuite = withSuiteAdmission,
1620
+ writeSignal,
1621
+ readSignals,
1071
1622
  } = deps;
1072
1623
  const block =
1073
1624
  deps.block ??
@@ -1096,6 +1647,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1096
1647
  git,
1097
1648
  runCommand,
1098
1649
  syncFromBase,
1650
+ probeBaseSync: deps.probeBaseSync,
1099
1651
  probeReview,
1100
1652
  computeReview,
1101
1653
  progress,
@@ -1108,9 +1660,13 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1108
1660
  scopeGate,
1109
1661
  presentBaselines,
1110
1662
  getChangedFilesFn,
1663
+ runDuplicationRescore,
1664
+ emitFriction,
1665
+ admitSuite,
1111
1666
  state: readState(statePath, progress),
1112
1667
  review: null,
1113
1668
  reviewPending: null,
1669
+ reviewSettled: null,
1114
1670
  reviewMs: null,
1115
1671
  reviewPath: storyReviewDepositPath(storyId, config),
1116
1672
  scripts: readPackageScriptsFn(cwd),
@@ -1130,24 +1686,49 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1130
1686
  return file;
1131
1687
  },
1132
1688
  };
1133
- ctx.depositor = selectCreditedDepositor({
1689
+ const plan = selectCreditedDepositor({
1134
1690
  config,
1135
1691
  scripts: ctx.scripts,
1136
1692
  cwd,
1137
1693
  getChangedFilesImpl: getChangedFilesFn,
1138
1694
  });
1695
+ ctx.depositor = plan.depositor;
1696
+ ctx.skipBranch = plan.skipBranch;
1139
1697
  ctx.head = headSha(ctx);
1140
1698
 
1141
1699
  const steps = [];
1142
- let stop = precheck(ctx);
1143
- if (stop) steps.push(stop);
1144
- else stop = await runSteps(ctx, steps);
1145
- 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);
1146
1718
 
1147
1719
  const status = stop?.stop ?? HANDOFF_STATUS.READY;
1148
1720
  const credited = steps.find((s) => s.name === 'credited-run');
1149
1721
  if (status === HANDOFF_STATUS.BLOCKED) {
1150
- 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
+ }
1151
1732
  }
1152
1733
  const envelope = {
1153
1734
  kind: 'story-handoff',
@@ -1156,23 +1737,35 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1156
1737
  headSha: ctx.head,
1157
1738
  status,
1158
1739
  depositor: ctx.depositor,
1159
- steps: steps.map(({ stop: _stop, ...rest }) => rest),
1740
+ steps: steps.map((step) => envelopeStep(ctx, step)),
1160
1741
  review: ctx.review,
1161
1742
  lockWait: credited?.lockWait ?? null,
1162
1743
  suiteTimings: credited?.suiteTimings ?? null,
1163
1744
  reviewMs: ctx.reviewMs,
1745
+ ...coverageEnvelope(ctx),
1746
+ ...hostResourcesEnvelope(ctx),
1747
+ ...ctx.baseMergeEnvelope,
1164
1748
  ...(stop
1165
1749
  ? {
1166
1750
  failedStep: stop.name,
1751
+ cause: handoffCause(stop.cause),
1167
1752
  evidencePath: stop.evidencePath ?? null,
1168
1753
  ...(stop.reason ? { reason: stop.reason } : {}),
1169
1754
  ...(stop.conflictFiles ? { conflictFiles: stop.conflictFiles } : {}),
1170
1755
  }
1171
1756
  : {}),
1757
+ attempt: await nextHandoffAttempt({ storyId, config, readFn: readSignals }),
1172
1758
  };
1173
1759
  writeFileAtomic(
1174
1760
  statePath,
1175
1761
  `${JSON.stringify({ state: ctx.state, envelope }, null, 2)}\n`,
1176
1762
  );
1763
+ await emitHandoffRecord({
1764
+ storyId,
1765
+ envelope,
1766
+ config,
1767
+ writeFn: writeSignal,
1768
+ warn: (m) => progress('TELEMETRY', m),
1769
+ });
1177
1770
  return { envelope, exitCode: EXIT_CODES[status] };
1178
1771
  }