mandrel 2.109.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 +44 -11
  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 +17 -0
  37. package/package.json +1 -1
@@ -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([
@@ -167,6 +167,18 @@ function baselinesEnvelopeGates(validationGates) {
167
167
  return out;
168
168
  }
169
169
 
170
+ /**
171
+ * A capture deferred to CI is the one capture outcome a reviewer must see.
172
+ *
173
+ * @param {Record<string, string>|null|undefined} validationGates
174
+ * @returns {Record<string, string>}
175
+ */
176
+ function deferredCaptureGate(validationGates) {
177
+ return validationGates?.['coverage-capture'] === 'deferred'
178
+ ? { 'coverage-capture': 'deferred' }
179
+ : {};
180
+ }
181
+
170
182
  /**
171
183
  * `overridden` > `degraded` > `passed`: an override records the human
172
184
  * decision on a failed review; `degraded` says a review surface produced no
@@ -197,6 +209,7 @@ export function closeEnvelopeGates(
197
209
  return {
198
210
  validation: options.skipValidation ? 'skipped' : 'passed',
199
211
  ...baselinesEnvelopeGates(validationGates),
212
+ ...deferredCaptureGate(validationGates),
200
213
  baseSync: options.skipSync ? 'skipped' : 'passed',
201
214
  codeReview: codeReviewGate(reviewOverride, reviewDegraded),
202
215
  };
@@ -363,6 +363,7 @@ function landedPrePush(ctx) {
363
363
  lockWait: null,
364
364
  suiteTimings: null,
365
365
  pending: false,
366
+ coverageDeferred: false,
366
367
  };
367
368
  return null;
368
369
  }
@@ -53,10 +53,17 @@ import { writeFileAtomic } from '../util/atomic-write.js';
53
53
  import { defaultSleep } from '../util/sleep.js';
54
54
  import { runStreamed } from './evidence-stream.js';
55
55
  import {
56
+ carryCoverageDeferral,
56
57
  carryLintCredit,
58
+ clearCoverageDeferral,
59
+ coverageEnvelope,
57
60
  creditedPreflight,
61
+ isOverBudgetCapture,
58
62
  lintCredit,
63
+ postCaptureSettled,
59
64
  scorePostCapture,
65
+ seatableKinds,
66
+ settleOverBudget,
60
67
  } from './handoff-gates.js';
61
68
  import { handoffStatePath } from './handoff-state.js';
62
69
  import { probeHeldReviewDiff } from './review-deposit.js';
@@ -138,7 +145,7 @@ const SEAT_SCRIPTS = Object.freeze({
138
145
  /**
139
146
  * A settled step. `stop` carries the envelope status that ends the run.
140
147
  *
141
- * @typedef {{ name: string, outcome: 'ran'|'skipped'|'failed'|'error'|'aborted',
148
+ * @typedef {{ name: string, outcome: 'ran'|'skipped'|'deferred'|'failed'|'error'|'aborted',
142
149
  * detail: string, evidencePath?: string|null, conflictFiles?: string[],
143
150
  * stop?: 'fix-required'|'blocked', reason?: string }} StepResult
144
151
  */
@@ -519,9 +526,7 @@ async function creditedRun(ctx, signal) {
519
526
  ...extra,
520
527
  };
521
528
  }
522
- if (run.status !== 0) {
523
- return fixRequired(name, describeSuiteFailure(run.status), extra);
524
- }
529
+ if (run.status !== 0) return settleSuiteExit(ctx, name, run.status, extra);
525
530
  const [ranSignal, freshSignal] = capture
526
531
  ? [SIGNALS.captureRan, SIGNALS.captureFresh]
527
532
  : [SIGNALS.testRan, SIGNALS.testFresh];
@@ -541,10 +546,18 @@ async function creditedRun(ctx, signal) {
541
546
  );
542
547
  }
543
548
 
