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
@@ -0,0 +1,213 @@
1
+ /**
2
+ * phases/land-review-record.js — the post-land step that guarantees a landed
3
+ * PR carries a `verification-results` record: close's own post, else the
4
+ * handoff deposit matching the merged head, else an `Unreviewed` marker.
5
+ * Runs before the temp purge, which deletes the deposit.
6
+ */
7
+
8
+ import { createGh } from '../../../gh-exec.js';
9
+ import { gitSpawn as defaultGitSpawn } from '../../../git-utils.js';
10
+ import {
11
+ emitRuntimeFriction as defaultEmitRuntimeFriction,
12
+ RUNTIME_FRICTION_CATEGORIES,
13
+ } from '../../../observability/runtime-friction.js';
14
+ import { postReviewComment } from '../../code-review.js';
15
+ import { MERGE_WAIT_GH_TIMEOUT_MS } from '../../merge-poll.js';
16
+ import {
17
+ probeHeldReviewDiff as defaultProbeHeldReviewDiff,
18
+ readReviewDeposit as defaultReadReviewDeposit,
19
+ depositAsComputedReview,
20
+ } from '../../review-deposit.js';
21
+ import {
22
+ findStructuredComment as defaultFindStructuredComment,
23
+ postStructuredComment as defaultPostStructuredComment,
24
+ upsertStructuredComment as defaultUpsertStructuredComment,
25
+ } from '../../ticketing.js';
26
+ import { settleStoryScopeReview as defaultSettleStoryScopeReview } from './code-review.js';
27
+
28
+ const REVIEW_TYPE = 'verification-results';
29
+
30
+ /** The merged PR's head SHA and URL, through the merge wait's time-boxed gh. */
31
+ async function readPrHead({
32
+ prNumber,
33
+ gh = createGh(undefined, { timeoutMs: MERGE_WAIT_GH_TIMEOUT_MS }),
34
+ }) {
35
+ const view = await gh.pr.view(prNumber, ['headRefOid', 'url']);
36
+ const headSha = typeof view?.headRefOid === 'string' ? view.headRefOid : '';
37
+ if (!headSha) throw new Error(`PR #${prNumber} reported no headRefOid`);
38
+ return { headSha, url: typeof view?.url === 'string' ? view.url : null };
39
+ }
40
+
41
+ /** Digest equality alone: land-time matching keeps no-verdict deposits. */
42
+ function sameDiff(probed, deposit) {
43
+ return Boolean(probed.diffDigest) && probed.diffDigest === deposit.diffDigest;
44
+ }
45
+
46
+ /** Head-SHA equality first: a merge-commit merge empties the three-dot diff. */
47
+ function matchDeposit(ctx, headSha) {
48
+ const deposit = ctx.readDepositFn(Number(ctx.storyId), {
49
+ config: ctx.config,
50
+ });
51
+ if (!deposit) return { deposit: null, reason: 'no-deposit' };
52
+ if (deposit.headSha === headSha) return { deposit, reason: null };
53
+ const probed = ctx.probeHeldReviewDiffFn({
54
+ cwd: ctx.cwd,
55
+ storyId: ctx.storyId,
56
+ sha: headSha,
57
+ baseBranch: ctx.baseBranch,
58
+ gitSpawnFn: ctx.gitSpawnFn,
59
+ config: ctx.config,
60
+ readDepositFn: () => deposit,
61
+ });
62
+ return sameDiff(probed, deposit)
63
+ ? { deposit, reason: null }
64
+ : { deposit: null, reason: 'stale-deposit' };
65
+ }
66
+
67
+ /**
68
+ * @param {{ storyId: number|string, reason: string, headSha: string }} args
69
+ * @returns {string}
70
+ */
71
+ function buildUnreviewedMarker({ storyId, reason, headSha }) {
72
+ return [
73
+ `## 🔬 Code Review — Story #${storyId}`,
74
+ '',
75
+ `**Unreviewed** (\`${reason}\`): this PR landed without close and no handoff review matches its merged head \`${headSha}\`.`,
76
+ '',
77
+ `Run \`node .agents/scripts/story-review-compute.js --story ${storyId}\` and read the diff before trusting this merge.`,
78
+ ].join('\n');
79
+ }
80
+
81
+ /** A halt is a merged CRITICAL unless the reviewer never reached a verdict. */
82
+ function mergedOverCritical(deposit) {
83
+ return Boolean(deposit.halted) && deposit.haltCause !== 'no-verdict';
84
+ }
85
+
86
+ async function postDeposit(ctx, deposit, pr) {
87
+ const computed = depositAsComputedReview(deposit);
88
+ computed.result.report =
89
+ `> Computed at handoff for \`${deposit.headSha}\`; recorded at land because the Story landed without close.\n\n` +
90
+ computed.result.report;
91
+ const outcome = await ctx.settleStoryScopeReviewFn({
92
+ computed,
93
+ storyId: ctx.storyId,
94
+ prUrl: pr.url ?? ctx.prUrl,
95
+ prNumber: ctx.prNumber,
96
+ provider: ctx.provider,
97
+ progress: (tag, msg) => ctx.progress?.(tag, msg),
98
+ postReportFn: (post) =>
99
+ postReviewComment({
100
+ ...post,
101
+ upsertCommentFn: ctx.upsertStructuredCommentFn,
102
+ }),
103
+ });
104
+ if (!outcome?.posted) return { ok: false, detail: 'post-failed' };
105
+ await emit(ctx, RUNTIME_FRICTION_CATEGORIES.REVIEW_RECORDED_AT_LAND, {
106
+ outcome: 'posted-from-deposit',
107
+ headSha: pr.headSha,
108
+ severity: deposit.severity,
109
+ });
110
+ if (mergedOverCritical(deposit)) {
111
+ await emit(ctx, RUNTIME_FRICTION_CATEGORIES.REVIEW_CRITICAL_MERGED, {
112
+ outcome: 'posted-from-deposit',
113
+ headSha: pr.headSha,
114
+ severity: deposit.severity,
115
+ });
116
+ }
117
+ return { ok: true, detail: 'posted-from-deposit' };
118
+ }
119
+
120
+ async function postUnreviewed(ctx, reason, pr) {
121
+ const outcome = `unreviewed-${reason}`;
122
+ const body = buildUnreviewedMarker({
123
+ storyId: ctx.storyId,
124
+ reason,
125
+ headSha: pr.headSha,
126
+ });
127
+ await ctx.upsertStructuredCommentFn(
128
+ ctx.provider,
129
+ ctx.prNumber,
130
+ REVIEW_TYPE,
131
+ body,
132
+ );
133
+ await ctx.postStructuredCommentFn(
134
+ ctx.provider,
135
+ ctx.storyId,
136
+ 'notification',
137
+ `🔬 PR [#${ctx.prNumber}](${pr.url ?? ctx.prUrl}) landed **unreviewed** (\`${reason}\`) — run the Story-scope review before trusting the merge.`,
138
+ );
139
+ await emit(ctx, RUNTIME_FRICTION_CATEGORIES.REVIEW_RECORDED_AT_LAND, {
140
+ outcome,
141
+ headSha: pr.headSha,
142
+ });
143
+ return { ok: true, detail: outcome };
144
+ }
145
+
146
+ function emit(ctx, category, details) {
147
+ return ctx.emitRuntimeFrictionFn({
148
+ storyId: ctx.storyId,
149
+ category,
150
+ tool: 'runPostLandTail',
151
+ details: { ...details, prNumber: ctx.prNumber },
152
+ config: ctx.config,
153
+ });
154
+ }
155
+
156
+ /**
157
+ * @param {object} args
158
+ * @returns {Promise<{ ok: boolean, detail: string }>} `ok` is false only when
159
+ * the record failed to post; a read failure throws for `step()` to degrade.
160
+ */
161
+ export async function recordLandReview({
162
+ storyId,
163
+ prNumber,
164
+ prUrl = null,
165
+ gh,
166
+ baseBranch,
167
+ cwd,
168
+ provider,
169
+ config,
170
+ progress,
171
+ findStructuredCommentFn = defaultFindStructuredComment,
172
+ readPrHeadFn = readPrHead,
173
+ readDepositFn = defaultReadReviewDeposit,
174
+ probeHeldReviewDiffFn = defaultProbeHeldReviewDiff,
175
+ settleStoryScopeReviewFn = defaultSettleStoryScopeReview,
176
+ upsertStructuredCommentFn = defaultUpsertStructuredComment,
177
+ postStructuredCommentFn = defaultPostStructuredComment,
178
+ emitRuntimeFrictionFn = defaultEmitRuntimeFriction,
179
+ gitSpawnFn = defaultGitSpawn,
180
+ }) {
181
+ if (!Number.isInteger(prNumber) || prNumber <= 0) {
182
+ return { ok: true, detail: 'no-pr' };
183
+ }
184
+ if (await findStructuredCommentFn(provider, prNumber, REVIEW_TYPE)) {
185
+ return { ok: true, detail: 'already-recorded' };
186
+ }
187
+ const ctx = {
188
+ storyId,
189
+ prNumber,
190
+ prUrl,
191
+ baseBranch,
192
+ cwd,
193
+ provider,
194
+ config,
195
+ progress,
196
+ readDepositFn,
197
+ probeHeldReviewDiffFn,
198
+ settleStoryScopeReviewFn,
199
+ upsertStructuredCommentFn,
200
+ postStructuredCommentFn,
201
+ emitRuntimeFrictionFn,
202
+ gitSpawnFn,
203
+ };
204
+ const pr = await readPrHeadFn({ prNumber, gh });
205
+ const { deposit, reason } = matchDeposit(ctx, pr.headSha);
206
+ progress?.(
207
+ 'POST-LAND',
208
+ `🔬 PR #${prNumber} has no review record — posting ${deposit ? 'the handoff deposit' : `an unreviewed marker (${reason})`}.`,
209
+ );
210
+ return deposit
211
+ ? postDeposit(ctx, deposit, pr)
212
+ : postUnreviewed(ctx, reason, pr);
213
+ }
@@ -5,6 +5,7 @@
5
5
  * module does the git read and assembles the `gh pr create` strings.
