@sun-asterisk/sungen 3.2.21 → 3.2.22-beta.2

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 (188) hide show
  1. package/dist/cli/commands/audit.d.ts.map +1 -1
  2. package/dist/cli/commands/audit.js +8 -0
  3. package/dist/cli/commands/audit.js.map +1 -1
  4. package/dist/cli/commands/delivery.d.ts +3 -0
  5. package/dist/cli/commands/delivery.d.ts.map +1 -1
  6. package/dist/cli/commands/delivery.js +15 -0
  7. package/dist/cli/commands/delivery.js.map +1 -1
  8. package/dist/cli/commands/inspect.d.ts +41 -0
  9. package/dist/cli/commands/inspect.d.ts.map +1 -0
  10. package/dist/cli/commands/inspect.js +134 -0
  11. package/dist/cli/commands/inspect.js.map +1 -0
  12. package/dist/cli/commands/trace.d.ts.map +1 -1
  13. package/dist/cli/commands/trace.js +9 -0
  14. package/dist/cli/commands/trace.js.map +1 -1
  15. package/dist/cli/index.js +2 -0
  16. package/dist/cli/index.js.map +1 -1
  17. package/dist/exporters/matrix/build.d.ts +10 -0
  18. package/dist/exporters/matrix/build.d.ts.map +1 -1
  19. package/dist/exporters/matrix/build.js +38 -0
  20. package/dist/exporters/matrix/build.js.map +1 -1
  21. package/dist/exporters/matrix/export.d.ts.map +1 -1
  22. package/dist/exporters/matrix/export.js +11 -0
  23. package/dist/exporters/matrix/export.js.map +1 -1
  24. package/dist/exporters/matrix/render-xlsx.d.ts.map +1 -1
  25. package/dist/exporters/matrix/render-xlsx.js +44 -1
  26. package/dist/exporters/matrix/render-xlsx.js.map +1 -1
  27. package/dist/exporters/matrix/types.d.ts +10 -0
  28. package/dist/exporters/matrix/types.d.ts.map +1 -1
  29. package/dist/exporters/matrix/types.js.map +1 -1
  30. package/dist/exporters/playwright-report-parser.d.ts.map +1 -1
  31. package/dist/exporters/playwright-report-parser.js +1 -0
  32. package/dist/exporters/playwright-report-parser.js.map +1 -1
  33. package/dist/exporters/types.d.ts +2 -0
  34. package/dist/exporters/types.d.ts.map +1 -1
  35. package/dist/generators/test-generator/adapters/appium/templates/imports.hbs +9 -0
  36. package/dist/generators/test-generator/adapters/appium/templates/scenario.hbs +23 -1
  37. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/capture-row-column.hbs +2 -0
  38. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/capture-variable.hbs +10 -0
  39. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/click-with-alert-action.hbs +7 -0
  40. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/drag-action.hbs +14 -2
  41. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/hover-element-with-text.hbs +3 -0
  42. package/dist/generators/test-generator/adapters/appium/templates/steps/actions/table-action-in-row-nth.hbs +2 -0
  43. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/all-contain-assertion.hbs +17 -0
  44. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/all-contain-element.hbs +13 -0
  45. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-filter-assertion.hbs +26 -0
  46. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-role-variable-assertion.hbs +24 -0
  47. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-variable-assertion.hbs +9 -0
  48. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-dialog-heading-assertion.hbs +10 -0
  49. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-filter-assertion.hbs +14 -0
  50. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-role-variable-assertion.hbs +21 -0
  51. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-variable-assertion.hbs +10 -0
  52. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/row-scoped-column-assertion.hbs +2 -0
  53. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/state-with-filter-assertion.hbs +23 -0
  54. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/storage-key-assertion.hbs +2 -0
  55. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/tab-order-assertion.hbs +3 -0
  56. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/visible-dialog-heading-assertion.hbs +10 -0
  57. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/visible-filtered-assertion.hbs +17 -0
  58. package/dist/generators/test-generator/adapters/appium/templates/steps/assertions/visible-with-role-variable-assertion.hbs +13 -0
  59. package/dist/generators/test-generator/adapters/appium/templates/steps/navigation/wait-table-refresh.hbs +13 -0
  60. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/drag-action.hbs +1 -1
  61. package/dist/generators/test-generator/adapters/playwright/templates/steps/actions/frame-enter-action.hbs +1 -1
  62. package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/all-contain-element.hbs +5 -5
  63. package/dist/generators/test-generator/adapters/playwright/templates/steps/assertions/row-scoped-column-assertion.hbs +1 -0
  64. package/dist/generators/test-generator/code-generator.d.ts.map +1 -1
  65. package/dist/generators/test-generator/code-generator.js +29 -8
  66. package/dist/generators/test-generator/code-generator.js.map +1 -1
  67. package/dist/generators/test-generator/diagnostics.d.ts +25 -1
  68. package/dist/generators/test-generator/diagnostics.d.ts.map +1 -1
  69. package/dist/generators/test-generator/diagnostics.js +24 -0
  70. package/dist/generators/test-generator/diagnostics.js.map +1 -1
  71. package/dist/generators/test-generator/patterns/index.d.ts +45 -0
  72. package/dist/generators/test-generator/patterns/index.d.ts.map +1 -1
  73. package/dist/generators/test-generator/patterns/index.js +159 -20
  74. package/dist/generators/test-generator/patterns/index.js.map +1 -1
  75. package/dist/generators/test-generator/patterns/types.d.ts +36 -0
  76. package/dist/generators/test-generator/patterns/types.d.ts.map +1 -1
  77. package/dist/generators/test-generator/step-mapper.d.ts +33 -0
  78. package/dist/generators/test-generator/step-mapper.d.ts.map +1 -1
  79. package/dist/generators/test-generator/step-mapper.js +100 -24
  80. package/dist/generators/test-generator/step-mapper.js.map +1 -1
  81. package/dist/harness/audit.d.ts +2 -0
  82. package/dist/harness/audit.d.ts.map +1 -1
  83. package/dist/harness/audit.js +101 -10
  84. package/dist/harness/audit.js.map +1 -1
  85. package/dist/harness/flow-contract.d.ts +87 -0
  86. package/dist/harness/flow-contract.d.ts.map +1 -0
  87. package/dist/harness/flow-contract.js +259 -0
  88. package/dist/harness/flow-contract.js.map +1 -0
  89. package/dist/harness/flow-plan.d.ts +3 -0
  90. package/dist/harness/flow-plan.d.ts.map +1 -1
  91. package/dist/harness/flow-plan.js +6 -2
  92. package/dist/harness/flow-plan.js.map +1 -1
  93. package/dist/harness/parse.d.ts +5 -0
  94. package/dist/harness/parse.d.ts.map +1 -1
  95. package/dist/harness/parse.js +29 -1
  96. package/dist/harness/parse.js.map +1 -1
  97. package/dist/harness/perf.d.ts +40 -0
  98. package/dist/harness/perf.d.ts.map +1 -0
  99. package/dist/harness/perf.js +136 -0
  100. package/dist/harness/perf.js.map +1 -0
  101. package/dist/harness/sensors.d.ts.map +1 -1
  102. package/dist/harness/sensors.js +13 -1
  103. package/dist/harness/sensors.js.map +1 -1
  104. package/dist/harness/spec-coverage.d.ts +8 -0
  105. package/dist/harness/spec-coverage.d.ts.map +1 -1
  106. package/dist/harness/spec-coverage.js +60 -6
  107. package/dist/harness/spec-coverage.js.map +1 -1
  108. package/dist/orchestrator/templates/ai-src/commands/add-flow.md +51 -3
  109. package/dist/orchestrator/templates/ai-src/commands/create-test.md +10 -0
  110. package/dist/orchestrator/templates/ai-src/commands/run-test.md +23 -0
  111. package/dist/orchestrator/templates/ai-src/skills/sungen-api-design/SKILL.md +2 -2
  112. package/dist/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +4 -0
  113. package/dist/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +61 -12
  114. package/dist/orchestrator/templates/ai-src/skills/sungen-mobile-gestures/SKILL.md +22 -8
  115. package/dist/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +65 -17
  116. package/dist/orchestrator/templates/qa-context.md +14 -1
  117. package/dist/orchestrator/templates/specs-api.d.ts.map +1 -1
  118. package/dist/orchestrator/templates/specs-api.js +104 -29
  119. package/dist/orchestrator/templates/specs-api.js.map +1 -1
  120. package/dist/orchestrator/templates/specs-api.ts +104 -26
  121. package/dist/orchestrator/templates/specs-db.d.ts.map +1 -1
  122. package/dist/orchestrator/templates/specs-db.js +18 -5
  123. package/dist/orchestrator/templates/specs-db.js.map +1 -1
  124. package/dist/orchestrator/templates/specs-db.ts +19 -5
  125. package/package.json +3 -3
  126. package/src/cli/commands/audit.ts +8 -0
  127. package/src/cli/commands/delivery.ts +14 -2
  128. package/src/cli/commands/inspect.ts +128 -0
  129. package/src/cli/commands/trace.ts +9 -0
  130. package/src/cli/index.ts +2 -0
  131. package/src/exporters/matrix/build.ts +40 -0
  132. package/src/exporters/matrix/export.ts +11 -0
  133. package/src/exporters/matrix/render-xlsx.ts +45 -1
  134. package/src/exporters/matrix/types.ts +10 -0
  135. package/src/exporters/playwright-report-parser.ts +2 -0
  136. package/src/exporters/types.ts +2 -0
  137. package/src/generators/test-generator/adapters/appium/templates/imports.hbs +9 -0
  138. package/src/generators/test-generator/adapters/appium/templates/scenario.hbs +23 -1
  139. package/src/generators/test-generator/adapters/appium/templates/steps/actions/capture-row-column.hbs +2 -0
  140. package/src/generators/test-generator/adapters/appium/templates/steps/actions/capture-variable.hbs +10 -0
  141. package/src/generators/test-generator/adapters/appium/templates/steps/actions/click-with-alert-action.hbs +7 -0
  142. package/src/generators/test-generator/adapters/appium/templates/steps/actions/drag-action.hbs +14 -2
  143. package/src/generators/test-generator/adapters/appium/templates/steps/actions/hover-element-with-text.hbs +3 -0
  144. package/src/generators/test-generator/adapters/appium/templates/steps/actions/table-action-in-row-nth.hbs +2 -0
  145. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/all-contain-assertion.hbs +17 -0
  146. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/all-contain-element.hbs +13 -0
  147. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-filter-assertion.hbs +26 -0
  148. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-role-variable-assertion.hbs +24 -0
  149. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/disabled-with-variable-assertion.hbs +9 -0
  150. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-dialog-heading-assertion.hbs +10 -0
  151. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-filter-assertion.hbs +14 -0
  152. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-role-variable-assertion.hbs +21 -0
  153. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/hidden-with-variable-assertion.hbs +10 -0
  154. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/row-scoped-column-assertion.hbs +2 -0
  155. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/state-with-filter-assertion.hbs +23 -0
  156. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/storage-key-assertion.hbs +2 -0
  157. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/tab-order-assertion.hbs +3 -0
  158. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/visible-dialog-heading-assertion.hbs +10 -0
  159. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/visible-filtered-assertion.hbs +17 -0
  160. package/src/generators/test-generator/adapters/appium/templates/steps/assertions/visible-with-role-variable-assertion.hbs +13 -0
  161. package/src/generators/test-generator/adapters/appium/templates/steps/navigation/wait-table-refresh.hbs +13 -0
  162. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/drag-action.hbs +1 -1
  163. package/src/generators/test-generator/adapters/playwright/templates/steps/actions/frame-enter-action.hbs +1 -1
  164. package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/all-contain-element.hbs +5 -5
  165. package/src/generators/test-generator/adapters/playwright/templates/steps/assertions/row-scoped-column-assertion.hbs +1 -0
  166. package/src/generators/test-generator/code-generator.ts +34 -9
  167. package/src/generators/test-generator/diagnostics.ts +25 -1
  168. package/src/generators/test-generator/patterns/index.ts +172 -25
  169. package/src/generators/test-generator/patterns/types.ts +35 -0
  170. package/src/generators/test-generator/step-mapper.ts +106 -23
  171. package/src/harness/audit.ts +104 -11
  172. package/src/harness/flow-contract.ts +261 -0
  173. package/src/harness/flow-plan.ts +10 -3
  174. package/src/harness/parse.ts +31 -1
  175. package/src/harness/perf.ts +112 -0
  176. package/src/harness/sensors.ts +13 -1
  177. package/src/harness/spec-coverage.ts +55 -5
  178. package/src/orchestrator/templates/ai-src/commands/add-flow.md +51 -3
  179. package/src/orchestrator/templates/ai-src/commands/create-test.md +10 -0
  180. package/src/orchestrator/templates/ai-src/commands/run-test.md +23 -0
  181. package/src/orchestrator/templates/ai-src/skills/sungen-api-design/SKILL.md +2 -2
  182. package/src/orchestrator/templates/ai-src/skills/sungen-error-mapping/SKILL.md +4 -0
  183. package/src/orchestrator/templates/ai-src/skills/sungen-gherkin-syntax/SKILL.md +61 -12
  184. package/src/orchestrator/templates/ai-src/skills/sungen-mobile-gestures/SKILL.md +22 -8
  185. package/src/orchestrator/templates/ai-src/skills/sungen-tc-generation/SKILL.md +65 -17
  186. package/src/orchestrator/templates/qa-context.md +14 -1
  187. package/src/orchestrator/templates/specs-api.ts +104 -26
  188. package/src/orchestrator/templates/specs-db.ts +19 -5
