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
@@ -9,8 +9,18 @@ import { fileURLToPath } from 'node:url';
9
9
  import {
10
10
  BASELINES_GATE_NAMES,
11
11
  buildDefaultGates,
12
+ OVER_BUDGET_BLOCK_HINT,
13
+ overBudgetPolicy,
12
14
  QUALITY_PREVIEW_GATE_NAMES,
13
15
  } from '../close-validation/gates.js';
16
+ import { getPostSeatChecks } from '../config/handoff.js';
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';
14
24
  import {
15
25
  hashCommandConfig,
16
26
  recordPass,
@@ -29,6 +39,7 @@ function closeGates(ctx) {
29
39
  return buildDefaultGates({
30
40
  config: ctx.config,
31
41
  baseBranch: ctx.baseBranch,
42
+ baselineRef: ctx.baselineRef,
32
43
  cwd: ctx.cwd,
33
44
  evidenceCwd: ctx.evidenceCwd,
34
45
  storyId: ctx.storyId,
@@ -40,13 +51,63 @@ function closeGates(ctx) {
40
51
  }
41
52
 
42
53
  /**
43
- * Close's `lint` and `format` entries wrapped in `evidence-gate.js` with the
44
- * 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.
45
106
  */
46
107
  export function creditedPreflight(ctx) {
47
108
  const checks = [];
48
109
  for (const gate of closeGates(ctx).filter((g) =>
49
- ['lint', 'format'].includes(g.name),
110
+ ['typecheck', 'lint', 'format'].includes(g.name),
50
111
  )) {
51
112
  const run = ctx.scopeGate({
52
113
  gate,
@@ -56,75 +117,193 @@ export function creditedPreflight(ctx) {
56
117
  if (run.skip) continue;
57
118
  checks.push({
58
119
  key: gate.name,
59
- cmd: 'node',
60
- args: [
61
- EVIDENCE_GATE,
62
- '--standalone',
63
- '--scope-id',
64
- String(ctx.storyId),
65
- '--gate',
66
- gate.name,
67
- '--worktree',
68
- ctx.cwd,
69
- '--cwd',
70
- ctx.evidenceCwd,
71
- '--',
72
- run.cmd,
73
- ...run.args,
74
- ],
120
+ ...preflightArgv(ctx, gate, run),
75
121
  deposit: { cmd: run.cmd, args: run.args },
76
122
  tolerateNoFilesProcessed: run.tolerateNoFilesProcessed,
123
+ wholeTree: isWholeTreeLint(gate, run),
77
124
  });
78
125
  }
79
126
  return checks;
80
127
  }
81
128
 
82
- /** The `lint` credit a clean preflight deposited, hashed as close hashes it. */
83
- export function lintCredit(ctx, check) {
84
- 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] = {
85
133
  head: ctx.head,
86
134
  configHash: hashCommandConfig({ ...check.deposit, cwd: ctx.cwd }),
87
135
  };
88
136
  }
89
137
 
90
- /**
91
- * Re-key the `lint` pass deposited at `priorHead` onto the seated HEAD. Not
92
- * `format`: its scoped argv names the changed files, which the seat changes.
93
- * Best-effort: a failed write only costs close a lint run.
94
- */
95
- export function carryLintCredit(ctx, priorHead) {
96
- const credit = ctx.state.lintCredit;
97
- 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) {
98
140
  try {
99
141
  recordPass(
100
142
  {
101
143
  storyId: ctx.storyId,
102
- gateName: 'lint',
144
+ gateName,
103
145
  sha: ctx.head,
104
146
  configHash: credit.configHash,
105
147
  inputFingerprint: treeFingerprint(ctx.cwd, ctx.git),
106
148
  },
107
149
  { cwd: ctx.evidenceCwd, standalone: true },
108
150
  );
109
- ctx.state.lintCredit = { ...credit, head: ctx.head };
151
+ return { ...credit, head: ctx.head };
110
152
  } catch (err) {
111
- 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;
112
158
  }
113
159
  }
114
160
 
115
- /** `quality-preview-crap` (capture depositor only) and every baselines entry. */
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
+ }
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Did the credited run defer coverage to CI at this HEAD?
173
+ *
174
+ * @param {{ head: string, state: { coverageDeferredHead?: string } }} ctx
175
+ * @returns {boolean}
176
+ */
177
+ export function isCoverageDeferred(ctx) {
178
+ return Boolean(ctx.head) && ctx.state.coverageDeferredHead === ctx.head;
179
+ }
180
+
181
+ /**
182
+ * Did the depositor — the capture or the `test` run — declare its slice over
183
+ * this host's budget?
184
+ *
185
+ * @param {number} status
186
+ * @returns {boolean}
187
+ */
188
+ export function isOverBudgetExit(status) {
189
+ return status === COVERAGE_OVER_BUDGET_EXIT_CODE;
190
+ }
191
+
192
+ /**
193
+ * An over-budget depositor's step result: deferred to CI (no credit, the
194
+ * coverage-reading gates skipped) or `blocked`, by `coverage.onOverBudget`.
195
+ *
196
+ * @param {object} ctx @param {string} name @param {object} extra
197
+ * @returns {object}
198
+ */
199
+ export function settleOverBudget(ctx, name, extra) {
200
+ const exit = `exit ${COVERAGE_OVER_BUDGET_EXIT_CODE}`;
201
+ if (overBudgetPolicy(ctx.config) === 'defer-to-ci') {
202
+ deferCoverage(ctx.state, ctx.head, COVERAGE_DEFERRED_REASONS.overBudget);
203
+ return {
204
+ name,
205
+ outcome: 'deferred',
206
+ detail: `coverage deferred to CI (${exit}, onOverBudget: defer-to-ci) — no suite ran and no credit was deposited`,
207
+ ...extra,
208
+ };
209
+ }
210
+ return {
211
+ name,
212
+ outcome: 'failed',
213
+ detail: `${ctx.depositor} over budget (${exit}) under delivery.quality.gates.coverage.onOverBudget: block`,
214
+ reason: OVER_BUDGET_BLOCK_HINT,
215
+ cause: 'capture-over-budget',
216
+ stop: 'blocked',
217
+ ...extra,
218
+ };
219
+ }
220
+
221
+ /** The envelope's `coverage` field, present only after a deferral. */
222
+ export function coverageEnvelope(ctx) {
223
+ if (!isCoverageDeferred(ctx)) return {};
224
+ return { coverage: deferralEnvelope(ctx.state.coverageDeferredReason) };
225
+ }
226
+
227
+ /**
228
+ * A real credit ends a deferral; the seat it skipped CRAP on is re-opened,
229
+ * so the captured HEAD still seats its CRAP rows.
230
+ *
231
+ * @param {{ coverageDeferredHead?: string, seatHead?: string }} state
232
+ */
233
+ export function clearCoverageDeferral(state) {
234
+ if (state.coverageDeferredHead === undefined) return;
235
+ delete state.coverageDeferredHead;
236
+ delete state.coverageDeferredReason;
237
+ delete state.seatHead;
238
+ }
239
+
240
+ /** A seat commit keeps a deferral its parent HEAD held. */
241
+ export function carryCoverageDeferral(state, priorHead, head) {
242
+ if (state.coverageDeferredHead === priorHead) {
243
+ state.coverageDeferredHead = head;
244
+ }
245
+ }
246
+
247
+ /** Post-capture re-scores until the run is credited or deferred at HEAD. */
248
+ export function postCaptureSettled(ctx) {
249
+ return ctx.state.creditHead === ctx.head || isCoverageDeferred(ctx);
250
+ }
251
+
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. */
256
+ export function seatableKinds(ctx, kinds) {
257
+ const deferred = isCoverageDeferred(ctx);
258
+ return kinds.filter((kind) => !deferred || !ARTIFACT_SEATS.has(kind));
259
+ }
260
+
261
+ /**
262
+ * `quality-preview-crap` (capture depositor only) and every baselines entry;
263
+ * after a deferral, none that reads the coverage artifact.
264
+ */
116
265
  function postCaptureGates(ctx) {
117
266
  const names = new Set(Object.values(BASELINES_GATE_NAMES));
118
267
  if (ctx.depositor === 'coverage-capture') {
119
268
  names.add(QUALITY_PREVIEW_GATE_NAMES.crap);
120
269
  }
121
- return closeGates(ctx).filter((g) => names.has(g.name) && !g.skip);
270
+ const keep = postCaptureFilter(names, isCoverageDeferred(ctx));
271
+ return closeGates(ctx).filter(keep);
272
+ }
273
+
274
+ /** A registered, unskipped post-capture gate, minus artifact readers after a deferral. */
275
+ function postCaptureFilter(names, deferred) {
276
+ return (g) =>
277
+ names.has(g.name) && !g.skip && !(deferred && g.readsCoverageArtifact);
278
+ }
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];
122
284
  }
123
285
 
124
286
  /** The gate name, plus the kinds a baselines entry scores. */
125
287
  function describeGate(gate) {
126
- const i = gate.args.indexOf('--gate');
127
- 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
+ };
128
307
  }
129
308
 
130
309
  /** Run each post-capture gate through `run`; the first non-zero exit is the finding. */
@@ -138,13 +317,7 @@ export async function scorePostCapture(ctx, run) {
138
317
  gate.args,
139
318
  env,
140
319
  );
141
- if (res.status !== 0) {
142
- const finding = `${describeGate(gate)} finding (exit ${res.status}) — fix and commit, then re-run`;
143
- return {
144
- gates,
145
- failed: { gate: gate.name, finding, evidencePath: res.evidencePath },
146
- };
147
- }
320
+ if (res.status !== 0) return { gates, failed: failure(gate, res) };
148
321
  }
149
322
  return { gates, failed: null };
150
323
  }
