@orion-qa/orion 3.4.1 → 3.5.0

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 (68) hide show
  1. package/.claude/agents/change-agent.md +1 -1
  2. package/.claude/agents/requirement-analyst.md +1 -1
  3. package/.claude/agents/test-reporter.md +1 -1
  4. package/.claude/skills/appium/templates/project-java/src/test/java/automation/pageObjects/BaseScreen.java +36 -2
  5. package/.claude/skills/appium/templates/project-java/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
  6. package/.claude/skills/appium/templates/project-java/src/test/java/automation/utils/AutomationError.java +21 -0
  7. package/.claude/skills/automation-implementation/SKILL.md +1 -1
  8. package/.claude/skills/automation-implementation/references/patterns.md +14 -0
  9. package/.claude/skills/change-management/SKILL.md +1 -1
  10. package/.claude/skills/code-review/SKILL.md +1 -1
  11. package/.claude/skills/code-review/references/pattern-rules.md +4 -0
  12. package/.claude/skills/documentation/SKILL.md +2 -1
  13. package/.claude/skills/execution/SKILL.md +1 -0
  14. package/.claude/skills/orion/SKILL.md +6 -3
  15. package/.claude/skills/orion/references/conversation.md +1 -1
  16. package/.claude/skills/orion/references/project-context-files.md +3 -1
  17. package/.claude/skills/orion/references/setup-card.md +2 -1
  18. package/.claude/skills/orion/scripts/browser_setup.mjs +4 -4
  19. package/.claude/skills/orion/scripts/case_check.mjs +69 -0
  20. package/.claude/skills/orion/scripts/cases_coverage.py +179 -0
  21. package/.claude/skills/orion/scripts/cases_export.py +3 -0
  22. package/.claude/skills/orion/scripts/cases_model.py +256 -0
  23. package/.claude/skills/orion/scripts/context_guard.mjs +172 -0
  24. package/.claude/skills/orion/scripts/graph.mjs +112 -22
  25. package/.claude/skills/orion/scripts/lib/scan.mjs +8 -2
  26. package/.claude/skills/orion/scripts/report_make.mjs +15 -11
  27. package/.claude/skills/orion/scripts/run_state.mjs +4 -0
  28. package/.claude/skills/orion/scripts/screen_map.mjs +392 -0
  29. package/.claude/skills/orion/scripts/suite_check.mjs +1 -1
  30. package/.claude/skills/playwright/templates/dotnet/PageObjects/BasePage.cs +46 -0
  31. package/.claude/skills/playwright/templates/dotnet/Tests/Unit/UtilsTests.cs +10 -0
  32. package/.claude/skills/playwright/templates/dotnet/Utils/AutomationError.cs +19 -1
  33. package/.claude/skills/playwright/templates/javascript/pageObjects/basePage.js +52 -0
  34. package/.claude/skills/playwright/templates/javascript/reporters/summaryReporter.js +18 -9
  35. package/.claude/skills/playwright/templates/javascript/tests/unit/basePage.test.js +51 -0
  36. package/.claude/skills/playwright/templates/javascript/utils/errors.js +9 -2
  37. package/.claude/skills/playwright/templates/project/pageObjects/basePage.ts +54 -1
  38. package/.claude/skills/playwright/templates/project/reporters/summaryReporter.ts +18 -9
  39. package/.claude/skills/playwright/templates/project/tests/unit/basePage.test.ts +52 -0
  40. package/.claude/skills/playwright/templates/project/utils/errors.ts +12 -2
  41. package/.claude/skills/playwright/templates/python/page_objects/base_page.py +43 -0
  42. package/.claude/skills/playwright/templates/python/tests/unit/test_fail_fast_helpers.py +57 -0
  43. package/.claude/skills/playwright/templates/python/utils/errors.py +7 -3
  44. package/.claude/skills/requests/templates/python-pytest/src/services/api_client.py +11 -1
  45. package/.claude/skills/requests/templates/python-pytest/tests/unit/test_api_client.py +16 -0
  46. package/.claude/skills/requirement-analysis/references/test-case-import.md +9 -1
  47. package/.claude/skills/requirement-analysis/scripts/tm.py +422 -2
  48. package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/config/Flags.java +19 -0
  49. package/.claude/skills/rest-assured/templates/java-testng/src/test/java/automation/services/ApiSpec.java +10 -3
  50. package/.claude/skills/selenium/templates/csharp-nunit/PageObjects/BasePage.cs +89 -11
  51. package/.claude/skills/selenium/templates/csharp-nunit/Tests/Unit/UtilsTests.cs +10 -0
  52. package/.claude/skills/selenium/templates/csharp-nunit/Utils/AutomationError.cs +19 -1
  53. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/pageObjects/BasePage.java +65 -8
  54. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/tests/unit/UtilsTest.java +10 -0
  55. package/.claude/skills/selenium/templates/java-testng/src/test/java/automation/utils/AutomationError.java +21 -0
  56. package/.claude/skills/selenium/templates/python-pytest/page_objects/base_page.py +70 -11
  57. package/.claude/skills/selenium/templates/python-pytest/tests/unit/test_fail_fast_helpers.py +43 -0
  58. package/.claude/skills/selenium/templates/python-pytest/utils/errors.py +7 -3
  59. package/.claude/skills/test-design/SKILL.md +1 -1
  60. package/.claude/skills/test-reporting/SKILL.md +1 -0
  61. package/.claude/skills/ui-observation/SKILL.md +4 -1
  62. package/.claude-plugin/plugin.json +1 -1
  63. package/.cursor/rules/orion-quiet.mdc +13 -0
  64. package/AGENTS.md +1 -1
  65. package/README.md +2 -2
  66. package/bin/orion.mjs +5 -1
  67. package/hosts/gemini-extension/gemini-extension.json +1 -1
  68. package/package.json +2 -1
