mandrel 2.79.0 → 2.81.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 (55) hide show
  1. package/.agents/agents/auditor.md +8 -3
  2. package/.agents/audit-checklists/data-model.md +9 -1
  3. package/.agents/audit-checklists/security.md +15 -1
  4. package/.agents/docs/agentrc-reference.json +4 -0
  5. package/.agents/docs/configuration.md +4 -3
  6. package/.agents/docs/execution-reference.md +25 -5
  7. package/.agents/docs/workflows.md +2 -2
  8. package/.agents/schemas/agentrc.schema.json +31 -3
  9. package/.agents/schemas/audit-rules.json +15 -2
  10. package/.agents/scripts/deliver-run.js +43 -8
  11. package/.agents/scripts/lib/audit-to-stories/seed-from-findings.js +37 -2
  12. package/.agents/scripts/lib/baselines/duplication-scanner.js +7 -1
  13. package/.agents/scripts/lib/baselines/refresh-service.js +6 -0
  14. package/.agents/scripts/lib/cli-args.js +16 -2
  15. package/.agents/scripts/lib/config/explain.js +1 -1
  16. package/.agents/scripts/lib/config/gates/duplication.schema.js +10 -2
  17. package/.agents/scripts/lib/config-settings-schema.js +18 -1
  18. package/.agents/scripts/lib/findings/audit-finding-record.js +95 -0
  19. package/.agents/scripts/lib/findings/route-finding.js +4 -3
  20. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  21. package/.agents/scripts/lib/observability/close-telemetry.js +17 -2
  22. package/.agents/scripts/lib/orchestration/complexity-gate.js +58 -11
  23. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +182 -0
  24. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +11 -10
  25. package/.agents/scripts/lib/orchestration/plan-persist/collision-message.js +52 -0
  26. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +56 -9
  27. package/.agents/scripts/lib/orchestration/plan-persist/source-rewrite.js +177 -0
  28. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +202 -57
  29. package/.agents/scripts/lib/orchestration/plan-persist/supersede-ops.js +57 -15
  30. package/.agents/scripts/lib/orchestration/plan-persist/wave-collision-gate.js +8 -4
  31. package/.agents/scripts/lib/orchestration/plan-persist/wave-serialisation.js +3 -2
  32. package/.agents/scripts/lib/orchestration/resolve-stories.js +12 -3
  33. package/.agents/scripts/lib/orchestration/resume-effort.js +121 -0
  34. package/.agents/scripts/lib/orchestration/single-story-close/phases/options.js +13 -2
  35. package/.agents/scripts/lib/orchestration/single-story-close/runner.js +10 -2
  36. package/.agents/scripts/lib/orchestration/ticketing/reads.js +3 -0
  37. package/.agents/scripts/lib/qa/resolve-qa-contract.js +28 -9
  38. package/.agents/scripts/lib/templates/decomposer-prompts.js +2 -2
  39. package/.agents/scripts/lib/wave-runner/footprint.js +114 -17
  40. package/.agents/scripts/lib/wave-runner/ready-set.js +16 -5
  41. package/.agents/scripts/plan-persist.js +20 -6
  42. package/.agents/scripts/providers/github/tickets.js +2 -1
  43. package/.agents/scripts/resolve-stories.js +8 -2
  44. package/.agents/scripts/single-story-close.js +11 -3
  45. package/.agents/workflows/audit-data-model.md +94 -10
  46. package/.agents/workflows/audit-security.md +136 -49
  47. package/.agents/workflows/audit-to-stories.md +22 -7
  48. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  49. package/.agents/workflows/helpers/deliver-reference.md +7 -2
  50. package/.agents/workflows/helpers/deliver-story.md +5 -3
  51. package/.agents/workflows/helpers/plan-reference.md +53 -5
  52. package/.agents/workflows/mandrel-deliver.md +9 -4
  53. package/.agents/workflows/mandrel-plan.md +7 -1
  54. package/docs/CHANGELOG.md +25 -0
  55. package/package.json +2 -1
@@ -10,6 +10,7 @@ import crypto from 'node:crypto';
10
10
 
11
11
  import { parseWorkerModel, parseWorkerTokens } from '../cli-args.js';
12
12
  import { Logger } from '../Logger.js';
13
+ import { parseWorkerEffort } from '../orchestration/resume-effort.js';
13
14
  import { EVENT_KINDS } from '../signals/schema.js';