549
+ /** A non-zero depositor exit: an over-budget capture by policy, else a fix. */
550
+ function settleSuiteExit(ctx, name, status, extra) {
551
+ return isOverBudgetCapture(ctx, status)
552
+ ? settleOverBudget(ctx, name, extra)
553
+ : fixRequired(name, describeSuiteFailure(status), extra);
554
+ }
555
+
544
556
  /** Credit and its run's figures move together, keyed by the credited head. */
545
557
  function recordCredit(ctx, creditTimings) {
546
558
  ctx.state.creditHead = creditTimings.head;
547
559
  ctx.state.creditTimings = creditTimings;
560
+ clearCoverageDeferral(ctx.state);
548
561
  }
549
562
 
550
563
  /**
@@ -589,6 +602,7 @@ async function commitSeatedRows(ctx, total, evidencePath) {
589
602
  const priorHead = ctx.head;
590
603
  const creditedPrior = ctx.state.creditHead === priorHead;
591
604
  ctx.head = headSha(ctx) ?? ctx.head;
605
+ carryCoverageDeferral(ctx.state, priorHead, ctx.head);
592
606
  ctx.state.seatHead = ctx.head;
593
607
  // Both capture-stamp digests leave `baselines/` out, so a baseline-JSON-only
594
608
  // commit keeps the credit it already holds.
@@ -624,7 +638,7 @@ async function stepSeat(ctx) {
624
638
  if (ctx.state.seatHead === ctx.head) {
625
639
  return skipped(name, `nothing to seat at ${ctx.head.slice(0, 12)}`);
626
640
  }
627
- const kinds = seatKinds(ctx.config);
641
+ const kinds = seatableKinds(ctx, seatKinds(ctx.config));
628
642
  let total = 0;
629
643
  let evidencePath = null;
630
644
  for (const kind of kinds) {
@@ -861,8 +875,8 @@ function stepReview(ctx) {
861
875
  */