@@ -10,10 +10,11 @@ import * as path from 'path';
10
10
  import * as fs from 'fs';
11
11
  import { loadUnitScenarios, readUnitFeatureText, parseViewpointOverview, ScenarioInfo, ViewpointEntry } from './parse';
12
12
  import { checkViewpointBaseline, ViewpointBaseline } from './viewpoint-baseline';
13
+ import { flowQuality, statefulDepthFor, FlowQualityResult } from './flow-contract';
13
14
  import { featureFilesFor } from './unit-paths';
14
15
  import {
15
16
  loadCatalog, viewpointGate, assertionDepth, dataThemesFor, depthThresholdFor, coverageBalance, duplicateClusters, traceability, claimProof, taxonomyLint,
16
- automatableManual, flowCoveredThemes, flowRegressionDepth, oracleStrength,
17
+ automatableManual, flowCoveredThemes, flowRegressionDepth, oracleStrength, declaredPageType,
17
18
  GateResult, DepthResult, BalanceResult, DuplicateResult, TraceResult, ClaimProofResult, TaxonomyResult, Catalog, AutomatableManualResult, FlowDepthResult, OracleStrengthResult,
18
19
  } from './sensors';
19
20
  import { loadFlowScenarios } from './flow-check';
@@ -48,6 +49,7 @@ export interface AuditReport {
48
49
  oracle: OracleStrengthResult; // H4 — facet-oracle strength (weak name-substring vs title/detail/API/DB)
49
50
  ledger: LedgerResult; // atomic viewpoint-item coverage (per-bullet status)
50
51
  viewpointBaseline: ViewpointBaseline; // is the yardstick still the accepted one? (#557)
52
+ flowQuality?: FlowQualityResult; // #569 — flow contract verification (flows only)
51
53
  calibration: { // #8 — multi-axis score so a high overall can't hide a weak axis
52
54
  axes: Record<string, number>;
53
55
  weakest: { axis: string; value: number };
@@ -154,15 +156,28 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
154
156
  // back to the in-core functions if the capability provides none.
155
157
  // A capability gate may need project context (the API gate resolves endpoint methods from the
156
158
  // catalog) + the focus depth threshold (so it scores depth with the SAME bar as the UI gate).
157
- const capGate = scoringCap?.gateProvider as
158
- ((i: { scenarios: ScenarioInfo[]; viewpoints: ViewpointEntry[]; catalog: Catalog; focus: typeof intent.focus; cwd: string; screenName: string; threshold: number; businessCriticalMethods?: string[] }) => { gate: GateResult; depth: DepthResult }) | undefined;
159
- const provided = capGate?.({ scenarios, viewpoints, catalog, focus: intent.focus, cwd: projectRootFromScreenDir(screenDir), screenName: catalogScreenName, threshold: depthThresholdFor(intent.focus), businessCriticalMethods: intent.businessCriticalMethods });
160
159
  // Is the declaration this suite is measured against still the one a human accepted?
161
160
  const viewpointBaseline = checkViewpointBaseline(
162
161
  projectRootFromScreenDir(screenDir), catalogScreenName, viewpointPath);
163
162
  const viewpointText = fs.existsSync(viewpointPath) ? readTextFile(viewpointPath) : '';
164
- const gate = provided?.gate ?? viewpointGate(scenarios, viewpoints, catalog, platform === 'mobile', viewpointText);
165
- const depth = provided?.depth ?? assertionDepth(scenarios, dataThemesFor(catalog, gate.pageType), intent.focus);
163
+ // #569 a flow WITH a contract is measured against ITS declaration, not a screen's.
164
+ // Keyword page-type detection force-fit flows into screen checklists (a registration
165
+ // flow judged as a `form` screen scored coverage 0%), so for contract-holding flows the
166
+ // page-type machinery only applies when the project DECLARED a page type explicitly.
167
+ // The stripped catalog feeds the CAPABILITY gate too — driver-ui provides the gate on
168
+ // real projects, and handing it the unstripped catalog re-introduced the force-fit.
169
+ const isUiFlowUnit = /^flows\//.test(catalogScreenName);
170
+ const flowQ: FlowQualityResult = isUiFlowUnit
171
+ ? flowQuality(screenDir, scenarios)
172
+ : { hasContract: false, errors: [], outcomeProven: false, outcomeManualOnly: false, offGoal: [], offGoalRatio: 0, offGoalCategories: [], phases: [], phaseRatio: 1, handoffs: { total: 0, asserted: 0, ratio: 1 }, sit: [] };
173
+ const gateCatalog = (flowQ.hasContract && !declaredPageType(viewpointText, catalog))
174
+ ? { ...catalog, page_types: {} } as Catalog
175
+ : catalog;
176
+ const capGate = scoringCap?.gateProvider as
177
+ ((i: { scenarios: ScenarioInfo[]; viewpoints: ViewpointEntry[]; catalog: Catalog; focus: typeof intent.focus; cwd: string; screenName: string; threshold: number; businessCriticalMethods?: string[] }) => { gate: GateResult; depth: DepthResult }) | undefined;
178
+ const provided = capGate?.({ scenarios, viewpoints, catalog: gateCatalog, focus: intent.focus, cwd: projectRootFromScreenDir(screenDir), screenName: catalogScreenName, threshold: depthThresholdFor(intent.focus), businessCriticalMethods: intent.businessCriticalMethods });
179
+ const gate = provided?.gate ?? viewpointGate(scenarios, viewpoints, gateCatalog, platform === 'mobile', viewpointText);
180
+ const depth = provided?.depth ?? assertionDepth(scenarios, dataThemesFor(gateCatalog, gate.pageType), intent.focus);
166
181
 
167
182
  // TQ-4 — deferral-aware coverage credit: an inherently cross-screen theme (cart / detail /
168
183
  // filter correctness) belongs in a FLOW, not on the screen. When a flow deeply covers a screen
@@ -200,8 +215,15 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
200
215
  // collection, the regression dimensions (count/quantity proof · teardown · multi-source) cap the
201
216
  // businessDepth headroom: it can reach 1.0 only when all three are exercised, so a present-but-
202
217
  // shallow flow can't claim a perfect score (floor 0.5 — assertion depth still dominates).
203
- const isUiFlow = /^flows\//.test(catalogScreenName);
204
- const flowDepth = isUiFlow ? flowRegressionDepth(scenarios) : { stateful: false, countProof: false, teardown: false, multiSource: false, ratio: 1, missing: [] } as FlowDepthResult;
218
+ const isUiFlow = isUiFlowUnit;
219
+ let flowDepth = isUiFlow ? flowRegressionDepth(scenarios) : { stateful: false, countProof: false, teardown: false, multiSource: false, ratio: 1, missing: [] } as FlowDepthResult;
220
+ // Contract-declared statefulness generalizes the cart-hardcoded vocabulary: a flow that
221
+ // mutates ANY named collection (order, application, submission …) gets the same three
222
+ // regression dims. The legacy cart detection stays for contract-less flows (snapshots).
223
+ if (isUiFlow && !flowDepth.stateful && flowQ.contract?.stateful) {
224
+ const d = statefulDepthFor(flowQ.contract.stateful, scenarios);
225
+ flowDepth = { stateful: true, countProof: d.countProof, teardown: d.teardown, multiSource: d.multiSource, ratio: d.ratio, missing: d.missing };
226
+ }
205
227
  const FLOW_DEPTH_FLOOR = 0.5;
206
228
  // H4 — oracle strength: a weak facet oracle (name-substring "proves" category/brand membership)
207
229
  // caps businessDepth the same way (floor 0.5). A suite with no facet claim, or a strong oracle, is
@@ -211,10 +233,14 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
211
233
 
212
234
  // Sub-scores
213
235
  const coverage = gate.coverageRatio;
236
+ // #569 — handoff integrity: a flow's depth is also whether each cross-screen transition
237
+ // is followed by an assertion on the carried state (same floor discipline as the other caps).
238
+ const HANDOFF_FLOOR = 0.5;
214
239
  const businessDepth = Math.min(
215
240
  depth.bcDepthRatio,
216
241
  flowDepth.stateful ? FLOW_DEPTH_FLOOR + (1 - FLOW_DEPTH_FLOOR) * flowDepth.ratio : 1,
217
242
  oracle.weak.length ? ORACLE_FLOOR + (1 - ORACLE_FLOOR) * oracle.ratio : 1,
243
+ flowQ.hasContract && flowQ.handoffs.total > 0 ? HANDOFF_FLOOR + (1 - HANDOFF_FLOOR) * flowQ.handoffs.ratio : 1,
218
244
  );
219
245
  // When the taxonomy drifted (most scenarios unclassified), the balance axis is unreliable — cap it
220
246
  // at 0.5 instead of awarding a vacuous 1.0 so a stale taxonomy fails loudly, not silently (H1).
@@ -246,8 +272,15 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
246
272
  // what a create-test run did, silently dropping the performance viewpoint on
247
273
  // the way. While the declaration is unconfirmed, neither axis is evidence.
248
274
  const viewpointMoved = viewpointBaseline.status === 'changed';
275
+ // 4. A flow with a contract is measured on ITS coverage: journey phases (HP/ER/EH
276
+ // automated) — not a screen's page-type themes. Same weight, same criticality,
277
+ // so a flow can finally EARN the coverage axis instead of always losing it to
278
+ // PAGE-TYPE-UNDETERMINED (or worse, being judged against a form checklist).
279
+ const flowScored = flowQ.hasContract;
249
280
  const axisDefs: Array<{ key: string; value: number; weight: number; applicable: boolean; critical: boolean }> = [
250
- { key: 'coverage', value: coverage, weight: 0.22, applicable: !!gate.pageType && gate.themesTotal > 0, critical: true },
281
+ flowScored
282
+ ? { key: 'flowCoverage', value: flowQ.phaseRatio, weight: 0.22, applicable: true, critical: true }
283
+ : { key: 'coverage', value: coverage, weight: 0.22, applicable: !!gate.pageType && gate.themesTotal > 0, critical: true },
251
284
  { key: 'specFR', value: specRatio, weight: 0.15, applicable: spec.hasSpec && spec.frTotal > 0, critical: true },
252
285
  { key: 'atomicLedger', value: ledger.ratio, weight: 0.13, applicable: ledger.hasViewpoint && ledger.total > 0 && !viewpointMoved, critical: true },
253
286
  { key: 'businessDepth', value: businessDepth, weight: 0.20, applicable: true, critical: true },
@@ -297,9 +330,49 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
297
330
  ].filter(Boolean).join(', ');
298
331
  findings.push(`VIEWPOINT-BASELINE-CHANGED: test-viewpoint.md no longer declares what it did when this unit was last accepted — ${moved || 'the declared ids were reordered or replaced'}. atomicLedger + traceability measure the suite AGAINST this file, so they are excluded from the score until the change is confirmed: a generator that rewrites the declaration scores both 100% by construction, and a viewpoint dropped from the file stops being missing from anything. Review the diff (a removed id means that coverage is now unclaimed), then run \`sungen audit --screen ${screenName} --accept-viewpoint\`.`);
299
332
  }
300
- if (gate.pageTypeSource === 'undetermined') {
333
+ // On a contract flow the page type is INTENTIONALLY not applied — the contract is the checklist.
334
+ if (gate.pageTypeSource === 'undetermined' && !flowScored) {
301
335
  findings.push(`PAGE-TYPE-UNDETERMINED: no page type fits this screen with enough confidence (best ${gate.pageTypeEvidence?.hits ?? 0} keyword hit(s)), so NO critical themes were demanded and the coverage axis is excluded from the score — declare it in test-viewpoint.md (\`page-type: <id>\`) to have the theme checklist applied.`);
302
336
  }
337
+ // ---- #569: flow-quality findings -----------------------------------------
338
+ if (isUiFlow && !flowQ.hasContract) {
339
+ const why = flowQ.errors.length ? ` (${flowQ.errors.join('; ')})` : '';
340
+ findings.push(`FLOW-CONTRACT-MISSING: this flow declares no contract${why} — without \`requirements/flow-contract.yaml\` (goal · trigger · outcome.screen · phases) the flow cannot be scored on ITS coverage (journey phases) and falls back to screen machinery. Author it with the boundary checklist: one business goal, a clear trigger, ONE observable outcome valuable to the actor, name = "Verb + outcome"; split anything that forms an independently valuable flow.`);
341
+ }
342
+ if (flowQ.hasContract) {
343
+ if (!flowQ.outcomeProven) {
344
+ findings.push(flowQ.outcomeManualOnly
345
+ ? `FLOW-OUTCOME-UNPROVEN: the goal "${flowQ.contract!.goal}" is covered only by @manual scenarios — the flow's own outcome (\`${flowQ.contract!.outcome.screen}\`) has no AUTOMATED data assertion, so a regression run cannot prove the journey still works. Automate the happy-path proof first; it is the reason this flow exists.`
346
+ : `FLOW-OUTCOME-UNPROVEN: no scenario asserts data on the outcome screen \`${flowQ.contract!.outcome.screen}\` — the flow never proves its own goal ("${flowQ.contract!.goal}"). Add the happy-path scenario that ends in the declared final assertion.`);
347
+ }
348
+ if (flowQ.offGoalRatio > 0.35) {
349
+ findings.push(`FLOW-SCOPE-CREEP: ${flowQ.offGoal.length}/${scenarios.length} scenarios never touch the outcome screen \`${flowQ.contract!.outcome.screen}\` and are not guards/error-recovery (categories: ${flowQ.offGoalCategories.join(', ')}) — evidence of a SECOND business goal in this flow. Split them into their own flow (one flow = one goal, one observable outcome).`);
350
+ }
351
+ for (const ph of flowQ.phases.filter((p) => !p.covered || !p.automated)) {
352
+ findings.push(`FLOW-PHASE-${ph.phase}-MISSING: journey phase ${ph.phase} (${ph.phase === 'HP' ? 'happy path proving the outcome' : ph.phase === 'ER' ? 'error recovery — validation must not trap the journey' : 'guards — direct access / back / refresh'}) is ${ph.covered ? 'covered only by @manual' : 'not covered'} → it does not count toward flowCoverage until automated.`);
353
+ }
354
+ // #580 P10 — the QA matrix keeps System INTEGRATION cases (external-system legs)
355
+ // separate, and holds their exit criteria open while they are mock-verified only.
356
+ for (const x of flowQ.sit.filter((v) => v.mockOnly).slice(0, 4)) {
357
+ findings.push(`SIT-MOCK-ONLY: "${x.name}" touches the external system "${x.external}" but is verified only against mocks — Pass (Mocked) says nothing about the real vendor behaviour. Re-verify on the real dependency before calling it Done (the delivery's External Dependency Tracking table holds the checklist).`);
358
+ }
359
+ // #580 P9 — a release-critical flow must carry its Final-Inspection selection.
360
+ if (flowQ.contract!.golden && !/@golden\b/i.test(featureText)) {
361
+ findings.push(`GOLDEN-MISSING: the contract declares \`golden: true\` (release-critical) but no scenario is tagged @golden — Final Inspection (\`sungen inspect\`) will have nothing to run for this flow. Tag the happy-path scenario(s) that prove the outcome.`);
362
+ }
363
+ if (flowQ.handoffs.total > 0 && flowQ.handoffs.ratio < 0.7) {
364
+ findings.push(`FLOW-HANDOFF-SHALLOW: only ${flowQ.handoffs.asserted}/${flowQ.handoffs.total} cross-screen transitions are followed by an assertion in the new screen — carried state (the thing a flow exists to verify) is unproven at the handoff. businessDepth is capped until asserted.`);
365
+ }
366
+ }
367
+ if (isUiFlow) {
368
+ // Flows defer more than screens, so an UNCODED @manual is costlier here: the capability
369
+ // planner cannot route it to the driver that would automate it (password-reset: 11/22
370
+ // manual, most of them M5-inbox — invisible while tagged bare).
371
+ const bareManual = (featureText.match(/@manual(?![:\w])/g) || []).length;
372
+ if (bareManual > 0) {
373
+ findings.push(`MANUAL-CODE-MISSING: ${bareManual} @manual tag(s) carry no reason code — tag @manual:M1..M9 (M5 = external dependency e.g. inbox, M3 = mock/network, M7 = environment) so the capability planner can route what a driver would automate.`);
374
+ }
375
+ }
303
376
  for (const c of flowCredits) {
304
377
  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\`.`);
305
378
  }
@@ -318,7 +391,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
318
391
  const tag = depth.verdict === 'fail' ? 'DEPTH-FAIL' : depth.verdict === 'warn' ? 'DEPTH-WARN' : 'DEPTH';
319
392
  findings.push(
320
393
  `${tag}: ${depth.businessCriticalShallow}/${depth.businessCriticalTotal} data-correctness scenarios assert only visibility ` +
321
- `(ratio ${depth.bcDepthRatio.toFixed(2)} < threshold ${depth.threshold.toFixed(2)} for focus "${depth.focus}") → ` +
394
+ `(ratio ${depth.bcDepthRatio.toFixed(2)} ${depth.bcDepthRatio < depth.threshold ? '<' : '≥'} threshold ${depth.threshold.toFixed(2)} for focus "${depth.focus}"${depth.bcDepthRatio < depth.threshold ? '' : ' — the gate holds; these are the remaining deepen-targets'}) → ` +
322
395
  `add data assertions (\`... with {{value}}\`, \`see all ... contain {{v}}\`) or, if cross-screen, defer to a flow with @manual + reason.`,
323
396
  );
324
397
  }
