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.
@@ -51,8 +51,36 @@ function assertLiveSourceRevision(capture, projectRoot) {
51
51
  throw new Error('Trace source revision changed during the run; rerun with current live evidence.');
52
52
  }
53
53
 
54
- /** Mirror Steps 2-4 dispositions; the fresh-failure cap uses each record's actual SHA. */
55
- function liveReference(capture, criterionIds) {
54
+ /** The local part of a qualified id: `AC-1` of `shop--e1-s2--AC-1`, `R1` of `shop--e1--R1`. */
55
+ const localId = (id) => id.slice(id.lastIndexOf('--') + 2);
56
+
57
+ /**
58
+ * Requirement-oracle live identity, the rule Trace Step 3 states: a qualified criterion id
59
+ * (`<story key>--<criterion id>`) maps to itself; a local id (`AC-1`) maps to the one criterion
60
+ * carrying it. A local id two criteria carry, or a requirement row's id (qualified or local `R<n>`),
61
+ * maps to an unmatched reason. Entries are set in that order and never overwritten. Ids absent from
62
+ * the map are unknown.
63
+ */
64
+ function liveAliasMap(criterionIds, requirementIds = []) {
65
+ const aliases = new Map();
66
+ const carriers = new Map();
67
+ for (const id of criterionIds) {
68
+ aliases.set(id, { id });
69
+ carriers.set(localId(id), [...(carriers.get(localId(id)) ?? []), id]);
70
+ }
71
+ for (const id of requirementIds) if (!aliases.has(id)) aliases.set(id, { reason: 'requirement-row' });
72
+ for (const [key, ids] of carriers)
73
+ if (!aliases.has(key)) aliases.set(key, ids.length === 1 ? { id: ids[0] } : { reason: 'ambiguous-local-id', carriers: ids });
74
+ for (const id of requirementIds) if (!aliases.has(localId(id))) aliases.set(localId(id), { reason: 'requirement-row' });
75
+ return aliases;
76
+ }
77
+
78
+ /**
79
+ * Mirror Steps 2-4 dispositions; the fresh-failure cap uses each record's actual SHA. Records are
80
+ * normalized through `aliases` before failure grouping, so a pass and a fail for one criterion meet
81
+ * whichever spelling each used; the supplied id stays on the record for diagnostics.
82
+ */
83
+ function liveReference(capture, aliases) {
56
84
  if (!capture) return;
57
85
  const { manifest, currentSha } = capture;
58
86
  if (!manifest) return { present: true, freshness: 'unreadable', current_source_sha: currentSha, failed: 0, freshFailed: 0 };
@@ -60,13 +88,13 @@ function liveReference(capture, criterionIds) {
60
88
  const records = manifest.results.map((entry) => {
61
89
  const row = entry && typeof entry === 'object' && !Array.isArray(entry) ? entry : {};
62
90
  const id = asString(row.id),
63
- requirement = asString(row.requirement_id),
91
+ supplied = asString(row.requirement_id),
64
92
  status = asString(row.status).toLowerCase();
65
93
  const sha = normalizedSha(row.source_sha ?? manifest.source_sha);
66
94
  const duplicate = Boolean(id) && seen.has(id);
67
95
  if (id) seen.add(id);
68
96
  let disposition;
69
- if (!id || !requirement || !['pass', 'fail', 'blocked', 'skipped'].includes(status) || !sha || duplicate) disposition = 'invalid';
97
+ if (!id || !supplied || !['pass', 'fail', 'blocked', 'skipped'].includes(status) || !sha || duplicate) disposition = 'invalid';
70
98
  else if (status !== 'pass') disposition = status;
71
99
  else if (!currentSha) disposition = 'unverifiable';
72
100
  else if (shaMatches(sha, currentSha)) {
@@ -74,13 +102,16 @@ function liveReference(capture, criterionIds) {
74
102
  } else {
75
103
  disposition = 'stale';
76
104
  }
77
- return { requirement, sha, disposition };
105
+ const resolved = aliases.get(supplied);
106
+ return { id, supplied, requirement: resolved?.id ?? supplied, resolved, sha, disposition, reason: null };
78
107
  });
79
108
  const failedRequirements = new Set(records.filter((row) => row.disposition === 'fail').map((row) => row.requirement));
80
109
  for (const row of records) {
81
110
  if (row.disposition !== 'counted') continue;
82
- if (!criterionIds.has(row.requirement)) row.disposition = 'unmatched';
83
- else if (failedRequirements.has(row.requirement)) row.disposition = 'contradicted';
111
+ if (!row.resolved?.id) {
112
+ row.disposition = 'unmatched';
113
+ row.reason = row.resolved?.reason ?? 'unknown-id';
114
+ } else if (failedRequirements.has(row.requirement)) row.disposition = 'contradicted';
84
115
  }
85
116
  const count = (status) => records.filter((row) => row.disposition === status).length;
86
117
  return {
@@ -95,7 +126,14 @@ function liveReference(capture, criterionIds) {
95
126
  : 'stale'
96
127
  : 'unverifiable',
97
128
  freshFailed: records.filter((row) => row.disposition === 'fail' && shaMatches(row.sha, currentSha)).length,
129
+ records: records.map((row) => ({
130
+ id: row.id,
131
+ supplied_requirement_id: row.supplied,
132
+ requirement_id: row.requirement,
133
+ disposition: row.disposition,
134
+ reason: row.reason,
135
+ })),
98
136
  };
99
137
  }
100
138
 
101
- module.exports = { captureLiveResults, assertLiveSourceRevision, liveReference };
139
+ module.exports = { captureLiveResults, assertLiveSourceRevision, liveAliasMap, liveReference, localId };
package/cli/trace.js CHANGED
@@ -9,6 +9,8 @@ const { captureLiveResults, assertLiveSourceRevision } = require('./lib/trace-li
9
9
  const { addAgentOptions, projectPath, readInput, resolveWorkflowSkill, headlessPrompt, runWithEvidence } = require('./lib/workflow-cli');
10
10
  const {
11
11
  sourceOracleLedger,
12
+ epicTicketSources,
13
+ requirementOracle,
12
14
  COLLECTION_MODES,
13
15
  GATE_TYPES,
14
16
  resolveTraceTarget,
@@ -65,7 +67,16 @@ function execute(options, registerOutputGuard = () => {}) {
65
67
  const targetFile = options.target ? readInput(projectRoot, options.target, '--target') : undefined;
66
68
  const target = resolveTraceTarget({ projectRoot, target: targetFile, targetId: options.targetId, gateType: options.gateType });
67
69
  const targetText = targetFile ? fs.readFileSync(targetFile, 'utf8') : '';
68
- const oracleLedger = sourceOracleLedger(targetText, targetFile ?? 'project');
70
+ const oracleLedger = sourceOracleLedger(targetText, targetFile ?? 'project', target);
71
+ // The requirement oracle's criteria come from the epic's tickets; capture them before the agent runs.
72
+ const tickets = requirementOracle(target, oracleLedger) ? epicTicketSources(projectRoot, target) : undefined;
73
+ const requirementLines = tickets
74
+ ? [
75
+ `This is v7 epic ${target.epicKey}; the frozen ledger holds its Requirements lines. Record oracleGranularity: requirements.`,
76
+ 'Persist Step 1 criterionLedger and the requirement and exception oracleLedger rows in matrix YAML frontmatter with every field Step 1 section 1b names.',
77
+ 'In the summary JSON, set oracle.granularity to "requirements" and oracle.rows to one entry per oracleLedger row, in ledger order: {id, kind, priority, priority_basis, coverage}, plus parent, missing_behaviors and contributors [{id, story, coverage}] for a requirement row, or exception for an exception row.',
78
+ ]
79
+ : [];
69
80
  const liveResults = options.liveResults
70
81
  ? readInput(projectRoot, options.liveResults, '--live-results')
71
82
  : path.join(artifactRoot, 'live-verification-results.json');
@@ -83,7 +94,7 @@ function execute(options, registerOutputGuard = () => {}) {
83
94
  const rightStat = fs.statSync(right);
84
95
  return leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino;
85
96
  };
86
- const inputs = [targetFile, liveResults, waiverRegister].filter(Boolean);
97
+ const inputs = [...new Set([targetFile, liveResults, waiverRegister, ...(tickets?.files.keys() ?? [])].filter(Boolean))];
87
98
  const heldInputs = inputs.map((file) => {
88
99
  if (!fs.existsSync(file)) return { file, missing: true };
89
100
  const stat = fs.statSync(file);
@@ -104,7 +115,7 @@ function execute(options, registerOutputGuard = () => {}) {
104
115
  if (outputs.some((left, index) => outputs.slice(index + 1).some((right) => aliases(left, right))))
105
116
  throw new Error('Trace artifacts must use separate paths from each other.');
106
117
  if (Object.values(destinations).some((output) => inputs.some((input) => aliases(output, input))))
107
- throw new Error('Trace artifacts must use separate paths from the target, live results, and waiver register.');
118
+ throw new Error('Trace artifacts must use separate paths from the target, its ticket sources, live results, and waiver register.');
108
119
  if (!options.json) return;
109
120
  projectPath(projectRoot, options.json, '--json');
110
121
  const protectedPaths = [...inputs, ...Object.values(destinations)];
@@ -133,6 +144,7 @@ function execute(options, registerOutputGuard = () => {}) {
133
144
  'Execute both trace phases, finishing Step 5. Use deterministic gate decisions.',
134
145
  `Frozen source oracle ledger: ${JSON.stringify(oracleLedger)}. Preserve its requirement text, source references, identities, and explicit priorities in Step 1 and the final matrix.`,
135
146
  'Persist Step 1 oracleLedger in matrix YAML frontmatter as an array of {id, requirement, priority, source} records. Assign priorities only where the source leaves them unspecified.',
147
+ ...requirementLines,
136
148
  `The only trace target for this run is ${target.document ? JSON.stringify(target.document) : `the project (${target.runScope})`}.`,
137
149
  `Resolved identity: ${JSON.stringify(target)}. Preserve it in every output.`,
138
150
  `Resolve {gate_type} to ${JSON.stringify(target.type)}, {run_scope} to ${JSON.stringify(target.runScope)}, and {run_key} to ${JSON.stringify(target.runKey)}.`,
@@ -179,6 +191,7 @@ function execute(options, registerOutputGuard = () => {}) {
179
191
  requireOracleLedger: true,
180
192
  liveCapture,
181
193
  requireLiveManifest: true,
194
+ tickets,
182
195
  });
183
196
  },
184
197
  });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "$schema": "https://json.schemastore.org/package.json",
3
3
  "name": "bmad-method-test-architecture-enterprise",
4
- "version": "3.5.0",
4
+ "version": "3.6.1",
5
5
  "description": "Master Test Architect for quality strategy, test automation, and release gates",
6
6
  "keywords": [
7
7
  "bmad",
@@ -27,6 +27,12 @@ This checklist covers **two sequential phases**:
27
27
 
28
28
  - [ ] Story file read successfully (if applicable)
29
29
  - [ ] Oracle items extracted or inferred correctly
30
+ - [ ] Each `oracleLedger` row built from a numbered criterion with a bold name records that bold name alone as its `requirement`, without the parenthesised `R` ids or priority (`Order number shown`); a `verify`-only criterion's row records its `verify` text. This holds for criterion-oracle rows and for exception rows alike
31
+ - [ ] `oracleGranularity` recorded: `requirements` only for a fresh run on a v7 epic whose file has at least one `R<n>` Requirements line, `criteria` for every other target; a checkpoint with no `oracleGranularity` resumed as a criterion-oracle run
32
+ - [ ] A v7 epic run keyed `epic-<epic key>` (`epic-shop--e1`), the key never slugged; a v6 epic keeps `epic-<epic_num>`
33
+ - [ ] For a requirement-granularity run: `criterionLedger` holds every criterion the story contract selects for every entry in the epic's `tickets/tickets.toml`, each with `localId`, `story`, its `name` (a numbered criterion's bold name alone, a `verify`-only criterion's `verify` text), its full frozen `text`, a `source` at the line holding its bold name or `verify` text, `priority`, `priorityBasis`, `declaredLinks`, `validLinks`, `invalidLinks`, and `exception`; `oracleLedger` holds one row per `R<n>` line plus one row per criterion whose `exception` is not `none`; every row records `priorityBasis`
34
+ - [ ] A requirement row with no explicit priority and at least one contributor records `priorityBasis: contributors` and the highest contributor priority; `inferred` only when it has no contributors
35
+ - [ ] A duplicate local `R` id halted the run before mapping, naming both source lines
30
36
  - [ ] Story ID identified (e.g., 1.3)
31
37
  - [ ] Test design loaded (if available): `{test_artifacts}/test-design/test-design-epic-{epic_num}.md` for an epic or for a story's epic (epic number from the story id), or `test-design-architecture.md` and `test-design-qa.md` at system level, falling back to the same names at the legacy root `{test_artifacts}/`
32
38
  - [ ] NFR evidence audit loaded (if available), first match of `nfr/nfr-assessment-{run_key}.md`, then for a story `nfr/nfr-assessment-epic-{epic_num}.md`, then `nfr/nfr-assessment-system.md`, then the legacy root `nfr-assessment.md`, with the file used named
@@ -44,6 +50,8 @@ This checklist covers **two sequential phases**:
44
50
  - [ ] Each live result classified against the commit under trace (only a fresh `pass` counts as coverage)
45
51
  - [ ] `stale`, `unverifiable`, `fail`, `contradicted`, `blocked`, `skipped`, `unmatched`, and `invalid` live results raised as blockers with reasons
46
52
  - [ ] `live_only` derived from each requirement's active mapped tests, never read from a flag an earlier step was asked to set
53
+ - [ ] In a requirement-granularity run, a gate row whose status is not NONE is live-only when it depends on a live-only criterion: an exception row on its own criterion, a requirement row on any contributor whose status is not NONE
54
+ - [ ] Every live record resolved through the shared alias map before failure grouping: a qualified criterion id to itself, a unique local id to its criterion, an ambiguous local id or a requirement row id `unmatched` with its reason
47
55
  - [ ] Test metadata extracted:
48
56
  - [ ] Test IDs (e.g., 1.3-E2E-001)
49
57
  - [ ] Describe/context blocks
@@ -84,6 +92,9 @@ This section is the definition of the five coverage statuses. Every other file i
84
92
  - [ ] **UNIT-ONLY** and **INTEGRATION-ONLY** applied only where the missing level is what leaves the criterion unestablished. A criterion an appropriate single level establishes in full is **FULL**, and `resources/traceability-matrix.example.md` classifies two single-level criteria that way
85
93
  - [ ] Classification justifications provided
86
94
  - [ ] Edge cases considered in FULL vs PARTIAL determination
95
+ - [ ] In a requirement-granularity run, each requirement row is FULL only when it has at least one contributor, every contributor is FULL, and the contributors' stated behaviors together establish every behavior the requirement line states (the "every stated scenario" rule above, applied to the requirement text). A behavior no contributor states is listed in `missingBehaviors` and keeps the row below FULL
96
+ - [ ] A requirement row is NONE when it has no contributor ("no story covers it") or every contributor is NONE, and PARTIAL otherwise; UNIT-ONLY and INTEGRATION-ONLY contributors count as not FULL and are listed in its gaps
97
+ - [ ] Every gate row built by Step 3 section 1c records its `kind`, and every contributor test keeps its `skipped`, `pending`, and `fixme` flags
87
98
 
88
99
  ---
89
100
 
@@ -127,6 +138,7 @@ This section is the definition of the five coverage statuses. Every other file i
127
138
  ## Coverage Metrics
128
139
 
129
140
  - [ ] Overall coverage percentage calculated (FULL coverage / total criteria)
141
+ - [ ] In a requirement-granularity run, statistics, priority buckets, and thresholds computed over the `oracleLedger` rows, invalid-link and unlinked exception rows included; unique test counts and per-level `criteria_covered` computed from the criterion rows, each criterion and test counted once
130
142
  - [ ] P0 coverage percentage calculated
131
143
  - [ ] P1 coverage percentage calculated
132
144
  - [ ] P2 coverage percentage calculated (if applicable)
@@ -176,6 +188,11 @@ Knowledge fragments referenced:
176
188
  - [ ] Gap analysis section included
177
189
  - [ ] Quality assessment section included
178
190
  - [ ] Recommendations section included
191
+ - [ ] Every detail heading reads `<id> (P<n>): <requirement>`, its text repeating the `oracleLedger` row's `requirement` exactly and `(P<n>)` its only annotation; the priority basis and any `R` links sit in the detail body. A heading such as `AC-1: Order number shown (R1) (P0, inferred)` fails validation
192
+ - [ ] In a requirement-granularity run, the gate table (`| ID | Requirement | Priority | Coverage |`) and the detail headings (`### <id> (P<n>): <text>`) list exactly the `oracleLedger` rows, the Requirement cell and heading text both repeating the ledger's `requirement` exactly, with its priority
193
+ - [ ] Each requirement detail carries its parent link, `missingBehaviors`, and, when it has contributors, a contributors table headed exactly `| Contributor | Story | Status | Tests |` with one row per contributor; a requirement with no contributors reads `**Contributors:** none` and has no table; contributing criteria appear as no heading and no gate table row
194
+ - [ ] In a requirement-granularity run, the report keeps Step 3's `Requirement Aggregation` heading and its ` ```json ` block unchanged, and every final criterion status, requirement status, and missing behavior matches it
195
+ - [ ] The Invalid and Unlinked Criteria section names every exception row with its declared and invalid links
179
196
 
180
197
  ### Machine-Readable JSON Output
181
198
 
@@ -185,7 +202,7 @@ Knowledge fragments referenced:
185
202
  - [ ] `repo`, `collection_mode`, `collection_status`, `inventory_basis`, and `source_sha` fields populated
186
203
  - [ ] `gate_basis` populated (`priority_thresholds` when gate-eligible, `none` otherwise)
187
204
  - [ ] `snapshot_at` replaces the old `generated_at` timestamp field
188
- - [ ] Oracle metadata populated (`resolution_mode`, `confidence`, `sources`, `external_pointer_status`, `synthetic`)
205
+ - [ ] Oracle metadata populated (`resolution_mode`, `confidence`, `sources`, `external_pointer_status`, `synthetic`, `granularity`)
189
206
  - [ ] `target.type` and `target.id` identify the evaluated story / epic / release / hotfix
190
207
  - [ ] `gate_status` populated only when `allow_gate: true` and `collection_status` is `COLLECTED`
191
208
  - [ ] `coverage.inventory` includes `covered`, `total`, and `pct`
@@ -200,6 +217,8 @@ Knowledge fragments referenced:
200
217
  - [ ] `recommendations` array present (may be empty)
201
218
  - [ ] `waivers` present when `{waiver_register_input}` exists, carrying `register`, `filed`, `valid`, `invalid`, and one entry per waiver with its `id`, `covers`, `valid` flag, and `failed_checks`; absent when no register was found
202
219
  - [ ] `rejected_evidence` array present (may be empty), one entry per test whose name claims a criterion its assertions do not establish
220
+ - [ ] `oracle.granularity` present in the summary and the Phase 1 matrix (`criteria` or `requirements`); in a requirement-granularity run, each gate row of the Phase 1 matrix carries its `kind`, and each requirement row a `contributors` array and `missingBehaviors`
221
+ - [ ] In a requirement-granularity run, the summary's `oracle.rows` lists every `oracleLedger` row in ledger order with `id`, `kind`, `priority`, `priority_basis`, and `coverage`; requirement rows add `parent`, `missing_behaviors`, and `contributors` (`id`, `story`, `coverage`), exception rows add `exception`
203
222
  - [ ] `links.trace_report_path` points to this run's `{outputFile}` (`trace/traceability-matrix-{run_key}.md`)
204
223
  - [ ] `links.trace_report_url`, `links.artifact_url`, and `links.journey_evidence_url` fields present (may be empty)
205
224
  - [ ] `gate-decision-{run_key}.json` written to `{gate_decision_output}` when gate-eligible
@@ -48,7 +48,7 @@ Coverage status uses FULL, PARTIAL, NONE, UNIT-ONLY, and INTEGRATION-ONLY, defin
48
48
 
49
49
  ### Detailed Mapping
50
50
 
51
- #### AC-1: Administrator schedules a weekly report for their tenant, P0
51
+ #### AC-1 (P0): Administrator schedules a weekly report for their tenant
52
52
 
53
53
  - **Coverage:** FULL
54
54
  - **Tests:**
@@ -56,7 +56,7 @@ Coverage status uses FULL, PARTIAL, NONE, UNIT-ONLY, and INTEGRATION-ONLY, defin
56
56
  - `6-API-001`, `tests/api/report-schedules.spec.ts:24`: persists cadence, recipients, timezone, and report type
57
57
  - **Recommendation:** None
58
58
 
59
- #### AC-2: Cross-tenant schedule access is denied, P0
59
+ #### AC-2 (P0): Cross-tenant schedule access is denied
60
60
 
61
61
  - **Coverage:** FULL
62
62
  - **Tests:**
@@ -64,21 +64,21 @@ Coverage status uses FULL, PARTIAL, NONE, UNIT-ONLY, and INTEGRATION-ONLY, defin
64
64
  - `6-E2E-002`, `tests/e2e/scheduled-report-permissions.spec.ts:20`: hides the schedule editor from a tenant Viewer
65
65
  - **Recommendation:** None
66
66
 
67
- #### AC-3: Administrator pauses and resumes a schedule, P1
67
+ #### AC-3 (P1): Administrator pauses and resumes a schedule
68
68
 
69
69
  - **Coverage:** FULL
70
70
  - **Tests:**
71
71
  - `6-API-003`, `tests/api/report-schedules.spec.ts:79`: transitions ACTIVE to PAUSED and back without changing recipients
72
72
  - **Recommendation:** None
73
73
 
74
- #### AC-4: Invalid or duplicate recipients receive field-level guidance, P1
74
+ #### AC-4 (P1): Invalid or duplicate recipients receive field-level guidance
75
75
 
76
76
  - **Coverage:** FULL
77
77
  - **Tests:**
78
78
  - `6-COMP-001`, `tests/component/report-recipient-editor.spec.tsx:42`: validates malformed and duplicate addresses through user-level interaction
79
79
  - **Recommendation:** None
80
80
 
81
- #### AC-5: Delivery retries after provider failure and surfaces final failure, P1
81
+ #### AC-5 (P1): Delivery retries after provider failure and surfaces final failure
82
82
 
83
83
  - **Coverage:** PARTIAL
84
84
  - **Tests:**
@@ -86,21 +86,21 @@ Coverage status uses FULL, PARTIAL, NONE, UNIT-ONLY, and INTEGRATION-ONLY, defin
86
86
  - **Gap:** No test exhausts the retry budget and proves the schedule history shows a final failed delivery with an actionable reason.
87
87
  - **Recommendation:** Add `6-E2E-003` for the exhausted-retry history state and `6-API-006` for the terminal provider response.
88
88
 
89
- #### AC-6: Next delivery respects the selected timezone across daylight-saving changes, P1
89
+ #### AC-6 (P1): Next delivery respects the selected timezone across daylight-saving changes
90
90
 
91
91
  - **Coverage:** FULL
92
92
  - **Tests:**
93
93
  - `6-UNIT-001`, `tests/unit/next-report-run.test.ts:15`: checks both spring-forward and fall-back boundaries with a fixed clock
94
94
  - **Recommendation:** None
95
95
 
96
- #### AC-7: Schedule changes emit a complete audit event, P1
96
+ #### AC-7 (P1): Schedule changes emit a complete audit event
97
97
 
98
98
  - **Coverage:** FULL
99
99
  - **Tests:**
100
100
  - `6-INT-001`, `tests/integration/report-schedule-audit.test.ts:33`: asserts actor, tenant, prior state, new state, and schedule ID
101
101
  - **Recommendation:** None
102
102
 
103
- #### AC-8: Administrator can set an optional safe filename prefix, P2
103
+ #### AC-8 (P2): Administrator can set an optional safe filename prefix
104
104
 
105
105
  - **Coverage:** FULL
106
106
  - **Tests:**
@@ -82,7 +82,7 @@ Resolve the oracle in this order:
82
82
  - `P2`: secondary workflows and edge scenarios
83
83
  - `P3`: low-risk polish or optional flows
84
84
 
85
- Persist `oracleLedger` in this step's progress YAML frontmatter as an array of `{id, requirement, priority, source}` records: one row per item with its stable ID, requirement text, priority, and source reference. An explicit priority in the selected oracle is authoritative for that item's coverage statistics. Infer a priority with `test-priorities-matrix.md` only when the oracle leaves it unspecified, and record that inference. A mapped test's own priority describes the test and never changes the oracle item's priority. Carry this ledger through mapping and gap analysis, including resumed runs.
85
+ Persist `oracleLedger` in this step's progress YAML frontmatter as an array of `{id, requirement, priority, source}` records: one row per item with its stable ID, requirement text, priority, and source reference. For a numbered criterion with a bold name, such as `1. **Order number shown** (R1, P0)` followed by its Given, When, and Then lines, the row's `requirement` is the bold name alone, `Order number shown`, without the parenthesised `R` ids or priority after it. For a `verify`-only story's single criterion it is the `verify` text. Every other item keeps its source text, and a criterion whose source states its id before a colon (`AC-1: Admin may export`) keeps the text after the colon. A run with `oracleGranularity: requirements` builds its ledgers by section 1b; every rule in this paragraph and the next still applies to them. An explicit priority in the selected oracle is authoritative for that item's coverage statistics. Infer a priority with `test-priorities-matrix.md` only when the oracle leaves it unspecified, and record that inference. A mapped test's own priority describes the test and never changes the oracle item's priority. Carry this ledger through mapping and gap analysis, including resumed runs.
86
86
 
87
87
  For local source files, read numbered lines before recording each ledger source reference. When the source declares an item's ID and priority, cite that line. For an inferred item, cite numbered source lines that support its requirement; the generated ID and priority stay in the ledger. Check each source line independently because headings and criteria may span different numbers of lines.
88
88
 
@@ -98,6 +98,75 @@ If none of the four oracle types can be resolved, **HALT** and request the small
98
98
 
99
99
  ---
100
100
 
101
+ ## 1b. Oracle Granularity and the v7 Requirement Spine
102
+
103
+ Record `oracleGranularity` beside `coverageBasis` and `oracleResolutionMode`. It is `requirements` or `criteria`.
104
+
105
+ ### A) When the Spine Applies
106
+
107
+ A fresh run uses the requirement oracle and records `oracleGranularity: requirements` only when both hold:
108
+
109
+ - Its target is a v7 epic: the user names an epic, or the target reference resolves through `{tea-contracts}/story-identity.md` to a container its section 3 classifies as an epic. A v7 epic is an `epic-*` folder inside an initiative's `tickets/` folder.
110
+ - That epic's file has at least one Requirements line of the form `R<n> (<parent or source>): <line>`, for example `R1 (parent R2): Shopper pays with a saved card`.
111
+
112
+ Such a run also records `coverageBasis: acceptance_criteria` and `oracleResolutionMode: formal_requirements`.
113
+ Every other target keeps the criterion oracle and records `oracleGranularity: criteria`: a story, a release, a hotfix, the system, a v6 epic, and a v7 epic whose file has no `R<n>` line. Section 1's ledger rules then apply unchanged, and the rest of this section does not.
114
+ Only a fresh run decides granularity. A checkpoint with no `oracleGranularity` is a criterion-oracle run and resumes as one, with its rows and evidence unchanged; `step-01b-resume.md` never re-decides it.
115
+ Initiative-wide tracing is out of scope: an initiative target keeps the criterion oracle, and epic rows never roll up to initiative `R` lines.
116
+
117
+ ### B) Duplicate Requirement IDs
118
+
119
+ Read the epic file's Requirements section with numbered lines before building any ledger.
120
+ Two `R` lines with the same local id in one epic **halt** the run before mapping. Name the id and both source `path:line` locations, and ask for the epic file to be corrected.
121
+ Never merge, renumber, or skip either line, and save no ledger for the run. A halted run emits no matrix, summary, or gate decision.
122
+
123
+ ### C) `criterionLedger`
124
+
125
+ For every entry in the epic's `tickets/tickets.toml`, resolve and read its story by `{tea-contracts}/story-identity.md` sections 2 and 4. Record every criterion the contract selects, in the contract's order, as one `criterionLedger` record. The ticket's numbered criteria are a story leaf's under `## Requirements` and a bug or spike leaf's under `## Acceptance Criteria`. A plan's acceptance criteria are the list under its Acceptance Criteria heading, or the list after the bold `**Acceptance Criteria:**` label in its `## Tasks & Acceptance` section. The CLI captures the same criteria from the same files before the run and rejects a ledger that omits, adds, renames, or rewrites any of them:
126
+
127
+ - `id`: `<story key>--<localId>`, for example `shop--e1-s2--AC-1`.
128
+ - `localId`: the id the source states for the criterion (`AC-1`); else `AC-<n>` from its position in the numbered list; `verify` for a `verify`-only story's single criterion.
129
+ - `story`: the story key.
130
+ - `name`: the criterion's name. For a numbered criterion that is its bold name alone, without the parenthesised `R` ids or priority after it: `Order number shown` for `1. **Order number shown** (R1, P0)`. For a plan criterion it is its bold label, else its first line, again without the parenthesised `R` ids or priority. For a `verify`-only story's single criterion it is the `verify` text.
131
+ - `text`: the criterion's frozen full text as the source states it with the list marker removed. For a numbered criterion that is its name line (the bold name and the `R` ids it names) followed by every line beneath it (Given, When, Then, And, a spike's `Verify:` line, and any fenced or indented block such as a Gherkin scenario or an expected body, fences included), joined with single spaces. For a `verify`-only story's single criterion it is the `verify` text: the pulled leaf's `Verify:` line once the story has a leaf, else the entry's `verify`.
132
+ - `source`: the `path:line` where the criterion starts: the line holding a numbered criterion's bold name, a plan criterion's first line, or the `verify` text. Never a Given, When, or Then line.
133
+ - `priority` and `priorityBasis`: by section E. Every record carries both.
134
+ - `declaredLinks`: the `R` ids the criterion names. For a `verify`-only story's single criterion, the story's `covers`: the pulled leaf's frontmatter `covers` once the story has a leaf, else the entry's.
135
+ - `validLinks`: the declared ids the epic's Requirements define. `invalidLinks`: the declared ids it does not.
136
+ - `exception`: `unlinked` when `declaredLinks` is empty; `invalid-link` when `invalidLinks` is not empty, even when `validLinks` is not; `none` otherwise.
137
+
138
+ A criterion contributes to every requirement in its `validLinks`. A criterion with any `exception` other than `none` also gets its own gate row in section D, so it never leaves the gate.
139
+ Every ledger id uses only letters, digits, `.`, `_`, and `-`. Spell a source id that holds any other character with each run of such characters replaced by `-`. A `localId` never contains `--`, so the part of a criterion id after its last `--` is always its `localId`; spell a source id that holds `--` with a single `-`.
140
+
141
+ ### D) `oracleLedger`
142
+
143
+ The `oracleLedger` is the gate inventory, and the CLI validates it. Write one row per `R<n>` line, in the epic file's order:
144
+
145
+ - `id`: `<epic key>--R<n>`, for example `shop--e1--R1`. `<epic key>` is the key section 4 B resolves.
146
+ - `kind`: `requirement`.
147
+ - `requirement`: the line's frozen text after its `R<n> (...):` prefix.
148
+ - `parent`: what the line's parentheses name (`parent R2`, or the source section a split or added line names).
149
+ - `source`: the line's `path:line`.
150
+ - `priority` and `priorityBasis`: by section E.
151
+ - `contributors`: the ids of every `criterionLedger` record whose `validLinks` include `R<n>`, in ledger order. Empty when no story covers the requirement.
152
+
153
+ Then write one row per `criterionLedger` record whose `exception` is not `none`:
154
+
155
+ - `id`: the criterion's id. `kind`: `exception`. `exception`: `unlinked` or `invalid-link`.
156
+ - `requirement`: the criterion's `name`. A numbered criterion's row reads `Form remembers address`, its bold name alone.
157
+ - `source`, `priority`, and `priorityBasis`: the criterion's own.
158
+
159
+ ### E) Priorities
160
+
161
+ Assign every ledger record its priority and record `priorityBasis` now, before mapping. P0 is the highest priority.
162
+
163
+ - A `criterionLedger` record takes the explicit priority its criterion states (`explicit`); else one inferred from its behavior and story risk with `test-priorities-matrix.md` (`inferred`). Its `priorityBasis` is `explicit` or `inferred`.
164
+ - A requirement row takes the explicit priority its `R` line states (`explicit`); else the highest priority among its contributors (`contributors`); else, with no contributors, one inferred from the requirement text and epic context with `test-priorities-matrix.md` (`inferred`).
165
+ - `contributors` means exactly this: the row's priority is the highest `priority` recorded on the `criterionLedger` records its `contributors` list, whatever each record's own `priorityBasis`. A contributor at P0 makes the row P0. A requirement row with at least one contributor and no explicit priority always records `contributors`; `inferred` is recorded only when its `contributors` list is empty.
166
+ - An exception row copies its criterion's `priority` and `priorityBasis` unchanged. A story's risk never lowers a priority its criterion states.
167
+
168
+ ---
169
+
101
170
  ## 2. Load Knowledge Base
102
171
 
103
172
  From `{knowledgeIndex}` load:
@@ -148,7 +217,7 @@ Resolve the gate type in this order:
148
217
  Resolve the target for that gate type in the same order: the target the user named in this invocation first, then the target the loaded artifacts carry.
149
218
 
150
219
  - **story:** `story_id` and `story_key` by `{tea-contracts}/story-identity.md`, which also resolves and reads the story: `1.2` and `shop--e1-s2` for a v7 epic entry, the story's own id and its file basename (`1-2-user-authentication`) for a v6 story.
151
- - **epic:** `epic_num`, read from the epic document metadata, its H1 heading, or its filename. If the epic carries no number, use the slug of its title (slug rule below) in place of the number.
220
+ - **epic:** for a v7 epic (section 1b A), `epic_key` by `{tea-contracts}/story-identity.md` section 4: `<initiative>--e<epic id>` (`shop--e1`), or `<initiative>--<epic folder>` (`shop--epic-loyalty`) for an epic its initiative does not number. The target id is the epic key, and `epic_num` is the epic id (empty for an unnumbered epic). For a v6 epic, `epic_num`, read from the epic document metadata, its H1 heading, or its filename. If the v6 epic carries no number, use the slug of its title (slug rule below) in place of the number.
152
221
  - **release:** the release version, from this invocation or from the release notes or version the loaded artifacts name.
153
222
  - **hotfix:** the hotfix id, from this invocation or from the loaded artifacts.
154
223
 
@@ -166,12 +235,13 @@ If no target can be resolved at all, the run covers the whole project or system:
166
235
  Set `run_key` from the gate type and target:
167
236
 
168
237
  - `story-{story_key}`: one story.
169
- - `epic-{epic_num}`: one epic.
238
+ - `epic-{epic_key}`: one v7 epic, for example `epic-shop--e1`. Two initiatives with the same epic number or epic folder name get separate matrices, summaries, and gate files. The epic key is used as written; never slug it, because slugging collapses its `--`.
239
+ - `epic-{epic_num}`: one v6 epic.
170
240
  - `release-{slug}`: one release, where `{slug}` is the slug of the release version.
171
241
  - `hotfix-{slug}`: one hotfix, where `{slug}` is the slug of the hotfix id.
172
242
  - `system`: the whole project or system, or no narrower scope could be resolved. Target id and label stay empty, the gate type stays the one resolved in A, and the output states "No story, epic, release, or hotfix target could be resolved; this run is scoped to `system`."
173
243
 
174
- Slug rule, used for every `{slug}` and for an epic title with no number: lowercase; replace every run of characters outside `a-z` and `0-9` with a single `-`; trim leading and trailing `-`; truncate to 64 characters.
244
+ Slug rule, used for every `{slug}` and for a v6 epic title with no number: lowercase; replace every run of characters outside `a-z` and `0-9` with a single `-`; trim leading and trailing `-`; truncate to 64 characters.
175
245
 
176
246
  Set `run_scope` to the kind of key: `story`, `epic`, `release`, `hotfix`, or `system`.
177
247
 
@@ -222,12 +292,56 @@ oracleConfidence: '{resolved oracle_confidence}'
222
292
  oracleResolutionMode: '{resolved oracle_resolution_mode}'
223
293
  oracleSources: ['{resolved oracle source 1}', '{resolved oracle source 2}']
224
294
  externalPointerStatus: '{resolved external_pointer_status}'
295
+ oracleGranularity: '{criteria | requirements}'
225
296
  oracleLedger: [{ id: '{oracle item id}', requirement: '{requirement text}', priority: '{P0-P3}', source: '{source reference}' }]
226
297
  ---
227
298
  ```
228
299
 
229
300
  Then write this step's output below the frontmatter.
230
301
 
302
+ For a run with `oracleGranularity: requirements`, write the ledgers section 1b defines, with every field it names:
303
+
304
+ ```yaml
305
+ oracleGranularity: 'requirements'
306
+ criterionLedger:
307
+ - {
308
+ id: '{story key}--{localId}',
309
+ localId: '{localId}',
310
+ story: '{story key}',
311
+ name: '{criterion name}',
312
+ text: '{frozen full criterion text}',
313
+ source: '{path:line}',
314
+ priority: '{P0-P3}',
315
+ priorityBasis: '{explicit | inferred}',
316
+ declaredLinks: ['{R id}'],
317
+ validLinks: ['{R id}'],
318
+ invalidLinks: ['{R id}'],
319
+ exception: '{none | unlinked | invalid-link}',
320
+ }
321
+ oracleLedger:
322
+ - {
323
+ id: '{epic key}--R{n}',
324
+ kind: 'requirement',
325
+ requirement: '{frozen line text}',
326
+ parent: '{parent R<m> or source section}',
327
+ source: '{path:line}',
328
+ priority: '{P0-P3}',
329
+ priorityBasis: '{explicit | contributors | inferred}',
330
+ contributors: ['{criterion id}'],
331
+ }
332
+ - {
333
+ id: '{criterion id}',
334
+ kind: 'exception',
335
+ exception: '{unlinked | invalid-link}',
336
+ requirement: '{criterion name}',
337
+ source: '{path:line}',
338
+ priority: '{P0-P3}',
339
+ priorityBasis: '{explicit | inferred}',
340
+ }
341
+ ```
342
+
343
+ Steps 3, 4, and 5 and Resume read these ledgers from the frontmatter, so a resumed run reproduces the same rows.
344
+
231
345
  For a story run (`run_scope` is `story`), also write `storyId`, `storyKey`, `ticketRef` and `storyFile` into this frontmatter, as `{tea-contracts}/story-identity.md` section 4 defines them. Other scopes leave them out.
232
346
 
233
347
  `runScope`, `runKey`, `targetType`, `targetId`, and `targetLabel` are this run's identity. Later steps carry them forward unchanged and never re-derive them: Step 4 reads the target from this frontmatter, and Resume mode refuses to continue a file whose `runKey` does not match the run being resumed.
@@ -241,10 +355,12 @@ Load next step: `{nextStepFile}`
241
355
  - Step completed in full with required outputs
242
356
  - Gate target, `run_scope`, and `run_key` resolved before the first save, persisted in the frontmatter, and the output written to the path they name
243
357
  - Any pre-existing output for this scope was reported to the user and either resumed or replaced
358
+ - `oracleGranularity` recorded; a requirement-granularity run persisted `criterionLedger` and `oracleLedger`, every row with its `priorityBasis`, before mapping
244
359
 
245
360
  ### ❌ SYSTEM FAILURE:
246
361
 
247
362
  - Skipped sequence steps or missing outputs
363
+ - A criterion dropped from the gate because it has no valid link, or a requirement row built from an epic with a duplicate local `R` id
248
364
  - Saving progress before run identity is resolved, or writing to an output path that carries no run identity
249
365
  - Appending this run's progress to an output left by a previous run, or reading or writing another scope's output
250
366
  **Master Rule:** Skipping steps is FORBIDDEN.
@@ -37,7 +37,7 @@ Resume an interrupted workflow by selecting the traceability matrix that belongs
37
37
 
38
38
  ### 1. Select the Run to Resume
39
39
 
40
- Each run writes its own matrix at `{outputFile}`, where `run_key` is `story-{story_key}`, `epic-{epic_num}`, `release-{slug}`, `hotfix-{slug}`, or `system`. Build the candidate list:
40
+ Each run writes its own matrix at `{outputFile}`, where `run_key` is `story-{story_key}`, `epic-{epic_key}` for a v7 epic, `epic-{epic_num}` for a v6 epic, `release-{slug}`, `hotfix-{slug}`, or `system`. Build the candidate list:
41
41
 
42
42
  1. List every file matching `{progressGlob}`.
43
43
  2. Also check `{legacyOutputFile}`. Runs from before outputs carried run identity wrote to that fixed name. It is a candidate only while it is in progress: read its `workflowStatus`, or infer it from `lastStep` as section 2 describes when the field is absent. A completed legacy matrix stays where it is and is never moved or deleted.
@@ -46,11 +46,19 @@ Then select one:
46
46
 
47
47
  - **No candidates:** display "⚠️ **No previous progress found.** There is no output document to resume from. Please use **[C] Create** to start a fresh workflow run." **Halt.**
48
48
 
49
- - **The user named a scope in this invocation** (a specific story, epic, release, or hotfix): resolve `run_key` exactly as `step-01-load-context.md` section 4 does, then select `{outputFile}` for that key. When it does not exist and `{legacyOutputFile}` is a candidate, offer to migrate the legacy matrix to `{run_key}` and **halt** until the user answers; if they accept, select it. If nothing was selected for that key, display "⚠️ **No progress found for `{run_key}`.** Matrices exist for: {list of candidate run keys}. Use **[C] Create** to start a run for `{run_key}`, or name one of the listed scopes." **Halt.** Never fall back to another scope's matrix.
49
+ - **The user named a scope in this invocation** (a specific story, epic, release, or hotfix): resolve `run_key` exactly as `step-01-load-context.md` section 4 does, then select `{outputFile}` for that key. For a v7 epic, also apply the pre-change epic file rule below. When nothing is selected yet and `{legacyOutputFile}` is a candidate, offer to migrate the legacy matrix to `{run_key}` and **halt** until the user answers; if they accept, select it. If nothing was selected for that key, display "⚠️ **No progress found for `{run_key}`.** Matrices exist for: {list of candidate run keys}. Use **[C] Create** to start a run for `{run_key}`, or name one of the listed scopes." **Halt.** Never fall back to another scope's matrix.
50
50
 
51
51
  - **Exactly one candidate and no scope named:** select it and state which run it belongs to before continuing.
52
52
 
53
- - **More than one candidate and no scope named:** list each candidate with its `runKey`, `lastStep`, and `lastSaved`, and ask which run to resume. **Halt** until the user answers.
53
+ - **More than one candidate and no scope named:** list each candidate with its `runKey`, `lastStep`, and `lastSaved`, and ask which run to resume. **Halt** until the user answers. A headless run halts with the list.
54
+
55
+ **Pre-change v7 epic file.** Runs from before v7 epic keys wrote a v7 epic's matrix as `{test_artifacts}/trace/traceability-matrix-epic-<epic id>.md`. When resuming a named v7 epic, also check that file for the epic's id:
56
+
57
+ 1. The file is accepted only when its saved target names this epic: its `oracleSources` or `inputDocuments` cite a file inside this epic's folder (`initiative-<initiative>/tickets/<epic folder>/`). An epic number or a similar title alone is never evidence. A file that cites no file of any epic is not a candidate.
58
+ 2. When the file names another initiative's epic, or `{outputFile}` for the new key and an accepted pre-change file are both candidates, list each file with its `runKey`, saved target, `lastStep`, and `lastSaved`, and ask which run to resume. **Halt** until the user answers. A headless run halts with the list.
59
+ 3. When the accepted pre-change file is the only candidate, select it and say so.
60
+
61
+ A selected pre-change file keeps its stored `runScope`, `runKey`, and target for the rest of the run, so its summary and gate decision keep its own `run_key`. It has no `oracleGranularity`, so it resumes as a criterion-oracle run. An unnamed resume finds the same file through `{progressGlob}` and adopts its stored identity the same way.
54
62
 
55
63
  ---
56
64
 
@@ -65,8 +73,10 @@ Read the selected matrix and parse YAML frontmatter for:
65
73
  - `stepsCompleted`: array of completed step names
66
74
  - `lastStep`: last completed step name
67
75
  - `lastSaved`: timestamp of last save
76
+ - `oracleGranularity`: `requirements` or `criteria`. A checkpoint with no `oracleGranularity` is a criterion-oracle run and resumes as one, with its rows and evidence unchanged. Resume never re-decides granularity; only a fresh run adopts requirement granularity.
77
+ - `oracleLedger`, and for a requirement-granularity run `criterionLedger`: the frozen ledgers Step 1 wrote, with parents, `priorityBasis`, and contributors. A resumed Step 3, 4, or 5 builds its rows from them and never rebuilds them from the ticket files.
68
78
 
69
- **Run identity check.** When the user named a scope in this invocation, `runKey` must equal the `run_key` resolved for it. If it does not, display "⚠️ **Matrix belongs to a different run** (`{runKey}`, not `{run_key}`). Refusing to resume." **Halt.** Do not read its progress state and do not report its `workflowStatus`. When the user named no scope, adopt the matrix's own `runScope`, `runKey`, and target as this run's identity.
79
+ **Run identity check.** When the user named a scope in this invocation, `runKey` must equal the `run_key` resolved for it. A pre-change v7 epic file that section 1 accepted passes this check through its saved target and keeps its stored `runKey`. If neither holds, display "⚠️ **Matrix belongs to a different run** (`{runKey}`, not `{run_key}`). Refusing to resume." **Halt.** Do not read its progress state and do not report its `workflowStatus`. When the user named no scope, adopt the matrix's own `runScope`, `runKey`, and target as this run's identity.
70
80
 
71
81
  **Legacy matrix migration.** If the selected matrix is `{legacyOutputFile}` and carries no `runKey`, it predates run identity and cannot be proven to belong to any scope, so the run identity check above does not apply to it. Migrate it before continuing:
72
82
 
@@ -46,6 +46,8 @@ Search `{test_dir}` for:
46
46
  - Resolved oracle item IDs/titles
47
47
  - Spec patterns (`*.spec.*`, `*.test.*`)
48
48
 
49
+ When `oracleGranularity` is `requirements`, the searchable items are the `criterionLedger` records: search for each record's qualified `id`, its `localId` (`AC-1`) where a test names its story or story key, its `name`, and its full `text`. A test is evidence for the criterion it maps to, so a requirement row id is never a search target.
50
+
49
51
  When the oracle is synthetic (`synthetic_requirements` or `user_journeys`), also search for:
50
52
 
51
53
  - route/path matches
@@ -205,6 +207,8 @@ const liveManifestHeader = {
205
207
 
206
208
  `runtime.getSourceSha()` must resolve `git rev-parse HEAD` in `{project-root}`. Run that command directly when neither helper is available, and reach `GITHUB_SHA` only when the working tree is not a git repository at all. Every live result is `unverifiable` while `currentSourceSha` stays empty, which is deliberate: an unknown current commit cannot establish that a recorded observation is still valid.
207
209
 
210
+ Each record keeps its `requirement_id` exactly as the producer supplied it. Step 3 section 1b resolves it to a canonical oracle id through the live alias map before any failure grouping, so this step never rewrites or matches it.
211
+
208
212
  **Persist `liveRecords` and `liveManifestHeader` into this step's section of `{outputFile}`** as a fenced ` ```json ` block titled `Live Verification Results`. Steps 3 and 4 read them from there. A run resumed at Step 3 or Step 4 has no in-memory bindings from this step, so a value that lives only in memory is a value the resumed run silently loses.
209
213
 
210
214
  ---