mandrel 2.79.0 → 2.80.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 (30) hide show
  1. package/.agents/agents/auditor.md +8 -3
  2. package/.agents/audit-checklists/data-model.md +9 -1
  3. package/.agents/docs/agentrc-reference.json +3 -0
  4. package/.agents/docs/configuration.md +1 -1
  5. package/.agents/docs/workflows.md +1 -1
  6. package/.agents/schemas/agentrc.schema.json +19 -1
  7. package/.agents/schemas/audit-rules.json +5 -1
  8. package/.agents/scripts/lib/audit-to-stories/seed-from-findings.js +37 -2
  9. package/.agents/scripts/lib/config/explain.js +1 -1
  10. package/.agents/scripts/lib/config-settings-schema.js +18 -1
  11. package/.agents/scripts/lib/findings/audit-finding-record.js +95 -0
  12. package/.agents/scripts/lib/findings/route-finding.js +4 -3
  13. package/.agents/scripts/lib/generated/agentrc-validator.js +1 -1
  14. package/.agents/scripts/lib/orchestration/plan-persist/audit-attribution.js +182 -0
  15. package/.agents/scripts/lib/orchestration/plan-persist/audit-provenance.js +11 -10
  16. package/.agents/scripts/lib/orchestration/plan-persist/collision-message.js +52 -0
  17. package/.agents/scripts/lib/orchestration/plan-persist/run-plan-persist.js +5 -3
  18. package/.agents/scripts/lib/orchestration/plan-persist/story-ops.js +28 -14
  19. package/.agents/scripts/lib/orchestration/plan-persist/wave-collision-gate.js +8 -4
  20. package/.agents/scripts/lib/orchestration/plan-persist/wave-serialisation.js +3 -2
  21. package/.agents/scripts/lib/qa/resolve-qa-contract.js +28 -9
  22. package/.agents/scripts/lib/templates/decomposer-prompts.js +2 -2
  23. package/.agents/scripts/lib/wave-runner/footprint.js +114 -17
  24. package/.agents/scripts/lib/wave-runner/ready-set.js +16 -5
  25. package/.agents/workflows/audit-data-model.md +94 -10
  26. package/.agents/workflows/audit-to-stories.md +22 -7
  27. package/.agents/workflows/helpers/audit-lens-core.md +8 -5
  28. package/.agents/workflows/helpers/plan-reference.md +11 -3
  29. package/docs/CHANGELOG.md +9 -0
  30. package/package.json +1 -1
