@sun-asterisk/sungen 3.2.33 → 3.2.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/dist/cli/commands/audit.d.ts +4 -0
  2. package/dist/cli/commands/audit.d.ts.map +1 -1
  3. package/dist/cli/commands/audit.js +16 -3
  4. package/dist/cli/commands/audit.js.map +1 -1
  5. package/dist/cli/commands/changed.d.ts.map +1 -1
  6. package/dist/cli/commands/changed.js +2 -3
  7. package/dist/cli/commands/changed.js.map +1 -1
  8. package/dist/cli/commands/dashboard.d.ts.map +1 -1
  9. package/dist/cli/commands/dashboard.js +2 -28
  10. package/dist/cli/commands/dashboard.js.map +1 -1
  11. package/dist/cli/commands/delivery.d.ts.map +1 -1
  12. package/dist/cli/commands/delivery.js +40 -35
  13. package/dist/cli/commands/delivery.js.map +1 -1
  14. package/dist/cli/commands/results-merge.d.ts +9 -0
  15. package/dist/cli/commands/results-merge.d.ts.map +1 -1
  16. package/dist/cli/commands/results-merge.js +7 -0
  17. package/dist/cli/commands/results-merge.js.map +1 -1
  18. package/dist/cli/commands/select.d.ts +12 -0
  19. package/dist/cli/commands/select.d.ts.map +1 -0
  20. package/dist/cli/commands/select.js +122 -0
  21. package/dist/cli/commands/select.js.map +1 -0
  22. package/dist/cli/commands/update.d.ts.map +1 -1
  23. package/dist/cli/commands/update.js +3 -0
  24. package/dist/cli/commands/update.js.map +1 -1
  25. package/dist/cli/index.js +7 -2
  26. package/dist/cli/index.js.map +1 -1
  27. package/dist/dashboard/templates/index.html +1 -1
  28. package/dist/dashboard/types.d.ts +1 -0
  29. package/dist/dashboard/types.d.ts.map +1 -1
  30. package/dist/exporters/csv-exporter.d.ts.map +1 -1
  31. package/dist/exporters/csv-exporter.js +11 -10
  32. package/dist/exporters/csv-exporter.js.map +1 -1
  33. package/dist/exporters/json-exporter.d.ts.map +1 -1
  34. package/dist/exporters/json-exporter.js +7 -0
  35. package/dist/exporters/json-exporter.js.map +1 -1
  36. package/dist/exporters/manual-hybrid-oracle.d.ts +54 -0
  37. package/dist/exporters/manual-hybrid-oracle.d.ts.map +1 -0
  38. package/dist/exporters/manual-hybrid-oracle.js +114 -0
  39. package/dist/exporters/manual-hybrid-oracle.js.map +1 -0
  40. package/dist/exporters/matrix/build.d.ts.map +1 -1
  41. package/dist/exporters/matrix/build.js +6 -2
  42. package/dist/exporters/matrix/build.js.map +1 -1
  43. package/dist/exporters/matrix/export.d.ts +3 -0
  44. package/dist/exporters/matrix/export.d.ts.map +1 -1
  45. package/dist/exporters/matrix/export.js +1 -0
  46. package/dist/exporters/matrix/export.js.map +1 -1
  47. package/dist/exporters/matrix/gates.js +6 -0
  48. package/dist/exporters/matrix/gates.js.map +1 -1
  49. package/dist/exporters/matrix/render-testcase-sheet.d.ts.map +1 -1
  50. package/dist/exporters/matrix/render-testcase-sheet.js +10 -4
  51. package/dist/exporters/matrix/render-testcase-sheet.js.map +1 -1
  52. package/dist/exporters/matrix/types.d.ts +8 -1
  53. package/dist/exporters/matrix/types.d.ts.map +1 -1
  54. package/dist/exporters/matrix/types.js.map +1 -1
  55. package/dist/exporters/matrix/wording.d.ts +1 -1
  56. package/dist/exporters/matrix/wording.d.ts.map +1 -1
  57. package/dist/exporters/matrix/wording.js +10 -1
  58. package/dist/exporters/matrix/wording.js.map +1 -1
  59. package/dist/exporters/run-environment.d.ts +32 -0
  60. package/dist/exporters/run-environment.d.ts.map +1 -0
  61. package/dist/exporters/run-environment.js +125 -0
  62. package/dist/exporters/run-environment.js.map +1 -0
  63. package/dist/exporters/scenario-merger.d.ts +18 -0
  64. package/dist/exporters/scenario-merger.d.ts.map +1 -1
  65. package/dist/exporters/scenario-merger.js +47 -3
  66. package/dist/exporters/scenario-merger.js.map +1 -1
  67. package/dist/exporters/test-data-resolver.d.ts +0 -4
  68. package/dist/exporters/test-data-resolver.d.ts.map +1 -1
  69. package/dist/exporters/test-data-resolver.js +0 -7
  70. package/dist/exporters/test-data-resolver.js.map +1 -1
  71. package/dist/generators/gherkin-parser/index.d.ts +11 -4
  72. package/dist/generators/gherkin-parser/index.d.ts.map +1 -1
  73. package/dist/generators/gherkin-parser/index.js +49 -19
  74. package/dist/generators/gherkin-parser/index.js.map +1 -1
  75. package/dist/generators/test-generator/adapters/adapter-interface.d.ts +4 -0
  76. package/dist/generators/test-generator/adapters/adapter-interface.d.ts.map +1 -1
  77. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/click-select-action.hbs +1 -1
  78. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/select-action.hbs +1 -1
  79. package/dist/generators/test-generator/adapters/playwright/templates/steps/partials/pick-option.hbs +13 -0
  80. package/dist/generators/test-generator/adapters/playwright/templates/test-file.hbs +16 -0
  81. package/dist/generators/test-generator/code-generator.d.ts.map +1 -1
  82. package/dist/generators/test-generator/code-generator.js +23 -2
  83. package/dist/generators/test-generator/code-generator.js.map +1 -1
  84. package/dist/generators/test-generator/diagnostics.d.ts +3 -1
  85. package/dist/generators/test-generator/diagnostics.d.ts.map +1 -1
  86. package/dist/generators/test-generator/diagnostics.js +3 -1
  87. package/dist/generators/test-generator/diagnostics.js.map +1 -1
  88. package/dist/harness/audit.d.ts +3 -0
  89. package/dist/harness/audit.d.ts.map +1 -1
  90. package/dist/harness/audit.js +17 -8
  91. package/dist/harness/audit.js.map +1 -1
  92. package/dist/harness/data-driven-lint.d.ts.map +1 -1
  93. package/dist/harness/data-driven-lint.js +69 -27
  94. package/dist/harness/data-driven-lint.js.map +1 -1
  95. package/dist/harness/next-step.d.ts.map +1 -1
  96. package/dist/harness/next-step.js +1 -0
  97. package/dist/harness/next-step.js.map +1 -1
  98. package/dist/harness/parse.d.ts +24 -0
  99. package/dist/harness/parse.d.ts.map +1 -1
  100. package/dist/harness/parse.js +117 -13
  101. package/dist/harness/parse.js.map +1 -1
  102. package/dist/harness/quality-gates.d.ts.map +1 -1
  103. package/dist/harness/quality-gates.js +6 -4
  104. package/dist/harness/quality-gates.js.map +1 -1
  105. package/dist/harness/read-text.d.ts +15 -0
  106. package/dist/harness/read-text.d.ts.map +1 -1
  107. package/dist/harness/read-text.js +25 -0
  108. package/dist/harness/read-text.js.map +1 -1
  109. package/dist/harness/select-by-ids.d.ts +31 -0
  110. package/dist/harness/select-by-ids.d.ts.map +1 -0
  111. package/dist/harness/select-by-ids.js +106 -0
  112. package/dist/harness/select-by-ids.js.map +1 -0
  113. package/dist/harness/sensors.d.ts +8 -1
  114. package/dist/harness/sensors.d.ts.map +1 -1
  115. package/dist/harness/sensors.js +61 -9
  116. package/dist/harness/sensors.js.map +1 -1
  117. package/dist/harness/spec-branches.js +1 -1
  118. package/dist/harness/spec-branches.js.map +1 -1
  119. package/dist/harness/ui-inventory.d.ts +40 -0
  120. package/dist/harness/ui-inventory.d.ts.map +1 -0
  121. package/dist/harness/ui-inventory.js +191 -0
  122. package/dist/harness/ui-inventory.js.map +1 -0
  123. package/dist/harness/viewpoint-ledger.d.ts.map +1 -1
  124. package/dist/harness/viewpoint-ledger.js +64 -9
  125. package/dist/harness/viewpoint-ledger.js.map +1 -1
  126. package/dist/orchestrator/screen-manager.d.ts.map +1 -1
  127. package/dist/orchestrator/screen-manager.js +3 -11
  128. package/dist/orchestrator/screen-manager.js.map +1 -1
  129. package/dist/orchestrator/templates/ai-src/agents/discovery.md +11 -3
  130. package/dist/orchestrator/templates/ai-src/agents/reviewer.md +8 -0
  131. package/dist/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  132. package/dist/orchestrator/templates/ai-src/commands/review.md +2 -2
  133. package/dist/orchestrator/templates/ai-src/commands/run-test.md +70 -13
  134. package/dist/orchestrator/templates/ai-src/skills/sungen-capture/mode-local.md +2 -2
  135. package/dist/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +20 -0
  136. package/dist/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +17 -8
  137. package/dist/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +58 -14
  138. package/dist/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +41 -1
  139. package/dist/orchestrator/templates/ai-src/skills/sungen-tc-review/SKILL.md +7 -0
  140. package/dist/orchestrator/templates/playwright.config.ts +4 -2
  141. package/dist/orchestrator/templates/specs-url-assert.d.ts.map +1 -1
  142. package/dist/orchestrator/templates/specs-url-assert.js +24 -2
  143. package/dist/orchestrator/templates/specs-url-assert.js.map +1 -1
  144. package/dist/orchestrator/templates/specs-url-assert.ts +23 -2
  145. package/dist/orchestrator/trace-mode-install.d.ts +14 -0
  146. package/dist/orchestrator/trace-mode-install.d.ts.map +1 -0
  147. package/dist/orchestrator/trace-mode-install.js +132 -0
  148. package/dist/orchestrator/trace-mode-install.js.map +1 -0
  149. package/dist/orchestrator/viewpoint-pattern-catalog.d.ts +20 -0
  150. package/dist/orchestrator/viewpoint-pattern-catalog.d.ts.map +1 -0
  151. package/dist/orchestrator/viewpoint-pattern-catalog.js +45 -0
  152. package/dist/orchestrator/viewpoint-pattern-catalog.js.map +1 -0
  153. package/package.json +3 -3
  154. package/src/cli/commands/audit.ts +14 -3
  155. package/src/cli/commands/changed.ts +2 -4
  156. package/src/cli/commands/dashboard.ts +1 -26
  157. package/src/cli/commands/delivery.ts +37 -32
  158. package/src/cli/commands/results-merge.ts +7 -1
  159. package/src/cli/commands/select.ts +88 -0
  160. package/src/cli/commands/update.ts +3 -0
  161. package/src/cli/index.ts +7 -2
  162. package/src/dashboard/templates/index.html +1 -1
  163. package/src/dashboard/types.ts +1 -0
  164. package/src/exporters/csv-exporter.ts +7 -10
  165. package/src/exporters/json-exporter.ts +6 -1
  166. package/src/exporters/manual-hybrid-oracle.ts +112 -0
  167. package/src/exporters/matrix/build.ts +6 -2
  168. package/src/exporters/matrix/export.ts +4 -0
  169. package/src/exporters/matrix/gates.ts +6 -0
  170. package/src/exporters/matrix/render-testcase-sheet.ts +10 -4
  171. package/src/exporters/matrix/types.ts +8 -1
  172. package/src/exporters/matrix/wording.ts +10 -1
  173. package/src/exporters/run-environment.ts +89 -0
  174. package/src/exporters/scenario-merger.ts +49 -4
  175. package/src/exporters/test-data-resolver.ts +0 -6
  176. package/src/generators/gherkin-parser/index.ts +50 -18
  177. package/src/generators/test-generator/adapters/adapter-interface.ts +4 -0
  178. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/click-select-action.hbs +1 -1
  179. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/select-action.hbs +1 -1
  180. package/src/generators/test-generator/adapters/playwright/templates/steps/partials/pick-option.hbs +13 -0
  181. package/src/generators/test-generator/adapters/playwright/templates/test-file.hbs +16 -0
  182. package/src/generators/test-generator/code-generator.ts +23 -2
  183. package/src/generators/test-generator/diagnostics.ts +3 -1
  184. package/src/harness/audit.ts +20 -9
  185. package/src/harness/data-driven-lint.ts +82 -24
  186. package/src/harness/next-step.ts +1 -0
  187. package/src/harness/parse.ts +123 -16
  188. package/src/harness/quality-gates.ts +6 -4
  189. package/src/harness/read-text.ts +25 -0
  190. package/src/harness/select-by-ids.ts +83 -0
  191. package/src/harness/sensors.ts +59 -9
  192. package/src/harness/spec-branches.ts +1 -1
  193. package/src/harness/ui-inventory.ts +164 -0
  194. package/src/harness/viewpoint-ledger.ts +57 -11
  195. package/src/orchestrator/screen-manager.ts +3 -11
  196. package/src/orchestrator/templates/ai-src/agents/discovery.md +11 -3
  197. package/src/orchestrator/templates/ai-src/agents/reviewer.md +8 -0
  198. package/src/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  199. package/src/orchestrator/templates/ai-src/commands/review.md +2 -2
  200. package/src/orchestrator/templates/ai-src/commands/run-test.md +70 -13
  201. package/src/orchestrator/templates/ai-src/skills/sungen-capture/mode-local.md +2 -2
  202. package/src/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +20 -0
  203. package/src/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +17 -8
  204. package/src/orchestrator/templates/ai-src/skills/sungen-selector-fix/SKILL.md +58 -14
  205. package/src/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +41 -1
  206. package/src/orchestrator/templates/ai-src/skills/sungen-tc-review/SKILL.md +7 -0
  207. package/src/orchestrator/templates/playwright.config.ts +4 -2
  208. package/src/orchestrator/templates/specs-url-assert.ts +23 -2
  209. package/src/orchestrator/trace-mode-install.ts +94 -0
  210. package/src/orchestrator/viewpoint-pattern-catalog.ts +58 -0
