bmad-method-test-architecture-enterprise 3.5.0 → 3.6.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.
@@ -37,9 +37,14 @@ Create the traceability matrix linking the resolved oracle items to tests.
37
37
 
38
38
  ## 1. Build Matrix
39
39
 
40
+ Read `oracleGranularity` from the progress frontmatter. A checkpoint with no `oracleGranularity` is a criterion-oracle run.
41
+
42
+ - **`criteria`:** the oracle items are the `oracleLedger` rows, and the matrix this section builds is `traceabilityMatrix`, the gate inventory, exactly as before.
43
+ - **`requirements`:** the oracle items are the `criterionLedger` records, and the matrix this section builds is `criterionMatrix`: one row per record, keyed by its qualified id (`shop--e1-s2--AC-1`), carrying its `localId`, `story`, and links. Every rule in this section, section 1a, and section 1b applies to these criterion rows unchanged. Section 1c then aggregates them into `traceabilityMatrix`, the gate rows of the `oracleLedger`.
44
+
40
45
  For each resolved oracle item (formal requirement, endpoint/spec item, or synthetic journey):
41
46
 
42
- - Copy its ID, requirement text, and priority from Step 1's persisted oracle ledger. Preserve explicit source priorities through every matrix heading and statistics bucket. Keep each mapped test's priority in the test record as a separate field.
47
+ - Copy its ID, requirement text, and priority from Step 1's persisted oracle ledger. In a requirement-granularity run that ledger is the `criterionLedger`: copy each record's `name` and full `text`, and classify coverage against the full `text`. Preserve explicit source priorities through every matrix heading and statistics bucket. Keep each mapped test's priority in the test record as a separate field.
43
48
  - Map to matching tests
44
49
  - Mark coverage status: FULL / PARTIAL / NONE / UNIT-ONLY / INTEGRATION-ONLY. `checklist.md`'s "Coverage Classification" section is the definition; **read it before classifying anything**, and apply the rule it turns on:
45
50
  - Classification is decided by what the evidence **establishes** about the criterion. The number of levels the evidence spans does not set the status.
@@ -69,7 +74,7 @@ That is the rule for this workflow, and it fixes what every count derived from `
69
74
 
70
75
  Record every such test in `rejectedEvidence` against the criterion it claims, with the reason its assertions fall short. Carry the list forward for Step 4 and persist it into the progress document so a resumed Step 4 can read it. A reader needs to see that the test was read and turned down: a test that claims a criterion and then vanishes from the report is indistinguishable from a test nobody found.
71
76
 
72
- Use the test's explicit ID when its source declares one. Otherwise set `test_id` to its project-relative `file:line` declaration anchor. Do not assign a new sequence number to a rejected test.
77
+ Use the test's explicit ID when its source declares one. Otherwise set `test_id` to its project-relative `file:line` declaration anchor. Do not assign a new sequence number to a rejected test. In a requirement-granularity run, `requirement_id` is the qualified id of the criterion the test claims.
73
78
 
74
79
  ```javascript
75
80
  // One entry per test whose name claims a criterion its assertions do not establish.
