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
@@ -15,7 +15,7 @@ import { detectCollision } from '../../wave-runner/footprint.js';
15
15
  * @param {ReturnType<typeof buildWaveTable>} waveTable
16
16
  * @param {Array<{ slug: string, title?: string, body?: string, spec?: string, changes?: Array }>} stories
17
17
  * @param {{ tempRoot?: string }} [options] Accepted for compatibility; unread.
18
- * @returns {Array<{ wave: number, slugs: [string, string], paths: string[], source: string }>}
18
+ * @returns {Array<{ wave: number, slugs: [string, string], paths: string[], source: string, declaredBy: Record<string, string> }>}
19
19
  */
20
20
  export function predictWaveSerialisation(waveTable, stories, options = {}) {
21
21
  const bySlug = new Map(
@@ -71,6 +71,7 @@ export function renderPredictedSerialisationLines(collisions) {
71
71
  '_The dispatcher compares the **declared** `changes[]` footprints ' +
72
72
  '(Story #5313 retired the text scrape), so these pairs are shown in ' +
73
73
  'one order above but will be dispatched one at a time: both Stories ' +
74
- 'declare a colliding path, or one declares a glob._',
74
+ 'declare a colliding path, or one declares a glob that covers the ' +
75
+ "other's path._",
75
76
  ];
76
77
  }
@@ -278,6 +278,9 @@ export async function readNativeBlockedBy({
278
278
  * @param {Map<number, number[]>} nativeEdges
279
279
  * @param {number[]} foreignDone Ids outside the set already satisfied.
280
280
  * @param {(msg: string) => void} [warn]
281
+ * @param {Map<number, number>} [priorBlocksById] Local prior-block count per
282
+ * Story; absent counts 0.
283
+ * @param {boolean} [roleScopedAgents] `delivery.routing.roleScopedAgents`.
281
284
  * @returns {{ kind: string, stories: object[], dag: object[], done: number[] }}
282
285
  */
283
286
  export function buildStoriesEnvelope({
@@ -285,13 +288,16 @@ export function buildStoriesEnvelope({
285
288
  nativeEdges = new Map(),
286
289
  foreignDone = [],
287
290
  warn,
291
+ priorBlocksById = new Map(),
292
+ roleScopedAgents = false,
288
293
  }) {
289
294
  const sorted = [...stories].sort((a, b) => a.id - b.id);
290
295
  const inSetDone = sorted.filter(isSatisfiedBlocker).map((s) => s.id);
291
296
  return {
292
297
  kind: 'stories',
293
298
  // `inline` (the router's own session) only for a single-Story set, so no
294
- // sibling can claim that session. Decided on the resolved set size, not
299
+ // sibling can claim that session — unless a one-Story resume needs a
300
+ // spawn for its per-call effort. Decided on the resolved set size, not
295
301
  // the undelivered remainder, so the mode never changes mid-run.
296
302
  stories: sorted.map(({ id, title, url, labels, state }) => ({
297
303
  id,
@@ -299,8 +305,11 @@ export function buildStoriesEnvelope({
299
305
  url,
300
306
  labels,
301
307
  state,
302
- dispatchMode: resolveStoryDispatchMode({ storyCount: sorted.length })
303
- .mode,
308
+ dispatchMode: resolveStoryDispatchMode({
309
+ storyCount: sorted.length,
310
+ priorBlocks: priorBlocksById.get(id) ?? 0,
311
+ roleScopedAgents,
312
+ }).mode,
304
313
  })),
305
314
  dag: storiesToDag(sorted, nativeEdges, warn),
306
315
  done: [...new Set([...inSetDone, ...foreignDone])].sort((a, b) => a - b),
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Per-call story-worker effort for a resumed blocked Story, from its local
3
+ * signals only.
4
+ *
5
+ * @module lib/orchestration/resume-effort
6
+ */
7
+
8
+ import { getDeliveryRouting } from '../config/delivery-routing.js';
9
+ import { Logger } from '../Logger.js';
10
+ import { RUNTIME_FRICTION_CATEGORIES } from '../observability/runtime-friction.js';
11
+ import { forEachLine } from '../observability/signals-writer.js';
12
+ import { EVENT_KINDS } from '../signals/schema.js';
13
+
14
+ const AGENT_EFFORT_LEVELS = Object.freeze([
15
+ 'low',
16
+ 'medium',
17
+ 'high',
18
+ 'xhigh',
19
+ 'max',
20
+ ]);
21
+
22
+ /**
23
+ * @param {unknown} value
24
+ * @returns {{ effort: string|null, warning: string|null }}
25
+ */
26
+ export function parseWorkerEffort(value) {
27
+ if (value == null) return { effort: null, warning: null };
28
+ const raw = String(value).trim();
29
+ if (AGENT_EFFORT_LEVELS.includes(raw)) {
30
+ return { effort: raw, warning: null };
31
+ }
32
+ return {
33
+ effort: null,
34
+ warning: `--worker-effort must be one of ${AGENT_EFFORT_LEVELS.join('|')} (got ${JSON.stringify(value)}); telemetry.workerEffort records null.`,
35
+ };
36
+ }
37
+
38
+ /**
39
+ * @param {unknown} record
40
+ * @returns {boolean}
41
+ */
42
+ function isPriorBlockRecord(record) {
43
+ return (
44
+ record !== null &&
45
+ typeof record === 'object' &&
46
+ record.kind === EVENT_KINDS.FRICTION &&
47
+ record.category === RUNTIME_FRICTION_CATEGORIES.STORY_BLOCKED &&
48
+ record.details?.recovered !== true
49
+ );
50
+ }
51
+
52
+ /**
53
+ * The ladder's single source; absolute, not relative to session effort.
54
+ *
55
+ * @param {number} priorBlocks
56
+ * @returns {'high'|'xhigh'|null}
57
+ */
58
+ function resumeEffortFor(priorBlocks) {
59
+ if (priorBlocks < 1) return null;
60
+ return priorBlocks === 1 ? 'high' : 'xhigh';
61
+ }
62
+
63
+ /**
64
+ * @param {number} storyId
65
+ * @param {{ config?: object, readFn?: typeof forEachLine }} [opts]
66
+ * @returns {Promise<number>}
67
+ */
68
+ async function countPriorBlocks(
69
+ storyId,
70
+ { config, readFn = forEachLine } = {},
71
+ ) {
72
+ let count = 0;
73
+ try {
74
+ await readFn(
75
+ null,
76
+ storyId,
77
+ (record) => {
78
+ if (isPriorBlockRecord(record)) count += 1;
79
+ },
80
+ config,
81
+ );
82
+ } catch (err) {
83
+ Logger.warn(
84
+ `[resume-effort] signal read failed for Story #${storyId}: ${
85
+ err instanceof Error ? err.message : String(err)
86
+ } — counting 0 prior blocks.`,
87
+ );
88
+ return 0;
89
+ }
90
+ return count;
91
+ }
92
+
93
+ /**
94
+ * @param {number} storyId
95
+ * @param {{ config?: object, readFn?: typeof forEachLine }} [opts]
96
+ * @returns {Promise<'high'|'xhigh'|null>}
97
+ */
98
+ export async function resolveResumeEffort(storyId, opts) {
99
+ return resumeEffortFor(await countPriorBlocks(storyId, opts));
100
+ }
101
+
102
+ /**
103
+ * @param {Array<{ id: number }>} stories
104
+ * @param {{ config?: object, countFn?: typeof countPriorBlocks }} [opts]
105
+ * @returns {Promise<{ priorBlocksById: Map<number, number>,
106
+ * roleScopedAgents: boolean }>}
107
+ */
108
+ export async function resolveRunDispatchInputs(
109
+ stories,
110
+ { config, countFn = countPriorBlocks } = {},
111
+ ) {
112
+ const priorBlocksById = new Map();
113
+ if (stories.length === 1) {
114
+ const [{ id }] = stories;
115
+ priorBlocksById.set(id, await countFn(id, { config }));
116
+ }
117
+ return {
118
+ priorBlocksById,
119
+ roleScopedAgents: getDeliveryRouting(config).roleScopedAgents,
120
+ };
121
+ }
@@ -126,11 +126,20 @@ function workerFlags(tokensParam, modelParam, parsed) {
126
126
  };
127
127
  }
128
128
 
129
+ /**
130
+ * @param {unknown} effortParam
131
+ * @param {{ workerEffort?: unknown }} parsed
132
+ * @returns {unknown}
133
+ */
134
+ function workerEffortFlag(effortParam, parsed) {
135
+ return resolveFlag(effortParam, parsed.workerEffort);
136
+ }
137
+
129
138
  /**
130
139
  * Returns raw wait-for-merge intent; the runner resolves it after the arm.
131
140
  *
132
- * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam, workerModelParam }} raw
133
- * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens, workerModel }}
141
+ * @param {{ storyIdParam, cwdParam, skipValidationParam, skipSyncParam, noAutoMergeParam, waitForMergeParam, noWaitForMergeParam, maxWaitSecondsParam, mergeWatchModeParam, rerunAdvisoryParam, overrideReviewBlockParam, workerTokensParam, workerModelParam, workerEffortParam }} raw
142
+ * @returns {{ storyId, cwd, skipValidation, skipSync, noAutoMerge, waitForMergeExplicit, noWaitForMerge, maxWaitSeconds, mergeWatchMode, rerunAdvisory, overrideReviewBlock, workerTokens, workerModel, workerEffort }}
134
143
  */
135
144
  export function parseCloseOptions({
136
145
  storyIdParam,
@@ -146,6 +155,7 @@ export function parseCloseOptions({
146
155
  overrideReviewBlockParam,
147
156
  workerTokensParam,
148
157
  workerModelParam,
158
+ workerEffortParam,
149
159
  }) {
150
160
  // An injecting caller never reads argv (the host's flags are not its
151
161
  // business), so `parsed` stays empty and the retired-flag guard is skipped.
@@ -187,5 +197,6 @@ export function parseCloseOptions({
187
197
  resolveFlag(overrideReviewBlockParam, parsed.overrideReviewBlock),
188
198
  ),
189
199
  ...workerFlags(workerTokensParam, workerModelParam, parsed),
200
+ workerEffort: workerEffortFlag(workerEffortParam, parsed),
190
201
  };
191
202
  }
@@ -12,6 +12,7 @@ import { Logger } from '../../Logger.js';
12
12
  import {
13
13
  emitReviewBlockedFriction,
14
14
  recordCloseTelemetry,
15
+ resolveWorkerEffort,
15
16
  resolveWorkerModel,
16
17
  resolveWorkerTokens,
17
18
  } from '../../observability/close-telemetry.js';
@@ -104,7 +105,11 @@ function createPhaseTimer(nowMs = Date.now) {
104
105
  const UNTIMED = Object.freeze({ stamp() {} });
105
106
 
106
107
  /** No worker figures: an inline close, or an ending before they resolve. */
107
- const NO_WORKER = Object.freeze({ workerTokens: null, workerModel: null });
108
+ const NO_WORKER = Object.freeze({
109
+ workerTokens: null,
110
+ workerModel: null,
111
+ workerEffort: null,
112
+ });
108
113
 
109
114
  /**
110
115
  * The single terminal writer: the retry signal, the result summary (with its
@@ -600,6 +605,7 @@ export async function runSingleStoryClose({
600
605
  overrideReviewBlock: overrideReviewBlockParam,
601
606
  workerTokens: workerTokensParam,
602
607
  workerModel: workerModelParam,
608
+ workerEffort: workerEffortParam,
603
609
  ...injected
604
610
  } = {}) {
605
611
  const options = parseCloseOptions({
@@ -616,10 +622,11 @@ export async function runSingleStoryClose({
616
622
  overrideReviewBlockParam,
617
623
  workerTokensParam,
618
624
  workerModelParam,
625
+ workerEffortParam,
619
626
  });
620
627
  if (!options.storyId) {
621
628
  throw new Error(
622
- 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>]',
629
+ 'Usage: node single-story-close.js --story <STORY_ID> [--cwd <main-repo>] [--skip-validation] [--skip-sync] [--no-auto-merge] [--wait-merge|--no-wait-merge] [--max-wait-seconds <n>] [--merge-watch-mode <sync|async>] [--rerun-advisory <n>] [--override-review-block <reason>] [--worker-tokens <n>] [--worker-model <model>] [--worker-effort <level>]',
623
630
  );
624
631
  }
625
632
 
@@ -1212,6 +1219,7 @@ async function runClosePipeline(run, deps) {
1212
1219
  worker: {
1213
1220
  workerTokens: resolveWorkerTokens(run.options.workerTokens),
1214
1221
  workerModel: resolveWorkerModel(run.options.workerModel),
1222
+ workerEffort: resolveWorkerEffort(run.options.workerEffort),
1215
1223
  },
1216
1224
  };
1217
1225
  for (const phase of CLOSE_PIPELINE) {
@@ -60,6 +60,9 @@ export const STRUCTURED_COMMENT_TYPES = Object.freeze([
60
60
  // Posted before closing a superseded source issue; the marker keeps
61
61
  // re-runs from double-commenting.
62
62
  'superseded-by',
63
+ // The source ticket's pre-plan title and body, posted once before a
64
+ // one-for-one rewrite; first write wins, so re-plans keep the original.
65
+ 'plan-rewrite',
63
66
  ]);
64
67
 
65
68
  export const WAVE_TYPE_PATTERN = WAVE_MARKER_RE;
@@ -25,8 +25,9 @@ export const QA_REQUIRED_FIELDS = Object.freeze([
25
25
  'personas',
26
26
  ]);
27
27
 
28
- // The only environment whose `allowWrites` defaults to true; every other
29
- // target is read-only unless the consumer opts in.
28
+ // The only environment whose `allowWrites` (and `database.allowAudit`)
29
+ // defaults to true; every other target is read-only and unaudited unless the
30
+ // consumer opts in.
30
31
  const WRITE_ENABLED_DEFAULT_ENVIRONMENT = 'local';
31
32
 
32
33
  export const QA_CONTRACT_DEFAULTS = Object.freeze({
@@ -93,7 +94,7 @@ function describeError(err) {
93
94
  * @returns {{
94
95
  * featureRoot: string,
95
96
  * fixturesManifest: string,
96
- * environments: Record<string, { baseUrl: string, signInSeam: object, allowWrites?: boolean }>,
97
+ * environments: Record<string, { baseUrl: string, signInSeam: object, allowWrites?: boolean, database?: { urlEnv: string, allowAudit?: boolean } }>,
97
98
  * defaultEnvironment: string,
98
99
  * personas: Record<string, object>,
99
100
  * personaNames: string[],
@@ -220,16 +221,34 @@ function resolveSignInSeam(seam, envName, options) {
220
221
  return { ...seam, skillPath: found.path };
221
222
  }
222
223
 
224
+ /**
225
+ * The audit opt-in mirrors `allowWrites`: an explicit boolean wins, else only
226
+ * the `local` environment is audited by default.
227
+ *
228
+ * @param {{ urlEnv: string, allowAudit?: boolean } | undefined} database
229
+ * @param {boolean} isDefaultLocal
230
+ * @returns {{ urlEnv: string, allowAudit: boolean } | null}
231
+ */
232
+ function resolveDatabaseTarget(database, isDefaultLocal) {
233
+ if (database == null) return null;
234
+ const allowAudit =
235
+ typeof database.allowAudit === 'boolean'
236
+ ? database.allowAudit
237
+ : isDefaultLocal;
238
+ return { urlEnv: database.urlEnv, allowAudit };
239
+ }
240
+
223
241
  /**
224
242
  * Select one environment: omitted → default; exact name (wins even if it
225
243
  * parses as a URL); else a raw URL matched by origin against each `baseUrl`.
226
- * `allowWrites` resolves to an explicit boolean.
244
+ * `allowWrites` resolves to an explicit boolean; `database` resolves to
245
+ * `null` or `{ urlEnv, allowAudit }` with `allowAudit` an explicit boolean.
227
246
  *
228
- * @param {{ environments: Record<string, { baseUrl: string, signInSeam?: object, allowWrites?: boolean }>, defaultEnvironment: string }} contract
247
+ * @param {{ environments: Record<string, { baseUrl: string, signInSeam?: object, allowWrites?: boolean, database?: { urlEnv: string, allowAudit?: boolean } }>, defaultEnvironment: string }} contract
229
248
  * A contract returned by `resolveQaContract`.
230
249
  * @param {string} [target] Environment name or raw URL.
231
250
  * @param {{ repoRoot?: string }} [options] Roots skill-seam resolution.
232
- * @returns {{ name: string, baseUrl: string, signInSeam: object | null, allowWrites: boolean }}
251
+ * @returns {{ name: string, baseUrl: string, signInSeam: object | null, allowWrites: boolean, database: { urlEnv: string, allowAudit: boolean } | null }}
233
252
  * @throws {Error} on an unknown name, an unmatched URL, or a `{ skill }` seam
234
253
  * that resolves under no skills root.
235
254
  */
@@ -273,15 +292,15 @@ export function resolveQaEnvironment(contract, target, options = {}) {
273
292
  }
274
293
 
275
294
  const env = environments[resolvedName];
295
+ const isDefaultLocal = resolvedName === WRITE_ENABLED_DEFAULT_ENVIRONMENT;
276
296
  const allowWrites =
277
- typeof env.allowWrites === 'boolean'
278
- ? env.allowWrites
279
- : resolvedName === WRITE_ENABLED_DEFAULT_ENVIRONMENT;
297
+ typeof env.allowWrites === 'boolean' ? env.allowWrites : isDefaultLocal;
280
298
 
281
299
  return {
282
300
  name: resolvedName,
283
301
  baseUrl: env.baseUrl,
284
302
  signInSeam: resolveSignInSeam(env.signInSeam, resolvedName, options),
285
303
  allowWrites,
304
+ database: resolveDatabaseTarget(env.database, isDefaultLocal),
286
305
  };
287
306
  }
@@ -87,7 +87,7 @@ The **persisted** \`body\` renders these sections in order:
87
87
  - **spec** (optional): The decided approach at the altitude the SPEC PROSE CONTRACT below fixes. As long as the work needs; persist keeps Specs inline at any length and never writes them under \`docs/\`.
88
88
  - **slicing** (optional): Ordered intra-session checkpoints, one line each. A checkpoint is a **stage of the work** — a commit boundary the deliverer passes through, stated as the step it performs. An acceptance item is a **state of the codebase** a PR reviewer confirms once the Story has landed. Never a second acceptance list, never sibling tickets. End a checkpoint with \`— verify: <exact command>\` so the deliverer can prove it before moving on — encouraged past two checkpoints.
89
89
  - **context** (optional): The facts you verified while planning, so the deliverer does not rediscover them — entry points (file + symbol), the existing pattern to mirror, the test file or harness to extend, known traps, the scoped test command. Terse verified facts, never a walkthrough. Backticked paths are probed at persist; one absent at base is a warning.
90
- - **changes**: Each entry is a **bare path string** — the default; persist derives its assumption by probing the base branch and reports the derivation. Pin the object form \`{ path, assumption }\` (\`creates | refactors-existing | deletes\`) only when the probe would get it wrong, and always for a \`deletes\`, which a bare path can never express. Globs (\`tests/e2e/*.spec.ts\`) are accepted. **Name the files the deliverer authors, and omit generated artifacts** — quality baselines, generated indexes, lockfiles and the like are regenerated by the work itself, and declaring one needlessly reserves a footprint that serializes sibling Stories at dispatch. A \`creates\` on an existing path or a \`refactors-existing\` on an absent one is a dry-run warning; only a \`deletes\` naming an absent path is refused.
90
+ - **changes**: Each entry is a **bare path string** — the default; persist derives its assumption by probing the base branch and reports the derivation. Pin the object form \`{ path, assumption }\` (\`creates | refactors-existing | deletes\`) only when the probe would get it wrong, and always for a \`deletes\`, which a bare path can never express. Globs (\`tests/e2e/*.spec.ts\`) are accepted, but a glob reserves every path it can match, so a broad glob such as \`lib/**\` serializes its Story against any sibling declaring a path under that tree — prefer concrete paths whenever the files are known. **Name the files the deliverer authors, and omit generated artifacts** — quality baselines, generated indexes, lockfiles and the like are regenerated by the work itself, and declaring one needlessly reserves a footprint that serializes sibling Stories at dispatch. A \`creates\` on an existing path or a \`refactors-existing\` on an absent one is a dry-run warning; only a \`deletes\` naming an absent path is refused.
91
91
  - **references** (optional): The files the deliverer should read before editing but does not change. A bare path; persist derives \`exists\` and warns when one is absent at base.
92
92
  - **acceptance** (top-level array): Each item is an **outcome a PR reviewer can confirm from the diff and the verify output** — what is true of the codebase once the Story lands, at the altitude of the capability (a command that now exits 0 against a named input, a behavior a named test now asserts, a config that now fails validation on a retired key). State as many outcomes as the capability has — the list has no target, floor or ceiling, and a long one is never a reason to split the Story. Push grep-shaped probes, file-exists checks and exit-code tests down into \`verify[]\`. UNACCEPTABLE: "verify by reading the diff", "looks good", "matches the spec".
93
93
  - **verify** (top-level array): The **mechanical checks** — exact commands or test paths the deliverer runs and the acceptance critic reads as evidence: \`node --test tests/x.test.js\`, \`npm run lint\`, a scoped grep. Every acceptance item should be confirmable from at least one verify entry's output plus the diff. An empty list is warned about, not rejected — but leaves the critic no evidence.
@@ -153,7 +153,7 @@ You are splitting past the default-single policy, so simulate the delivery sched
153
153
 
154
154
  #### THE COLLISION REFUSAL (persist-enforced at N>1):
155
155
 
156
- Persist runs the **dispatcher's own** collision predicate pairwise over your draft, before it creates a single issue, and **refuses** the plan when any two same-wave Stories collide — both declaring a path in \`changes[]\`, or one declaring a glob that covers the other's path. Such a pair cannot be co-dispatched, so the split buys no parallelism and costs a delivery session. Two remedies, both yours to choose at authoring time:
156
+ Persist runs the **dispatcher's own** collision predicate pairwise over your draft, before it creates a single issue, and **refuses** the plan when any two same-wave Stories collide — both declaring a path in \`changes[]\`, one declaring a glob that covers a concrete path the other declares, or both declaring globs whose static bases overlap (\`lib/**\` and \`lib/sub/*.js\`; \`lib/**\` and \`docs/*.md\` do not). Such a pair cannot be co-dispatched, so the split buys no parallelism and costs a delivery session. Two remedies, both yours to choose at authoring time:
157
157
 
158
158
  - **Merge the pair** into the one Story they already are, with \`## Slicing\` checkpoints for the stages; or
159
159
  - **Order them** with \`depends_on\` so they sit in different waves, when they genuinely have separate reasons to exist.
@@ -2,12 +2,15 @@
2
2
  * lib/wave-runner/footprint.js — whether two Stories' declared footprints
3
3
  * intersect. The footprint is the declaration only: paths scraped from
4
4
  * titles, specs or prose manufactured far more serialisation than they
5
- * prevented, so two Stories collide only when both declare a path (or one
6
- * declares a glob). Reads and mutates nothing.
5
+ * prevented, so two Stories collide only when both declare a path, one
6
+ * declares a glob covering the other's path, or both declare globs whose
7
+ * static bases overlap. Reads and mutates nothing.
7
8
  *
8
9
  * @module lib/wave-runner/footprint
9
10
  */
10
11
 
12
+ import picomatch from 'picomatch';
13
+
11
14
  /**
12
15
  * One class today; kept on the envelope so consumers keyed on `source` stay
13
16
  * stable if a second class appears.
@@ -45,37 +48,118 @@ export function storyFootprint(story) {
45
48
  * @param {string} path
46
49
  * @returns {boolean}
47
50
  */
48
- function isGlobPath(path) {
51
+ export function isGlobPath(path) {
49
52
  return path.includes('*') || path.includes('?') || path.includes('{');
50
53
  }
51
54
 
55
+ const GLOB_OPTIONS = Object.freeze({ dot: true });
56
+
57
+ /**
58
+ * The glob's static directory prefix — `''` for a glob such as `**` or
59
+ * `*.md` that is rooted nowhere.
60
+ *
61
+ * @param {string} glob
62
+ * @returns {string}
63
+ */
64
+ function globBase(glob) {
65
+ return picomatch.scan(glob).base;
66
+ }
67
+
68
+ /**
69
+ * Whole-segment prefix overlap: `lib` covers `lib/x`, never `libs`. An empty
70
+ * base overlaps everything.
71
+ *
72
+ * @param {string} x
73
+ * @param {string} y
74
+ * @returns {boolean}
75
+ */
76
+ function basesOverlap(x, y) {
77
+ if (x === '' || y === '' || x === y) return true;
78
+ const [short, long] = x.length < y.length ? [x, y] : [y, x];
79
+ return long.startsWith(`${short}/`);
80
+ }
81
+
52
82
  /**
53
- * A glob is unknown width, not no width: exact-string comparison would pass
54
- * `lib/**` alongside a file beneath it, so a glob collides with everything.
83
+ * Whether two globs may match a common path, judged by their static bases.
84
+ * Conservative by design: two globs sharing a base may still be disjoint
85
+ * (`lib/*.js` vs `lib/*.md`), and the predicate serializes them anyway.
55
86
  *
56
- * @param {Set<string>} hits
57
- * @param {Set<string>} side
87
+ * @param {string} g
88
+ * @param {string} h
89
+ * @returns {boolean}
58
90
  */
59
- function collectGlobs(hits, side) {
60
- for (const path of side) {
61
- if (isGlobPath(path)) hits.add(path);
91
+ export function globsOverlap(g, h) {
92
+ return basesOverlap(globBase(g), globBase(h));
93
+ }
94
+
95
+ /**
96
+ * Record that `side` declared `path` as a colliding path.
97
+ *
98
+ * @param {Map<string, Set<string>>} hits
99
+ * @param {string} path
100
+ * @param {'a'|'b'} side
101
+ */
102
+ function addHit(hits, path, side) {
103
+ const sides = hits.get(path) ?? new Set();
104
+ sides.add(side);
105
+ hits.set(path, sides);
106
+ }
107
+
108
+ /**
109
+ * Collect the globs on `globSide` that cover a concrete path or overlap a
110
+ * glob on `otherSide`. A glob hit reports the glob — the thing an author
111
+ * edits — never the concrete path it matched.
112
+ *
113
+ * @param {Map<string, Set<string>>} hits
114
+ * @param {{ globs: string[], concrete: string[] }} mine
115
+ * @param {{ globs: string[], concrete: string[] }} theirs
116
+ * @param {'a'|'b'} side
117
+ */
118
+ function collectGlobHits(hits, mine, theirs, side) {
119
+ for (const glob of mine.globs) {
120
+ const matches = picomatch(glob, GLOB_OPTIONS);
121
+ const covers =
122
+ theirs.concrete.some((path) => matches(path)) ||
123
+ theirs.globs.some((other) => globsOverlap(glob, other));
124
+ if (covers) addHit(hits, glob, side);
62
125
  }
63
126
  }
64
127
 
128
+ /**
129
+ * @param {Set<string>} footprint
130
+ * @returns {{ globs: string[], concrete: string[] }}
131
+ */
132
+ function partition(footprint) {
133
+ const globs = [];
134
+ const concrete = [];
135
+ for (const path of footprint)
136
+ (isGlobPath(path) ? globs : concrete).push(path);
137
+ return { globs, concrete };
138
+ }
139
+
65
140
  /**
66
141
  * Colliding paths, or `null`. An empty footprint never collides —
67
142
  * withholding on absence would serialize every run.
68
143
  *
144
+ * Two footprints collide on a concrete path both declare, on a glob that
145
+ * matches a concrete path the other side declares, or on two globs whose
146
+ * static bases overlap. The `**` UNKNOWN sentinel therefore collides with
147
+ * every non-empty footprint by construction: it matches every concrete path
148
+ * and its empty base overlaps every glob.
149
+ *
69
150
  * `concreteOnly` is for the cross-beat reservation: an in-flight Story holds
70
151
  * its footprint for hours, and unparseable bodies resolve to an UNKNOWN glob
71
152
  * sentinel, so honouring globs there would make one bad Story serialize the
72
153
  * whole run. The beat-local guard honours globs.
73
154
  *
155
+ * `declaredBy` maps each colliding path to the side that declared it —
156
+ * `'a'`, `'b'` or `'both'` — so a refusal can name its declarer.
157
+ *
74
158
  * @param {object} a
75
159
  * @param {object} b
76
160
  * @param {object} [options]
77
161
  * @param {boolean} [options.concreteOnly=false] Skip glob paths on both sides.
78
- * @returns {{ paths: string[], source: string }|null}
162
+ * @returns {{ paths: string[], source: string, declaredBy: Record<string, 'a'|'b'|'both'> }|null}
79
163
  */
80
164
  export function detectCollision(a, b, { concreteOnly = false } = {}) {
81
165
  const fa = storyFootprint(a);
@@ -83,14 +167,27 @@ export function detectCollision(a, b, { concreteOnly = false } = {}) {
83
167
  const fb = storyFootprint(b);
84
168
  if (fb.size === 0) return null;
85
169
 
86
- const hits = new Set();
87
- for (const path of fa) {
88
- if (!isGlobPath(path) && fb.has(path)) hits.add(path);
170
+ const pa = partition(fa);
171
+ const pb = partition(fb);
172
+ /** @type {Map<string, Set<string>>} */
173
+ const hits = new Map();
174
+ for (const path of pa.concrete) {
175
+ if (fb.has(path)) {
176
+ addHit(hits, path, 'a');
177
+ addHit(hits, path, 'b');
178
+ }
89
179
  }
90
180
  if (!concreteOnly) {
91
- collectGlobs(hits, fa);
92
- collectGlobs(hits, fb);
181
+ collectGlobHits(hits, pa, pb, 'a');
182
+ collectGlobHits(hits, pb, pa, 'b');
93
183
  }
94
184
  if (hits.size === 0) return null;
95
- return { paths: [...hits].sort(), source: OVERLAP_SOURCES.DECLARED };
185
+ const paths = [...hits.keys()].sort();
186
+ const declaredBy = Object.fromEntries(
187
+ paths.map((path) => {
188
+ const sides = hits.get(path);
189
+ return [path, sides.size === 2 ? 'both' : [...sides][0]];
190
+ }),
191
+ );
192
+ return { paths, source: OVERLAP_SOURCES.DECLARED, declaredBy };
96
193
  }
@@ -83,9 +83,9 @@ export function classifyStory(story) {
83
83
 
84
84
  /**
85
85
  * Beat-local overlap guard: `true` when two footprints intersect. A glob
86
- * (unknown width) overlaps everything, since exact-string comparison would
87
- * otherwise pass two Stories that really race; this fail-safe is beat-local
88
- * only.
86
+ * collides with every path it can match and with any glob whose static base
87
+ * overlaps its own, so the `**` UNKNOWN sentinel still collides with every
88
+ * declared footprint; honouring globs is beat-local only.
89
89
  *
90
90
  * @param {StoryRecord} a
91
91
  * @param {StoryRecord} b
@@ -282,6 +282,17 @@ function blockingCollision({ rec, id, selected, reserved, evidence }) {
282
282
  return peer ? { ...peer, scope: WITHHOLD_SCOPES.BEAT } : null;
283
283
  }
284
284
 
285
+ /**
286
+ * A withhold row keeps `paths` and `source` only — the ledger shape predates
287
+ * the collision's `declaredBy` attribution.
288
+ *
289
+ * @param {number|null} blockedBy
290
+ * @param {{ paths: string[], source: string }} collision
291
+ */
292
+ function blockerRow(blockedBy, { paths, source }) {
293
+ return { blockedBy, paths, source };
294
+ }
295
+
285
296
  /**
286
297
  * The same-beat peer this candidate would race, with the colliding paths, so
287
298
  * an unfilled slot is never unexplained.
@@ -294,7 +305,7 @@ function blockingCollision({ rec, id, selected, reserved, evidence }) {
294
305
  function findBeatBlocker(candidate, selected, options = {}) {
295
306
  for (const picked of selected) {
296
307
  const collision = detectCollision(picked, candidate, options);
297
- if (collision) return { blockedBy: storyIdOf(picked), ...collision };
308
+ if (collision) return blockerRow(storyIdOf(picked), collision);
298
309
  }
299
310
  return null;
300
311
  }
@@ -315,7 +326,7 @@ function findInFlightBlocker(candidate, candidateId, reserved, options = {}) {
315
326
  const heldId = storyIdOf(held);
316
327
  if (heldId === null || heldId === candidateId) continue;
317
328
  const collision = reservesConcretePath(held, candidate, options);
318
- if (collision) return { blockedBy: heldId, ...collision };
329
+ if (collision) return blockerRow(heldId, collision);
319
330
  }
320
331
  return null;
321
332
  }
@@ -56,6 +56,8 @@ const CLI_OPTIONS = {
56
56
  'source-tickets': { type: 'string' },
57
57
  'close-superseded': { type: 'boolean', default: true },
58
58
  'no-close-superseded': { type: 'boolean', default: false },
59
+ 'rewrite-source': { type: 'boolean', default: true },
60
+ 'no-rewrite-source': { type: 'boolean', default: false },
59
61
  'dry-run': { type: 'boolean', default: false },
60
62
  'force-review': { type: 'boolean', default: false },
61
63
  'epic-title': { type: 'string' },
@@ -66,7 +68,7 @@ const CLI_OPTIONS = {
66
68
  const USAGE =
67
69
  'Usage: plan-persist.js --stories <file> ' +
68
70
  '[--tech-spec <file>] [--plan-dir <dir>] [--plan-context <file>] ' +
69
- '[--source-tickets <ids>] [--no-close-superseded] ' +
71
+ '[--source-tickets <ids>] [--no-close-superseded] [--no-rewrite-source] ' +
70
72
  '[--dry-run] [--force-review] ' +
71
73
  '[--epic-title <text> --epic-goal <text> | --epic <id>]';
72
74
 
@@ -182,6 +184,17 @@ export function resolveEpicAdoptionId(values) {
182
184
  return id;
183
185
  }
184
186
 
187
+ /**
188
+ * A `--x` / `--no-x` pair: the negation always wins.
189
+ *
190
+ * @param {object} values
191
+ * @param {string} name
192
+ * @returns {boolean}
193
+ */
194
+ function negatableFlag(values, name) {
195
+ return values[`no-${name}`] !== true && values[name] !== false;
196
+ }
197
+
185
198
  /**
186
199
  * Where envelope-derived source ids meet the engine; a break here silently
187
200
  * un-wires `--tickets` superseding.
@@ -206,11 +219,8 @@ export function buildPersistOptions(values, paths, planContextEnvelope) {
206
219
  sourceTicketOrigin: source.origin,
207
220
  epic: resolveEpicRequest(values),
208
221
  adoptEpicId: resolveEpicAdoptionId(values),
209
- // `--no-close-superseded` always wins.
210
- closeSuperseded:
211
- values['no-close-superseded'] === true
212
- ? false
213
- : values['close-superseded'] !== false,
222
+ closeSuperseded: negatableFlag(values, 'close-superseded'),
223
+ rewriteSource: negatableFlag(values, 'rewrite-source'),
214
224
  };
215
225
  }
216
226
 
@@ -429,6 +439,10 @@ runAsCli(import.meta.url, main, {
429
439
  ['--source-tickets <ids>', 'Ticket ids this plan supersedes.'],
430
440
  ['--dry-run', 'Validate and report; create nothing.'],
431
441
  ['--no-close-superseded', 'Leave superseded source tickets open.'],
442
+ [
443
+ '--no-rewrite-source',
444
+ 'File a new Story for a one-for-one plan instead of rewriting its source ticket in place.',
445
+ ],
432
446
  [
433
447
  '--force-review',
434
448
  'Require the review gate even when it would be skipped.',