@@ -376,6 +449,13 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
376
449
  const shown = spec.inferredOnly.slice(0, 8).join(', ');
377
450
  findings.push(`SPEC-TRACE-IMPLICIT: ${spec.inferredOnly.length} requirement(s) are covered by keyword inference only (${shown}${spec.inferredOnly.length > 8 ? ', …' : ''}) — add \`@spec:<id>\` to the scenario that proves each so the trace survives edits and delivery can report it.`);
378
451
  }
452
+ // Safety net for the parser (#572): the feature CITES requirement ids the spec parser
453
+ // could not find a declaration for. Silence here would repeat the original failure —
454
+ // "nothing found" quietly excluding the specFR axis while the evidence sits in the file.
455
+ if (spec.hasSpec && spec.frTotal === 0 && /@spec:/i.test(featureText)) {
456
+ const cited = [...new Set([...featureText.matchAll(/@spec:([A-Za-z0-9.-]+)/g)].map((m) => m[1].toUpperCase()))];
457
+ findings.push(`SPEC-IDS-UNPARSED: the feature cites ${cited.length} requirement id(s) via @spec: (${cited.slice(0, 5).join(', ')}${cited.length > 5 ? ', …' : ''}) but requirements/spec.md yielded ZERO parseable requirement declarations — the spec likely declares ids in a scheme the parser cannot read. Declare each requirement on its own line as \`<ID>: <clause>\` (bullet/bold/backtick all fine; the id must end in a number) so the MUST-coverage gate and the specFR axis can run.`);
458
+ }
379
459
  if (taxonomyMismatch) {
380
460
  findings.push(`VP-TAXONOMY-MISMATCH: only ${(trace.mappedRatio * 100).toFixed(0)}% of scenarios use the viewpoint IDs declared in test-viewpoint.md — scenarios invented a generic VP-<CAT> scheme. Re-tag to the project's viewpoint IDs so the coverage matrix is accurate.`);
381
461
  }