@@ -0,0 +1,169 @@
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
+ config: ctx.config,
73
+ logger: { info: log, warn: log },
74
+ });
75
+ } catch (err) {
76
+ return { outcome: 'error', detail: `threw: ${err?.message ?? err}` };
77
+ }
78
+ const settled = settle(ctx, result, readHead);
79
+ if (settled.outcome !== 'error') {
80
+ ctx.state.duplicationRescore = {
81
+ head: ctx.head,
82
+ partners: result?.partners ?? {},
83
+ };
84
+ }
85
+ return settled;
86
+ }
87
+
88
+ /** @returns {string} the configured duplication baseline path. */
89
+ function baselineRelPath(config) {
90
+ try {
91
+ return (
92
+ getQuality(config)?.gates?.duplication?.baselinePath ??
93
+ DEFAULT_BASELINE_REL_PATH
94
+ );
95
+ } catch {
96
+ return DEFAULT_BASELINE_REL_PATH;
97
+ }
98
+ }
99
+
100
+ /** Path → percentage; `null` on any read or parse failure. */
101
+ function rowsOf(text) {
102
+ try {
103
+ const rows = JSON.parse(text)?.rows;
104
+ if (!Array.isArray(rows)) return null;
105
+ return new Map(rows.map((r) => [r?.path, r?.percentage ?? null]));
106
+ } catch {
107
+ return null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The duplication rows the worktree's baseline raised over `baselineRef`,
113
+ * each with its recorded clone partners. Descriptive only: check-baselines
114
+ * stays the verdict, so an unreadable side yields `[]`.
115
+ *
116
+ * @param {object} ctx the handoff context.
117
+ * @param {{ baselineRef?: string, limit: number, readFile?: (p: string) => string }} opts
118
+ * @returns {string[]}
119
+ */
120
+ function raisedDuplicationRows(
121
+ ctx,
122
+ {
123
+ baselineRef = `origin/${ctx.baseBranch}`,
124
+ limit,
125
+ readFile = (p) => fs.readFileSync(p, 'utf8'),
126
+ },
127
+ ) {
128
+ const relPath = baselineRelPath(ctx.config);
129
+ const base = ctx.git(ctx.cwd, 'show', `${baselineRef}:${relPath}`);
130
+ const baseRows = base?.status === 0 ? rowsOf(base.stdout ?? '') : null;
131
+ let headRows = null;
132
+ try {
133
+ headRows = rowsOf(readFile(path.resolve(ctx.cwd, relPath)));
134
+ } catch {
135
+ headRows = null;
136
+ }
137
+ if (!baseRows || !headRows) return [];
138
+ const partners = ctx.state.duplicationRescore?.partners ?? {};
139
+ const lines = [];
140
+ for (const [file, head] of headRows) {
141
+ const before = baseRows.get(file) ?? null;
142
+ if (head === null || (before !== null && head <= before)) continue;
143
+ const clones = partners[file]?.length
144
+ ? ` (clones: ${partners[file].join(', ')})`
145
+ : '';
146
+ lines.push(`${file} ${pct(before)} → ${pct(head)}${clones}`);
147
+ }
148
+ return lines.slice(0, limit);
149
+ }
150
+
151
+ /**
152
+ * The post-capture finding's suffix naming raised duplication rows; `''` for
153
+ * a gate that does not score duplication or when nothing was raised.
154
+ *
155
+ * @param {object} ctx
156
+ * @param {{ scoresDuplication?: boolean, baselineRef?: string }} failed
157
+ * @param {number} limit
158
+ * @returns {string}
159
+ */
160
+ export function raisedDuplicationSuffix(ctx, failed, limit) {
161
+ if (!failed.scoresDuplication) return '';
162
+ const raised = raisedDuplicationRows(ctx, {
163
+ baselineRef: failed.baselineRef,
164
+ limit,
165
+ });
166
+ return raised.length > 0
167
+ ? `; raised duplication rows: ${raised.join('; ')}`
168
+ : '';
169
+ }
@@ -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
+ }
@@ -636,7 +636,11 @@ export async function runPlanPersist({
636
636
  assumptionNormalizations: validated.normalizations ?? [],
637
637
  waveCollisions,
638
638
  supersede,
639
- rewrite: { ticket: rewrite.ticketId, reason: rewrite.reason },
639
+ rewrite: {
640
+ ticket: rewrite.ticketId,
641
+ reason: rewrite.reason,
642
+ preservedMarker: Boolean(rewrite.target?.trailingMarker),
643
+ },
640
644
  epic: containerEpic,
641
645
  };
642
646
  }
@@ -28,7 +28,7 @@ const MID_DELIVERY_LABELS = Object.freeze([
28
28
 
29
29
  /**
30
30
  * @typedef {object} RewriteResolution
31
- * @property {{ id: number, ticket: object }|null} target The source to
31
+ * @property {{ id: number, ticket: object, trailingMarker?: string|null }|null} target The source to
32
32
  * rewrite, carrying the probe's fresh copy so the rewrite needs no re-read.
33
33
  * @property {number|null} ticketId The rewritten source's id, or null.
34
34
  * @property {string|null} reason Why there is no target.
@@ -111,7 +111,79 @@ export async function resolveRewriteTarget({
111
111
  `filing a new Story and closing #${id} instead.`,
112
112
  ]);
113
113
  }
114
- return { target: { id, ticket }, ticketId: id, reason: null, warnings: [] };
114
+ const trailingMarker = await resolveTrailingMarker(provider, id, ticket);
115
+ return {
116
+ target: { id, ticket, trailingMarker },
117
+ ticketId: id,
118
+ reason: null,
119
+ warnings: [],
120
+ };
121
+ }
122
+
123
+ /** One HTML comment filling the whole line, and nothing after its close. */
124
+ const SINGLE_COMMENT_LINE_RE = /^<!--(?:(?!-->)[\s\S])*-->$/;
125
+ /** Mandrel's own markers: a carried stale fingerprint would shadow the new one. */
126
+ const MANDREL_MARKER_RE = /^<!--\s*(?:plan-story:|ap:structured-comment\b)/;
127
+
128
+ /**
129
+ * @param {unknown} body
130
+ * @returns {string|null} The last non-blank line when it is a consumer's
131
+ * single-line HTML-comment marker.
132
+ */
133
+ function trailingMarkerOf(body) {
134
+ if (typeof body !== 'string') return null;
135
+ const last = body
136
+ .split('\n')
137
+ .map((line) => line.trim())
138
+ .filter((line) => line !== '')
139
+ .at(-1);
140
+ if (!last || !SINGLE_COMMENT_LINE_RE.test(last)) return null;
141
+ return MANDREL_MARKER_RE.test(last) ? null : last;
142
+ }
143
+
144
+ /**
145
+ * @param {unknown} commentBody A `plan-rewrite` comment.
146
+ * @returns {string|null} The original body inside its `<details>` block.
147
+ */
148
+ function originalBodyOf(commentBody) {
149
+ if (typeof commentBody !== 'string') return null;
150
+ const open = commentBody.indexOf('</summary>');
151
+ const close = commentBody.lastIndexOf('</details>');
152
+ if (open < 0 || close < open) return null;
153
+ return commentBody.slice(open + '</summary>'.length, close);
154
+ }
155
+
156
+ /**
157
+ * The pre-plan body decides: a preserved original wins over a body an earlier
158
+ * rewrite already replaced. Reads only, so a dry run resolves it too.
159
+ *
160
+ * @param {object} provider
161
+ * @param {number} id
162
+ * @param {{ body?: string }} ticket
163
+ * @returns {Promise<string|null>}
164
+ */
165
+ async function resolveTrailingMarker(provider, id, ticket) {
166
+ try {
167
+ const preserved = await findStructuredComment(
168
+ provider,
169
+ id,
170
+ PLAN_REWRITE_COMMENT_TYPE,
171
+ );
172
+ if (preserved) return trailingMarkerOf(originalBodyOf(preserved.body));
173
+ } catch {
174
+ // Unreadable comments: the current body is the best remaining evidence.
175
+ }
176
+ return trailingMarkerOf(ticket.body);
177
+ }
178
+
179
+ /**
180
+ * @param {string} body
181
+ * @param {string|null|undefined} marker
182
+ * @returns {string} `body` with `marker` as its last line, exactly once.
183
+ */
184
+ function withTrailingMarker(body, marker) {
185
+ if (!marker || trailingMarkerOf(body) === marker) return body;
186
+ return `${body}\n${marker}`;
115
187
  }
116
188
 
117
189
  /**
@@ -141,7 +213,7 @@ function buildPlanRewriteCommentBody(ticket) {
141
213
  *
142
214
  * @param {object} args
143
215
  * @param {object} args.provider
144
- * @param {{ id: number, ticket: object }} args.target
216
+ * @param {{ id: number, ticket: object, trailingMarker?: string|null }} args.target
145
217
  * @param {string} args.title
146
218
  * @param {string} args.body
147
219
  * @param {{ add: string[], remove: string[] }} args.labels
@@ -170,7 +242,7 @@ export async function rewriteSourceTicket({
170
242
  }
171
243
  await provider.updateTicket(id, {
172
244
  title,
173
- body,
245
+ body: withTrailingMarker(body, target.trailingMarker),
174
246
  labels,
175
247
  _ticketSnapshot: ticket,
176
248
  });
@@ -794,7 +794,7 @@ function adoptedEntry(story, already, rewriting) {
794
794
  * @param {object} args
795
795
  * @param {object} args.provider
796
796
  * @param {object} args.story
797
- * @param {{ id: number, ticket: object }} args.rewriting
797
+ * @param {{ id: number, ticket: object, trailingMarker?: string|null }} args.rewriting
798
798
  * @param {string[]} args.labels
799
799
  * @param {Map<string, number>} args.idBySlug
800
800
  * @returns {Promise<object>} The `created[]` entry.
@@ -892,7 +892,7 @@ async function createOneStory({
892
892
  * @param {ReturnType<typeof assemblePlanStories>['stories']} args.stories
893
893
  * @param {object} [args.opts]
894
894
  * @param {boolean} [args.opts.dryRun=false]
895
- * @param {{ id: number, ticket: object }|null} [args.opts.rewriteTarget=null]
895
+ * @param {{ id: number, ticket: object, trailingMarker?: string|null }|null} [args.opts.rewriteTarget=null]
896
896
  * @returns {Promise<{
897
897
  * created: Array<{ slug: string, id: number, url?: string, title: string, adopted: boolean, rewritten?: boolean }>,
898
898
  * dependencyEdges: { edgesAdded: number, edgesSkipped: number, edgesFailed: number, storiesProcessed: number }|null,