mandrel 2.110.0 → 2.111.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 (37) hide show
  1. package/.agents/audit-checklists/state-machines.md +21 -0
  2. package/.agents/docs/agentrc-reference.json +2 -1
  3. package/.agents/docs/configuration.md +33 -0
  4. package/.agents/docs/workflows.md +2 -1
  5. package/.agents/rules/ci-remediation.md +28 -4
  6. package/.agents/schemas/agentrc.schema.json +6 -0
  7. package/.agents/schemas/audit-rules.json +28 -0
  8. package/.agents/schemas/story-deliver-terminal.schema.json +9 -2
  9. package/.agents/scripts/coverage-capture.js +3 -1
  10. package/.agents/scripts/file-ci-gap.js +220 -10
  11. package/.agents/scripts/lib/audit-to-stories/audit-lenses.js +1 -0
  12. package/.agents/scripts/lib/close-validation/gates.js +48 -0
  13. package/.agents/scripts/lib/close-validation/runner.js +118 -31
  14. package/.agents/scripts/lib/config/gates/coverage.schema.js +9 -0
  15. package/.agents/scripts/lib/config/quality.js +3 -0
  16. package/.agents/scripts/lib/coverage-capture-usage.js +1 -1
  17. package/.agents/scripts/lib/coverage-capture.js +16 -0
  18. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  19. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +124 -23
  20. package/.agents/scripts/lib/orchestration/handoff-gates.js +108 -2
  21. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -1
  22. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +76 -4
  23. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +2 -2
  24. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +3 -0
  25. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +7 -1
  26. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +20 -2
  27. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +21 -13
  28. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +1 -0
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +3 -0
  30. package/.agents/scripts/lib/orchestration/single-story-close/result.js +13 -0
  31. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +1 -0
  32. package/.agents/scripts/lib/orchestration/story-handoff.js +22 -7
  33. package/.agents/workflows/audit-state-machines.md +213 -0
  34. package/.agents/workflows/helpers/deliver-reference.md +8 -1
  35. package/.agents/workflows/helpers/plan-reference.md +10 -2
  36. package/docs/CHANGELOG.md +10 -0
  37. package/package.json +1 -1