@@ -0,0 +1,392 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Shared screen memory: each screen's proven locators kept once in project-context/ui-maps/screens/<key>.md, and a
4
+ * live check that says, per screen, whether a new story can reuse them or must explore that screen again.
5
+ *
6
+ * node .claude/skills/orion/scripts/screen_map.mjs extract <story UI map> [--context project-context]
7
+ * node .claude/skills/orion/scripts/screen_map.mjs record --base-url <test URL> [--screens a,b | all] [--storage-state <file>]
8
+ * node .claude/skills/orion/scripts/screen_map.mjs check --base-url <test URL> [--screens a,b | all] [--storage-state <file>]
9
+ * node .claude/skills/orion/scripts/screen_map.mjs record|check --runner <Playwright test project> [--screens a,b | all]
10
+ * common: [--context project-context] [--project <test project, to find its Playwright>] [--json <file>] [--timeout 15000]
11
+ *
12
+ * --runner (a Playwright suite, JavaScript or TypeScript): the check runs inside the suite with its own Playwright and
13
+ * config, so its baseURL, httpCredentials, env file and sign-in setup apply: signed-in screens are reached the
14
+ * way the tests reach them (the suite's setup signs in from its .env; Orion never sees a value, and the suite's
15
+ * own teardown removes the session as after any run). It writes three throwaway files into the suite's
16
+ * git-ignored .ui-map/ folder, runs `npx --no-install playwright test -c .ui-map/screen-check.config.mjs`, and
17
+ * deletes them. No --base-url needed. Without --runner, --base-url and a saved --storage-state file are used.
18
+ *
19
+ * extract splits a story map's rows by screen key into screen files, merged with what they hold (same element: the
20
+ * newer row wins). Rows without a screen key or a proven light selector are left out (they were not proven).
21
+ * record while the map is known good (Orion: after Gate 6, once the story's tests passed with these locators): opens each screen once (headless, read-only: it only
22
+ * loads the page, never clicks or types) and marks which locators are on the page when it loads, and whether
23
+ * the screen is reached with the saved session or without one. That is the baseline.
24
+ * check later, before a story explores: the same load, and per screen a verdict:
25
+ * reuse the page is reached, every locator that was on the page at load still matches exactly one element,
26
+ * and none matches more than one
27
+ * explore anything else, with the reason: the page is not reached (redirect, HTTP error), a locator matches
28
+ * 0 (gone or renamed) or 2+ (no longer unique), or there is no baseline yet
29
+ * Locators that appear only after a step (a message after submit) can't be seen by loading the page: they are
30
+ * listed as "after a step" and checked when their test runs (a failure there goes to the heal step).
31
+ * Elements inside an iframe or shadow root (the map's Context) are listed as not checked here.
32
+ * Recording picks, per screen, the session (signed in or out) under which more of its locators are found; a tie keeps
33
+ * signed out. Waits are for the screen's own elements (each capped by --timeout), never for network idle.
34
+ * The browser comes from the test project's Playwright (--project), else the workspace's; none → exit 3 and the
35
+ * advice to explore as today. Only the test environment's URL: the orchestrator's production check (H5) applies before.
36
+ * Never reads .env files; a session is used only from the storage-state file given (the starter's saved session).
37
+ * Exit: 0 every screen reusable (check) or recorded (record) · 1 a screen to explore again · 2 usage · 3 can't check here.
38
+ */
39
+ import fs from 'node:fs';
40
+ import path from 'node:path';
41
+ import { createRequire } from 'node:module';
42
+ import { spawnSync } from 'node:child_process';
43
+ import { fileURLToPath, pathToFileURL } from 'node:url';
44
+
45
+ const HEAD = ['Element', 'Page', 'Light selector (proven)', 'Playwright locator (generated)', 'Context', 'Project locator',
46
+ 'Page object', 'On load', 'Last check'];
47
+
48
+ function die(code, msg) { console.error(msg); process.exit(code); }
49
+ const today = () => new Date().toISOString().slice(0, 10);
50
+ const cellOf = (v) => String(v ?? '').replace(/\|/g, '\\|').replace(/\n/g, ' ').trim();
51
+
52
+ /** Markdown tables of a text: [{ head: [..], rows: [{ cells, line }] }]. Escaped pipes stay inside a cell. */
53
+ export function tables(text) {
54
+ const out = []; let cur = null;
55
+ text.split('\n').forEach((l, i) => {
56
+ if (!l.trim().startsWith('|')) { cur = null; return; }
57
+ const cells = l.trim().replace(/^\||\|$/g, '').split(/(?<!\\)\|/).map((c) => c.trim().replace(/\\\|/g, '|'));
58
+ if (!cur) { cur = { head: cells, rows: [] }; out.push(cur); return; }
59
+ if (cells.every((c) => /^:?-+:?$/.test(c))) return;
60
+ cur.rows.push({ cells, line: i + 1 });
61
+ });
62
+ return out;
63
+ }
64
+
65
+ const col = (head, re) => head.findIndex((h) => re.test(h.toLowerCase()));
66
+
67
+ /** The page path of a map's "Page · step" cell: `/login · 1` → `/login`. */
68
+ const pageOf = (cell) => (cell || '').split('·')[0].trim();
69
+
70
+ /** A screen file: { key, path, session, checked, rows: [{ element, page, light, generated, context, project, po, onLoad, last }] }. */
71
+ export function readScreen(file) {
72
+ const text = fs.readFileSync(file, 'utf8');
73
+ const key = path.basename(file, '.md');
74
+ const head = text.match(/^# Screen: (.+)$/m);
75
+ const meta = Object.fromEntries((head ? head[1].split('·').slice(1) : []).map((x) => x.trim().split(/:\s*/)).filter((p) => p.length === 2));
76
+ const t = tables(text).find((x) => col(x.head, /light selector/) >= 0);
77
+ const rows = (t ? t.rows : []).map(({ cells }) => Object.fromEntries(['element', 'page', 'light', 'generated', 'context', 'project', 'po', 'onLoad', 'last']
78
+ .map((k, i) => [k, cells[i] ?? ''])));
79
+ return { key, file, path: meta.path || (rows[0] && rows[0].page) || '/', session: meta.session || '?', checked: meta.checked || '—', rows };
80
+ }
81
+
82
+ export function writeScreen(s) {
83
+ const lines = [`# Screen: ${s.key} · path: ${s.path} · session: ${s.session} · checked: ${s.checked}`,
84
+ '', 'Kept by `screen_map.mjs` (extract from story maps, record and check against the live test app). Locators and page',
85
+ 'structure only; never a secret value or real personal data.', '',
86
+ `| ${HEAD.join(' | ')} |`, `|${HEAD.map(() => '---').join('|')}|`,
87
+ ...s.rows.map((r) => `| ${[r.element, r.page, r.light, r.generated, r.context || '—', r.project, r.po, r.onLoad || '?', r.last || '—'].map(cellOf).join(' | ')} |`)];
88
+ fs.mkdirSync(path.dirname(s.file), { recursive: true });
89
+ fs.writeFileSync(s.file, `${lines.join('\n')}\n`);
90
+ }
91
+
92
+ function screensDir(o) { return path.join(o.context, 'ui-maps', 'screens'); }
93
+
94
+ /** Story map rows → screen files. Returns { key: added|updated count }. */
95
+ export function extract(mapFile, context) {
96
+ const text = fs.readFileSync(mapFile, 'utf8');
97
+ const changed = {};
98
+ for (const t of tables(text)) {
99
+ const c = { key: col(t.head, /screen key/), page: col(t.head, /^page/), el: col(t.head, /^element/), light: col(t.head, /light selector/),
100
+ gen: col(t.head, /playwright locator/), ctx: col(t.head, /^context/), proj: col(t.head, /project locator/), po: col(t.head, /page object/) };
101
+ if (c.key < 0 || c.light < 0) continue;
102
+ for (const { cells } of t.rows) {
103
+ const key = (cells[c.key] || '').trim();
104
+ const light = (cells[c.light] || '').trim();
105
+ if (!/^[\w.-]+$/.test(key) || !/^(css:light=|xpath=|css=)/.test(light)) continue; // unproven or no key: not kept
106
+ const file = path.join(context, 'ui-maps', 'screens', `${key}.md`);
107
+ const s = fs.existsSync(file) ? readScreen(file) : { key, file, path: pageOf(cells[c.page]) || '/', session: '?', checked: '—', rows: [] };
108
+ const row = { element: cells[c.el] || '', page: pageOf(cells[c.page]), light, generated: c.gen >= 0 ? cells[c.gen] : '',
109
+ context: c.ctx >= 0 ? cells[c.ctx] : '—', project: c.proj >= 0 ? cells[c.proj] : '', po: c.po >= 0 ? cells[c.po] : '', onLoad: '?', last: '—' };
110
+ const i = s.rows.findIndex((r) => r.element.toLowerCase() === row.element.toLowerCase() && r.page === row.page);
111
+ if (i >= 0) {
112
+ if (s.rows[i].light !== row.light) { s.rows[i] = row; s.checked = '—'; } // a changed locator needs a new baseline
113
+ else { s.rows[i] = { ...row, onLoad: s.rows[i].onLoad, last: s.rows[i].last }; }
114
+ } else { s.rows.push(row); }
115
+ writeScreen(s);
116
+ changed[key] = (changed[key] || 0) + 1;
117
+ }
118
+ }
119
+ return changed;
120
+ }
121
+
122
+ /** Playwright's chromium from the test project, the workspace, or this script's own folder; null if none. */
123
+ function loadPlaywright(project) {
124
+ const from = [project, process.cwd(), path.dirname(fileURLToPath(import.meta.url))].filter(Boolean);
125
+ for (const dir of from) {
126
+ const req = createRequire(pathToFileURL(path.join(path.resolve(dir), 'noop.js')).href);
127
+ for (const name of ['playwright', '@playwright/test', 'playwright-core']) {
128
+ try { const m = req(name); if (m.chromium) return m.chromium; } catch { /* next */ }
129
+ }
130
+ }
131
+ return null;
132
+ }
133
+
134
+ const samePath = (a, b) => a.replace(/\/+$/, '') === b.replace(/\/+$/, '');
135
+
136
+ /** Load one screen in a fresh context and count each locator. */
137
+ async function visit(browser, o, s, withSession) {
138
+ const ctx = await browser.newContext(withSession && o.storage ? { storageState: o.storage } : {});
139
+ try {
140
+ const page = await ctx.newPage();
141
+ const target = /^https?:/.test(s.path) ? s.path : new URL(s.path, o.base).href;
142
+ let res;
143
+ try { res = await page.goto(target, { waitUntil: 'load', timeout: o.timeout }); } catch (e) { return { reached: false, why: `no page (${String(e.message).split('\n')[0].slice(0, 80)})` }; }
144
+ const wait = waitList(s);
145
+ if (wait.length) await Promise.any(wait.map((sel) => page.locator(sel).first().waitFor({ state: 'attached', timeout: o.timeout }))).catch(() => {});
146
+ const status = res ? res.status() : 0;
147
+ const landed = new URL(page.url());
148
+ const wanted = new URL(target);
149
+ if (status >= 400) return { reached: false, why: `HTTP ${status}` };
150
+ if (!samePath(landed.pathname, wanted.pathname)) return { reached: false, why: `landed on ${landed.pathname}${withSession ? '' : ' (sign-in needed?)'}` };
151
+ const counts = [];
152
+ for (const r of s.rows) {
153
+ if (r.context && r.context !== '—') { counts.push(null); continue; }
154
+ try { counts.push(await page.locator(r.light).count()); } catch { counts.push(-1); }
155
+ }
156
+ return { reached: true, counts };
157
+ } finally { await ctx.close(); }
158
+ }
159
+
160
+ /** Selectors to wait for after a page loads: those on the page at load (baseline), else every checkable one. */
161
+ function waitList(s) {
162
+ const checkable = s.rows.filter((r) => !r.context || r.context === '—');
163
+ const onLoad = checkable.filter((r) => r.onLoad === 'yes');
164
+ return (onLoad.length ? onLoad : checkable).map((r) => r.light);
165
+ }
166
+
167
+ const CONFIGS = ['playwright.config.ts', 'playwright.config.js', 'playwright.config.mjs', 'playwright.config.cjs', 'playwright.config.mts', 'playwright.config.cts'];
168
+ const RUN_FILES = ['screen-check.config.mjs', 'screen-check.spec.mjs', 'screen-check.json'];
169
+
170
+ /** The check inside a Playwright suite: { visits: Map<key, { in?, out? }> } or { error }. */
171
+ function runnerVisits(o, todo, runsOf) {
172
+ const root = path.resolve(o.runner);
173
+ const config = CONFIGS.find((c) => fs.existsSync(path.join(root, c)));
174
+ if (!config) return { error: `no Playwright config in ${o.runner}` };
175
+ const req = createRequire(pathToFileURL(path.join(root, 'noop.js')).href);
176
+ try { req.resolve('@playwright/test'); } catch { return { error: `${o.runner} has no @playwright/test installed (run its package install first)` }; }
177
+ const dir = path.join(root, '.ui-map');
178
+ fs.mkdirSync(dir, { recursive: true });
179
+ const job = { timeout: o.timeout, screens: todo.map((s) => ({ key: s.key, path: s.path, runs: runsOf(s),
180
+ selectors: s.rows.map((r) => (r.context && r.context !== '—' ? null : r.light)), wait: waitList(s) })) };
181
+ const outFile = (key, tag) => path.join(dir, `screen-check.${key}.${tag}.out.json`);
182
+ const results = path.join(dir, 'screen-check-results');
183
+ const files = [...RUN_FILES.map((f) => path.join(dir, f)), ...job.screens.flatMap((x) => ['in', 'out'].map((t) => outFile(x.key, t)))];
184
+ const unwrap = 'const base = loaded && loaded.default && (loaded.__esModule || (!loaded.projects && !loaded.use)) ? loaded.default : loaded;';
185
+ try {
186
+ fs.writeFileSync(path.join(dir, 'screen-check.json'), JSON.stringify(job));
187
+ fs.writeFileSync(path.join(dir, 'screen-check.config.mjs'), `// Written by Orion's screen_map.mjs for one check; deleted after it. The suite's own config, with its paths made
188
+ // absolute (this file sits in .ui-map/), plus two check projects: signed in through the suite's own setup, and signed out.
189
+ import path from 'node:path';
190
+ import loaded from '../${config}';
191
+ ${unwrap}
192
+ const root = process.cwd();
193
+ const abs = (p) => path.resolve(root, p ?? '.');
194
+ const projects = (base.projects || []).map((p) => ({ ...p, testDir: abs(p.testDir ?? base.testDir) }));
195
+ const signed = projects.find((p) => p.use && p.use.storageState && (p.dependencies || []).length) || projects.find((p) => p.use && p.use.storageState);
196
+ const check = { testDir: abs('.ui-map'), testMatch: /screen-check\.spec\.mjs$/, retries: 0 };
197
+ const use = { ...(base.use || {}), ...(signed ? signed.use : {}) };
198
+ export default {
199
+ ...base, testDir: abs(base.testDir), outputDir: abs('.ui-map/screen-check-results'), reporter: 'line', retries: 0, workers: 1,
200
+ globalSetup: base.globalSetup ? abs(base.globalSetup) : undefined, globalTeardown: base.globalTeardown ? abs(base.globalTeardown) : undefined,
201
+ projects: [...projects,
202
+ { ...check, name: 'orion-screens-in', dependencies: signed ? (signed.dependencies || []) : [], use },
203
+ { ...check, name: 'orion-screens-out', use: { ...use, storageState: { cookies: [], origins: [] } } }],
204
+ };
205
+ `);
206
+ fs.writeFileSync(path.join(dir, 'screen-check.spec.mjs'), `// Written by Orion's screen_map.mjs for one check; deleted after it. Loads each screen and counts its proven
207
+ // locators; never clicks or types. Results go to .ui-map/screen-check.<screen>.<in|out>.out.json.
208
+ import fs from 'node:fs';
209
+ import { test } from '@playwright/test';
210
+ const job = JSON.parse(fs.readFileSync(new URL('./screen-check.json', import.meta.url), 'utf8'));
211
+ for (const s of job.screens) {
212
+ test(s.key, async ({ page }) => {
213
+ const tag = test.info().project.name === 'orion-screens-in' ? 'in' : 'out';
214
+ test.skip(!s.runs.includes(tag), 'not needed for this screen');
215
+ const write = (v) => fs.writeFileSync(new URL(\`./screen-check.\${s.key}.\${tag}.out.json\`, import.meta.url), JSON.stringify(v));
216
+ let res;
217
+ try { res = await page.goto(s.path, { timeout: job.timeout }); } catch (e) { write({ reached: false, why: 'no page (' + String(e.message).split('\\n')[0].slice(0, 80) + ')' }); return; }
218
+ if (s.wait.length) await Promise.any(s.wait.map((sel) => page.locator(sel).first().waitFor({ state: 'attached', timeout: job.timeout }))).catch(() => {});
219
+ const counts = [];
220
+ for (const sel of s.selectors) { if (sel === null) { counts.push(null); continue; } try { counts.push(await page.locator(sel).count()); } catch { counts.push(-1); } }
221
+ write({ status: res ? res.status() : 0, url: page.url(), counts });
222
+ });
223
+ }
224
+ `);
225
+ const want = new Set(job.screens.flatMap((x) => x.runs));
226
+ const args = ['--no-install', 'playwright', 'test', '-c', path.join('.ui-map', 'screen-check.config.mjs'),
227
+ ...(want.has('in') ? ['--project=orion-screens-in'] : []), ...(want.has('out') ? ['--project=orion-screens-out'] : [])];
228
+ const r = spawnSync(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, { cwd: root, encoding: 'utf8', shell: process.platform === 'win32',
229
+ timeout: 120000 + job.screens.length * 2 * o.timeout * 2 });
230
+ const tail = `${r.stdout || ''}${r.stderr || ''}`.split('\n').map((l) => l.trim()).filter((l) => /error|failed|timed? ?out/i.test(l)).slice(-1)[0] || (r.error ? String(r.error.message) : 'no result');
231
+ const visits = new Map();
232
+ for (const x of job.screens) {
233
+ const v = {};
234
+ for (const tag of x.runs) {
235
+ let out = null; try { out = JSON.parse(fs.readFileSync(outFile(x.key, tag), 'utf8')); } catch { /* not run */ }
236
+ if (!out) {
237
+ v[tag] = { reached: false, notRun: true, why: tag === 'in'
238
+ ? "the suite's sign-in didn't work, so signed-in screens weren't checked (check the test account in its .env, or run its setup alone)"
239
+ : `the check didn't run (${tail.slice(0, 140)})` };
240
+ continue;
241
+ }
242
+ if (out.reached === false) { v[tag] = out; continue; }
243
+ const landed = new URL(out.url); const wanted = /^https?:/.test(x.path) ? new URL(x.path).pathname : x.path.split('?')[0];
244
+ if (out.status >= 400) v[tag] = { reached: false, why: `HTTP ${out.status}` };
245
+ else if (!samePath(landed.pathname, wanted)) v[tag] = { reached: false, why: `landed on ${landed.pathname}${tag === 'in' ? '' : ' (sign-in needed?)'}` };
246
+ else v[tag] = { reached: true, counts: out.counts };
247
+ }
248
+ visits.set(x.key, v);
249
+ }
250
+ return { visits };
251
+ } finally {
252
+ for (const f of files) fs.rmSync(f, { force: true });
253
+ fs.rmSync(results, { recursive: true, force: true });
254
+ }
255
+ }
256
+
257
+ /** One screen's verdict from a visit. */
258
+ function judge(s, v, recording) {
259
+ if (!v.reached) return { verdict: 'explore', why: v.notRun ? v.why : `page not reached: ${v.why}`, rows: [] };
260
+ const rows = s.rows.map((r, i) => {
261
+ const n = v.counts[i];
262
+ if (n === null) return { r, state: 'not checked here (iframe or shadow root)' };
263
+ if (n === -1) return { r, state: 'selector not valid', bad: true };
264
+ if (n > 1) return { r, state: `${n} matches (no longer unique)`, bad: true };
265
+ if (n === 1) return { r, state: 'ok', ok: true };
266
+ if (recording) return { r, state: 'after a step (not on the page at load)', later: true };
267
+ if (r.onLoad === 'yes') return { r, state: 'gone (was on the page at load)', bad: true };
268
+ if (r.onLoad === 'no') return { r, state: 'after a step: checked when its test runs', later: true };
269
+ return { r, state: 'no baseline', unknown: true };
270
+ });
271
+ const bad = rows.filter((x) => x.bad);
272
+ if (bad.length) return { verdict: 'explore', why: bad.map((x) => `${x.r.element}: ${x.state}`).join('; '), rows };
273
+ if (!rows.some((x) => x.ok)) return { verdict: 'explore', why: 'no locator of this screen is on the page at load', rows };
274
+ if (!recording && (s.checked === '—' || rows.some((x) => x.unknown))) return { verdict: 'explore', why: 'no baseline yet (recorded once the tests of a story using it pass)', rows };
275
+ return { verdict: recording ? 'recorded' : 'reuse', why: `${rows.filter((x) => x.ok).length} on load ok, ${rows.filter((x) => x.later).length} after a step`, rows };
276
+ }
277
+
278
+ async function liveRun(o, recording) {
279
+ const dir = screensDir(o);
280
+ const all = fs.existsSync(dir) ? fs.readdirSync(dir).filter((f) => f.endsWith('.md')).map((f) => f.slice(0, -3)).sort() : [];
281
+ const keys = !o.screens || o.screens === 'all' ? all : o.screens.split(',').map((x) => x.trim()).filter(Boolean);
282
+ if (!keys.length) die(2, `screen_map: no screen files in ${dir} (extract a story map first)`);
283
+ const results = [];
284
+ const todo = [];
285
+ for (const k of keys) {
286
+ if (!all.includes(k)) { results.push({ key: k, verdict: 'explore', why: 'never explored (no screen file)' }); continue; }
287
+ const s = readScreen(path.join(dir, `${k}.md`));
288
+ if (!recording && s.checked === '—') { results.push({ key: k, verdict: 'explore', why: 'no baseline yet (recorded once the tests of a story using it pass)' }); continue; }
289
+ todo.push(s);
290
+ }
291
+ const canSignIn = Boolean(o.runner || o.storage);
292
+ const runsOf = (s) => (recording ? (canSignIn ? ['in', 'out'] : ['out']) : [s.session === 'signed in' ? 'in' : 'out']);
293
+ const cantCheck = (why, code) => {
294
+ console.log(`screen_map: ${why}; explore ${todo.length ? 'these screens' : 'them'} as today.`);
295
+ for (const s of todo) results.push({ key: s.key, verdict: 'explore', why: `can't check here (${why})` });
296
+ report(o, results);
297
+ return code;
298
+ };
299
+ let visits = new Map();
300
+ if (todo.length && o.runner) {
301
+ const r = runnerVisits(o, todo, runsOf);
302
+ if (r.error) return cantCheck(r.error, 3);
303
+ visits = r.visits;
304
+ } else if (todo.length) {
305
+ const chromium = loadPlaywright(o.project);
306
+ if (!chromium) return cantCheck('no Playwright here (test project or workspace)', 3);
307
+ let browser;
308
+ try { browser = await chromium.launch(); } catch (e) { return cantCheck(`the browser didn't start: ${String(e.message).split('\n')[0].slice(0, 120)}`, 3); }
309
+ try {
310
+ for (const s of todo) {
311
+ const v = {};
312
+ for (const tag of runsOf(s)) {
313
+ v[tag] = tag === 'in' && !o.storage ? { reached: false, why: 'needs the saved session (--storage-state, or --runner for a Playwright suite)' }
314
+ : await visit(browser, o, s, tag === 'in');
315
+ }
316
+ visits.set(s.key, v);
317
+ }
318
+ } finally { await browser.close(); }
319
+ }
320
+ for (const s of todo) {
321
+ const v = visits.get(s.key) || {};
322
+ const tags = runsOf(s);
323
+ // Recording: the session under which more locators are found; a tie keeps signed out. Checking: the recorded one.
324
+ const ok = (x) => (x && x.reached ? x.counts.filter((n) => n === 1).length : -1);
325
+ const tag = tags.length === 1 ? tags[0] : (ok(v.in) > ok(v.out) ? 'in' : (v.out && v.out.reached ? 'out' : (v.in && v.in.reached ? 'in' : tags[0])));
326
+ const chosen = v[tag] || { reached: false, why: 'not checked' };
327
+ const j = judge(s, chosen, recording);
328
+ if (recording && chosen.reached) {
329
+ s.session = tag === 'in' ? 'signed in' : 'signed out';
330
+ s.checked = today();
331
+ j.rows.forEach(({ r, ok: good, later }) => { if (good) r.onLoad = 'yes'; else if (later) r.onLoad = 'no'; });
332
+ }
333
+ if (chosen.reached) j.rows.forEach(({ r, state }) => { r.last = `${state === 'ok' ? '✓ 1 match' : state} · ${today()}`; });
334
+ if (chosen.reached && (recording || j.verdict === 'reuse')) { if (!recording) s.checked = today(); writeScreen(s); }
335
+ results.push({ key: s.key, verdict: j.verdict, why: j.why, rows: j.rows.map((x) => ({ element: x.r.element, state: x.state })) });
336
+ }
337
+ report(o, results);
338
+ return results.some((r) => r.verdict === 'explore') ? 1 : 0;
339
+ }
340
+
341
+ function report(o, results) {
342
+ const n = (v) => results.filter((r) => r.verdict === v).length;
343
+ console.log(`screen_map: ${results.length} screen(s) · reuse ${n('reuse')} · explore again ${n('explore')}${n('recorded') ? ` · recorded ${n('recorded')}` : ''}`);
344
+ console.log('| Screen | Do | Why |\n|---|---|---|');
345
+ for (const r of results) console.log(`| ${r.key} | ${r.verdict} | ${cellOf(r.why)} |`);
346
+ if (o.json) fs.writeFileSync(o.json, `${JSON.stringify({ format: 'orion-screens/1', base: o.base || `the config of ${o.runner}`, date: today(), results }, null, 1)}\n`);
347
+ }
348
+
349
+ function args(argv) {
350
+ const o = { context: 'project-context', timeout: 15000 };
351
+ const rest = [];
352
+ for (let i = 0; i < argv.length; i++) {
353
+ const a = argv[i];
354
+ const val = () => { const v = argv[++i]; if (v === undefined) die(2, `screen_map: ${a} needs a value`); return v; };
355
+ if (a === '--context') o.context = val();
356
+ else if (a === '--base-url') o.base = val();
357
+ else if (a === '--screens') o.screens = val();
358
+ else if (a === '--storage-state') o.storage = val();
359
+ else if (a === '--project') o.project = val();
360
+ else if (a === '--runner') o.runner = val();
361
+ else if (a === '--json') o.json = val();
362
+ else if (a === '--timeout') o.timeout = Number(val());
363
+ else if (a.startsWith('--')) die(2, `screen_map: unknown option ${a}`);
364
+ else rest.push(a);
365
+ }
366
+ o.rest = rest;
367
+ return o;
368
+ }
369
+
370
+ async function main() {
371
+ const [cmd, ...argv] = process.argv.slice(2);
372
+ const o = args(argv);
373
+ if (cmd === 'extract') {
374
+ if (!o.rest[0] || !fs.existsSync(o.rest[0])) die(2, 'usage: screen_map.mjs extract <story UI map> [--context project-context]');
375
+ const changed = extract(o.rest[0], o.context);
376
+ const keys = Object.keys(changed).sort();
377
+ console.log(`screen_map: ${keys.length} screen(s) from ${o.rest[0]}${keys.length ? `: ${keys.map((k) => `${k} (${changed[k]})`).join(', ')}` : ' (no row with a screen key and a proven light selector)'}`);
378
+ return 0;
379
+ }
380
+ if (cmd === 'record' || cmd === 'check') {
381
+ if (o.runner && !fs.existsSync(o.runner)) die(2, `screen_map: no such test project: ${o.runner}`);
382
+ if (!o.runner && (!o.base || !/^https?:\/\//.test(o.base))) die(2, `usage: screen_map.mjs ${cmd} --base-url <http(s) test URL> [--storage-state <file>] | --runner <Playwright test project>`);
383
+ if (o.storage && !fs.existsSync(o.storage)) die(2, `screen_map: no such session file: ${o.storage}`);
384
+ if (!(o.timeout > 0)) die(2, 'screen_map: --timeout needs milliseconds');
385
+ return liveRun(o, cmd === 'record');
386
+ }
387
+ die(2, 'usage: screen_map.mjs extract <story map> | record --base-url <url> | check --base-url <url> (see the header)');
388
+ }
389
+
390
+ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
391
+ main().then((code) => process.exit(code || 0), (e) => die(1, `screen_map: ${String(e && e.message || e).split('\n')[0]}`));
392
+ }
@@ -12,7 +12,7 @@
12
12
  * `--existing` is report-only and checks no layout: it scans the suite with `lib/scan.mjs` (framework, UI or API,
13
13
  * tests, page objects, which files the tests use) and lists what a script can see of the review rules, each with
14
14
  * file:line and a short quote (secrets masked): U1 fixed waits, U2 secrets in code, U3 order dependence, U7 absolute or
15
- * position locators, P1 assertions in page objects, P2 locators in tests, P5 a static driver, P6 environment reads
15
+ * position locators, U16 unbounded loops, U17 JavaScript clicks, failure-swallowing flags and `catch { return false }`, P1 assertions in page objects, P2 locators in tests, P5 a static driver, P6 environment reads
16
16
  * outside config, P8 implicit waits, P17 locator files. It ends with what it can't see ("Not assessed"); the reviewer
17
17
  * judges the rest. `--json` prints the whole scan instead.
18
18
  *
@@ -1,3 +1,4 @@
1
+ using Automation.Config;
1
2
  using Automation.Utils;
2
3
  using Microsoft.Playwright;
3
4
 
@@ -60,4 +61,49 @@ public abstract class BasePage(IPage page)
60
61
  }
61
62
  return this;
62
63
  }
64
+
65
+ /// <summary>
66
+ /// Requires an element to be visible, and fails fast with a named reason when it isn't: what was missing, on which
67
+ /// page, after how long. One bounded wait that checks continuously (no polling loop, no fixed delay).
68
+ /// @toolkit: kept for page actions to reuse.
69
+ /// </summary>
70
+ /// <param name="locator">The element that must be visible.</param>
71
+ /// <param name="what">The element in the user's words, e.g. "the Webhooks section".</param>
72
+ /// <param name="timeoutMs">How long to wait, in ms (default: the suite's assertion wait, sized from the site).</param>
73
+ /// <returns>The same locator, visible.</returns>
74
+ /// <exception cref="AutomationError">"Wait for &lt;what&gt;: not visible within &lt;n&gt;s (page: &lt;url&gt;)".</exception>
75
+ protected async Task<ILocator> EnsureVisibleAsync(ILocator locator, string what, float? timeoutMs = null)
76
+ {
77
+ var timeout = timeoutMs ?? Flags.ExpectTimeout();
78
+ try
79
+ {
80
+ await locator.First.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = timeout });
81
+ }
82
+ catch (TimeoutException)
83
+ {
84
+ throw new AutomationError("Wait for", what, $"not visible within {timeout / 1000}s",
85
+ new Dictionary<string, string?> { ["page"] = Page.Url });
86
+ }
87
+ return locator;
88
+ }
89
+
90
+ /// <summary>
91
+ /// Asks whether an element is shown, without failing: for choosing a path in a page action, never for what a test
92
+ /// checks (tests assert with <c>Expect</c>). @toolkit: kept for page actions to reuse.
93
+ /// </summary>
94
+ /// <param name="locator">The element to look for.</param>
95
+ /// <param name="timeoutMs">How long to look, in ms.</param>
96
+ /// <returns>Whether it became visible within the time.</returns>
97
+ protected static async Task<bool> IsShownAsync(ILocator locator, float timeoutMs = 2000)
98
+ {
99
+ try
100
+ {
101
+ await locator.First.WaitForAsync(new() { State = WaitForSelectorState.Visible, Timeout = timeoutMs });
102
+ return true;
103
+ }
104
+ catch (TimeoutException)
105
+ {
106
+ return false;
107
+ }
108
+ }
63
109
  }
