bmad-method-test-architecture-enterprise 3.5.0 → 3.6.1

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.
@@ -4,8 +4,9 @@ const fs = require('node:fs');
4
4
  const path = require('node:path');
5
5
  const yaml = require('js-yaml');
6
6
  const MarkdownIt = require('markdown-it');
7
+ const TOML = require('smol-toml');
7
8
  const { readInput } = require('./workflow-cli');
8
- const { liveReference } = require('./trace-live');
9
+ const { liveAliasMap, liveReference, localId } = require('./trace-live');
9
10
 
10
11
  const GATE_TYPES = ['story', 'epic', 'release', 'hotfix'];
11
12
  const COLLECTION_MODES = [
@@ -29,7 +30,8 @@ function criterionText(value) {
29
30
  )
30
31
  .join('')
31
32
  .replaceAll(/\s+/g, ' ')
32
- .trim();
33
+ .trim()
34
+ .replace(/\.$/, ''); // a trailing sentence period is presentation, not requirement text
33
35
  }
34
36
 
35
37
  function slug(value) {
@@ -45,6 +47,119 @@ function inputError(message) {
45
47
  return Object.assign(new Error(message), { code: 'TRACE_INPUT_INVALID' });
46
48
  }
47
49
 
50
+ const ORACLE_ID = /^[A-Za-z0-9._-]+$/;
51
+ const LEAF_TYPES = new Set(['story', 'spike', 'bug']);
52
+
53
+ /** YAML frontmatter and the body with frontmatter lines blanked, so Markdown line maps stay file line numbers. */
54
+ function frontmatter(text) {
55
+ const match = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
56
+ if (!match) return { data: null, body: text };
57
+ let data = null;
58
+ try {
59
+ data = yaml.load(match[1]);
60
+ } catch {
61
+ data = null;
62
+ }
63
+ return {
64
+ data: data && typeof data === 'object' && !Array.isArray(data) ? data : null,
65
+ body: `${'\n'.repeat(match[0].split('\n').length - 1)}${text.slice(match[0].length)}`,
66
+ };
67
+ }
68
+
69
+ function readToml(file) {
70
+ try {
71
+ return TOML.parse(fs.readFileSync(file, 'utf8'));
72
+ } catch (error) {
73
+ throw inputError(`Cannot read ${file}: ${error.message}`);
74
+ }
75
+ }
76
+
77
+ /** The epic id an initiative's `tickets/tickets.toml` gives the epic folder, or null when it does not number it. */
78
+ function epicNumber(tickets, folder) {
79
+ const index = path.join(tickets, 'tickets.toml');
80
+ if (!fs.existsSync(index)) return null;
81
+ const epics = readToml(index).epic ?? [];
82
+ if (!Array.isArray(epics)) throw inputError(`${index} must list epics as [[epic]] tables.`);
83
+ const numbered = epics.filter((epic) => epic?.slug === folder);
84
+ if (numbered.length > 1) throw inputError(`${index} lists ${folder} more than once.`);
85
+ return numbered[0]?.id === undefined ? null : String(numbered[0].id);
86
+ }
87
+
88
+ /**
89
+ * A v7 epic file is `initiative-<i>/tickets/<epic folder>/<epic folder>.md`. Its key follows the
90
+ * story contract: `<i>--e<epic id>` when the initiative's tickets.toml numbers it, else `<i>--<epic folder>`.
91
+ */
92
+ function nativeEpic(document) {
93
+ const folder = path.basename(path.dirname(document));
94
+ const tickets = path.dirname(path.dirname(document));
95
+ const initiativeFolder = path.basename(path.dirname(tickets));
96
+ if (
97
+ path.basename(document) !== `${folder}.md` ||
98
+ !folder.startsWith('epic-') ||
99
+ path.basename(tickets) !== 'tickets' ||
100
+ !initiativeFolder.startsWith('initiative-')
101
+ )
102
+ return null;
103
+ const initiative = initiativeFolder.slice('initiative-'.length);
104
+ const epicId = epicNumber(tickets, folder);
105
+ const epicKey = epicId === null ? `${initiative}--${folder}` : `${initiative}--e${epicId}`;
106
+ if (!initiative || initiative.includes('--') || folder.includes('--') || !ORACLE_ID.test(epicKey))
107
+ throw inputError(
108
+ `Cannot form a v7 epic key from ${document}; initiative and epic folders need letters, digits, ".", "_" or "-" and no "--".`,
109
+ );
110
+ return { initiative, epicId, epicFolder: folder, epicKey };
111
+ }
112
+
113
+ /**
114
+ * A v7 story leaf, keyed by the story contract (section 4): `initiative-<i>/tickets/epic-<slug>/tickets/<leaf>.md`
115
+ * is `<i>--e<epic id>-s<entry id>` (`<i>--<epic folder>-s<entry id>` for an unnumbered epic), a leaf in
116
+ * `initiative-<i>/tickets/` is `<i>--s<entry id>`, and `backlog/<leaf>.md` is `backlog--<leaf stem>`.
117
+ * The entry id is the leaf's frontmatter `id`; a leaf's frontmatter `type` is story, spike or bug.
118
+ */
119
+ function nativeStory(projectRoot, document, text) {
120
+ if (path.extname(document) !== '.md' || document.endsWith('-plan.md')) return null;
121
+ const meta = frontmatter(text).data;
122
+ if (!meta || !LEAF_TYPES.has(meta.type)) return null;
123
+ const folder = path.dirname(document);
124
+ let storyId;
125
+ let storyKey;
126
+ let container = folder;
127
+ let parts;
128
+ if (path.basename(folder) === 'backlog') {
129
+ storyId = path.basename(document);
130
+ storyKey = `backlog--${path.basename(document, '.md')}`;
131
+ parts = [path.basename(document, '.md')];
132
+ } else {
133
+ if (path.basename(folder) !== 'tickets' || meta.id === undefined || meta.id === null || !String(meta.id).trim()) return null;
134
+ const entry = String(meta.id).trim();
135
+ container = path.dirname(folder);
136
+ const owner = path.basename(container);
137
+ if (owner.startsWith('initiative-')) {
138
+ const initiative = owner.slice('initiative-'.length);
139
+ [storyId, storyKey, parts] = [entry, `${initiative}--s${entry}`, [initiative, entry]];
140
+ } else {
141
+ const tickets = path.dirname(container);
142
+ const initiativeFolder = path.basename(path.dirname(tickets));
143
+ if (!owner.startsWith('epic-') || path.basename(tickets) !== 'tickets' || !initiativeFolder.startsWith('initiative-')) return null;
144
+ const initiative = initiativeFolder.slice('initiative-'.length);
145
+ const epicId = epicNumber(tickets, owner);
146
+ storyId = epicId === null ? entry : `${epicId}.${entry}`;
147
+ storyKey = epicId === null ? `${initiative}--${owner}-s${entry}` : `${initiative}--e${epicId}-s${entry}`;
148
+ parts = [initiative, owner, entry];
149
+ }
150
+ }
151
+ if (parts.some((part) => !part || part.includes('--')) || !ORACLE_ID.test(storyKey))
152
+ throw inputError(
153
+ `Cannot form a v7 story key from ${document}; initiative, epic folder, entry id and leaf name need letters, digits, ".", "_" or "-" and no "--".`,
154
+ );
155
+ return {
156
+ storyId,
157
+ storyKey,
158
+ ticketRef: `${storyId} @ ${path.relative(path.resolve(projectRoot), container).split(path.sep).join('/')}`,
159
+ storyFile: document,
160
+ };
161
+ }
162
+
48
163
  /** Resolve the scope once, before allocating outputs or invoking a vendor. */
49
164
  function resolveTraceTarget({ projectRoot, target, targetId, gateType }) {
50
165
  let document = null;
@@ -59,24 +174,57 @@ function resolveTraceTarget({ projectRoot, target, targetId, gateType }) {
59
174
  if (!text.trim()) throw inputError(`--target ${document} is empty.`);
60
175
  }
61
176
  const basename = document ? path.basename(document, path.extname(document)) : '';
62
- const tokens = new MarkdownIt().parse(text, {});
177
+ const tokens = new MarkdownIt().parse(frontmatter(text).body, {});
63
178
  const headingIndex = tokens.findIndex((token) => token.type === 'heading_open' && token.tag === 'h1');
64
179
  const heading = headingIndex === -1 ? '' : tokens[headingIndex + 1].content;
65
- const inferred =
66
- /^story\b/i.test(heading) || /^\d+[.-]\d+[-.]/.test(basename) || /^story[-.]/i.test(basename)
180
+ // The native v7 shapes decide the type before any heading does: an epic titled "Story publishing" is still an epic.
181
+ const native = document && (gateType === undefined || gateType === 'epic') ? nativeEpic(document) : null;
182
+ const leaf = document && !native && (gateType === undefined || gateType === 'story') ? nativeStory(projectRoot, document, text) : null;
183
+ const inferred = native
184
+ ? 'epic'
185
+ : leaf
67
186
  ? 'story'
68
- : /^epic\b/i.test(heading) || /^epic[-.]/i.test(basename)
69
- ? 'epic'
70
- : /^release\b/i.test(heading)
71
- ? 'release'
72
- : /^hotfix\b/i.test(heading)
73
- ? 'hotfix'
74
- : null;
187
+ : /^story\b/i.test(heading) || /^\d+[.-]\d+[-.]/.test(basename) || /^story[-.]/i.test(basename)
188
+ ? 'story'
189
+ : /^epic\b/i.test(heading) || /^epic[-.]/i.test(basename)
190
+ ? 'epic'
191
+ : /^release\b/i.test(heading)
192
+ ? 'release'
193
+ : /^hotfix\b/i.test(heading)
194
+ ? 'hotfix'
195
+ : null;
75
196
  const type = gateType ?? inferred ?? 'story';
76
197
  if (!GATE_TYPES.includes(type)) throw inputError(`--gate-type must be one of ${GATE_TYPES.join(', ')}.`);
77
198
 
78
199
  let id = targetId?.trim();
79
200
  if (targetId !== undefined && !id) throw inputError('--target-id must be non-empty.');
201
+ if (native) {
202
+ // Keep `--`: slugging would merge two initiatives' epic 1 into one run key.
203
+ if (id && id !== native.epicKey && id !== native.epicId)
204
+ throw inputError(`--target-id ${id} does not name the v7 epic ${native.epicKey}.`);
205
+ return {
206
+ type,
207
+ id: native.epicKey,
208
+ label: heading || `Epic ${native.epicKey}`,
209
+ runScope: type,
210
+ runKey: `epic-${native.epicKey}`,
211
+ document,
212
+ ...native,
213
+ };
214
+ }
215
+ if (leaf) {
216
+ if (id && id !== leaf.storyId && id !== leaf.storyKey)
217
+ throw inputError(`--target-id ${id} does not name the v7 story ${leaf.storyKey}.`);
218
+ return {
219
+ type,
220
+ id: leaf.storyId,
221
+ label: heading || `Story ${leaf.storyId}`,
222
+ runScope: type,
223
+ runKey: `story-${leaf.storyKey}`,
224
+ document,
225
+ ...leaf,
226
+ };
227
+ }
80
228
  if (!id && type === 'epic') {
81
229
  id = heading.match(/^Epic\s+(\d+)\b/i)?.[1] ?? basename.match(/^epic[-.](\d+)(?:[-.]|$)/i)?.[1];
82
230
  if (!id && document) id = slug(heading || basename);
@@ -116,8 +264,93 @@ function readJson(file) {
116
264
  return value;
117
265
  }
118
266
 
119
- /** Capture explicitly identified requirements from the caller's source before execution. */
120
- function sourceOracleLedger(text, source) {
267
+ /** Strip `*` and backtick formatting from a table cell, heading label, or identifier. */
268
+ const bare = (value) => value.replaceAll(/[*`]/g, '').trim();
269
+
270
+ /**
271
+ * Split `<id><annotations>: <body>`. Emphasis and code markers are stripped only around the id and its
272
+ * annotations; the body keeps every literal character, so `*.json`, `2 * 3` and `` `*` `` survive capture.
273
+ */
274
+ function splitClaim(line, idPattern, annotationPattern) {
275
+ const marks = '[*`]*';
276
+ const match = new RegExp(`^(${marks})(${idPattern})(${marks})(${annotationPattern})(${marks})\\s*:`).exec(line);
277
+ if (!match) return null;
278
+ // Markers opened before the id and still open after the annotations close right after the colon.
279
+ const open = match[1].length - match[3].length - match[5].length;
280
+ let body = line.slice(match[0].length);
281
+ if (open > 0) body = body.replace(new RegExp(`^[*\`]{0,${open}}`), '');
282
+ body = body.trim();
283
+ return body ? { id: match[2], annotations: match[4], body } : null;
284
+ }
285
+
286
+ /**
287
+ * Capture a v7 epic's `R<n> (<parent or source>): <line>` Requirements lines as `<epic key>--R<n>`.
288
+ * A priority is explicit only as a `P0`-`P3` annotation before the colon or a trailing `(P<n>)`.
289
+ */
290
+ function epicRequirementLedger(text, source, epicKey) {
291
+ const tokens = new MarkdownIt().parse(text, {});
292
+ const ledger = new Map();
293
+ let section = 0; // heading depth of the open Requirements section; 0 outside it
294
+ for (let index = 0; index < tokens.length; index++) {
295
+ const token = tokens[index];
296
+ if (token.type === 'heading_open') {
297
+ const depth = Number(token.tag.slice(1));
298
+ if (section && depth <= section) section = 0;
299
+ if (/^requirements$/i.test(bare(tokens[index + 1].content))) section = depth;
300
+ continue;
301
+ }
302
+ if (!section || token.type !== 'inline' || tokens[index - 1]?.type === 'heading_open') continue;
303
+ let pending;
304
+ const flush = () => {
305
+ if (!pending) return;
306
+ const existing = ledger.get(pending.id);
307
+ if (existing)
308
+ throw inputError(
309
+ `Epic ${epicKey} defines ${localId(pending.id)} twice, at ${existing.source} and ${pending.source}; give each requirement its own id before tracing.`,
310
+ );
311
+ ledger.set(pending.id, pending);
312
+ };
313
+ for (const [offset, line] of token.content.split('\n').entries()) {
314
+ const claim = splitClaim(line, String.raw`R\d+`, String.raw`(?:\s*\([^)]*\))*`);
315
+ if (!claim) {
316
+ if (pending) pending.requirement += `\n${line}`;
317
+ continue;
318
+ }
319
+ flush();
320
+ const annotated = [...claim.annotations.matchAll(/\(([^)]*)\)/g)]
321
+ .flatMap((group) => group[1].split(','))
322
+ .map((part) => bare(part))
323
+ .filter((part) => /^P[0-3]$/.test(part));
324
+ const trailing = /\((P[0-3])\)\s*$/.exec(claim.body)?.[1];
325
+ const priorities = new Set([...annotated, trailing].filter(Boolean));
326
+ if (priorities.size > 1) throw inputError(`Epic ${epicKey} gives ${claim.id} conflicting priorities.`);
327
+ pending = {
328
+ id: `${epicKey}--${claim.id}`,
329
+ priority: [...priorities][0] ?? null,
330
+ requirement: claim.body,
331
+ source: `${source}:${(token.map?.[0] ?? 0) + offset + 1}`,
332
+ };
333
+ }
334
+ flush();
335
+ }
336
+ return [...ledger.values()];
337
+ }
338
+
339
+ /** True when the frozen ledger holds a native v7 epic's Requirements lines (the requirement oracle). */
340
+ function requirementOracle(target, ledger) {
341
+ const prefix = target?.epicKey ? `${target.epicKey}--` : null;
342
+ return Boolean(prefix) && ledger.length > 0 && ledger.every((row) => row.id.startsWith(prefix) && /^R\d+$/.test(localId(row.id)));
343
+ }
344
+
345
+ /**
346
+ * Capture explicitly identified requirements from the caller's source before execution. A native
347
+ * v7 epic with `R<n>` Requirements lines yields those lines; every other source yields its AC/FR/NFR/REQ claims.
348
+ */
349
+ function sourceOracleLedger(text, source, target) {
350
+ if (target?.epicKey) {
351
+ const requirements = epicRequirementLedger(text, source, target.epicKey);
352
+ if (requirements.length > 0) return requirements;
353
+ }
121
354
  const tokens = new MarkdownIt().parse(text, {});
122
355
  const ledger = new Map();
123
356
  const add = (id, priority, requirement, line) => {
@@ -142,19 +375,20 @@ function sourceOracleLedger(text, source) {
142
375
  if (tokens[index].type === 'tr_open') {
143
376
  row = [];
144
377
  line = (tokens[index].map?.[0] ?? token.map?.[0] ?? 0) + 1;
145
- } else if (tokens[index].type === 'inline' && row) row.push(tokens[index].content.replaceAll(/[*`]/g, '').trim());
378
+ } else if (tokens[index].type === 'inline' && row) row.push(tokens[index].content.trim());
146
379
  else if (tokens[index].type === 'tr_close') rows.push({ cells: row, line });
147
380
  }
148
- const header = rows.shift()?.cells ?? [];
381
+ const header = (rows.shift()?.cells ?? []).map(bare);
149
382
  const idIndex = header.findIndex((cell) => /^(?:id|criterion|criterion id|requirement id)$/i.test(cell));
150
383
  const requirementIndex = header.findIndex((cell) => /^(?:requirement|criterion text)$/i.test(cell));
151
384
  const priorityIndex = header.findIndex((cell) => /^priority$/i.test(cell));
152
385
  if (idIndex === -1 || requirementIndex === -1) continue;
153
386
  for (const { cells, line } of rows) {
154
- const priority = priorityIndex === -1 ? '' : cells[priorityIndex];
387
+ const priority = priorityIndex === -1 ? '' : bare(cells[priorityIndex] ?? '');
155
388
  if (priority && !/^P[0-3]$/.test(priority)) throw inputError('Source oracle has invalid priority.');
156
- if (!cells[idIndex] || !cells[requirementIndex]) throw inputError('Source oracle has an incomplete criterion row.');
157
- add(cells[idIndex], priority, cells[requirementIndex], line);
389
+ const id = bare(cells[idIndex] ?? '');
390
+ if (!id || !cells[requirementIndex]) throw inputError('Source oracle has an incomplete criterion row.');
391
+ add(id, priority, cells[requirementIndex], line);
158
392
  }
159
393
  } else if (token.type === 'inline' && !(tokens[index - 1]?.type === 'heading_open' && tokens[index - 1].tag === 'h1')) {
160
394
  let pending;
@@ -162,13 +396,16 @@ function sourceOracleLedger(text, source) {
162
396
  if (pending) add(pending.id, pending.priority, pending.requirement, pending.line);
163
397
  };
164
398
  for (const [offset, line] of token.content.split('\n').entries()) {
165
- const claim = /^((?:AC|FR|NFR|REQ)[-_.]?\d+(?:[-_.]\d+)*)(?:\s*\((P[0-3])\))?\s*:\s*(.+)/.exec(line.replaceAll(/[*`]/g, ''));
399
+ const claim = splitClaim(line, String.raw`(?:AC|FR|NFR|REQ)[-_.]?\d+(?:[-_.]\d+)*`, String.raw`(?:\s*\(P[0-3]\))?`);
166
400
  if (claim) {
167
401
  flush();
168
402
  pending = {
169
- id: claim[1],
170
- priority: claim[2] ?? /\((P[0-3])\)\s*$/.exec(claim[3])?.[1] ?? /\b(P[0-3])\b/.exec(claim[3])?.[1],
171
- requirement: claim[3],
403
+ id: claim.id,
404
+ priority:
405
+ /\((P[0-3])\)/.exec(claim.annotations)?.[1] ??
406
+ /\((P[0-3])\)\s*$/.exec(claim.body)?.[1] ??
407
+ /\b(P[0-3])\b/.exec(claim.body)?.[1],
408
+ requirement: claim.body,
172
409
  line: (token.map?.[0] ?? 0) + offset + 1,
173
410
  };
174
411
  } else if (pending) pending.requirement += `\n${line}`;
@@ -179,8 +416,677 @@ function sourceOracleLedger(text, source) {
179
416
  return [...ledger.values()];
180
417
  }
181
418
 
182
- /** Reconcile the saved Step 1 ledger with the caller's frozen source claims. */
183
- function oracleReference(progress, sourceLedger, required, allowLegacyExplicitOracle) {
419
+ const sameSet = (list, expected) =>
420
+ Array.isArray(list) && list.length === expected.size && new Set(list).size === list.length && list.every((item) => expected.has(item));
421
+
422
+ function validOracleRow(row) {
423
+ return (
424
+ row &&
425
+ typeof row.id === 'string' &&
426
+ Boolean(row.id.trim()) &&
427
+ /^P[0-3]$/.test(row.priority) &&
428
+ typeof row.requirement === 'string' &&
429
+ Boolean(row.requirement.trim()) &&
430
+ typeof row.source === 'string' &&
431
+ Boolean(row.source.trim())
432
+ );
433
+ }
434
+
435
+ const PRIORITY_RANK = { P0: 0, P1: 1, P2: 2, P3: 3 };
436
+ const COVERAGE = new Set(['FULL', 'PARTIAL', 'NONE', 'UNIT-ONLY', 'INTEGRATION-ONLY']);
437
+
438
+ /** A heading's section: every token until the next heading at the same or a higher level. */
439
+ function sections(tokens, title) {
440
+ const found = [];
441
+ for (let index = 0; index < tokens.length; index++) {
442
+ if (tokens[index].type !== 'heading_open' || !title.test(bare(tokens[index + 1].content))) continue;
443
+ const depth = Number(tokens[index].tag.slice(1));
444
+ let end = index + 1;
445
+ while (end < tokens.length && !(tokens[end].type === 'heading_open' && Number(tokens[end].tag.slice(1)) <= depth)) end++;
446
+ found.push(tokens.slice(index + 3, end));
447
+ }
448
+ return found;
449
+ }
450
+
451
+ /** A parenthesised group holding only `R` ids and priorities, such as `(R1, R3)`, `(P0)` or `(R2, P1)`. */
452
+ const ANNOTATION = /\(\s*(?:R\d+|P[0-3])(?:[\s,]+(?:R\d+|P[0-3]))*\s*\)/gi;
453
+ const VERIFY_LINE = /^\s*[*`]*Verify[*`]*\s*:[*`]*\s*(.+)$/i;
454
+
455
+ /**
456
+ * Every top-level item of the lists in `tokens` (ordered lists only when `ordered`), as the inline
457
+ * content of the whole item, nested lines included, and the file line where the item starts.
458
+ */
459
+ function topListItems(tokens, ordered) {
460
+ const items = [];
461
+ let depth = 0;
462
+ let accepted = false;
463
+ let current = null;
464
+ for (const token of tokens) {
465
+ if (token.type === 'ordered_list_open' || token.type === 'bullet_list_open') {
466
+ depth++;
467
+ if (depth === 1) accepted = !ordered || token.type === 'ordered_list_open';
468
+ } else if (token.type === 'ordered_list_close' || token.type === 'bullet_list_close') depth--;
469
+ else if (token.type === 'list_item_open' && depth === 1 && accepted) current = { parts: [], line: (token.map?.[0] ?? 0) + 1 };
470
+ else if (token.type === 'list_item_close' && depth === 1 && current) {
471
+ items.push(current);
472
+ current = null;
473
+ } else if (token.type === 'inline' && current) current.parts.push(token.content);
474
+ // Fenced and indented code inside an item is part of the criterion (a Gherkin scenario, an expected body).
475
+ else if (token.type === 'fence' && current) current.parts.push(`${token.markup}${token.info}\n${token.content}${token.markup}`);
476
+ else if (token.type === 'code_block' && current) current.parts.push(token.content);
477
+ }
478
+ return items.map(({ parts, line }) => ({ content: parts.join('\n'), line }));
479
+ }
480
+
481
+ /**
482
+ * One criterion from a list item: its name (the leading bold label, else its first line), both without
483
+ * the parenthesised `R` ids or priority; its full text; its declared `R` ids and explicit priority.
484
+ */
485
+ function capturedCriterion(item, file) {
486
+ const first = item.content.split('\n')[0].trim();
487
+ const bold = /^\*\*(.+?)\*\*\s*(.*)$/.exec(first);
488
+ const annotations = bold ? [...bold[2].matchAll(/\(([^)]*)\)/g)].map((group) => group[1]) : (first.match(ANNOTATION) ?? []);
489
+ const parts = annotations.flatMap((group) =>
490
+ group
491
+ .replaceAll(/[()]/g, '')
492
+ .split(/[\s,]+/)
493
+ .map(bare),
494
+ );
495
+ const name = (bold ? bold[1] : first.replaceAll(ANNOTATION, '')).replaceAll(/\s+/g, ' ').trim().replace(/\s*:$/, '');
496
+ return {
497
+ name,
498
+ text: item.content,
499
+ links: [...new Set(parts.filter((part) => /^R\d+$/.test(part)))],
500
+ priority: parts.find((part) => /^P[0-3]$/.test(part)) ?? null,
501
+ file,
502
+ line: item.line,
503
+ };
504
+ }
505
+
506
+ /**
507
+ * A pulled leaf's numbered criteria: a story's under `## Requirements`, a bug's or spike's under
508
+ * `## Acceptance Criteria`; plus its `Verify:` line and that line's number.
509
+ */
510
+ function leafCriteria(text, file) {
511
+ const { body } = frontmatter(text);
512
+ const tokens = new MarkdownIt().parse(body, {});
513
+ const criteria = sections(tokens, /^(?:requirements|acceptance criteria)$/i)
514
+ .flatMap((section) => topListItems(section, true))
515
+ .map((item) => capturedCriterion(item, file));
516
+ let verify = null;
517
+ for (const section of sections(tokens, /^requirements$/i)) {
518
+ let item = 0;
519
+ for (const token of section) {
520
+ if (token.type === 'list_item_open') item++;
521
+ else if (token.type === 'list_item_close') item--;
522
+ else if (token.type === 'inline' && item === 0 && verify === null) {
523
+ for (const [offset, line] of token.content.split('\n').entries()) {
524
+ const match = VERIFY_LINE.exec(line);
525
+ if (match) {
526
+ verify = { text: match[1].trim(), file, line: (token.map?.[0] ?? 0) + offset + 1 };
527
+ break;
528
+ }
529
+ }
530
+ }
531
+ }
532
+ }
533
+ if (verify === null && criteria.length === 0) {
534
+ const lines = body.split(/\r?\n/);
535
+ const index = lines.findIndex((line) => VERIFY_LINE.test(line));
536
+ if (index !== -1) verify = { text: VERIFY_LINE.exec(lines[index])[1].trim(), file, line: index + 1 };
537
+ }
538
+ return { criteria, verify };
539
+ }
540
+
541
+ /**
542
+ * A build plan's acceptance criteria: the list under an Acceptance Criteria heading, or the list after
543
+ * the bold `**Acceptance Criteria:**` label in `## Tasks & Acceptance`. `## Prior builds` is history.
544
+ */
545
+ function planCriteria(text, file) {
546
+ const parsed = new MarkdownIt().parse(frontmatter(text).body, {});
547
+ const tokens = [];
548
+ let history = 0; // heading depth of an open `## Prior builds` section; 0 outside it
549
+ for (const [index, token] of parsed.entries()) {
550
+ if (token.type === 'heading_open') {
551
+ const depth = Number(token.tag.slice(1));
552
+ if (history && depth <= history) history = 0;
553
+ if (!history && /^prior builds$/i.test(bare(parsed[index + 1].content))) history = depth;
554
+ }
555
+ if (!history) tokens.push(token);
556
+ }
557
+ const items = sections(tokens, /^acceptance criteria$/i).flatMap((section) => topListItems(section, false));
558
+ for (const section of sections(tokens, /^tasks\s*(?:&|and)\s*acceptance$/i)) {
559
+ for (let index = 0; index < section.length; index++) {
560
+ const label = section[index].type === 'inline' && /^\*\*Acceptance Criteria:?\*\*:?$/i.test(section[index].content.trim());
561
+ if (!label) continue;
562
+ let start = index + 1;
563
+ while (start < section.length && section[start].type === 'paragraph_close') start++;
564
+ if (!['bullet_list_open', 'ordered_list_open'].includes(section[start]?.type)) continue;
565
+ let end = start;
566
+ for (let depth = 0; end < section.length; end++) {
567
+ if (section[end].type.endsWith('_list_open')) depth++;
568
+ else if (section[end].type.endsWith('_list_close') && --depth === 0) break;
569
+ }
570
+ items.push(...topListItems(section.slice(start, end + 1), false));
571
+ }
572
+ }
573
+ return items.toSorted((left, right) => left.line - right.line).map((item) => capturedCriterion(item, file));
574
+ }
575
+
576
+ /** The line of each `[[entry]]` table's `verify` key in a tickets.toml, in entry order; null when absent. */
577
+ function tomlVerifyLines(text) {
578
+ const lines = [];
579
+ let current = -1;
580
+ for (const [index, line] of text.split(/\r?\n/).entries()) {
581
+ if (/^\s*\[\[\s*entry\s*\]\]/.test(line)) {
582
+ lines.push(null);
583
+ current = lines.length - 1;
584
+ } else if (/^\s*\[/.test(line)) current = -1;
585
+ else if (current !== -1 && lines[current] === null && /^\s*verify\s*=/.test(line)) lines[current] = index + 1;
586
+ }
587
+ return lines;
588
+ }
589
+
590
+ /**
591
+ * Independently capture the epic's tickets before the agent runs: every `[[entry]]` of the epic's
592
+ * `tickets/tickets.toml` and the criteria the story contract selects for it (section 2): the pulled
593
+ * leaf's numbered criteria; else, when the ticket has only a verify line, its plan's acceptance criteria;
594
+ * else its verify line. `files` holds every file read, so the CLI can protect them as inputs.
595
+ */
596
+ function epicTicketSources(projectRoot, target) {
597
+ const epicDir = path.dirname(target.document);
598
+ const ticketsDir = path.join(epicDir, 'tickets');
599
+ const index = path.join(ticketsDir, 'tickets.toml');
600
+ const files = new Map();
601
+ const read = (file) => {
602
+ const text = fs.readFileSync(file, 'utf8');
603
+ files.set(file, text);
604
+ return text;
605
+ };
606
+ read(target.document);
607
+ let entries = [];
608
+ let verifyLines = [];
609
+ if (fs.existsSync(index)) {
610
+ verifyLines = tomlVerifyLines(read(index));
611
+ entries = readToml(index).entry ?? [];
612
+ if (!Array.isArray(entries)) throw inputError(`${index} must list stories as [[entry]] tables.`);
613
+ }
614
+ const leaves = new Map();
615
+ const plans = new Map();
616
+ if (fs.existsSync(ticketsDir) && fs.statSync(ticketsDir).isDirectory()) {
617
+ for (const name of fs.readdirSync(ticketsDir).toSorted()) {
618
+ const file = path.join(ticketsDir, name);
619
+ if (!name.endsWith('.md') || !fs.statSync(file).isFile()) continue;
620
+ const meta = frontmatter(read(file)).data;
621
+ const [owners, key] = name.endsWith('-plan.md') ? [plans, meta?.ticket] : [leaves, meta?.id];
622
+ if (key === undefined || key === null) continue;
623
+ if (owners.has(String(key))) throw inputError(`${ticketsDir} holds two ${owners === plans ? 'plans' : 'leaves'} for entry ${key}.`);
624
+ owners.set(String(key), file);
625
+ }
626
+ }
627
+ const seen = new Set();
628
+ return {
629
+ root: path.resolve(projectRoot),
630
+ epicDir,
631
+ index,
632
+ files,
633
+ entries: entries.map((entry, position) => {
634
+ const id = entry?.id === undefined || entry?.id === null ? '' : String(entry.id).trim();
635
+ const storyKey = `${target.epicKey}-s${id}`;
636
+ if (!id || id.includes('--') || !ORACLE_ID.test(storyKey) || seen.has(id))
637
+ throw inputError(`${index} has an entry with a missing, malformed or repeated id.`);
638
+ seen.add(id);
639
+ // Once pulled, the leaf is the ticket: its `covers` and `Verify:` replace the index entry's.
640
+ const leaf = leaves.get(id) ?? null;
641
+ const leafMeta = leaf ? frontmatter(files.get(leaf)).data : null;
642
+ const [covers, coversFrom] =
643
+ leafMeta && leafMeta.covers !== undefined ? [leafMeta.covers ?? [], leaf] : [entry.covers ?? [], `${index} entry ${id}`];
644
+ if (!Array.isArray(covers) || covers.some((link) => typeof link !== 'string'))
645
+ throw inputError(`${coversFrom} must list covers as strings.`);
646
+ const captured = leaf ? leafCriteria(files.get(leaf), leaf) : { criteria: [], verify: null };
647
+ const plan = plans.get(id) ?? null;
648
+ const planned = captured.criteria.length === 0 && plan ? planCriteria(files.get(plan), plan) : [];
649
+ const verify = [];
650
+ if (leaf) {
651
+ if (captured.verify) verify.push(captured.verify);
652
+ } else if (typeof entry.verify === 'string' && entry.verify.trim() && verifyLines[position])
653
+ verify.push({ text: entry.verify, file: index, line: verifyLines[position] });
654
+ const [selection, criteria] =
655
+ captured.criteria.length > 0 ? ['numbered', captured.criteria] : planned.length > 0 ? ['plan', planned] : ['verify', []];
656
+ if (selection === 'verify' && verify.length === 0)
657
+ throw inputError(
658
+ `${leaf ?? `${index} entry ${id}`} states no numbered criteria, plan acceptance criteria, or verify line; give the ticket a criterion before tracing the epic.`,
659
+ );
660
+ return { id, storyKey, covers, leaf, plan, selection, criteria, verify };
661
+ }),
662
+ };
663
+ }
664
+
665
+ const declaredLinks = (criterion) => new Set([...criterion.validLinks, ...criterion.invalidLinks]);
666
+ const storyOf = (id) => id.slice(0, id.lastIndexOf('--'));
667
+ const loose = (text) => criterionText(text).toLowerCase();
668
+ /** Frozen criterion text for comparison: Markdown and whitespace normalized, `R` id and priority groups dropped. */
669
+ const frozen = (text) =>
670
+ loose(text)
671
+ .replaceAll(ANNOTATION, ' ')
672
+ .replaceAll(/\s+/g, ' ')
673
+ .replaceAll(/\s+([:.,;])/g, '$1')
674
+ .trim()
675
+ .replace(/\.$/, '');
676
+ const cited = (captured) => `${captured.file}:${captured.line}`;
677
+
678
+ /** A criterion's `source` must be a `path:line` inside the epic folder; returns it resolved, or throws. */
679
+ function citationOf(tickets, criterion) {
680
+ const match = /^(.+):(\d+)$/.exec(criterion.source);
681
+ const file = match ? path.resolve(tickets.root, match[1]) : null;
682
+ const relative = file ? path.relative(tickets.epicDir, file) : '..';
683
+ if (!match || relative.startsWith('..') || path.isAbsolute(relative))
684
+ throw new Error(
685
+ `Trace criterion ${criterion.id} source ${criterion.source} is not a path:line inside the epic folder ${tickets.epicDir}.`,
686
+ );
687
+ return `${file}:${Number(match[2])}`;
688
+ }
689
+
690
+ /**
691
+ * Compare `criterionLedger` with the independently captured tickets. Each entry lists exactly the
692
+ * criteria the story contract selects: the same members, each with the captured name, full text,
693
+ * declared links and explicit priority, and a `source` at the exact file and line where it starts.
694
+ * A verify-only entry's single criterion is its verify line, carrying its covers.
695
+ */
696
+ function reconcileTickets(tickets, criteria) {
697
+ const byStory = new Map(tickets.entries.map((entry) => [entry.storyKey, []]));
698
+ for (const criterion of criteria.values()) {
699
+ const story = storyOf(criterion.id);
700
+ if (!byStory.has(story)) throw new Error(`Trace criterion ${criterion.id} names no entry of ${tickets.index}.`);
701
+ if (criterion.story !== undefined && criterion.story !== story)
702
+ throw new Error(`Trace criterion ${criterion.id} must record story ${story}.`);
703
+ byStory.get(story).push(criterion);
704
+ }
705
+ for (const entry of tickets.entries) {
706
+ const listed = byStory.get(entry.storyKey);
707
+ if (listed.length === 0) throw new Error(`Trace criterionLedger omits ${entry.storyKey}, entry ${entry.id} of ${tickets.index}.`);
708
+ if (entry.selection === 'verify') {
709
+ const [criterion] = listed;
710
+ const matches = entry.verify.filter(
711
+ (verify) =>
712
+ criterionText(verify.text) === criterionText(criterion.text) && criterionText(verify.text) === criterionText(criterion.name),
713
+ );
714
+ if (listed.length !== 1 || matches.length === 0 || !sameSet([...declaredLinks(criterion)], new Set(entry.covers)))
715
+ throw new Error(
716
+ `Trace criterionLedger must give verify-only entry ${entry.storyKey} one criterion: its verify line as name and text, linked to its covers.`,
717
+ );
718
+ const source = citationOf(tickets, criterion);
719
+ if (!matches.some((verify) => cited(verify) === source))
720
+ throw new Error(`Trace criterion ${criterion.id} source ${criterion.source} must be ${cited(matches[0])}, its verify line.`);
721
+ const stated = (criterion.text.match(ANNOTATION) ?? [])
722
+ .join(' ')
723
+ .match(/\bP[0-3]\b/i)?.[0]
724
+ .toUpperCase();
725
+ if (stated ? criterion.priority !== stated || criterion.priorityBasis !== 'explicit' : criterion.priorityBasis !== 'inferred')
726
+ throw new Error(
727
+ `Trace criterion ${criterion.id} must record ${stated ? `the explicit priority ${stated} its verify line states` : 'priorityBasis inferred; its verify line states no priority'}.`,
728
+ );
729
+ continue;
730
+ }
731
+ const from = entry.selection === 'plan' ? entry.plan : entry.leaf;
732
+ if (listed.length !== entry.criteria.length)
733
+ throw new Error(
734
+ `Trace criterionLedger lists ${listed.length} criteria for ${entry.storyKey}; the story contract selects ${entry.criteria.length} from ${from}.`,
735
+ );
736
+ const unused = [...listed];
737
+ for (const captured of entry.criteria) {
738
+ const index = unused.findIndex(
739
+ (criterion) => sameSet([...declaredLinks(criterion)], new Set(captured.links)) && loose(criterion.name) === loose(captured.name),
740
+ );
741
+ if (index === -1)
742
+ throw new Error(
743
+ `Trace criterionLedger has no ${entry.storyKey} criterion named "${captured.name}" (${captured.links.join(', ') || 'no links'}) from ${cited(captured)}; it was omitted or its name or links changed.`,
744
+ );
745
+ const [criterion] = unused.splice(index, 1);
746
+ if (frozen(criterion.text) !== frozen(captured.text))
747
+ throw new Error(
748
+ `Trace criterion ${criterion.id} text differs from the criterion at ${cited(captured)}; freeze its name line and every line beneath it as the source states them.`,
749
+ );
750
+ if (captured.priority && (criterion.priority !== captured.priority || criterion.priorityBasis !== 'explicit'))
751
+ throw new Error(`Trace criterion ${criterion.id} must keep the explicit priority ${captured.priority} its source states.`);
752
+ if (!captured.priority && criterion.priorityBasis !== 'inferred')
753
+ throw new Error(`Trace criterion ${criterion.id} must record priorityBasis inferred; ${cited(captured)} states no priority.`);
754
+ if (citationOf(tickets, criterion) !== cited(captured))
755
+ throw new Error(
756
+ `Trace criterion ${criterion.id} source ${criterion.source} must be ${cited(captured)}, where "${captured.name}" starts.`,
757
+ );
758
+ }
759
+ }
760
+ }
761
+
762
+ /**
763
+ * Reconcile a requirement-oracle run: every frozen `R<n>` line is a gate row with its source text,
764
+ * explicit priority and line; every other gate row is a link exception from `criterionLedger`, which
765
+ * itself matches the independently captured tickets. Priorities follow Step 1 section E.
766
+ */
767
+ function requirementReference(progress, sourceLedger, tickets) {
768
+ const recorded = progress.oracleLedger;
769
+ if (!Array.isArray(recorded) || recorded.length === 0) throw new Error('Trace Step 1 oracleLedger must be a nonempty array.');
770
+ if (!Array.isArray(progress.criterionLedger)) throw new Error('Trace requirement oracle must persist the Step 1 criterionLedger.');
771
+ if (!tickets) throw new Error("Trace requirement oracle needs the epic's independently captured tickets.");
772
+ const requirementIds = sourceLedger.map((row) => row.id);
773
+ const requirementSet = new Set(requirementIds);
774
+ const definedLinks = new Set(requirementIds.map(localId));
775
+ const criteria = new Map();
776
+ for (const criterion of progress.criterionLedger) {
777
+ const links = (field) => Array.isArray(criterion?.[field]) && criterion[field].every((link) => typeof link === 'string');
778
+ if (
779
+ !criterion ||
780
+ typeof criterion.id !== 'string' ||
781
+ !ORACLE_ID.test(criterion.id) ||
782
+ !criterion.id.includes('--') ||
783
+ typeof criterion.name !== 'string' ||
784
+ !criterion.name.trim() ||
785
+ typeof criterion.text !== 'string' ||
786
+ !criterion.text.trim() ||
787
+ typeof criterion.source !== 'string' ||
788
+ !criterion.source.trim() ||
789
+ !/^P[0-3]$/.test(criterion.priority) ||
790
+ !['explicit', 'inferred'].includes(criterion.priorityBasis) ||
791
+ !links('validLinks') ||
792
+ !links('invalidLinks') ||
793
+ criteria.has(criterion.id)
794
+ )
795
+ throw new Error('Trace Step 1 criterionLedger has an invalid or duplicate criterion.');
796
+ if (!loose(criterion.text).includes(loose(criterion.name)))
797
+ throw new Error(`Trace criterion ${criterion.id} text must contain its name "${criterion.name}".`);
798
+ const declared = declaredLinks(criterion);
799
+ if (
800
+ criterion.validLinks.some((link) => !definedLinks.has(link)) ||
801
+ criterion.invalidLinks.some((link) => definedLinks.has(link)) ||
802
+ (criterion.declaredLinks !== undefined && !sameSet(criterion.declaredLinks, declared))
803
+ )
804
+ throw new Error(`Trace criterion ${criterion.id} sorts its links differently from the epic's Requirements lines.`);
805
+ const exception = criterion.invalidLinks.length > 0 ? 'invalid-link' : criterion.validLinks.length > 0 ? 'none' : 'unlinked';
806
+ if (criterion.exception !== exception) throw new Error(`Trace criterion ${criterion.id} must record exception ${exception}.`);
807
+ criteria.set(criterion.id, criterion);
808
+ }
809
+ const reference = new Map();
810
+ for (const row of recorded) {
811
+ if (!validOracleRow(row) || !ORACLE_ID.test(row.id) || reference.has(row.id))
812
+ throw new Error('Trace Step 1 oracleLedger has an invalid or duplicate criterion.');
813
+ reference.set(row.id, row);
814
+ }
815
+ for (const row of sourceLedger) {
816
+ const saved = reference.get(row.id);
817
+ if (!saved) throw new Error(`Trace Step 1 oracleLedger omits epic requirement ${row.id}.`);
818
+ if (saved.kind !== 'requirement') throw new Error(`Trace requirement ${row.id} must record kind requirement.`);
819
+ if (saved.parent !== null && typeof saved.parent !== 'string')
820
+ throw new Error(`Trace requirement ${row.id} must record its parent link, or null.`);
821
+ // Contributors decide FULL; a dropped one could hide a NONE criterion.
822
+ const contributors = [...criteria.values()].filter((criterion) => criterion.validLinks.includes(localId(row.id)));
823
+ if (!Array.isArray(saved.contributors) || saved.contributors.join('\n') !== contributors.map(({ id }) => id).join('\n'))
824
+ throw new Error(
825
+ `Trace requirement ${row.id} must list exactly the criteria whose validLinks name it as contributors, in criterionLedger order.`,
826
+ );
827
+ if (criterionText(saved.requirement) !== criterionText(row.requirement) || saved.source !== row.source)
828
+ throw new Error(`Trace Step 1 requirement ${row.id} changed its frozen requirement text or source binding.`);
829
+ if (row.priority && saved.priority !== row.priority)
830
+ throw new Error(`Trace Step 1 requirement ${row.id} changed its explicit source priority.`);
831
+ const highest = contributors.map(({ priority }) => priority).toSorted((left, right) => PRIORITY_RANK[left] - PRIORITY_RANK[right])[0];
832
+ const basis = row.priority ? 'explicit' : highest ? 'contributors' : 'inferred';
833
+ if (saved.priorityBasis !== basis)
834
+ throw new Error(
835
+ `Trace requirement ${row.id} must record priorityBasis ${basis}: ${row.priority ? 'its R line states a priority' : highest ? 'it has contributors' : 'no criterion contributes to it'}.`,
836
+ );
837
+ if (basis === 'contributors' && saved.priority !== highest)
838
+ throw new Error(`Trace requirement ${row.id} priority must be ${highest}, the highest priority among its contributors.`);
839
+ }
840
+ for (const [id, row] of reference) {
841
+ if (requirementSet.has(id)) continue;
842
+ const criterion = criteria.get(id);
843
+ if (!criterion || criterion.exception === 'none')
844
+ throw new Error(`Trace oracleLedger row ${id} is neither an epic requirement nor a criterionLedger link exception.`);
845
+ if (row.kind !== 'exception' || row.exception !== criterion.exception)
846
+ throw new Error(`Trace exception row ${id} must record kind exception and its criterion's exception ${criterion.exception}.`);
847
+ // A gate row names its criterion: the bold name of a numbered criterion, the verify text of a verify-only one.
848
+ if (criterionText(criterion.name) !== criterionText(row.requirement) || criterion.source !== row.source)
849
+ throw new Error(
850
+ `Trace exception row ${id} requirement must be its criterion's name "${criterion.name}" with the criterion's source binding.`,
851
+ );
852
+ if (criterion.priority !== row.priority || criterion.priorityBasis !== row.priorityBasis)
853
+ throw new Error(`Trace exception row ${id} changed its criterion's priority or priorityBasis.`);
854
+ }
855
+ for (const criterion of criteria.values())
856
+ if (criterion.exception !== 'none' && !reference.has(criterion.id))
857
+ throw new Error(`Trace criterion ${criterion.id} has link exception ${criterion.exception} but no gate row.`);
858
+ reconcileTickets(tickets, criteria);
859
+ return { reference, criteria, requirementIds };
860
+ }
861
+
862
+ /**
863
+ * Contributor tables (`| Contributor | Story | Status | Tests |`) under each gate row's detail heading.
864
+ * A requirement with no contributors needs no table; a placeholder row (`| none | none | none | none |`)
865
+ * lists no contributor, because a criterion id always holds `--`.
866
+ */
867
+ function matrixContributors(matrix, reference) {
868
+ const tables = new Map();
869
+ const tokens = new MarkdownIt().parse(matrix.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, ''), {});
870
+ let current = null;
871
+ let depth = 0;
872
+ for (let index = 0; index < tokens.length; index++) {
873
+ const token = tokens[index];
874
+ if (token.type === 'heading_open') {
875
+ const nextDepth = Number(token.tag.slice(1));
876
+ if (nextDepth <= depth) current = null;
877
+ const id = /^\*{0,2}([A-Za-z0-9][A-Za-z0-9_.-]*)\*{0,2}(?:\s*\(P[0-3]\))?\s*:\s/.exec(tokens[index + 1].content)?.[1];
878
+ if (id && reference.has(id)) [current, depth] = [id, nextDepth];
879
+ continue;
880
+ }
881
+ if (token.type !== 'table_open' || !current) continue;
882
+ const rows = [];
883
+ let row = null;
884
+ while (++index < tokens.length && tokens[index].type !== 'table_close') {
885
+ if (tokens[index].type === 'tr_open') row = [];
886
+ else if (tokens[index].type === 'inline' && row) row.push(bare(tokens[index].content));
887
+ else if (tokens[index].type === 'tr_close') rows.push(row);
888
+ }
889
+ const header = (rows.shift() ?? []).map((cell) => cell.toLowerCase());
890
+ const [contributor, story, status] = ['contributor', 'story', 'status'].map((name) => header.indexOf(name));
891
+ if (contributor === -1) continue;
892
+ if (tables.has(current)) throw new Error(`Trace matrix lists contributors for ${current} more than once.`);
893
+ tables.set(
894
+ current,
895
+ rows
896
+ .filter((cells) => !cells.every((cell) => /^(?:none|n\/a|-|—|)$/i.test(cell)))
897
+ .map((cells) => ({
898
+ id: cells[contributor],
899
+ story: cells[story],
900
+ coverage: /^(FULL|PARTIAL|NONE|UNIT-ONLY|INTEGRATION-ONLY)\b/.exec(cells[status] ?? '')?.[1],
901
+ })),
902
+ );
903
+ }
904
+ return tables;
905
+ }
906
+
907
+ /** AC5: NONE with no contributor or only NONE contributors; FULL only when every contributor is FULL and nothing is missing. */
908
+ function requirementCoverage(contributorStatuses, missingBehaviors) {
909
+ if (contributorStatuses.every((status) => status === 'NONE')) return 'NONE';
910
+ return contributorStatuses.every((status) => status === 'FULL') && missingBehaviors.length === 0 ? 'FULL' : 'PARTIAL';
911
+ }
912
+
913
+ const behaviors = (list) => list.map((behavior) => criterionText(behavior).toLowerCase()).toSorted();
914
+
915
+ /**
916
+ * Step 3's persisted mapping: the fenced json block under the `Requirement Aggregation` heading, holding
917
+ * `criterionMatrix` (one row per `criterionLedger` record) and `traceabilityMatrix` (one row per
918
+ * `oracleLedger` row, in ledger order). Checked against both ledgers and against AC5, so it can serve as
919
+ * the reference the final renderings must match. Returns each criterion's and each gate row's status.
920
+ */
921
+ function requirementAggregation(matrix, ledger, criteria) {
922
+ const tokens = new MarkdownIt().parse(matrix.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, ''), {});
923
+ const found = sections(tokens, /^requirement aggregation\b/i);
924
+ const fences = found.flatMap((section) => section.filter((token) => token.type === 'fence' && /^json\b/i.test(token.info.trim())));
925
+ if (fences.length !== 1)
926
+ throw new Error(
927
+ "Trace requirement run must keep Step 3's Requirement Aggregation block, one fenced json block under that heading, in the final matrix.",
928
+ );
929
+ let aggregation;
930
+ try {
931
+ aggregation = JSON.parse(fences[0].content);
932
+ } catch (error) {
933
+ throw new Error(`Trace Step 3 Requirement Aggregation block is not valid JSON: ${error.message}`, { cause: error });
934
+ }
935
+ const { criterionMatrix, traceabilityMatrix } = aggregation ?? {};
936
+ if (!Array.isArray(criterionMatrix) || !Array.isArray(traceabilityMatrix))
937
+ throw new Error('Trace Step 3 Requirement Aggregation block must hold criterionMatrix and traceabilityMatrix arrays.');
938
+ const criterionStatus = new Map();
939
+ for (const row of criterionMatrix) {
940
+ if (!row || typeof row.id !== 'string' || !criteria.has(row.id) || criterionStatus.has(row.id))
941
+ throw new Error(`Trace Step 3 criterionMatrix row ${row?.id} is not a criterionLedger record, or repeats one.`);
942
+ if (!COVERAGE.has(row.coverage)) throw new Error(`Trace Step 3 criterionMatrix row ${row.id} has invalid coverage.`);
943
+ criterionStatus.set(row.id, row.coverage);
944
+ }
945
+ for (const id of criteria.keys()) if (!criterionStatus.has(id)) throw new Error(`Trace Step 3 criterionMatrix omits criterion ${id}.`);
946
+ if (traceabilityMatrix.length !== ledger.length)
947
+ throw new Error('Trace Step 3 traceabilityMatrix must hold one gate row per oracleLedger row, in ledger order.');
948
+ const rows = new Map();
949
+ for (const [index, saved] of ledger.entries()) {
950
+ const row = traceabilityMatrix[index];
951
+ if (!row || row.id !== saved.id || row.kind !== saved.kind)
952
+ throw new Error(`Trace Step 3 traceabilityMatrix[${index}] must be ${saved.kind} row ${saved.id}, in oracleLedger order.`);
953
+ if (saved.kind === 'exception') {
954
+ if (row.coverage !== criterionStatus.get(saved.id))
955
+ throw new Error(
956
+ `Trace Step 3 exception row ${saved.id} is ${row.coverage}, but its criterionMatrix row is ${criterionStatus.get(saved.id)}.`,
957
+ );
958
+ rows.set(saved.id, { coverage: row.coverage });
959
+ continue;
960
+ }
961
+ if (
962
+ !Array.isArray(row.contributors) ||
963
+ row.contributors.map((contributor) => contributor?.id).join('\n') !== saved.contributors.join('\n')
964
+ )
965
+ throw new Error(`Trace Step 3 requirement ${saved.id} contributors must be the oracleLedger contributors, in order.`);
966
+ for (const contributor of row.contributors)
967
+ if (contributor.coverage !== criterionStatus.get(contributor.id))
968
+ throw new Error(
969
+ `Trace Step 3 requirement ${saved.id} gives contributor ${contributor.id} ${contributor.coverage}, but its criterionMatrix row is ${criterionStatus.get(contributor.id)}.`,
970
+ );
971
+ const missing = row.missingBehaviors;
972
+ if (!Array.isArray(missing) || missing.some((behavior) => typeof behavior !== 'string' || !behavior.trim()))
973
+ throw new Error(`Trace Step 3 requirement ${saved.id} must list missingBehaviors as strings.`);
974
+ const expected = requirementCoverage(
975
+ row.contributors.map((contributor) => contributor.coverage),
976
+ missing,
977
+ );
978
+ if (row.coverage !== expected)
979
+ throw new Error(
980
+ `Trace Step 3 requirement ${saved.id} is ${row.coverage}, but its contributors and missingBehaviors make it ${expected}.`,
981
+ );
982
+ rows.set(saved.id, { coverage: expected, missing });
983
+ }
984
+ return { criterionStatus, rows };
985
+ }
986
+
987
+ /**
988
+ * Check the published requirement rows (`summary.oracle.rows`) against the gate ledger, the matrix
989
+ * statuses and contributor tables, and AC5's aggregation: a requirement is NONE with no contributor or
990
+ * only NONE contributors, FULL only when every contributor is FULL and no behavior is missing, else PARTIAL.
991
+ * Then hold every final status to Step 3's persisted mapping: each criterion keeps the status Step 3
992
+ * assessed, and each requirement the status and missing behaviors AC5 derives from it.
993
+ */
994
+ function reconcileRequirementRows(summary, ledger, criteria, statuses, tables, aggregation) {
995
+ const rows = summary.oracle.rows;
996
+ if (!Array.isArray(rows) || rows.length !== ledger.length)
997
+ throw new Error('Trace summary oracle.rows must list every oracleLedger row, in ledger order.');
998
+ const coverage = new Map();
999
+ const record = (id, status, where) => {
1000
+ if (!COVERAGE.has(status)) throw new Error(`Trace criterion ${id} has invalid coverage in ${where}.`);
1001
+ if (coverage.has(id) && coverage.get(id) !== status)
1002
+ throw new Error(`Trace criterion ${id} is ${coverage.get(id)} in one gate row and ${status} in ${where}.`);
1003
+ coverage.set(id, status);
1004
+ };
1005
+ const pairs = ledger.map((saved, index) => [saved, rows[index]]);
1006
+ for (const [index, [saved, row]] of pairs.entries()) {
1007
+ if (!row || typeof row !== 'object' || row.id !== saved.id)
1008
+ throw new Error(`Trace summary oracle.rows[${index}] must be ${saved.id}, in oracleLedger order.`);
1009
+ if (row.kind !== saved.kind || row.priority !== saved.priority || row.priority_basis !== saved.priorityBasis)
1010
+ throw new Error(`Trace summary row ${saved.id} kind, priority or priority_basis differs from the oracleLedger.`);
1011
+ if (row.coverage !== statuses.get(saved.id)) throw new Error(`Trace summary row ${saved.id} coverage differs from the matrix.`);
1012
+ if (saved.kind === 'exception') {
1013
+ if (row.exception !== saved.exception) throw new Error(`Trace summary row ${saved.id} must record exception ${saved.exception}.`);
1014
+ record(saved.id, row.coverage, `its exception row`);
1015
+ }
1016
+ }
1017
+ for (const [saved, row] of pairs) {
1018
+ if (saved.kind !== 'requirement') continue;
1019
+ if (row.parent !== saved.parent) throw new Error(`Trace summary row ${saved.id} parent differs from the oracleLedger.`);
1020
+ if (!Array.isArray(row.missing_behaviors) || row.missing_behaviors.some((behavior) => typeof behavior !== 'string' || !behavior.trim()))
1021
+ throw new Error(`Trace summary row ${saved.id} must list missing_behaviors as strings.`);
1022
+ if (
1023
+ !Array.isArray(row.contributors) ||
1024
+ row.contributors.map((contributor) => contributor?.id).join('\n') !== saved.contributors.join('\n')
1025
+ )
1026
+ throw new Error(`Trace summary row ${saved.id} contributors must be the oracleLedger contributors, in order.`);
1027
+ for (const contributor of row.contributors) {
1028
+ if (contributor.story !== storyOf(contributor.id))
1029
+ throw new Error(`Trace summary row ${saved.id} gives contributor ${contributor.id} a different story.`);
1030
+ record(contributor.id, contributor.coverage, `${saved.id}'s contributors`);
1031
+ }
1032
+ const table = tables.get(saved.id) ?? [];
1033
+ const listed = new Map(row.contributors.map((contributor) => [contributor.id, contributor]));
1034
+ if (
1035
+ table.length !== listed.size ||
1036
+ table.some(
1037
+ (cell) => listed.get(cell.id)?.story !== cell.story || listed.get(cell.id)?.coverage !== cell.coverage || !listed.delete(cell.id),
1038
+ )
1039
+ )
1040
+ throw new Error(`Trace matrix contributors table for ${saved.id} disagrees with its summary row.`);
1041
+ const below = row.contributors.find((contributor) => contributor.coverage !== 'FULL');
1042
+ const covered = row.contributors.find((contributor) => contributor.coverage !== 'NONE');
1043
+ if (row.coverage === 'FULL' && row.contributors.length === 0)
1044
+ throw new Error(`Trace requirement ${saved.id} is FULL, but no criterion contributes to it.`);
1045
+ if (row.coverage === 'FULL' && below)
1046
+ throw new Error(`Trace requirement ${saved.id} is FULL, but contributor ${below.id} is ${below.coverage}.`);
1047
+ if (row.coverage === 'FULL' && row.missing_behaviors.length > 0)
1048
+ throw new Error(`Trace requirement ${saved.id} is FULL, but it lists missing behaviors.`);
1049
+ if (row.coverage === 'NONE' && covered)
1050
+ throw new Error(`Trace requirement ${saved.id} is NONE, but contributor ${covered.id} is ${covered.coverage}.`);
1051
+ const expected = requirementCoverage(
1052
+ row.contributors.map((contributor) => contributor.coverage),
1053
+ row.missing_behaviors,
1054
+ );
1055
+ if (row.coverage !== expected)
1056
+ throw new Error(`Trace requirement ${saved.id} is ${row.coverage}, but its contributors and missing behaviors make it ${expected}.`);
1057
+ }
1058
+ for (const id of coverage.keys())
1059
+ if (!criteria.has(id)) throw new Error(`Trace summary names criterion ${id} absent from criterionLedger.`);
1060
+ for (const [id, status] of coverage)
1061
+ if (status !== aggregation.criterionStatus.get(id))
1062
+ throw new Error(
1063
+ `Trace final coverage gives criterion ${id} ${status}, but Step 3's Requirement Aggregation assessed it ${aggregation.criterionStatus.get(id)}.`,
1064
+ );
1065
+ for (const [saved, row] of pairs) {
1066
+ const step3 = aggregation.rows.get(saved.id);
1067
+ if (row.coverage !== step3.coverage)
1068
+ throw new Error(`Trace gate row ${saved.id} is ${row.coverage}, but Step 3's Requirement Aggregation makes it ${step3.coverage}.`);
1069
+ if (saved.kind === 'requirement' && behaviors(row.missing_behaviors).join('\n') !== behaviors(step3.missing).join('\n'))
1070
+ throw new Error(`Trace requirement ${saved.id} missing_behaviors differ from Step 3's persisted missingBehaviors.`);
1071
+ }
1072
+ }
1073
+
1074
+ /**
1075
+ * Reconcile the saved Step 1 ledger with the caller's frozen source claims. Returns the gate rows
1076
+ * and the live alias map: identity over gate rows for the criterion oracle, Step 3's shared map otherwise.
1077
+ */
1078
+ function oracleReference(progress, sourceLedger, required, allowLegacyExplicitOracle, requirements = false, tickets) {
1079
+ const granularity = progress.oracleGranularity ?? 'criteria';
1080
+ if (!['criteria', 'requirements'].includes(granularity)) throw new Error('Trace oracleGranularity must be criteria or requirements.');
1081
+ if (requirements && granularity !== 'requirements')
1082
+ throw new Error('Trace of a v7 epic with Requirements lines must record oracleGranularity: requirements.');
1083
+ if (!requirements && granularity === 'requirements')
1084
+ throw new Error("Trace oracleGranularity requirements needs a native v7 epic's frozen Requirements lines.");
1085
+ if (requirements) {
1086
+ const { reference, criteria, requirementIds } = requirementReference(progress, sourceLedger, tickets);
1087
+ const criterionIds = [...criteria.keys()];
1088
+ return { reference, criteria, criterionIds, aliases: liveAliasMap(criterionIds, requirementIds) };
1089
+ }
184
1090
  const recorded = progress.oracleLedger;
185
1091
  if (
186
1092
  recorded === undefined &&
@@ -192,17 +1098,7 @@ function oracleReference(progress, sourceLedger, required, allowLegacyExplicitOr
192
1098
  if (recorded !== undefined) {
193
1099
  if (!Array.isArray(recorded) || recorded.length === 0) throw new Error('Trace Step 1 oracleLedger must be a nonempty array.');
194
1100
  for (const row of recorded) {
195
- if (
196
- !row ||
197
- typeof row.id !== 'string' ||
198
- !row.id.trim() ||
199
- !/^P[0-3]$/.test(row.priority) ||
200
- typeof row.requirement !== 'string' ||
201
- !row.requirement.trim() ||
202
- typeof row.source !== 'string' ||
203
- !row.source.trim() ||
204
- reference.has(row.id)
205
- )
1101
+ if (!validOracleRow(row) || reference.has(row.id))
206
1102
  throw new Error('Trace Step 1 oracleLedger has an invalid or duplicate criterion.');
207
1103
  reference.set(row.id, row);
208
1104
  }
@@ -219,7 +1115,7 @@ function oracleReference(progress, sourceLedger, required, allowLegacyExplicitOr
219
1115
  reference.set(row.id, { ...row, priority: row.priority ?? saved?.priority, compareText: Boolean(saved) });
220
1116
  }
221
1117
  }
222
- return reference;
1118
+ return { reference, criteria: null, criterionIds: null, aliases: new Map([...reference.keys()].map((id) => [id, { id }])) };
223
1119
  }
224
1120
 
225
1121
  /** Read criterion claims from Markdown headings and their coverage labels. */
@@ -237,13 +1133,13 @@ function matrixInventory(matrix, reference) {
237
1133
  let row = null;
238
1134
  while (++index < tokens.length && tokens[index].type !== 'table_close') {
239
1135
  if (tokens[index].type === 'tr_open') row = [];
240
- else if (tokens[index].type === 'inline' && row) row.push(tokens[index].content.replaceAll(/[*`]/g, '').trim());
1136
+ else if (tokens[index].type === 'inline' && row) row.push(tokens[index].content.trim());
241
1137
  else if (tokens[index].type === 'tr_close') {
242
1138
  rows.push(row);
243
1139
  row = null;
244
1140
  }
245
1141
  }
246
- const header = rows.shift() ?? [];
1142
+ const header = (rows.shift() ?? []).map(bare);
247
1143
  const idIndex = header.findIndex((cell) => /^(?:id|criterion|criterion id)$/i.test(cell));
248
1144
  const requirementIndex = header.findIndex((cell) => /^requirement$/i.test(cell));
249
1145
  const priorityIndex = header.findIndex((cell) => /^priority$/i.test(cell));
@@ -251,15 +1147,15 @@ function matrixInventory(matrix, reference) {
251
1147
  if (idIndex === -1 || priorityIndex === -1) continue;
252
1148
  if (coverageIndex === -1 && !header.some((cell) => /^requirement$/i.test(cell))) continue;
253
1149
  for (const cells of rows) {
254
- const id = cells[idIndex];
255
- const priority = cells[priorityIndex];
1150
+ const id = bare(cells[idIndex] ?? '');
1151
+ const priority = bare(cells[priorityIndex] ?? '');
256
1152
  if (!id || !/^P[0-3]$/.test(priority)) throw new Error('Trace criterion table has missing identity or priority.');
257
1153
  if (ledgerPriorities.has(id) && ledgerPriorities.get(id) !== priority)
258
1154
  throw new Error(`Trace criterion ${id} has conflicting priorities.`);
259
1155
  ledgerPriorities.set(id, priority);
260
1156
  if (coverageIndex === -1) continue;
261
1157
  if (tableClaims.has(id)) throw new Error(`Trace criterion ${id} is duplicated in the matrix table.`);
262
- const status = /^(FULL|PARTIAL|NONE|UNIT-ONLY|INTEGRATION-ONLY)\b/.exec(cells[coverageIndex])?.[1];
1158
+ const status = /^(FULL|PARTIAL|NONE|UNIT-ONLY|INTEGRATION-ONLY)\b/.exec(bare(cells[coverageIndex] ?? ''))?.[1];
263
1159
  if (!status) throw new Error(`Trace criterion ${id} has invalid table coverage.`);
264
1160
  tableClaims.set(id, { priority, status, requirement: requirementIndex === -1 ? undefined : cells[requirementIndex] });
265
1161
  }
@@ -317,13 +1213,14 @@ function matrixInventory(matrix, reference) {
317
1213
  if (reference.size > 0 && [...criteria.keys()].some((id) => !reference.has(id)))
318
1214
  throw new Error('Trace matrix has criteria absent from the Step 1 oracle ledger.');
319
1215
  const inventory = Object.fromEntries(['P0', 'P1', 'P2', 'P3'].map((priority) => [priority, { total: 0, covered: 0 }]));
1216
+ const statuses = new Map();
320
1217
  for (const [id, criterion] of criteria) {
321
- if (!['FULL', 'PARTIAL', 'NONE', 'UNIT-ONLY', 'INTEGRATION-ONLY'].includes(criterion.status))
322
- throw new Error(`Trace criterion ${id} has missing or invalid coverage.`);
1218
+ if (!COVERAGE.has(criterion.status)) throw new Error(`Trace criterion ${id} has missing or invalid coverage.`);
323
1219
  inventory[criterion.priority].total++;
324
1220
  if (criterion.status === 'FULL') inventory[criterion.priority].covered++;
1221
+ statuses.set(id, criterion.status);
325
1222
  }
326
- return inventory;
1223
+ return { inventory, statuses };
327
1224
  }
328
1225
 
329
1226
  /** Check the public artifact contract and Step 5's deterministic gate invariants. */
@@ -337,6 +1234,7 @@ function validateTraceOutputs({
337
1234
  allowLegacyExplicitOracle = false,
338
1235
  liveCapture,
339
1236
  requireLiveManifest = false,
1237
+ tickets,
340
1238
  }) {
341
1239
  const attemptRoot = path.dirname(path.dirname(paths.matrix));
342
1240
  for (const [name, file] of Object.entries(paths)) {
@@ -416,8 +1314,29 @@ function validateTraceOutputs({
416
1314
  if (bucket.pct !== expected) throw new Error(`Trace coverage ${name} percentage does not match its counts.`);
417
1315
  }
418
1316
  const priorities = ['P0', 'P1', 'P2', 'P3'].map((key) => summary.coverage.priority_breakdown[key]);
419
- const reference = oracleReference(progress, oracleLedger, requireOracleLedger, allowLegacyExplicitOracle);
420
- const declared = matrixInventory(matrix, reference);
1317
+ const requirements = requirementOracle(target, oracleLedger);
1318
+ const { reference, criteria, criterionIds, aliases } = oracleReference(
1319
+ progress,
1320
+ oracleLedger,
1321
+ requireOracleLedger,
1322
+ allowLegacyExplicitOracle,
1323
+ requirements,
1324
+ tickets,
1325
+ );
1326
+ // Legacy criterion summaries may omit the field; a requirement run must label its inventory.
1327
+ const granularity = requirements ? 'requirements' : 'criteria';
1328
+ if ((summary.oracle.granularity ?? (requirements ? null : 'criteria')) !== granularity)
1329
+ throw new Error(`Trace summary oracle.granularity must be ${granularity}, matching the progress oracleGranularity.`);
1330
+ const { inventory: declared, statuses } = matrixInventory(matrix, reference);
1331
+ if (requirements)
1332
+ reconcileRequirementRows(
1333
+ summary,
1334
+ progress.oracleLedger,
1335
+ criteria,
1336
+ statuses,
1337
+ matrixContributors(matrix, reference),
1338
+ requirementAggregation(matrix, progress.oracleLedger, criteria),
1339
+ );
421
1340
  for (const [priority, counts] of Object.entries(declared)) {
422
1341
  const reported = summary.coverage.priority_breakdown[priority];
423
1342
  if (reported.total !== counts.total || reported.covered !== counts.covered)
@@ -438,6 +1357,9 @@ function validateTraceOutputs({
438
1357
  bucket.criteria_covered < 0
439
1358
  )
440
1359
  throw new Error(`Trace summary has invalid ${level} inventory.`);
1360
+ // Requirement rows share criteria; per-level counts come from criterionLedger, each criterion once.
1361
+ if (criterionIds && bucket.criteria_covered > criterionIds.length)
1362
+ throw new Error(`Trace ${level} criteria_covered exceeds the Step 1 criterionLedger.`);
441
1363
  }
442
1364
  for (const field of ['files', 'cases', 'skipped_cases', 'fixme_cases', 'pending_cases']) {
443
1365
  if (!Number.isInteger(summary.tests?.[field]) || summary.tests[field] < 0) throw new Error(`Trace summary has invalid tests.${field}.`);
@@ -451,7 +1373,7 @@ function validateTraceOutputs({
451
1373
  throw new Error(`Trace summary has invalid risk_summary.${field}.`);
452
1374
  if (!summary.live_evidence || typeof summary.live_evidence !== 'object' || Array.isArray(summary.live_evidence))
453
1375
  throw new Error('Trace summary has no live_evidence metadata.');
454
- const frozenLive = liveReference(liveCapture, new Set(reference.keys()));
1376
+ const frozenLive = liveReference(liveCapture, aliases);
455
1377
  if (frozenLive) {
456
1378
  for (const field of ['present', 'freshness', 'failed'])
457
1379
  if (summary.live_evidence[field] !== frozenLive[field])
@@ -619,6 +1541,8 @@ function publishTraceOutputs(value, destinations, io = fs) {
619
1541
 
620
1542
  module.exports = {
621
1543
  sourceOracleLedger,
1544
+ epicTicketSources,
1545
+ requirementOracle,
622
1546
  COLLECTION_MODES,
623
1547
  GATE_TYPES,
624
1548
  resolveTraceTarget,