mandrel 2.98.0 → 2.101.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 (46) hide show
  1. package/.agents/agents/story-worker.md +7 -1
  2. package/.agents/audit-checklists/quality.md +1 -0
  3. package/.agents/docs/agentrc-reference.json +3 -0
  4. package/.agents/docs/configuration.md +3 -0
  5. package/.agents/rules/api-conventions.md +4 -0
  6. package/.agents/rules/ci-remediation.md +8 -0
  7. package/.agents/rules/testing-standards.md +19 -1
  8. package/.agents/schemas/agentrc.schema.json +26 -0
  9. package/.agents/schemas/story-deliver-terminal.schema.json +17 -3
  10. package/.agents/schemas/validation-evidence.schema.json +10 -0
  11. package/.agents/scripts/lib/close-lock-events.js +18 -5
  12. package/.agents/scripts/lib/close-validation/gates.js +6 -1
  13. package/.agents/scripts/lib/close-validation/runner.js +10 -11
  14. package/.agents/scripts/lib/close-validation/test-delta.js +124 -0
  15. package/.agents/scripts/lib/config/pull-request.js +25 -0
  16. package/.agents/scripts/lib/config-settings-schema-delivery.js +22 -0
  17. package/.agents/scripts/lib/config-settings-schema.js +5 -0
  18. package/.agents/scripts/lib/coverage-capture-delta.js +2 -1
  19. package/.agents/scripts/lib/generated/agentrc-validator.js +2 -2
  20. package/.agents/scripts/lib/git/sync-from-base.js +4 -2
  21. package/.agents/scripts/lib/orchestration/ci-red-handling.js +4 -3
  22. package/.agents/scripts/lib/orchestration/ci-rerun-guard.js +81 -25
  23. package/.agents/scripts/lib/orchestration/handoff-state.js +41 -0
  24. package/.agents/scripts/lib/orchestration/review-providers/code-review.js +97 -28
  25. package/.agents/scripts/lib/orchestration/single-story-close/phases/base-sync.js +7 -0
  26. package/.agents/scripts/lib/orchestration/single-story-close/phases/close-validation.js +22 -4
  27. package/.agents/scripts/lib/orchestration/single-story-close/phases/confirm-merge.js +104 -57
  28. package/.agents/scripts/lib/orchestration/single-story-close/phases/merge-wait-recovery.js +16 -16
  29. package/.agents/scripts/lib/orchestration/single-story-close/phases/normalize-pr-title.js +28 -13
  30. package/.agents/scripts/lib/orchestration/single-story-close/phases/open-pr.js +1 -0
  31. package/.agents/scripts/lib/orchestration/single-story-close/phases/pr-body-trailers.js +38 -0
  32. package/.agents/scripts/lib/orchestration/single-story-close/phases/pre-push.js +24 -16
  33. package/.agents/scripts/lib/orchestration/single-story-close/phases/pull-request.js +18 -7
  34. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +60 -34
  35. package/.agents/scripts/lib/orchestration/story-deliver-terminal.js +1 -1
  36. package/.agents/scripts/lib/orchestration/story-handoff.js +36 -9
  37. package/.agents/scripts/lib/test-run-credit.js +26 -0
  38. package/.agents/scripts/lib/test-tiers.js +14 -10
  39. package/.agents/scripts/lib/validation-evidence.js +6 -0
  40. package/.agents/scripts/run-tests.js +162 -92
  41. package/.agents/skills/core/code-review-and-quality/SKILL.md +1 -1
  42. package/.agents/workflows/audit-quality.md +7 -0
  43. package/.agents/workflows/helpers/code-review.md +10 -0
  44. package/.agents/workflows/helpers/deliver-reference.md +28 -1
  45. package/docs/CHANGELOG.md +33 -0
  46. package/package.json +1 -1
@@ -98,7 +98,11 @@ Conventional Commit subjects on `story-<storyId>` per
98
98
  chars, `(refs #<storyId>)`. Never bypass a hook (`--no-verify` /
99
99
  `--no-gpg-sign`); if one fails, fix the cause in a follow-up commit, never
100
100
  amend. Docs are digest-first: read the digest your caller passes and pull
101
- files on demand; a null digest path means no docs mandate.
101
+ files on demand; a null digest path means no docs mandate. When the
102
+ consumer declares `delivery.pullRequest.bodyTrailers`, record each required
103
+ declaration as a git trailer on a branch commit
104
+ (`git commit --trailer 'Key: value'`): close lifts the last one into the PR
105
+ body, and you never edit a PR.
102
106
 
103
107
  ## Acceptance self-eval (MUST)
104
108
 