@@ -37,4 +37,14 @@ public class UtilsTests
37
37
  [Test]
38
38
  public void AddDaysAndIsoDateFromAFixedDay() =>
39
39
  Assert.That(Dates.IsoDate(Dates.AddDays(1, new DateOnly(2026, 1, 31))), Is.EqualTo("2026-02-01"));
40
+
41
+ /// <summary>AutomationError names what, where and how long, plus the page; the three-part form is unchanged.</summary>
42
+ [Test]
43
+ public void AutomationErrorCarriesContext()
44
+ {
45
+ Assert.That(new AutomationError("Wait for", "the Login button", "not visible within 10s",
46
+ new Dictionary<string, string?> { ["page"] = "https://app.test/login" }).Message,
47
+ Is.EqualTo("Wait for the Login button: not visible within 10s (page: https://app.test/login)"));
48
+ Assert.That(new AutomationError("Open", "/login", "HTTP 500").Message, Is.EqualTo("Open /login: HTTP 500"));
49
+ }
40
50
  }
@@ -7,7 +7,25 @@ namespace Automation.Utils;
7
7
  /// <param name="action">What the suite was doing, e.g. "Open" or "Wait for".</param>
8
8
  /// <param name="where">The URL or element it was acting on.</param>
9
9
  /// <param name="detail">What came back: an HTTP status, or the state that was never reached.</param>
