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
@@ -13,7 +13,14 @@ import {
13
13
  overBudgetPolicy,
14
14
  QUALITY_PREVIEW_GATE_NAMES,
15
15
  } from '../close-validation/gates.js';
16
+ import { getPostSeatChecks } from '../config/handoff.js';
16
17
  import { COVERAGE_OVER_BUDGET_EXIT_CODE } from '../coverage-capture.js';
18
+ import {
19
+ COVERAGE_DEFERRED_REASONS,
20
+ deferCoverage,
21
+ deferralEnvelope,
22
+ } from '../coverage-deferral.js';
23
+ import { quoteFailureRows } from '../failure-rows.js';
17
24
  import {
18
25
  hashCommandConfig,
19
26
  recordPass,
@@ -32,6 +39,7 @@ function closeGates(ctx) {
32
39
  return buildDefaultGates({
33
40
  config: ctx.config,
34
41
  baseBranch: ctx.baseBranch,
42
+ baselineRef: ctx.baselineRef,
35
43
  cwd: ctx.cwd,
36
44
  evidenceCwd: ctx.evidenceCwd,
37
45
  storyId: ctx.storyId,
@@ -43,13 +51,63 @@ function closeGates(ctx) {
43
51
  }
44
52
 
45
53
  /**
46
- * Close's `lint` and `format` entries wrapped in `evidence-gate.js` with the
47
- * argv close executes; a disabled or scoped-out gate deposits nothing.
54
+ * Gates whose argv ignores the changed-file set, so a baselines-only seat
55
+ * keeps their credit. Not `format`: its scoped argv names the changed files.
56
+ */
57
+ const CARRYABLE_GATES = new Set(['lint', 'typecheck']);
58
+
59
+ /**
60
+ * With `postSeatChecks` declared, `lint` runs bare: its credit is held until
61
+ * those checks pass at HEAD (story-handoff's `releaseHeldLint`).
62
+ */
63
+ function holdsLint(ctx, gate) {
64
+ return gate.name === 'lint' && getPostSeatChecks(ctx.config).length > 0;
65
+ }
66
+
67
+ /** The argv a preflight check runs: bare when held, else deposited. */
68
+ function preflightArgv(ctx, gate, run) {
69
+ if (holdsLint(ctx, gate)) {
70
+ return { cmd: run.cmd, args: run.args, held: true };
71
+ }
72
+ return {
73
+ cmd: 'node',
74
+ args: [
75
+ EVIDENCE_GATE,
76
+ '--standalone',
77
+ '--scope-id',
78
+ String(ctx.storyId),
79
+ '--gate',
80
+ gate.name,
81
+ '--worktree',
82
+ ctx.cwd,
83
+ '--cwd',
84
+ ctx.evidenceCwd,
85
+ '--',
86
+ run.cmd,
87
+ ...run.args,
88
+ ],
89
+ };
90
+ }
91
+
92
+ /** A lint whose argv close never narrows to the changed files. */
93
+ function isWholeTreeLint(gate, run) {
94
+ return (
95
+ gate.name === 'lint' &&
96
+ !gate.changedFileScope &&
97
+ run.cmd === gate.cmd &&
98
+ run.args.length === gate.args.length &&
99
+ run.args.every((arg, i) => arg === gate.args[i])
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Close's preflight entries wrapped in `evidence-gate.js` with the argv close
105
+ * executes; a disabled or scoped-out gate deposits nothing.
48
106
  */
49
107
  export function creditedPreflight(ctx) {
50
108
  const checks = [];
51
109
  for (const gate of closeGates(ctx).filter((g) =>
52
- ['lint', 'format'].includes(g.name),
110
+ ['typecheck', 'lint', 'format'].includes(g.name),
53
111
  )) {
54
112
  const run = ctx.scopeGate({
55
113
  gate,
@@ -59,59 +117,54 @@ export function creditedPreflight(ctx) {
59
117
  if (run.skip) continue;
60
118
  checks.push({
61
119
  key: gate.name,
62
- cmd: 'node',
63
- args: [
64
- EVIDENCE_GATE,
65
- '--standalone',
66
- '--scope-id',
67
- String(ctx.storyId),
68
- '--gate',
69
- gate.name,
70
- '--worktree',
71
- ctx.cwd,
72
- '--cwd',
73
- ctx.evidenceCwd,
74
- '--',
75
- run.cmd,
76
- ...run.args,
77
- ],
120
+ ...preflightArgv(ctx, gate, run),
78
121
  deposit: { cmd: run.cmd, args: run.args },
79
122
  tolerateNoFilesProcessed: run.tolerateNoFilesProcessed,
123
+ wholeTree: isWholeTreeLint(gate, run),
80
124
  });
81
125
  }
82
126
  return checks;
83
127
  }
84
128
 
85
- /** The `lint` credit a clean preflight deposited, hashed as close hashes it. */
86
- export function lintCredit(ctx, check) {
87
- return {
129
+ /** Record a passed carryable check's credit, hashed as close hashes it. */
130
+ export function recordPreflightCredit(ctx, check) {
131
+ if (!CARRYABLE_GATES.has(check.key)) return;
132
+ ctx.state.preflightCredits[check.key] = {
88
133
  head: ctx.head,
89
134
  configHash: hashCommandConfig({ ...check.deposit, cwd: ctx.cwd }),
90
135
  };
91
136
  }
92
137
 
93
- /**
94
- * Re-key the `lint` pass deposited at `priorHead` onto the seated HEAD. Not
95
- * `format`: its scoped argv names the changed files, which the seat changes.
96
- * Best-effort: a failed write only costs close a lint run.
97
- */
98
- export function carryLintCredit(ctx, priorHead) {
99
- const credit = ctx.state.lintCredit;
100
- if (credit?.head !== priorHead) return;
138
+ /** Re-key one credit onto the seated HEAD; best-effort, like close's rerun. */
139
+ export function carryCredit(ctx, gateName, credit) {
101
140
  try {
102
141
  recordPass(
103
142
  {
104
143
  storyId: ctx.storyId,
105
- gateName: 'lint',
144
+ gateName,
106
145
  sha: ctx.head,
107
146
  configHash: credit.configHash,
108
147
  inputFingerprint: treeFingerprint(ctx.cwd, ctx.git),
109
148
  },
110
149
  { cwd: ctx.evidenceCwd, standalone: true },
111
150
  );
112
- ctx.state.lintCredit = { ...credit, head: ctx.head };
151
+ return { ...credit, head: ctx.head };
113
152
  } catch (err) {
114
- ctx.progress('seat', `⚠️ lint credit not carried: ${err?.message ?? err}`);
153
+ ctx.progress(
154
+ 'seat',
155
+ `⚠️ ${gateName} credit not carried: ${err?.message ?? err}`,
156
+ );
157
+ return credit;
158
+ }
159
+ }
160
+
161
+ /** Re-key each credit deposited at `priorHead` onto the seated HEAD. */
162
+ export function carryPreflightCredits(ctx, priorHead) {
163
+ const credits = ctx.state.preflightCredits ?? {};
164
+ for (const [gateName, credit] of Object.entries(credits)) {
165
+ if (credit?.head === priorHead) {
166
+ credits[gateName] = carryCredit(ctx, gateName, credit);
167
+ }
115
168
  }
116
169
  }
117
170
 
@@ -121,25 +174,23 @@ export function carryLintCredit(ctx, priorHead) {
121
174
  * @param {{ head: string, state: { coverageDeferredHead?: string } }} ctx
122
175
  * @returns {boolean}
123
176
  */
124
- function isCoverageDeferred(ctx) {
177
+ export function isCoverageDeferred(ctx) {
125
178
  return Boolean(ctx.head) && ctx.state.coverageDeferredHead === ctx.head;
126
179
  }
127
180
 
128
181
  /**
129
- * Did the capture depositor declare its slice over this host's budget?
182
+ * Did the depositor — the capture or the `test` run — declare its slice over
183
+ * this host's budget?
130
184
  *
131
- * @param {{ depositor: string }} ctx @param {number} status
185
+ * @param {number} status
132
186
  * @returns {boolean}
133
187
  */
134
- export function isOverBudgetCapture(ctx, status) {
135
- return (
136
- ctx.depositor === 'coverage-capture' &&
137
- status === COVERAGE_OVER_BUDGET_EXIT_CODE
138
- );
188
+ export function isOverBudgetExit(status) {
189
+ return status === COVERAGE_OVER_BUDGET_EXIT_CODE;
139
190
  }
140
191
 
141
192
  /**
142
- * An over-budget capture's step result: deferred to CI (no credit, the
193
+ * An over-budget depositor's step result: deferred to CI (no credit, the
143
194
  * coverage-reading gates skipped) or `blocked`, by `coverage.onOverBudget`.
144
195
  *
145
196
  * @param {object} ctx @param {string} name @param {object} extra
@@ -148,7 +199,7 @@ export function isOverBudgetCapture(ctx, status) {
148
199
  export function settleOverBudget(ctx, name, extra) {
149
200
  const exit = `exit ${COVERAGE_OVER_BUDGET_EXIT_CODE}`;
150
201
  if (overBudgetPolicy(ctx.config) === 'defer-to-ci') {
151
- ctx.state.coverageDeferredHead = ctx.head;
202
+ deferCoverage(ctx.state, ctx.head, COVERAGE_DEFERRED_REASONS.overBudget);
152
203
  return {
153
204
  name,
154
205
  outcome: 'deferred',
@@ -159,8 +210,9 @@ export function settleOverBudget(ctx, name, extra) {
159
210
  return {
160
211
  name,
161
212
  outcome: 'failed',
162
- detail: `capture over budget (${exit}) under onOverBudget: block`,
213
+ detail: `${ctx.depositor} over budget (${exit}) under delivery.quality.gates.coverage.onOverBudget: block`,
163
214
  reason: OVER_BUDGET_BLOCK_HINT,
215
+ cause: 'capture-over-budget',
164
216
  stop: 'blocked',
165
217
  ...extra,
166
218
  };
@@ -169,13 +221,7 @@ export function settleOverBudget(ctx, name, extra) {
169
221
  /** The envelope's `coverage` field, present only after a deferral. */
170
222
  export function coverageEnvelope(ctx) {
171
223
  if (!isCoverageDeferred(ctx)) return {};
172
- return {
173
- coverage: {
174
- status: 'deferred',
175
- reason: 'over-budget',
176
- policy: 'defer-to-ci',
177
- },
178
- };
224
+ return { coverage: deferralEnvelope(ctx.state.coverageDeferredReason) };
179
225
  }
180
226
 
181
227
  /**
@@ -187,6 +233,7 @@ export function coverageEnvelope(ctx) {
187
233
  export function clearCoverageDeferral(state) {
188
234
  if (state.coverageDeferredHead === undefined) return;
189
235
  delete state.coverageDeferredHead;
236
+ delete state.coverageDeferredReason;
190
237
  delete state.seatHead;
191
238
  }
192
239
 
@@ -202,10 +249,13 @@ export function postCaptureSettled(ctx) {
202
249
  return ctx.state.creditHead === ctx.head || isCoverageDeferred(ctx);
203
250
  }
204
251
 
205
- /** CRAP seating needs a fresh artifact, which a deferral never writes. */
252
+ /** Seat kinds that read the coverage artifact, which a deferral never writes. */
253
+ const ARTIFACT_SEATS = new Set(['crap', 'coverage']);
254
+
255
+ /** CRAP and coverage seating need a fresh artifact. */
206
256
  export function seatableKinds(ctx, kinds) {
207
257
  const deferred = isCoverageDeferred(ctx);
208
- return kinds.filter((kind) => kind !== 'crap' || !deferred);
258
+ return kinds.filter((kind) => !deferred || !ARTIFACT_SEATS.has(kind));
209
259
  }
210
260
 
211
261
  /**
@@ -227,10 +277,33 @@ function postCaptureFilter(names, deferred) {
227
277
  names.has(g.name) && !g.skip && !(deferred && g.readsCoverageArtifact);
228
278
  }
229
279
 
280
+ /** The kinds a baselines entry scores; `null` without `--gate` (every kind). */
281
+ function gateKinds(gate) {
282
+ const i = gate.args.indexOf('--gate');
283
+ return i === -1 ? null : gate.args[i + 1];
284
+ }
285
+
230
286
  /** The gate name, plus the kinds a baselines entry scores. */
231
287
  function describeGate(gate) {
232
- const i = gate.args.indexOf('--gate');
233
- return i === -1 ? gate.name : `${gate.name} (kinds: ${gate.args[i + 1]})`;
288
+ const kinds = gateKinds(gate);
289
+ return kinds ? `${gate.name} (kinds: ${kinds})` : gate.name;
290
+ }
291
+
292
+ /** Does a baselines entry score duplication? (No `--gate` scores every kind.) */
293
+ function scoresDuplication(gate) {
294
+ if (gate.name === QUALITY_PREVIEW_GATE_NAMES.crap) return false;
295
+ return (gateKinds(gate) ?? 'duplication').includes('duplication');
296
+ }
297
+
298
+ /** A non-zero post-capture exit as the handoff's finding. */
299
+ function failure(gate, res) {
300
+ return {
301
+ gate: gate.name,
302
+ finding: `${describeGate(gate)} finding (exit ${res.status})${quoteFailureRows(res.output)} — fix and commit, then re-run`,
303
+ evidencePath: res.evidencePath,
304
+ scoresDuplication: scoresDuplication(gate),
305
+ baselineRef: gate.env?.BASELINE_REF,
306
+ };
234
307
  }
235
308
 
236
309
  /** Run each post-capture gate through `run`; the first non-zero exit is the finding. */
@@ -244,13 +317,7 @@ export async function scorePostCapture(ctx, run) {
244
317
  gate.args,
245
318
  env,
246
319
  );
247
- if (res.status !== 0) {
248
- const finding = `${describeGate(gate)} finding (exit ${res.status}) — fix and commit, then re-run`;
249
- return {
250
- gates,
251
- failed: { gate: gate.name, finding, evidencePath: res.evidencePath },
252
- };
253
- }
320
+ if (res.status !== 0) return { gates, failed: failure(gate, res) };
254
321
  }
255
322
  return { gates, failed: null };
256
323
  }
@@ -0,0 +1,170 @@
1
+ /**
2
+ * handoff-rescore.js — the handoff runs close's own duplication re-score
3
+ * before any credit, so close's later re-score over the same tree no-ops;
4
+ * and names the duplication rows a branch raised in a post-capture finding.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+
10
+ import { getQuality } from '../config-resolver.js';
11
+ import { DEFAULT_BASELINE_REL_PATH } from './story-close/duplication-close-rescore.js';
12
+
13
+ /** Re-score reasons that settle `skipped`; every other reason is an error. */
14
+ const SKIP_REASONS = new Set(['gate-disabled', 'no-changed-files']);
15
+
16
+ const pct = (v) => (v === null || v === undefined ? 'none' : `${v}%`);
17
+
18
+ /**
19
+ * @param {Array<{ path: string, before: number|null, after: number|null }>} moved
20
+ * @returns {string}
21
+ */
22
+ function describeMoved(moved) {
23
+ return moved
24
+ .map((m) => `${m.path} ${pct(m.before)} → ${pct(m.after)}`)
25
+ .join(', ');
26
+ }
27
+
28
+ /** @returns {{ outcome: string, detail: string }} */
29
+ function settle(ctx, result, readHead) {
30
+ if (result?.committed) {
31
+ ctx.head = readHead() ?? ctx.head;
32
+ return {
33
+ outcome: 'ran',
34
+ detail: `re-scored ${describeMoved(result.moved ?? [])}; committed untagged ${result.sha}`,
35
+ };
36
+ }
37
+ if (result?.reason === 'unchanged') {
38
+ return { outcome: 'ran', detail: 'unchanged' };
39
+ }
40
+ if (SKIP_REASONS.has(result?.reason)) {
41
+ return { outcome: 'skipped', detail: result.reason };
42
+ }
43
+ return { outcome: 'error', detail: result?.reason ?? 'no result' };
44
+ }
45
+
46
+ /**
47
+ * Run the re-score once per HEAD; best-effort, it never stops the run. An
48
+ * `error` records nothing, so a re-run retries.
49
+ *
50
+ * @param {object} ctx the handoff context; `ctx.head` moves on a commit and
51
+ * `ctx.runDuplicationRescore` is close's `runDuplicationCloseRescore`.
52
+ * @param {() => string|null} readHead
53
+ * @returns {Promise<{ outcome: string, detail: string }>}
54
+ */
55
+ export async function rescoreDuplication(ctx, readHead) {
56
+ const prior = ctx.state.duplicationRescore;
57
+ if (prior?.head === ctx.head) {
58
+ return {
59
+ outcome: 'skipped',
60
+ detail: `already re-scored at ${ctx.head.slice(0, 12)}`,
61
+ };
62
+ }
63
+ const log = (m) => ctx.progress('duplication-rescore', m);
64
+ let result;
65
+ try {
66
+ result = await ctx.runDuplicationRescore({
67
+ cwd: ctx.cwd,
68
+ worktreePath: ctx.cwd,
69
+ storyId: ctx.storyId,
70
+ baseBranch: ctx.baseBranch,
71
+ storyBranch: ctx.branch,
72
+ baselineRef: ctx.baselineRef,
73
+ config: ctx.config,
74
+ logger: { info: log, warn: log },
75
+ });
76
+ } catch (err) {
77
+ return { outcome: 'error', detail: `threw: ${err?.message ?? err}` };
78
+ }
79
+ const settled = settle(ctx, result, readHead);
80
+ if (settled.outcome !== 'error') {
81
+ ctx.state.duplicationRescore = {
82
+ head: ctx.head,
83
+ partners: result?.partners ?? {},
84
+ };
85
+ }
86
+ return settled;
87
+ }
88
+
89
+ /** @returns {string} the configured duplication baseline path. */
90
+ function baselineRelPath(config) {
91
+ try {
92
+ return (
93
+ getQuality(config)?.gates?.duplication?.baselinePath ??
94
+ DEFAULT_BASELINE_REL_PATH
95
+ );
96
+ } catch {
97
+ return DEFAULT_BASELINE_REL_PATH;
98
+ }
99
+ }
100
+
101
+ /** Path → percentage; `null` on any read or parse failure. */
102
+ function rowsOf(text) {
103
+ try {
104
+ const rows = JSON.parse(text)?.rows;
105
+ if (!Array.isArray(rows)) return null;
106
+ return new Map(rows.map((r) => [r?.path, r?.percentage ?? null]));
107
+ } catch {
108
+ return null;
109
+ }
110
+ }
111
+
112
+ /**
113
+ * The duplication rows the worktree's baseline raised over `baselineRef`,
114
+ * each with its recorded clone partners. Descriptive only: check-baselines
115
+ * stays the verdict, so an unreadable side yields `[]`.
116
+ *
117
+ * @param {object} ctx the handoff context.
118
+ * @param {{ baselineRef?: string, limit: number, readFile?: (p: string) => string }} opts
119
+ * @returns {string[]}
120
+ */
121
+ function raisedDuplicationRows(
122
+ ctx,
123
+ {
124
+ baselineRef = `origin/${ctx.baseBranch}`,
125
+ limit,
126
+ readFile = (p) => fs.readFileSync(p, 'utf8'),
127
+ },
128
+ ) {
129
+ const relPath = baselineRelPath(ctx.config);
130
+ const base = ctx.git(ctx.cwd, 'show', `${baselineRef}:${relPath}`);
131
+ const baseRows = base?.status === 0 ? rowsOf(base.stdout ?? '') : null;
132
+ let headRows = null;
133
+ try {
134
+ headRows = rowsOf(readFile(path.resolve(ctx.cwd, relPath)));
135
+ } catch {
136
+ headRows = null;
137
+ }
138
+ if (!baseRows || !headRows) return [];
139
+ const partners = ctx.state.duplicationRescore?.partners ?? {};
140
+ const lines = [];
141
+ for (const [file, head] of headRows) {
142
+ const before = baseRows.get(file) ?? null;
143
+ if (head === null || (before !== null && head <= before)) continue;
144
+ const clones = partners[file]?.length
145
+ ? ` (clones: ${partners[file].join(', ')})`
146
+ : '';
147
+ lines.push(`${file} ${pct(before)} → ${pct(head)}${clones}`);
148
+ }
149
+ return lines.slice(0, limit);
150
+ }
151
+
152
+ /**
153
+ * The post-capture finding's suffix naming raised duplication rows; `''` for
154
+ * a gate that does not score duplication or when nothing was raised.
155
+ *
156
+ * @param {object} ctx
157
+ * @param {{ scoresDuplication?: boolean, baselineRef?: string }} failed
158
+ * @param {number} limit
159
+ * @returns {string}
160
+ */
161
+ export function raisedDuplicationSuffix(ctx, failed, limit) {
162
+ if (!failed.scoresDuplication) return '';
163
+ const raised = raisedDuplicationRows(ctx, {
164
+ baselineRef: failed.baselineRef,
165
+ limit,
166
+ });
167
+ return raised.length > 0
168
+ ? `; raised duplication rows: ${raised.join('; ')}`
169
+ : '';
170
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * handoff-suite-of-record.js — the credited-run step under
3
+ * `coverage.suiteOfRecord: "ci"`, decided from config before any lock or spawn.
4
+ */
5
+
6
+ import { suiteOfRecord } from '../close-validation/gates.js';
7
+ import {
8
+ COVERAGE_DEFERRED_REASONS,
9
+ deferCoverage,
10
+ } from '../coverage-deferral.js';
11
+
12
+ const UNDECLARED_DETAIL =
13
+ 'delivery.quality.gates.coverage.suiteOfRecord is "ci" but delivery.quality.gates.coverage.ciRatchetCheck is unset — name the CI check that runs coverage-ratchet.js, or set suiteOfRecord to "local"';
14
+
15
+ /**
16
+ * The capture depositor's step under the `ci` posture: deferred to CI, or
17
+ * `blocked` when no `ciRatchetCheck` would take the ratchet. `null` when the
18
+ * posture is off or the depositor is `test`.
19
+ *
20
+ * @param {{ config: object, depositor: string, head: string, state: object }} ctx
21
+ * @param {string} name
22
+ * @returns {object|null}
23
+ */
24
+ export function settleSuiteOfRecord(ctx, name) {
25
+ const { ci, ciRatchetCheck } = suiteOfRecord(ctx.config);
26
+ if (!ci || ctx.depositor !== 'coverage-capture') return null;
27
+ const extra = { depositor: ctx.depositor };
28
+ if (!ciRatchetCheck) {
29
+ return {
30
+ name,
31
+ outcome: 'failed',
32
+ detail: UNDECLARED_DETAIL,
33
+ reason: 'ci-ratchet-undeclared',
34
+ stop: 'blocked',
35
+ ...extra,
36
+ };
37
+ }
38
+ deferCoverage(ctx.state, ctx.head, COVERAGE_DEFERRED_REASONS.suiteOfRecordCi);
39
+ return {
40
+ name,
41
+ outcome: 'deferred',
42
+ detail: `coverage deferred to CI (suiteOfRecord: ci, ratchet check "${ciRatchetCheck}") — nothing spawned and no credit was deposited`,
43
+ ...extra,
44
+ };
45
+ }