@@ -130,6 +134,8 @@ review, then prints one envelope (what each step runs:
130
134
  `ready` → return. `fix-required` (exit 2) → fix the cause it names, commit,
131
135
  re-run it; the same cause surviving the same fix twice is your blocked path.
132
136
  `blocked` (exit 1) → it already flipped `agent::blocked`; exit non-zero.
137
+ A close after a base move re-runs only the affected tests when the
138
+ consumer declares `project.commands.testChanged`.
133
139
 
134
140
  If it outruns the host's sync Bash ceiling, dispatch it in the
135
141
  **background**: its completion re-invokes you. Never spawn a task to poll or
@@ -23,4 +23,5 @@ Self-check your change against this lens's concerns before you ship:
23
23
  - [ ] An optional field nothing populates
24
24
  - [ ] Property-Based Coverage — Invariants Tested Only by Examples.
25
25
  - [ ] Toolchain by ecosystem, never one library.
26
+ - [ ] Vacuous property tests.
26
27
  - [ ] Name the property.
@@ -249,6 +249,9 @@
249
249
  "advisoryAllowlist": [],
250
250
  "rerunAdvisory": 0
251
251
  },
252
+ "pullRequest": {
253
+ "bodyTrailers": []
254
+ },
252
255
  "routing": {
253
256
  "roleScopedAgents": true,
254
257
  "ceremonyProfile": "standard",
@@ -86,6 +86,7 @@ Project identity, filesystem roots, planner docs context, and the commands the c
86
86
  | `docsContextFiles` | No | `array<string>` | `["architecture.md","data-dictionary.md","decisions.md","patterns.md"]` | Files under `paths.docsRoot` the planner treats as standing context. Read digest-first — the docs digest names the file and the line range, and only the named section is pulled. |
87
87
  | `commands` | No | `object` | — | Shell commands the close-validation chain spawns, each run from the repo root. One tri-state per key: absent uses the default shown; an explicit `null` disables an optional gate (`typecheck`, `lint`, `formatCheck`) — close reports it as skipped (`<gate>-disabled`) and runs nothing; a string is that command. Like every command here it must be a single argv (no `;`, `&&`, pipes or substitution), so wrap a multi-tool pair in one script and name that. |
88
88
  | `commands.test` | No | `string` | `"npm test"` | Full test-suite command close's `test` gate spawns, and the identity its `test` credit is hashed under — the deposit `run-tests.js` makes, close's credit probe and `verify[]` credit all key on it, as does `mandrel doctor`'s `test-credit-path` check. Set it for a non-npm project (e.g. `python3 scripts/validation.py`). Mandatory: `null` is rejected. |
89
+ | `commands.testChanged` | No | `string` \| `null` | — | Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files. Absent or `null` keeps the full re-run. |
89
90
  | `commands.typecheck` | No | `string` \| `null` | `"npm run typecheck"` | Static type-check command run as a close-validation gate. An explicit `null` disables the gate for projects with no type layer (skip reason `typecheck-disabled`). The empty string is rejected so a typo cannot silently disable it. |
90
91
  | `commands.lint` | No | `string` \| `null` | `"npm run lint"` | Lint command run as a close-validation gate and by the handoff preflight. An explicit `null` disables both (skip reason `lint-disabled`). Point it at the scoped command your hooks already run to stop paying for a third whole-repo lint at close — the gate still lints the diff, and CI still owns whole-repo drift. |
91
92
  | `commands.formatCheck` | No | `string` \| `null` | `"npx biome format ."` | Non-mutating format verification run as a close-validation gate. An explicit `null` disables the gate (skip reason `format-disabled`). |
@@ -258,6 +259,8 @@ Everything `/mandrel-deliver` and `single-story-close` consume: worktree isolati
258
259
  | `ci.blockOnAdvisoryFailure` | No | `boolean` | `true` | Story #5096. When true (default), delivery refuses to arm — and disarms — GitHub native auto-merge while a non-required (advisory) check is genuinely red on the PR head and GitHub reports the PR mergeable anyway (mergeStateStatus=UNSTABLE). `--auto` waits on REQUIRED contexts only, so without this a red advisory quality gate merges unattended. Set false to restore the pre-#5096 behaviour verbatim. |
259
260
  | `ci.advisoryAllowlist` | No | `array<string>` | `[]` | Story #5096. Check-run names exempt from blockOnAdvisoryFailure — a red run whose name matches exactly never blocks arming. Matching is exact; an unnamed run can never match and always blocks. |
260
261
  | `ci.rerunAdvisory` | No | `integer` | `0` | Story #5266. How many times close may re-run a failed advisory workflow run before blocking on it, per close invocation. Default 0: close spends no CI minutes and issues no GitHub mutation on an advisory red unless asked. At n > 0 the failed run(s) are re-run within that allowance and the merge wait re-polls inside its existing budget, landing or blocking on the re-run verdict. Overridden per invocation by --rerun-advisory <n>. |
262
+ | `pullRequest` | No | `object` | — | Story #5875. What close writes into the pull request it opens, beyond the title and the `Closes #<id>` line. |
263
+ | `pullRequest.bodyTrailers` | No | `array<string>` | `[]` | Story #5875. Git-trailer keys close lifts from the Story branch commits into the PR body, for a consumer whose required check reads a body line (e.g. `Policy-impact`). For each key the last branch commit carrying `<Key>: <value>` as a trailer wins, and the line is appended after the auto-opened marker and before any `BREAKING CHANGE:` footer. A key no commit carries appends nothing and logs one info line. Workers record the value with `git commit --trailer`. Default [] leaves the body unchanged. |
261
264
  | `routing` | No | `object` | — | v2 delivery-spawn routing: role-scoped boot contexts and the ceremony profile. The v1 singleDelivery epic-route kill-switch was removed in Stage 6; the freshCriticSampleRate sampling floor was retired in Story #5313 and the derived-level ceremony routing in Story #5343. |
262
265
  | `routing.roleScopedAgents` | No | `boolean` | `true` | Epic #4478 (M7-B). Kill-switch for the role-scoped boot contexts. When true (default), a converted delivery spawn (`story-worker`, `acceptance-critic`) boots on its own `.claude/agents/<role>.md` system prompt instead of re-paying the full entry-doc (AGENTS.md or CLAUDE.md) @-import closure. When false, every converted spawn falls back to `subagent_type: general-purpose` — the instant, code-rollback-free per-consumer revert, and the universal escape for hosts that ignore `.claude/agents/`. The fallback is the full-closure agent that ran before M7-B, so flipping it off never drops a gate. |
263
266
  | `routing.ceremonyProfile` | No | `"minimal"` \| `"standard"` \| `"strict"` | `"standard"` | Acceptance-ceremony depth — who authors the Story acceptance verdict. minimal and standard (default) = the inline self-eval, whatever the diff touches; strict = a fresh-context maker-blind critic. Review depth is a separate decision and still derives `deep` for any sensitive path (review-depth.js). |
@@ -108,4 +108,8 @@ Before opening a PR that adds or edits an API surface:
108
108
  removal is unavoidable, use expand–contract: ship the replacement,
109
109
  migrate consumers, then delete the old surface in a later release.
110
110
  - [ ] Naming follows [§ Payload Formatting](#payload-formatting).
111
+ - [ ] Every public function or endpoint states its caller obligations
112
+ (input preconditions, required call ordering, ownership) in its
113
+ JSDoc/TSDoc or schema, and the contract tier carries a negative test
114
+ for each obligation the surface rejects.
111
115
  - [ ] API documentation or types are committed alongside the implementation.
@@ -186,6 +186,14 @@ alongside the failing check-run identity. On green it adjudicates:
186
186
  digest) before the delivery proceeds.
187
187
  - **New head SHA** → fix at source. The digest is retired, auto-merge is
188
188
  re-armed, and the delivery continues unobstructed.
189
+ - **Same head SHA, every recorded failure advisory, each now green**
190
+ (`advisory-cleared`) → an advisory red disarmed the PR under
191
+ `delivery.ci.blockOnAdvisoryFailure` (the digest records each failure's
192
+ `required: false`), and the check has since gone green — a body fix or a
193
+ re-run, no new commit. The merge wait (a `--wait` resume included)
194
+ re-arms auto-merge once and lands. A required red, a still-red or unread
195
+ advisory check, or a digest without the `required` flag keeps the
196
+ verdicts above; `delivery.ci.autoMerge: 'strict'` never re-arms.
189
197
 
190
198
  A delivery that never went red has no digest and is untouched.
191
199
 
@@ -33,6 +33,18 @@ never read a skipped test as coverage for its tier.
33
33
  `.spec.` suffix.
34
34
  - **Coverage.** Unit tests are where line and branch coverage targets are
35
35
  met. Mutation testing, when configured, runs at this tier.
36
+ - **Property tests.** A unit whose correctness rests on an invariant — a
37
+ round-trip (`decode(encode(x)) === x`), idempotency, an ordering, a state
38
+ machine, or a documented "always"/"never" claim — states that invariant as a
39
+ property test with the stack's property-based library (`fast-check` for
40
+ JS/TS, `hypothesis` for Python, `proptest` for Rust). Keep a few example
41
+ tests beside it as readable witnesses; examples alone cannot reach the
42
+ inputs nobody thought to pick. Pin or print the seed so a red reproduces.
43
+ - **Failure witness.** A new property test counts only after it was seen to
44
+ fail against a deliberately broken implementation (a mutant: an off-by-one,
45
+ a dropped branch, a swapped comparison). Record the mutation in one
46
+ commit-body line beginning `Failure witness:`. A property no mutant can
47
+ fail constrains nothing.
36
48
 