10
- public class AutomationError(string action, string where, string detail) : Exception($"{action} {where}: {detail}");
10
+ public class AutomationError(string action, string where, string detail) : Exception($"{action} {where}: {detail}")
11
+ {
12
+ /// <summary>Builds the message from its three parts plus facts that help the reader, e.g. the page or the item.</summary>
13
+ /// <param name="action">What the suite was doing.</param>
14
+ /// <param name="where">The URL or element it was acting on.</param>
15
+ /// <param name="detail">What came back.</param>
16
+ /// <param name="context">Facts in order, e.g. <c>new() { ["page"] = url }</c>; empty values are left out.</param>
17
+ public AutomationError(string action, string where, string detail, IReadOnlyDictionary<string, string?> context)
18
+ : this(action, where, detail + Facts(context)) { }
19
+
20
+ /// <summary>" (key: value, …)" for the non-empty facts, or "".</summary>
21
+ /// <param name="context">The facts.</param>
22
+ /// <returns>The suffix for the message.</returns>
23
+ private static string Facts(IReadOnlyDictionary<string, string?> context)
24
+ {
25
+ var joined = string.Join(", ", context.Where(f => !string.IsNullOrEmpty(f.Value)).Select(f => $"{f.Key}: {f.Value}"));
26
+ return joined.Length == 0 ? "" : $" ({joined})";
27
+ }
28
+ }
11
29
 
