@vijaypjavvadi/bdd2pw 4.6.5 → 4.6.7

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 (69) hide show
  1. package/CHANGELOG.md +4607 -4556
  2. package/README.md +534 -471
  3. package/dist/cli.js +5 -11
  4. package/dist/cli.js.map +1 -1
  5. package/dist/data/dataLoader.js +1 -3
  6. package/dist/data/dataLoader.js.map +1 -1
  7. package/dist/data/examplesInjector.js.map +1 -1
  8. package/dist/data/synthGenerator.js.map +1 -1
  9. package/dist/discovery/domHash.js.map +1 -1
  10. package/dist/discovery/mcpClient.js.map +1 -1
  11. package/dist/emitters/facade.js +3 -7
  12. package/dist/emitters/facade.js.map +1 -1
  13. package/dist/http/artifacts.js.map +1 -1
  14. package/dist/http/routes.js +5 -6
  15. package/dist/http/routes.js.map +1 -1
  16. package/dist/index.js +19 -15
  17. package/dist/index.js.map +1 -1
  18. package/dist/llm/anthropicClient.js +9 -17
  19. package/dist/llm/anthropicClient.js.map +1 -1
  20. package/dist/llm/cache.js +1 -3
  21. package/dist/llm/cache.js.map +1 -1
  22. package/dist/llm/candidateRules.js.map +1 -1
  23. package/dist/llm/geminiClient.js +8 -12
  24. package/dist/llm/geminiClient.js.map +1 -1
  25. package/dist/llm/governanceClient.js.map +1 -1
  26. package/dist/llm/index.js.map +1 -1
  27. package/dist/llm/llmStepMatcher.js.map +1 -1
  28. package/dist/llm/openaiClient.js +1 -2
  29. package/dist/llm/openaiClient.js.map +1 -1
  30. package/dist/llm/prompt.js +79 -73
  31. package/dist/llm/prompt.js.map +1 -1
  32. package/dist/llm/proposeRules.js +5 -1
  33. package/dist/llm/proposeRules.js.map +1 -1
  34. package/dist/llm/telemetry.js +1 -3
  35. package/dist/llm/telemetry.js.map +1 -1
  36. package/dist/parser/gherkinParser.js.map +1 -1
  37. package/dist/repo/projectScaffolder.js +1 -3
  38. package/dist/repo/projectScaffolder.js.map +1 -1
  39. package/dist/repo/repoScanner.js.map +1 -1
  40. package/dist/reports/coverage.js.map +1 -1
  41. package/dist/reports/healStats.js +1 -3
  42. package/dist/reports/healStats.js.map +1 -1
  43. package/dist/reports/metaSidecar.js.map +1 -1
  44. package/dist/reports/quarantineStats.js +1 -3
  45. package/dist/reports/quarantineStats.js.map +1 -1
  46. package/dist/reports/reviewReport.js.map +1 -1
  47. package/dist/reports/specMerge.js.map +1 -1
  48. package/dist/transformers/apiRules.js.map +1 -1
  49. package/dist/transformers/domains/banking.js.map +1 -1
  50. package/dist/transformers/domains/education.js.map +1 -1
  51. package/dist/transformers/domains/gov.js.map +1 -1
  52. package/dist/transformers/domains/healthcare.js.map +1 -1
  53. package/dist/transformers/domains/insurance.js.map +1 -1
  54. package/dist/transformers/domains/retail.js.map +1 -1
  55. package/dist/transformers/domains/telecom.js.map +1 -1
  56. package/dist/transformers/locatorPicker.js +1 -1
  57. package/dist/transformers/locatorPicker.js.map +1 -1
  58. package/dist/transformers/pomResolver.js +1 -3
  59. package/dist/transformers/pomResolver.js.map +1 -1
  60. package/dist/transformers/stepMatcher.js +33 -15
  61. package/dist/transformers/stepMatcher.js.map +1 -1
  62. package/dist/transformers/stepNormalizer.js +22 -4
  63. package/dist/transformers/stepNormalizer.js.map +1 -1
  64. package/dist/transformers/visibilityRules.js +1 -7
  65. package/dist/transformers/visibilityRules.js.map +1 -1
  66. package/dist/utils/naming.js +6 -2
  67. package/dist/utils/naming.js.map +1 -1
  68. package/package.json +120 -109
  69. package/templates/heal.ts.tmpl +452 -452