@@ -93,24 +98,86 @@ const rejectedEvidence = [
93
98
 
94
99
  Attach the live records to the oracle items they name.
95
100
 
101
+ A live record's `requirement_id` resolves to a canonical oracle id through one alias map. The CLI's live validation builds the same map, so the workflow and the CLI give every record the same disposition:
102
+
103
+ - A qualified id maps to itself: every matrix row id in a criterion-oracle run, and every criterion id (`shop--e1-s2--AC-1`) in a requirement-granularity run.
104
+ - A local id (`AC-1`), the part of a criterion id after its last `--`, maps to the one criterion that carries it, in a requirement-granularity run only.
105
+ - A local id two or more criteria share maps to nothing, and its record is `unmatched` with a reason naming every criterion that carries it.
106
+ - A requirement row id, qualified (`shop--e1--R1`) or local (`R1`), maps to nothing, and its record is `unmatched` with a reason saying live evidence attaches to a criterion. A test or live record is evidence for the criterion it maps to, and a requirement row takes its status from those criteria alone.
107
+
108
+ Normalize every record to its canonical id **before** failure grouping, contradiction checks, evidence attachment, and disposition counts, so a pass and a fail for one criterion meet whichever spelling each used. Keep the supplied id in `supplied_requirement_id` for diagnostics. Invalid, stale, and failure precedence is unchanged, and a criterion-oracle run's map holds only its row ids, which keeps its dispositions exactly as before.
109
+
96
110
  ```javascript
97
111
  // Read from this step's inputs when present, else from the `Live Verification Results` JSON block
98
112
  // Step 2 wrote into the progress document. A run resumed here has no Step 2 bindings in memory.
99
113
  const liveRecords = runtime.getLiveRecords?.() || progressLiveRecords || [];
100
- const oracleItemIds = new Set(traceabilityMatrix.map((req) => String(req.id).trim()));
114
+ const progressFrontmatter = yaml.parse(fs.readFileSync('{outputFile}', 'utf8').match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] || '') || {};
115
+ // A checkpoint with no `oracleGranularity` is a criterion-oracle run.
116
+ const oracleGranularity = progressFrontmatter.oracleGranularity === 'requirements' ? 'requirements' : 'criteria';
117
+ // The rows live evidence can attach to: criterion rows in a requirement-granularity run, the matrix rows otherwise.
118
+ const criterionRows = oracleGranularity === 'requirements' ? criterionMatrix : traceabilityMatrix;
119
+
120
+ // The alias map, built in the CLI's order: qualified criterion ids, qualified requirement row ids, local
121
+ // criterion ids, then local requirement ids. An entry already set is never overwritten, so a qualified id
122
+ // always maps to itself whatever else shares its spelling.
123
+ const liveAliasMap = new Map();
124
+ const localPart = (id) => id.slice(id.lastIndexOf('--') + 2);
125
+ const requirementRowReason = (id) => ({ id: null, reason: `"${id}" names a requirement row; live evidence attaches to a criterion` });
126
+ criterionRows.forEach((row) => {
127
+ const id = String(row.id).trim();
128
+ liveAliasMap.set(id, { id, reason: '' });
129
+ });
130
+ if (oracleGranularity === 'requirements') {
131
+ const requirementRowIds = (progressFrontmatter.oracleLedger || [])
132
+ .filter((row) => row.kind === 'requirement')
133
+ .map((row) => String(row.id).trim());
134
+ requirementRowIds.forEach((id) => liveAliasMap.set(id, requirementRowReason(id)));
135
+ const localCarriers = new Map();
136
+ criterionRows.forEach((row) => {
137
+ const id = String(row.id).trim();
138
+ localCarriers.set(localPart(id), [...(localCarriers.get(localPart(id)) || []), id]);
139
+ });
140
+ localCarriers.forEach((ids, localId) => {
141
+ if (liveAliasMap.has(localId)) return;
142
+ liveAliasMap.set(
143
+ localId,
144
+ ids.length === 1
145
+ ? { id: ids[0], reason: '' }
146
+ : { id: null, reason: `local id "${localId}" is carried by ${ids.length} criteria (${ids.join(', ')}); name the qualified id` },
147
+ );
148
+ });
149
+ requirementRowIds.forEach((id) => {
150
+ if (!liveAliasMap.has(localPart(id))) liveAliasMap.set(localPart(id), requirementRowReason(localPart(id)));
151
+ });
152
+ }
153
+ const resolveLiveRequirementId = (supplied) =>
154
+ liveAliasMap.get(supplied) || { id: null, reason: `"${supplied}" is not in the resolved coverage oracle` };
155
+
156
+ // Canonical ids first. Every grouping and check below reads the canonical id, so `AC-1` and its
157
+ // qualified spelling are one criterion. A record with no requirement_id is already `invalid`.
158
+ const canonicalLiveRecords = liveRecords.map((record) => {
159
+ if (!record.requirement_id) return record;
160
+ const resolved = resolveLiveRequirementId(record.requirement_id);
161
+ return {
162
+ ...record,
163
+ supplied_requirement_id: record.requirement_id,
164
+ requirement_id: resolved.id || record.requirement_id,
165
+ unmatched_reason: resolved.id ? '' : resolved.reason,
166
+ };
167
+ });
101
168
 
102
169
  // A requirement with a fresh `fail` is a requirement the producer's own file says is broken. Counting
103
170
  // a `pass` alongside it would let an appended retry overwrite a recorded failure, so the fail wins and
104
171
  // live evidence for that requirement is set aside entirely. Producers replace records, they do not append.
105
172
  const requirementsWithLiveFailure = new Set(
106
- liveRecords.filter((record) => record.disposition === 'fail').map((record) => record.requirement_id),
173
+ canonicalLiveRecords.filter((record) => record.disposition === 'fail').map((record) => record.requirement_id),
107
174
  );
108
175
 
109
176
  // A `counted` record that names an oracle item nobody recognizes is not coverage of anything.
110
177
  // Demote rather than drop, so the report can name the id that failed to match.
111
- const resolvedLiveRecords = liveRecords.map((record) => {
178
+ const resolvedLiveRecords = canonicalLiveRecords.map((record) => {
112
179
  if (record.disposition !== 'counted') return record;
113
- if (!oracleItemIds.has(record.requirement_id)) return { ...record, disposition: 'unmatched' };
180
+ if (record.unmatched_reason) return { ...record, disposition: 'unmatched' };
114
181
  if (requirementsWithLiveFailure.has(record.requirement_id)) return { ...record, disposition: 'contradicted' };
115
182
  return record;
116
183
  });
@@ -125,7 +192,7 @@ resolvedLiveRecords
125
192
  });
126
193
  ```
127
194
 
128
- For each oracle item with counted live records:
195
+ For each row of `criterionRows` with counted live records, keyed by canonical id:
129
196
 
130
197
  - Append them to the item's `tests` array with `level: 'live'`, `status: 'active'`, `file: ''`, and `line: null`. They carry stable `id` values, so the existing deduplication keys work unchanged.
131
198
  - Classify coverage on the same evidence rules as any other level. A live record that exercises the item's full behavior yields FULL; one that exercises part of it yields PARTIAL. Live evidence is not weaker per requirement; the gate applies its own cap in Step 5.
@@ -136,6 +203,100 @@ Records with any other disposition contribute no coverage. Carry `resolvedLiveRe
136
203
 
137
204
  ---
138
205
 
206
+ ## 1c. Aggregate Requirement Rows
207
+
208
+ Skip this section when `oracleGranularity` is `criteria`; `traceabilityMatrix` is already the gate inventory.
209
+
210
+ In a requirement-granularity run, build `traceabilityMatrix` from the frontmatter `oracleLedger`, one gate row per ledger row in ledger order. The requirement layer only aggregates: every criterion keeps the status sections 1, 1a, and 1b gave it, and no evidence rule changes.
211
+
212
+ **Exception rows.** An exception row copies its criterion row from `criterionMatrix`: coverage, tests, evidence, rejected evidence, and gaps. It records `kind: 'exception'` and the ledger's `exception`, `requirement`, `source`, `priority`, and `priorityBasis`.
213
+
214
+ **Requirement rows.** A requirement row records `kind: 'requirement'` and the ledger's `id`, `requirement`, `parent`, `priority`, `priorityBasis`, and `source`, plus:
215
+
216
+ - `contributors`: one entry per id in the ledger row's `contributors`, built from its criterion row: `{ id, story, coverage, tests }`. Each contributor test keeps its `id`, `level`, `status`, `file`, `line`, and its `skipped`, `pending`, and `fixme` flags, because Steps 4 and 5 read those flags to decide whether the test is active.
217
+ - `missingBehaviors`: split the requirement line into the behaviors it states, each result, condition, scenario, and failure path. That is the "every stated scenario" rule of `checklist.md` "Coverage Classification", applied to the requirement text. For each behavior, name the contributors whose stated criterion text establishes it. A behavior no contributor states goes into `missingBehaviors` in the requirement line's own words. Judge from what the criteria state, since a passing test proves only its own criterion.
218
+ - `tests`: an empty array. A test is evidence for the criterion it maps to; it never maps to a requirement row, and it never marks a requirement FULL on its own.
219
+ - `coverage`: from `requirementCoverage` below.
220
+
221
+ Build the rows with this code, so every row carries its `kind` and every contributor test its execution flags. A ledger row whose id is a `criterionLedger` id is an exception row; every other ledger row is a requirement row. Criterion ids and requirement row ids never share a spelling, because a story key extends its epic key.
222
+
223
+ ```javascript
224
+ // `linked` holds the contributor entries of one requirement row; `missingBehaviors` comes from the
225
+ // judgment above. FULL needs a contributor, every contributor FULL, and no missing behavior.
226
+ const requirementCoverage = (linked, missingBehaviors) => {
227
+ if (linked.length === 0) return 'NONE'; // no story covers it
228
+ if (linked.every((criterion) => criterion.coverage === 'NONE')) return 'NONE';
229
+ if (linked.every((criterion) => criterion.coverage === 'FULL') && missingBehaviors.length === 0) return 'FULL';
230
+ return 'PARTIAL';
231
+ };
232
+
233
+ // A contributor test keeps every field Steps 4 and 5 read. Dropping `skipped`, `pending`, or `fixme`
234
+ // would turn a skipped static test into active static evidence and switch the live-only cap off.
235
+ const contributorTest = (test) => ({
236
+ id: test.id,
237
+ level: test.level,
238
+ status: test.status,
239
+ file: test.file || '',
240
+ line: test.line ?? null,
241
+ skipped: test.skipped === true,
242
+ pending: test.pending === true,
243
+ fixme: test.fixme === true,
244
+ });
245
+
246
+ // One gate row per `oracleLedger` row, in ledger order. `missingBehaviorsById` maps each requirement
247
+ // row id to the behaviors the judgment above found missing.
248
+ const buildGateRows = (oracleLedger, criterionMatrix, missingBehaviorsById = {}) => {
249
+ const criterionById = new Map(criterionMatrix.map((row) => [String(row.id).trim(), row]));
250
+ return oracleLedger.map((ledgerRow) => {
251
+ const id = String(ledgerRow.id).trim();
252
+ if (criterionById.has(id)) {
253
+ return {
254
+ ...criterionById.get(id),
255
+ id,
256
+ kind: 'exception',
257
+ exception: ledgerRow.exception,
258
+ requirement: ledgerRow.requirement,
259
+ source: ledgerRow.source,
260
+ priority: ledgerRow.priority,
261
+ priorityBasis: ledgerRow.priorityBasis,
262
+ };
263
+ }
264
+ const contributors = (ledgerRow.contributors || []).map((contributorId) => {
265
+ const criterion = criterionById.get(String(contributorId).trim());
266
+ return {
267
+ id: contributorId,
268
+ story: criterion?.story ?? null,
269
+ coverage: criterion?.coverage || 'NONE',
270
+ tests: (criterion?.tests || []).map(contributorTest),
271
+ };
272
+ });
273
+ const missingBehaviors = [...(missingBehaviorsById[id] || [])];
274
+ return {
275
+ id,
276
+ kind: 'requirement',
277
+ requirement: ledgerRow.requirement,
278
+ parent: ledgerRow.parent ?? null,
279
+ source: ledgerRow.source,
280
+ priority: ledgerRow.priority,
281
+ priorityBasis: ledgerRow.priorityBasis,
282
+ contributors,
283
+ missingBehaviors,
284
+ tests: [],
285
+ coverage: requirementCoverage(contributors, missingBehaviors),
286
+ };
287
+ });
288
+ };
289
+
290
+ const traceabilityMatrix = buildGateRows(progressFrontmatter.oracleLedger || [], criterionMatrix, missingBehaviorsById);
291
+ ```
292
+
293
+ - A requirement row with no contributors is NONE, and its gaps read "no story covers it".
294
+ - A UNIT-ONLY or INTEGRATION-ONLY contributor counts as not FULL. List each one in the row's gaps with its status.
295
+ - List every behavior in `missingBehaviors` in the row's gaps too. A requirement whose contributors are all FULL stays PARTIAL while any behavior is missing.
296
+ - Never mark a requirement FULL from a partial set of its criteria.
297
+
298
+ ---
299
+
139
300
  ## 2. Validate Coverage Logic
140
301
 
141
302
  Ensure:
@@ -147,6 +308,7 @@ Ensure:
147
308
  - Auth/authz items include at least one denied/invalid-path test where applicable
148
309
  - Synthetic UI journeys are not marked FULL when no E2E or component test asserts the critical path and key failure states
149
310
  - Items are not marked covered on the strength of a `stale`, `unverifiable`, `fail`, `blocked`, `skipped`, `invalid`, `unmatched`, or `contradicted` live record
311
+ - In a requirement-granularity run, `traceabilityMatrix` holds exactly one gate row per `oracleLedger` row, invalid-link and unlinked criteria included, each with its `kind`; every contributor test keeps its `skipped`, `pending`, and `fixme` flags; and no requirement row is FULL with no contributor, a contributor below FULL, or a non-empty `missingBehaviors`
150
312
 
151
313
  ---
152
314
 
@@ -161,7 +323,9 @@ Update it in place:
161
323
  - Add `'step-03-map-criteria'` to `stepsCompleted` array (only if not already present)
162
324
  - Set `lastStep: 'step-03-map-criteria'`
163
325
  - Set `lastSaved: '{date}'`
164
- - Keep `runScope`, `runKey`, `targetType`, `targetId`, and `targetLabel` unchanged
326
+ - Keep `runScope`, `runKey`, `targetType`, `targetId`, `targetLabel`, `oracleGranularity`, `oracleLedger`, and `criterionLedger` unchanged
327
+ - In a requirement-granularity run, persist `criterionMatrix` and the aggregated `traceabilityMatrix` (with `contributors`, `missingBehaviors`, and statuses) into this step's section as a fenced ` ```json ` block titled `Requirement Aggregation`: a `### Requirement Aggregation` heading followed by exactly one ` ```json ` block holding `{ "criterionMatrix": [...], "traceabilityMatrix": [...] }`. `criterionMatrix` has one row per `criterionLedger` record with its `id` and `coverage`; `traceabilityMatrix` has one row per `oracleLedger` row, in ledger order, with its `id`, `kind`, and `coverage`, and each requirement row its `contributors` (`id` and `coverage`) and `missingBehaviors`. A resumed Step 4 reads both from there.
328
+ - The block is required, and it stays in the final document: Step 5 carries it into the report unchanged. The CLI rejects a requirement run whose matrix lacks it, and a run whose final criterion statuses, requirement statuses, or missing behaviors differ from what this block records.
165
329
  - Append this step's output to the appropriate section of the document. Appending is safe because the file holds only this run's work.
166
330
 
167
331
  Load next step: `{nextStepFile}`
@@ -120,6 +120,23 @@ Resolution precedence:
120
120
 
121
121
  Before classifying gaps, compare every matrix item's ID and priority with Step 1's persisted oracle ledger. Require exactly one matrix item per oracle item and unchanged priorities. Correct any drift from the ledger before using the matrix in Sections 1 and 3. Repeat this check when resuming a saved mapping.
122
122
 
123
+ In a requirement-granularity run, `traceabilityMatrix` is the gate rows Step 3 section 1c aggregated, and its oracle ledger is the `oracleLedger`: one gate row per requirement row and per exception row, so invalid-link and unlinked criteria stay in the gate. Reconcile `criterionMatrix` against the `criterionLedger` the same way, one criterion row per record. A run resumed here reads both matrices from Step 3's `Requirement Aggregation` block.
124
+
125
+ ```javascript
126
+ const ledgerDoc = fs.readFileSync('{outputFile}', 'utf8');
127
+ const ledgerFrontmatter = yaml.parse(ledgerDoc.match(/^---\r?\n([\s\S]*?)\r?\n---/)?.[1] || '') || {};
128
+ // A checkpoint with no `oracleGranularity` is a criterion-oracle run, with its rows unchanged.
129
+ const oracleGranularity = ledgerFrontmatter.oracleGranularity === 'requirements' ? 'requirements' : 'criteria';
130
+ // Gate statistics and gaps read `traceabilityMatrix`, the oracleLedger rows. Test counts and per-level
131
+ // `criteria_covered` read `criterionRows`, so a criterion or test serving several requirements counts once.
132
+ const criterionRows =
133
+ oracleGranularity === 'requirements'
134
+ ? runtime.getCriterionMatrix?.() || criterionMatrix || progressCriterionMatrix || []
135
+ : traceabilityMatrix;
136
+ ```
137
+
138
+ Section 0b runs before any worker starts and hands `traceabilityMatrix`, `criterionRows`, and `oracleGranularity` to each one.
139
+
123
140
  ### 1. Gap Analysis
124
141
 
125
142
  **Identify uncovered requirements:**
@@ -210,9 +227,9 @@ const isActiveTest = (test) => {
210
227
  if (['skipped', 'pending', 'fixme'].includes(status)) return false;
211
228
  return test.skipped !== true && test.pending !== true && test.fixme !== true;
212
229
  };
213
- const liveOnlyRequirements = traceabilityMatrix.filter((req) => {
214
- if (!coverageEligibleStatuses.has(req.coverage)) return false;
215
- const activeTests = (req.tests || []).filter(isActiveTest);
230
+ // A criterion is live-only when every active test mapped to it is live.
231
+ const isLiveOnlyTestSet = (tests) => {
232
+ const activeTests = (tests || []).filter(isActiveTest);
216
233
  return (
217
234
  activeTests.length > 0 &&
218
235
  activeTests.every(
@@ -222,6 +239,20 @@ const liveOnlyRequirements = traceabilityMatrix.filter((req) => {
222
239
  .toLowerCase() === 'live',
223
240
  )
224
241
  );
242
+ };
243
+ // A gate row is live-only when its status is not NONE and it depends on a live-only criterion. A
244
+ // criterion row and an exception row depend on their own tests. A requirement row depends on every
245
+ // contributor whose status is not NONE, so one live-only contributor beside static ones still caps the
246
+ // gate: checking the requirement's combined tests would find static evidence and switch the cap off.
247
+ const liveOnlyRequirements = traceabilityMatrix.filter((req) => {
248
+ if (!coverageEligibleStatuses.has(req.coverage)) return false;
249
+ // A row with `contributors` is a requirement row even when an older or hand-edited matrix lost its `kind`.
250
+ if (req.kind === 'requirement' || Array.isArray(req.contributors)) {
251
+ return (req.contributors || []).some(
252
+ (contributor) => coverageEligibleStatuses.has(contributor.coverage) && isLiveOnlyTestSet(contributor.tests),
253
+ );
254
+ }
255
+ return isLiveOnlyTestSet(req.tests);
225
256
  });
226
257
 
227
258
  // A dropped live result is worse than a missing one: someone believes that requirement was verified.
@@ -238,7 +269,8 @@ const liveBlockers = liveRecordsForRollup
238
269
  contradicted: `Live result passed, but the same file records a failure for requirement "${record.requirement_id}". Replace the record rather than appending a retry.`,
239
270
  blocked: 'Live verification was blocked before it could reach a verdict.',
240
271
  skipped: 'Live verification was skipped.',
241
- unmatched: `Live result names requirement "${record.requirement_id}", which is not in the resolved coverage oracle.`,
272
+ // Step 3 section 1b keeps the producer's spelling in `supplied_requirement_id` and the alias map's reason.
273
+ unmatched: `Live result names requirement "${record.supplied_requirement_id || record.requirement_id}": ${record.unmatched_reason || 'it is not in the resolved coverage oracle'}.`,
242
274
  invalid: `Live result is not usable: ${record.invalid_reason || 'missing id, requirement_id, source_sha, or a recognized status'}.`,
243
275
  }[record.disposition],
244
276
  test_file: '',
@@ -475,6 +507,8 @@ if (oracleResolutionMode === 'synthetic_source') {
475
507
 
476
508
  ### 4. Calculate Coverage Statistics
477
509
 
510
+ Statistics, priority buckets, and thresholds are computed over `traceabilityMatrix`, the `oracleLedger` rows. In a requirement-granularity run that includes every invalid-link and unlinked exception row, so those criteria stay in the denominator. Thresholds and status meanings are unchanged.
511
+
478
512
  ```javascript
479
513
  const totalRequirements = traceabilityMatrix.length;
480
514
  const coveredRequirements = traceabilityMatrix.filter((r) => r.coverage === 'FULL' || r.coverage === 'PARTIAL').length;
@@ -505,7 +539,7 @@ const p3CoveragePercentage = safePct(p3Covered, p3Total);
505
539
 
506
540
  Persist the unique discovered tests in Phase 1 so Step 5 does not need to reconstruct counts from per-requirement mappings.
507
541
 
508
- Every count below is built from `req.tests`, and Step 3 section 1a admits only tests that establish part of their criterion. So `cases` and `by_level.*.tests` count the test cases this trace accepted as evidence, and a test whose name claims a criterion its assertions do not establish is absent from both. Those tests are in `rejectedEvidence`, which is carried into the matrix in section 5 and reported by Step 5.
542
+ Every count below is built from the `tests` of `criterionRows` (section 0b), and Step 3 section 1a admits only tests that establish part of their criterion. In a requirement-granularity run those are the criterion rows, so each criterion and each test is counted once even when it serves several requirements; in a criterion-oracle run they are the matrix rows, exactly as before. So `cases` and `by_level.*.tests` count the test cases this trace accepted as evidence, and a test whose name claims a criterion its assertions do not establish is absent from both. Those tests are in `rejectedEvidence`, which is carried into the matrix in section 5 and reported by Step 5.
509
543
 
510
544
  ```javascript
511
545
  // Declared locally so this section stays self-contained when workers run in parallel.
@@ -531,7 +565,7 @@ const normalizeTestStatus = (test) => {
531
565
  };
532
566
 
533
567
  const uniqueTests = new Map();
534
- (traceabilityMatrix || []).forEach((req) => {
568
+ (criterionRows || []).forEach((req) => {
535
569
  (req.tests || []).forEach((test, index) => {
536
570
  // Do NOT use the per-requirement `index` as a fallback — the same test can appear
537
571
  // at different indices across requirements, producing spurious duplicate entries.
@@ -568,7 +602,8 @@ const uniqueTests = new Map();
568
602
  byLevel[bucket].tests += 1;
569
603
  });
570
604
 
571
- (traceabilityMatrix || []).forEach((req) => {
605
+ // One count per covered criterion per level, read from `criterionRows`.
606
+ (criterionRows || []).forEach((req) => {
572
607
  if (!coverageEligibleStatuses.has(req.coverage)) return;
573
608
  const requirementLevels = new Set(
574
609
  (req.tests || []).map((test) => {
@@ -650,9 +685,15 @@ const coverageMatrix = {
650
685
  sources: oracleSources,
651
686
  external_pointer_status: externalPointerStatus,
652
687
  synthetic: oracleResolutionMode === 'synthetic_source',
688
+ // `requirements` for a v7 epic traced against its requirement spine, `criteria` otherwise (section 0b).
689
+ granularity: oracleGranularity,
653
690
  },
654
691
 
655
- requirements: traceabilityMatrix, // Full matrix from Step 3
692
+ // Gate rows from Step 3, in oracleLedger order, each with its `kind` and `priorityBasis`. Requirement rows carry
693
+ // `parent`, `contributors`, and `missingBehaviors`; Step 5 publishes them as the summary's `oracle.rows`.
694
+ requirements: traceabilityMatrix,
695
+ // The criterion rows Step 5 re-derives test counts from. In a criterion-oracle run they are the gate rows.
696
+ criteria: criterionRows,
656
697
 
657
698
  coverage_statistics: {
658
699
  total_requirements: totalRequirements,
@@ -797,7 +838,7 @@ When `resolvedMode` is `agent-team` or `subagent`, parallelize only dependency-s
797
838
  - Worker B: heuristics gap extraction and live evidence rollup (sections 2 and 2b)
798
839
  - Worker C: coverage statistics (section 4)
799
840
 
800
- Each worker's sections declare their own constants, so the three are independent. Section 3 (recommendation synthesis) depends on outputs from sections 1, 2, and 2b, so run it only after Workers A and B complete. Section 5 joins section 2b's `liveBlockers` with section 4b's inventory, which is safe because section 5 is the merge point after all workers finish.
841
+ Each worker's sections declare their own constants and read the `traceabilityMatrix`, `criterionRows`, and `oracleGranularity` section 0b handed them, so the three are independent. Section 3 (recommendation synthesis) depends on outputs from sections 1, 2, and 2b, so run it only after Workers A and B complete. Section 5 joins section 2b's `liveBlockers` with section 4b's inventory, which is safe because section 5 is the merge point after all workers finish.
801
842
 
802
843
  Section 5 remains the deterministic merge point after sections 1-4 are finished.
803
844
 
@@ -830,7 +871,8 @@ Update it in place:
830
871
  - Add `'step-04-analyze-gaps'` to `stepsCompleted` array (only if not already present)
831
872
  - Set `lastStep: 'step-04-analyze-gaps'`
832
873
  - Set `lastSaved: '{date}'`
833
- - Keep `runScope`, `runKey`, `targetType`, `targetId`, and `targetLabel` unchanged
874
+ - Keep `runScope`, `runKey`, `targetType`, `targetId`, `targetLabel`, `oracleGranularity`, `oracleLedger`, and `criterionLedger` unchanged
875
+ - In a requirement-granularity run, keep Step 3's `Requirement Aggregation` block exactly as Step 3 saved it. Gap analysis reads the mapping and leaves every criterion status and every `missingBehaviors` list as saved.
834
876
  - Append this step's output to the appropriate section of the document. Appending is safe because the file holds only this run's work.
835
877
 
836
878
  Load next step: `{nextStepFile}`
@@ -180,9 +180,13 @@ const isActiveTest = (test) => {
180
180
  if (['skipped', 'pending', 'fixme'].includes(status)) return false;
181
181
  return test.skipped !== true && test.pending !== true && test.fixme !== true;
182
182
  };
183
- const derivedLiveOnlyRequirements = (coverageMatrix.requirements || []).filter((req) => {
184
- if (!liveCoverageEligible.has(req.coverage)) return false;
185
- const activeTests = (req.tests || []).filter(isActiveTest);
183
+ // Same rule as Step 4 section 2b. A criterion is live-only when every active test mapped to it is live.
184
+ // A gate row is live-only when its status is not NONE and it depends on a live-only criterion: a
185
+ // criterion or exception row on its own tests, a requirement row on any contributor whose status is not
186
+ // NONE. Contributors carry their criteria's tests, so a resumed Step 5 derives this from the persisted
187
+ // Phase 1 rows alone.
188
+ const isLiveOnlyTestSet = (tests) => {
189
+ const activeTests = (tests || []).filter(isActiveTest);
186
190
  return (
187
191
  activeTests.length > 0 &&
188
192
  activeTests.every(
@@ -192,6 +196,16 @@ const derivedLiveOnlyRequirements = (coverageMatrix.requirements || []).filter((
192
196
  .toLowerCase() === 'live',
193
197
  )
194
198
  );
199
+ };
200
+ const derivedLiveOnlyRequirements = (coverageMatrix.requirements || []).filter((req) => {
201
+ if (!liveCoverageEligible.has(req.coverage)) return false;
202
+ // A row with `contributors` is a requirement row even when an older or hand-edited matrix lost its `kind`.
203
+ if (req.kind === 'requirement' || Array.isArray(req.contributors)) {
204
+ return (req.contributors || []).some(
205
+ (contributor) => liveCoverageEligible.has(contributor.coverage) && isLiveOnlyTestSet(contributor.tests),
206
+ );
207
+ }
208
+ return isLiveOnlyTestSet(req.tests);
195
209
  }).length;
196
210
  const reportedLiveOnly = Number(liveEvidence.requirements_live_only);
197
211
  const liveOnlyCoveredRequirements = Math.max(
@@ -232,10 +246,19 @@ const deriveActiveTestCasesFromRequirements = (requirements) => {
232
246
 
233
247
  return [...uniqueTests.values()].filter((status) => status === 'active').length;
234
248
  };
249
+ // A Phase 1 matrix with no `oracle.granularity` comes from a criterion-oracle run.
250
+ const oracleGranularity = coverageMatrix.oracle?.granularity === 'requirements' ? 'requirements' : 'criteria';
251
+ // Test counts come from criterion rows, each criterion and test counted once. Requirement rows carry no
252
+ // tests of their own, so a requirement-granularity run reads `criteria`; a criterion-oracle run's gate
253
+ // rows are its criterion rows.
254
+ const criterionRows =
255
+ oracleGranularity === 'requirements' && Array.isArray(coverageMatrix.criteria)
256
+ ? coverageMatrix.criteria
257
+ : coverageMatrix.requirements || [];
235
258
  const summarizedTestInventory = coverageMatrix.test_inventory?.summary || null;
236
259
  const activeTestCases =
237
260
  summarizedTestInventory === null
238
- ? deriveActiveTestCasesFromRequirements(coverageMatrix.requirements)
261
+ ? deriveActiveTestCasesFromRequirements(criterionRows)
239
262
  : Math.max(
240
263
  0,
241
264
  (summarizedTestInventory.cases || 0) -
@@ -501,9 +524,13 @@ The summary metadata is a strict contract. Emit the resolved run value for every
501
524
  | `links.journey_evidence_url` | `''` |
502
525
  | `tests.skipped_cases`, `tests.fixme_cases`, `tests.pending_cases` | The real inventory counts. Use `0` when no cases have that status. |
503
526
  | `heuristics.ui_journey_status`, `heuristics.ui_state_status` | `not_applicable` for a non-synthetic formal requirements oracle |
527
+ | `oracle.granularity` | `requirements` or `criteria`, from the Phase 1 matrix |
528
+ | `oracle.rows` | Every `oracleLedger` row when `requirements`; absent otherwise |
504
529
 
505
530
  Do not shorten `{outputFile}`, invent a URL, or replace an unavailable runtime value with a guess. Use the literal string `unknown` for an unavailable runtime value.
506
531
 
532
+ In a requirement-granularity run, `oracle.rows` is the published gate inventory: one entry per `oracleLedger` row, in ledger order, each `{ id, kind, priority, priority_basis, coverage }`. A requirement row adds `parent` (a string, or `null`), `missing_behaviors` (an array), and `contributors`, one `{ id, story, coverage }` per contributing criterion. An exception row adds `exception` (`unlinked` or `invalid-link`). `summaryOracleRows` below builds them from the Phase 1 gate rows.
533
+
507
534
  ```javascript
508
535
  const buildFallbackInventory = () => {
509
536
  const byLevel = {
@@ -517,7 +544,7 @@ const buildFallbackInventory = () => {
517
544
  const coverageEligibleStatuses = new Set(['FULL', 'PARTIAL', 'UNIT-ONLY', 'INTEGRATION-ONLY']);
518
545
  const uniqueTests = new Map();
519
546
 
520
- (coverageMatrix.requirements || []).forEach((req) => {
547
+ criterionRows.forEach((req) => {
521
548
  (req.tests || []).forEach((test) => {
522
549
  const stableId =
523
550
  test.id ||
@@ -637,6 +664,33 @@ const gateBasis = gateEligible ? 'priority_thresholds' : 'none';
637
664
  // which is true. Emitting the literal "{project_name}" would name a repository that does not exist.
638
665
  const repoName = isUnresolved('{project_name}') ? '' : String('{project_name}').trim();
639
666
 
667
+ // The published gate inventory of a requirement-granularity run: one entry per `oracleLedger` row, in
668
+ // ledger order, read from the Phase 1 gate rows Step 3 section 1c built. Requirement rows carry their
669
+ // parent, missing behaviors, and contributors with each contributor's own status; exception rows carry
670
+ // their exception. The CLI reconciles these rows against the ledgers, so every key is always written.
671
+ const summaryOracleRows = (gateRows) =>
672
+ gateRows.map((row) => {
673
+ const isRequirementRow = row.kind === 'requirement' || Array.isArray(row.contributors);
674
+ const entry = {
675
+ id: row.id,
676
+ kind: isRequirementRow ? 'requirement' : 'exception',
677
+ priority: row.priority,
678
+ priority_basis: row.priorityBasis,
679
+ coverage: row.coverage,
680
+ };
681
+ if (!isRequirementRow) return { ...entry, exception: row.exception };
682
+ return {
683
+ ...entry,
684
+ parent: row.parent ?? null,
685
+ missing_behaviors: [...(row.missingBehaviors || [])],
686
+ contributors: (row.contributors || []).map((contributor) => ({
687
+ id: contributor.id,
688
+ story: contributor.story,
689
+ coverage: contributor.coverage,
690
+ })),
691
+ };
692
+ });
693
+
640
694
  const e2eTraceSummary = {
641
695
  schema_version: '0.3.0', // 0.2.0 added live_evidence and the by_level.live bucket; 0.3.0 added waivers
642
696
  snapshot_at: new Date().toISOString(),
@@ -656,6 +710,9 @@ const e2eTraceSummary = {
656
710
  sources: coverageMatrix.oracle?.sources || [],
657
711
  external_pointer_status: coverageMatrix.oracle?.external_pointer_status || 'not_used',
658
712
  synthetic: syntheticOracle,
713
+ granularity: oracleGranularity, // `requirements` for a v7 epic's requirement spine, `criteria` otherwise
714
+ // A criterion-oracle run omits `rows`; its gate rows are the matrix rows the report lists.
715
+ ...(oracleGranularity === 'requirements' ? { rows: summaryOracleRows(coverageMatrix.requirements || []) } : {}),
659
716
  },
660
717
 
661
718
  coverage: {
@@ -815,7 +872,9 @@ if (gateEligible && ['PASS', 'CONCERNS', 'FAIL', 'WAIVED'].includes(gateDecision
815
872
 
816
873
  ## Traceability Matrix
817
874
 
818
- [Full matrix with requirement → test mappings, each criterion carrying its "Considered and rejected" entries from `rejected_evidence`]
875
+ [Full matrix with requirement → test mappings, each criterion carrying its "Considered and rejected" entries from `rejected_evidence`. Each detail heading is `<id> (P<n>): <requirement>`, where `<requirement>` repeats the `oracleLedger` row's `requirement` exactly and `(P<n>)` is the only annotation; the priority basis and any `R` links go in the detail body.]
876
+
877
+ [When `oracleGranularity` is `requirements`: `trace-template.md`'s "Requirement Oracle Mapping" block. The gate table and the detail headings list exactly the `oracleLedger` rows, each repeating the row's `requirement` exactly; each requirement detail adds its parent link, `missingBehaviors`, and a contributors table when it has contributors; the invalid and unlinked criteria follow. Every status and missing behavior repeats Step 3's `Requirement Aggregation` block, which the save below keeps at the end of the report.]
819
878
 
820
879
  ## Gaps & Recommendations
821
880
 
@@ -834,7 +893,9 @@ if (gateEligible && ['PASS', 'CONCERNS', 'FAIL', 'WAIVED'].includes(gateDecision
834
893
 
835
894
  The report replaces the working notes Steps 1 to 4 of this run accumulated below the frontmatter. The frontmatter block stays as it is, because it holds this run's identity (`runScope`, `runKey`, the target) and its progress state. The file belongs to this run alone: Step 1 created it for this `run_key`, so replacing its body never discards another run's work.
836
895
 
837
- ```javascript
896
+ In a requirement-granularity run, Step 3's `Requirement Aggregation` block is the one part of the working notes the report keeps. Carry its heading and its ` ```json ` block into the end of the report unchanged, exactly once: the code below appends it, so `reportContent` leaves it out. The CLI checks every final criterion status, requirement status, and missing behavior against it, and rejects a matrix without it.
897
+
898
+ ````javascript
838
899
  // `reportContent` is the rendered report body, without a frontmatter block of its own.
839
900
  const existingDoc = fs.readFileSync('{outputFile}', 'utf8');
840
901
  const existingFrontmatter = existingDoc.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/)?.[0];
@@ -843,8 +904,18 @@ if (!existingFrontmatter) {
843
904
  'TRACE ERROR: {outputFile} has no frontmatter from Step 1; re-run from Step 1 so the matrix carries runScope, runKey, and the gate target.',
844
905
  );
845
906
  }
846
- fs.writeFileSync('{outputFile}', `${existingFrontmatter}\n${reportContent}`, 'utf8');
847
- ```
907
+ // Step 3's persisted mapping survives the body replacement, heading and json block unchanged.
908
+ const aggregationBlock =
909
+ oracleGranularity === 'requirements'
910
+ ? existingDoc.match(/^#{2,6} Requirement Aggregation\b[^\n]*\r?\n[\s\S]*?^```json[^\n]*\r?\n[\s\S]*?^```[ \t]*$/m)?.[0]
911
+ : null;
912
+ if (oracleGranularity === 'requirements' && !aggregationBlock) {
913
+ throw new Error(
914
+ 'TRACE ERROR: {outputFile} has no Requirement Aggregation block from Step 3; resume from Step 3 so the report keeps the criterion mapping its statuses come from.',
915
+ );
916
+ }
917
+ fs.writeFileSync('{outputFile}', `${existingFrontmatter}\n${reportContent}${aggregationBlock ? `\n\n${aggregationBlock}\n` : ''}`, 'utf8');
918
+ ````
848
919
 
849
920
  This is the only write of report content in this step. Section 6 changes the frontmatter and appends the section 5 summary; it never writes the report again.
850
921
 
@@ -910,7 +981,7 @@ Section 4 (Generate Traceability Report) already wrote the report below the fron
910
981
  - Set `lastStep: 'step-05-gate-decision'`
911
982
  - Set `lastSaved: '{date}'`
912
983
  - Set `workflowStatus: 'completed'`
913
- - Keep `runScope`, `runKey`, `targetType`, `targetId`, and `targetLabel` unchanged
984
+ - Keep `runScope`, `runKey`, `targetType`, `targetId`, `targetLabel`, `oracleGranularity`, `oracleLedger`, and `criterionLedger` unchanged
914
985
 
915
986
  Then append the gate decision summary (from section 5 above) to the end of the report section 4 wrote.
916
987