12
30
  /// <summary>A setting the run needs is missing from the environment and the project's `.env`.</summary>
13
31
  /// <param name="name">The environment variable that has no value.</param>
@@ -1,5 +1,7 @@
1
1
  // @ts-check
2
+ const { test } = require('@playwright/test');
2
3
  const { AutomationError } = require('../utils/errors');
4
+ const { flags } = require('../src/config/flags');
3
5
 
4
6
  /**
5
7
  * What every page shares: one way to open its path and one way to wait until it is usable.
@@ -61,6 +63,56 @@ class BasePage {
61
63
  }
62
64
  return this;
63
65
  }
66
+
67
+ /**
68
+ * Requires an element to be visible, and fails fast with a named reason when it isn't: what was missing, on which
69
+ * page, after how long. One bounded wait that checks continuously (no polling loop, no fixed sleep).
70
+ * @param {import('@playwright/test').Locator} locator The element that must be visible.
71
+ * @param {string} what The element in the user's words, e.g. "the Webhooks section" or "the Login button".
72
+ * @param {{ timeout?: number, context?: Record<string, string | number | undefined> }} [options] `timeout` in ms
73
+ * (default: the suite's assertion wait, sized from the site); `context` adds facts to the message.
74
+ * @returns {Promise<import('@playwright/test').Locator>} The same locator, visible.
75
+ * @throws {AutomationError} "Wait for <what>: not visible within <n>s (page: <url>, …)".
76
+ */
77
+ async ensureVisible(locator, what, options = {}) {
78
+ const timeout = options.timeout ?? flags.expectTimeout;
79
+ try {
80
+ await locator.first().waitFor({ state: 'visible', timeout });
81
+ } catch {
82
+ throw new AutomationError('Wait for', what, `not visible within ${timeout / 1000}s`, {
83
+ page: this.page.url(),
84
+ ...options.context,
85
+ });
86
+ }
87
+ return locator;
88
+ }
89
+
90
+ /**
91
+ * Asks whether an element is shown, without failing: for a branch in a page action ("is the menu already open?"),
92
+ * never for what a test checks (tests assert with `expect`).
93
+ * @param {import('@playwright/test').Locator} locator The element to look for.
94
+ * @param {{ timeout?: number }} [options] How long to look, in ms (default 2000).
95
+ * @returns {Promise<boolean>} Whether it became visible within the time.
96
+ */
97
+ async isShown(locator, options = {}) {
98
+ return locator
99
+ .first()
100
+ .waitFor({ state: 'visible', timeout: options.timeout ?? 2000 })
101
+ .then(() => true)
102
+ .catch(() => false);
103
+ }
104
+
105
+ /**
106
+ * Runs a user action as a named step, so the report shows which step failed (`test.step`, boxed: the failure
107
+ * points at the test line that called the action).
108
+ * @template T
109
+ * @param {string} name The step in the user's words, e.g. 'Filter logs by "order.created"'.
110
+ * @param {() => Promise<T>} body The action.
111
+ * @returns {Promise<T>} What the action returns.
112
+ */
113
+ async step(name, body) {
114
+ return test.step(name, body, { box: true });
115
+ }
64
116
  }