@@ -31,14 +31,27 @@ import {
31
31
  const MAX_PRIOR_REDS = 10;
32
32
 
33
33
  /**
34
- * Verdicts earning the one same-SHA rerun: proven environment faults no
35
- * commit can fix. `pre-existing` is excluded — a real defect on `main`.
34
+ * Verdicts earning the one same-SHA green: proven environment faults no
35
+ * commit can fix, or a fresh run an operator-approved governance label
36
+ * started. `pre-existing` is excluded — a real defect on `main`.
36
37
  *
37
- * @type {readonly ['capacity', 'unreproducible-tier']}
38
+ * @type {readonly ['capacity', 'unreproducible-tier', 'governance-label']}
38
39
  */
39
- export const RERUN_ALLOWANCE_VERDICTS = Object.freeze([
40
+ const RERUN_ALLOWANCE_VERDICTS = Object.freeze([
40
41
  'capacity',
41
42
  'unreproducible-tier',
43
+ 'governance-label',
44
+ ]);
45
+
46
+ /** The audited recovery verdict: allowance only, never an intake filing. */
47
+ export const GOVERNANCE_LABEL_VERDICT = 'governance-label';
48
+
49
+ /** REST check-run conclusions that mean the run failed. */
50
+ const FAILED_REST_CONCLUSIONS = new Set([
51
+ 'failure',
52
+ 'timed_out',
53
+ 'action_required',
54
+ 'startup_failure',
42
55
  ]);
43
56
 
44
57
  /**
@@ -141,15 +154,25 @@ function resolvePrHeadShaRest({ prRef, cwd, spawnFn }) {
141
154
  return typeof sha === 'string' && sha.length > 0 ? sha : null;
142
155
  }
143
156
 
144
- /** `[{ name, link }]` for the PR head's check runs, as `gh pr checks --json` gives it. */
157
+ /** `gh pr checks` rows in {@link readCheckLinks}'s shape; `null` when unread. */
158
+ function readGhCheckRows({ prRef, cwd, spawnFn }) {
159
+ const rows = readGhJson(
160
+ ['pr', 'checks', prRef, '--json', 'name,link,bucket,completedAt'],
161
+ { cwd, spawnFn, anyExit: true },
162
+ );
163
+ if (!Array.isArray(rows)) return null;
164
+ return rows.map((e) => ({
165
+ name: e?.name,
166
+ link: e?.link ?? null,
167
+ failed: e?.bucket === 'fail',
168
+ passed: e?.bucket === 'pass',
169
+ completedAt: e?.completedAt ?? null,
170
+ }));
171
+ }
172
+
173
+ /** `[{ name, link, failed, passed, completedAt }]` for the PR head's check runs. */
145
174
  function readCheckLinks({ prRef, cwd, spawnFn }) {
146
- if (!prSurfaceUsesRest()) {
147
- return readGhJson(['pr', 'checks', prRef, '--json', 'name,link'], {
148
- cwd,
149
- spawnFn,
150
- anyExit: true,
151
- });
152
- }
175
+ if (!prSurfaceUsesRest()) return readGhCheckRows({ prRef, cwd, spawnFn });
153
176
  const sha = resolvePrHeadShaRest({ prRef, cwd, spawnFn });
154
177
  if (!sha) return null;
155
178
  const runs = readGhJson(
@@ -159,23 +182,72 @@ function readCheckLinks({ prRef, cwd, spawnFn }) {
159
182
  return (runs?.check_runs ?? []).map((run) => ({
160
183
  name: run?.name,
161
184
  link: run?.details_url ?? run?.html_url ?? null,
185
+ failed: FAILED_REST_CONCLUSIONS.has(
186
+ String(run?.conclusion ?? '').toLowerCase(),
187
+ ),
188
+ passed: String(run?.conclusion ?? '').toLowerCase() === 'success',
189
+ completedAt: run?.completed_at ?? null,
162
190
  }));
163
191
  }
164
192
 
193
+ function runIdOfLink(link) {
194
+ const m = link ? /\/runs\/(\d+)/.exec(String(link)) : null;
195
+ return m ? m[1] : null;
196
+ }
197
+
198
+ /** The hinted run when given, else the most recently completed one. */
199
+ function pickEntry(rows, runId) {
200
+ if (runId != null) {
201
+ return rows.find((e) => runIdOfLink(e.link) === String(runId)) ?? null;
202
+ }
203
+ const byRecency = [...rows].sort((a, b) =>
204
+ String(b.completedAt ?? '').localeCompare(String(a.completedAt ?? '')),
205
+ );
206
+ return byRecency[0] ?? null;
207
+ }
208
+
165
209
  /**
166
210
  * The failing check's run id and URL (the intake filing needs the link).
167
- * Best-effort.
211
+ * Only a FAILED entry qualifies — a same-name green run from another
212
+ * workflow run on the head is never blamed; none → nulls. Best-effort.
168
213
  *
214
+ * @param {{ prRef: string, checkName: string, runId?: string|number|null, cwd: string, spawnFn?: Function }} opts
169
215
  * @returns {{ runId: string|null, url: string|null }}
170
216
  */
171
- function resolveFailingCheckRun({ prRef, checkName, cwd, spawnFn }) {
217
+ function resolveFailingCheckRun({
218
+ prRef,
219
+ checkName,
220
+ runId = null,
221
+ cwd,
222
+ spawnFn,
223
+ }) {
172
224
  const parsed = readCheckLinks({ prRef, cwd, spawnFn });
173
- const entry = Array.isArray(parsed)
174
- ? parsed.find((e) => e?.name === checkName)
175
- : null;
176
- const link = entry?.link ? String(entry.link) : null;
177
- const m = link ? /\/runs\/(\d+)/.exec(link) : null;
178
- return { runId: m ? m[1] : null, url: link };
225
+ const failed = Array.isArray(parsed)
226
+ ? parsed.filter((e) => e?.name === checkName).filter((e) => e.failed)
227
+ : [];
228
+ const entry = pickEntry(failed, runId);
229
+ const url = entry?.link ? String(entry.link) : null;
230
+ return {
231
+ runId: runIdOfLink(url) ?? (runId != null ? String(runId) : null),
232
+ url,
233
+ };
234
+ }
235
+
236
+ /**
237
+ * The latest green run of `checkName` on the PR head — the governance-label
238
+ * recovery's audit names it. Best-effort; nulls when none.
239
+ *
240
+ * @param {{ prRef: string, checkName: string, cwd: string, spawnFn?: Function }} opts
241
+ * @returns {{ runId: string|null, url: string|null }}
242
+ */
243
+ export function resolvePassingCheckRun({ prRef, checkName, cwd, spawnFn }) {
244
+ const parsed = readCheckLinks({ prRef, cwd, spawnFn });
245
+ const passed = Array.isArray(parsed)
246
+ ? parsed.filter((e) => e?.name === checkName && e.passed)
247
+ : [];
248
+ const entry = pickEntry(passed, null);
249
+ const url = entry?.link ? String(entry.link) : null;
250
+ return { runId: runIdOfLink(url), url };
179
251
  }
180
252
 
181
253
  /**
@@ -312,8 +384,9 @@ function renderDigestMarkdown(digest, failures) {
312
384
  * @param {number|string|null} [opts.storyId] The v2 delivery scope.
313
385
  * @param {number} opts.prNumber
314
386
  * @param {string|null} [opts.headSha] PR head SHA at the moment of the red.
315
- * @param {Array<{name:string, outcome:string, required?:boolean}>} opts.failures
387
+ * @param {Array<{name:string, outcome:string, required?:boolean, runId?:string|number}>} opts.failures
316
388
  * `required` is recorded per entry; anything but `false` is stored as `true`.
389
+ * A `runId` names the red run itself.
317
390
  * @param {string} opts.tempRoot
318
391
  * @param {string} opts.cwd
319
392
  * @param {string} opts.prRef
@@ -345,8 +418,17 @@ export function writeCiDigest({
345
418
  outcome: 'failure',
346
419
  required: true,
347
420
  };
421
+ // A failure carrying its own run id (the close path's red rollup runs)
422
+ // pins the lookup to that run.
423
+ const hintedRunId = runIdOf(primary);
348
424
  const checkRun =
349
- checkRunFn({ prRef, checkName: primary.name, cwd, spawnFn }) ?? {};
425
+ checkRunFn({
426
+ prRef,
427
+ checkName: primary.name,
428
+ runId: hintedRunId,
429
+ cwd,
430
+ spawnFn,
431
+ }) ?? {};
350
432
  const logTail = logTailFn({ runId: checkRun.runId, cwd, spawnFn });
351
433
  const previous = readCiDigest({ storyId, tempRoot, cwd });
352
434
  const digest = {
@@ -374,6 +456,16 @@ export function writeCiDigest({
374
456
  return { jsonPath: paths.jsonPath, mdPath: paths.mdPath };
375
457
  }
376
458
 
459
+ /** A failure entry's own red run id as a string, else `null`. */
460
+ function runIdOf(failure) {
461
+ return failure.runId != null ? String(failure.runId) : null;
462
+ }
463
+
464
+ /** `{ evidence }` when given, else nothing — an audit-free allowance stays as before. */
465
+ function evidenceField(evidence) {
466
+ return evidence ? { evidence } : {};
467
+ }
468
+
377
469
  /**
378
470
  * Stamp the one-rerun allowance, called by `file-ci-gap.js` after filing.
379
471
  * Keyed on the digest's own head SHA so it cannot apply to a later head.
@@ -384,8 +476,9 @@ export function writeCiDigest({
384
476
  * verdict: string,
385
477
  * tempRoot: string,
386
478
  * cwd: string,
479
+ * evidence?: object|null,
387
480
  * now?: () => Date,
388
- * }} opts
481
+ * }} opts `evidence` — the verdict's audit facts, stored on the allowance.
389
482
  * @returns {{ verdict: string, headSha: string, recordedAt: string } | null}
390
483
  */
391
484
  export function recordRerunAllowance({
@@ -393,6 +486,7 @@ export function recordRerunAllowance({
393
486
  verdict,
394
487
  tempRoot,
395
488
  cwd,
489
+ evidence = null,
396
490
  now = () => new Date(),
397
491
  }) {
398
492
  if (!RERUN_ALLOWANCE_VERDICTS.includes(verdict)) return null;
@@ -403,6 +497,7 @@ export function recordRerunAllowance({
403
497
  verdict,
404
498
  headSha: digest.headSha,
405
499
  recordedAt: now().toISOString(),
500
+ ...evidenceField(evidence),
406
501
  };
407
502
  try {
408
503
  writeFileAtomic(
@@ -550,6 +645,12 @@ export function formatRerunViolation({ digest, headSha, prNumber, reason }) {
550
645
  ' verdict also records the one-rerun allowance for this head SHA, so a',
551
646
  ' single rerun of the failed job is then admitted; `pre-existing` does',
552
647
  ' not, because it names a real defect a rerun cannot remove.',
648
+ '3. When the green came from a fresh run that an operator-approved',
649
+ ' governance label (e.g. `migration:destructive-ok`) started on this',
650
+ ' head, record the audited recovery instead — `node',
651
+ ' .agents/scripts/file-ci-gap.js --story <id> --verdict governance-label',
652
+ ' --label <name>` — then resume. It proves the label was added after',
653
+ ' the red, files no intake issue, and admits this one green.',
553
654
  ].join('\n');
554
655
  }
555
656
 
@@ -9,8 +9,11 @@ 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 { COVERAGE_OVER_BUDGET_EXIT_CODE } from '../coverage-capture.js';
14
17
  import {
15
18
  hashCommandConfig,
16
19
  recordPass,
@@ -112,13 +115,116 @@ export function carryLintCredit(ctx, priorHead) {
112
115
  }
113
116
  }
114
117
 
115
- /** `quality-preview-crap` (capture depositor only) and every baselines entry. */
118
+ /**
119
+ * Did the credited run defer coverage to CI at this HEAD?
120
+ *
121
+ * @param {{ head: string, state: { coverageDeferredHead?: string } }} ctx
122
+ * @returns {boolean}
123
+ */
124
+ function isCoverageDeferred(ctx) {
125
+ return Boolean(ctx.head) && ctx.state.coverageDeferredHead === ctx.head;
126
+ }
127
+
128
+ /**
129
+ * Did the capture depositor declare its slice over this host's budget?
130
+ *
131
+ * @param {{ depositor: string }} ctx @param {number} status
132
+ * @returns {boolean}
133
+ */
134
+ export function isOverBudgetCapture(ctx, status) {
135
+ return (
136
+ ctx.depositor === 'coverage-capture' &&
137
+ status === COVERAGE_OVER_BUDGET_EXIT_CODE
138
+ );
139
+ }
140
+
141
+ /**
142
+ * An over-budget capture's step result: deferred to CI (no credit, the
143
+ * coverage-reading gates skipped) or `blocked`, by `coverage.onOverBudget`.
144
+ *
145
+ * @param {object} ctx @param {string} name @param {object} extra
146
+ * @returns {object}
147
+ */
148
+ export function settleOverBudget(ctx, name, extra) {
149
+ const exit = `exit ${COVERAGE_OVER_BUDGET_EXIT_CODE}`;
150
+ if (overBudgetPolicy(ctx.config) === 'defer-to-ci') {
151
+ ctx.state.coverageDeferredHead = ctx.head;
152
+ return {
153
+ name,
154
+ outcome: 'deferred',
155
+ detail: `coverage deferred to CI (${exit}, onOverBudget: defer-to-ci) — no suite ran and no credit was deposited`,
156
+ ...extra,
157
+ };
158
+ }
159
+ return {
160
+ name,
161
+ outcome: 'failed',
162
+ detail: `capture over budget (${exit}) under onOverBudget: block`,
163
+ reason: OVER_BUDGET_BLOCK_HINT,
164
+ stop: 'blocked',
165
+ ...extra,
166
+ };
167
+ }
168
+
169
+ /** The envelope's `coverage` field, present only after a deferral. */
170
+ export function coverageEnvelope(ctx) {
171
+ if (!isCoverageDeferred(ctx)) return {};
172
+ return {
173
+ coverage: {
174
+ status: 'deferred',
175
+ reason: 'over-budget',
176
+ policy: 'defer-to-ci',
177
+ },
178
+ };
179
+ }
180
+
181
+ /**
182
+ * A real credit ends a deferral; the seat it skipped CRAP on is re-opened,
183
+ * so the captured HEAD still seats its CRAP rows.
184
+ *
185
+ * @param {{ coverageDeferredHead?: string, seatHead?: string }} state
186
+ */
187
+ export function clearCoverageDeferral(state) {
188
+ if (state.coverageDeferredHead === undefined) return;
189
+ delete state.coverageDeferredHead;
190
+ delete state.seatHead;
191
+ }
192
+
193
+ /** A seat commit keeps a deferral its parent HEAD held. */
194
+ export function carryCoverageDeferral(state, priorHead, head) {
195
+ if (state.coverageDeferredHead === priorHead) {
196
+ state.coverageDeferredHead = head;
197
+ }
198
+ }
199
+
200
+ /** Post-capture re-scores until the run is credited or deferred at HEAD. */
201
+ export function postCaptureSettled(ctx) {
202
+ return ctx.state.creditHead === ctx.head || isCoverageDeferred(ctx);
203
+ }
204
+
205
+ /** CRAP seating needs a fresh artifact, which a deferral never writes. */
206
+ export function seatableKinds(ctx, kinds) {
207
+ const deferred = isCoverageDeferred(ctx);
208
+ return kinds.filter((kind) => kind !== 'crap' || !deferred);
209
+ }
210
+
211
+ /**
212
+ * `quality-preview-crap` (capture depositor only) and every baselines entry;
213
+ * after a deferral, none that reads the coverage artifact.
214
+ */
116
215
  function postCaptureGates(ctx) {
117
216
  const names = new Set(Object.values(BASELINES_GATE_NAMES));
118
217
  if (ctx.depositor === 'coverage-capture') {
119
218
  names.add(QUALITY_PREVIEW_GATE_NAMES.crap);
120
219
  }
121
- return closeGates(ctx).filter((g) => names.has(g.name) && !g.skip);
220
+ const keep = postCaptureFilter(names, isCoverageDeferred(ctx));
221
+ return closeGates(ctx).filter(keep);
222
+ }
223
+
224
+ /** A registered, unskipped post-capture gate, minus artifact readers after a deferral. */
225
+ function postCaptureFilter(names, deferred) {
226
+ return (g) =>
227
+ names.has(g.name) && !g.skip && !(deferred && g.readsCoverageArtifact);
122
228
  }
123
229
 
124
230
  /** The gate name, plus the kinds a baselines entry scores. */
@@ -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,
@@ -134,6 +134,7 @@ export async function runCloseValidationPhase({
134
134
  lockWait,
135
135
  suiteTimings: sourcedTimings(timings, 'close'),
136
136
  pending: false,
137
+ coverageDeferred: (validation.deferred ?? []).length > 0,
137
138
  };
138
139
  }
139
140
 
@@ -248,5 +249,7 @@ function gateOutcomes(gateList, validation) {
248
249
  for (const gate of gateList) outcomes[gate.name] = 'passed';
249
250
  for (const { gate } of validation.skipped ?? [])
250
251
  outcomes[gate.name] = 'skipped';
252
+ for (const { gate } of validation.deferred ?? [])
253
+ outcomes[gate.name] = 'deferred';
251
254
  return outcomes;
252
255
  }
@@ -812,14 +812,20 @@ async function resolveAdvisoryUnlanded(ctx, probe, elapsedSeconds) {
812
812
  };
813
813
  }
814
814
 
815
- /** `{ name, outcome }` of a red rollup run, as the CI digest records it. */
815
+ /** `{ name, outcome, runId? }` of a red rollup run, as the CI digest records it. */
816
816
  function failureOfRun(run) {
817
817
  return {
818
818
  name: run?.name ?? 'unknown',
819
819
  outcome: String(run?.conclusion ?? 'failure').toLowerCase(),
820
+ ...runIdField(run),
820
821
  };
821
822
  }
822
823
 
824
+ /** `{ runId }` when the rollup run carries one, else nothing. */
825
+ function runIdField(run) {
826
+ return run?.runId ? { runId: run.runId } : {};
827
+ }
828
+
823
829
  /** `policy-impact=failure, …` — the checks a block names. */
824
830
  function describeFailures(failures) {
825
831
  return failures.map((f) => `${f.name}=${f.outcome}`).join(', ');
@@ -143,9 +143,24 @@ function synthesizeSubject({ description, storyId, commitMessages }) {
143
143
  * trailerBlock?: string[] }} args
144
144
  * @returns {string}
145
145
  */
146
- function buildPrBody({ storyId, breakingNotes, trailerBlock = [] }) {
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
+ function buildPrBody({
156
+ storyId,
157
+ breakingNotes,
158
+ trailerBlock = [],
159
+ coverageDeferred = false,
160
+ }) {
147
161
  const lines = [
148
162
  `Closes #${storyId}`,
163
+ ...deferralLines(coverageDeferred),
149
164
  '',
150
165
  '_Auto-opened by `/mandrel-deliver`._',
151
166
  ...trailerBlock,
@@ -175,7 +190,8 @@ function announceBreaking(breakingNotes, progress) {
175
190
  * @param {{ storyTitle: string, storyId: number|string, storyBody?: string,
176
191
  * storyBranch: string, baseBranch: string, cwd?: string,
177
192
  * gitSpawn?: typeof defaultGitSpawn, config?: object,
178
- * progress?: (tag: string, msg: string) => void }} args
193
+ * progress?: (tag: string, msg: string) => void,
194
+ * coverageDeferred?: boolean }} args
179
195
  * @returns {{ title: string, body: string, breaking: boolean, breakingNotes: string[] }}
180
196
  */
181
197
  export function buildPullRequestFields({
@@ -188,6 +204,7 @@ export function buildPullRequestFields({
188
204
  gitSpawn = defaultGitSpawn,
189
205
  config,
190
206
  progress = () => {},
207
+ coverageDeferred = false,
191
208
  }) {
192
209
  const read = { storyBranch, baseBranch, cwd, gitSpawn };
193
210
  const commitMessages = readBranchCommits(read);
@@ -205,6 +222,7 @@ export function buildPullRequestFields({
205
222
  storyId,
206
223
  breakingNotes,
207
224
  trailerBlock: liftTrailers({ commitMessages, config }),
225
+ coverageDeferred,
208
226
  }),
209
227
  breaking,
210
228
  breakingNotes,
@@ -7,9 +7,25 @@ import { resolveReviewHalt } from './review-halt.js';
7
7
 
8
8
  const progress = Logger.createProgress('single-story-close', { stderr: true });
9
9
 
10
+ /** What `ensurePullRequestWith` needs from the close context. */
11
+ function pullRequestArgs(ctx, deps) {
12
+ const { options, story, storyId, storyBranch, baseBranch, prePush } = ctx;
13
+ return {
14
+ cwd: options.cwd,
15
+ storyId,
16
+ storyTitle: story.title,
17
+ storyBody: story.body,
18
+ storyBranch,
19
+ baseBranch,
20
+ config: deps.config,
21
+ gh: deps.gh,
22
+ progress,
23
+ coverageDeferred: prePush.coverageDeferred,
24
+ };
25
+ }
26
+
10
27
  export async function openAndReviewPr(ctx, deps) {
11
- const { options, worktreePath, story, storyId, storyBranch, baseBranch } =
12
- ctx;
28
+ const { options, worktreePath, storyId, storyBranch, baseBranch } = ctx;
13
29
  const { cwd } = options;
14
30
  ctx.setPhase('push');
15
31
  // Push from the worktree so `pre-push` measures the tree being sent; the
@@ -22,17 +38,9 @@ export async function openAndReviewPr(ctx, deps) {
22
38
  progress,
23
39
  });
24
40
  ctx.setPhase('pull-request');
25
- const { url: prUrl, alreadyMerged } = await ensurePullRequestWith({
26
- cwd,
27
- storyId,
28
- storyTitle: story.title,
29
- storyBody: story.body,
30
- storyBranch,
31
- baseBranch,
32
- config: deps.config,
33
- gh: deps.gh,
34
- progress,
35
- });
41
+ const { url: prUrl, alreadyMerged } = await ensurePullRequestWith(
42
+ pullRequestArgs(ctx, deps),
43
+ );
36
44
  const prNumber = parsePrNumber(prUrl);
37
45
  ctx.recordPrNumber(prNumber);
38
46
  // Already merged (landed between invocations): skip review and arm; confirm observes it.
@@ -110,5 +110,6 @@ export async function runPrePushPhases(ctx, deps) {
110
110
  lockWait: validation?.lockWait ?? null,
111
111
  suiteTimings: validation?.suiteTimings ?? null,
112
112
  pending: validation?.pending === true,
113
+ coverageDeferred: validation?.coverageDeferred === true,
113
114
  };
114
115
  }
@@ -78,6 +78,7 @@ function emptyDiffError({ storyBranch, baseRef, storyId }) {
78
78
  * gh?: ReturnType<typeof import('../../../gh-exec.js').createGh>,
79
79
  * computeChangeSetFn?: typeof defaultComputeChangeSet,
80
80
  * progress?: (tag: string, msg: string) => void,
81
+ * coverageDeferred?: boolean,
81
82
  * }} args
82
83
  * @returns {Promise<{ url: string, alreadyMerged: boolean, created: boolean }>}
83
84
  */
@@ -92,6 +93,7 @@ export async function ensurePullRequestWith({
92
93
  gh = defaultGh,
93
94
  computeChangeSetFn = defaultComputeChangeSet,
94
95
  progress = () => {},
96
+ coverageDeferred = false,
95
97
  }) {
96
98
  // `gh-exec` spawns `gh` in the process cwd, not `_cwd`.
97
99
  try {
@@ -139,6 +141,7 @@ export async function ensurePullRequestWith({
139
141
  cwd: _cwd ?? process.cwd(),
140
142
  config,
141
143
  progress,
144
+ coverageDeferred,
142
145
  });
143
146
  try {
144
147
  const createResult = await gh.pr.create([