37
49
  ### Contract — data crossing a boundary
38
50
 
@@ -146,7 +158,13 @@ first, then the minimum code that makes it pass, then refactoring with the
146
158
  suite green; skip it only for configuration, documentation, or static-content
147
159
  changes. For a bug fix the **Prove-It Pattern** binds — write the reproduction
148
160
  test and watch it fail *before* implementing the fix; a fix without a
149
- failing-then-passing reproduction is not done. Assert on outcomes rather than
161
+ failing-then-passing reproduction is not done. The fix also states its
162
+ **behaviour delta** — which inputs now behave differently, and how — in one
163
+ commit-body line beginning `Behaviour delta:` (wrap it under commitlint's
164
+ 100-character body-line limit). The regression test covers exactly that
165
+ delta: inputs inside it fail before the fix and pass after, and at least one
166
+ input just outside it is asserted unchanged. A fix that changes behaviour
167
+ beyond its stated delta reached green by being broader than the bug. Assert on outcomes rather than
150
168
  on which internal methods were called, prefer real implementations **> fakes >
151
169
  stubs > mocks** within [§ Mocking & Isolation](#mocking--isolation), and favour
152
170
  DAMP over DRY so each test reads as a self-contained story named after the
@@ -84,6 +84,15 @@
84
84
  "description": "Full test-suite command close's `test` gate spawns, and the identity its `test` credit is hashed under — the deposit `run-tests.js` makes, close's credit probe and `verify[]` credit all key on it, as does `mandrel doctor`'s `test-credit-path` check. Set it for a non-npm project (e.g. `python3 scripts/validation.py`). Mandatory: `null` is rejected.",
85
85
  "default": "npm test"
86
86
  },