14
15
  import {
15
16
  emitRuntimeFriction,
@@ -246,7 +247,7 @@ async function readStoryTally({ storyId, config, readFn = forEachLine }) {
246
247
 
247
248
  /**
248
249
  * @param {{ storyId: number, config?: object, workerTokens?: number|null,
249
- * workerModel?: string|null, landed?: boolean,
250
+ * workerModel?: string|null, workerEffort?: string|null, landed?: boolean,
250
251
  * readFn?: typeof forEachLine }} args
251
252
  * @returns {Promise<object>}
252
253
  */
@@ -255,6 +256,7 @@ async function buildCloseTelemetry({
255
256
  config,
256
257
  workerTokens = null,
257
258
  workerModel = null,
259
+ workerEffort = null,
258
260
  landed = false,
259
261
  readFn,
260
262
  }) {
@@ -268,6 +270,7 @@ async function buildCloseTelemetry({
268
270
  },
269
271
  workerTokens: Number.isInteger(workerTokens) ? workerTokens : null,
270
272
  workerModel,
273
+ workerEffort,
271
274
  };
272
275
  }
273
276
 
@@ -309,13 +312,23 @@ export function resolveWorkerModel(raw) {
309
312
  return model;
310
313
  }
311
314
 
315
+ /**
316
+ * @param {unknown} raw
317
+ * @returns {string|null}
318
+ */
319
+ export function resolveWorkerEffort(raw) {
320
+ const { effort, warning } = parseWorkerEffort(raw);
321
+ if (warning) Logger.warn(`[single-story-close] ${warning}`);
322
+ return effort;
323
+ }
324
+
312
325
  /**
313
326
  * The retry goes first so the summary counts it; a failure leaves
314
327
  * `telemetry: null` and the close's status untouched.
315
328
  *
316
329
  * @param {{ terminal: object, result?: object|null, config?: object,
317
330
  * workerTokens?: number|null, workerModel?: string|null,
318
- * readFn?: typeof forEachLine }} args
331
+ * workerEffort?: string|null, readFn?: typeof forEachLine }} args
319
332
  * @returns {Promise<void>}
320
333
  */
321
334
  export async function recordCloseTelemetry({
@@ -324,6 +337,7 @@ export async function recordCloseTelemetry({
324
337
  config,
325
338
  workerTokens = null,
326
339
  workerModel = null,
340
+ workerEffort = null,
327
341
  readFn,
328
342
  }) {
329
343
  await emitCloseRetrySignal({ envelope: terminal, config });
@@ -334,6 +348,7 @@ export async function recordCloseTelemetry({
334
348
  config,
335
349
  workerTokens,
336
350
  workerModel,
351
+ workerEffort,
337
352
  landed: terminal?.status === 'landed',
338
353
  readFn,
339
354
  });
@@ -332,20 +332,54 @@ export function deriveStoryShape({
332
332
  * run would put several engines on one session and checkout. Only *where*
333
333
  * changes; close gates, PR and terminal envelope are identical.
334
334
  *
335
- * @param {{ storyCount?: unknown }} [args] Anything but exactly 1 dispatches
336
- * as a sub-agent.
335
+ * A resumed one-Story run spawns: only a spawn carries per-call effort.
336
+ *
337
+ * @param {{ storyCount?: unknown, priorBlocks?: unknown,
338
+ * roleScopedAgents?: unknown }} [args] Anything but exactly 1 Story
339
+ * dispatches as a sub-agent.
337
340
  * @returns {{ mode: 'inline'|'subagent', reasons: string[] }}
338
341
  */
339
- export function resolveStoryDispatchMode({ storyCount } = {}) {
340
- if (storyCount === 1) {
341
- return {
342
- mode: 'inline',
343
- reasons: [
344
- 'single-Story run — execute deliver-story inline; sub-agent isolation is load-bearing only for concurrent dispatch, and a one-Story run has no sibling to race (close gates, PR, and terminal envelope unchanged)',
345
- ],
346
- };
347
- }
342
+ export function resolveStoryDispatchMode({
343
+ storyCount,
344
+ priorBlocks,
345
+ roleScopedAgents,
346
+ } = {}) {
347
+ if (storyCount !== 1) return multiStoryDispatch();
348
+ return singleStoryDispatch(priorBlocks, roleScopedAgents);
349
+ }
350
+
351
+ /**
352
+ * @param {unknown} priorBlocks
353
+ * @param {unknown} roleScopedAgents
354
+ * @returns {{ mode: 'inline'|'subagent', reasons: string[] }}
355
+ */
356
+ function singleStoryDispatch(priorBlocks, roleScopedAgents) {
357
+ return isResumeDispatch(priorBlocks, roleScopedAgents)
358
+ ? resumeDispatch(Number(priorBlocks))
359
+ : inlineDispatch();
360
+ }
361
+
362
+ /**
363
+ * @param {unknown} priorBlocks
364
+ * @param {unknown} roleScopedAgents
365
+ * @returns {boolean}
366
+ */
367
+ function isResumeDispatch(priorBlocks, roleScopedAgents) {
368
+ return roleScopedAgents === true && Number(priorBlocks) >= 1;
369
+ }
348
370
 
371
+ /** @returns {{ mode: 'inline', reasons: string[] }} */
372
+ function inlineDispatch() {
373
+ return {
374
+ mode: 'inline',
375
+ reasons: [
376
+ 'single-Story run — execute deliver-story inline; sub-agent isolation is load-bearing only for concurrent dispatch, and a one-Story run has no sibling to race (close gates, PR, and terminal envelope unchanged)',
377
+ ],
378
+ };
379
+ }
380
+
381
+ /** @returns {{ mode: 'subagent', reasons: string[] }} */
382
+ function multiStoryDispatch() {
349
383
  return {
350
384
  mode: 'subagent',
351
385
  reasons: [
@@ -353,3 +387,16 @@ export function resolveStoryDispatchMode({ storyCount } = {}) {
353
387
  ],
354
388
  };
355
389
  }
390
+
391
+ /**
392
+ * @param {number} priorBlocks
393
+ * @returns {{ mode: 'subagent', reasons: string[] }}
394
+ */
395
+ function resumeDispatch(priorBlocks) {
396
+ return {
397
+ mode: 'subagent',
398
+ reasons: [
399
+ `single-Story resume after ${priorBlocks} prior block(s) — dispatch a story-worker sub-agent so the resume effort rides the Agent call's per-call effort instead of raising session effort (close gates, PR, and terminal envelope unchanged)`,
400
+ ],
401
+ };
402
+ }
@@ -0,0 +1,182 @@
1
+ /**
2
+ * Per-Story attribution of an audit seed's findings. An N>1 plan whose seed
3
+ * carries `audit-finding` records stamps each Story with the findings its
4
+ * `changes[]` cover — and the `audit::*` labels those findings explain —
5
+ * instead of smearing the seed union across every Story. Anything else keeps
6
+ * the union path (`audit-provenance.js`).
7
+ */
8
+
9
+ import picomatch from 'picomatch';
10
+
11
+ import { parseAuditFindingRecords } from '../../findings/audit-finding-record.js';
12
+ import { ownedProvenanceSource } from '../../findings/provenance-field.js';
13
+ import {
14
+ parseAuditLabelFooter,
15
+ parseFingerprintFooter,
16
+ parseSemanticKeyFooter,
17
+ } from '../../findings/route-finding.js';
18
+
19
+ /**
20
+ * @param {unknown} changes — `changes[]` entries, strings or `{ path }`.
21
+ * @returns {Array<(file: string) => boolean>}
22
+ */
23
+ function coverageMatchers(changes) {
24
+ if (!Array.isArray(changes)) return [];
25
+ return changes
26
+ .map((c) => (typeof c === 'string' ? c : c?.path))
27
+ .filter((p) => typeof p === 'string' && p.trim().length > 0)
28
+ .map((p) => {
29
+ const glob = p.trim();
30
+ const match = picomatch(glob, { dot: true });
31
+ return (file) => file === glob || match(file);
32
+ });
33
+ }
34
+
35
+ /**
36
+ * @param {Array<{ index: number, covers: Array<(f: string) => boolean> }>} candidates
37
+ * @param {string[]} files
38
+ * @returns {number[]}
39
+ */
40
+ function coveringIndexes(candidates, files) {
41
+ const covering = (file) =>
42
+ candidates.filter((c) => c.covers.some((m) => m(file))).map((c) => c.index);
43
+ // The primary file decides; the others only when nobody covers it.
44
+ const [primary, ...rest] = files;
45
+ if (primary === undefined) return [];
46
+ const byPrimary = covering(primary);
47
+ if (byPrimary.length > 0) return byPrimary;
48
+ return [...new Set(rest.flatMap(covering))];
49
+ }
50
+
51
+ /**
52
+ * Seed shas with no record are unattributable: carried like an unattributed
53
+ * finding so every seed sha still reaches a Story.
54
+ *
55
+ * @param {string} provenanceSource
56
+ * @returns {Array<{ sha: string, key: string, label: string|null, files: string[] }>}
57
+ */
58
+ function seedIdentities(provenanceSource) {
59
+ const records = parseAuditFindingRecords(provenanceSource);
60
+ const known = new Set(records.map((r) => r.sha));
61
+ const bare = parseFingerprintFooter(provenanceSource)
62
+ .filter((sha) => !known.has(sha))
63
+ .map((sha) => ({ sha, key: '', label: null, files: [] }));
64
+ return [...records, ...bare];
65
+ }
66
+
67
+ /**
68
+ * Whether persist attributes per Story: an N>1 draft whose seed carries at
69
+ * least one `audit-finding` record. Anything else keeps the union path.
70
+ *
71
+ * @param {number} storyCount
72
+ * @param {string} [provenanceSource]
73
+ * @returns {boolean}
74
+ */
75
+ function attributionApplies(storyCount, provenanceSource) {
76
+ return (
77
+ storyCount > 1 &&
78
+ parseAuditFindingRecords(provenanceSource ?? '').length > 0
79
+ );
80
+ }
81
+
82
+ /**
83
+ * Attribute each seed finding to the Stories that cover it. Order per Story:
84
+ * an authored `provenance` wins outright; otherwise the Story owns every
85
+ * finding one of whose files its `changes[]` covers (exact path, or a glob
86
+ * under picomatch `dot: true`). A finding no Story owns is unattributed: it
87
+ * rides on every non-authored Story and is named in the warnings.
88
+ *
89
+ * @param {Array<{ provenance: object|null, changes?: unknown }>} stories — draft order.
90
+ * @param {string} [provenanceSource] — the resolved seed provenance.
91
+ * @returns {{ sources: Array<string|null>, warnings: string[] }}
92
+ * One footer source per Story (`null` for an authored Story, which keeps
93
+ * its own); the seed union for every Story when attribution does not
94
+ * apply.
95
+ */
96
+ export function attributeSeedProvenance(stories, provenanceSource) {
97
+ const list = Array.isArray(stories) ? stories : [];
98
+ if (!attributionApplies(list.length, provenanceSource)) {
99
+ return { sources: list.map(() => provenanceSource ?? ''), warnings: [] };
100
+ }
101
+
102
+ const candidates = list
103
+ .map((s, index) => ({ s, index }))
104
+ .filter(({ s }) => s.provenance === null || s.provenance === undefined)
105
+ .map(({ s, index }) => ({ index, covers: coverageMatchers(s.changes) }));
106
+ const authored = new Set(
107
+ list.flatMap((s) => s.provenance?.fingerprints ?? []),
108
+ );
109
+ const identities = seedIdentities(provenanceSource);
110
+ const owned = list.map(() => []);
111
+ const warnings = [];
112
+
113
+ for (const identity of identities) {
114
+ const owners = coveringIndexes(candidates, identity.files);
115
+ if (owners.length > 0 || authored.has(identity.sha)) {
116
+ for (const i of owners) owned[i].push(identity);
117
+ continue;
118
+ }
119
+ for (const c of candidates) owned[c.index].push(identity);
120
+ warnings.push(
121
+ `unattributed audit finding ${identity.sha.slice(0, 12)} ` +
122
+ `(${identity.files[0] ?? 'no file'}) — carried on all ` +
123
+ `${candidates.length} Stories`,
124
+ );
125
+ }
126
+
127
+ const recordKeys = new Set(identities.map((r) => r.key));
128
+ const bareKeys = parseSemanticKeyFooter(provenanceSource).filter(
129
+ (k) => !recordKeys.has(k),
130
+ );
131
+ const sources = list.map((s, i) => {
132
+ if (s.provenance !== null && s.provenance !== undefined) return null;
133
+ return ownedProvenanceSource({
134
+ fingerprints: owned[i].map((r) => r.sha),
135
+ semanticKeys: [
136
+ ...new Set([...owned[i].map((r) => r.key), ...bareKeys]),
137
+ ].filter((k) => k.length > 0),
138
+ });
139
+ });
140
+ return { sources, warnings };
141
+ }
142
+
143
+ /**
144
+ * The labels one Story's stamped shas explain. A sha with no record (an
145
+ * authored identity outside the seed) gets the seed union: a label only
146
+ * widens the next sweep's corpus (matching is by fingerprint), so erring
147
+ * wide is safe.
148
+ *
149
+ * @param {string} body
150
+ * @param {Map<string, string|null>} labelBySha
151
+ * @param {string[]} union
152
+ * @returns {string[]}
153
+ */
154
+ function attributedLabels(body, labelBySha, union) {
155
+ const out = [];
156
+ for (const sha of parseFingerprintFooter(body)) {
157
+ if (!labelBySha.has(sha)) return [...new Set([...out, ...union])];
158
+ const label = labelBySha.get(sha);
159
+ if (label) out.push(label);
160
+ }
161
+ return out;
162
+ }
163
+
164
+ /**
165
+ * Per-Story `audit::*` labels, in draft order. Union path (N==1, or a seed
166
+ * with no records): every Story gets the seed's union labels. Attribution
167
+ * path: each Story gets the labels of the findings stamped on its body.
168
+ *
169
+ * @param {Array<{ body?: string }>} stories
170
+ * @param {string} provenanceSource
171
+ * @returns {string[][]}
172
+ */
173
+ export function auditLabelsPerStory(stories, provenanceSource) {
174
+ const union = parseAuditLabelFooter(provenanceSource);
175
+ if (!attributionApplies(stories.length, provenanceSource)) {
176
+ return stories.map(() => union);
177
+ }
178
+ const labelBySha = new Map(
179
+ parseAuditFindingRecords(provenanceSource).map((r) => [r.sha, r.label]),
180
+ );
181
+ return stories.map((s) => attributedLabels(s.body ?? '', labelBySha, union));
182
+ }
@@ -1,11 +1,13 @@
1
1
  /**
2
2
  * What an audit-seeded plan leaves for the next sweep: the provenance footers
3
- * every Story carries (the cross-run dedup memory) and the `audit::*` labels
3
+ * each Story carries (the cross-run dedup memory) and the `audit::*` labels
4
4
  * (the dedup corpus is label-listed, so footers alone are invisible to an
5
- * indexed sweep).
5
+ * indexed sweep). An N>1 plan whose seed carries `audit-finding` records
6
+ * attributes each finding to the Stories covering its files; otherwise every
7
+ * Story carries the seed union.
6
8
  */
7
9
 
8
- import { parseAuditLabelFooter } from '../../findings/route-finding.js';
10
+ import { auditLabelsPerStory } from './audit-attribution.js';
9
11
 
10
12
  /**
11
13
  * @param {object|null} envelope
@@ -42,19 +44,18 @@ export function resolveSeedProvenance(envelope) {
42
44
  }
43
45
 
44
46
  /**
45
- * Labels come from the seed union, not per-Story attribution: a label only
46
- * widens the next sweep's corpus (matching is by fingerprint), so erring
47
- * wide is safe.
47
+ * Stamp the `audit::*` labels. Union path (N==1, or a seed with no records):
48
+ * every Story gets the seed's union labels. Attribution path: each Story gets
49
+ * the labels of the findings stamped on its body.
48
50
  *
49
51
  * @param {Array<object>} stories
50
52
  * @param {string} [provenanceSource]
51
53
  * @returns {Array<object>}
52
54
  */
53
55
  export function withAuditLabels(stories, provenanceSource) {
54
- const fromSeed = parseAuditLabelFooter(provenanceSource ?? '');
55
- if (fromSeed.length === 0) return stories;
56
- return stories.map((story) => ({
56
+ const perStory = auditLabelsPerStory(stories, provenanceSource ?? '');
57
+ return stories.map((story, i) => ({
57
58
  ...story,
58
- labels: [...new Set([...story.labels, ...fromSeed])],
59
+ labels: [...new Set([...story.labels, ...perStory[i]])],
59
60
  }));
60
61
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * collision-message.js — the clauses of a same-wave refusal line, naming
3
+ * who declared each colliding path, so a Story that declared
4
+ * nothing is never blamed for a sibling's glob.
5
+ *
6
+ * @module lib/orchestration/plan-persist/collision-message
7
+ */
8
+
9
+ import { globsOverlap, isGlobPath } from '../../wave-runner/footprint.js';
10
+
11
+ /**
12
+ * One clause per colliding path, naming who declared it. A glob both sides
13
+ * declare and a concrete path both declare read alike; a one-sided glob says
14
+ * what it covers. A glob the other side's glob already names as an overlap
15
+ * is not restated from the other direction.
16
+ *
17
+ * @param {{ slugs: [string, string], paths: string[], declaredBy?: Record<string, string> }} collision
18
+ * @returns {string[]}
19
+ */
20
+ export function declarerClauses({ slugs, paths, declaredBy = {} }) {
21
+ const name = { a: `"${slugs[0]}"`, b: `"${slugs[1]}"` };
22
+ const other = { a: 'b', b: 'a' };
23
+ const globsOf = (side) =>
24
+ paths.filter(
25
+ (p) => isGlobPath(p) && [side, 'both'].includes(declaredBy[p] ?? 'both'),
26
+ );
27
+ const clauses = [];
28
+ for (const path of paths) {
29
+ const side = declaredBy[path] ?? 'both';
30
+ if (side === 'both' || !isGlobPath(path)) {
31
+ clauses.push(`${name.a} + ${name.b} both declare \`${path}\``);
32
+ continue;
33
+ }
34
+ const peer = other[side];
35
+ const overlapping = globsOf(peer).filter((g) => globsOverlap(path, g));
36
+ if (overlapping.length === 0) {
37
+ clauses.push(
38
+ `${name[side]} declares glob \`${path}\`, which covers a path ${name[peer]} declares`,
39
+ );
40
+ continue;
41
+ }
42
+ // A `b` glob overlapping an `a`-only glob is already named by that clause.
43
+ if (side === 'b' && overlapping.some((g) => declaredBy[g] === 'a')) {
44
+ continue;
45
+ }
46
+ const globs = overlapping.map((g) => `\`${g}\``).join(', ');
47
+ clauses.push(
48
+ `${name[side]} declares glob \`${path}\`, which may overlap ${name[peer]}'s glob ${globs}`,
49
+ );
50
+ }
51
+ return clauses;
52
+ }
@@ -1,7 +1,8 @@
1
1
  /**
2
2
  * Flat Story persist. Hard gates refuse; everything else is a warning the
3
3
  * dry-run lists. Order: validate → reachability → wave-collision gate →
4
- * create (without `agent::ready`) → plan comment on every Story → flip to
4
+ * create (without `agent::ready`) — or, for a one-for-one `--tickets` plan,
5
+ * rewrite the source in place → plan comment on every Story → flip to
5
6
  * `agent::ready` last, so `ready` implies "plan comments written" → close
6
7
  * superseded sources (never fails the run) → temp cleanup.
7
8
  *
@@ -40,6 +41,7 @@ import {
40
41
  } from './cross-plan-links.js';
41
42
  import { validateTickets } from './persist-helpers.js';
42
43
  import { surfaceSoftConflictFindings } from './soft-findings.js';
44
+ import { resolveRewriteTarget } from './source-rewrite.js';
43
45
  import {
44
46
  assemblePlanStories,
45
47
  createStoryIssues,
@@ -163,6 +165,7 @@ async function runSupersedePhase(args) {
163
165
  dryRun: args.dryRun === true,
164
166
  reason: `phase-error: ${err.message}`,
165
167
  closed: [],
168
+ rewritten: [],
166
169
  planned: [],
167
170
  epicRollup: { closed: [], pending: [] },
168
171
  skipped: [],
@@ -335,6 +338,36 @@ async function cleanupPlanDirs({ config, planDir, skipCleanup }) {
335
338
  await reapStalePlanDirs({ config, keepDir: skipCleanup ? planDir : null });
336
339
  }
337
340
 
341
+ /**
342
+ * Reads only, so the dry run probes too and reports the planned rewrite. A
343
+ * refused one-for-one lands in the run's warnings.
344
+ *
345
+ * @param {Parameters<typeof resolveRewriteTarget>[0]} args
346
+ * @param {string[]} warnings Appended to in place.
347
+ * @returns {ReturnType<typeof resolveRewriteTarget>}
348
+ */
349
+ async function resolveRewrite(args, warnings) {
350
+ const rewrite = await resolveRewriteTarget(args);
351
+ warnings.push(...rewrite.warnings);
352
+ logWarnings(rewrite.warnings);
353
+ return rewrite;
354
+ }
355
+
356
+ /**
357
+ * @param {object[]} created
358
+ * @param {{ id: number, rewritten?: boolean }} primary
359
+ * @returns {string}
360
+ */
361
+ function persistHeadline(created, primary) {
362
+ if (primary.rewritten) {
363
+ return `[plan-persist] Rewrote #${primary.id} in place; it is agent::ready.`;
364
+ }
365
+ return (
366
+ `[plan-persist] Persisted ${created.length} Story(ies)` +
367
+ `; primary #${primary.id} is agent::ready.`
368
+ );
369
+ }
370
+
338
371
  /**
339
372
  * @param {{
340
373
  * created: object[],
@@ -357,10 +390,7 @@ function logPersistEpilogue({
357
390
  `from a previous persist: ${adopted.map((s2) => `#${s2.id}`).join(', ')}.`,
358
391
  );
359
392
  }
360
- Logger.info(
361
- `[plan-persist] Persisted ${created.length} Story(ies)` +
362
- `; primary #${primary.id} is agent::ready.`,
363
- );
393
+ Logger.info(persistHeadline(created, primary));
364
394
  Logger.info(
365
395
  `[plan-persist] Deliver with: /mandrel-deliver ${created.map((s2) => s2.id).join(' ')}`,
366
396
  );
@@ -392,6 +422,7 @@ function logPersistEpilogue({
392
422
  * sourceTicketIds?: number[],
393
423
  * sourceTicketOrigin?: 'flag'|'envelope'|'none',
394
424
  * closeSuperseded?: boolean,
425
+ * rewriteSource?: boolean,
395
426
  * },
396
427
  * }} input
397
428
  */
@@ -416,6 +447,8 @@ export async function runPlanPersist({
416
447
  sourceTicketIds = [],
417
448
  sourceTicketOrigin = 'none',
418
449
  closeSuperseded = true,
450
+ // One-for-one plans rewrite their source in place unless opted out.
451
+ rewriteSource = true,
419
452
  // Optional container Epic; only set when the operator confirmed one.
420
453
  epic = null,
421
454
  } = opts;
@@ -458,8 +491,10 @@ export async function runPlanPersist({
458
491
  assemblePlanStories(rawStories, {
459
492
  sharedSpec: techSpecContent,
460
493
  sourceTicketIds,
461
- // Audit footers carried onto every Story that did not attribute its own
462
- // `provenance`; empty for a `--tickets` run.
494
+ // Audit footers for every Story without an authored `provenance`: an
495
+ // N>1 draft over a record-carrying seed attributes them per Story by
496
+ // `changes[]` coverage (unattributed findings ride on all and surface
497
+ // in `warnings`); otherwise the seed union. Empty for `--tickets`.
463
498
  provenanceSource: seedProvenance,
464
499
  });
465
500
 
@@ -467,7 +502,7 @@ export async function runPlanPersist({
467
502
  logWarnings(supersedeWarnings);
468
503
 
469
504
  // The dedup corpus is listed by `audit::*` label; footers alone leave the
470
- // Story invisible to an indexed sweep.
505
+ // Story invisible to an indexed sweep. Labels follow the stamped findings.
471
506
  const stories = withAuditLabels(assembled, seedProvenance);
472
507
 
473
508
  const assembledConflicts = analyzeAssembledStories({
@@ -491,11 +526,22 @@ export async function runPlanPersist({
491
526
  tempRoot: getPaths(config).tempRoot,
492
527
  });
493
528
 
529
+ const rewrite = await resolveRewrite(
530
+ {
531
+ provider,
532
+ storyCount: stories.length,
533
+ sourceTicketIds,
534
+ rewriteSource,
535
+ closeSuperseded,
536
+ },
537
+ warnings,
538
+ );
539
+
494
540
  const { created, planRunLabel, planRunLabelApplied } =
495
541
  await createStoryIssues({
496
542
  provider,
497
543
  stories,
498
- opts: { dryRun },
544
+ opts: { dryRun, rewriteTarget: rewrite.target },
499
545
  });
500
546
 
501
547
  const primary = created[0];
@@ -571,6 +617,7 @@ export async function runPlanPersist({
571
617
  assumptionNormalizations: validated.normalizations ?? [],
572
618
  waveCollisions,
573
619
  supersede,
620
+ rewrite: { ticket: rewrite.ticketId, reason: rewrite.reason },
574
621
  epic: containerEpic,
575
622
  };
576
623
  }