@@ -1,2 +1,2 @@
1
1
  await {{> locator}}.click();
2
- await page.getByText('{{selectValue}}', { exact: true }).first().click();
2
+ {{> pick-option}}
@@ -9,7 +9,7 @@ if ((await el.evaluate((n) => n.tagName.toLowerCase())) === 'select') {
9
9
  await el.selectOption('{{selectValue}}');
10
10
  } else {
11
11
  await el.click();
12
- await page.getByText('{{selectValue}}', { exact: true }).first().click();
12
+ {{> pick-option}}
13
13
  }
14
14
  }
15
15
  {{~else~}}
@@ -0,0 +1,13 @@
1
+ {{!-- #847 — pick the value in an OPENED custom listbox (Radix/shadcn, MUI, Headless UI).
2
+ The popup portals to the end of <body>, so a page-wide getByText(…).first() resolved to
3
+ any EARLIER element with the same text (a badge showing the current choice, a result
4
+ card) — and the open popup blocks clicks outside it, so the step timed out every time,
5
+ looking like a race. The ARIA option lives only in the open listbox: wait briefly for it
6
+ (a count() right after opening would race the popup animation), and fall back to the old
7
+ text match only for a widget that exposes no listbox roles. --}}
8
+ { const __opt = page.getByRole('option', { name: '{{selectValue}}', exact: true }).first();
9
+ if (await __opt.waitFor({ state: 'visible', timeout: 3000 }).then(() => true, () => false)) {
10
+ await __opt.click();
11
+ } else {
12
+ await page.getByText('{{selectValue}}', { exact: true }).first().click();
13
+ } }
@@ -46,6 +46,10 @@ test.describe('{{featureName}}', () => {
46
46
  test.describe('{{authRole}}', () => {
47
47
  test.use({ storageState: 'specs/.auth/{{authRole}}.json' });
48
48
 
49
+ {{#if afterEach}}
50
+ {{indent afterEach 2}}
51
+
52
+ {{/if}}
49
53
  {{#each scenarios}}
50
54
  {{indent this 2}}
51
55
 
@@ -63,6 +67,18 @@ test.describe('{{featureName}}', () => {
63
67
  {{#each scenarios}}
64
68
  {{indent this 2}}
65
69
 
70
+ {{/each}}
71
+ });
72
+
73
+ {{else if afterEach}}
74
+ {{!-- The un-tagged group next to a `@no-auth` one (#815): an ANONYMOUS describe scopes the hook to
75
+ these tests without adding a title segment, so test titles (and delivery fingerprints) stay put. --}}
76
+ test.describe(() => {
77
+ {{indent afterEach 2}}
78
+
79
+ {{#each scenarios}}
80
+ {{indent this 2}}
81
+
66
82
  {{/each}}
67
83
  });
68
84
 
@@ -10,6 +10,7 @@ import { capabilityRegistry } from '../../capabilities/registry';
10
10
  import { discoverAndRegisterCapabilities } from '../../capabilities/discover';
11
11
  import { readCapabilities } from '../../harness/capability';
12
12
  import { parseManualComments } from '../../exporters/scenario-merger';
13
+ import { isPresencePlaceholderHybrid } from '../../exporters/manual-hybrid-oracle';
13
14
  import { findSyntaxError } from './utils/spec-syntax-check';
14
15
 
15
16
  /** One capability-injected precondition statement (`@api:`/`@query:` → `testData.bind(name, …)`). */
@@ -790,11 +791,18 @@ export class CodeGenerator {
790
791
  // labeled `Observable:`/`Oracle:`/`Expected:` line (parseManualComments — the
791
792
  // SAME parser delivery uses). Field finding (student-site, 87 scenarios): prose
792
793
  // paragraphs and rationale-only comments exported EMPTY Steps + Expected cells.
794
+ // • HAS a Then, but every assertion is a bare presence placeholder while the real oracle
795
+ // sits in the comments (#810) — the same banned hybrid wearing a Then: the deliverable
796
+ // reads "See [X] table" and a tester ticking it Passed records a check nobody made.
793
797
  const isStructured = scenario.steps.length > 0;
794
798
  if (isStructured && !hasThenStep(scenario)) {
795
799
  this.diagnostics.add('SG-W008',
796
800
  `@manual scenario "${scenario.name}" has Gherkin steps but no Then — a When without Then is invalid Gherkin. Add the Then step, or remove the steps and write the full procedure (action steps, then "Observable:"/"Oracle:" lines) in its \`# Tester verifies:\` block`,
797
801
  { feature: feature.name, step: scenario.name });
802
+ } else if (isStructured && isPresencePlaceholderHybrid(scenario.steps, scenario.comments ?? [])) {
803
+ this.diagnostics.add('SG-W008',
804
+ `@manual scenario "${scenario.name}" asserts only presence (e.g. "User see [X] table") while its real oracle sits in the \`# Tester verifies:\` comment — the deliverable's Expected would not say what the case checks. Write the oracle as the Then step (e.g. \`table match data:\`), or remove the steps and write the full numbered procedure ("1. <action>" … "N. Observable: <what>")`,
805
+ { feature: feature.name, step: scenario.name });
798
806
  } else if (!isStructured) {
799
807
  const parsed = parseManualComments(scenario.comments ?? []);
800
808
  if (!parsed.steps.length || !parsed.expected.length) {
@@ -880,7 +888,7 @@ export class CodeGenerator {
880
888
  authGroupMap.get(key)!.push(code);
881
889
  }
882
890
 
883
- const authGroups = groupOrder.map(key => ({
891
+ const authGroups = groupOrder.map((key): { authRole?: string; noAuth: boolean; scenarios: string[]; afterEach?: string } => ({
884
892
  authRole: key === NO_AUTH_GROUP_KEY ? undefined : (key || undefined),
885
893
  noAuth: key === NO_AUTH_GROUP_KEY,
886
894
  scenarios: authGroupMap.get(key)!,
@@ -923,6 +931,19 @@ export class CodeGenerator {
923
931
  }
924
932
  const scenarios = renderedScenarios.map(s => s.code);
925
933
 
934
+ // #815 — a feature-level `@afterEach` used to sit in the outermost describe, so it also ran after
935
+ // every `@no-auth` test, on an EMPTY session: a hook that needs the signed-in page (`Given User is
936
+ // on [probe] page` → redirected to /login) failed an anonymous test whose own steps passed. When
937
+ // the feature mixes `@no-auth` with any other group, the hook moves INTO each other group and the
938
+ // no-auth group runs without it. A feature that is anonymous throughout keeps the hook — it was
939
+ // written for those tests.
940
+ // (A no-auth group beside another one means ≥2 groups, so `renderAuthBlocks` is already true.)
941
+ const afterEachInGroups = !!afterEach
942
+ && authGroups.some(g => g.noAuth) && authGroups.some(g => !g.noAuth);
943
+ if (afterEachInGroups) {
944
+ for (const g of authGroups) if (!g.noAuth) g.afterEach = afterEach;
945
+ }
946
+
926
947
  // For single group, extract the auth role to put test.use at describe level. Keyed on
927
948
  // `renderAuthBlocks`, not `needsGrouping`: a lone `@no-auth` group now renders its own block, so
928
949
  // hoisting anything to the feature describe would double up. Its authRole is undefined anyway.
@@ -1019,7 +1040,7 @@ export class CodeGenerator {
1019
1040
  featureDescription: feature.description,
1020
1041
  background,
1021
1042
  beforeAll,
1022
- afterEach,
1043
+ afterEach: afterEachInGroups ? undefined : afterEach,
1023
1044
  afterAll,
1024
1045
  cleanupConfig,
1025
1046
  screenshotOnFailure,
@@ -24,7 +24,9 @@
24
24
  * SG-W008 — @manual scenario is incomplete in either direction: Gherkin steps without a
25
25
  * Then (invalid Gherkin; comments cannot substitute), or a documentation-style
26
26
  * manual (no steps) whose comments lack the extractable procedure — ≥1 numbered
27
- * action line + ≥1 labeled Observable:/Oracle:/Expected: line
27
+ * action line + ≥1 labeled Observable:/Oracle:/Expected: line — or a Then that
28
+ * asserts only presence while the real oracle sits in a `# Tester verifies:`
29
+ * comment (#810)
28
30
  * SG-W009 — test-data references a `${QA_*}` secret that is declared in neither .env.qa
29
31
  * nor .env.qa.example — the test will throw "not set" the moment the key is used
30
32
  * SG-W010 — a row step's [Ref] looks POSITIONAL (First/Last/Top/…) but has no selectors.yaml
@@ -32,7 +32,8 @@ const MULTI_SCREEN_RISK_COUNT = MULTI_SCREEN_RISKS.length;
32
32
  import { capabilityRegistry } from '../capabilities/registry';
33
33
  import { discoverAndRegisterCapabilities } from '../capabilities/discover';
34
34
  import { contextRouter } from '../capabilities/context-router';
35
- import { readTextFile } from './read-text';
35
+ import { readTextFile, readViewpointText } from './read-text';
36
+ import { uiInventoryCoverage, uiInventoryFindings, UiInventoryResult } from './ui-inventory';
36
37
 
37
38
  export interface AuditReport {
38
39
  screen: string;
@@ -57,6 +58,8 @@ export interface AuditReport {
57
58
  flowQuality?: FlowQualityResult; // #569 — flow contract verification (flows only)
58
59
  /** #595 — coverage per DECLARED FLOW; absent when the contract declares no `flows:`. */
59
60
  flowInventory?: InventoryResult;
61
+ /** #811 — design items vs the suite; present only when the unit holds design sources. */
62
+ uiInventory?: UiInventoryResult;
60
63
  calibration: { // #8 — multi-axis score so a high overall can't hide a weak axis
61
64
  axes: Record<string, number>;
62
65
  weakest: { axis: string; value: number };
@@ -185,6 +188,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
185
188
  const scoringCap = scoringCapId ? capabilityRegistry.get(scoringCapId) : undefined;
186
189
  const catalog = (scoringCap?.viewpoints?.() as Catalog | undefined) || loadCatalog();
187
190
  const spec = specCoverage(specPath, scenarios, featureText);
191
+ const uiInv = uiInventoryCoverage(path.join(screenDir, 'requirements'), featureText);
188
192
 
189
193
  // P3 — intent profile from qa/context.md drives the depth threshold (focus).
190
194
  const intent = readIntent(projectRootFromScreenDir(screenDir));
@@ -196,7 +200,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
196
200
  // Is the declaration this suite is measured against still the one a human accepted?
197
201
  const viewpointBaseline = checkViewpointBaseline(
198
202
  projectRootFromScreenDir(screenDir), catalogScreenName, viewpointPath);
199
- const viewpointText = fs.existsSync(viewpointPath) ? readTextFile(viewpointPath) : '';
203
+ const viewpointText = readViewpointText(viewpointPath);
200
204
  // #569 — a flow WITH a contract is measured against ITS declaration, not a screen's.
201
205
  // Keyword page-type detection force-fit flows into screen checklists (a registration
202
206
  // flow judged as a `form` screen scored coverage 0%), so for contract-holding flows the
@@ -373,7 +377,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
373
377
  { key: 'atomicLedger', value: ledger.ratio, weight: 0.13, applicable: ledger.hasViewpoint && ledger.total > 0 && !viewpointMoved, critical: true, withheld: viewpointMoved && ledger.hasViewpoint && ledger.total > 0 },
374
378
  { key: 'businessDepth', value: businessDepth, weight: 0.20, applicable: true, critical: true },
375
379
  { key: 'claimProof', value: claim.ratio, weight: 0.15, applicable: claim.withClaims > 0, critical: true },
376
- { key: 'traceability', value: traceScore, weight: 0.09, applicable: viewpoints.length > 0 && !viewpointMoved, critical: false, withheld: viewpointMoved && viewpoints.length > 0 },
380
+ { key: 'traceability', value: traceScore, weight: 0.09, applicable: viewpoints.length > 0 && scenarios.length > 0 && !viewpointMoved, critical: false, withheld: viewpointMoved && viewpoints.length > 0 && scenarios.length > 0 },
377
381
  // A use-case decomposition is EF-heavy by construction (1 basic flow, N alternates, N
378
382
  // exceptions) — that is the shape of a well-decomposed use case, not neglected business
379
383
  // core. `flowCoverage` already measures whether the journey's phases are covered, so
@@ -585,7 +589,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
585
589
  findings.push(`COVERED-VIA-FLOW: critical theme "${c.theme}" is not covered on this screen but is deeply covered by flow "${c.flow}" — cross-screen depth correctly owned by the flow, so it is credited (not a screen gap). Verify with \`sungen flow-check\`.`);
586
590
  }
587
591
  // Verification-scope (advisory): API/DB verification the project's recorded test type never asked for.
588
- for (const v of verificationScopeFindings(featureText, fs.existsSync(viewpointPath) ? readTextFile(viewpointPath) : '', capProfile)) {
592
+ for (const v of verificationScopeFindings(featureText, viewpointText, capProfile)) {
589
593
  findings.push(`VERIFICATION-OUT-OF-SCOPE (${v.layer}): this unit ${v.message}`);
590
594
  }
591
595
  for (const g of gate.gaps) {
@@ -657,7 +661,8 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
657
661
  ...(unsourced.length ? [`${unsourced.length} scenario(s) could not be traced to a source`] : []),
658
662
  ];
659
663
  findings.push(`VIEWPOINT-MISSING: \`requirements/test-viewpoint.md\` ${ledger.hasViewpoint ? 'declares no viewpoints' : 'does not exist'}, so this unit has no yardstick. Two scored axes are excluded (atomicLedger, traceability) and four sensors cannot run: the atomic ledger, the declaration-integrity checks (reused ids, dangling refs, uniform priority), the browser-gesture check and the two-way continuity check. Nothing here is a pass — it is unmeasured [${lost.join(', ')}]. A flow contract does NOT substitute: the contract declares the use case, the viewpoint declares the CLAIMS the suite is scored against, and only the second is independent of what was generated. Author it (\`sungen add-flow\` scaffolds a template), then \`sungen audit --screen ${screenName} --accept-viewpoint\`.`);
660
- } else if (trace.mappedRatio < 0.5) {
664
+ } else if (scenarios.length > 0 && trace.mappedRatio < 0.5) {
665
+ // No scenario yet is not a traceability gap — the axis is n/a, like coverage and claimProof (#852).
661
666
  findings.push(`TRACE: ${trace.note}`);
662
667
  }
663
668
  // (UNIVERSAL viewpoint-gap finding now emitted by the `ui` gate sensor — see the gate block below.)
@@ -698,8 +703,10 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
698
703
  for (const d of downstream.underCovered) {
699
704
  findings.push(`DOWNSTREAM-SCOPE-MISSING: "${d.route}" is a navigation target but is covered only by a page-nav assertion — cover its content/guards, or scaffold it (\`sungen add --screen ${d.slug}\`).`);
700
705
  }
706
+ // #811 — design inventory (advisory): never moves the score or the gate.
707
+ findings.push(...uiInventoryFindings(uiInv));
701
708
  for (const m of manualOracleResult.insufficient.slice(0, 8)) {
702
- findings.push(`MANUAL-STEPS-INSUFFICIENT: "${m}" — @manual is incomplete: either Gherkin steps without a Then (invalid Gherkin; comments can't substitute), or a documentation manual whose comments lack numbered action steps + a labeled Observable:/Oracle: line. Write \`# Tester verifies:\` as "1. <action>" … "N. Observable: <what>" / "Oracle: <tool>" — that is what the delivery parser extracts into Steps/Expected.`);
709
+ findings.push(`MANUAL-STEPS-INSUFFICIENT: "${m}" — @manual is incomplete: either Gherkin steps without a Then (invalid Gherkin; comments can't substitute), a Then that only asserts presence (\`see [X] table\`) while the real oracle sits in a \`# Tester verifies:\` comment (the deliverable's Expected would not say what is checked), or a documentation manual whose comments lack numbered action steps + a labeled Observable:/Oracle: line. Write \`# Tester verifies:\` as "1. <action>" … "N. Observable: <what>" / "Oracle: <tool>" — that is what the delivery parser extracts into Steps/Expected.`);
703
710
  }
704
711
  // TQ-2 — automatable @manual: deferred (usually cross-screen) but fully DSL-expressible.
705
712
  for (const m of autoManual.scenarios.slice(0, 8)) {
@@ -797,7 +804,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
797
804
  // #622 — the priority table is where release selection comes from; a tag that contradicts it
798
805
  // means nobody can tell which of the two was the decision.
799
806
  {
800
- const pm = priorityMismatches(hasYardstick ? (readText(viewpointPath) ?? '') : '', scenarios);
807
+ const pm = priorityMismatches(hasYardstick ? viewpoints : [], scenarios);
801
808
  const byId = new Map<string, { declared: string; tagged: string; n: number }>();
802
809
  for (const m of pm) {
803
810
  const cur = byId.get(m.id) ?? { declared: m.declared, tagged: m.tagged, n: 0 };
@@ -870,8 +877,11 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
870
877
  axes.manualOracle = Math.round(manualCompleteness * 100) / 100;
871
878
  // Only a real mismatch scores 0. Without a yardstick `trace.mappedRatio` is 0 because there is
872
879
  // nothing to map to, and reporting that as the weakest axis sent authors to "raise taxonomy" —
873
- // an axis that was never measured.
874
- if (hasYardstick) axes.taxonomy = taxonomyMismatch ? 0 : Math.round(trace.mappedRatio * 100) / 100;
880
+ // an axis that was never measured. The same holds for a yardstick the ledger can read but that
881
+ // declares no viewpoint ID traceability can read (per-axis tables only, #832): the ledger has
882
+ // items, so `hasYardstick` is true, yet there is still nothing to map to. Same condition as the
883
+ // `traceability` score axis (`applicable: viewpoints.length > 0`).
884
+ if (hasYardstick && viewpoints.length > 0 && scenarios.length > 0) axes.taxonomy = taxonomyMismatch ? 0 : Math.round(trace.mappedRatio * 100) / 100;
875
885
  const notApplicable = axisDefs.filter((a) => !a.applicable).map((a) => a.key);
876
886
  const weakestEntry = Object.entries(axes).sort((a, b) => a[1] - b[1])[0];
877
887
  const weakest = { axis: weakestEntry[0], value: weakestEntry[1] };
@@ -899,6 +909,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
899
909
  gate, depth, claim, taxonomy, balance, duplicates, trace, spec,
900
910
  taxonomyMismatch, reusedScenarioIds: reusedIds, downstream, manualOracle: manualOracleResult, automatableManual: autoManual, flowDepth, oracle, ledger, viewpointBaseline, calibration,
901
911
  ...(isUiFlow ? { flowQuality: flowQ, flowInventory: inventory ?? undefined } : {}),
912
+ ...(uiInv.designSources.length ? { uiInventory: uiInv } : {}),
902
913
  score: {
903
914
  overall: Math.round(overall * 10) / 10,
904
915
  coverage: Math.round(coverage * 100) / 100,
@@ -155,29 +155,100 @@ function overrideKeys(raw?: string): Set<string> {
155
155
  return out;
156
156
  }
157
157
 
158
+ interface FeatureUnderLint {
159
+ /** Feature file basename — names the test-data file the runtime loads for it. */
160
+ name: string;
161
+ scenarios: ParsedScenario[];
162
+ tags: string[];
163
+ }
164
+
165
+ /** What every feature of a unit shares: unit-level refs and the @api catalog. */
166
+ interface UnitLintContext {
167
+ screenDir: string;
168
+ screenName: string;
169
+ cwd: string;
170
+ fileRefs: Set<string>;
171
+ apiParams: Map<string, string[]>;
172
+ }
173
+
158
174
  /** Lint the @cases/@query usage of one screen/flow directory. Returns advisory warnings. */
159
175
  export function lintDataDriven(screenDir: string, cwd: string = process.cwd()): DataDrivenWarning[] {
160
176
  const base = path.basename(screenDir);
161
177
  const screenName = unitIdOf(screenDir);
162
178
  // Every `.feature` of the unit — `add --feature` sub-features lint too. A file that
163
179
  // fails to parse contributes nothing rather than voiding the whole unit's lint.
164
- const scenarios: ParsedScenario[] = [];
165
- const featureTags: string[] = [];
166
- for (const p of featureFilesFor(screenDir, base).filter((f) => fs.existsSync(f))) {
180
+ const features: FeatureUnderLint[] = [];
181
+ const featureFiles = featureFilesFor(screenDir, base).filter((f) => fs.existsSync(f));
182
+ for (const p of featureFiles) {
167
183
  try {
168
184
  const feature = new GherkinParser().parseFeatureFile(p);
169
- scenarios.push(...(feature.scenarios || []));
170
- featureTags.push(...(feature.tags || []));
185
+ features.push({ name: path.basename(p, '.feature'), scenarios: feature.scenarios || [], tags: feature.tags || [] });
171
186
  } catch {
172
187
  /* a file that fails to parse contributes nothing */
173
188
  }
174
189
  }
175
- if (scenarios.length === 0) return [];
190
+ if (!features.some((f) => f.scenarios.length > 0)) return [];
191
+
192
+ const ctx: UnitLintContext = {
193
+ screenDir, screenName, cwd,
194
+ // `{{key}}` refs carried by the unit's selectors (i18n) and mock catalog are live too.
195
+ fileRefs: refsInUnitFiles(screenDir),
196
+ apiParams: apiParamsByName(screenName, cwd),
197
+ };
198
+
199
+ // #839 — each feature against ITS OWN test-data file. The runtime loads
200
+ // `test-data/<feature file basename>.yaml` (TestDataLoader.load(unit, featureFileName)), with no
201
+ // fallback and no merging; reading `<unit dir>.yaml` instead found nothing whenever the names
202
+ // differ — the default for `add --screen x --path /a/b` (→ b.feature) and for `--feature` — so
203
+ // every key read as missing and no orphan was ever reported. The tables are deliberately NOT
204
+ // merged: a key in another feature's file compiles to the literal `${key}` here.
205
+ const warns: DataDrivenWarning[] = [];
206
+ for (const f of features) if (f.scenarios.length > 0) warns.push(...lintFeature(f, ctx));
207
+ warns.push(...unloadedTestDataFiles(screenDir, featureFiles.map((f) => path.basename(f, '.feature'))));
208
+
209
+ // Catalog-level lint (SELECT-only, params declared/used, datasource present).
210
+ try {
211
+ for (const e of lintCatalog(screenName, null, cwd).errors) warns.push({ message: e });
212
+ } catch {
213
+ /* no catalog → nothing to lint */
214
+ }
215
+ return warns;
216
+ }
217
+
218
+ /**
219
+ * A test-data file no feature loads is dead in full: the runtime reads only
220
+ * `<feature>.yaml` and its `<feature>.<env>.yaml` overlays. Typically a `<unit>.yaml` written by
221
+ * hand next to a feature `add --path` named after the URL — its keys never reach a test.
222
+ * Every existing feature file counts (even one that failed to parse), so a parse error never
223
+ * turns its data into a false "loaded by no feature".
224
+ */
225
+ function unloadedTestDataFiles(screenDir: string, featureNames: string[]): DataDrivenWarning[] {
226
+ let files: string[];
227
+ try {
228
+ files = fs.readdirSync(path.join(screenDir, 'test-data')).filter((f) => /\.ya?ml$/.test(f) && !f.startsWith('_'));
229
+ } catch {
230
+ return [];
231
+ }
232
+ const loaded = (stem: string): boolean => featureNames.some((n) => stem === n || stem.startsWith(`${n}.`));
233
+ return files
234
+ .filter((f) => !loaded(f.replace(/\.ya?ml$/, '')) || !f.endsWith('.yaml'))
235
+ .map((f) => ({
236
+ message: `test-data/${f} is loaded by no feature — the runtime reads test-data/<feature>.yaml (+ <feature>.<env>.yaml) for ${featureNames.map((n) => `${n}.feature`).join(', ')}: move its keys there or remove it.`,
237
+ }));
238
+ }
176
239
 
177
- const tdPath = path.join(screenDir, 'test-data', `${base}.yaml`);
178
- const td: Record<string, any> = tdPath && fs.existsSync(tdPath) ? parseYaml(fs.readFileSync(tdPath, 'utf8')) || {} : {};
240
+ function lintFeature(feature: FeatureUnderLint, ctx: UnitLintContext): DataDrivenWarning[] {
241
+ const { screenName, cwd, fileRefs, apiParams } = ctx;
242
+ const { scenarios, tags: featureTags } = feature;
243
+ const tdFile = `test-data/${feature.name}.yaml`;
244
+ const tdPath = path.join(ctx.screenDir, 'test-data', `${feature.name}.yaml`);
245
+ const td: Record<string, any> = fs.existsSync(tdPath) ? parseYaml(fs.readFileSync(tdPath, 'utf8')) || {} : {};
179
246
  const topKeys = new Set(Object.keys(td));
180
247
  const warns: DataDrivenWarning[] = [];
248
+ // H3: an `@extend:<base>` scenario runs the base's steps first — the base's captures bind for it.
249
+ // Per feature, like the compiler's steps registry: an `@extend` never reaches another file's base.
250
+ const stepsBase = new Map<string, ParsedScenario>();
251
+ for (const sc of scenarios) if (sc.stepsName) stepsBase.set(sc.stepsName, sc);
181
252
  // Bindings a `@beforeAll` hook's `@api:`/`@query:` preconditions make are readable from EVERY
182
253
  // scenario of the feature (the compiler registers them feature-wide). A `remember … as` inside the
183
254
  // hook is NOT — it stays hook-local — so only the tag-bound names are exempted here.
@@ -186,18 +257,12 @@ export function lintDataDriven(screenDir: string, cwd: string = process.cwd()):
186
257
  if (sc.hookType !== 'beforeAll') continue;
187
258
  for (const t of sc.tags || []) { const m = t.match(/^@(?:api|query):([A-Za-z_]\w*)/); if (m) featureBound.add(m[1]); }
188
259
  }
189
- // H3: an `@extend:<base>` scenario runs the base's steps first — the base's captures bind for it.
190
- const stepsBase = new Map<string, ParsedScenario>();
191
- for (const sc of scenarios) if (sc.stepsName) stepsBase.set(sc.stepsName, sc);
192
- // `{{key}}` refs carried by the unit's selectors (i18n) and mock catalog are live too.
193
- const fileRefs = refsInUnitFiles(screenDir);
194
260
  // A feature-level `@manual` makes every scenario manual (the whole file is skipped by the compiler).
195
261
  const featureManual = featureTags.some((t) => t === '@manual' || t.startsWith('@manual:'));
196
262
 
197
263
  // What the scenarios bind, collected up front — the @query pass below adds the params it binds by name.
198
264
  const usedHeads = new Set<string>();
199
265
  const usedDatasets = new Set<string>();
200
- const apiParams = apiParamsByName(screenName, cwd);
201
266
  for (const h of fileRefs) usedHeads.add(h);
202
267
  for (const sc of scenarios) {
203
268
  for (const r of collectRefs(sc, featureManual || isManualScenario(sc))) usedHeads.add(r.split(/[.[]/)[0]);
@@ -228,7 +293,7 @@ export function lintDataDriven(screenDir: string, cwd: string = process.cwd()):
228
293
  const ds = casesTag.slice('@cases:'.length).trim();
229
294
  const rows = td[ds];
230
295
  if (!Array.isArray(rows)) {
231
- warns.push({ scenario: sc.name, message: `@cases:${ds} → dataset "${ds}" is missing or not a list in test-data.` });
296
+ warns.push({ scenario: sc.name, message: `@cases:${ds} → dataset "${ds}" is missing or not a list in ${tdFile}.` });
232
297
  } else {
233
298
  const colSets = rows.map((r) => new Set(Object.keys(r || {}).filter((k) => !ROW_META.has(k))));
234
299
  const allCols = new Set<string>();
@@ -256,7 +321,7 @@ export function lintDataDriven(screenDir: string, cwd: string = process.cwd()):
256
321
  for (const r of refs) {
257
322
  const head = r.split(/[.[]/)[0];
258
323
  if (head.startsWith('$') || bound.has(head) || featureBound.has(head) || topKeys.has(head)) continue;
259
- warns.push({ scenario: sc.name, message: `{{${r}}} is not a test-data key and nothing binds it at run time — it compiles to the literal text '\${${r}}' (add the key to test-data, or fix the ref).` });
324
+ warns.push({ scenario: sc.name, message: `{{${r}}} is not a test-data key and nothing binds it at run time — it compiles to the literal text '\${${r}}' (add the key to ${tdFile}, or fix the ref).` });
260
325
  }
261
326
  }
262
327
 
@@ -289,15 +354,8 @@ export function lintDataDriven(screenDir: string, cwd: string = process.cwd()):
289
354
  for (const k of topKeys) {
290
355
  if (k.startsWith('_')) continue; // Data Factory metadata, not scenario data
291
356
  if (!usedHeads.has(k) && !usedDatasets.has(k)) {
292
- warns.push({ message: `test-data key "${k}" is defined but never referenced ({{${k}}}, a @cases dataset, or an override) — dead data: bind it into a scenario or remove it.` });
357
+ warns.push({ message: `test-data key "${k}" is defined but never referenced ({{${k}}}, a @cases dataset, or an override) by ${feature.name}.feature — dead data: bind it into a scenario or remove it from ${tdFile}.` });
293
358
  }
294
359
  }
295
-
296
- // Catalog-level lint (SELECT-only, params declared/used, datasource present).
297
- try {
298
- for (const e of lintCatalog(screenName, null, cwd).errors) warns.push({ message: e });
299
- } catch {
300
- /* no catalog → nothing to lint */
301
- }
302
360
  return warns;
303
361
  }
@@ -170,6 +170,7 @@ const REPAIRABLE = [
170
170
  'SPEC-RESTATED-UNVERIFIED', 'VIEWPOINT-GESTURE-SUBSTITUTED', 'SPEC-UNCOVERED', 'SPEC-CLAUSE-UNCOVERED',
171
171
  'TRIGGER-UNCOVERED', 'PERMISSION-PAIR-MISSING', 'VISIBILITY-PAIR-MISSING',
172
172
  'VIEWPOINT-ITEM-MISSING', 'MANUAL-CODE-MISSING', 'MANUAL-AUTOMATABLE', 'DEPTH-DEFERRED',
173
+ 'UI-INVENTORY-MISSING', 'UI-INVENTORY-INCOMPLETE', 'UI-ITEM-UNCOVERED',
173
174
  ];
174
175
 
175
176
  /**
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import * as fs from 'fs';
9
9
  import { GherkinParser, ParsedScenario, ParsedStep } from '../generators/gherkin-parser';
10
- import { readTextFile } from './read-text';
10
+ import { readTextFile, readViewpointText } from './read-text';
11
11
  import { featureFilesFor } from './unit-paths';
12
12
 
13
13
  export type Priority = 'high' | 'normal' | 'low' | 'unknown';
@@ -15,10 +15,49 @@ export type Priority = 'high' | 'normal' | 'low' | 'unknown';
15
15
  export interface ViewpointEntry {
16
16
  id: string; // e.g. VP-DATA-CONSISTENCY
17
17
  priority: 'High' | 'Medium' | 'Low' | 'Unknown';
18
+ /** The declared priority word as written (`critical` · `high` · `medium` · `normal` · `low` ·
19
+ * `deferred` · `skip`, which also stands for skipped / n/a / none / not applicable), kept because `priority` folds several of them together and the
20
+ * PRIORITY-CONTRADICTED check needs them apart. Absent when no priority was declared. */
21
+ priorityWord?: string;
18
22
  reason: string;
19
23
  group?: 'Required' | 'Recommended' | 'Optional';
20
24
  }
21
25
 
26
+ /**
27
+ * Whole SECTIONS that declare something ABOUT the checklist rather than listing claims or
28
+ * viewpoints — known issues, traceability indexes, references, changelogs. Shared by the atomic
29
+ * ledger (their rows are not claims to prove, #630) and the viewpoint-overview parser (an id
30
+ * listed there is a reference, not a declaration, #833). `UI Patterns Identified` is the author's
31
+ * pick of WHICH sungen-viewpoint patterns apply — a `Skip` row there is not a claim to cover (#841).
32
+ * A `How to run` / `Procedure` section — that exact heading, optionally naming one id — is a manual
33
+ * check's steps, not claims of its own (#855); `How to test the login flow` stays a normal section.
34
+ */
35
+ export const NON_DECLARATION_SECTION = /^(?:(?:ui patterns?(?: identified)?|(?:how to (?:run|test|reproduce|verify)|(?:manual )?procedures?)(?:\s+(?:vp|fl)-[^\s:]+)?)\s*:?$|(?:known issues?|open questions?|deferred|out of scope|viewpoint grouping|traceability|metadata|scope|journey phases?|revision history|references?|sources?|changelog)\b)/i;
36
+
37
+ /**
38
+ * Every word a viewpoint row may declare as its priority — ONE list for the overview parser, the
39
+ * atomic ledger and the integrity checks, which each carried their own copy and all missed the
40
+ * `Skip` that the `sungen add` / `add-flow` scaffolds themselves suggest (#853). `deferred` and the
41
+ * not-applicable words are declarations as well: such a row is not a claim to cover.
42
+ */
43
+ export const PRIORITY_WORDS = 'critical|high|medium|normal|low|deferred|skip(?:ped)?|n\\/a|none|not applicable';
44
+ /** "Declared not applicable" — folded to `skip` so every consumer checks one word. */
45
+ const NOT_APPLICABLE = /^(?:skip(?:ped)?|n\/a|none|not applicable)$/i;
46
+
47
+ // The whole cell must BE the word (emphasis aside), as the old `| VP-… | high |` scan required:
48
+ // "Low risk" or "Not high" declares no priority.
49
+ const PRIORITY_WORD = new RegExp(`^[\\s*_\`]*(${PRIORITY_WORDS})[\\s*_\`.]*$`, 'i');
50
+ /** Header names of a priority column, in the languages viewpoint files are written in. */
51
+ const PRIORITY_HEADER = /^(?:priority|pri|level|severity|優先度?|độ ưu tiên|ưu tiên)(?:\s|\(|$)/i;
52
+
53
+ /** A priority cell → the folded level plus the word as written. */
54
+ function priorityOf(cell: string): { priority: ViewpointEntry['priority']; priorityWord?: string } {
55
+ const raw = cell.match(PRIORITY_WORD)?.[1].toLowerCase();
56
+ const word = raw && NOT_APPLICABLE.test(raw) ? 'skip' : raw;
57
+ const priority = /high/i.test(cell) ? 'High' : /medium/i.test(cell) ? 'Medium' : /low/i.test(cell) ? 'Low' : 'Unknown';
58
+ return word ? { priority, priorityWord: word } : { priority };
59
+ }
60
+
22
61
  export interface ScenarioInfo {
23
62
  name: string;
24
63
  vpCode?: string; // VP-CART-001 style code in the scenario title
@@ -39,8 +78,10 @@ export interface ScenarioInfo {
39
78
  exploration?: boolean; // @exploration — a probe outside the official suite, exempt from source tracing
40
79
  deferredToFlow?: boolean; // @deferred:flow — owned by a flow, not automated on this screen (H6)
41
80
  ownedByFlow?: string; // @owned-by:<flow> — the flow that owns this deferred scenario (H6)
81
+ featureManual?: boolean; // its Feature is tagged @manual — codegen skips the whole file (#835)
42
82
  /** Ordered steps with their resolved bucket (And/But inherit) — flow handoff analysis (#569). */
43
- steps?: Array<{ bucket: 'given' | 'when' | 'then'; text: string }>;
83
+ /** `arg` = the step's data table, normalised (#817) — absent when the step has none. */
84
+ steps?: Array<{ bucket: 'given' | 'when' | 'then'; text: string; arg?: string }>;
44
85
  /**
45
86
  * The `.feature` this scenario was read from. A unit may hold several (`add --feature`), and
46
87
  * `scenarioIdReuse` scopes its uniqueness check to ONE file — so the sensor needs to know
@@ -106,7 +147,7 @@ function headingParts(line: string): { level: number; text: string } | null {
106
147
 
107
148
  export function parseViewpointOverview(filePath: string): ViewpointEntry[] {
108
149
  if (!fs.existsSync(filePath)) return [];
109
- const text = readTextFile(filePath);
150
+ const text = readViewpointText(filePath);
110
151
  const lines = text.split('\n');
111
152
 
112
153
  const entries = new Map<string, ViewpointEntry>();
@@ -125,8 +166,7 @@ export function parseViewpointOverview(filePath: string): ViewpointEntry[] {
125
166
  // and an id read with its emphasis markers still attached matches no scenario tag.
126
167
  const id = cells[0].replace(/[*`]/g, '').trim();
127
168
  if (isViewpointId(id) && !/^-+$/.test(cells[1])) {
128
- const pr = /high/i.test(cells[1]) ? 'High' : /medium/i.test(cells[1]) ? 'Medium' : /low/i.test(cells[1]) ? 'Low' : 'Unknown';
129
- entries.set(id.toUpperCase(), { id: id.toUpperCase(), priority: pr as any, reason: cells[2] });
169
+ entries.set(id.toUpperCase(), { id: id.toUpperCase(), ...priorityOf(cells[1]), reason: cells[2] });
130
170
  }
131
171
  }
132
172
  }
@@ -179,6 +219,52 @@ export function parseViewpointOverview(filePath: string): ViewpointEntry[] {
179
219
  }
180
220
  }
181
221
 
222
+ // 3) ID-first tables (#833): per-axis tables such as `| ID | Priority | Input | Expected |`.
223
+ // A row whose FIRST cell is a viewpoint id declares that id — the same rows the
224
+ // PRIORITY-CONTRADICTED check always read, so the two readers now agree. Kept narrow on purpose,
225
+ // because a viewpoint file also holds tables that only MENTION ids:
226
+ // - the id must be a `VP-`/`FL-` id, or belong to a family this file already declared above
227
+ // (`MS-HP` in Priority Viewpoints → `MS-HP-001`); `TC-01`, `FR-001`, `ISO-27001` never are;
228
+ // - reference sections (Known Issues, Traceability…) are skipped WITH their subsections, the
229
+ // way the ledger inherits the exclusion (#657), and fenced blocks are skipped;
230
+ // - the header is the row directly above a `|---|` separator (structure, not guessed words);
231
+ // its Priority column (any position, any alias) gives the priority, else column 2 does, as
232
+ // the old scan read it;
233
+ // - `reason` stays empty: viewpoint reasons feed page-type detection, and these rows were never
234
+ // entries before — the page type of an untouched file must not move.
235
+ const declaredFamilies = [...entries.keys()];
236
+ const familyOk = (id: string): boolean =>
237
+ /^(?:VP|FL)-/i.test(id) || declaredFamilies.some((f) => id.startsWith(`${f}-`) || id === f);
238
+ const isSeparator = (l: string): boolean => /^\|[\s|:-]+\|?$/.test(l) && l.includes('-');
239
+ let excludedAt: number | null = null;
240
+ let inFence = false;
241
+ let priorityCol = 1;
242
+ for (let i = 0; i < lines.length; i++) {
243
+ const line = lines[i].trim();
244
+ if (/^(```|~~~)/.test(line)) { inFence = !inFence; continue; }
245
+ if (inFence) continue;
246
+ const head = headingParts(line);
247
+ if (head) {
248
+ if (excludedAt !== null && head.level > excludedAt) continue; // subsection inherits
249
+ const text = head.text.replace(/[*`]/g, '').trim();
250
+ excludedAt = /^Priority Viewpoints/i.test(text) || NON_DECLARATION_SECTION.test(text) ? head.level : null;
251
+ continue;
252
+ }
253
+ if (excludedAt !== null || !line.startsWith('|') || isSeparator(line)) continue;
254
+ const cells = line.split('|').map((c) => c.trim()).filter((_, k, a) => k > 0 && k < a.length - 1);
255
+ if (isSeparator((lines[i + 1] ?? '').trim())) { // header row
256
+ const col = cells.findIndex((c) => PRIORITY_HEADER.test(c.replace(/[*`]/g, '').trim()));
257
+ priorityCol = col >= 0 ? col : 1;
258
+ continue;
259
+ }
260
+ const id = (cells[0] ?? '').replace(/[*`]/g, '').trim().toUpperCase();
261
+ if (!isViewpointId(id) || !familyOk(id)) continue;
262
+ const declared = priorityOf(cells[priorityCol] ?? '');
263
+ const existing = entries.get(id);
264
+ if (!existing) entries.set(id, { id, ...declared, reason: '' });
265
+ else if (!existing.priorityWord && declared.priorityWord) existing.priorityWord = declared.priorityWord;
266
+ }
267
+
182
268
  return [...entries.values()];
183
269
  }
184
270
 
@@ -246,22 +332,20 @@ function classifyScenario(sc: ParsedScenario): ScenarioInfo {
246
332
  const skeletonParts: string[] = [];
247
333
  const textParts: string[] = [sc.name];
248
334
  const stepTextParts: string[] = [];
249
- const orderedSteps: Array<{ bucket: 'given' | 'when' | 'then'; text: string }> = [];
335
+ const orderedSteps: Array<{ bucket: 'given' | 'when' | 'then'; text: string; arg?: string }> = [];
250
336
 
251
337
  for (const step of sc.steps as ParsedStep[]) {
252
338
  const kw = step.keyword.trim();
253
339
  if (kw === 'Given' || kw === 'When' || kw === 'Then') last = kw;
254
340
  textParts.push(step.text);
255
341
  stepTextParts.push(step.text);
256
- orderedSteps.push({ bucket: (kw === 'And' || kw === 'But' ? last : kw).toLowerCase() as 'given' | 'when' | 'then', text: step.text });
257
- // normalized skeleton: keep [refs] (distinct targets = distinct tests),
258
- // but neutralize {{vars}} and quoted values so EP/data families collapse.
259
- const skel = step.text
260
- .replace(/\{\{[^}]*\}\}/g, '{}')
261
- .replace(/"[^"]*"/g, '""')
262
- .replace(/\s+/g, ' ')
263
- .trim()
264
- .toLowerCase();
342
+ // The data table is part of what a step says (#817): `User see tab order:` with [FieldA]→[Cancel]
343
+ // and with [Save]→[Close] are different tests, and comparing step text alone called them exact
344
+ // duplicates and one oracle asserted N times. Kept OUT of `text`, which the claim/keyword sensors
345
+ // read as prose.
346
+ const arg = tableArg(step);
347
+ orderedSteps.push({ bucket: (kw === 'And' || kw === 'But' ? last : kw).toLowerCase() as 'given' | 'when' | 'then', text: step.text, ...(arg ? { arg } : {}) });
348
+ const skel = skeletonOf(step.text) + (arg ? ` ${skeletonOf(arg)}` : '');
265
349
  skeletonParts.push(`${kw === 'And' || kw === 'But' ? last : kw}:${skel}`);
266
350
 
267
351
  if (last === 'Then') {
@@ -309,9 +393,11 @@ export function loadScenarios(featurePath: string): ScenarioInfo[] {
309
393
  if (!fs.existsSync(featurePath)) return [];
310
394
  const parser = new GherkinParser();
311
395
  const feature = parser.parseFeatureFile(featurePath);
396
+ // Kept apart from `manual` so the audit's accounting is unchanged; only `select` reads it.
397
+ const featureManual = (feature.tags || []).some((t: string) => /^@manual\b/i.test(t)) || undefined;
312
398
  return (feature.scenarios || [])
313
399
  .filter((s) => !s.stepsName && !s.hookType) // skip @steps/@hook blocks
314
- .map((s) => ({ ...classifyScenario(withBackground(s, feature.background)), sourceFile: featurePath }));
400
+ .map((s) => ({ ...classifyScenario(withBackground(s, feature.background)), sourceFile: featurePath, featureManual }));
315
401
  }
316
402
 
317
403
  /**
@@ -334,3 +420,24 @@ export function readUnitFeatureText(unitDir: string, unit: string): string {
334
420
  .map((p) => readTextFile(p))
335
421
  .join('\n');
336
422
  }
423
+
424
+ /**
425
+ * Normalised skeleton of step text: keep [refs] (distinct targets = distinct tests), but neutralise
426
+ * {{vars}} and quoted values so EP/data families collapse.
427
+ */
428
+ function skeletonOf(text: string): string {
429
+ return text
430
+ .replace(/\{\{[^}]*\}\}/g, '{}')
431
+ .replace(/"[^"]*"/g, '""')
432
+ .replace(/\s+/g, ' ')
433
+ .trim()
434
+ .toLowerCase();
435
+ }
436
+
437
+ /** A step's data table as one comparable string — `<h1|h2 / c1|c2 / …>` — or undefined. */
438
+ function tableArg(step: ParsedStep): string | undefined {
439
+ const t = step.dataTable;
440
+ if (!t || (!t.headers.length && !t.rows.length)) return undefined;
441
+ const rows = [t.headers, ...t.rows.map((r) => r.cells)].map((cells) => cells.map((c) => c.trim()).join('|'));
442
+ return `<${rows.join(' / ')}>`;
443
+ }