65
117
 
66
118
  module.exports = { BasePage };
@@ -132,18 +132,27 @@ function renderSummary(run) {
132
132
  <td class="muted">${esc(r.project)}</td>
133
133
  <td class="num">${duration(r.durationMs)}${r.attempts > 1 ? ` <span class="muted">· ${r.attempts} tries</span>` : ''}</td>
134
134
  </tr>`;
135
- // Story cases first, then framework and unit checks (grouped by file).
136
- const sections = [...groups]
137
- .sort(([, a], [, b]) => Number(!a[0].story) - Number(!b[0].story))
138
- .map(
139
- ([key, rows]) => `
135
+ // Story cases first; the suite's own framework and unit checks (no story) fold away under them, open when one failed.
136
+ /** One story or file: its heading and its table. @param {[string, Row[]]} group */
137
+ const section = ([key, rows]) => `
140
138
  <section>
141
139
  <h2>${esc(key)} <span class="muted">${rows.filter((r) => r.outcome === 'passed').length}/${rows.length} passed</span></h2>
142
140
  <div class="scroll"><table><thead><tr><th></th><th>Test</th><th>Project</th><th class="num">Time</th></tr></thead><tbody>${rows.map(row).join('')}
143
141
  </tbody></table></div>
144
- </section>`,
145
- )
146
- .join('');
142
+ </section>`;
143
+ const stories = [...groups].filter(([, rows]) => rows[0].story);
144
+ const checks = [...groups].filter(([, rows]) => !rows[0].story);
145
+ const checkRows = checks.flatMap(([, rows]) => rows);
146
+ const storyRows = stories.flatMap(([, rows]) => rows);
147
+ if (v.tone === 'good' && storyRows.length && checkRows.length) {
148
+ v.sentence = `All ${storyRows.length} story tests passed, and the suite's ${checkRows.length} own checks.`;
149
+ }
150
+ const sections = stories.length
151
+ ? stories.map(section).join('') +
152
+ (checks.length
153
+ ? `<details class="checks"${checkRows.some((r) => r.outcome !== 'passed') ? ' open' : ''}><summary>The suite's own checks · ${checkRows.filter((r) => r.outcome === 'passed').length}/${checkRows.length} passed</summary>${checks.map(section).join('')}</details>`
154
+ : '')
155
+ : checks.map(section).join('');
147
156
  return `<!doctype html>
148
157
  <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
149
158
  <title>Test run · ${esc(run.startedAt.toISOString().slice(0, 10))}</title>
@@ -164,7 +173,7 @@ td{padding:10px 12px;border-bottom:1px solid var(--line);vertical-align:top}tr:l
164
173
  .id{font-weight:600;color:var(--id);font-variant-numeric:tabular-nums}.ac{color:var(--muted);font-size:13px}
165
174
  tr.failed td{background:var(--badbg)}details{margin-top:6px}summary{cursor:pointer;color:var(--bad);font-size:13px}
166
175
  pre{white-space:pre-wrap;word-break:break-word;font-size:12.5px;background:var(--bg);border:1px solid var(--line);border-radius:6px;padding:8px;margin:6px 0}
167
- .setup{padding:12px 14px;background:var(--badbg)}a{color:inherit}footer{margin-top:32px;color:var(--muted);font-size:13px}
176
+ .setup{padding:12px 14px;background:var(--badbg)}.checks{margin-top:28px}.checks>summary{color:var(--muted);font-size:14px}a{color:inherit}footer{margin-top:32px;color:var(--muted);font-size:13px}
168
177
  </style></head><body><main>
169
178
  <div class="verdict ${v.tone}"><h1>${v.mark} ${esc(v.label)}</h1><p>${esc(v.sentence)}</p></div>
170
179
  <div class="facts">