6
6
  */
7
7
 
8
+ import { deferralLines as markerLines } from '../../../coverage-deferral.js';
8
9
  import { gitSpawn as defaultGitSpawn } from '../../../git-utils.js';
9
10
  import { Logger as DefaultLogger } from '../../../Logger.js';
10
11
  import {
@@ -134,6 +135,11 @@ function synthesizeSubject({ description, storyId, commitMessages }) {
134
135
  return `${type}: ${shapeDescription(raw)}`;
135
136
  }
136
137
 
138
+ /** @param {string|null} coverageDeferred @returns {string[]} */
139
+ function deferralLines(coverageDeferred) {
140
+ return markerLines(coverageDeferred);
141
+ }
142
+
137
143
  /**
138
144
  * `Closes #<id>` auto-closes the Story; lifted trailers follow the marker and
139
145
  * a breaking footer goes LAST, per the spec, for repos that squash with the
@@ -143,20 +149,11 @@ function synthesizeSubject({ description, storyId, commitMessages }) {
143
149
  * trailerBlock?: string[] }} args
144
150
  * @returns {string}
145
151
  */
146
- /** The PR-body line a capture deferred to CI adds beneath `Closes #<id>`. */
147
- const COVERAGE_DEFERRED_PR_LINE =
148
- "Coverage deferred to CI: the capture slice was over this host's budget (exit 76, onOverBudget: defer-to-ci).";
149
-
150
- /** @param {boolean} coverageDeferred @returns {string[]} */
151
- function deferralLines(coverageDeferred) {
152
- return coverageDeferred ? ['', COVERAGE_DEFERRED_PR_LINE] : [];
153
- }
154
-
155
152
  function buildPrBody({
156
153
  storyId,
157
154
  breakingNotes,
158
155
  trailerBlock = [],
159
- coverageDeferred = false,
156
+ coverageDeferred = null,
160
157
  }) {
161
158
  const lines = [
162
159
  `Closes #${storyId}`,
@@ -191,7 +188,7 @@ function announceBreaking(breakingNotes, progress) {
191
188
  * storyBranch: string, baseBranch: string, cwd?: string,
192
189
  * gitSpawn?: typeof defaultGitSpawn, config?: object,
193
190
  * progress?: (tag: string, msg: string) => void,
194
- * coverageDeferred?: boolean }} args
191
+ * coverageDeferred?: 'over-budget'|'suite-of-record-ci'|null }} args
195
192
  * @returns {{ title: string, body: string, breaking: boolean, breakingNotes: string[] }}
