@sun-asterisk/sungen 3.2.12-beta.1 → 3.2.12-beta.10

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 (29) hide show
  1. package/dist/dashboard/templates/index.html +1 -1
  2. package/dist/exporters/csv-exporter.d.ts.map +1 -1
  3. package/dist/exporters/csv-exporter.js +7 -2
  4. package/dist/exporters/csv-exporter.js.map +1 -1
  5. package/dist/exporters/feature-parser.d.ts.map +1 -1
  6. package/dist/exporters/feature-parser.js +15 -2
  7. package/dist/exporters/feature-parser.js.map +1 -1
  8. package/dist/exporters/json-exporter.d.ts.map +1 -1
  9. package/dist/exporters/json-exporter.js +10 -5
  10. package/dist/exporters/json-exporter.js.map +1 -1
  11. package/dist/exporters/result-variants.d.ts +23 -5
  12. package/dist/exporters/result-variants.d.ts.map +1 -1
  13. package/dist/exporters/result-variants.js +65 -9
  14. package/dist/exporters/result-variants.js.map +1 -1
  15. package/dist/exporters/test-data-resolver.d.ts.map +1 -1
  16. package/dist/exporters/test-data-resolver.js.map +1 -1
  17. package/dist/orchestrator/templates/ai-src/commands/create-data-test.md +13 -1
  18. package/dist/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  19. package/dist/orchestrator/templates/ai-src/skills/sungen-data-factory/SKILL.md +105 -8
  20. package/package.json +3 -3
  21. package/src/dashboard/templates/index.html +1 -1
  22. package/src/exporters/csv-exporter.ts +7 -3
  23. package/src/exporters/feature-parser.ts +15 -2
  24. package/src/exporters/json-exporter.ts +10 -6
  25. package/src/exporters/result-variants.ts +68 -9
  26. package/src/exporters/test-data-resolver.ts +1 -0
  27. package/src/orchestrator/templates/ai-src/commands/create-data-test.md +13 -1
  28. package/src/orchestrator/templates/ai-src/commands/create-test.md +2 -2
  29. package/src/orchestrator/templates/ai-src/skills/sungen-data-factory/SKILL.md +105 -8
@@ -25,7 +25,7 @@ import {
25
25
  import { ApiCatalogEntry, EnvironmentInfo, PlaywrightResult, ScreenSummary, TestCaseRow } from './types';
26
26
  import { collectSecretValues, formatApiExpected, formatApiRequest, hasApiCalls, redactSecrets } from './api-testcase-formatter';
27
27
  import { SelectorKeyMap, substituteSelectorKeysInStep } from './selector-key-resolver';
28
- import { resolveResultVariants } from './result-variants';
28
+ import { formatVariantRow, resolveResultVariants } from './result-variants';
29
29
 
30
30
  export interface BuildCsvInput {
31
31
  screen: string;
@@ -70,7 +70,7 @@ export function buildTestCaseRows(input: BuildCsvInput): TestCaseRow[] {
70
70
  // Data-driven (@cases): expand to one CSV row per executed dataset input (Playwright titles
71
71
  // "<scenario> — <label>"); plain scenarios resolve their single result. Shared with the
72
72
  // dashboard/JSON exporter via resolveResultVariants so the two can't drift on @cases handling.
73
- const variants = resolveResultVariants(m, input.results);
73
+ const variants = resolveResultVariants(m, input.results, input.testData);
74
74
 
75
75
  for (const variant of variants) {
76
76
  const displayName = `${m.feature.name}${variant.nameSuffix}`;
@@ -132,7 +132,11 @@ export function buildTestCaseRows(input: BuildCsvInput): TestCaseRow[] {
132
132
  // Multi-line bullet format keeps delivery CSV/XLSX in sync with the
133
133
  // dashboard's Test data section. Multi-line CSV cells are valid (quoted
134
134
  // automatically) and render natively as multi-line in XLSX.
135
- const testData = formatTestData(m.feature.referencedVars, input.testData, Infinity, '\n');
135
+ let testData = formatTestData(m.feature.referencedVars, input.testData, Infinity, '\n');
136
+ // @cases: each report line shows ITS OWN dataset row (executed auto rows and manual
137
+ // split rows both carry variant.row) — one line per case, one dataset per line.
138
+ const variantRow = formatVariantRow(variant, '\n');
139
+ if (variantRow) testData = testData ? `${testData}\n${variantRow}` : variantRow;
136
140
 
137
141
  // Status for this (possibly per-input) row — resolved into `variant` above.
138
142
  const result: PlaywrightResult | undefined = variant.result;
@@ -9,7 +9,7 @@ import { FeatureMetadata, OrderedStep, ScenarioMetadata } from './types';
9
9
  /**
10
10
  * Variables referenced in a scenario: find all {{var_name}} in step text.
11
11
  */
12
- function extractReferencedVars(scenario: ParsedScenario): string[] {
12
+ function extractReferencedVars(scenario: ParsedScenario, includeComments = false): string[] {
13
13
  const vars = new Set<string>();
14
14
  for (const step of scenario.steps) {
15
15
  const matches = step.text.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_.-]*)\}\}/g);
@@ -28,6 +28,19 @@ function extractReferencedVars(scenario: ParsedScenario): string[] {
28
28
  }
29
29
  }
30
30
  }
31
+ // Manual scenarios carry their real tester procedure in `# Tester verifies:` comment
32
+ // blocks — the {{var}} refs there are the data the tester needs, so include them
33
+ // (issue: manual test cases exported with an empty Test Data cell). Automated
34
+ // scenarios keep step-only scanning: their comments are notes (SPEC-GAP etc.) and
35
+ // would only add noise vars to the delivery report.
36
+ if (includeComments) {
37
+ for (const line of scenario.comments ?? []) {
38
+ const matches = line.matchAll(/\{\{([a-zA-Z_][a-zA-Z0-9_.-]*)\}\}/g);
39
+ for (const match of matches) {
40
+ vars.add(match[1]);
41
+ }
42
+ }
43
+ }
31
44
  return Array.from(vars);
32
45
  }