@@ -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
+ }
@@ -458,8 +458,10 @@ export async function runPlanPersist({
458
458
  assemblePlanStories(rawStories, {
459
459
  sharedSpec: techSpecContent,
460
460
  sourceTicketIds,
461
- // Audit footers carried onto every Story that did not attribute its own
462
- // `provenance`; empty for a `--tickets` run.
461
+ // Audit footers for every Story without an authored `provenance`: an
462
+ // N>1 draft over a record-carrying seed attributes them per Story by
463
+ // `changes[]` coverage (unattributed findings ride on all and surface
464
+ // in `warnings`); otherwise the seed union. Empty for `--tickets`.
463
465
  provenanceSource: seedProvenance,
464
466
  });
465
467
 
@@ -467,7 +469,7 @@ export async function runPlanPersist({
467
469
  logWarnings(supersedeWarnings);
468
470
 
469
471
  // The dedup corpus is listed by `audit::*` label; footers alone leave the
470
- // Story invisible to an indexed sweep.
472
+ // Story invisible to an indexed sweep. Labels follow the stamped findings.
471
473
  const stories = withAuditLabels(assembled, seedProvenance);
472
474
 
473
475
  const assembledConflicts = analyzeAssembledStories({
@@ -24,6 +24,7 @@ import {
24
24
  concurrentMap,
25
25
  FANOUT_CONCURRENCY,
26
26
  } from '../../util/concurrent-map.js';
27
+ import { attributeSeedProvenance } from './audit-attribution.js';
27
28
  import {
28
29
  externalDependencyId,
29
30
  isExternalDependencyRef,
@@ -329,20 +330,21 @@ export function foldSpecIntoStoryBody(bodyObject, slug, opts = {}) {
329
330
 
330
331
  /**
331
332
  * An authored `provenance` stamps exactly the identities this Story owns;
332
- * otherwise the whole seed's footers are carried. Keep that union fallback:
333
- * without it a non-attributing plan persists Stories with no provenance and
334
- * the next audit sweep re-files planned work.
333
+ * otherwise the source `attributeSeedProvenance` resolved — the findings path
334
+ * attribution gave this Story, or the whole seed's union. Keep that union
335
+ * fallback: without it a non-attributing plan persists Stories with no
336
+ * provenance and the next audit sweep re-files planned work.
335
337
  *
336
338
  * @param {{ fingerprints: string[], semanticKeys: string[] }|null} provenance
337
- * @param {object} opts
339
+ * @param {string} resolved
338
340
  * @returns {string}
339
341
  */
340
- function resolveProvenanceSource(provenance, opts) {
342
+ function resolveProvenanceSource(provenance, resolved) {
341
343
  if (provenance !== null) return ownedProvenanceSource(provenance);
342
- return opts.provenanceSource ?? '';
344
+ return resolved;
343
345
  }
344
346
 
345
- function assembleOnePlanStory(ticket, opts) {
347
+ function assembleOnePlanStory(normalized, attributed, opts) {
346
348
  const {
347
349
  slug,
348
350
  title,
@@ -351,7 +353,7 @@ function assembleOnePlanStory(ticket, opts) {
351
353
  labels,
352
354
  supersedes,
353
355
  provenance,
354
- } = normalizeStoryTicket(ticket);
356
+ } = normalized;
355
357
  const { bodyObject: folded } = foldSpecIntoStoryBody(bodyObject, slug, {
356
358
  sharedSpec: opts.sharedSpec ?? null,
357
359
  });
@@ -359,7 +361,7 @@ function assembleOnePlanStory(ticket, opts) {
359
361
  // Mechanical on purpose: the authoring agent is not asked to hand-carry
360
362
  // audit footers. A non-audit seed has none, so this is a no-op there.
361
363
  const { body } = carryProvenanceFooters({
362
- from: resolveProvenanceSource(provenance, opts),
364
+ from: resolveProvenanceSource(provenance, attributed),
363
365
  into: serialized,
364
366
  });
365
367
  const fingerprint = planStoryFingerprint({ slug, title, body });
@@ -402,6 +404,8 @@ function assertSharedSpecAllowed(tickets, sharedSpec) {
402
404
  * @param {object} [opts]
403
405
  * @param {string|null} [opts.sharedSpec]
404
406
  * @param {number[]} [opts.sourceTicketIds] Ids passed to `/mandrel-plan --tickets`.
407
+ * @param {string} [opts.provenanceSource] The seed's provenance footers; an
408
+ * N>1 draft attributes its `audit-finding` records per Story.
405
409
  * @returns {{ stories: Array<{ slug: string, title: string, body: string, acceptance: string[], depends_on: string[], supersedes: Array<{ id: number, note: string|null }> }>, warnings: string[] }}
406
410
  */
407
411
  export function assemblePlanStories(tickets, opts = {}) {
@@ -413,14 +417,24 @@ export function assemblePlanStories(tickets, opts = {}) {
413
417
 
414
418
  assertSharedSpecAllowed(tickets, opts.sharedSpec);
415
419
 
420
+ const normalized = tickets.map(normalizeStoryTicket);
421
+ const attribution = attributeSeedProvenance(
422
+ normalized.map((n) => ({
423
+ provenance: n.provenance,
424
+ changes: n.bodyObject.changes,
425
+ })),
426
+ opts.provenanceSource,
427
+ );
416
428
  const stories = orderStoriesByDependencies(
417
- tickets.map((ticket) => assembleOnePlanStory(ticket, opts).story),
429
+ normalized.map(
430
+ (n, i) => assembleOnePlanStory(n, attribution.sources[i], opts).story,
431
+ ),
418
432
  );
419
433
 
420
- const warnings = resolveSupersedePartition(
421
- stories,
422
- opts.sourceTicketIds ?? [],
423
- );
434
+ const warnings = [
435
+ ...attribution.warnings,
436
+ ...resolveSupersedePartition(stories, opts.sourceTicketIds ?? []),
437
+ ];
424
438
 
425
439
  return { stories, warnings };
426
440
  }
@@ -5,6 +5,7 @@
5
5
  * @module lib/orchestration/plan-persist/wave-collision-gate
6
6
  */
7
7
 
8
+ import { declarerClauses } from './collision-message.js';
8
9
  import { predictWaveSerialisation } from './wave-serialisation.js';
9
10
 
10
11
  /**
@@ -27,12 +28,15 @@ function withDeclaredFootprint(story) {
27
28
  }
28
29
 
29
30
  /**
30
- * @param {{ wave: number, slugs: [string, string], paths: string[], source: string }} collision
31
+ * One refusal line per colliding path, each naming its declarer.
32
+ *
33
+ * @param {{ wave: number, slugs: [string, string], paths: string[], source: string, declaredBy?: Record<string, string> }} collision
31
34
  * @returns {string}
32
35
  */
33
- function formatCollision({ wave, slugs, paths, source }) {
34
- const declared = paths.map((p) => `\`${p}\``).join(', ');
35
- return ` - wave ${wave}: "${slugs[0]}" + "${slugs[1]}" both declare ${declared} (${source})`;
36
+ function formatCollision({ wave, source, ...collision }) {
37
+ return declarerClauses(collision)
38
+ .map((clause) => ` - wave ${wave}: ${clause} (${source})`)
39
+ .join('\n');
36
40
  }
37
41
 
38
42
  /**
@@ -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
  }
@@ -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.