862
876
  async function stepPostCapture(ctx) {
863
877
  const name = 'post-capture';
864
- const { postCaptureHead, creditHead } = ctx.state;
865
- if (postCaptureHead === ctx.head && creditHead === ctx.head) {
878
+ const { postCaptureHead } = ctx.state;
879
+ if (postCaptureHead === ctx.head && postCaptureSettled(ctx)) {
866
880
  return skipped(name, `already clean at ${ctx.head.slice(0, 12)}`);
867
881
  }
868
882
  const { gates, failed } = await scorePostCapture(ctx, (...a) =>
@@ -1161,6 +1175,7 @@ export async function runStoryHandoff({ storyId, cwd, config }, deps) {
1161
1175
  lockWait: credited?.lockWait ?? null,
1162
1176
  suiteTimings: credited?.suiteTimings ?? null,
1163
1177
  reviewMs: ctx.reviewMs,
1178
+ ...coverageEnvelope(ctx),
1164
1179
  ...(stop
1165
1180
  ? {
1166
1181
  failedStep: stop.name,
@@ -0,0 +1,213 @@
1
+ ---
2
+ description: >-
3
+ Audit implicit state machines — co-varying flags, status sidecar fields,
4
+ scattered transitions, state split across systems — and report only the
5
+ impossible or unhandled combinations the code can reach, each with a traced
6
+ write path and a sketch of the explicit form.
7
+ ---
8
+
9
+ # State Machine Audit
10
+
11
+ You are a Staff Engineer hunting the states nobody designed. Most code tracks
12
+ state in loose variables: a few booleans, a status string with fields that
13
+ only make sense in some statuses, a label on a ticket plus a file on disk.
14
+ Together those variables form a state machine that exists only by implication,
15
+ and it usually admits combinations its authors never meant to allow. This lens
16
+ names those machines, proves which bad combinations are reachable, and
17
+ sketches the explicit form — a discriminated union, a tagged object with one
18
+ guard, or a transition table — that would make them unrepresentable. A
19
+ machine's writers rarely sit in one file, so the lens is cumulative.
20
+
21
+ The shared lens machinery lives in
22
+ [`helpers/audit-lens-core.md`](helpers/audit-lens-core.md). Write the report to
23
+ `{{auditResultsDir}}/audit-state-machines-results.md`. Dimension values:
24
+ `Boolean Soup | Status Sidecar | Scattered Transitions | Unhandled State | Distributed State`.
25
+ Extra finding fields: **Variables:** (the co-varying set, `path:line` each),
26
+ **Reachable Path:** (the traced write sequence that produces the bad
27
+ combination) and **Explicit Form:** (a few lines naming the replacement
28
+ shape). The report adds two mandatory sections, **State Inventory** and
29
+ **Refactor Sketch** (see Report additions).
30
+
31
+ > **Prove reachability before you judge.** Every object with two fields is
32
+ > technically a state machine. A finding is a claim that a specific bad
33
+ > combination can happen, so it carries the write path that produces it; a
34
+ > combination you cannot trace is inventoried, never reported.
35
+
36
+ ## Boundaries
37
+
38
+ Four lenses border this one. Report a finding **here** only when the fix is
39
+ "change the shape of the state so the bad combination cannot be written";
40
+ defer the rest so the suite never double-reports:
41
+
42
+ - `audit-resilience` keeps whether a reconcile job's filter covers every state
43
+ a failure can leave. This lens reports the state shape that makes the
44
+ combination possible, and defers when the only gap is the reconciler's
45
+ filter.
46
+ - `audit-data-model` keeps database enums, `CHECK` constraints and DB-level
47
+ invariants. This lens reports application-level state, and a DB-backed
48
+ status only when the application writes combinations the schema permits.
49
+ - `audit-performance` keeps interleaving and concurrency races (TOCTOU, lost
50
+ updates). This lens reports combinations reachable on a single thread of
51
+ execution, with no interleaving required.
52
+ - `audit-clean-code` keeps complexity hotspots, naming and stale feature
53
+ flags. A long if-chain is reported here only when it misses a reachable
54
+ state.
55
+
56
+ ## Scope
57
+
58
+ Per the core's Scope interpretation:
59
+
60
+ ```text
61
+ {{changedFiles}}
62
+ ```
63
+
64
+ When the fence resolves to a file list, take the state variables those files
65
+ read or write as the candidates, but trace every writer and reader across the
66
+ **whole tree** — a machine's other writers usually sit outside the change set.
67
+ When the fence renders literally, run codebase-wide.
68
+
69
+ ## Execution strategy
70
+
71
+ Run this lens as one `subagent_type: auditor` dispatch per the core's
72
+ Execution strategy. It never fans out on its own judgment.
73
+
74
+ ## Step 0: Qualifying bar (mandatory)
75
+
76
+ A candidate is an implicit state machine only when **both** parts hold:
77
+
78
+ 1. **Shape: the variables move together.** Two or more variables change
79
+ together to encode one logical state: a set of booleans, a status value plus fields whose validity depends
80
+ on it, or one logical state held in two systems (labels, files on disk, git
81
+ refs, a database row plus a cache, a lease assignee).
82
+ 2. **Consequence: a bad combination is reachable.** At least one combination of those variables that the code
83
+ does not intend is reachable, or one reachable value is not handled by a
84
+ consumer — shown with a traced path: the entry point, then each write by
85
+ `path:line` in the order it executes, then the bad combination it leaves.
86
+
87
+ A candidate that clears part 1 but not part 2 is recorded in the State
88
+ Inventory with `reachable: no` and produces **no finding**. A combination that
89
+ only a test fixture or a hand-edited file can produce is not reachable.
90
+
91
+ ## Step 1: Find candidates (tool-first)
92
+
93
+ Run the greps, then group hits by the object or module that owns them — a
94
+ candidate is a group, not a line. Adapt the patterns to the project's
95
+ languages per the core's ecosystem-detection rule:
96
+
97
+ - Run the candidate greps:
98
+
99
+ ```bash
100
+ git grep -nE '\b(is|has|was|did|should)[A-Z][A-Za-z]*\s*[:=]\s*(true|false)\b'
101
+ git grep -nE "\b(status|state|phase|stage|mode|kind)\s*[:=]\s*['\"][A-Za-z_-]+['\"]"
102
+ git grep -nE '\.(status|state|phase|stage)\s*=[^=]'
103
+ git grep -nE 'switch\s*\(\s*[A-Za-z_.]*(status|state|phase|stage|kind)\s*\)'
104
+ ```
105
+
106
+ - For each status variable, count its writer sites; three or more writers with
107
+ no shared guard is a Scattered Transitions candidate.
108
+
109
+ ## Step 2: Judge each candidate
110
+
111
+ ### Boolean Soup
112
+
113
+ - **Flags that encode one enum:** booleans that together stand for one state
114
+ (`isLoading` / `isError` / `isDone`, `started` / `finished` / `cancelled`)
115
+ where some true/false product is meaningless yet writable — both
116
+ `isLoading` and `isError` true, or `finished` without `started`.
117
+
118
+ ### Status Sidecar
119
+
120
+ - **Fields valid only in some statuses:** a status field plus nullable fields
121
+ whose meaning depends on it — an `error` set while status is `ok`, a
122
+ `result` null while status is `done`, a `mergedAt` while status is `open`.
123
+ Report the write that leaves the sidecar stale when the status moves.
124
+
125
+ ### Scattered Transitions
126
+
127
+ - **Transitions with no single guard:** a state written from many sites, so
128
+ an illegal transition (`done` back to `executing`) or a re-entry that
129
+ repeats a side effect is reachable. Name every writer site and the one
130
+ that skips the check the others make.
131
+
132
+ ### Unhandled State
133
+
134
+ - **Consumers that miss a value:** a `switch`, if-chain or lookup table over a
135
+ status that omits a reachable value and has no exhaustiveness check, or
136
+ falls through to a silent default that treats the missing value as another.
137
+
138
+ ### Distributed State
139
+
140
+ - **One state, two stores:** one logical state spread across systems that can
141
+ disagree — two lifecycle labels at once, a lease held after its branch is
142
+ gone, a marker file that outlives the work it marks — with no reconciler,
143
+ or with a reconciler that cannot see the disagreeing combination (then
144
+ name the combination and defer the filter to `audit-resilience`).
145
+
146
+ ## Step 3: Evidence and severity
147
+
148
+ - **Second read of the write order.** Every finding's Reachable Path is
149
+ re-checked by a second read of the actual write order — the call sequence,
150
+ the early returns, the guards upstream — not of a comment, a type
151
+ annotation, or one file. A path an upstream guard actually blocks is
152
+ dropped and counted in the kept/dropped line.
153
+ - **Severity calibration.** Grade on the core scale with these anchors:
154
+ - `Critical` or `High` — the reachable state loses or corrupts data, repeats
155
+ an external side effect (a double charge, a double merge, a double post),
156
+ or wedges a lifecycle with no recovery path.
157
+ - `Medium` — a wrong user-visible result, or a stuck state that a retry or
158
+ an operator clears.
159
+ - `Low` — a reachable but cosmetic mismatch.
160
+
161
+ ## Report additions
162
+
163
+ Beyond the core's shared skeleton, this lens adds its title, the two mandatory
164
+ sections and the three finding fields. Write `_No findings._` under a section
165
+ rather than omitting it.
166
+
167
+ The **State Inventory** comes before any finding, one row per candidate that
168
+ cleared part 1 of the qualifying bar; every finding cites a row.
169
+
170
+ The **Refactor Sketch** covers the single most critical finding only: a
171
+ before/after sketch in the project's own language — a discriminated union in
172
+ TypeScript, a JSDoc `@typedef` union plus one guard function in JavaScript, a
173
+ tagged class or an `enum` plus an exhaustive `match` in other languages, or a transition table with one
174
+ `transition(state, event)` function every writer goes through. It names which
175
+ writer sites move behind the guard and which combination becomes
176
+ unrepresentable. It is a sketch inside the report: this lens edits no code,
177
+ per the core's read-only constraint, and the fix lands through
178
+ `/audit-to-stories`.
179
+
180
+ ```markdown
181
+ # State Machine Audit Report
182
+
183
+ ## Executive Summary
184
+
185
+ [Headline read.]
186
+
187
+ Self-cross-check: kept <k> / dropped <d>.
188
+ Severity tally: Critical <n> / High <n> / Medium <n> / Low <n>
189
+
190
+ ## State Inventory
191
+
192
+ | Candidate | Variables | Implicit states | Transitions (writers) | Impossible or unhandled combinations | Reachable |
193
+ | --- | --- | --- | --- | --- | --- |
194
+ | [name] | `path:line`, … | [states] | `path:line`, … | [combination] | [yes — finding title / no] |
195
+
196
+ ## Detailed Findings
197
+
198
+ ### `path/to/primary-file.ext` — [Short title of the issue]
199
+
200
+ - **Dimension:** [Boolean Soup | Status Sidecar | Scattered Transitions | Unhandled State | Distributed State]
201
+ - **Severity:** [Critical | High | Medium | Low | Info]
202
+ - **Variables:** [the co-varying set, `path:line` each]
203
+ - **Reachable Path:** [entry point → write at `path:line` → write at `path:line` → the bad combination]
204
+ - **Explicit Form:** [the replacement shape in a few lines]
205
+ - [Location, Current State, Recommendation & Rationale, Acceptance signal —
206
+ per the core skeleton]
207
+
208
+ ## Refactor Sketch
209
+
210
+ [The most critical finding's title. Before: the loose variables and their
211
+ writers. After: the explicit form and the one guard every writer calls. The
212
+ combination that becomes unrepresentable.]
213
+ ```
@@ -510,7 +510,14 @@ reports a one-line digest on success; a failed gate replays its tail inline.
510
510
  `AGENT_LOG_LEVEL=verbose` restores live streaming. A gate exiting `75` (its
511
511
  full-suite lock wait expired) logs a deferred line and the close settles
512
512
  `pending`; one exiting `124` (the suite outran its timeout) logs a timeout
513
- line naming host contention — neither is reported as failing tests.
513
+ line naming host contention — neither is reported as failing tests. A
514
+ coverage-capture exiting `76` (the consumer's capture script declared its
515
+ slice over this host's budget, so nothing ran) follows
516
+ `delivery.quality.gates.coverage.onOverBudget`: under `defer-to-ci` the gate
517
+ reports `deferred`, the coverage-reading gates report `skipped`
518
+ (`coverage-deferred-ci`), the handoff settles `ready` with a `coverage`
519
+ field, and the PR body says coverage was deferred to CI; under the default
520
+ `block` the handoff settles `blocked` and close fails, both naming the key.
514
521
 
515
522
  Every full-suite run ends on `⏲ suite timings: lockWaitMs=… hostWaitMs=…
516
523
  testRunMs=…`. The handoff envelope carries its credited run's figures as
@@ -578,12 +578,20 @@ for a source that was already `agent::ready`:
578
578
  2. One PATCH sets the new title and body (with the plan fingerprint, so a
579
579
  retried persist adopts the rewritten issue instead of duplicating it),
580
580
  adds the Story's labels and this run's `plan-run::` label, and removes
581
- every `agent::*` label and any earlier run's `plan-run::` label.
581
+ every `agent::*` label and any earlier run's `plan-run::` label. When the
582
+ original body's last non-blank line is a single HTML comment — a
583
+ consumer's machine-readable marker such as
584
+ `<!-- design-lab-ship branch=… sha=… -->` — that line is appended
585
+ verbatim after the fingerprint, so it stays the body's last line. It is
586
+ read from the preserved `plan-rewrite` original when one exists, so a
587
+ re-plan keeps exactly one copy; Mandrel's own fingerprint and
588
+ structured-comment markers are never carried.
582
589
  3. The `story-plan-state` comment, then the terminal `agent::ready` flip.
583
590
 
584
591
  The supersede phase lists the rewritten id under `supersede.rewritten` and
585
592
  neither comments on nor closes it; the result's `rewrite` field names the
586
- ticket or why there was none.
593
+ ticket or why there was none, and `rewrite.preservedMarker` says whether a
594
+ trailing marker was carried (a dry run reports the same answer).
587
595
 
588
596
  **Falls back to create-and-close** with no warning for any other shape
589
597
  (several sources, several Stories), under `--no-rewrite-source`, and under
package/docs/CHANGELOG.md CHANGED
@@ -15,6 +15,23 @@ All notable changes to this project will be documented in this file.
15
15
  -->
16
16
  <!-- markdownlint-disable-file MD004 MD012 MD037 -->
17
17
 
18
+ ## [2.111.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.110.0...mandrel-v2.111.0) (2026-11-06)
19
+
20
+
21
+ ### Added
22
+
23
+ * add /audit-state-machines: a read-only lens that finds implicit state machines and the impossible states they can reach ([#5952](https://github.com/dsj1984/mandrel/issues/5952)) ([#5953](https://github.com/dsj1984/mandrel/issues/5953)) ([8ef0489](https://github.com/dsj1984/mandrel/commit/8ef0489c4a464726439a4575bb25574baa79694d))
24
+ * CI digest blames the failed run, not a same-name green one; add an audited governance-label recovery verdict ([#5945](https://github.com/dsj1984/mandrel/issues/5945)) ([#5946](https://github.com/dsj1984/mandrel/issues/5946)) ([1839f9d](https://github.com/dsj1984/mandrel/commit/1839f9df7d6d9482f9ad038ce6c11ea102508cf6))
25
+ * coverage-capture: a consumer-declared over-budget slice defers to CI instead of timing out handoff and close ([#5949](https://github.com/dsj1984/mandrel/issues/5949)) ([#5951](https://github.com/dsj1984/mandrel/issues/5951)) ([7ee6b55](https://github.com/dsj1984/mandrel/commit/7ee6b556667e375d6272b91ffc94160f481dfcf8))
26
+ * plan-persist: keep a source ticket's trailing HTML-comment marker line when rewriting it in place ([#5948](https://github.com/dsj1984/mandrel/issues/5948)) ([#5950](https://github.com/dsj1984/mandrel/issues/5950)) ([1afdfa3](https://github.com/dsj1984/mandrel/commit/1afdfa324452c36a44477c50228051e046fc225d))
27
+
28
+ ## [2.110.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.109.0...mandrel-v2.110.0) (2026-11-05)
29
+
30
+
31
+ ### Fixed
32
+
33
+ * close lifts PR-body trailers from merge commits and takes the PR type from the Story branch's own commits ([#5942](https://github.com/dsj1984/mandrel/issues/5942)) ([#5943](https://github.com/dsj1984/mandrel/issues/5943)) ([adbc4f6](https://github.com/dsj1984/mandrel/commit/adbc4f6d608a43ba79beeeb2b217ee494a8b1ead))
34
+
18
35
  ## [2.109.0](https://github.com/dsj1984/mandrel/compare/mandrel-v2.108.0...mandrel-v2.109.0) (2026-10-30)
19
36
 
20
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mandrel",
3
- "version": "2.109.0",
3
+ "version": "2.111.0",
4
4
  "description": "Claude Code-first opinionated workflow framework: instructions, skills, rules, and SDLC workflows that govern AI coding assistants.",
5
5
  "files": [
6
6
  ".agents/",