87
+ "testChanged": {
88
+ "type": ["string", "null"],
89
+ "minLength": 1,
90
+ "not": {
91
+ "type": "string",
92
+ "pattern": "([;&|`]|\\$\\()"
93
+ },
94
+ "description": "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files. Absent or `null` keeps the full re-run."
95
+ },
87
96
  "typecheck": {
88
97
  "type": ["string", "null"],
89
98
  "minLength": 1,
@@ -1458,6 +1467,23 @@
1458
1467
  },
1459
1468
  "additionalProperties": false
1460
1469
  },
1470
+ "pullRequest": {
1471
+ "type": "object",
1472
+ "description": "Story #5875. What close writes into the pull request it opens, beyond the title and the `Closes #<id>` line.",
1473
+ "properties": {
1474
+ "bodyTrailers": {
1475
+ "type": "array",
1476
+ "items": {
1477
+ "type": "string",
1478
+ "pattern": "^[A-Za-z][A-Za-z0-9-]*$"
1479
+ },
1480
+ "uniqueItems": true,
1481
+ "description": "Story #5875. Git-trailer keys close lifts from the Story branch commits into the PR body, for a consumer whose required check reads a body line (e.g. `Policy-impact`). For each key the last branch commit carrying `<Key>: <value>` as a trailer wins, and the line is appended after the auto-opened marker and before any `BREAKING CHANGE:` footer. A key no commit carries appends nothing and logs one info line. Workers record the value with `git commit --trailer`. Default [] leaves the body unchanged.",
1482
+ "default": []
1483
+ }
1484
+ },
1485
+ "additionalProperties": false
1486
+ },
1461
1487
  "routing": {
1462
1488
  "type": "object",
1463
1489
  "description": "v2 delivery-spawn routing: role-scoped boot contexts and the ceremony profile. The v1 singleDelivery epic-route kill-switch was removed in Stage 6; the freshCriticSampleRate sampling floor was retired in Story #5313 and the derived-level ceremony routing in Story #5343.",
@@ -227,12 +227,26 @@
227
227
  },
228
228
  "suiteTimings": {
229
229
  "type": ["object", "null"],
230
- "description": "Story #5485 — the close's one full-suite run split into three separate figures: lockWaitMs (queued on the host full-suite lock), hostWaitMs (spawn until the suite signalled MANDREL_SUITE_READY_FILE; null when it did not use the handshake) and testRunMs (the test phase the coverage.timeoutMs kill bound applies to). null when no full suite ran in this close.",
231
- "required": ["lockWaitMs", "hostWaitMs", "testRunMs"],
230
+ "description": "Story #5485 — the last full-suite run split into three separate figures: lockWaitMs (queued on the host full-suite lock), hostWaitMs (spawn until the suite signalled MANDREL_SUITE_READY_FILE; null when it did not use the handshake) and testRunMs (the test phase the coverage.timeoutMs kill bound applies to). Story #5879 — source says which run: close (this close spawned the suite) or credited-run (close honoured the handoff's credited run, whose figures these are); spawns lists every suite spawn of that run in order. null when neither ran a full suite.",
231
+ "required": ["lockWaitMs", "hostWaitMs", "testRunMs", "source", "spawns"],
232
232
  "properties": {
233
233
  "lockWaitMs": { "type": "number", "minimum": 0 },
234
234
  "hostWaitMs": { "type": ["number", "null"], "minimum": 0 },
235
- "testRunMs": { "type": "number", "minimum": 0 }
235
+ "testRunMs": { "type": "number", "minimum": 0 },
236
+ "source": { "enum": ["close", "credited-run"] },
237
+ "spawns": {
238
+ "type": "array",
239
+ "items": {
240
+ "type": "object",
241
+ "required": ["lockWaitMs", "hostWaitMs", "testRunMs"],
242
+ "properties": {
243
+ "lockWaitMs": { "type": "number", "minimum": 0 },
244
+ "hostWaitMs": { "type": ["number", "null"], "minimum": 0 },
245
+ "testRunMs": { "type": "number", "minimum": 0 }
246
+ },
247
+ "additionalProperties": false
248
+ }
249
+ }
236
250
  },
237
251
  "additionalProperties": false
238
252
  },