@@ -429,6 +509,18 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
429
509
  for (const d of ownership.duplicates.slice(0, 6)) {
430
510
  findings.push(`DUPLICATE-FLOW-OWNERSHIP: "${d.scenario}" has the same shape as a scenario in flow "${d.flow}" — keep one owner (screen-local vs flow); the other should only reference/set up.`);
431
511
  }
512
+ // #580 — the flow→screen half of the ownership rule (ISTQB system-test design:
513
+ // representative, not exhaustive). A flow's cases take ONE representative input per
514
+ // branch — one valid value on the main flow, one error value that triggers the
515
+ // exception flow. An EP/data-family cluster (≥3 same-shape scenarios differing only
516
+ // in data) inside a FLOW is the screen's validation matrix being re-run where it
517
+ // does not belong: the screen already proved the field rejects each class; the flow
518
+ // only has to prove the journey survives one of them. Advisory — never a gate.
519
+ if (isUiFlow) {
520
+ for (const c of duplicates.clusters.filter((x) => !x.sameDataLikely && x.scenarios.length >= 3).slice(0, 4)) {
521
+ findings.push(`FLOW-EXHAUSTIVE-INPUTS: ${c.scenarios.length} same-shape scenarios differ only in data (${c.scenarios.slice(0, 3).join(' | ')}${c.scenarios.length > 3 ? ' …' : ''}) — a system-test flow uses REPRESENTATIVE inputs (one valid + one that triggers the exception branch); the full EP/boundary matrix belongs to the owning screen (or a @cases dataset there). Keep one representative per branch here.`);
522
+ }
523
+ }
432
524
  for (const u of unsourced.slice(0, 6)) {
433
525
  findings.push(`UNSOURCEABLE-SCENARIO: "${u}" doesn't trace to any FR / viewpoint item — link it to a source, or tag it @exploration (not part of the official suite).`);
434
526
  }