package/README.md CHANGED
@@ -1,471 +1,534 @@
1
- [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.20450278.svg)](https://doi.org/10.5281/zenodo.20450278)
2
-
3
-
4
- # bdd2pw — Gherkin `.feature` → Playwright TypeScript scaffold
5
-
6
- # @vijaypjavvadi/bdd2pw
7
-
8
- [![npm version](https://img.shields.io/npm/v/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
9
- [![npm downloads](https://img.shields.io/npm/dm/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
10
- [![npm total downloads](https://img.shields.io/npm/dt/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
11
- [![license](https://img.shields.io/npm/l/@vijaypjavvadi/bdd2pw.svg)](https://github.com/javvadivijayprasad/bdd2pw/blob/main/LICENSE)
12
- [![Listed in Awesome Playwright](https://awesome.re/mentioned-badge.svg)](https://github.com/mxschmitt/awesome-playwright)
13
-
14
- > Scaffold runnable Playwright TypeScript tests from Gherkin `.feature` files. Auto-detects existing Page Objects, scans live pages via Microsoft Playwright MCP, emits POMs and specs ready for execution. CLI + HTTP service.
15
-
16
- [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
17
- [![Node](https://img.shields.io/badge/node-%E2%89%A518-brightgreen?logo=node.js)](https://nodejs.org/)
18
- [![npm](https://img.shields.io/npm/v/@vijaypjavvadi/bdd2pw.svg?label=npm)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
19
- [![Tests](https://img.shields.io/badge/tests-290%2B%20passing-brightgreen)](./tests)
20
- [![Rules](https://img.shields.io/badge/rules-200%2B%20deterministic-brightgreen)](./src/transformers)
21
- [![Domain packs](https://img.shields.io/badge/domain%20packs-7-blue)](./src/transformers/domains)
22
- [![VS Code Marketplace](https://img.shields.io/visual-studio-marketplace/v/vijaypjavvadi.bdd2pw?label=vscode-extension)](https://marketplace.visualstudio.com/items?itemName=vijaypjavvadi.bdd2pw)
23
-
24
- Most teams writing BDD test cases (via Cucumber `.feature` files, possibly authored by an LLM) face the same gap: the `.feature` describes the test, but **someone still has to write the Page Objects and the Playwright spec by hand**. That's the work `bdd2pw` does for you.
25
-
26
- Point it at a `.feature` file and a URL. It parses the Gherkin, scans the live page with Chromium, picks the most stable locator for every interactive element, matches each step to a POM method call, and emits a runnable Playwright TypeScript repo — including `playwright.config.ts`, `pages/login.page.ts`, `tests/login.spec.ts`, and a `BDD_REVIEW.md` listing anything a human still needs to look at.
27
-
28
- ## What `bdd2pw` is and isn't (as of v4.4.0)
29
-
30
- `bdd2pw` is a **deterministic scaffolder with an optional governed LLM fallback across three providers**. The output is honest about its limits:
31
-
32
- - **Specific `.feature` files** — quoted credentials, concrete assertion targets, standard verb forms — convert to **runnable specs with zero hand-edits**. Validated end-to-end against 8 public benchmark applications (`practicetestautomation.com`, `owasp-juice-shop`, SauceDemo, the-internet, OpenCart, Magento, Conduit, Reqres): 8/8 compilation across deterministic and LLM-governed modes.
33
- - **Vague `.feature` files** — "Enter valid username and password and click login button" with no quoted values — get partial coverage. Unmatched steps either route to the LLM fallback (when an Anthropic / OpenAI / Gemini key is configured) or land as `// TODO` comments + warnings in `BDD_REVIEW.md`.
34
- - **200+ deterministic rules**, organised across three layers:
35
- - **API rules** (v3.0+) — `page.request.*` patterns for GET / POST / PUT / DELETE / PATCH, body / header / status assertions.
36
- - **Visibility rules** (v3.1+) — `<noun> is visible / displayed / shown / appears` intercepts before URL-slug heuristics, so prose like "the user's name or profile indicator is visible in the UI" never gets slugified into a URL regex.
37
- - **UI + URL rules** (v1.x lineage, refined through v3.7.1) — 30+ rules covering first-person, third-person, no-subject Cucumber dialects + compound input steps.
38
- - **7 opt-in domain rule packs** (v3.4 + v3.8) — banking, healthcare, insurance, retail, gov, education, telecom. Each adds ~20 industry-specific patterns. Activated via `domains: ["banking"]`; empty by default for byte-stable existing behaviour.
39
- - **Three-provider LLM fallback, batched per scenario** (v3.5 + v3.11 + v3.12) — one Anthropic Claude Sonnet 4.6, OpenAI gpt-4o-mini, or Google Gemini 2.5 Flash call per scenario instead of one per unmatched step. ~75% cost reduction on unmatched-heavy scaffolds. Every prompt goes through the `ai-governance` sidecar's `/sanitize` endpoint (fail-closed on 4xx/5xx/timeout — the run terminates rather than emit ungoverned code).
40
- - **Three hallucination-rejection gates on LLM output** (v4.0.1) — invented-helper detection, structured-pomCall guard, and bare-field-call trap. Bindings the LLM emits that would compile-fail land as `// TODO` comments with `BDD_REVIEW.md` entries instead of broken code. Locked by 19 dedicated unit tests.
41
- - **Six-pattern LLM-binding rewriter** (v4.1) — mechanically transforms common LLM emission mistakes (invented-helper shapes, bare-field args, unquoted string values, CSS-selector args, `page.<method>` invented-helpers in customBody, Locator-only matchers hallucinated on `page`, bare-identifier assertion locators) into valid Playwright-idiomatic code. Runs *before* the v4.0.1 gates; if a rewrite would still produce broken code, the binding is rejected and lands as TODO. Bench result: 3/8 → **8/8 apps produce specs that pass `tsc --noEmit`**. Locked by 35 unit tests.
42
- - **DOM-drift detection via POM header hash** (v4.2) — every emitted POM carries a `@bdd2pw dom-hash` comment with a stable sha256 of the page's accessibility tree. On re-scaffold, bdd2pw diffs the new snapshot against the stored hash. Silent UI changes surface as a `DOM DRIFT` warning in `BDD_REVIEW.md` with both hashes and a suggested triage path. `--fail-on-drift` turns it into a non-zero exit code so CI can gate merges on silent UI regressions.
43
- - **In-process self-healing locators via `@vijaypjavvadi/pw-self-heal`** (v4.3) — `--self-healing` emits a 3-line `tests/fixtures.ts` that wraps the base `test` with `withSelfHealing({ mode })`. Every spec's top-of-file import auto-rewrites to pull `test` + `expect` from `./fixtures` instead of `@playwright/test` directly. POM classes are unchanged; healing is transparent. Ranker: trained ONNX model with a published Zenodo DOI ([10.5281/zenodo.19684439](https://doi.org/10.5281/zenodo.19684439)), GB AUC 0.9993, three modes (`heuristic` / `ml` / `hybrid`). No server, no API key, no Python — the DOM never leaves the machine.
44
- - **Legible provenance — `@llm-generated` tag + rule attribution + two report CLIs** (v4.4) — every emitted step records which rule (or which LLM provider + model) produced it in `*.spec.meta.json`. A scenario with an LLM-bound step gets the `@llm-generated` tag so `npx playwright test --grep-invert @llm-generated` runs the trusted lane. `bdd2pw quarantine-stats` reports scenarios / steps / cache-hit share / promotions per lane. `bdd2pw coverage` turns the same data into decisions: rule hit rate, dead rules, dead packs, promotion trail (candidate → rule → firing), and heal pressure. Both write JSON sidecars with a shared shape. Both are reports, not gates.
45
- - **Data-driven scaffolds** (v4.0.0) — `--data <path>` injects CSV / JSON / XLSX rows into every Scenario Outline's `Examples:` table; `--gen-data --schema <path> --rows N` generates synthetic rows via Faker + optional per-column LLM calls (`llm:auto insurance claim description`); seeded (`--seed 42`) for reproducibility.
46
- - **`updatePom` is append-only by construction.** Re-scanning a page that already has a Page Object adds new locators only. Hand-edited method bodies, custom helper methods, custom imports are all preserved byte-identical.
47
- - **`--merge` mode** (v3.2) preserves `// bdd2pw:user-block id="..."` sections across regenerations so iterative locator tuning doesn't lose work.
48
- - **Reproducible benchmark harness** (v4.0.0) — `bench/runner.ts` scaffolds all 8 benchmark apps in three modes (deterministic-only, LLM-blocked, LLM-governed) with per-app sha256 verification. Public artifact accompanying the SoftwareX manuscript.
49
-
50
- > **The pitch.** Run `bdd2pw scaffold` and you get a Playwright TS repo where `npx playwright test` runs against the real site. For specific fixtures, all green. For vague ones, the 60-90% you'd otherwise hand-write is done; you finish the rest — or you let the governed LLM finish them.
51
-
52
- ## What's new in v4.0.0
53
-
54
- - **NEW** `--data <path>` — load CSV / JSON / XLSX file and inject rows into every Scenario Outline's Examples table. Drop in a 500-row dataset without touching the .feature file.
55
- - **NEW** `--gen-data --schema <path> --rows N` — generate synthetic Examples rows. Schema picks per-column source: `faker.internet.email` for common fields, `llm:auto insurance claim description` for context-aware domain data. Seeded for reproducibility (`--seed 42`).
56
- - **NEW** `LLMClient.generateText()` — generic single-prompt API on all three providers (Anthropic, OpenAI, Gemini). Same governance + budget + timeout + telemetry pipeline as binding generation.
57
- - Gemini provider — three-provider parity complete. `--llm gemini` defaults to `gemini-2.5-flash` ($0.10/M input — cheapest across all three providers). (v3.12.0)
58
- - OpenAI provider with full parity. `--llm openai` defaults to `gpt-4o-mini`. (v3.11.0)
59
- - `bdd2pw heal-stats <repo>` CLI reads `<repo>/artefacts/heal-events.jsonl` and writes a heal-stats.json sidecar with heal rate, top failing fields, retry latency, candidate-selector promotions (v3.10.0).
60
- - `llmStats: true` writes `<repo>/artefacts/llm-stats.json` with per-call latency, token counts, cache hit rate, and an estimated cost in USD (v3.9.0).
61
- - Seven domain rule packs (banking, healthcare, insurance, retail, gov, education, telecom) — ~140 industry-specific patterns total.
62
- - Per-scenario LLM batching cuts Anthropic spend by ~75% on unmatched-heavy scaffolds.
63
- - `bdd2pw propose-rules` CLI clusters past LLM bindings into draft regex proposals — turning the offline-review pipeline into one command.
64
- - `diagnostics: true` adds a "Rule trace" block to `BDD_REVIEW.md` showing exactly which rules declined a step and why.
65
- - `merge: true` preserves user-edited blocks across regenerations.
66
- - `metaSidecar: true` writes `<spec>.spec.meta.json` describing every step's semantic intent for downstream tools.
67
- - VS Code extension (`vijaypjavvadi.bdd2pw`) v0.2.0 surfaces all the above as settings + commands.
68
-
69
- ## Where this fits in the platform
70
-
71
- | Stage | Service | Role |
72
- |---|---|---|
73
- | 1. Generate | `test-case-generation-service` (FastAPI :4100) | Author `.feature` files from requirements |
74
- | **1.5. Scaffold** | **`bdd2pw` (this repo) — Express :4300 + CLI** | `.feature` + URL → POM + spec, ready to run |
75
- | 2. Migrate | [`@vijaypjavvadi/sel2pw`](https://github.com/javvadivijayprasad/sel2pw) (Express :4200) | Legacy Selenium → Playwright |
76
- | 3. Stabilise | `self-healing-stage-services` (FastAPI :8003) | Heal locators at runtime |
77
- | 4. Govern | `ai-governance` (Python lib + sidecar :8004) | Sanitise every LLM payload (when v1.1 LLM fallback ships) |
78
- | Orchestrate | `modern-automation-platform` (Express :3000) | Auth, jobs, UI, artifacts |
79
-
80
- `bdd2pw` and `sel2pw` are siblings. Both consume **`@vijaypjavvadi/pw-emit`** (the shared emitter library), so the Page Objects produced by one are byte-identical in shape to those produced by the other.
81
-
82
- ## Install
83
-
84
- ```bash
85
- npm install -D @vijaypjavvadi/bdd2pw
86
- npx playwright install chromium # browser for live page discovery
87
- ```
88
-
89
- Node ≥ 18. Cross-platform (Linux / macOS / Windows). `playwright` is an optional dep — if you don't install browsers, pass `--snapshot-file <path.json>` instead.
90
-
91
- ## Quick start
92
-
93
- ```bash
94
- # Scaffold a runnable Playwright TS project from a .feature file
95
- npx bdd2pw scaffold path/to/login.feature \
96
- --url https://your-app.example.com/login \
97
- --page LoginPage \
98
- --repo ./my-tests
99
-
100
- cd ./my-tests
101
- npm install
102
- npx playwright test
103
- ```
104
-
105
- That's it. `./my-tests` now has `pages/login.page.ts`, `tests/login.spec.ts`, `playwright.config.ts`, `package.json`, `tsconfig.json`, `.gitignore`, and `BDD_REVIEW.md`.
106
-
107
- ## LLM fallback (v2.0+)
108
-
109
- When a Gherkin step doesn't match any of bdd2pw's 30 deterministic rules, you can opt-in to an Anthropic-backed LLM fallback that produces the binding instead of dropping to `// TODO`. Off by default.
110
-
111
- ```bash
112
- # Anthropic API key — required when --llm anthropic is set
113
- export ANTHROPIC_API_KEY=sk-ant-api03-...
114
-
115
- bdd2pw scaffold ./my.feature \
116
- --url https://app.example.com \
117
- --page LoginPage \
118
- --repo ./out \
119
- --llm anthropic \
120
- --governance-url http://localhost:4900
121
- ```
122
-
123
- Every successful LLM-binding is appended to `<repo>/artefacts/candidate-rules.jsonl` so an offline review pipeline can propose new deterministic rules. Auto-write back to `stepMatcher.ts` is deferred to v2.1+ — for v2.0 the LLM is a runtime overlay, never a code generator for the matcher itself.
124
-
125
- ### Two-lane runs — trusted vs review (v4.4+)
126
-
127
- A scenario in which at least one step was bound by the LLM fallback is emitted with a `@llm-generated` tag next to its existing tags. That lets Playwright's own `--grep`/`--grep-invert` filter split every run into two lanes with zero framework wiring:
128
-
129
- ```bash
130
- # Trusted lane — only scenarios whose every step was rule-bound
131
- npx playwright test --grep-invert @llm-generated
132
-
133
- # Review lane — only the scenarios that used the LLM fallback
134
- npx playwright test --grep @llm-generated
135
- ```
136
-
137
- Per-step provenance lives in the sidecar `<spec>.spec.meta.json` next to the emitted spec. LLM-bound steps carry `"rule": null` plus an `"llm": { provider, model, cached, governance, at }` block; rule-bound steps carry neither field. Everything the tag hides at scenario level is inspectable at step level.
138
-
139
- Aggregate a scaffolded repo with:
140
-
141
- ```bash
142
- npx bdd2pw quarantine-stats ./my-tests # table + writes artefacts/quarantine-stats.json
143
- npx bdd2pw quarantine-stats ./my-tests --json # machine-readable, same shape as the file
144
- ```
145
-
146
- Sample table output:
147
-
148
- ```
149
- scenarios: 24 total · 21 deterministic · 3 @llm-generated
150
- steps: 58 total · 55 by rule · 3 by LLM
151
- LLM cache hit share: 66.7%
152
-
153
- promotions: 2/9 candidate step(s) now rule-bound
154
- ```
155
-
156
- The `promotions` line is the story: candidate step-texts recorded in `artefacts/candidate-rules.jsonl` from earlier runs that no longer need the LLM because a deterministic rule now covers them. That number going up is the point of running the LLM at all — a scaffold, then a rule, then no LLM.
157
-
158
- `quarantine-stats` is a report, not a gate. It exits 0 on every clean read and only fails with a non-zero code on a real I/O error against the repo root. Wire it into your CI dashboard, don't wire it into your merge gate.
159
-
160
- ### Rule + pack coverage (v4.4+)
161
-
162
- Slice 1 tells you which lane a step is in. Coverage tells you which rules earned their place in the table:
163
-
164
- ```bash
165
- npx bdd2pw coverage ./my-tests --domains banking,retail
166
- npx bdd2pw coverage ./my-tests --json
167
- npx bdd2pw coverage ./my-tests --suggest-retire
168
- ```
169
-
170
- The report answers four things:
171
-
172
- - **rule hit rate** — for every rule that fired, how many steps it bound, plus up to 3 sample step texts.
173
- - **dead rules / dead packs** — every rule in the current registry that did NOT fire in this repo, and every domain pack whose rules were all dead. "Dead here" is a repo-scoped observation, not a global verdict on the rule.
174
- - **promotion trail** — same field as `quarantine-stats`. Candidate steps recorded by past LLM fallbacks that are now bound by a rule.
175
- - **heal pressure** — top locators from `artefacts/heal-events.jsonl` (or `.pwheal/heal-events.jsonl` when running with the v4.3 in-process healer). A rule that binds and then always needs healing is worse than no rule.
176
-
177
- `--suggest-retire` prints a copyable stanza listing the dead packs and dead rules; it never edits `stepMatcher.ts` or your bdd2pw config. Paste the parts you want to apply.
178
-
179
- The `totals` and `promotions` blocks in `coverage.json` are byte-identical to the same-named blocks in `quarantine-stats.json`, so a dashboard reading either one gets the same numbers.
180
-
181
- ### Governance sanitization (mandatory by default)
182
-
183
- Per the platform contract, **every prompt passes through the `ai-governance` sidecar's `/sanitize` endpoint** before reaching Anthropic. This scrubs API keys, JWTs, AWS creds, and other secrets that might leak via test data in the `.feature` file. **Fail-closed** — if the sidecar is unreachable, the LLM call is REFUSED and the step falls back to TODO.
184
-
185
- Two ways to satisfy this:
186
-
187
- **(a) Internal platform users:** the `ai-governance` service is part of your platform service mesh. Just point bdd2pw at it (`--governance-url http://ai-governance:4900` or wherever).
188
-
189
- **(b) External users:** run your own sidecar.
190
-
191
- ```bash
192
- # Clone and run the sidecar
193
- git clone https://github.com/javvadivijayprasad/ai-governance
194
- cd ai-governance
195
- python -m venv .venv && .\.venv\Scripts\Activate.ps1 # or `source .venv/bin/activate` on Mac/Linux
196
- pip install fastapi uvicorn pydantic pyyaml
197
- PYTHONPATH=src uvicorn service.app:app --port 4900
198
- ```
199
-
200
- Or there's a Docker image once it's published: `docker run -p 4900:4900 ghcr.io/javvadivijayprasad/ai-governance:latest`.
201
-
202
- **Test-only escape hatch:** `--llm-skip-governance` bypasses the sidecar entirely. Use only when your `.feature` data is synthetic (no real credentials, no PII). For production, **always** keep governance on.
203
-
204
- ```bash
205
- # UNSAFE for real test data — use only with synthetic fixtures
206
- bdd2pw scaffold ./my.feature ... --llm anthropic --llm-skip-governance
207
- ```
208
-
209
- ### Cost + determinism guardrails
210
-
211
- | Flag | Default | Purpose |
212
- |---|---|---|
213
- | `--llm-max-calls <n>` | `50` | Hard cap on provider calls per scaffold. Cache hits don't count. |
214
- | `--llm-cache <path>` | `<repo>/.bdd2pw/llm-cache.sqlite` | SQLite cache keyed by step text + POM signature + model. Same inputs across runs return the same binding — cost goes to zero on re-runs. Pass `:memory:` for one-shot use. |
215
- | `--llm-model <model>` | `claude-sonnet-4-6` | Override the Anthropic model. |
216
-
217
- Re-runs of the same `.feature` (after a code edit, retry, etc.) will hit the cache and make zero provider calls. A typical per-scaffold cost on first run: ~$0.005–0.02 USD with Sonnet, depending on how many steps need LLM fallback.
218
-
219
- ### Cloud-jobs deployment recipe
220
-
221
- If you're running bdd2pw in an automation pipeline (cloud-jobs-template, GitHub Actions, etc.):
222
-
223
- ```yaml
224
- env:
225
- ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # platform secrets store
226
-
227
- steps:
228
- - name: Run scaffold with LLM fallback
229
- run: |
230
- bdd2pw scaffold "$FEATURE_FILE" \
231
- --url "$TARGET_URL" \
232
- --page "$PAGE_NAME" \
233
- --repo /work \
234
- --self-healing \
235
- --llm anthropic \
236
- --governance-url http://ai-governance:4900
237
- ```
238
-
239
- Make sure the `ai-governance` sidecar is co-located (k8s sidecar pattern) or reachable on the platform service mesh.
240
-
241
- ## CLI surface — three commands
242
-
243
- ### `scaffold` — generate a fresh repo
244
-
245
- ```bash
246
- bdd2pw scaffold <feature> --url <url> --page <Name> --repo <dir> [options]
247
- ```
248
-
249
- Reads the `.feature`, scans the URL with Chromium, picks locators, matches steps, emits the project. Flags:
250
-
251
- ```
252
- --snapshot-file <path> Use a captured JSON snapshot instead of launching a browser
253
- --no-discovery Skip page discovery entirely (rule-only probing)
254
- --storage-state <path> Pre-authenticated storage state JSON
255
- --headed Show browser during scan
256
- --templates <dir> Override default project templates
257
- --dry-run Print plan, write nothing
258
- --no-validate Skip tsc --noEmit step
259
- --force Overwrite existing spec files
260
- ```
261
-
262
- ### `analyze` — dry-run the matcher
263
-
264
- ```bash
265
- bdd2pw analyze <feature> --url <url> [options]
266
- ```
267
-
268
- Same pipeline but writes nothing — prints the parsed feature, the discovered locators, and the planned step bindings as JSON. Useful for "what would scaffold do?" probing.
269
-
270
- ### `update-pom` — merge new locators into an existing POM
271
-
272
- ```bash
273
- bdd2pw update-pom --page <Name> --url <url> --repo <dir> [options]
274
- ```
275
-
276
- Re-scan the page and **append** any newly-discovered locators to the existing Page Object. Never touches existing fields, methods, or specs. Hand-edited method bodies survive byte-identical.
277
-
278
- ## HTTP service
279
-
280
- `bdd2pw serve` starts an Express service on `:4300` with the same three commands as REST endpoints. Mirror of the CLI; HTTP is a thin shell.
281
-
282
- ```bash
283
- bdd2pw serve --port 4300
284
-
285
- # In another terminal:
286
- curl -X POST http://localhost:4300/scaffold \
287
- -H 'content-type: application/json' \
288
- -d '{"feature":"/abs/path/to/login.feature","url":"https://...","page":"LoginPage","repo":"unused","options":{"snapshotFile":"/abs/snapshot.json","noValidate":true}}'
289
- # → 202 Accepted: {"jobId":"01HX...","links":{"self":"/jobs/01HX...","artifact":"/jobs/01HX.../artifact"}}
290
-
291
- curl http://localhost:4300/jobs/01HX... # poll for completion
292
- curl -O http://localhost:4300/jobs/01HX.../artifact # download zip
293
- ```
294
-
295
- | Endpoint | Purpose |
296
- |---|---|
297
- | `GET /healthz`, `/version`, `/readyz` | Liveness probes |
298
- | `POST /scaffold`, `/analyze`, `/update-pom` | Async job — returns `202` + `jobId` |
299
- | `GET /jobs/:id` | Job status / progress / result |
300
- | `GET /jobs/:id/artifact` | Stream zip of the scaffolded repo |
301
- | `GET /jobs/:id/log` | Plain-text dump of warnings + errors |
302
-
303
- In production, the platform gateway proxies `/api/v1/scaffold/*` to `:4300`. Direct port exposure is local-dev only.
304
-
305
- ## Pipeline
306
-
307
- ```
308
- .feature file
309
- │
310
- ▼
311
- ┌──────────────┐
312
- │ gherkinParser│ @cucumber/gherkin → FeatureIR (scenarios, background, examples)
313
- └──────┬───────┘
314
- ▼
315
- ┌──────────────┐
316
- │ repoScanner │ ts-morph → existing pages/*.page.ts → Map<class, IR>
317
- └──────┬───────┘
318
- ▼
319
- ┌──────────────┐
320
- │ pomResolver │ CREATE / AUGMENT / REUSE decision
321
- └──────┬───────┘
322
- ▼
323
- ┌──────────────┐
324
- │ scanPage │ playwright chromium → DOM walk → ElementIR[]
325
- │ │ (or --snapshot-file / --no-discovery fallbacks)
326
- └──────┬───────┘
327
- ▼
328
- ┌──────────────┐
329
- │ locatorPicker│ getByRole > getByLabel > getByPlaceholder > getByTestId
330
- │ │ > getByText > css > xpath
331
- │ │ Status-region special case + dedup by (api, args)
332
- └──────┬───────┘
333
- ▼
334
- ┌──────────────┐
335
- │ stepMatcher │ 30 rules — subject-agnostic, dialect-tolerant,
336
- │ │ compound-input via customBody
337
- └──────┬───────┘
338
- ▼
339
- ┌──────────────┐
340
- │ pw-emit │ @vijaypjavvadi/pw-emit → POM TS + spec TS + project scaffold
341
- └──────┬───────┘
342
- ▼
343
- ┌──────────────┐
344
- │ tscRunner │ Optional tsc --noEmit → diagnostics into BDD_REVIEW.md
345
- └──────┬───────┘
346
- ▼
347
- output/
348
- pages/<name>.page.ts
349
- tests/<name>.spec.ts
350
- playwright.config.ts
351
- package.json, tsconfig.json, .gitignore
352
- BDD_REVIEW.md ← warnings + manual TODOs
353
- ```
354
-
355
- ## What `bdd2pw` covers
356
-
357
- ### Step matcher rules (14)
358
-
359
- | # | Pattern | Emits |
360
- |---|---|---|
361
- | 1 | `(I/user) am on/navigate to/visit/open <X>` (with or without quoted URL) | `goto()` |
362
- | 2a | `(I/user) enter "<value>" into <field>` | `<field>.fill("<value>")` |
363
- | 2b | `(I/user) enter <field> "<value>"` | `<field>.fill("<value>")` |
364
- | 2c | **Compound:** `(I/user) enter <f1> "<v1>" <f2> "<v2>" ...` | N `.fill()` lines |
365
- | 3 | `(I/user/-) click/press/tap <X> button/link/icon/tab` | `<field>.click()` (or POM method if defined) |
366
- | 4 | `(I/user) select "<opt>" from <dropdown>` | `<field>.selectOption(...)` |
367
- | 5 | `(I/user) check/uncheck <checkbox>` | `<field>.check()` / `.uncheck()` |
368
- | 6 | `(I/user) (should) see <X>` | `expect(<X>).toBeVisible()` |
369
- | 7 | `(I/user) should not see <X>` | `expect(<X>).toBeHidden()` |
370
- | 8 | `(I/user) should see (the/an/a) error message "<X>"` | `expect(<errorField>).toContainText("<X>")` |
371
- | 9a | `(I/user) should see <X> containing/with text "<Y>"` | `expect(<X>).toContainText("<Y>")` |
372
- | 9b | `(I/user) should see <X> "<Y>"` (exact equality) | `expect(<X>).toHaveText("<Y>")` |
373
- | 10 | `(I/user) should remain on <page>` | `expect(page).toHaveURL(/<page>/)` |
374
- | 11 | `(I/user) (should be/is) redirected to <page>` | `expect(page).toHaveURL(/<page>/)` |
375
- | 12 | `the <field> field should be of type "<type>"` | `expect(<field>).toHaveAttribute("type", "<type>")` |
376
- | 13 | `the (current) URL should start with/contain "<X>"` | `expect(page).toHaveURL(/^<X>/)` |
377
-
378
- ### Cucumber features
379
-
380
- - `Background:` → `test.beforeEach`
381
- - `Scenario Outline:` + `Examples:` → one `test()` per row, with placeholder substitution
382
- - `Tags` → emitted as `// @tag` comments above each test
383
- - Doc strings + data tables — preserved on `StepIR.argument`
384
-
385
- ### Locator priority
386
-
387
- `getByRole` (with accessible name) > `getByLabel` > `getByPlaceholder` > `getByTestId` > `getByText` > CSS > xpath. **Status regions** (`<div id="error">`, `[role=alert]`, `[class*=notification]`) bypass the visibility filter (they're hidden until triggered) and use their `id` for both field name and locator (text content is volatile, id is stable).
388
-
389
- ## Verification
390
-
391
- | Check | Status |
392
- |---|---|
393
- | `npm run lint` | ✅ clean |
394
- | `tsc --noEmit` | ✅ clean |
395
- | `npm test` (vitest) | ✅ **101/101 green** across 10 test files |
396
- | `practice-test-login` end-to-end vs the live site | ✅ **7/7** scenarios green via `npx playwright test` |
397
- | `cms-login` (selenium14 dialect) regression | ✅ 12 assertions green, third-person + compound input + `is redirected` |
398
- | HTTP worker zip download | ✅ end-to-end test verifies real ZIP magic bytes |
399
- | `update-pom` preserves hand-edited method bodies | ✅ 5 byte-identical-survival assertions |
400
-
401
- ## Roadmap
402
-
403
- ### Shipped (Aug 2025 → May 2026)
404
-
405
- | Version | Theme | Highlight |
406
- |---|---|---|
407
- | v1.0 | Foundation | Gherkin → Playwright TS scaffolding, POM resolver, file-snapshot discovery, HTTP worker service on `:4300`, `update-pom` AST surgery |
408
- | v1.1 | Self-healing | `--self-healing` flag, `lib/heal.ts` template, JSONL event logging |
409
- | v2.0 | LLM fallback | Anthropic SDK integration, governance sidecar `/sanitize`, SQLite step-binding cache, opt-in via `--llm anthropic` |
410
- | v2.2 | Reliability | Promise.race watchdogs, ai-governance fail-closed, structured pino logging end-to-end |
411
- | v3.0 | API testing | Native `page.request.*` patterns (~17 rules), tag-driven `@api` / `@ui` scenario state injection |
412
- | v3.1 | TestForge P0+P1 | Visibility-prose intercept, `:root` locator rejection, `testInfo` in test signature, opt-in step hooks + boundary markers |
413
- | v3.2 | Iteration UX | `playwright.config.ts` end-marker, exact-dep pinning, `*.spec.meta.json` sidecar, JSON scenarios input, `--merge` mode preserving `// bdd2pw:user-block` sections |
414
- | v3.3 | Hook signature | `fixtures` arg + `status` + try/catch/finally wrapping for `beforeStep` / `afterStep` |
415
- | v3.4 | Domain packs | Banking / healthcare / insurance opt-in rule packs (~60 new patterns) |
416
- | v3.5 | LLM batching | One Anthropic call per scenario instead of N — ~75% cost reduction on unmatched-heavy scaffolds |
417
- | v3.6 | Diagnostics + auto-rules | Rule-trace block in `BDD_REVIEW.md`; new `bdd2pw propose-rules` CLI clustering candidate-rules.jsonl into draft regex |
418
- | v3.7.1 | Regression fixes | PascalCase className shadow fix; `test.step` wrapping regression-asserted |
419
- | v3.8.1 | More domain packs | Retail / gov / education / telecom packs added — seven total (~140 industry-specific rules) |
420
- | v3.9.0 | Telemetry | `artefacts/llm-stats.json` sidecar — per-call latency + tokens + cache hit rate + estimated cost. Makes v3.5 batching ROI measurable per scaffold. |
421
- | v3.10.0 | Heal stats | `bdd2pw heal-stats <repo>` CLI consumes `artefacts/heal-events.jsonl` and writes `heal-stats.json` with heal rate, top failing fields, top error patterns, retry latency, candidate-selector promotions. Self-healing ROI per test run. |
422
- | v3.11.0 | OpenAI provider | `LLMClientOptions.provider: "openai"` lands with cache + governance + batching + telemetry parity. Default model `gpt-4o-mini` (~17x cheaper than `gpt-4o` for structured-JSON tasks). |
423
- | v3.12.0 | Gemini provider | `LLMClientOptions.provider: "gemini"` lands with full parity. Default model `gemini-2.5-flash` ($0.10/M input — cheapest across all three providers). Three-provider parity complete. |
424
- | v4.0.0 | Data-driven scaffolds | `--data <path>` (CSV/JSON/XLSX) and `--gen-data --schema <path>` (Faker + LLM) inject Examples rows into Scenario Outlines. `LLMClient.generateText()` added to all three providers. **Additive only — no breaking changes.** |
425
- | v4.0.1 | LLM hallucination gates | Three-layer rejector for invented POM helpers — bindings that would compile-fail land as TODO instead of broken code. 19 unit tests lock the behaviour. |
426
- | v4.1.0 | LLM binding rewriter | Six-pattern rewriter that mechanically fixes common LLM emission mistakes (invented helpers, bare-field args, CSS-selector args, `page.<method>` in customBody, hallucinated Page matchers, bare-identifier assertion locators). Bench result: 3/8 → **8/8 apps produce specs that pass `tsc --noEmit`**. Peer-reviewed publication in Elsevier SoftwareX. |
427
- | v4.2.0 | DOM-drift detection | Every emitted POM carries a `@bdd2pw dom-hash` header (sha256 of the accessibility tree). Re-scaffold diffs against the stored hash and surfaces silent UI changes in `BDD_REVIEW.md`. `--fail-on-drift` CLI flag exits non-zero when drift is detected (CI merge gate). |
428
- | v4.3.0 | pw-self-heal integration | `--self-healing` swaps the v4.2 lib/heal.ts + external service shim for `@vijaypjavvadi/pw-self-heal` — trained ONNX ranker (Zenodo DOI 10.5281/zenodo.19684439), in-process, no server. Emits a 3-line `tests/fixtures.ts`; POM classes unchanged. `--legacy-healing` keeps v4.2 behaviour for one release. |
429
- | **v4.4.0 (current)** | Legible provenance | `@llm-generated` scenario tag + rule/pack attribution recorded in `*.spec.meta.json`. Two report CLIs: `bdd2pw quarantine-stats` splits the suite into trusted vs review lanes; `bdd2pw coverage` reports rule hit rate, dead rules, dead packs, promotion trail, and heal pressure. Reports, not gates. |
430
-
431
- ### Next 6 months (Oct 2026 → Mar 2027, ~1 release/month)
432
-
433
- | Target | Version | Theme | Headline |
434
- |---|---|---|---|
435
- | Oct 2026 | **v4.5.0** | Mobile dialect | New `mobile` domain pack. Touch / swipe / scroll-into-view rules + responsive viewport assertions. Reuses the existing emitter pipeline; opt-in via `domains: ["mobile"]`. Scenarios tagged `@mobile` scaffold against a mobile device descriptor (Pixel 7 by default). |
436
- | Nov 2026 | **v4.6.0** | sel2pw merge | sel2pw migrated onto `@vijaypjavvadi/pw-emit` — three packages share one emitter. All future emitter improvements automatically flow to Selenium users. |
437
- | Nov 2026 | **v4.7.0** | Auto-rules | `bdd2pw apply-proposals --interactive` — walks the human through each v3.6 proposal, validates the regex compiles + matches the sample texts, optionally appends to `stepMatcher.ts`. Closes the propose-rules loop. |
438
- | Dec 2026 | **v4.8.0** | Domain packs (3 more) | **fintech** (KYC, AML, trading desks), **real-estate** (MLS, listings, escrow), **hospitality** (PMS, reservations, OTA). ~60 more rules. |
439
- | Jan 2027 | **v4.9.0** | API v2 | WebSocket assertion rules, multipart file-upload patterns, GraphQL query / mutation / subscription rules. Extends v3.0's API testing surface. |
440
- | Feb 2027 | **v5.0.0** | CI/CD templates + default flips | Optional scaffolder output: GitHub Actions / GitLab CI / Azure Pipelines / CircleCI starter workflows wired to run the generated specs (opt-in via `--ci <provider>`). Bumps to v5 alongside a small set of default flips (llm-stats + healing become opt-out). Migration guide ships alongside. |
441
-
442
- Each release is shaped to be self-contained, ship in ~2 weeks, and keep `domains: []` byte-stable for existing users so the upgrade path stays painless.
443
-
444
- ## Documents
445
-
446
- | Doc | Purpose |
447
- |---|---|
448
- | [`docs/SCOPE.md`](./docs/SCOPE.md) | What's in / out of v1.0, FR/NFR, CLI + HTTP surface, decisions log |
449
- | [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) | Component diagram, sequence diagrams, `pw-emit` contract, HTTP API contract, error model |
450
- | [`docs/PHASE_0_PLAN.md`](./docs/PHASE_0_PLAN.md) | The pw-emit extraction plan (mostly historical now — it shipped) |
451
- | [`docs/STATUS.md`](./docs/STATUS.md) | Verified state right now — what works, what's pending, what's deferred |
452
- | [`CHANGELOG.md`](./CHANGELOG.md) | Full version history |
453
- | [`CONTRIBUTING.md`](./CONTRIBUTING.md) | Local dev, branching, PR conventions |
454
-
455
- ## Examples
456
-
457
- - [`examples/practice-test-login/`](./examples/practice-test-login/) — first-person dialect, `Scenario Outline + Examples`, security scenarios. Validated 7/7 green against a live public site.
458
- - [`examples/cms-login/`](./examples/cms-login/) — third-person dialect, compound input, `is redirected`. From a real OSS Selenium codebase.
459
- ## Citation
460
-
461
- If you use `@vijaypjavvadi/bdd2pw` in academic work, please cite:
462
-
463
- > Javvadi, V. P. (2026). *@vijaypjavvadi/bdd2pw: Live-DOM Page Object Scaffolding from Gherkin Specifications via the Microsoft Playwright MCP* (Version 4.0.1) [Computer software]. Zenodo. https://doi.org/10.5281/zenodo.21050268
464
-
465
- (v4.0.2 is a documentation-only patch on top of the v4.0.1 artifact; cite v4.0.1 for reproducibility.)
466
-
467
- A machine-readable [`CITATION.cff`](CITATION.cff) file is included in the repository root.
468
-
469
- ## License
470
-
471
- MIT
1
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.21050268.svg)](https://doi.org/10.5281/zenodo.21050268)
2
+
3
+
4
+ # bdd2pw — Gherkin `.feature` → Playwright TypeScript scaffold
5
+
6
+ # @vijaypjavvadi/bdd2pw
7
+
8
+ [![npm version](https://img.shields.io/npm/v/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
9
+ [![npm downloads](https://img.shields.io/npm/dm/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
10
+ [![npm total downloads](https://img.shields.io/npm/dt/@vijaypjavvadi/bdd2pw.svg)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
11
+ [![license](https://img.shields.io/npm/l/@vijaypjavvadi/bdd2pw.svg)](https://github.com/javvadivijayprasad/bdd2pw/blob/main/LICENSE)
12
+ [![Listed in Awesome Playwright](https://awesome.re/mentioned-badge.svg)](https://github.com/mxschmitt/awesome-playwright)
13
+
14
+ > Scaffold runnable Playwright TypeScript tests from Gherkin `.feature` files. Auto-detects existing Page Objects, scans live pages via Microsoft Playwright MCP, emits POMs and specs ready for execution. CLI + HTTP service.
15
+
16
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
17
+ [![Node](https://img.shields.io/badge/node-%E2%89%A518-brightgreen?logo=node.js)](https://nodejs.org/)
18
+ [![npm](https://img.shields.io/npm/v/@vijaypjavvadi/bdd2pw.svg?label=npm)](https://www.npmjs.com/package/@vijaypjavvadi/bdd2pw)
19
+ [![Tests](https://img.shields.io/badge/tests-290%2B%20passing-brightgreen)](./tests)
20
+ [![Rules](https://img.shields.io/badge/rules-200%2B%20deterministic-brightgreen)](./src/transformers)
21
+ [![Domain packs](https://img.shields.io/badge/domain%20packs-7-blue)](./src/transformers/domains)
22
+ [![VS Code Marketplace](https://img.shields.io/visual-studio-marketplace/v/vijaypjavvadi.bdd2pw?label=vscode-extension)](https://marketplace.visualstudio.com/items?itemName=vijaypjavvadi.bdd2pw)
23
+
24
+ Most teams writing BDD test cases (via Cucumber `.feature` files, possibly authored by an LLM) face the same gap: the `.feature` describes the test, but **someone still has to write the Page Objects and the Playwright spec by hand**. That's the work `bdd2pw` does for you.
25
+
26
+ Point it at a `.feature` file and a URL. It parses the Gherkin, scans the live page with Chromium, picks the most stable locator for every interactive element, matches each step to a POM method call, and emits a runnable Playwright TypeScript repo — including `playwright.config.ts`, `pages/login.page.ts`, `tests/login.spec.ts`, and a `BDD_REVIEW.md` listing anything a human still needs to look at.
27
+
28
+ ## What `bdd2pw` is and isn't (as of v4.4.0)
29
+
30
+ `bdd2pw` is a **deterministic scaffolder with an optional governed LLM fallback across three providers**. The output is honest about its limits:
31
+
32
+ - **Specific `.feature` files** — quoted credentials, concrete assertion targets, standard verb forms — convert to **runnable specs with zero hand-edits**. Validated end-to-end against 8 public benchmark applications (`practicetestautomation.com`, `owasp-juice-shop`, SauceDemo, the-internet, OpenCart, Magento, Conduit, Reqres): 8/8 compilation across deterministic and LLM-governed modes.
33
+ - **Vague `.feature` files** — "Enter valid username and password and click login button" with no quoted values — get partial coverage. Unmatched steps either route to the LLM fallback (when an Anthropic / OpenAI / Gemini key is configured) or land as `// TODO` comments + warnings in `BDD_REVIEW.md`.
34
+ - **200+ deterministic rules**, organised across three layers:
35
+ - **API rules** (v3.0+) — `page.request.*` patterns for GET / POST / PUT / DELETE / PATCH, body / header / status assertions.
36
+ - **Visibility rules** (v3.1+) — `<noun> is visible / displayed / shown / appears` intercepts before URL-slug heuristics, so prose like "the user's name or profile indicator is visible in the UI" never gets slugified into a URL regex.
37
+ - **UI + URL rules** (v1.x lineage, refined through v3.7.1) — 30+ rules covering first-person, third-person, no-subject Cucumber dialects + compound input steps.
38
+ - **7 opt-in domain rule packs** (v3.4 + v3.8) — banking, healthcare, insurance, retail, gov, education, telecom. Each adds ~20 industry-specific patterns. Activated via `domains: ["banking"]`; empty by default for byte-stable existing behaviour.
39
+ - **Three-provider LLM fallback, batched per scenario** (v3.5 + v3.11 + v3.12) — one Anthropic Claude Sonnet 4.6, OpenAI gpt-4o-mini, or Google Gemini 2.5 Flash call per scenario instead of one per unmatched step. ~75% cost reduction on unmatched-heavy scaffolds. Every prompt goes through the `ai-governance` sidecar's `/sanitize` endpoint (fail-closed on 4xx/5xx/timeout — the run terminates rather than emit ungoverned code).
40
+ - **Three hallucination-rejection gates on LLM output** (v4.0.1) — invented-helper detection, structured-pomCall guard, and bare-field-call trap. Bindings the LLM emits that would compile-fail land as `// TODO` comments with `BDD_REVIEW.md` entries instead of broken code. Locked by 19 dedicated unit tests.
41
+ - **Six-pattern LLM-binding rewriter** (v4.1) — mechanically transforms common LLM emission mistakes (invented-helper shapes, bare-field args, unquoted string values, CSS-selector args, `page.<method>` invented-helpers in customBody, Locator-only matchers hallucinated on `page`, bare-identifier assertion locators) into valid Playwright-idiomatic code. Runs *before* the v4.0.1 gates; if a rewrite would still produce broken code, the binding is rejected and lands as TODO. Bench result: 3/8 → **8/8 apps produce specs that pass `tsc --noEmit`**. Locked by 35 unit tests.
42
+ - **DOM-drift detection via POM header hash** (v4.2) — every emitted POM carries a `@bdd2pw dom-hash` comment with a stable sha256 of the page's accessibility tree. On re-scaffold, bdd2pw diffs the new snapshot against the stored hash. Silent UI changes surface as a `DOM DRIFT` warning in `BDD_REVIEW.md` with both hashes and a suggested triage path. `--fail-on-drift` turns it into a non-zero exit code so CI can gate merges on silent UI regressions.
43
+ - **In-process self-healing locators via `@vijaypjavvadi/pw-self-heal`** (v4.3) — `--self-healing` emits a 3-line `tests/fixtures.ts` that wraps the base `test` with `withSelfHealing({ mode })`. Every spec's top-of-file import auto-rewrites to pull `test` + `expect` from `./fixtures` instead of `@playwright/test` directly. POM classes are unchanged; healing is transparent. Ranker: trained ONNX model with a published Zenodo DOI ([10.5281/zenodo.19684439](https://doi.org/10.5281/zenodo.19684439)), GB AUC 0.9993, three modes (`heuristic` / `ml` / `hybrid`). No server, no API key, no Python — the DOM never leaves the machine.
44
+ - **Legible provenance — `@llm-generated` tag + rule attribution + two report CLIs** (v4.4) — every emitted step records which rule (or which LLM provider + model) produced it in `*.spec.meta.json`. A scenario with an LLM-bound step gets the `@llm-generated` tag so `npx playwright test --grep-invert @llm-generated` runs the trusted lane. `bdd2pw quarantine-stats` reports scenarios / steps / cache-hit share / promotions per lane. `bdd2pw coverage` turns the same data into decisions: rule hit rate, dead rules, dead packs, promotion trail (candidate → rule → firing), and heal pressure. Both write JSON sidecars with a shared shape. Both are reports, not gates.
45
+ - **Data-driven scaffolds** (v4.0.0) — `--data <path>` injects CSV / JSON / XLSX rows into every Scenario Outline's `Examples:` table; `--gen-data --schema <path> --rows N` generates synthetic rows via Faker + optional per-column LLM calls (`llm:auto insurance claim description`); seeded (`--seed 42`) for reproducibility.
46
+ - **`updatePom` is append-only by construction.** Re-scanning a page that already has a Page Object adds new locators only. Hand-edited method bodies, custom helper methods, custom imports are all preserved byte-identical.
47
+ - **`--merge` mode** (v3.2) preserves `// bdd2pw:user-block id="..."` sections across regenerations so iterative locator tuning doesn't lose work.
48
+ - **Reproducible benchmark harness** (v4.0.0) — `bench/runner.ts` scaffolds all 8 benchmark apps in three modes (deterministic-only, LLM-blocked, LLM-governed) with per-app sha256 verification. Public artifact accompanying the SoftwareX manuscript.
49
+
50
+ > **The pitch.** Run `bdd2pw scaffold` and you get a Playwright TS repo where `npx playwright test` runs against the real site. For specific fixtures, all green. For vague ones, the 60-90% you'd otherwise hand-write is done; you finish the rest — or you let the governed LLM finish them.
51
+
52
+ ## What's new in v4.0.0
53
+
54
+ - **NEW** `--data <path>` — load CSV / JSON / XLSX file and inject rows into every Scenario Outline's Examples table. Drop in a 500-row dataset without touching the .feature file.
55
+ - **NEW** `--gen-data --schema <path> --rows N` — generate synthetic Examples rows. Schema picks per-column source: `faker.internet.email` for common fields, `llm:auto insurance claim description` for context-aware domain data. Seeded for reproducibility (`--seed 42`).
56
+ - **NEW** `LLMClient.generateText()` — generic single-prompt API on all three providers (Anthropic, OpenAI, Gemini). Same governance + budget + timeout + telemetry pipeline as binding generation.
57
+ - Gemini provider — three-provider parity complete. `--llm gemini` defaults to `gemini-2.5-flash` ($0.10/M input — cheapest across all three providers). (v3.12.0)
58
+ - OpenAI provider with full parity. `--llm openai` defaults to `gpt-4o-mini`. (v3.11.0)
59
+ - `bdd2pw heal-stats <repo>` CLI reads `<repo>/artefacts/heal-events.jsonl` and writes a heal-stats.json sidecar with heal rate, top failing fields, retry latency, candidate-selector promotions (v3.10.0).
60
+ - `llmStats: true` writes `<repo>/artefacts/llm-stats.json` with per-call latency, token counts, cache hit rate, and an estimated cost in USD (v3.9.0).
61
+ - Seven domain rule packs (banking, healthcare, insurance, retail, gov, education, telecom) — ~140 industry-specific patterns total.
62
+ - Per-scenario LLM batching cuts Anthropic spend by ~75% on unmatched-heavy scaffolds.
63
+ - `bdd2pw propose-rules` CLI clusters past LLM bindings into draft regex proposals — turning the offline-review pipeline into one command.
64
+ - `diagnostics: true` adds a "Rule trace" block to `BDD_REVIEW.md` showing exactly which rules declined a step and why.
65
+ - `merge: true` preserves user-edited blocks across regenerations.
66
+ - `metaSidecar: true` writes `<spec>.spec.meta.json` describing every step's semantic intent for downstream tools.
67
+ - VS Code extension (`vijaypjavvadi.bdd2pw`) v0.2.0 surfaces all the above as settings + commands.
68
+
69
+ ## Where this fits in the platform
70
+
71
+ | Stage | Service | Role |
72
+ |---|---|---|
73
+ | 1. Generate | `test-case-generation-service` (FastAPI :4100) | Author `.feature` files from requirements |
74
+ | **1.5. Scaffold** | **`bdd2pw` (this repo) — Express :4300 + CLI** | `.feature` + URL → POM + spec, ready to run |
75
+ | 2. Migrate | [`@vijaypjavvadi/sel2pw`](https://github.com/javvadivijayprasad/sel2pw) (Express :4200) | Legacy Selenium → Playwright |
76
+ | 3. Stabilise | `self-healing-stage-services` (FastAPI :8003) | Heal locators at runtime |
77
+ | 4. Govern | `ai-governance` (Python lib + sidecar :8004) | Sanitise every LLM payload (when v1.1 LLM fallback ships) |
78
+ | Orchestrate | `modern-automation-platform` (Express :3000) | Auth, jobs, UI, artifacts |
79
+
80
+ `bdd2pw` and `sel2pw` are siblings. Both consume **`@vijaypjavvadi/pw-emit`** (the shared emitter library), so the Page Objects produced by one are byte-identical in shape to those produced by the other.
81
+
82
+ ## Install
83
+
84
+ ```bash
85
+ npm install -D @vijaypjavvadi/bdd2pw
86
+ npx playwright install chromium # browser for live page discovery
87
+ ```
88
+
89
+ Node ≥ 18. Cross-platform (Linux / macOS / Windows). `playwright` is an optional dep — if you don't install browsers, pass `--snapshot-file <path.json>` instead.
90
+
91
+ ## Quick start
92
+
93
+ ```bash
94
+ # Scaffold a runnable Playwright TS project from a .feature file
95
+ npx bdd2pw scaffold path/to/login.feature \
96
+ --url https://your-app.example.com/login \
97
+ --page LoginPage \
98
+ --repo ./my-tests
99
+
100
+ cd ./my-tests
101
+ npm install
102
+ npx playwright test
103
+ ```
104
+
105
+ That's it. `./my-tests` now has `pages/login.page.ts`, `tests/login.spec.ts`, `playwright.config.ts`, `package.json`, `tsconfig.json`, `.gitignore`, and `BDD_REVIEW.md`.
106
+
107
+ ## Examples
108
+
109
+ Two end-to-end fixtures live under `examples/` — each has the input `.feature`,
110
+ the live-page snapshot, and (via `tests/e2e/*.test.ts`) regression guards that
111
+ pin the exact `pages/<name>.page.ts` + `tests/<name>.spec.ts` the pipeline must
112
+ emit:
113
+
114
+ - [`examples/practice-test-login`](examples/practice-test-login) — login flow on
115
+ practicetestautomation.com (6 scenarios: positive + negative + outline + security)
116
+ - [`examples/cms-login`](examples/cms-login) — login flow on a real OSS CMS demo
117
+ (third-person Cucumber dialect, compound input steps)
118
+
119
+ ### What bdd2pw emits
120
+
121
+ Given a `.feature` file plus a live URL, `scaffold()` writes two files per
122
+ feature into your target repo:
123
+
124
+ ```
125
+ pages/<name>.page.ts ← POM class with locators picked from the live DOM
126
+ tests/<name>.spec.ts ← Playwright test spec that imports and uses the POM
127
+ ```
128
+
129
+ **Locator picker preference order:**
130
+ `getByRole` → `getByLabel` → `getByTestId` → `locator("#id")`
131
+
132
+ The picker falls back to the next option only when the a11y snapshot carries no
133
+ accessible name/role for the element. For the `practice-test-login` fixture, this
134
+ means `submitButton` picks `getByRole("button", { name: "Submit" })` while the
135
+ inputs land on `locator("#username")` / `locator("#password")` (the demo site's
136
+ inputs have no `<label>` association).
137
+
138
+ See [`tests/e2e/practiceTestLogin.test.ts`](tests/e2e/practiceTestLogin.test.ts)
139
+ for the full assertion of what the emitted POM + spec must contain.
140
+
141
+ > **Note on Phase 1a vs 1b.** The fixtures under `examples/` use hand-authored
142
+ > a11y snapshots (Phase 1a regression fixtures). The real `@playwright/mcp`
143
+ > integration (Phase 1b) captures the live DOM at scaffold time and eliminates
144
+ > the hand-authoring. The Phase 1b path lives in `src/` and is documented in
145
+ > the SoftwareX paper (DOI [10.1016/j.softx.2026.102933](https://doi.org/10.1016/j.softx.2026.102933)).
146
+
147
+ ## LLM fallback (v2.0+)
148
+
149
+ When a Gherkin step doesn't match any of bdd2pw's 30 deterministic rules, you can opt-in to an Anthropic-backed LLM fallback that produces the binding instead of dropping to `// TODO`. Off by default.
150
+
151
+ ```bash
152
+ # Anthropic API key — required when --llm anthropic is set
153
+ export ANTHROPIC_API_KEY=sk-ant-api03-...
154
+
155
+ bdd2pw scaffold ./my.feature \
156
+ --url https://app.example.com \
157
+ --page LoginPage \
158
+ --repo ./out \
159
+ --llm anthropic \
160
+ --governance-url http://localhost:4900
161
+ ```
162
+
163
+ Every successful LLM-binding is appended to `<repo>/artefacts/candidate-rules.jsonl` so an offline review pipeline can propose new deterministic rules. Auto-write back to `stepMatcher.ts` is deferred to v2.1+ — for v2.0 the LLM is a runtime overlay, never a code generator for the matcher itself.
164
+
165
+ ### Two-lane runs — trusted vs review (v4.4+)
166
+
167
+ A scenario in which at least one step was bound by the LLM fallback is emitted with a `@llm-generated` tag next to its existing tags. That lets Playwright's own `--grep`/`--grep-invert` filter split every run into two lanes with zero framework wiring:
168
+
169
+ ```bash
170
+ # Trusted lane — only scenarios whose every step was rule-bound
171
+ npx playwright test --grep-invert @llm-generated
172
+
173
+ # Review lane — only the scenarios that used the LLM fallback
174
+ npx playwright test --grep @llm-generated
175
+ ```
176
+
177
+ Per-step provenance lives in the sidecar `<spec>.spec.meta.json` next to the emitted spec. LLM-bound steps carry `"rule": null` plus an `"llm": { provider, model, cached, governance, at }` block; rule-bound steps carry neither field. Everything the tag hides at scenario level is inspectable at step level.
178
+
179
+ Aggregate a scaffolded repo with:
180
+
181
+ ```bash
182
+ npx bdd2pw quarantine-stats ./my-tests # table + writes artefacts/quarantine-stats.json
183
+ npx bdd2pw quarantine-stats ./my-tests --json # machine-readable, same shape as the file
184
+ ```
185
+
186
+ Sample table output:
187
+
188
+ ```
189
+ scenarios: 24 total · 21 deterministic · 3 @llm-generated
190
+ steps: 58 total · 55 by rule · 3 by LLM
191
+ LLM cache hit share: 66.7%
192
+
193
+ promotions: 2/9 candidate step(s) now rule-bound
194
+ ```
195
+
196
+ The `promotions` line is the story: candidate step-texts recorded in `artefacts/candidate-rules.jsonl` from earlier runs that no longer need the LLM because a deterministic rule now covers them. That number going up is the point of running the LLM at all — a scaffold, then a rule, then no LLM.
197
+
198
+ `quarantine-stats` is a report, not a gate. It exits 0 on every clean read and only fails with a non-zero code on a real I/O error against the repo root. Wire it into your CI dashboard, don't wire it into your merge gate.
199
+
200
+ ### Rule + pack coverage (v4.4+)
201
+
202
+ Slice 1 tells you which lane a step is in. Coverage tells you which rules earned their place in the table:
203
+
204
+ ```bash
205
+ npx bdd2pw coverage ./my-tests --domains banking,retail
206
+ npx bdd2pw coverage ./my-tests --json
207
+ npx bdd2pw coverage ./my-tests --suggest-retire
208
+ ```
209
+
210
+ The report answers four things:
211
+
212
+ - **rule hit rate** — for every rule that fired, how many steps it bound, plus up to 3 sample step texts.
213
+ - **dead rules / dead packs** — every rule in the current registry that did NOT fire in this repo, and every domain pack whose rules were all dead. "Dead here" is a repo-scoped observation, not a global verdict on the rule.
214
+ - **promotion trail** — same field as `quarantine-stats`. Candidate steps recorded by past LLM fallbacks that are now bound by a rule.
215
+ - **heal pressure** — top locators from `artefacts/heal-events.jsonl` (or `.pwheal/heal-events.jsonl` when running with the v4.3 in-process healer). A rule that binds and then always needs healing is worse than no rule.
216
+
217
+ `--suggest-retire` prints a copyable stanza listing the dead packs and dead rules; it never edits `stepMatcher.ts` or your bdd2pw config. Paste the parts you want to apply.
218
+
219
+ The `totals` and `promotions` blocks in `coverage.json` are byte-identical to the same-named blocks in `quarantine-stats.json`, so a dashboard reading either one gets the same numbers.
220
+
221
+ ### Governance sanitization (mandatory by default)
222
+
223
+ Per the platform contract, **every prompt passes through the `ai-governance` sidecar's `/sanitize` endpoint** before reaching Anthropic. This scrubs API keys, JWTs, AWS creds, and other secrets that might leak via test data in the `.feature` file. **Fail-closed** — if the sidecar is unreachable, the LLM call is REFUSED and the step falls back to TODO.
224
+
225
+ Two ways to satisfy this:
226
+
227
+ **(a) Internal platform users:** the `ai-governance` service is part of your platform service mesh. Just point bdd2pw at it (`--governance-url http://ai-governance:4900` or wherever).
228
+
229
+ **(b) External users:** run your own sidecar.
230
+
231
+ ```bash
232
+ # Clone and run the sidecar
233
+ git clone https://github.com/javvadivijayprasad/ai-governance
234
+ cd ai-governance
235
+ python -m venv .venv && .\.venv\Scripts\Activate.ps1 # or `source .venv/bin/activate` on Mac/Linux
236
+ pip install fastapi uvicorn pydantic pyyaml
237
+ PYTHONPATH=src uvicorn service.app:app --port 4900
238
+ ```
239
+
240
+ Or there's a Docker image once it's published: `docker run -p 4900:4900 ghcr.io/javvadivijayprasad/ai-governance:latest`.
241
+
242
+ **Test-only escape hatch:** `--llm-skip-governance` bypasses the sidecar entirely. Use only when your `.feature` data is synthetic (no real credentials, no PII). For production, **always** keep governance on.
243
+
244
+ ```bash
245
+ # UNSAFE for real test data — use only with synthetic fixtures
246
+ bdd2pw scaffold ./my.feature ... --llm anthropic --llm-skip-governance
247
+ ```
248
+
249
+ ### Cost + determinism guardrails
250
+
251
+ | Flag | Default | Purpose |
252
+ |---|---|---|
253
+ | `--llm-max-calls <n>` | `50` | Hard cap on provider calls per scaffold. Cache hits don't count. |
254
+ | `--llm-cache <path>` | `<repo>/.bdd2pw/llm-cache.sqlite` | SQLite cache keyed by step text + POM signature + model. Same inputs across runs return the same binding — cost goes to zero on re-runs. Pass `:memory:` for one-shot use. |
255
+ | `--llm-model <model>` | `claude-sonnet-4-6` | Override the Anthropic model. |
256
+
257
+ Re-runs of the same `.feature` (after a code edit, retry, etc.) will hit the cache and make zero provider calls. A typical per-scaffold cost on first run: ~$0.005–0.02 USD with Sonnet, depending on how many steps need LLM fallback.
258
+
259
+ ### Cloud-jobs deployment recipe
260
+
261
+ If you're running bdd2pw in an automation pipeline (cloud-jobs-template, GitHub Actions, etc.):
262
+
263
+ ```yaml
264
+ env:
265
+ ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} # platform secrets store
266
+
267
+ steps:
268
+ - name: Run scaffold with LLM fallback
269
+ run: |
270
+ bdd2pw scaffold "$FEATURE_FILE" \
271
+ --url "$TARGET_URL" \
272
+ --page "$PAGE_NAME" \
273
+ --repo /work \
274
+ --self-healing \
275
+ --llm anthropic \
276
+ --governance-url http://ai-governance:4900
277
+ ```
278
+
279
+ Make sure the `ai-governance` sidecar is co-located (k8s sidecar pattern) or reachable on the platform service mesh.
280
+
281
+ ## CLI surface — three commands
282
+
283
+ ### `scaffold` — generate a fresh repo
284
+
285
+ ```bash
286
+ bdd2pw scaffold <feature> --url <url> --page <Name> --repo <dir> [options]
287
+ ```
288
+
289
+ Reads the `.feature`, scans the URL with Chromium, picks locators, matches steps, emits the project. Flags:
290
+
291
+ ```
292
+ --snapshot-file <path> Use a captured JSON snapshot instead of launching a browser
293
+ --no-discovery Skip page discovery entirely (rule-only probing)
294
+ --storage-state <path> Pre-authenticated storage state JSON
295
+ --headed Show browser during scan
296
+ --templates <dir> Override default project templates
297
+ --dry-run Print plan, write nothing
298
+ --no-validate Skip tsc --noEmit step
299
+ --force Overwrite existing spec files
300
+ ```
301
+
302
+ ### `analyze` — dry-run the matcher
303
+
304
+ ```bash
305
+ bdd2pw analyze <feature> --url <url> [options]
306
+ ```
307
+
308
+ Same pipeline but writes nothing — prints the parsed feature, the discovered locators, and the planned step bindings as JSON. Useful for "what would scaffold do?" probing.
309
+
310
+ ### `update-pom` — merge new locators into an existing POM
311
+
312
+ ```bash
313
+ bdd2pw update-pom --page <Name> --url <url> --repo <dir> [options]
314
+ ```
315
+
316
+ Re-scan the page and **append** any newly-discovered locators to the existing Page Object. Never touches existing fields, methods, or specs. Hand-edited method bodies survive byte-identical.
317
+
318
+ ## HTTP service
319
+
320
+ `bdd2pw serve` starts an Express service on `:4300` with the same three commands as REST endpoints. Mirror of the CLI; HTTP is a thin shell.
321
+
322
+ ```bash
323
+ bdd2pw serve --port 4300
324
+
325
+ # In another terminal:
326
+ curl -X POST http://localhost:4300/scaffold \
327
+ -H 'content-type: application/json' \
328
+ -d '{"feature":"/abs/path/to/login.feature","url":"https://...","page":"LoginPage","repo":"unused","options":{"snapshotFile":"/abs/snapshot.json","noValidate":true}}'
329
+ # → 202 Accepted: {"jobId":"01HX...","links":{"self":"/jobs/01HX...","artifact":"/jobs/01HX.../artifact"}}
330
+
331
+ curl http://localhost:4300/jobs/01HX... # poll for completion
332
+ curl -O http://localhost:4300/jobs/01HX.../artifact # download zip
333
+ ```
334
+
335
+ | Endpoint | Purpose |
336
+ |---|---|
337
+ | `GET /healthz`, `/version`, `/readyz` | Liveness probes |
338
+ | `POST /scaffold`, `/analyze`, `/update-pom` | Async job — returns `202` + `jobId` |
339
+ | `GET /jobs/:id` | Job status / progress / result |
340
+ | `GET /jobs/:id/artifact` | Stream zip of the scaffolded repo |
341
+ | `GET /jobs/:id/log` | Plain-text dump of warnings + errors |
342
+
343
+ In production, the platform gateway proxies `/api/v1/scaffold/*` to `:4300`. Direct port exposure is local-dev only.
344
+
345
+ ## Pipeline
346
+
347
+ ```
348
+ .feature file
349
+ │
350
+ ▼
351
+ ┌──────────────┐
352
+ │ gherkinParser│ @cucumber/gherkin → FeatureIR (scenarios, background, examples)
353
+ └──────┬───────┘
354
+ ▼
355
+ ┌──────────────┐
356
+ │ repoScanner │ ts-morph → existing pages/*.page.ts → Map<class, IR>
357
+ └──────┬───────┘
358
+ ▼
359
+ ┌──────────────┐
360
+ │ pomResolver │ CREATE / AUGMENT / REUSE decision
361
+ └──────┬───────┘
362
+ ▼
363
+ ┌──────────────┐
364
+ │ scanPage │ playwright chromium → DOM walk → ElementIR[]
365
+ │ │ (or --snapshot-file / --no-discovery fallbacks)
366
+ └──────┬───────┘
367
+ ▼
368
+ ┌──────────────┐
369
+ │ locatorPicker│ getByRole > getByLabel > getByPlaceholder > getByTestId
370
+ │ │ > getByText > css > xpath
371
+ │ │ Status-region special case + dedup by (api, args)
372
+ └──────┬───────┘
373
+ ▼
374
+ ┌──────────────┐
375
+ │ stepMatcher │ 30 rules — subject-agnostic, dialect-tolerant,
376
+ │ │ compound-input via customBody
377
+ └──────┬───────┘
378
+ ▼
379
+ ┌──────────────┐
380
+ │ pw-emit │ @vijaypjavvadi/pw-emit → POM TS + spec TS + project scaffold
381
+ └──────┬───────┘
382
+ ▼
383
+ ┌──────────────┐
384
+ │ tscRunner │ Optional tsc --noEmit → diagnostics into BDD_REVIEW.md
385
+ └──────┬───────┘
386
+ ▼
387
+ output/
388
+ pages/<name>.page.ts
389
+ tests/<name>.spec.ts
390
+ playwright.config.ts
391
+ package.json, tsconfig.json, .gitignore
392
+ BDD_REVIEW.md ← warnings + manual TODOs
393
+ ```
394
+
395
+ ## What `bdd2pw` covers
396
+
397
+ ### Step matcher rules (14)
398
+
399
+ | # | Pattern | Emits |
400
+ |---|---|---|
401
+ | 1 | `(I/user) am on/navigate to/visit/open <X>` (with or without quoted URL) | `goto()` |
402
+ | 2a | `(I/user) enter "<value>" into <field>` | `<field>.fill("<value>")` |
403
+ | 2b | `(I/user) enter <field> "<value>"` | `<field>.fill("<value>")` |
404
+ | 2c | **Compound:** `(I/user) enter <f1> "<v1>" <f2> "<v2>" ...` | N `.fill()` lines |
405
+ | 3 | `(I/user/-) click/press/tap <X> button/link/icon/tab` | `<field>.click()` (or POM method if defined) |
406
+ | 4 | `(I/user) select "<opt>" from <dropdown>` | `<field>.selectOption(...)` |
407
+ | 5 | `(I/user) check/uncheck <checkbox>` | `<field>.check()` / `.uncheck()` |
408
+ | 6 | `(I/user) (should) see <X>` | `expect(<X>).toBeVisible()` |
409
+ | 7 | `(I/user) should not see <X>` | `expect(<X>).toBeHidden()` |
410
+ | 8 | `(I/user) should see (the/an/a) error message "<X>"` | `expect(<errorField>).toContainText("<X>")` |
411
+ | 9a | `(I/user) should see <X> containing/with text "<Y>"` | `expect(<X>).toContainText("<Y>")` |
412
+ | 9b | `(I/user) should see <X> "<Y>"` (exact equality) | `expect(<X>).toHaveText("<Y>")` |
413
+ | 10 | `(I/user) should remain on <page>` | `expect(page).toHaveURL(/<page>/)` |
414
+ | 11 | `(I/user) (should be/is) redirected to <page>` | `expect(page).toHaveURL(/<page>/)` |
415
+ | 12 | `the <field> field should be of type "<type>"` | `expect(<field>).toHaveAttribute("type", "<type>")` |
416
+ | 13 | `the (current) URL should start with/contain "<X>"` | `expect(page).toHaveURL(/^<X>/)` |
417
+
418
+ ### Cucumber features
419
+
420
+ - `Background:` → `test.beforeEach`
421
+ - `Scenario Outline:` + `Examples:` → one `test()` per row, with placeholder substitution
422
+ - `Tags` → emitted as `// @tag` comments above each test
423
+ - Doc strings + data tables — preserved on `StepIR.argument`
424
+
425
+ ### Locator priority
426
+
427
+ `getByRole` (with accessible name) > `getByLabel` > `getByPlaceholder` > `getByTestId` > `getByText` > CSS > xpath. **Status regions** (`<div id="error">`, `[role=alert]`, `[class*=notification]`) bypass the visibility filter (they're hidden until triggered) and use their `id` for both field name and locator (text content is volatile, id is stable).
428
+
429
+ ## Verification
430
+
431
+ | Check | Status |
432
+ |---|---|
433
+ | `npm run lint` | ✅ clean |
434
+ | `tsc --noEmit` | ✅ clean |
435
+ | `npm test` (vitest) | ✅ **101/101 green** across 10 test files |
436
+ | `practice-test-login` end-to-end vs the live site | ✅ **7/7** scenarios green via `npx playwright test` |
437
+ | `cms-login` (selenium14 dialect) regression | ✅ 12 assertions green, third-person + compound input + `is redirected` |
438
+ | HTTP worker zip download | ✅ end-to-end test verifies real ZIP magic bytes |
439
+ | `update-pom` preserves hand-edited method bodies | ✅ 5 byte-identical-survival assertions |
440
+
441
+ ## Roadmap
442
+
443
+ ### Shipped (Aug 2025 → May 2026)
444
+
445
+ | Version | Theme | Highlight |
446
+ |---|---|---|
447
+ | v1.0 | Foundation | Gherkin → Playwright TS scaffolding, POM resolver, file-snapshot discovery, HTTP worker service on `:4300`, `update-pom` AST surgery |
448
+ | v1.1 | Self-healing | `--self-healing` flag, `lib/heal.ts` template, JSONL event logging |
449
+ | v2.0 | LLM fallback | Anthropic SDK integration, governance sidecar `/sanitize`, SQLite step-binding cache, opt-in via `--llm anthropic` |
450
+ | v2.2 | Reliability | Promise.race watchdogs, ai-governance fail-closed, structured pino logging end-to-end |
451
+ | v3.0 | API testing | Native `page.request.*` patterns (~17 rules), tag-driven `@api` / `@ui` scenario state injection |
452
+ | v3.1 | TestForge P0+P1 | Visibility-prose intercept, `:root` locator rejection, `testInfo` in test signature, opt-in step hooks + boundary markers |
453
+ | v3.2 | Iteration UX | `playwright.config.ts` end-marker, exact-dep pinning, `*.spec.meta.json` sidecar, JSON scenarios input, `--merge` mode preserving `// bdd2pw:user-block` sections |
454
+ | v3.3 | Hook signature | `fixtures` arg + `status` + try/catch/finally wrapping for `beforeStep` / `afterStep` |
455
+ | v3.4 | Domain packs | Banking / healthcare / insurance opt-in rule packs (~60 new patterns) |
456
+ | v3.5 | LLM batching | One Anthropic call per scenario instead of N — ~75% cost reduction on unmatched-heavy scaffolds |
457
+ | v3.6 | Diagnostics + auto-rules | Rule-trace block in `BDD_REVIEW.md`; new `bdd2pw propose-rules` CLI clustering candidate-rules.jsonl into draft regex |
458
+ | v3.7.1 | Regression fixes | PascalCase className shadow fix; `test.step` wrapping regression-asserted |
459
+ | v3.8.1 | More domain packs | Retail / gov / education / telecom packs added — seven total (~140 industry-specific rules) |
460
+ | v3.9.0 | Telemetry | `artefacts/llm-stats.json` sidecar — per-call latency + tokens + cache hit rate + estimated cost. Makes v3.5 batching ROI measurable per scaffold. |
461
+ | v3.10.0 | Heal stats | `bdd2pw heal-stats <repo>` CLI consumes `artefacts/heal-events.jsonl` and writes `heal-stats.json` with heal rate, top failing fields, top error patterns, retry latency, candidate-selector promotions. Self-healing ROI per test run. |
462
+ | v3.11.0 | OpenAI provider | `LLMClientOptions.provider: "openai"` lands with cache + governance + batching + telemetry parity. Default model `gpt-4o-mini` (~17x cheaper than `gpt-4o` for structured-JSON tasks). |
463
+ | v3.12.0 | Gemini provider | `LLMClientOptions.provider: "gemini"` lands with full parity. Default model `gemini-2.5-flash` ($0.10/M input — cheapest across all three providers). Three-provider parity complete. |
464
+ | v4.0.0 | Data-driven scaffolds | `--data <path>` (CSV/JSON/XLSX) and `--gen-data --schema <path>` (Faker + LLM) inject Examples rows into Scenario Outlines. `LLMClient.generateText()` added to all three providers. **Additive only — no breaking changes.** |
465
+ | v4.0.1 | LLM hallucination gates | Three-layer rejector for invented POM helpers — bindings that would compile-fail land as TODO instead of broken code. 19 unit tests lock the behaviour. |
466
+ | v4.1.0 | LLM binding rewriter | Six-pattern rewriter that mechanically fixes common LLM emission mistakes (invented helpers, bare-field args, CSS-selector args, `page.<method>` in customBody, hallucinated Page matchers, bare-identifier assertion locators). Bench result: 3/8 → **8/8 apps produce specs that pass `tsc --noEmit`**. Peer-reviewed publication in Elsevier SoftwareX. |
467
+ | v4.2.0 | DOM-drift detection | Every emitted POM carries a `@bdd2pw dom-hash` header (sha256 of the accessibility tree). Re-scaffold diffs against the stored hash and surfaces silent UI changes in `BDD_REVIEW.md`. `--fail-on-drift` CLI flag exits non-zero when drift is detected (CI merge gate). |
468
+ | v4.3.0 | pw-self-heal integration | `--self-healing` swaps the v4.2 lib/heal.ts + external service shim for `@vijaypjavvadi/pw-self-heal` — trained ONNX ranker (Zenodo DOI 10.5281/zenodo.19684439), in-process, no server. Emits a 3-line `tests/fixtures.ts`; POM classes unchanged. `--legacy-healing` keeps v4.2 behaviour for one release. |
469
+ | **v4.4.0 (current)** | Legible provenance | `@llm-generated` scenario tag + rule/pack attribution recorded in `*.spec.meta.json`. Two report CLIs: `bdd2pw quarantine-stats` splits the suite into trusted vs review lanes; `bdd2pw coverage` reports rule hit rate, dead rules, dead packs, promotion trail, and heal pressure. Reports, not gates. |
470
+
471
+ ### Next 6 months (Oct 2026 → Mar 2027, ~1 release/month)
472
+
473
+ | Target | Version | Theme | Headline |
474
+ |---|---|---|---|
475
+ | Oct 2026 | **v4.5.0** | Mobile dialect | New `mobile` domain pack. Touch / swipe / scroll-into-view rules + responsive viewport assertions. Reuses the existing emitter pipeline; opt-in via `domains: ["mobile"]`. Scenarios tagged `@mobile` scaffold against a mobile device descriptor (Pixel 7 by default). |
476
+ | Nov 2026 | **v4.6.0** | sel2pw merge | sel2pw migrated onto `@vijaypjavvadi/pw-emit` — three packages share one emitter. All future emitter improvements automatically flow to Selenium users. |
477
+ | Nov 2026 | **v4.7.0** | Auto-rules | `bdd2pw apply-proposals --interactive` — walks the human through each v3.6 proposal, validates the regex compiles + matches the sample texts, optionally appends to `stepMatcher.ts`. Closes the propose-rules loop. |
478
+ | Dec 2026 | **v4.8.0** | Domain packs (3 more) | **fintech** (KYC, AML, trading desks), **real-estate** (MLS, listings, escrow), **hospitality** (PMS, reservations, OTA). ~60 more rules. |
479
+ | Jan 2027 | **v4.9.0** | API v2 | WebSocket assertion rules, multipart file-upload patterns, GraphQL query / mutation / subscription rules. Extends v3.0's API testing surface. |
480
+ | Feb 2027 | **v5.0.0** | CI/CD templates + default flips | Optional scaffolder output: GitHub Actions / GitLab CI / Azure Pipelines / CircleCI starter workflows wired to run the generated specs (opt-in via `--ci <provider>`). Bumps to v5 alongside a small set of default flips (llm-stats + healing become opt-out). Migration guide ships alongside. |
481
+
482
+ Each release is shaped to be self-contained, ship in ~2 weeks, and keep `domains: []` byte-stable for existing users so the upgrade path stays painless.
483
+
484
+ ## Documents
485
+
486
+ | Doc | Purpose |
487
+ |---|---|
488
+ | [`docs/SCOPE.md`](./docs/SCOPE.md) | What's in / out of v1.0, FR/NFR, CLI + HTTP surface, decisions log |
489
+ | [`docs/ARCHITECTURE.md`](./docs/ARCHITECTURE.md) | Component diagram, sequence diagrams, `pw-emit` contract, HTTP API contract, error model |
490
+ | [`docs/PHASE_0_PLAN.md`](./docs/PHASE_0_PLAN.md) | The pw-emit extraction plan (mostly historical now — it shipped) |
491
+ | [`docs/STATUS.md`](./docs/STATUS.md) | Verified state right now — what works, what's pending, what's deferred |
492
+ | [`CHANGELOG.md`](./CHANGELOG.md) | Full version history |
493
+
494
+ ## Community & project health
495
+
496
+ | Doc | Purpose |
497
+ |---|---|
498
+ | [`CONTRIBUTING.md`](./CONTRIBUTING.md) | Local dev, branching, PR conventions, your first contribution guide |
499
+ | [`CODE_OF_CONDUCT.md`](./CODE_OF_CONDUCT.md) | Contributor Covenant 2.1 — community standards + enforcement |
500
+ | [`SECURITY.md`](./SECURITY.md) | Supported-versions matrix, private vulnerability-reporting flow |
501
+ | [`SUPPORT.md`](./SUPPORT.md) | Where to ask different kinds of questions (bug / feature / discussion / security / consulting) |
502
+ | [`good first issue`](https://github.com/javvadivijayprasad/bdd2pw/labels/good%20first%20issue) | Scoped work a newcomer can land in a single session |
503
+ | [`help wanted`](https://github.com/javvadivijayprasad/bdd2pw/labels/help%20wanted) | Mid-size features the maintainer welcomes outside PRs on |
504
+
505
+ ## Citation
506
+
507
+ If you use `@vijaypjavvadi/bdd2pw` in academic work, please cite the
508
+ peer-reviewed SoftwareX paper (preferred) and the archived software
509
+ artifact (for exact-version reproducibility):
510
+
511
+ **Paper (preferred):**
512
+
513
+ > Javvadi, V. P. (2026). *bdd2pw: Live-DOM Page Object Scaffolding
514
+ > from Gherkin Specifications via the Microsoft Playwright MCP.*
515
+ > SoftwareX. https://doi.org/10.1016/j.softx.2026.102933
516
+
517
+ **Software artifact (reproducibility pin):**
518
+
519
+ > Javvadi, V. P. (2026). *@vijaypjavvadi/bdd2pw: Live-DOM Page Object
520
+ > Scaffolding from Gherkin Specifications via the Microsoft Playwright
521
+ > MCP* (Version 4.0.1) [Computer software]. Zenodo.
522
+ > https://doi.org/10.5281/zenodo.21050268
523
+
524
+ v4.0.2 and later are documentation + feature releases on top of the
525
+ v4.0.1 artifact; cite v4.0.1 for reproducibility. The paper's
526
+ experimental results were produced against v4.0.1.
527
+
528
+ A machine-readable [`CITATION.cff`](CITATION.cff) file is included in
529
+ the repository root; GitHub's "Cite this repository" button reads from
530
+ it automatically.
531
+
532
+ ## License
533
+
534
+ MIT