196
193
  */
197
194
  export function buildPullRequestFields({
@@ -204,7 +201,7 @@ export function buildPullRequestFields({
204
201
  gitSpawn = defaultGitSpawn,
205
202
  config,
206
203
  progress = () => {},
207
- coverageDeferred = false,
204
+ coverageDeferred = null,
208
205
  }) {
209
206
  const read = { storyBranch, baseBranch, cwd, gitSpawn };
210
207
  const commitMessages = readBranchCommits(read);
@@ -24,19 +24,25 @@ function pullRequestArgs(ctx, deps) {
24
24
  };
25
25
  }
26
26
 
27
- export async function openAndReviewPr(ctx, deps) {
28
- const { options, worktreePath, storyId, storyBranch, baseBranch } = ctx;
29
- const { cwd } = options;
27
+ /** Push from the worktree so `pre-push` measures the tree being sent. */
28
+ function pushPhase(ctx, deps) {
30
29
  ctx.setPhase('push');
31
- // Push from the worktree so `pre-push` measures the tree being sent; the
32
- // ref-based reads below resolve identically from the shared `.git`.
33
- pushStoryBranch({
34
- cwd,
35
- worktreePath,
36
- storyBranch,
30
+ return pushStoryBranch({
31
+ cwd: ctx.options.cwd,
32
+ worktreePath: ctx.worktreePath,
33
+ storyBranch: ctx.storyBranch,
34
+ skipValidation: ctx.options.skipValidation,
37
35
  gitSync: deps.git.gitSync,
36
+ gitSpawn: deps.git.gitSpawn,
38
37
  progress,
39
- });
38
+ }).outcome;
39
+ }
40
+
41
+ export async function openAndReviewPr(ctx, deps) {
42
+ const { options, storyId, storyBranch, baseBranch } = ctx;
43
+ const { cwd } = options;
44
+ // The ref-based reads below resolve identically from the shared `.git`.
45
+ const pushOutcome = pushPhase(ctx, deps);
40
46
  ctx.setPhase('pull-request');
41
47
  const { url: prUrl, alreadyMerged } = await ensurePullRequestWith(
42
48
  pullRequestArgs(ctx, deps),
@@ -46,7 +52,13 @@ export async function openAndReviewPr(ctx, deps) {
46
52
  // Already merged (landed between invocations): skip review and arm; confirm observes it.
47
53
  if (alreadyMerged) {
48
54
  discardHeldReview(ctx.heldReview, 'PR already merged', progress);
49
- return { prUrl, prNumber, alreadyMerged: true };
55
+ return {
56
+ prUrl,
57
+ prNumber,
58
+ alreadyMerged: true,
59
+ pushOutcome,
60
+ reviewSkipped: true,
61
+ };
50
62
  }
51
63
  const reviewOutcome = await reviewAfterPrOpen({
52
64
  held: ctx.heldReview,
@@ -59,6 +71,7 @@ export async function openAndReviewPr(ctx, deps) {
59
71
  provider: deps.provider,
60
72
  runCodeReviewFn: deps.runCodeReview,
61
73
  gitSpawnFn: deps.git.gitSpawn,
74
+ config: deps.config,
62
75
  progress,
63
76
  setPhase: ctx.setPhase,
64
77
  pauseTimer: ctx.phaseTimer.pause,
@@ -71,7 +84,8 @@ export async function openAndReviewPr(ctx, deps) {
71
84
  prUrl,
72
85
  prNumber,
73
86
  alreadyMerged: false,
87
+ pushOutcome,
74
88
  reviewOverride,
75
- reviewDegraded: reviewOutcome.degraded === true,
89
+ reviewDegradations: reviewOutcome.degradations ?? [],
76
90
  };
77
91
  }
@@ -29,6 +29,7 @@ import { reapPlanRunLabelsForStory as defaultReapPlanRunLabelsForStory } from '.
29
29
  import { reassertStatusColumn as defaultReassertStatusColumn } from '../../reassert-status-column.js';
30
30
  import { releaseStoryLease as defaultReleaseStoryLease } from '../../single-story-lease-guard.js';
31
31
  import { captureStoryFollowUps as defaultCaptureStoryFollowUps } from '../../story-follow-ups.js';
32
+ import { recordLandReview as defaultRecordLandReview } from './land-review-record.js';
32
33
  import { reapWorktreePhase as defaultReapWorktreePhase } from './worktree-reap.js';
33
34
  import { existingWorktreePath } from './worktree-restore.js';
34
35
 
@@ -394,16 +395,28 @@ async function runLockedLocalSteps({
394
395
  }
395
396
  }
396
397
 
398
+ /** Step outcomes → the per-step booleans plus their `details`. */
399
+ function toTailReport(outcomes) {
400
+ const entries = Object.entries(outcomes);
401
+ return {
402
+ ...Object.fromEntries(entries.map(([k, o]) => [k, o.ok])),
403
+ details: Object.fromEntries(entries.map(([k, o]) => [k, o.detail])),
404
+ };
405
+ }
406
+
397
407
  /**
398
- * Run the post-land tail: friction markers, then the GitHub steps and the
399
- * locked local steps concurrently, then review dispositions, temp purge and
400
- * lease release.
408
+ * Run the post-land tail: friction markers, the PR's review record, then the
409
+ * GitHub steps and the locked local steps concurrently, then review
410
+ * dispositions, temp purge and lease release.
401
411
  *
402
412
  * @param {object} args
403
413
  * @param {number} args.storyId
404
414
  * @param {string} args.storyBranch
405
415
  * @param {string} args.baseBranch
406
416
  * @param {string} args.cwd The MAIN checkout (never the worktree).
417
+ * @param {number|null} [args.prNumber] Absent skips the review record.
418
+ * @param {string|null} [args.prUrl]
419
+ * @param {object} [args.gh] The caller's gh, for the review record's PR read.
407
420
  * @param {object} args.provider
408
421
  * @param {object} [args.config]
409
422
  * @param {(tag: string, msg: string) => void} [args.progress]
@@ -421,13 +434,17 @@ async function runLockedLocalSteps({
421
434
  * @param {Function} [args.rollUpEpicForStoryFn]
422
435
  * @param {Function} [args.reapWorktreePhaseFn]
423
436
  * @param {Function} [args.recordStoryDispositionsFn]
424
- * @returns {Promise<{ followUps: boolean, statusResync: boolean, worktreeReap: boolean, refCleanup: boolean, baseFastForward: boolean, reviewDispositions: boolean, tempPurge: boolean, leaseRelease: boolean, epicRollup: boolean, details: Record<string, string|null> }>}
437
+ * @param {Function} [args.recordLandReviewFn]
438
+ * @returns {Promise<{ reviewRecord: boolean, followUps: boolean, statusResync: boolean, worktreeReap: boolean, refCleanup: boolean, baseFastForward: boolean, reviewDispositions: boolean, tempPurge: boolean, leaseRelease: boolean, epicRollup: boolean, details: Record<string, string|null> }>}
425
439
  */
426
440
  export async function runPostLandTail({
427
441
  storyId,
428
442
  storyBranch,
429
443
  baseBranch,
430
444
  cwd,
445
+ prNumber = null,
446
+ prUrl = null,
447
+ gh,
431
448
  provider,
432
449
  config,
433
450
  progress,
@@ -445,6 +462,7 @@ export async function runPostLandTail({
445
462
  rollUpEpicForStoryFn = defaultRollUpEpicForStory,
446
463
  reapWorktreePhaseFn = defaultReapWorktreePhase,
447
464
  recordStoryDispositionsFn = defaultRecordStoryDispositions,
465
+ recordLandReviewFn = defaultRecordLandReview,
448
466
  }) {
449
467
  progress?.('POST-LAND', `🧾 Running land tail for Story #${storyId}...`);
450
468
 
@@ -463,6 +481,23 @@ export async function runPostLandTail({
463
481
  config,
464
482
  });
465
483
 
484
+ // Before the purge, which deletes the deposit it posts.
485
+ const reviewRecord = await step(
486
+ () =>
487
+ recordLandReviewFn({
488
+ storyId,
489
+ prNumber,
490
+ prUrl,
491
+ gh,
492
+ baseBranch,
493
+ cwd,
494
+ provider,
495
+ config,
496
+ progress,
497
+ }),
498
+ { name: 'review record', progress },
499
+ );
500
+
466
501
  // The GitHub steps are independent of each other and of the local
467
502
  // lock-held mutations, so all of them run concurrently.
468
503
  const [followUps, statusResync, , epicRollup, local] = await Promise.all([
@@ -550,28 +585,18 @@ export async function runPostLandTail({
550
585
  { name: 'lease release', progress },
551
586
  );
552
587
 
553
- const tail = {
554
- followUps: followUps.ok,
555
- statusResync: statusResync.ok,
556
- worktreeReap: worktreeReap.ok,
557
- refCleanup: refCleanup.ok,
558
- baseFastForward: baseFastForward.ok,
559
- reviewDispositions: reviewDispositions.ok,
560
- tempPurge: tempPurge.ok,
561
- leaseRelease: leaseRelease.ok,
562
- epicRollup: epicRollup.ok,
563
- details: {
564
- followUps: followUps.detail,
565
- statusResync: statusResync.detail,
566
- worktreeReap: worktreeReap.detail,
567
- refCleanup: refCleanup.detail,
568
- baseFastForward: baseFastForward.detail,
569
- reviewDispositions: reviewDispositions.detail,
570
- tempPurge: tempPurge.detail,
571
- leaseRelease: leaseRelease.detail,
572
- epicRollup: epicRollup.detail,
573
- },
574
- };
588
+ const tail = toTailReport({
589
+ reviewRecord,
590
+ followUps,
591
+ statusResync,
592
+ worktreeReap,
593
+ refCleanup,
594
+ baseFastForward,
595
+ reviewDispositions,
596
+ tempPurge,
597
+ leaseRelease,
598
+ epicRollup,
599
+ });
575
600
  const degraded = Object.entries(tail)
576
601
  .filter(([k, v]) => k !== 'details' && v === false)
577
602
  .map(([k]) => k);
@@ -181,7 +181,8 @@ export async function runPreGateSteps({
181
181
  run: () =>
182
182
  writebackStep(ctx, {
183
183
  tag: 'DUPLICATION',
184
- run: runDuplicationCloseRescore,
184
+ run: (args) =>
185
+ runDuplicationCloseRescore({ ...args, baselineRef: ctx.baselineRef }),
185
186
  noun: 'duplication re-score commit',
186
187
  describe: (w) =>
187
188
  `Re-scored ${w.movedPaths?.length ?? 0} duplication row(s) (untagged)`,
@@ -57,7 +57,8 @@ export async function runPrePushPhases(ctx, deps) {
57
57
  progress,
58
58
  gitSpawn: deps.gitSpawn,
59
59
  });
60
- const baseSync = await runSyncStep(ctx, deps);
60
+ // biome-ignore lint/suspicious/noAssignInExpressions: the runner's envelope reads ctx.baseSync
61
+ const baseSync = (ctx.baseSync = await runSyncStep(ctx, deps));
61
62
  if (options.skipValidation) {
62
63
  progress('VALIDATE', '⏭ Skipped (--skip-validation).');
63
64
  return {
@@ -110,6 +111,6 @@ export async function runPrePushPhases(ctx, deps) {
110
111
  lockWait: validation?.lockWait ?? null,
111
112
  suiteTimings: validation?.suiteTimings ?? null,
112
113
  pending: validation?.pending === true,
113
- coverageDeferred: validation?.coverageDeferred === true,
114
+ coverageDeferred: validation?.coverageDeferred ?? null,
114
115
  };
115
116
  }
@@ -7,6 +7,10 @@
7
7
  * positively empty diff; an unenumerable diff fails open.
8
8
  */
9
9
 
10
+ import {
11
+ readDeferralMarker,
12
+ rewriteDeferralLines,
13
+ } from '../../../coverage-deferral.js';
10
14
  import { gh as defaultGh } from '../../../gh-exec.js';
11
15
  import { Logger } from '../../../Logger.js';
12
16
  import { computeChangeSet as defaultComputeChangeSet } from '../../change-set.js';
@@ -66,6 +70,26 @@ function emptyDiffError({ storyBranch, baseRef, storyId }) {
66
70
  );
67
71
  }
68
72
 
73
+ /**
74
+ * A reused PR must carry this run's deferral marker, or confirm-merge skips
75
+ * the CI ratchet. A null reason may mean "not measured", so no strip.
76
+ */
77
+ async function syncDeferralMarker({ gh, url, body, coverageDeferred }) {
78
+ if (!coverageDeferred || readDeferralMarker(body) === coverageDeferred) {
79
+ return;
80
+ }
81
+ try {
82
+ await gh.pr.edit(url, [
83
+ '--body',
84
+ rewriteDeferralLines(body, coverageDeferred),
85
+ ]);
86
+ } catch (err) {
87
+ throw new Error(
88
+ `[single-story-close] could not write \`Coverage-deferred: ${coverageDeferred}\` onto ${url}: ${err?.message ?? err}`,
89
+ );
90
+ }
91
+ }
92
+
69
93
  /**
70
94
  * @param {{
71
95
  * cwd: string,
@@ -78,7 +102,7 @@ function emptyDiffError({ storyBranch, baseRef, storyId }) {
78
102
  * gh?: ReturnType<typeof import('../../../gh-exec.js').createGh>,
79
103
  * computeChangeSetFn?: typeof defaultComputeChangeSet,
80
104
  * progress?: (tag: string, msg: string) => void,
81
- * coverageDeferred?: boolean,
105
+ * coverageDeferred?: 'over-budget'|'suite-of-record-ci'|null,
82
106
  * }} args
83
107
  * @returns {Promise<{ url: string, alreadyMerged: boolean, created: boolean }>}
84
108
  */
@@ -93,33 +117,42 @@ export async function ensurePullRequestWith({
93
117
  gh = defaultGh,
94
118
  computeChangeSetFn = defaultComputeChangeSet,
95
119
  progress = () => {},
96
- coverageDeferred = false,
120
+ coverageDeferred = null,
97
121
  }) {
98
122
  // `gh-exec` spawns `gh` in the process cwd, not `_cwd`.
123
+ let rows = [];
124
+ let existing = null;
99
125
  try {
100
126
  // `--state all`, not `open`: a merged PR must be seen.
101
- const rows = await gh.pr.list(
127
+ rows = await gh.pr.list(
102
128
  ['--head', storyBranch, '--state', 'all'],
103
- ['url', 'state', 'mergedAt'],
129
+ ['url', 'state', 'mergedAt', 'body'],
104
130
  );
105
- const existing = pickHeadPullRequest(rows);
106
- if (existing?.state === 'OPEN') {
107
- progress('PR', `Reusing existing PR: ${existing.url}`);
108
- return { url: existing.url, alreadyMerged: false, created: false };
109
- }
110
- if (existing?.state === 'MERGED') {
111
- progress(
112
- 'PR',
113
- `✅ PR for ${storyBranch} is already MERGED: ${existing.url} — ` +
114
- 'reporting that outcome instead of opening a second PR.',
115
- );
116
- return { url: existing.url, alreadyMerged: true, created: false };
117
- }
131
+ existing = pickHeadPullRequest(rows);
118
132
  } catch (err) {
119
133
  Logger.warn?.(
120
134
  `[single-story-close] ⚠️ \`gh pr list\` probe failed (continuing to create): ${err?.message ?? err}`,
121
135
  );
122
136
  }
137
+ if (existing?.state === 'OPEN') {
138
+ progress('PR', `Reusing existing PR: ${existing.url}`);
139
+ const row = rows.find((r) => String(r?.url ?? '').trim() === existing.url);
140
+ await syncDeferralMarker({
141
+ gh,
142
+ url: existing.url,
143
+ body: row?.body,
144
+ coverageDeferred,
145
+ });
146
+ return { url: existing.url, alreadyMerged: false, created: false };
147
+ }
148
+ if (existing?.state === 'MERGED') {
149
+ progress(
150
+ 'PR',
151
+ `✅ PR for ${storyBranch} is already MERGED: ${existing.url} — ` +
152
+ 'reporting that outcome instead of opening a second PR.',
153
+ );
154
+ return { url: existing.url, alreadyMerged: true, created: false };
155
+ }
123
156
 
124
157
  const emptyDiff = probeEmptyDiff({
125
158
  cwd: _cwd ?? process.cwd(),