@@ -485,6 +577,7 @@ export function runAudit(screenDir: string, screenName: string): AuditReport {
485
577
  scenarioCount: scenarios.length,
486
578
  gate, depth, claim, taxonomy, balance, duplicates, trace, spec,
487
579
  taxonomyMismatch, downstream, manualOracle: manualOracleResult, automatableManual: autoManual, flowDepth, oracle, ledger, viewpointBaseline, calibration,
580
+ ...(isUiFlow ? { flowQuality: flowQ } : {}),
488
581
  score: {
489
582
  overall: Math.round(overall * 10) / 10,
490
583
  coverage: Math.round(coverage * 100) / 100,
@@ -0,0 +1,261 @@
1
+ /**
2
+ * Flow Contract — the declared boundary of a flow, and the sensors that verify
3
+ * the suite against it. (#569, docs/spec/sungen-flow-quality-spec.md)
4
+ *
5
+ * A flow is the SMALLEST complete business action chain: one clear trigger ending
6
+ * in ONE observable, valuable outcome. Nothing enforced that: `add-flow` asked only
7
+ * "which screens, in order?", so a real example mixed three business goals (cart,
8
+ * filter, product-detail) in one "flow", and the harness scored flows with screen
9
+ * machinery — a registration flow was judged against the `form` page-type checklist
10
+ * (coverage 0%), and every flow audit showed taxonomy=0% because flow phase ids
11
+ * (FL-HP-001) don't even parse as categories.
12
+ *
13
+ * The contract is a declaration the QA owns (AI proposes at add-flow; a filled
14
+ * contract is an INPUT to generation, never an output — same rule as
15
+ * test-viewpoint.md). These sensors are deterministic checks against it:
16
+ *
17
+ * - outcome proof — the flow proves its own goal with an automated data assertion
18
+ * - scope creep — scenarios that never touch the outcome are a second goal
19
+ * - phase coverage — HP / ER / EH journey phases, the flow's coverage axis
20
+ * - handoff — a cross-screen transition is followed by an assertion
21
+ * - stateful depth — generalizes the cart-hardcoded regression dims to any
22
+ * declared collection (order, application, submission …)
23
+ */
24
+ import * as fs from 'fs';
25
+ import * as path from 'path';
26
+ import { parse as parseYaml } from 'yaml';
27
+ import { ScenarioInfo } from './parse';
28
+ import { readTextFile } from './read-text';
29
+
30
+ export interface FlowContract {
31
+ goal: string;
32
+ actor?: string;
33
+ trigger?: string;
34
+ precondition?: string;
35
+ outcome: { screen: string; assertion?: string };
36
+ value?: string;
37
+ /** Journey phases this flow declares. Default [HP, ER, EH]; UI is allowed but
38
+ * never demanded (presentation is the balance axis's business, not coverage's). */
39
+ phases: string[];
40
+ /** The mutated collection (cart, order, application …) — enables regression dims. */
41
+ stateful?: string;
42
+ budgets?: Record<string, number>;
43
+ /** External-system legs (owned by another team/vendor) — ISTQB System INTEGRATION Testing
44
+ * scope (#580 P10). Scenarios touching these namespaces are classified SIT. */
45
+ external?: Array<{ name: string; owner?: string; screens: string[] }>;
46
+ /** This flow is release-critical: Final Inspection expects a @golden scenario here (P9). */
47
+ golden?: boolean;
48
+ }
49
+
50
+ export interface FlowQualityResult {
51
+ hasContract: boolean;
52
+ contract?: FlowContract;
53
+ /** Parse/shape errors — a broken contract is reported, never silently ignored. */
54
+ errors: string[];
55
+ outcomeProven: boolean;
56
+ /** Manual-only proof: the goal is covered but not by automation. */
57
+ outcomeManualOnly: boolean;
58
+ /** Scenario names that never touch the outcome screen (guard/error phases excluded). */
59
+ offGoal: string[];
60
+ offGoalRatio: number;
61
+ /** Off-goal categories, for the split suggestion ("VP-FILTER-* looks like its own flow"). */
62
+ offGoalCategories: string[];
63
+ phases: { phase: string; covered: boolean; automated: boolean }[];
64
+ /** Covered-and-automated phases / declared phases (UI excluded) — the flow coverage axis. */
65
+ phaseRatio: number;
66
+ /** Cross-namespace transitions followed by an assertion / all transitions. */
67
+ handoffs: { total: number; asserted: number; ratio: number };
68
+ /** ISTQB SIT classification (#580 P10): scenarios whose steps touch an external-system
69
+ * namespace declared in the contract's `external:` block. */
70
+ sit: Array<{ name: string; external: string; mockOnly: boolean }>;
71
+ }
72
+
73
+ const DEFAULT_PHASES = ['HP', 'ER', 'EH'];
74
+
75
+ export function flowContractPath(unitDir: string): string {
76
+ return path.join(unitDir, 'requirements', 'flow-contract.yaml');
77
+ }
78
+
79
+ /** Load + validate. Returns null when absent; a present-but-broken file returns errors. */
80
+ export function loadFlowContract(unitDir: string): { contract: FlowContract | null; errors: string[] } {
81
+ const p = flowContractPath(unitDir);
82
+ if (!fs.existsSync(p)) return { contract: null, errors: [] };
83
+ let raw: Record<string, unknown>;
84
+ try {
85
+ raw = parseYaml(readTextFile(p)) as Record<string, unknown>;
86
+ } catch (e) {
87
+ return { contract: null, errors: [`flow-contract.yaml does not parse: ${(e as Error).message}`] };
88
+ }
89
+ if (!raw || typeof raw !== 'object') return { contract: null, errors: ['flow-contract.yaml is empty'] };
90
+ const errors: string[] = [];
91
+ if (!raw.goal || typeof raw.goal !== 'string') errors.push('missing `goal:` (Verb + outcome, e.g. "Place an order for a product added from home")');
92
+ const outcome = raw.outcome as { screen?: unknown; assertion?: unknown } | undefined;
93
+ if (!outcome || typeof outcome.screen !== 'string' || !outcome.screen.trim()) {
94
+ errors.push('missing `outcome.screen:` — the screen namespace that carries the final proof');
95
+ }
96
+ if (errors.length > 0) return { contract: null, errors };
97
+ const phases = Array.isArray(raw.phases) && raw.phases.length > 0
98
+ ? (raw.phases as unknown[]).map((x) => String(x).toUpperCase())
99
+ : DEFAULT_PHASES;
100
+ return {
101
+ contract: {
102
+ goal: String(raw.goal),
103
+ actor: raw.actor !== undefined ? String(raw.actor) : undefined,
104
+ trigger: raw.trigger !== undefined ? String(raw.trigger) : undefined,
105
+ precondition: raw.precondition !== undefined ? String(raw.precondition) : undefined,
106
+ outcome: { screen: String(outcome!.screen).toLowerCase(), assertion: outcome!.assertion !== undefined ? String(outcome!.assertion) : undefined },
107
+ value: raw.value !== undefined ? String(raw.value) : undefined,
108
+ phases,
109
+ stateful: raw.stateful !== undefined ? String(raw.stateful).toLowerCase() : undefined,
110
+ budgets: (raw.budgets && typeof raw.budgets === 'object') ? raw.budgets as Record<string, number> : undefined,
111
+ external: Array.isArray(raw.external)
112
+ ? (raw.external as Array<Record<string, unknown>>)
113
+ .filter((e) => e && typeof e === 'object' && e.name)
114
+ .map((e) => ({
115
+ name: String(e.name),
116
+ owner: e.owner !== undefined ? String(e.owner) : undefined,
117
+ screens: Array.isArray(e.screens) ? (e.screens as unknown[]).map((x) => String(x).toLowerCase()) : [],
118
+ }))
119
+ : undefined,
120
+ golden: raw.golden === true,
121
+ },
122
+ errors: [],
123
+ };
124
+ }
125
+
126
+ /** `[screen:element]` namespaces referenced by a scenario's steps, in step order. */
127
+ function namespacesInOrder(s: ScenarioInfo): string[] {
128
+ const out: string[] = [];
129
+ for (const m of s.stepsText.matchAll(/\[([a-z0-9_.-]+):/g)) out.push(m[1]);
130
+ return out;
131
+ }
132
+
133
+ function touchesOutcome(s: ScenarioInfo, outcomeScreen: string): boolean {
134
+ return namespacesInOrder(s).includes(outcomeScreen);
135
+ }
136
+
137
+ /** Phase of a scenario: its declared phase token (FL-HP-001 / VP-FLOW-ER-02 / MS-EH-005)
138
+ * when present, else vocabulary detection. */
139
+ export function phaseOf(s: ScenarioInfo, declared: string[]): string | null {
140
+ const id = (s.vpId ?? '').toUpperCase();
141
+ for (const ph of declared) {
142
+ if (new RegExp(`(^|-)${ph}(-|$)`).test(id)) return ph;
143
+ }
144
+ const hay = s.haystack;
145
+ if (declared.includes('EH') && /\b(direct access|without (a |the )?(submit|login)|browser back|refresh|expired|tamper|unauthoriz|redirect(ed)? (back )?to|guard)\b/.test(hay)) return 'EH';
146
+ if (declared.includes('ER') && /\b(invalid|error|required|validation|malformed|blocked|then correct|recover)\b/.test(hay)) return 'ER';
147
+ if (declared.includes('HP') && s.hasDataAssertion) return 'HP';
148
+ return null;
149
+ }
150
+
151
+ /**
152
+ * Verify the suite against the contract. Deterministic; a flow without a contract
153
+ * returns hasContract:false and neutral values (the audit reports the checklist).
154
+ */
155
+ export function flowQuality(unitDir: string, scenarios: ScenarioInfo[]): FlowQualityResult {
156
+ const { contract, errors } = loadFlowContract(unitDir);
157
+ const neutral: FlowQualityResult = {
158
+ hasContract: false, errors, outcomeProven: false, outcomeManualOnly: false,
159
+ offGoal: [], offGoalRatio: 0, offGoalCategories: [],
160
+ phases: [], phaseRatio: 1, handoffs: { total: 0, asserted: 0, ratio: 1 }, sit: [],
161
+ };
162
+ if (!contract) return neutral;
163
+
164
+ const outcomeScreen = contract.outcome.screen;
165
+
166
+ // --- Outcome proof: the flow proves its own goal, by automation -------------
167
+ const proofs = scenarios.filter((s) => touchesOutcome(s, outcomeScreen) && s.hasDataAssertion);
168
+ const outcomeProven = proofs.some((s) => !s.manual);
169
+ const outcomeManualOnly = !outcomeProven && proofs.length > 0;
170
+
171
+ // --- Scope creep: a scenario that never touches the outcome and is not a ----
172
+ // guard/error phase is evidence of a SECOND business goal in this flow.
173
+ const declaredPhases = contract.phases;
174
+ const offGoalScenarios = scenarios.filter((s) => {
175
+ if (touchesOutcome(s, outcomeScreen)) return false;
176
+ const ph = phaseOf(s, declaredPhases);
177
+ return ph !== 'EH' && ph !== 'ER'; // guards/error-recovery legitimately stop early
178
+ });
179
+ const offGoalRatio = scenarios.length ? offGoalScenarios.length / scenarios.length : 0;
180
+ const offGoalCategories = Array.from(new Set(
181
+ offGoalScenarios.map((s) => s.category ?? s.vpId?.replace(/-\d+.*$/, '') ?? '?')));
182
+
183
+ // --- Phase coverage: the flow's coverage axis (UI never demanded) -----------
184
+ const demanded = declaredPhases.filter((p) => p !== 'UI');
185
+ const phases = demanded.map((phase) => {
186
+ const inPhase = scenarios.filter((s) => phaseOf(s, declaredPhases) === phase);
187
+ // HP must additionally prove the outcome — a data assertion elsewhere is not the goal.
188
+ const relevant = phase === 'HP' ? inPhase.filter((s) => touchesOutcome(s, outcomeScreen)) : inPhase;
189
+ return {
190
+ phase,
191
+ covered: relevant.length > 0,
192
+ automated: relevant.some((s) => !s.manual),
193
+ };
194
+ });
195
+ const phaseRatio = demanded.length
196
+ ? phases.filter((p) => p.covered && p.automated).length / demanded.length
197
+ : 1;
198
+
199
+ // --- Handoff integrity: no blind tail after a cross-namespace transition. ---
200
+ // A transition counts as asserted when ANY assertion follows it — in the entered
201
+ // namespace or later. Demanding the assertion in the entered namespace itself
202
+ // flagged two legitimate shapes: a guard that asserts the REDIRECT target
203
+ // ("go to [Checkout] → see [Home] page"), and a passthrough click en route
204
+ // ("click [Cart:Checkout]" asserting on the next screen). What the sensor
205
+ // actually guards against is a flow that clicks through screens and ends blind.
206
+ let total = 0; let asserted = 0;
207
+ for (const s of scenarios) {
208
+ if (s.manual) continue;
209
+ const steps = s.steps ?? [];
210
+ let current: string | null = null;
211
+ for (let i = 0; i < steps.length; i++) {
212
+ const ns = (steps[i].text.match(/\[([A-Za-z0-9_.-]+):/) || [])[1]?.toLowerCase() ?? null;
213
+ if (!ns) continue;
214
+ if (current !== null && ns !== current) {
215
+ total++;
216
+ if (steps.slice(i).some((st) => st.bucket === 'then')) asserted++;
217
+ }
218
+ current = ns;
219
+ }
220
+ }
221
+ const handoffs = { total, asserted, ratio: total ? asserted / total : 1 };
222
+
223
+ // --- SIT classification (#580 P10): a scenario whose steps touch an external-system
224
+ // namespace belongs to the System INTEGRATION group the QA matrix keeps separate. When
225
+ // that scenario is also verified only against mocks, its pass says nothing about the
226
+ // real vendor behaviour — the exit criteria the QA doc holds open (Pass (Mocked)).
227
+ const MOCK_STEP = /\[[^\]]+\]\s+mock\s+(?:is\s+active|called)\b/i;
228
+ const sit: FlowQualityResult['sit'] = [];
229
+ for (const leg of contract.external ?? []) {
230
+ const legScreens = new Set(leg.screens);
231
+ for (const s of scenarios) {
232
+ if (!namespacesInOrder(s).some((ns) => legScreens.has(ns))) continue;
233
+ sit.push({ name: s.name.slice(0, 80), external: leg.name, mockOnly: MOCK_STEP.test(s.stepsText) });
234
+ }
235
+ }
236
+
237
+ return {
238
+ hasContract: true, contract, errors: [],
239
+ outcomeProven, outcomeManualOnly,
240
+ offGoal: offGoalScenarios.map((s) => s.name.slice(0, 80)),
241
+ offGoalRatio, offGoalCategories,
242
+ phases, phaseRatio, handoffs, sit,
243
+ };
244
+ }
245
+
246
+ /**
247
+ * Generalized stateful regression depth: the contract names the mutated collection,
248
+ * so the three dims (count-proof · teardown · multi-source) stop being cart-only.
249
+ */
250
+ export function statefulDepthFor(collection: string, scenarios: ScenarioInfo[]): { countProof: boolean; teardown: boolean; multiSource: boolean; missing: string[]; ratio: number } {
251
+ const hay = scenarios.map((s) => s.haystack);
252
+ const any = (re: RegExp) => hay.some((h) => re.test(h));
253
+ const noun = collection.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
254
+ const countProof = any(new RegExp(`\\b(quantity|qty|row count|count|number of|two (rows|lines|items)|\\d+ (rows|lines|items))\\b`)) ;
255
+ const teardown = any(/\b(remove|delete|clear|cancel|withdraw)(?:s|d|ed|ing|n)?\b/) && any(new RegExp(`\\b(empty|emptied|no items|zero|removed|cleared|cancelled|withdrawn|0 items)\\b|empty[- ]${noun}`));
256
+ const adds = hay.filter((h) => new RegExp(`\\b(add|submit|create|place).{0,40}${noun}|${noun}.{0,40}\\b(add|submit|create|place)`).test(h));
257
+ const multiSource = any(/\b(recommended|related|you may also|another source|both sources|second (list|source))\b/) && adds.length > 0;
258
+ const dims: Array<[string, boolean]> = [['count-proof', countProof], ['teardown', teardown], ['multi-source', multiSource]];
259
+ const missing = dims.filter(([, v]) => !v).map(([k]) => k);
260
+ return { countProof, teardown, multiSource, missing, ratio: (dims.length - missing.length) / dims.length };
261
+ }
@@ -71,6 +71,9 @@ export interface FlowPlan {
71
71
  legs: LegPlan[];
72
72
  byReason: Record<string, number>;
73
73
  capabilityManual: number;
74
+ /** @manual whose reason is "cross-screen → automate via flow" (class XS) — inside a flow this
75
+ * usually means the scenario should simply BE automated here. (#569) */
76
+ crossScreenManual: number;
74
77
  judgmentManual: number;
75
78
  contracts: Contract[];
76
79
  readiness: 'ready' | 'not-ready';
@@ -87,14 +90,18 @@ export function buildFlowPlan(cwd: string, flow: string): FlowPlan {
87
90
  // Legs = distinct screen namespaces.
88
91
  const legMap = new Map<string, { scenarios: Set<string>; refs: Set<string>; automated: boolean }>();
89
92
  const byReason: Record<string, number> = {};
90
- let capabilityManual = 0, judgmentManual = 0;
93
+ let capabilityManual = 0, judgmentManual = 0, crossScreenManual = 0;
91
94
 
92
95
  for (const sc of scenarios) {
93
96
  if (sc.manual) {
94
97
  const { code } = inferReasonCode(sc.tags, sc.reason);
95
98
  byReason[code] = (byReason[code] || 0) + 1;
96
99
  const cls = MANUAL_REASONS[code]?.cls;
97
- if (cls === 'capability') capabilityManual++; else if (cls === 'keep') judgmentManual++;
100
+ // XS ("cross-screen automate via flow") is a THIRD class; it used to be silently
101
+ // dropped from both counters, understating the plan's manual load. (#569)
102
+ if (cls === 'capability') capabilityManual++;
103
+ else if (cls === 'keep') judgmentManual++;
104
+ else if (cls === 'flow') crossScreenManual++;
98
105
  }
99
106
  for (const r of sc.refs) {
100
107
  const leg = r.screen.toLowerCase();
@@ -133,5 +140,5 @@ export function buildFlowPlan(cwd: string, flow: string): FlowPlan {
133
140
  }
134
141
  if (readiness === 'ready') plan.unshift('Selectors present for every automated leg — ready to compile + run.');
135
142
 
136
- return { flow, total: scenarios.length, legs, byReason, capabilityManual, judgmentManual, contracts, readiness, missingLegs, plan };
143
+ return { flow, total: scenarios.length, legs, byReason, capabilityManual, judgmentManual, crossScreenManual, contracts, readiness, missingLegs, plan };
137
144
  }
@@ -38,6 +38,8 @@ export interface ScenarioInfo {
38
38
  requiresCaps?: string[]; // @requires:<cap> — automation-ready but needs an opt-in driver (TQ-11)
39
39
  deferredToFlow?: boolean; // @deferred:flow — owned by a flow, not automated on this screen (H6)
40
40
  ownedByFlow?: string; // @owned-by:<flow> — the flow that owns this deferred scenario (H6)
41
+ /** Ordered steps with their resolved bucket (And/But inherit) — flow handoff analysis (#569). */
42
+ steps?: Array<{ bucket: 'given' | 'when' | 'then'; text: string }>;
41
43
  }
42
44
 
43
45
  /** Format-tolerant: is this token an ID (project's scheme), not a prose word?
@@ -91,6 +93,29 @@ export function parseViewpointOverview(filePath: string): ViewpointEntry[] {
91
93
  }
92
94
  }
93
95
 
96
+ // 1b) Flow-style declarations (#569). Flow viewpoint files commonly declare per-item
97
+ // ids at the END of a bullet ("… → **FL-HP-001**") under phase section headers
98
+ // ("## FL-HP — Happy Path"). Neither matched the table/group passes, so every flow
99
+ // audit collapsed to taxonomy=0% / traceability n-a — scenarios correctly tagged
100
+ // FL-HP-001 were reported as unmapped. Both forms are additive here.
101
+ for (const raw of lines) {
102
+ const line = raw.trim();
103
+ const section = line.match(/^##\s+([A-Z]{2,}(?:-[A-Z0-9]{2,})*)\s+[—–-]\s*(.*)$/);
104
+ if (section && isViewpointId(section[1] + '-0')) {
105
+ const id = section[1].toUpperCase();
106
+ if (!entries.has(id)) entries.set(id, { id, priority: 'Unknown', reason: section[2] ?? '' });
107
+ }
108
+ if (/^[-*+]\s/.test(line)) {
109
+ const arrow = line.match(/(?:→|->)\s*\*{0,2}([A-Z][A-Z0-9]*(?:-[A-Z0-9]+)*-\d+[a-zA-Z]?)\*{0,2}\s*$/);
110
+ if (arrow) {
111
+ const id = arrow[1].toUpperCase();
112
+ if (!entries.has(id)) {
113
+ entries.set(id, { id, priority: 'Unknown', reason: line.replace(/\s*(?:→|->).*$/, '').replace(/^[-*+]\s+/, '') });
114
+ }
115
+ }
116
+ }
117
+ }
118
+
94
119
  // 2) Viewpoint Grouping: ### Required / ### Recommended / ### Optional → bullet list
95
120
  let group: ViewpointEntry['group'] | undefined;
96
121
  for (const raw of lines) {
@@ -144,7 +169,9 @@ function classifyScenario(sc: ParsedScenario): ScenarioInfo {
144
169
  // Category is everything between `VP-` and the final `-<sequence>` — INCLUDING hyphens, so
145
170
  // compound categories (VP-LIST-DISPLAY-01, VP-ADD-TO-CART-03, VP-PRODUCT-DISCOVERY-02) parse,
146
171
  // not just single-word ones. A single-word category (VP-CART-001) still works. (H1)
147
- const codeMatch = sc.name.match(/\bVP-([A-Z]+(?:-[A-Z]+)*)-\d+/i);
172
+ // Flows use journey-phase ids (FL-HP-001 / FL-ER-002) — the VP- anchor rejected them, so every
173
+ // flow scenario had NO category and the whole suite bucketed `other` (taxonomy=0%, #569).
174
+ const codeMatch = sc.name.match(/\b(?:VP|FL)-([A-Z]+(?:-[A-Z]+)*)-\d+/i);
148
175
  const vpCode = codeMatch ? codeMatch[0].toUpperCase() : undefined;
149
176
  const category = codeMatch ? codeMatch[1].toUpperCase() : undefined;
150
177
  // Project-scheme ID: the leading token of the title (VP0-001 / MS-HP-001 / VP-LIST-001).
@@ -158,12 +185,14 @@ function classifyScenario(sc: ParsedScenario): ScenarioInfo {
158
185
  const skeletonParts: string[] = [];
159
186
  const textParts: string[] = [sc.name];
160
187
  const stepTextParts: string[] = [];
188
+ const orderedSteps: Array<{ bucket: 'given' | 'when' | 'then'; text: string }> = [];
161
189
 
162
190
  for (const step of sc.steps as ParsedStep[]) {
163
191
  const kw = step.keyword.trim();
164
192
  if (kw === 'Given' || kw === 'When' || kw === 'Then') last = kw;
165
193
  textParts.push(step.text);
166
194
  stepTextParts.push(step.text);
195
+ orderedSteps.push({ bucket: (kw === 'And' || kw === 'But' ? last : kw).toLowerCase() as 'given' | 'when' | 'then', text: step.text });
167
196
  // normalized skeleton: keep [refs] (distinct targets = distinct tests),
168
197
  // but neutralize {{vars}} and quoted values so EP/data families collapse.
169
198
  const skel = step.text
@@ -199,6 +228,7 @@ function classifyScenario(sc: ParsedScenario): ScenarioInfo {
199
228
  stepSkeleton: skeletonParts.join(' | '),
200
229
  haystack: textParts.join(' ').toLowerCase(),
201
230
  stepsText: stepTextParts.join(' ').toLowerCase(),
231
+ steps: orderedSteps,
202
232
  vpId,
203
233
  casesDataset,
204
234
  queryRefs: queryRefs.size ? [...queryRefs] : undefined,