@@ -72,6 +72,16 @@
72
72
  "type": ["string", "null"],
73
73
  "description": "Optional sha256 (or other stable digest) of the byte-identical inputs the gate consumed. When present, shouldSkip() will match on this even if the commit SHA has moved — letting docs-only or whitespace-only commits skip an unchanged gate."
74
74
  },
75
+ "scope": {
76
+ "type": "string",
77
+ "enum": ["full", "delta"],
78
+ "description": "Optional note on how the pass was earned. `delta` is close's `test` delta re-credit: after a base sync, only the tests affected by the commits since `since` ran (`project.commands.testChanged`), and the record credits the merged tree under the full-suite identity."
79
+ },
80
+ "since": {
81
+ "type": "string",
82
+ "pattern": "^[0-9a-f]{7,64}$",
83
+ "description": "With `scope: delta`, the credited commit the affected-tests run was keyed on."
84
+ },
75
85
  "timestamp": {
76
86
  "type": "string",
77
87
  "format": "date-time",
@@ -91,19 +91,32 @@ export function claimLockEventSink(env = process.env, { fsImpl = fs } = {}) {
91
91
  }
92
92
 
93
93
  /**
94
- * Waits sum, an expiry sticks, the last holder wins; timings are the last.
94
+ * Waits sum, an expiry sticks, the last holder wins; `spawns` keeps every
95
+ * suite's timings in order and `suiteTimings` is the last of them.
95
96
  *
96
97
  * @param {object[]} events
97
- * @returns {{ lockWait: object|null, suiteTimings: object|null }}
98
+ * @returns {{ lockWait: object|null, suiteTimings: object|null, spawns: object[] }}
98
99
  */
99
100
  export function summarizeLockEvents(events) {
100
101
  let lockWait = null;
101
- let suiteTimings = null;
102
+ const spawns = [];
102
103
  for (const event of events.filter((e) => e.kind !== 'lock-progress')) {
103
104
  if (event.kind === 'lock-wait') lockWait = mergeLockWait(lockWait, event);
104
- else suiteTimings = timingsOf(event);
105
+ else spawns.push(timingsOf(event));
105
106
  }
106
- return { lockWait, suiteTimings };
107
+ return { lockWait, suiteTimings: spawns.at(-1) ?? null, spawns };
108
+ }
109
+
110
+ /**
111
+ * The envelope's `suiteTimings`: the last spawn tagged with the run it came
112
+ * from, beside every spawn; `null` when the run spawned none.
113
+ *
114
+ * @param {{ suiteTimings: object|null, spawns: object[] }} summary
115
+ * @param {'close'|'credited-run'} source
116
+ * @returns {object|null}
117
+ */
118
+ export function sourcedTimings({ suiteTimings, spawns }, source) {
119
+ return suiteTimings && { ...suiteTimings, source, spawns };
107
120
  }
108
121
 
109
122
  function mergeLockWait(tally, event) {
@@ -35,6 +35,9 @@ import {
35
35
  * @property {{ reason: string }} [skip] - Pre-decided skip: recorded, never spawned.
36
36
  * @property {Record<string, string>} [env] - Overlay merged over `process.env` for this gate's child only.
37
37
  * @property {boolean} [lockEventChannel] - The child reports on close's lock-event channel.
38
+ * @property {{ cmd: string, args: string[] }} [evidenceIdentity] - Evidence argv, if not the spawned one.
39
+ * @property {{ scope: 'delta', since: string }} [evidenceNote]
40
+ * @property {string} [label]
38
41
  * @property {(cmd: string, args: string[], opts: { cwd: string, gateName?: string, log?: (m: string) => void, signal?: AbortSignal, env?: Record<string, string> }) => Promise<{ status: number }> | { status: number }} [run]
39
42
  * - In-process runner used instead of spawning `cmd`/`args`.
40
43
  */
@@ -108,7 +111,9 @@ function isCoverageCaptureActive(config, scripts) {
108
111
  /**
109
112
  * The plain `test` gate, unless coverage-capture will run the suite — every
110
113
  * close must keep exactly one working test gate. Its argv is
111
- * `project.commands.test` (default `npm test`).
114
+ * `project.commands.test` (default `npm test`); after a base move close's
115
+ * phase may swap it for the delta re-credit (`test-delta.js`), which runs
116
+ * `testChanged` keyed on `MANDREL_CHANGED_SINCE`.
112
117
  *
113
118
  * @param {boolean} coverageCaptureRunsSuite
114
119
  * @param {object|undefined|null} config - Canonical resolved config.
@@ -210,6 +210,7 @@ export async function runCloseValidation({
210
210
  exitCode: 0,
211
211
  durationMs,
212
212
  inputFingerprint: gate.inputFingerprint ?? treeSha,
213
+ ...gate.evidenceNote,
213
214
  },
214
215
  evidenceStoreOpts,
215
216
  );
@@ -227,7 +228,7 @@ export async function runCloseValidation({
227
228
  */
228
229
  const dispatchGate = async (gate, signal, configHash) => {
229
230
  log(
230
- `[close-validation] ▶ ${gate.name}${worktreePath ? ` (cwd=${worktreePath})` : ''}`,
231
+ `[close-validation] ▶ ${gate.label ?? gate.name}${worktreePath ? ` (cwd=${worktreePath})` : ''}`,
231
232
  );
232
233
  if (typeof onGateStart === 'function') onGateStart(gate);
233
234
  const dispatcher = typeof gate.run === 'function' ? gate.run : runner;
@@ -284,11 +285,7 @@ export async function runCloseValidation({
284
285
  });
285
286
  return;
286
287
  }
287
- const configHash = hashCommandConfig({
288
- cmd: execution.cmd,
289
- args: execution.args,
290
- cwd: spawnCwd,
291
- });
288
+ const configHash = gateConfigHash(gate, execution, spawnCwd);
292
289
  const verdict = evidenceVerdict(gate, configHash);
293
290
  if (verdict.skip) {
294
291
  skipped.push({ gate, reason: verdict.reason });
@@ -359,6 +356,12 @@ export async function runCloseValidation({
359
356
  return { ok: failed.length === 0, failed, skipped };
360
357
  }
361
358
 
359
+ /** The gate's `evidenceIdentity` argv hash, else its spawned argv's. */
360
+ function gateConfigHash(gate, execution, cwd) {
361
+ const { cmd, args } = gate.evidenceIdentity ?? execution;
362
+ return hashCommandConfig({ cmd, args, cwd });
363
+ }
364
+
362
365
  /**
363
366
  * The `fullSuiteLock` gate shares coverage capture's timeout
364
367
  * (`coverage.timeoutMs`) so a hung suite fails instead of holding the host
@@ -453,11 +456,7 @@ async function runSerialGates(
453
456
  });
454
457
  continue;
455
458
  }
456
- const configHash = hashCommandConfig({
457
- cmd: execution.cmd,
458
- args: execution.args,
459
- cwd: spawnCwd,
460
- });
459
+ const configHash = gateConfigHash(gate, execution, spawnCwd);
461
460
  const verdict = evidenceVerdict(gate, configHash);
462
461
  if (verdict.skip) {
463
462
  skipped.push({ gate, reason: verdict.reason });
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Close's `test` delta re-credit: after base-sync merged incoming paths, plan
3
+ * a `testChanged` run keyed on the pre-sync head instead of the full suite.
4
+ * The incoming-path rules are coverage-capture's own delta rules.
5
+ */
6
+
7
+ import { getChangedFiles } from '../changed-files.js';
8
+ import { deltaIneligibility } from '../coverage-capture-delta.js';
9
+ import { hasTestCreditAt } from '../test-run-credit.js';
10
+ import { resolveTestGateArgv } from './commands.js';
11
+
12
+ /**
13
+ * `project.commands.testChanged`: absent or `null` is disabled with no argv —
14
+ * it has no default. The schema guards it like every other command.
15
+ *
16
+ * @param {object|null|undefined} config
17
+ */
18
+ function resolveTestChangedCommand(config) {
19
+ const raw = config?.project?.commands?.testChanged?.trim() || null;
20
+ const [cmd, ...args] = raw ? raw.split(/\s+/) : [];
21
+ return { cmd, args, raw, disabled: raw === null };
22
+ }
23
+
24
+ const CHANGED_SINCE_TOKEN = '$MANDREL_CHANGED_SINCE';
25
+
26
+ /** `testChanged` keyed on `since`, credited as the full suite; no shell runs it, so the token is substituted here. */
27
+ function buildTestDeltaGate({ config, testChanged, since, incoming }) {
28
+ const label = `test (delta since ${since.slice(0, 12)}, ${incoming} incoming path(s))`;
29
+ return {
30
+ name: 'test',
31
+ label,
32
+ cmd: testChanged.cmd,
33
+ args: testChanged.args.map((a) => (a === CHANGED_SINCE_TOKEN ? since : a)),
34
+ env: { MANDREL_CHANGED_SINCE: since },
35
+ fullSuiteLock: true,
36
+ evidenceIdentity: resolveTestGateArgv(config),
37
+ evidenceNote: { scope: 'delta', since },
38
+ hint: `The delta re-credit failed — \`${testChanged.raw}\` (\`project.commands.testChanged\`, scope: delta, the tests affected since ${since.slice(0, 12)}) exited non-zero after the base sync. Fix the failing tests, commit, and re-run close.`,
39
+ };
40
+ }
41
+
42
+ /** Why the delta cannot replace the full run, or `null`; probes run lazily, cheapest first. */
43
+ function testDeltaIneligibility({
44
+ testChanged,
45
+ captureRuns,
46
+ credited,
47
+ incoming,
48
+ storyFiles,
49
+ }) {
50
+ if (testChanged.disabled) return 'no `project.commands.testChanged`';
51
+ if (captureRuns) return 'coverage-capture runs the suite';
52
+ if (!credited()) return 'no `test` credit for the pre-sync head';
53
+ const files = storyFiles();
54
+ if (!files) return 'Story change set unreadable';
55
+ return deltaIneligibility({ delta: incoming, storyFiles: files });
56
+ }
57
+
58
+ /** The Story's own change set against the synced base, or `null`. */
59
+ function readStoryFiles({ cwd, baseBranch, getChangedFilesImpl }) {
60
+ if (!cwd || !baseBranch) return null;
61
+ try {
62
+ const files = getChangedFilesImpl({ ref: `origin/${baseBranch}`, cwd });
63
+ return Array.isArray(files) ? files : null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Swap the plain `test` gate for the delta re-credit when every rule holds;
71
+ * otherwise return `gates` unchanged, logging the failed rule (no base move
72
+ * logs nothing). No plain `test` gate means coverage-capture runs the suite.
73
+ *
74
+ * @param {import('./gates.js').Gate[]} gates
75
+ * @returns {import('./gates.js').Gate[]}
76
+ */
77
+ export function applyTestDelta(
78
+ gates,
79
+ {
80
+ baseSync,
81
+ config,
82
+ storyId,
83
+ cwd,
84
+ evidenceCwd,
85
+ baseBranch,
86
+ shouldSkipImpl,
87
+ getChangedFilesImpl = getChangedFiles,
88
+ log,
89
+ },
90
+ ) {
91
+ const incoming = baseSync?.changedPaths ?? [];
92
+ if (incoming.length === 0) return gates;
93
+ const since = baseSync.creditedCommit;
94
+ const testChanged = resolveTestChangedCommand(config);
95
+ const index = gates.findIndex((g) => g.name === 'test');
96
+ const reason = testDeltaIneligibility({
97
+ testChanged,
98
+ captureRuns: index === -1,
99
+ credited: () =>
100
+ hasTestCreditAt({
101
+ config,
102
+ storyId,
103
+ cwd,
104
+ evidenceCwd,
105
+ sha: since,
106
+ ...(shouldSkipImpl ? { shouldSkipImpl } : {}),
107
+ }),
108
+ incoming,
109
+ storyFiles: () => readStoryFiles({ cwd, baseBranch, getChangedFilesImpl }),
110
+ });
111
+ if (reason) {
112
+ log?.(
113
+ `[close-validation] test delta re-credit not eligible (${reason}) — running the full suite`,
114
+ );
115
+ return gates;
116
+ }
117
+ const delta = buildTestDeltaGate({
118
+ config,
119
+ testChanged,
120
+ since,
121
+ incoming: incoming.length,
122
+ });
123
+ return gates.map((g, i) => (i === index ? delta : g));
124
+ }
@@ -0,0 +1,25 @@
1
+ /** `delivery.pullRequest`: trailer keys close lifts into the PR body. */
2
+
3
+ export const TRAILER_KEY_PATTERN = '^[A-Za-z][A-Za-z0-9-]*$';
4
+
5
+ export const PULL_REQUEST_DELIVERY_DEFAULTS = Object.freeze({
6
+ bodyTrailers: Object.freeze([]),
7
+ });
8
+
9
+ const TRAILER_KEY_RE = new RegExp(TRAILER_KEY_PATTERN);
10
+
11
+ /** Accepts the full config, `delivery`, or `pullRequest`; drops bad keys. */
12
+ export function getPullRequestDelivery(config) {
13
+ const block =
14
+ config?.delivery?.pullRequest ?? config?.pullRequest ?? config ?? {};
15
+ const keys = Array.isArray(block.bodyTrailers) ? block.bodyTrailers : [];
16
+ return {
17
+ bodyTrailers: [
18
+ ...new Set(
19
+ keys.filter(
20
+ (key) => typeof key === 'string' && TRAILER_KEY_RE.test(key),
21
+ ),
22
+ ),
23
+ ],
24
+ };
25
+ }
@@ -9,6 +9,10 @@ import {
9
9
  } from './config/agent-models.js';
10
10
  import { CI_DELIVERY_DEFAULTS } from './config/ci.js';
11
11
  import { DELIVERY_ROUTING_DEFAULTS } from './config/delivery-routing.js';
12
+ import {
13
+ PULL_REQUEST_DELIVERY_DEFAULTS,
14
+ TRAILER_KEY_PATTERN,
15
+ } from './config/pull-request.js';
12
16
  import { DEFAULT_CODE_REVIEW } from './config/runners.js';
13
17
  import { WORKTREE_ISOLATION_DEFAULTS } from './config/worktree-isolation.js';
14
18
  import { SHELL_INJECTION_PATTERN_STRING } from './config-schema-shared.js';
@@ -280,6 +284,23 @@ const CI_DELIVERY_SCHEMA = {
280
284
  additionalProperties: false,
281
285
  };
282
286
 
287
+ const PULL_REQUEST_DELIVERY_SCHEMA = {
288
+ type: 'object',
289
+ description:
290
+ 'Story #5875. What close writes into the pull request it opens, beyond the title and the `Closes #<id>` line.',
291
+ properties: {
292
+ bodyTrailers: {
293
+ type: 'array',
294
+ items: { type: 'string', pattern: TRAILER_KEY_PATTERN },
295
+ uniqueItems: true,
296
+ description:
297
+ 'Story #5875. Git-trailer keys close lifts from the Story branch commits into the PR body, for a consumer whose required check reads a body line (e.g. `Policy-impact`). For each key the last branch commit carrying `<Key>: <value>` as a trailer wins, and the line is appended after the auto-opened marker and before any `BREAKING CHANGE:` footer. A key no commit carries appends nothing and logs one info line. Workers record the value with `git commit --trailer`. Default [] leaves the body unchanged.',
298
+ default: [...PULL_REQUEST_DELIVERY_DEFAULTS.bodyTrailers],
299
+ },
300
+ },
301
+ additionalProperties: false,
302
+ };
303
+
283
304
  const REFACTOR_STAGE_SCHEMA = {
284
305
  type: 'object',
285
306
  description:
@@ -412,6 +433,7 @@ export const DELIVERY_SCHEMA = {
412
433
  acceptanceEval: ACCEPTANCE_EVAL_SCHEMA,
413
434
  feedbackLoop: FEEDBACK_LOOP_SCHEMA,
414
435
  ci: CI_DELIVERY_SCHEMA,
436
+ pullRequest: PULL_REQUEST_DELIVERY_SCHEMA,
415
437
  routing: ROUTING_SCHEMA,
416
438
  },
417
439
  additionalProperties: false,
@@ -86,6 +86,11 @@ const COMMANDS_SCHEMA = {
86
86
  "Full test-suite command close's `test` gate spawns, and the identity its `test` credit is hashed under — the deposit `run-tests.js` makes, close's credit probe and `verify[]` credit all key on it, as does `mandrel doctor`'s `test-credit-path` check. Set it for a non-npm project (e.g. `python3 scripts/validation.py`). Mandatory: `null` is rejected.",
87
87
  default: COMMANDS_DEFAULTS.test,
88
88
  },
89
+ testChanged: {
90
+ ...NULLABLE_NONEMPTY_SAFE_STRING,
91
+ description:
92
+ "Optional changed-tests command for the delta re-credit: when close's base sync merged sibling landings into a branch whose pre-sync head holds `test` credit, close's `test` gate runs this instead of the full suite, with the credited commit in the `MANDREL_CHANGED_SINCE` environment variable and in place of a literal `$MANDREL_CHANGED_SINCE` argument (e.g. `pnpm vitest run --changed $MANDREL_CHANGED_SINCE`; no shell runs it), and a green run re-credits the merged tree. Ineligible when coverage-capture runs the suite, an incoming path is a coverage-config file or one of the Story's own files. Absent or `null` keeps the full re-run.",
93
+ },
89
94
  typecheck: {
90
95
  ...NULLABLE_NONEMPTY_SAFE_STRING,
91
96
  description:
@@ -118,7 +118,8 @@ function treeIneligibility({ cwd, commit, spawn }) {
118
118
  return null;
119
119
  }
120
120
 
121
- function deltaIneligibility({ delta, storyFiles }) {
121
+ /** Shared with close's `test` delta re-credit: the reason a delta is ineligible, or `null`. */
122
+ export function deltaIneligibility({ delta, storyFiles }) {
122
123
  if (delta.length === 0) return 'no committed delta since the stamp';
123
124
  const story = new Set(storyFiles);
124
125
  const shared = delta.find((f) => story.has(f));