33
46
 
@@ -85,7 +98,7 @@ export function parseFeatureMetadata(featureFilePath: string): FeatureMetadata {
85
98
  tags: [...parsed.tags, ...sc.tags],
86
99
  stepsName: sc.stepsName,
87
100
  extendsName: sc.extendsName,
88
- referencedVars: extractReferencedVars(sc),
101
+ referencedVars: extractReferencedVars(sc, extractTestcaseType([...parsed.tags, ...sc.tags]) === 'Manual'),
89
102
  rawGivenSteps: given,
90
103
  rawWhenSteps: when,
91
104
  rawThenSteps: then,
@@ -23,7 +23,7 @@ import {
23
23
  } from './playwright-report-parser';
24
24
  import { ApiCatalogEntry, EnvironmentInfo, PlaywrightResult } from './types';
25
25
  import { SelectorKeyMap, substituteSelectorKeysInStep } from './selector-key-resolver';
26
- import { resolveResultVariants } from './result-variants';
26
+ import { formatVariantRow, resolveResultVariants } from './result-variants';
27
27
  import {
28
28
  ScenarioSnapshot,
29
29
  ScreenSnapshot,
@@ -123,13 +123,17 @@ export function buildScreenSnapshot(input: BuildScreenSnapshotInput): ScreenSnap
123
123
  }
124
124
  // Dashboard modal uses whitespace-pre-wrap — pass '\n' to render one
125
125
  // key/value per line instead of the CSV-friendly "; " join.
126
- const testDataStr = formatTestData(m.feature.referencedVars, input.testData, Infinity, '\n');
126
+ const baseTestDataStr = formatTestData(m.feature.referencedVars, input.testData, Infinity, '\n');
127
127
 
128
- // @cases scenarios expand to one snapshot entry per executed dataset row (shared with the CSV
129
- // exporter via resolveResultVariants), so their per-row pass/fail is counted not collapsed
130
- // into one Pending/N/A entry as before.
131
- const variants = resolveResultVariants(m, input.results ?? null);
128
+ // @cases scenarios expand to one snapshot entry per executed dataset row and manual
129
+ // @cases split per DATASET row (shared with the CSV exporter via resolveResultVariants),
130
+ // so their per-row pass/fail is counted — not collapsed into one Pending/N/A entry.
131
+ const variants = resolveResultVariants(m, input.results ?? null, input.testData);
132
132
  for (const variant of variants) {
133
+ // Per-line Test Data: shared vars + THIS variant's dataset row (parity with csv-exporter).
134
+ let testDataStr = baseTestDataStr;
135
+ const variantRow = formatVariantRow(variant, '\n');
136
+ if (variantRow) testDataStr = testDataStr ? `${testDataStr}\n${variantRow}` : variantRow;
133
137
  const displayName = `${m.feature.name}${variant.nameSuffix}`;
134
138
  const { vpId, category1 } = splitVpAndName(displayName);
135
139
  const tcId = generateTcId(input.screen, vpId, fallbackIndex);
@@ -5,12 +5,42 @@
5
5
  */
6
6
  import { MergedScenario } from './scenario-merger';
7
7
  import { PlaywrightResult } from './types';
8
+ import { extractTestcaseType } from './feature-parser';
8
9
 
9
10
  export interface ResultVariant {
10
- /** Appended to the scenario display name: `''` for a plain scenario, ` — <label>` per executed
11
+ /** Appended to the scenario display name: `''` for a plain scenario, ` — <label>` per
11
12
  * @cases dataset row (so each row gets a distinct category1). */
12
13
  nameSuffix: string;
13
14
  result?: PlaywrightResult;
15
+ /** The @cases dataset row backing this variant — lets the exporters render the row's own
16
+ * columns into the Test Data cell (`__`-prefixed bookkeeping keys excluded). Present on
17
+ * executed auto rows (matched by label) and on manual split rows. */
18
+ row?: Record<string, unknown>;
19
+ }
20
+
21
+ /**
22
+ * Read the `@cases:<name>` dataset rows for a scenario from the (flattened) test-data map.
23
+ * `loadTestData()` flattens arrays to JSON strings — accept that shape and raw arrays.
24
+ * Scalar rows normalize to `{ value }`, mirroring the runtime TestDataLoader.cases().
25
+ */
26
+ export function getCasesDatasetRows(
27
+ m: MergedScenario,
28
+ testData: Record<string, string> | null | undefined,
29
+ ): Array<Record<string, unknown>> | null {
30
+ const tag = m.feature.tags.find((t) => t.startsWith('@cases:'));
31
+ if (!tag || !testData) return null;
32
+ let list: unknown = testData[tag.slice('@cases:'.length)];
33
+ if (typeof list === 'string') {
34
+ try { list = JSON.parse(list); } catch { return null; }
35
+ }
36
+ if (!Array.isArray(list) || list.length === 0) return null;
37
+ return list.map((row) =>
38
+ row && typeof row === 'object' && !Array.isArray(row) ? (row as Record<string, unknown>) : { value: row });
39
+ }
40
+
41
+ /** Display label of a dataset row — mirrors the runtime TestDataLoader.cases() rule. */
42
+ function rowLabel(row: Record<string, unknown>, i: number): string {
43
+ return String(row.case ?? row.name ?? row.label ?? `row ${i + 1}`);
14
44
  }
15
45
 
16
46
  /**
@@ -18,9 +48,12 @@ export interface ResultVariant {
18
48
  *
19
49
  * A `@cases:<dataset>` scenario compiles to one `test()` per dataset row, whose Playwright title is
20
50
  * `<scenario> — <label>` — expand into one variant per EXECUTED row by matching that prefix (so an
21
- * already-run row carries its real pass/fail). A plain scenario resolves its single result by the
22
- * spec test title. With no results — or a @cases scenario with no matching result yet — a lone
23
- * variant with no result is returned, so the caller marks it Pending / N/A.
51
+ * already-run row carries its real pass/fail), attaching the backing dataset row by label.
52
+ *
53
+ * A MANUAL `@cases` scenario never executes, so that expansion can never fire — split it from the
54
+ * DATASET instead: one variant per row (` — <label>`, no result → Pending), each carrying its row
55
+ * so the manual tester gets one report line + its own data per case to walk and record. An auto
56
+ * @cases scenario that has not run yet stays a single line (its expansion belongs to execution).
24
57
  *
25
58
  * NOTE: this deliberately does NOT gate on `m.spec`. For @cases the compiled test title carries a
26
59
  * `— ${__row.__label}` suffix, so `findMatchingSpecTest` (base-name match) often leaves `m.spec`
@@ -30,13 +63,26 @@ export interface ResultVariant {
30
63
  export function resolveResultVariants(
31
64
  m: MergedScenario,
32
65
  results: Map<string, PlaywrightResult> | null,
66
+ testData?: Record<string, string> | null,
33
67
  ): ResultVariant[] {
34
68
  const isCases = m.feature.tags.some((t) => t.startsWith('@cases:'));
35
- if (isCases && results) {
36
- const marker = `${m.feature.name} — `;
37
- const rows = [...results.entries()].filter(([t]) => t.includes(marker));
38
- if (rows.length) {
39
- return rows.map(([t, r]) => ({ nameSuffix: ` — ${t.slice(t.indexOf(marker) + marker.length)}`, result: r }));
69
+ if (isCases) {
70
+ const datasetRows = getCasesDatasetRows(m, testData);
71
+ const byLabel = new Map<string, Record<string, unknown>>();
72
+ (datasetRows ?? []).forEach((row, i) => byLabel.set(rowLabel(row, i), row));
73
+
74
+ if (results) {
75
+ const marker = `${m.feature.name} — `;
76
+ const ran = [...results.entries()].filter(([t]) => t.includes(marker));
77
+ if (ran.length) {
78
+ return ran.map(([t, r]) => {
79
+ const label = t.slice(t.indexOf(marker) + marker.length);
80
+ return { nameSuffix: ` — ${label}`, result: r, row: byLabel.get(label) };
81
+ });
82
+ }
83
+ }
84
+ if (datasetRows && extractTestcaseType(m.feature.tags) === 'Manual') {
85
+ return datasetRows.map((row, i) => ({ nameSuffix: ` — ${rowLabel(row, i)}`, row }));
40
86
  }
41
87
  return [{ nameSuffix: '' }];
42
88
  }
@@ -45,3 +91,16 @@ export function resolveResultVariants(
45
91
  }
46
92
  return [{ nameSuffix: '' }];
47
93
  }
94
+
95
+ /**
96
+ * Render a variant's dataset row for the Test Data cell: one `col: value` line per column,
97
+ * `__`-prefixed bookkeeping keys excluded. Returns '' when the variant carries no row.
98
+ */
99
+ export function formatVariantRow(variant: ResultVariant, separator: string = '\n'): string {
100
+ if (!variant.row) return '';
101
+ const useBullet = separator.includes('\n');
102
+ return Object.entries(variant.row)
103
+ .filter(([k]) => !k.startsWith('__'))
104
+ .map(([k, v]) => `${useBullet ? '• ' : ''}${k}: ${v}`)
105
+ .join(separator);
106
+ }
@@ -133,6 +133,7 @@ function truncate(s: string, max: number): string {
133
133
  return s.substring(0, max - 1) + '…';
134
134
  }
135
135
 
136
+
136
137
  /**
137
138
  * Resolve `{{var}}` test-data placeholders in a step / expected-result line to their concrete values,
138
139
  * so the delivery report shows what QA actually verifies (e.g. `text contains {{app_version}}` →
@@ -90,9 +90,21 @@ Run (local-first): `[ -x ./bin/sungen.js ] && ./bin/sungen.js data lint --screen
90
90
 
91
91
  Run (local-first): `[ -x ./bin/sungen.js ] && ./bin/sungen.js data gen --screen <name> || npx sungen data gen --screen <name>`. If `test-data/<name>.yaml` already exists it **merges** the standardized field data in — it **replaces only the field keys it owns and preserves every other key** (create-test's data, flow-namespaced keys, `@cases` datasets, overrides). It asks before merging (in ALL mode after they confirmed, add `--yes`; `--force` skips the prompt). The output is standardized `valid/boundary/invalid` values with `CHK-*` traceability.
92
92
 
93
+ ### 5.5 Validate semantic correctness
94
+
95
+ Run (local-first): `[ -x ./bin/sungen.js ] && ./bin/sungen.js data validate --screen <name> || npx sungen data validate --screen <name>`. This is stronger than lint (coverage): it checks every generated value is **semantically** correct — each `valid`/`boundary` value actually satisfies the constraints, and each synthesized `invalid` value actually violates them (a value in the `valid` set that breaks `maxLength`, or a "below min" case that landed inside the range, is a `VALUE_NOT_VALID` error). Fix any `error`; `INVALID_LOOKS_VALID` warns are a prompt to confirm the value is invalid for a non-length reason (charset/format). Each generated value also carries an `expected: valid|invalid` field in the test-data for traceability.
96
+
97
+ ### 5.6 Domain / stateful preconditions (spec + viewpoint only — no DB/API needed)
98
+
99
+ If the spec describes a **stateful precondition** — an entity with relationships or a business state the test needs *before* it runs (e.g. "a paid order of user A", "a valid unused reset token ≤24h", "the session-storage buffer holds the entered values") — **auto-draft it: run `… data state --scaffold <name>`** to generate a recipe skeleton from the spec's precondition sentences (one resource per signal, provenance guessed, entity as `TODO`). Then **fill each `entity`/`desiredState`/`bindings` and confirm the domain specifics with the QA** (`AskUserQuestion`) — never invent domain values. (You can also hand-author the `resources:` graph in `qa/data-factory/recipes.yaml`.) Provenance is **not only api/db** — pick `prior-flow` / `fixture` / `client-storage` / `server-context` / `manual` (use `api`/`db` only when a datasource exists). Then run `data state --recipe <name>`: it validates the graph and renders a standardized **manual precondition** block (`@manual:data-setup` when it can't be auto-provisioned) to weave into the scenario's `Background`. This is the domain/stateful improvement that works with **only spec + viewpoint** — the testcase states the required state precisely instead of a vague note; it auto-provisions later if an api/db datasource is added (no rewrite). For a **journey where the same data flows across screens** (setup → confirmation → complete), declare a `shared: { entity, screens: [...] }` so one dataset is used across all of them (the Cross-artifact Gate then asserts they match).
100
+
101
+ ### 5.7 Cross-artifact check (testcase ↔ data agree)
102
+
103
+ Run (local-first): `… data crosscheck --screen <name>`. It verifies the testcase and its test-data agree: no dangling `{{var}}` (every referenced var has a value), any cross-screen **shared** dataset is identical across the journey, and a declared state-precondition is surfaced in the feature. Fix any `error`. This is the `data-only` harness profile — `data validate` (values correct) + `data crosscheck` (values match the test); together they are the deterministic Data Gate + Cross-artifact Gate.
104
+
93
105
  ### 6. Weave into scenarios (if create-test already ran)
94
106
 
95
- If the `.feature` exists, turn the generated invalid/boundary sets into data-driven `Scenario Outline` + `Examples` (`@cases`) referencing the values — following `sungen-gherkin-syntax`. Otherwise leave the standardized `test-data/<name>.yaml` for `/sungen:run-test` to consume.
107
+ If the `.feature` exists, turn the generated invalid/boundary sets into data-driven `Scenario Outline` + `Examples` (`@cases`) referencing the values — following `sungen-gherkin-syntax`. Weave any `data state` precondition block into the `Background`. Otherwise leave the standardized `test-data/<name>.yaml` for `/sungen:run-test` to consume.
96
108
 
97
109
  ## After running
98
110
 
@@ -167,7 +167,7 @@ If the unit is **api-first** (`qa/api/<name>/` or `qa/api/flows/<name>/`), the d
167
167
 
168
168
  **5d. Sequential fallback.** Use the single-context incremental path (Step 2: tier-by-tier `Write`/`Edit` batches) when: only **one** shard applies, **Copilot / no sub-agents**, or a constrained setup. Same output, just no speedup. **For flows**: `[Screen:Element]` namespace refs, test-data namespaced by phase, `@flow` tag.
169
169
 
170
- 5.3. **Standardize field test-data — Data Factory (when the unit has input fields).** Don't hand-invent per-field values — make them **standard**. For each input field, author the field-map `qa/data-factory/<name>.fields.yaml` (field → catalog `type` + the spec's real `constraints` + `errorMap` placeholder→real code), then run (Bash, local-first) `[ -x ./bin/sungen.js ] && ./bin/sungen.js data lint --screen <name> || npx sungen data lint --screen <name>` and `… data gen --screen <name>`, per the **`sungen-data-factory`** skill. `data gen` **MERGES** into `test-data.yaml` (replaces only its field keys, preserves your scenario/namespaced data), so it is safe to run here. Weave the standardized **boundary/invalid** sets into `@cases` (`Scenario Outline` + `Examples`) with `CHK-*` trace; keep the map's `errorMap`/`constraints` aligned to the spec. **This is the same standard as `/sungen:create-data-test`, applied inline — so you do NOT run that command separately afterwards.** A unit with **no input fields** (navigation / list / capture-compare) → **skip this step** (nothing to standardize).
170
+ 5.3. **Standardize field test-data — Data Factory (when the unit has input fields).** Don't hand-invent per-field values — make them **standard**. For each input field, author the field-map `qa/data-factory/<name>.fields.yaml` (field → catalog `type` + the spec's real `constraints` + `errorMap` placeholder→real code), then run (Bash, local-first) `[ -x ./bin/sungen.js ] && ./bin/sungen.js data lint --screen <name> || npx sungen data lint --screen <name>` and `… data gen --screen <name>`, per the **`sungen-data-factory`** skill. `data gen` **MERGES** into `test-data.yaml` (replaces only its field keys, preserves your scenario/namespaced data), so it is safe to run here. Weave the standardized **boundary/invalid** sets into `@cases` (`Scenario Outline` + `Examples`) with `CHK-*` trace; keep the map's `errorMap`/`constraints` aligned to the spec. Then run `… data validate --screen <name>` (values are semantically correct) and — once the `.feature` exists — `… data crosscheck --screen <name>` (testcase ↔ data agree: no dangling `{{var}}`, shared datasets identical); fix any `error`. If the spec has a **stateful precondition** (an entity/state the test needs first), run `… data state --scaffold <name>` to auto-draft a recipe skeleton from the spec, **fill each `entity`/`desiredState` + confirm domain values with the QA**, then `… data state` and weave its `@manual:data-setup` `Background` block (see the `sungen-data-factory` skill — works with spec+viewpoint only, no DB/API). **This is the same standard as `/sungen:create-data-test`, applied inline — so you do NOT run that command separately afterwards.** A unit with **no input fields** (navigation / list / capture-compare) → **skip this step** (nothing to standardize).
171
171
 
172
172
  5.4. **Depth self-check (deterministic — run BEFORE the audit).** Run `sungen depth-lint --screen <name>` (Bash). It reuses the audit's businessDepth classifier and splits every shallow business-critical scenario into two actionable buckets — act on them now so the audit/repair loop doesn't burn rounds on depth:
173
173
  - **DEEPEN IN PLACE** — add a real value assertion to each (`User see all [X] contain {{v}}`, `User remember [X] as {{v}}` + `… with {{v}}`). The printed `template` is a **hint** keyed off the theme — apply judgment to the scenario's actual claim; do NOT paste a value assertion that doesn't fit (e.g. a carousel-visibility scenario should assert the product SET, not a price). If a flagged scenario is genuinely visibility/behavior (not data-correctness), that's an over-count — leave it and note it, never fake an assertion.
@@ -196,7 +196,7 @@ If the unit is **api-first** (`qa/api/<name>/` or `qa/api/flows/<name>/`), the d
196
196
  4. Follow the `sungen-tc-generation` skill for section identification, viewpoint generation, and output format. **For flows**, use the "Flow Test Generation" section in the skill. When requirements exist, use the "Requirements-Driven Generation" strategy. **For Tier 1**, apply the **Lightweight Guard** — verify required fields, validation rules, business rules, security checks, and key state transitions all have TCs after generation. **For Tier 2+**, **MUST** apply the full **Mapping Contract** — walk every `spec.md` section top-to-bottom and produce the indicated TCs per Table 1; handle `test-viewpoint.md` per Table 2. Do not silently skip sections. Present sections as a numbered list and let user pick.
197
197
  5. Generate or update `.feature` + `test-data.yaml` following `sungen-gherkin-syntax` and `sungen-tc-generation` skills. Generate **group-by-group** (one viewpoint group at a time, tier-by-tier `Write`/`Edit` batches) to stay under the output-token cap. **For flows**: use `[Screen:Element]` namespace format, namespace test-data by phase, add `@flow` tag. **If a scenario needs `@query` DB verification**, check the datasource `engine` first — unsupported engine → follow `sungen-gherkin-syntax` § "Unsupported DB engine — fallback" instead of authoring `@query` steps.
198
198
  > **No parallel fan-out here.** Copilot has no sub-agents, so generation is sequential (the Claude Code variant fans out one `sungen-generator` per viewpoint group and merges). Same output, no speedup.
199
- 5.3. **Standardize field test-data — Data Factory (when the unit has input fields).** For each input field, author the field-map `qa/data-factory/<name>.fields.yaml` (field → catalog `type` + real `constraints` + `errorMap`), then run `sungen data lint --screen ${input:name}` and `sungen data gen --screen ${input:name}` per the **`sungen-data-factory`** skill. `data gen` **MERGES** into `test-data.yaml` (replaces only its field keys, preserves the rest), so it is safe here. Weave the standardized boundary/invalid sets into `@cases` with `CHK-*` trace. **Same standard as `/sungen:create-data-test`, applied inline — do NOT run that command separately afterwards.** No input fields (navigation/list) → skip.
199
+ 5.3. **Standardize field test-data — Data Factory (when the unit has input fields).** For each input field, author the field-map `qa/data-factory/<name>.fields.yaml` (field → catalog `type` + real `constraints` + `errorMap`), then run `sungen data lint --screen ${input:name}` and `sungen data gen --screen ${input:name}` per the **`sungen-data-factory`** skill. `data gen` **MERGES** into `test-data.yaml` (replaces only its field keys, preserves the rest), so it is safe here. Weave the standardized boundary/invalid sets into `@cases` with `CHK-*` trace. Then `… data validate` (values correct) + `… data crosscheck` (testcase↔data agree); for a stateful precondition, `… data state --scaffold <name>` to auto-draft → fill entities + confirm with QA → `… data state`, weave the `@manual:data-setup` `Background` (works spec+viewpoint only). **Same standard as `/sungen:create-data-test`, applied inline — do NOT run that command separately afterwards.** No input fields (navigation/list) → skip.
200
200
  5.4. **Depth self-check (deterministic — BEFORE the audit).** Run `sungen depth-lint --screen ${input:name}`. It splits every shallow business-critical scenario into **DEEPEN IN PLACE** (add a real value assertion — the printed `template` is a theme-keyed hint, apply judgment to the actual claim; never fake one onto a visibility/behavior scenario) and **CROSS-SCREEN** (route to a flow / tag `@manual:Mx` + reason — removes it from the depth denominator honestly). Act on both, re-run until `deepen` is empty (or only honest over-counts remain), THEN gate. Lifts first-pass `businessDepth` mechanically instead of via 2–3 repair rounds.
201
201
  5.5. **Quality gate & repair (harness — always run).** Per `sungen-harness-audit`: run `sungen audit --screen ${input:name}` (structural), THEN do an **independent semantic review inline** using the `sungen-reviewer` criteria (does each scenario's steps PROVE its title/viewpoint? observable Thens? business-critical assertion depth?). Merge both sets of issues; if gate FAILs / findings exist, repair (budget 3) and re-audit — GATE missing theme → generate it (cross-screen → **automate it in the flow** via `/sungen:add-flow`, NOT a full `@manual` screen duplicate — `sungen audit` flags an automatable `@manual` as `MANUAL-AUTOMATABLE`; reserve `@manual:Mx` for true judgment/missing-capability); DEPTH → add data assertions; BALANCE → add business-core first; TRACE → align VP ids. Never fake a pass.
202
202
  5.6. **Record.** `sungen manifest --screen ${input:name}`. Ledger **each phase** (not just repair) — pick one `runId` at the start and pass it so `trace`/`ledger report` show THIS run, not a mix: `sungen ledger record --screen ${input:name} --run <runId> --step <discovery|viewpoint|gherkin|audit|repair:N> --ms <elapsed>`. On re-run, start with `sungen manifest --screen ${input:name} --diff` and only regenerate changed sections.
@@ -15,6 +15,17 @@ Turn a screen/flow's fields into **standardized test data** — not guessed valu
15
15
  Data Factory is **bundled with core** (runtime-free) — no `capability add` needed; the `sungen data …`
16
16
  CLI is available out of the box.
17
17
 
18
+ **Auto-detection (act on these, don't wait to be asked).** `sungen generate`/`sungen audit` now NOTICE
19
+ the work a unit needs, even before any field-map exists:
20
+ - **`DATA-FACTORY-UNSTANDARDIZED`** — the unit has input fields but no `qa/data-factory/<name>.fields.yaml`.
21
+ → author the field-map + `data gen` (this skill's main job).
22
+ - **`DATA-FACTORY-PRECONDITION-UNDECLARED`** — the spec describes a stateful precondition (a required
23
+ entity/state) but the test declares none. → **auto-draft a state-recipe** from the spec sentence, run
24
+ `sungen data state`, and weave its `@manual:data-setup` `Background`; confirm the drafted values with
25
+ the QA (`AskUserQuestion`) — never invent domain values.
26
+ When you see either finding, do the work rather than leaving it — that is what makes Sungen self-driving
27
+ instead of a toolbox the QA must operate.
28
+
18
29
  ## The 4-source method (phuong-phap-tao-test-data.md)
19
30
 
20
31
  Never invent values from memory. Cross-reference four sources — each covers the previous one's gap:
@@ -85,20 +96,26 @@ This is the core discipline: *common is never enough; when blind, think and ask
85
96
  ## Customizing the catalog — `.overwrite` (survives `sungen update`)
86
97
 
87
98
  The shipped `common/` is a floor. Project rules go in `qa/data-factory/common.overwrite.yaml`,
88
- deep-merged over the common (**later-wins**, keyed by `type` + data-point `id`): same `id` replaces,
89
- new `id` appends, `constraints` merge key-by-key. `sungen update` refreshes `common/` but never
90
- touches your overlay. If an update makes an overlay entry stale (references a bank/constraint that no
91
- longer exists), the loader **warns you to prune it** it never edits your file. Prefer a targeted
92
- `errorMap`/`constraints` in the field-map for per-screen tweaks; use `.overwrite` only for rules that
93
- apply project-wide.
99
+ deep-merged over the common (**later-wins**, keyed by `type` + data-point `id`) via three explicit
100
+ operations: **EXTEND** (a new `id` appends), **REPLACE** (same `id` wins; `constraints` merge
101
+ key-by-key), **DISABLE** (list ids under `disable:` to drop shipped cases that don't apply a stale
102
+ target id warns). You can also override `security:` banks and `techniques:` the same way. `sungen
103
+ update` refreshes `common/` but never touches your overlay; a stale entry **warns you to prune it** —
104
+ it never edits your file. Nothing is silently overwritten: **`sungen data provenance`** (and a
105
+ `⟲ .overwrite →` line at `data gen`) shows exactly what your overlay changed, and each overlaid value
106
+ is tagged `via: .overwrite` in the test-data. Prefer a targeted `errorMap`/`constraints` in the
107
+ field-map for per-screen tweaks; use `.overwrite` only for rules that apply project-wide.
94
108
 
95
109
  ## Bulk-import fixtures (CSV)
96
110
 
97
111
  For CSV/Excel import or bulk-upload testing, `sungen data fixture --screen <name> [--rows N] [--invalid]`
98
112
  turns the field-map into a fixture FILE under `qa/fixtures/`: `<name>.csv` (N valid rows; nested groups
99
113
  → dotted headers; `unique` fields row-indexed) that should import cleanly, and — with `--invalid` —
100
- `<name>.invalid.csv` (one seeded-bad row per field + a `_violation` column) for row-level rejection
101
- tests. Reference it from an `@api` upload (`files:`) or a UI file input.
114
+ `<name>.invalid.csv` (one seeded-bad row per field, **same columns as the valid file so a strict
115
+ importer fails on the data, not an extra column**) plus a **sidecar** `<name>.invalid.expected.yaml`
116
+ that says which 0-based row must be rejected and why (`field`, `chk`, `reason`, `expected_error`).
117
+ Reference the CSV from an `@api` upload (`files:`) or a UI file input, and assert row rejection against
118
+ the sidecar.
102
119
 
103
120
  ## Verify before done — the phuong-phap §6 checklist
104
121
 
@@ -109,6 +126,86 @@ Then `sungen data gen` writes the standardized `test-data/<name>.yaml`. Do not h
109
126
  generated values — change the field-map or `.overwrite` and re-run (determinism: same input → same
110
127
  data).
111
128
 
129
+ Then run **`sungen data validate`** — the semantic check beyond coverage. It verifies each generated
130
+ value is *correct*, not just *present*: every `valid`/`boundary` value actually satisfies the
131
+ constraints and every synthesized `invalid` value actually violates them. A boundary is expanded to
132
+ **one case per point** (`min / min+1` → two cases; `< min` → min-1, below the minimum), each stamped
133
+ `expected: valid|invalid` in the output. Any `VALUE_NOT_VALID` error means a value labeled valid breaks
134
+ a constraint — fix the field-map/constraints and re-run. This is what stops the "structurally right but
135
+ semantically wrong" data (e.g. a "below minimum length" case that is actually long enough to pass).
136
+
137
+ **Applicability & profiles.** The generator only emits cases that apply, and reports the rest (never
138
+ silent). Set **`required: true|false`** correctly — an optional field drops the "empty (required)" case;
139
+ a numeric field with `min ≥ 0` drops the negative example. Security/injection payloads land in their own
140
+ **`adversarial:`** bucket, separate from `invalid:`. Dropped cases show up as `_not_applicable` in the
141
+ output + a `NOT_APPLICABLE` lint info. A `--profile` (`regression` default · `functional` · `smoke` ·
142
+ `security-min`) and `--locale`/`--channel`/`--sink` on `data gen|validate|lint` select a reduced set;
143
+ selection is deterministic. Prefer setting `required` in the field-map over disabling the empty case.
144
+
145
+ ## Domain / stateful preconditions (spec + viewpoint only — no DB/API)
146
+
147
+ Field values are not enough when a test needs a **business state first** — "a paid order of user A",
148
+ "a valid unused reset token ≤24h", "the session-storage buffer holds the entered values". Declare a
149
+ **state-recipe** in `qa/data-factory/recipes.yaml` under `resources:` — each resource has an `entity`,
150
+ a **`provenance`** (`prior-flow` | `fixture` | `client-storage` | `server-context` | `manual` |
151
+ `api` | `db`), optional `dependsOn`, `desiredState`, `lifecycle` (`reusable`/`consumable`/`expiring`/
152
+ `leased`/`mutable-state`/`unique-per-run`), and `with:` values — plus `bindings:` (`orderId: ${order.id}`).
153
+ **Auto-draft it — don't make the QA hand-write it.** When the spec describes a precondition (or you saw
154
+ a `PRECONDITION-UNDECLARED` finding), run **`sungen data state --scaffold <unit>`**: it drafts a recipe
155
+ skeleton from the spec's precondition sentences (one resource per signal, provenance guessed, entity
156
+ left as `TODO`). Then **fill each `entity` + `desiredState`/`bindings` from the spec and confirm the
157
+ domain specifics with the QA (`AskUserQuestion`)** — never invent domain values.
158
+
159
+ Run **`sungen data state`**: it validates the graph (cycles, dangling deps, bindings) and renders a
160
+ standardized **manual precondition** block — tagged **`@manual:data-setup`** when it can't be
161
+ auto-provisioned — to weave into the scenario's `Background`. **This works with only spec + viewpoint:
162
+ provenance is usually `prior-flow`/`fixture`/`manual`, NOT DB/API.** If a datasource is later added and
163
+ a resource uses `api`/`db` provenance (+ a `provider:` endpoint), the *same* recipe auto-provisions — no
164
+ rewrite. For a **journey where the same data flows across screens** (setup → confirmation → complete),
165
+ add `shared: { entity, screens: [...] }` so one dataset is used across all of them.
166
+
167
+ ## One QA-facing door: `/sungen:create-test`
168
+
169
+ QA never needs to remember which `sungen data …` sub-command to run. **`/sungen:create-test` is the
170
+ single entry** — it standardizes fields, validates, cross-checks, and drafts any stateful precondition
171
+ inline. The `sungen data gen|lint|validate|crosscheck|state|provenance|fixture` commands are the
172
+ **deterministic plumbing** the create-test loop (and CI) drives; run them directly only for a targeted
173
+ re-standardize. `/sungen:create-data-test` is the same pipeline on demand (re-standardize after editing
174
+ a field-map/`.overwrite`, or a unit authored before Data Factory) — not a step you must invoke after
175
+ create-test.
176
+
177
+ ## Cross-artifact check — testcase ↔ data agree
178
+
179
+ `data validate` checks the data alone; **`sungen data crosscheck`** checks the testcase and its data
180
+ AGREE: no dangling `{{var}}` (every referenced var has a value), a cross-screen `shared` dataset is
181
+ identical across the journey (confirmation shows what setup entered), and a declared state-precondition
182
+ is surfaced in the feature. Run it after the `.feature` exists; fix any `error`. Together
183
+ `data validate` + `data crosscheck` are the **Data Gate + Cross-artifact Gate** (the `data-only`
184
+ harness profile). Every `data gen` also stamps a `_fingerprint` (catalog+generator+context hash) so a
185
+ reader/cache can tell whether the inputs that produced the data changed.
186
+
187
+ ## Boundary completeness + trim
188
+
189
+ Boundary Value Analysis is **complete by construction**: for every bounded dimension in the field-map's
190
+ `constraints` — including ones the field-type's catalog didn't model (e.g. an **email `minLength`**) —
191
+ the generator auto-emits the full set **min-1 (invalid) · min · min+1 · max-1 · max · max+1 (invalid)**.
192
+ So a spec "email min 5" yields length 4 (invalid), 5, 6 — don't hand-add them. Text fields also carry a
193
+ **leading/trailing-whitespace** case (trim behaviour: the server must trim then accept, or reject per
194
+ spec — confirm). If `data validate`/the QA still finds a missing boundary, it means the constraint was
195
+ absent from the field-map — add it there.
196
+
197
+ ## Login / authentication screens — credential-state cases (experience)
198
+
199
+ A login screen is not just field-format validation. The catalog carries an **experience checklist**
200
+ (`auth-account-states`) of credential/account STATES a login must cover — each a scenario, most needing
201
+ a domain-state precondition (a seeded account in that state; declare it with a state-recipe →
202
+ `@manual:data-setup` Background):
203
+ - **active** (happy path) · **wrong-password** · **non-existent** (same generic error — anti-enumeration)
204
+ - **soft-deleted** (must NOT authenticate — real-world bug precedent) · **locked/suspended** ·
205
+ **unverified-email** · **password-expired** · **valid-with-surrounding-whitespace** (trim → accept).
206
+ When the unit is a login/auth screen, generate these as scenarios (confirm the exact outcome/message
207
+ code with the spec). Do not assume the outcome — ask the QA for states the spec doesn't pin.
208
+
112
209
  ## Weaving into scenarios
113
210
 
114
211
  When a `.feature` exists, express invalid/boundary sets as data-driven `Scenario Outline` + `Examples`