architecture-harness 0.21.2 → 0.23.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 (107) hide show
  1. package/package.json +16 -4
  2. package/src/cli/check.mjs +61 -0
  3. package/src/cli/child-run.mjs +39 -0
  4. package/src/cli/child-run.test.mjs +16 -0
  5. package/src/cli/ci-template.test.mjs +28 -0
  6. package/src/cli/cli.test.mjs +6 -1
  7. package/src/cli/codex-implement.mjs +79 -5
  8. package/src/cli/codex-implement.test.mjs +170 -4
  9. package/src/cli/dispatch-guard.mjs +24 -1
  10. package/src/cli/dispatch-guard.test.mjs +30 -0
  11. package/src/cli/dispatch-reminder.mjs +7 -4
  12. package/src/cli/dispatch-reminder.test.mjs +8 -4
  13. package/src/cli/dispatch-slot.mjs +12 -0
  14. package/src/cli/gate-slot.mjs +151 -0
  15. package/src/cli/gate-slot.test.mjs +90 -0
  16. package/src/cli/git-hooks.test.mjs +5 -0
  17. package/src/cli/integrate.mjs +122 -0
  18. package/src/cli/integrate.test.mjs +94 -0
  19. package/src/cli/ledger.mjs +25 -3
  20. package/src/cli/ledger.test.mjs +9 -0
  21. package/src/cli/merge-guard.mjs +13 -3
  22. package/src/cli/merge-guard.test.mjs +24 -1
  23. package/src/cli/migrations.mjs +127 -0
  24. package/src/cli/migrations.test.mjs +94 -0
  25. package/src/cli/plugin-agents.test.mjs +35 -8
  26. package/src/cli/qc.mjs +58 -1
  27. package/src/cli/report-stop.mjs +3 -0
  28. package/src/cli/report-stop.test.mjs +8 -0
  29. package/src/cli/retry-failed.mjs +80 -0
  30. package/src/cli/retry-failed.test.mjs +51 -0
  31. package/src/cli/review-gate.mjs +16 -7
  32. package/src/cli/screens-discovery.mjs +60 -0
  33. package/src/cli/screens.mjs +84 -0
  34. package/src/cli/slot-guard.mjs +43 -0
  35. package/src/cli/slot-guard.test.mjs +28 -0
  36. package/src/cli/stack.mjs +14 -0
  37. package/src/cli/task-gate-review.test.mjs +10 -0
  38. package/src/cli/task-gate.mjs +39 -7
  39. package/src/cli/task-gate.test.mjs +45 -0
  40. package/src/cli/throwaway-db.mjs +127 -0
  41. package/src/cli/throwaway-db.test.mjs +83 -0
  42. package/src/cli/ui-reuse-hint.mjs +89 -0
  43. package/src/cli/ui-reuse-hint.test.mjs +60 -0
  44. package/src/cli/ui.mjs +181 -0
  45. package/src/cli/ui.test.mjs +137 -0
  46. package/src/cli/watch.mjs +211 -0
  47. package/src/cli/watch.test.mjs +246 -0
  48. package/src/config.mjs +27 -2
  49. package/src/descriptions.mjs +3 -0
  50. package/src/gates/contract-keys.mjs +33 -0
  51. package/src/gates/contract-keys.test.mjs +38 -0
  52. package/src/gates/migration-numbers.mjs +1 -1
  53. package/src/gates/migration-numbers.test.mjs +1 -0
  54. package/src/gates/ui-catalog.mjs +45 -0
  55. package/src/gates/ui-catalog.test.mjs +48 -0
  56. package/src/gates/ui-dupes.mjs +36 -0
  57. package/src/gates/ui-dupes.test.mjs +29 -0
  58. package/src/screens/auth-context.test.mjs +41 -0
  59. package/src/screens/auth-run.test.mjs +144 -0
  60. package/src/screens/auth.mjs +223 -0
  61. package/src/screens/auth.test.mjs +76 -0
  62. package/src/screens/capture-idle.test.mjs +26 -0
  63. package/src/screens/capture.browser-test.mjs +73 -0
  64. package/src/screens/capture.mjs +175 -0
  65. package/src/screens/capture.test.mjs +28 -0
  66. package/src/screens/catalog.browser-test.mjs +32 -0
  67. package/src/screens/catalog.mjs +72 -0
  68. package/src/screens/catalog.test.mjs +36 -0
  69. package/src/screens/compare.mjs +40 -0
  70. package/src/screens/compare.test.mjs +30 -0
  71. package/src/screens/discovery.browser-test.mjs +29 -0
  72. package/src/screens/discovery.mjs +158 -0
  73. package/src/screens/discovery.test.mjs +27 -0
  74. package/src/screens/inventory.mjs +69 -0
  75. package/src/screens/inventory.test.mjs +10 -0
  76. package/src/screens/map.mjs +63 -0
  77. package/src/screens/map.test.mjs +35 -0
  78. package/src/screens/open.browser-test.mjs +50 -0
  79. package/src/screens/regions.mjs +137 -0
  80. package/src/screens/regions.test.mjs +38 -0
  81. package/src/screens/session-files.mjs +39 -0
  82. package/src/screens/session-files.test.mjs +39 -0
  83. package/src/screens/setup.browser-test.mjs +49 -0
  84. package/src/screens/setup.mjs +78 -0
  85. package/src/screens/stack-auth.browser-test.mjs +30 -0
  86. package/src/screens/stack-auth.mjs +106 -0
  87. package/src/screens/stack-auth.test.mjs +65 -0
  88. package/src/screens/write-guard.mjs +26 -0
  89. package/src/stack/stack.mjs +131 -0
  90. package/src/stack/stack.test.mjs +40 -0
  91. package/src/stack/supervisor.mjs +30 -0
  92. package/src/ui/catalog.mjs +87 -0
  93. package/src/ui/catalog.test.mjs +54 -0
  94. package/src/ui/class-sites.mjs +151 -0
  95. package/src/ui/class-sites.test.mjs +41 -0
  96. package/src/ui/codemod.mjs +138 -0
  97. package/src/ui/codemod.test.mjs +140 -0
  98. package/src/ui/components.mjs +176 -0
  99. package/src/ui/components.test.mjs +87 -0
  100. package/src/ui/dupes.mjs +141 -0
  101. package/src/ui/dupes.test.mjs +85 -0
  102. package/src/ui/find.mjs +45 -0
  103. package/src/ui/find.test.mjs +48 -0
  104. package/src/ui/options.mjs +40 -0
  105. package/src/ui/scan.mjs +78 -0
  106. package/src/ui/typescript.mjs +29 -0
  107. package/templates/github/workflows/ci.yml +54 -0
@@ -0,0 +1,158 @@
1
+ import { createHash } from "node:crypto";
2
+ import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { safeControl, installWriteGuard } from "./write-guard.mjs";
5
+
6
+ const normalized = text => String(text ?? "").normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
7
+ const hash = text => createHash("sha256").update(text).digest("hex").slice(0, 16);
8
+
9
+ /** Record: source route patterns resolve only known fixture parameters. */
10
+ export function sourceRoutes(source, fixtures = {}) {
11
+ const result = [];
12
+ const names = { projectId: "project", folderId: "folder", photoId: "photo", drawingId: "drawing", id: "project" };
13
+ for (const match of source.matchAll(/\bpath\s*[:=]\s*["'](\/[^"']*)["']/g)) {
14
+ const pattern = match[1];
15
+ let missing = false;
16
+ const route = pattern.replace(/:([a-zA-Z]\w*)\??/g, (_, name) => {
17
+ const value = fixtures[name] ?? fixtures[names[name]];
18
+ if (!value) missing = true;
19
+ return encodeURIComponent(value ?? "");
20
+ });
21
+ result.push({ pattern, path: missing || route.includes("*") ? null : route });
22
+ }
23
+ return result;
24
+ }
25
+
26
+ /** Resource: route extraction reads application source without loading its modules. */
27
+ export function readSourceRoutes(roots = [], fixtures = {}) {
28
+ const routes = [];
29
+ const walk = root => {
30
+ for (const item of readdirSync(root, { withFileTypes: true })) {
31
+ if (/^(?:node_modules|\.git|dist|build|coverage|\.worktree|\.next)$/.test(item.name)) continue;
32
+ const file = path.join(root, item.name);
33
+ if (item.isDirectory()) walk(file);
34
+ else if (/\.[jt]sx?$/.test(item.name) && !/\.(?:test|spec)\./.test(item.name) && statSync(file).size < 2000000) routes.push(...sourceRoutes(readFileSync(file, "utf8"), fixtures));
35
+ }
36
+ };
37
+ for (const root of roots) walk(root);
38
+ return [...new Map(routes.map(route => [route.pattern, route])).values()];
39
+ }
40
+
41
+ const locatorFor = (page, step) => step.testId ? page.getByTestId(step.testId) : page.getByRole(step.role, { name: step.name, exact: true });
42
+
43
+ /** Record: a UI signature identifies state independently of its data rows. */
44
+ export async function stateSignature(page, pattern) {
45
+ const read = async selector => page.locator(selector).evaluateAll(nodes => nodes.filter(node => node.getBoundingClientRect().width && node.getBoundingClientRect().height).map(node => node.getAttribute("aria-label") || node.textContent.trim()).join(" | "));
46
+ const dialogs = page.getByRole("dialog");
47
+ const dialog = await dialogs.count() ? await dialogs.last().ariaSnapshot() : "";
48
+ return JSON.stringify({ route: pattern, dialog: dialog.split("\n")[0].replace(/^\s*-\s*/, ""), tab: await read('[role="tab"][aria-selected="true"]'), menu: await read('[role="menu"]'), heading: await read('main h1,main [role="heading"][aria-level="1"],h1'), expanded: await read('[aria-expanded="true"]') });
49
+ }
50
+
51
+ async function candidates(page) {
52
+ const controls = page.locator('button,[role="button"],[role="tab"],[role="menuitem"],[role="combobox"],[role="switch"],summary');
53
+ const result = [];
54
+ for (const control of await controls.all()) {
55
+ if (!await control.isVisible() || !await control.isEnabled()) continue;
56
+ const data = await control.evaluate(element => ({ type: element.getAttribute("type") ?? (element.tagName === "BUTTON" && element.closest("form") ? "submit" : ""), text: `${element.textContent} ${element.getAttribute("aria-label") ?? ""}`, testId: element.getAttribute("data-testid"), role: element.getAttribute("role") ?? (element.tagName === "SUMMARY" ? "button" : "button") }));
57
+ if (!safeControl(data)) continue;
58
+ const snapshot = await control.ariaSnapshot().catch(() => "");
59
+ const first = snapshot.split("\n")[0].match(/^-\s+([\w]+)(?:\s+"(.*?)")?/);
60
+ const step = { role: first?.[1] ?? data.role, name: first?.[2] ?? "", ...(data.testId ? { testId: data.testId } : {}) };
61
+ if (!step.testId && !step.name) continue;
62
+ if (await locatorFor(page, step).count() !== 1) continue;
63
+ result.push(step);
64
+ }
65
+ return result;
66
+ }
67
+
68
+ /** Pipeline: replay safe paths from every route and retain unique UI states. */
69
+ export async function discover(session, target, { out, targetName, widths = [2514, 390], depth = 4, timeout = 15000, allowWrites = false, maxStates = 500, say = () => {} } = {}) {
70
+ const { page, context } = session;
71
+ page.setDefaultTimeout(timeout);
72
+ const states = [], errors = [], unresolvedRoutes = [];
73
+ let blockedRequests = 0;
74
+ await installWriteGuard(context, target, { allowWrites, onBlocked: () => blockedRequests++ });
75
+ const discoveredRoutes = readSourceRoutes(target.sourceRoots, target.fixtures);
76
+ for (const route of discoveredRoutes) if (!route.path) unresolvedRoutes.push(route.pattern);
77
+ const starts = [...(target.routes ?? ["/"]).map(route => typeof route === "string" ? { path: route, pattern: route } : route), ...discoveredRoutes.filter(route => route.path)];
78
+ const origin = new URL(target.baseUrl).origin;
79
+ const seen = new Set();
80
+ const queuedRoutes = new Set();
81
+ const queue = [];
82
+ const addRoute = (route, width) => {
83
+ const key = `${width}:${route.path}`;
84
+ if (!queuedRoutes.has(key)) { queuedRoutes.add(key); queue.push({ route, width, path: [] }); }
85
+ };
86
+ for (const width of widths) for (const route of starts) addRoute(route, width);
87
+ mkdirSync(out, { recursive: true });
88
+ while (queue.length) {
89
+ if (states.length >= maxStates) { errors.push({ message: `State limit ${maxStates} reached; discovery is incomplete` }); break; }
90
+ const current = queue.shift();
91
+ try {
92
+ await page.setViewportSize({ width: current.width, height: 900 });
93
+ const response = await page.goto(new URL(current.route.path, target.baseUrl).href, { waitUntil: "domcontentloaded", timeout });
94
+ if (response?.status() >= 400) throw new Error(`HTTP ${response.status()}`);
95
+ for (const step of target.discoverySteps ?? []) {
96
+ const control = locatorFor(page, step);
97
+ if (await control.isVisible() && safeControl({ text: step.name })) await control.click({ timeout });
98
+ }
99
+ for (const step of current.path) await locatorFor(page, step).click({ timeout });
100
+ await page.waitForLoadState("networkidle", { timeout });
101
+ if (new URL(page.url()).origin !== origin) throw new Error("Discovery left the target origin");
102
+ await page.locator(target.auth.signedIn).first().waitFor({ state: "visible", timeout });
103
+ const actual = new URL(page.url());
104
+ const pattern = actual.pathname === new URL(current.route.path, target.baseUrl).pathname ? current.route.pattern : actual.pathname;
105
+ const signature = await stateSignature(page, pattern);
106
+ const key = `${current.width}:${signature}`;
107
+ if (seen.has(key)) continue;
108
+ seen.add(key);
109
+ const id = hash(key);
110
+ const thumbnail = `${targetName}-${id}.png`;
111
+ await page.screenshot({ path: path.join(out, thumbnail), animations: "disabled" });
112
+ const state = { id, signature, route: current.route.path, pattern, width: current.width, path: current.path, thumbnail };
113
+ states.push(state);
114
+ say(`Discovered ${targetName} ${current.width} ${pattern} ${id}`);
115
+ const links = await page.locator("a[href]").evaluateAll(nodes => nodes.map(node => node.href));
116
+ for (const href of links) {
117
+ const url = new URL(href);
118
+ if (url.origin === origin && !/logout|signout|delete|remove|complete/i.test(url.pathname)) addRoute({ path: url.pathname + url.search, pattern: url.pathname }, current.width);
119
+ }
120
+ if (current.path.length < depth) for (const step of await candidates(page)) queue.push({ ...current, path: [...current.path, step] });
121
+ } catch (error) { errors.push({ route: current.route.path, width: current.width, path: current.path, message: error.message }); }
122
+ }
123
+ const counts = Object.fromEntries([...new Set(states.map(state => state.pattern))].map(route => [route, states.filter(state => state.pattern === route).length]));
124
+ const result = { target: targetName, states, counts, errors, unresolvedRoutes, blockedRequests, complete: !errors.length && !unresolvedRoutes.length };
125
+ writeFileSync(path.join(out, `discovered-${targetName}.json`), JSON.stringify(result, null, 2));
126
+ return result;
127
+ }
128
+
129
+ function pairingText(state) {
130
+ const value = JSON.parse(state.signature);
131
+ const text = normalized([value.dialog, value.tab, value.menu, value.heading, value.expanded].filter(Boolean).join(" | "));
132
+ return `${state.width}:${text || value.route}`;
133
+ }
134
+
135
+ /** Pipeline: match identical state text once, retaining both parity gaps. */
136
+ export function pairStates(legacy, mono) {
137
+ const available = new Set(mono);
138
+ const result = legacy.map(left => {
139
+ const right = [...available].find(right => pairingText(left) === pairingText(right));
140
+ if (right) { available.delete(right); return { kind: "paired", legacy: left, mono: right }; }
141
+ return { kind: "legacy-only", legacy: left };
142
+ });
143
+ return [...result, ...[...available].map(right => ({ kind: "mono-only", mono: right }))];
144
+ }
145
+
146
+ /** Branch: every discovery needs a catalog signature or a written exclusion. */
147
+ export function catalogCoverage(states, entries, excluded = [], targetName) {
148
+ const signatures = entries.flatMap(entry => Array.isArray(entry.signatures) ? entry.signatures : entry.signatures?.[targetName] ?? entry.signatures?.[targetName?.split("-")[0]] ?? []);
149
+ const missing = states.filter(state => !signatures.some(signature => typeof signature === "string" ? signature === state.signature : signature.signature === state.signature && signature.width === state.width) && !excluded.some(item => item.signature === state.signature && (!item.target || item.target === targetName) && (!item.width || item.width === state.width) && item.reason?.trim()));
150
+ return { covered: states.length - missing.length, total: states.length, missing };
151
+ }
152
+
153
+ /** Fragment: scaffold selectors replay the recorded path through named steps. */
154
+ export function scaffoldEntry(state, family) {
155
+ const steps = state.path.map((step, index) => ` await ctx.step(${JSON.stringify(`${index + 1}. ${step.name || step.testId}`)}, () => ${step.testId ? `page.getByTestId(${JSON.stringify(step.testId)})` : `page.getByRole(${JSON.stringify(step.role)}, {name:${JSON.stringify(step.name)},exact:true})`}.click());`).join("\n");
156
+ const name = `discovered/${family}-${state.id ?? hash(state.signature)}`;
157
+ return `export const state${state.id ?? hash(state.signature)} = {\n name:${JSON.stringify(name)},\n signatures:{${JSON.stringify(family)}:[${JSON.stringify({ signature: state.signature, width: state.width })}]},\n open:{${JSON.stringify(family)}:async (page, ctx) => {\n await ctx.step("Navigate", () => page.goto(new URL(${JSON.stringify(state.route)},ctx.baseUrl).href));\n${steps}\n }}\n};\n`;
158
+ }
@@ -0,0 +1,27 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { safeControl, permitsRequest } from "./write-guard.mjs";
4
+ import { pairStates, catalogCoverage, scaffoldEntry, sourceRoutes } from "./discovery.mjs";
5
+
6
+ test("write guard blocks mutations in English and Japanese and allows local opt-in", () => {
7
+ for (const name of ["Save", "Delete project", "送信", "保存", "確定", "竣工にする", "アップロード", "登録"]) assert.equal(safeControl({ text: name }), false);
8
+ assert.equal(safeControl({ text: "Photos" }), true);
9
+ assert.equal(permitsRequest("POST", "http://localhost/api", { baseUrl: "http://localhost" }), false);
10
+ assert.equal(permitsRequest("POST", "http://localhost/api", { baseUrl: "http://localhost" }, true), true);
11
+ assert.equal(permitsRequest("POST", "https://other.test/x", { baseUrl: "http://localhost" }, true), false);
12
+ assert.equal(permitsRequest("POST", "https://cloud.test/api", { baseUrl: "https://cloud.test" }, true), false);
13
+ assert.equal(permitsRequest("POST", "https://tenant.auth0.com/u/login", { baseUrl: "https://cloud.test", auth: { domain: "tenant.auth0.com" } }), true);
14
+ assert.equal(permitsRequest("POST", "https://tenant.auth0.com/api/users", { baseUrl: "https://cloud.test", auth: { domain: "tenant.auth0.com" } }), false);
15
+ });
16
+
17
+ test("pairing is one-to-one and coverage requires an entry or a reason", () => {
18
+ const state = title => ({ signature: JSON.stringify({ heading: title, tab: "", menu: "", dialog: "", route: "/" }), width: 390, route: "/", path: [] });
19
+ const old = [state("Projects"), state("Legacy")];
20
+ const next = [state("Projects"), state("Mono")];
21
+ const pairs = pairStates(old, next);
22
+ assert.deepEqual(pairs.map(item => item.kind), ["paired", "legacy-only", "mono-only"]);
23
+ assert.equal(catalogCoverage(old, [{ signatures: [old[0].signature] }], [{ signature: old[1].signature, reason: "Legacy settings" }]).missing.length, 0);
24
+ assert.equal(catalogCoverage(old, [], [{ signature: old[1].signature, reason: "" }]).missing.length, 2);
25
+ assert.match(scaffoldEntry({ ...old[0], path: [{ role: "tab", name: "Photos" }] }, "mono"), /getByRole\("tab"/);
26
+ assert.deepEqual(sourceRoutes('<Route path="/projects/:projectId"/><Route path="/login"/>', { project: "p" }).map(item => item.path), ["/projects/p", "/login"]);
27
+ });
@@ -0,0 +1,69 @@
1
+ const normalize = value => String(value ?? "").normalize("NFKC").replace(/\s+/g, " ").trim().toLowerCase();
2
+ const key = item => `${item.role}:${normalize(item.name)}`;
3
+ const roles = new Set(["textbox", "searchbox", "combobox", "checkbox", "radio", "spinbutton", "slider", "switch", "button", "link", "tab", "menuitem", "menuitemcheckbox", "menuitemradio", "heading", "columnheader"]);
4
+
5
+ /** Pipeline: read accessible names from Playwright snapshots and attach field metadata in page order. */
6
+ export async function collectInventory(page, excludes = []) {
7
+ const selector = 'input,textarea,select,button,a[href],h1,h2,h3,h4,h5,h6,th,[role]';
8
+ const elements = page.locator(selector);
9
+ const inventory = [];
10
+ for (let index = 0; index < await elements.count(); index++) {
11
+ const element = elements.nth(index);
12
+ const metadata = await element.evaluate((node, omitted) => {
13
+ if (omitted.some(selector => node.closest(selector))) return null;
14
+ const style = getComputedStyle(node);
15
+ const rect = node.getBoundingClientRect();
16
+ if (!rect.width || !rect.height || style.visibility === "hidden" || style.display === "none") return null;
17
+ const type = node.tagName === "SELECT" ? "select" : node.getAttribute("type") ?? (node.tagName === "TEXTAREA" ? "textarea" : "");
18
+ if (type === "hidden") return null;
19
+ return { type, label: Array.from(node.labels ?? []).map(label => label.textContent.trim()).join(" "), placeholder: node.getAttribute("placeholder") ?? "", state: { disabled: node.matches(":disabled") || node.getAttribute("aria-disabled") === "true", required: node.required === true || node.getAttribute("aria-required") === "true", checked: "checked" in node ? node.checked : node.getAttribute("aria-checked"), selected: node.getAttribute("aria-selected"), value: node.tagName === "SELECT" ? node.selectedOptions[0]?.textContent?.trim() ?? "" : undefined }, box: { x: Math.max(0, rect.x), y: Math.max(0, rect.y), width: rect.width, height: rect.height } };
20
+ }, excludes);
21
+ if (!metadata) continue;
22
+ const snapshot = await element.ariaSnapshot();
23
+ const match = snapshot.match(/^- (\w+)(?: "((?:\\.|[^"\\])*)")?/);
24
+ if (!match || !roles.has(match[1])) continue;
25
+ let name = match[2] ?? "";
26
+ try { name = JSON.parse(`"${name}"`); } catch { /* Names from older Playwright snapshots can contain literal newlines. */ }
27
+ inventory.push({ role: match[1], name, ...metadata });
28
+ }
29
+ return inventory;
30
+ }
31
+
32
+ /** Pipeline: align role and normalized name, then reconcile moves, renames, types, and states. */
33
+ export function diffInventory(left, right) {
34
+ const rows = Array.from({ length: left.length + 1 }, () => new Uint32Array(right.length + 1));
35
+ for (let i = left.length - 1; i >= 0; i--) for (let j = right.length - 1; j >= 0; j--) rows[i][j] = key(left[i]) === key(right[j]) ? rows[i + 1][j + 1] + 1 : Math.max(rows[i + 1][j], rows[i][j + 1]);
36
+ const aligned = [], unmatchedLeft = [], unmatchedRight = [];
37
+ let i = 0, j = 0;
38
+ while (i < left.length || j < right.length) {
39
+ if (i < left.length && j < right.length && key(left[i]) === key(right[j])) aligned.push([i++, j++]);
40
+ else if (i < left.length && (j === right.length || rows[i + 1][j] >= rows[i][j + 1])) unmatchedLeft.push(i++);
41
+ else unmatchedRight.push(j++);
42
+ }
43
+ const findings = [];
44
+ const add = (kind, a, b) => findings.push({ id: findings.length + 1, kind, left: a === undefined ? null : left[a], right: b === undefined ? null : right[b], leftIndex: a ?? null, rightIndex: b ?? null });
45
+ for (const [a, b] of aligned) {
46
+ if (left[a].type !== right[b].type) add("type", a, b);
47
+ if (JSON.stringify(left[a].state) !== JSON.stringify(right[b].state)) add("state", a, b);
48
+ }
49
+ const used = new Set();
50
+ for (const a of unmatchedLeft) {
51
+ let b = unmatchedRight.find(b => !used.has(b) && key(left[a]) === key(right[b]));
52
+ if (b !== undefined) { used.add(b); add("moved", a, b); continue; }
53
+ b = unmatchedRight.find(b => !used.has(b) && normalize(left[a].name) === normalize(right[b].name));
54
+ if (b !== undefined) { used.add(b); add("type", a, b); continue; }
55
+ b = unmatchedRight.find(b => !used.has(b) && left[a].role === right[b].role && Math.abs(a - b) <= 1);
56
+ if (b !== undefined) { used.add(b); add("renamed", a, b); continue; }
57
+ add("missing", a, undefined);
58
+ }
59
+ for (const b of unmatchedRight) if (!used.has(b)) add("extra", undefined, b);
60
+ return findings;
61
+ }
62
+
63
+ /** Record: cover the visible part of either element with one crop. */
64
+ export function inventoryBox(finding, width, height) {
65
+ const boxes = [finding.left?.box, finding.right?.box].filter(Boolean);
66
+ const x = Math.min(width - 1, Math.max(0, Math.floor(Math.min(...boxes.map(box => box.x)))));
67
+ const y = Math.min(height - 1, Math.max(0, Math.floor(Math.min(...boxes.map(box => box.y)))));
68
+ return { x, y, width: Math.max(1, Math.min(width - x, Math.ceil(Math.max(...boxes.map(box => box.x + box.width))) - x)), height: Math.max(1, Math.min(height - y, Math.ceil(Math.max(...boxes.map(box => box.y + box.height))) - y)) };
69
+ }
@@ -0,0 +1,10 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { diffInventory } from "./inventory.mjs";
4
+ const field = (name, role = "textbox", type = "text", state = {}) => ({ role, name, type, state, box: { x: 0, y: 0, width: 100, height: 30 } });
5
+ test("a removed field is missing", () => assert.equal(diffInventory([field("Email")], [])[0].kind, "missing"));
6
+ test("a renamed button is renamed", () => assert.equal(diffInventory([field("Continue", "button")], [field("Next", "button")])[0].kind, "renamed"));
7
+ test("swapped fields report a move", () => assert.ok(diffInventory([field("A"), field("B")], [field("B"), field("A")]).some(f => f.kind === "moved")));
8
+ test("a text input against a select reports type", () => assert.equal(diffInventory([field("Country")], [field("Country", "combobox", "select")])[0].kind, "type"));
9
+ test("a disabled field reports state", () => assert.equal(diffInventory([field("Email")], [field("Email", "textbox", "text", { disabled: true })])[0].kind, "state"));
10
+ test("identical inventories have no findings", () => assert.deepEqual(diffInventory([field("Email")], [field(" Email ")]), []));
@@ -0,0 +1,63 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { resolveStackTargets } from "./stack-auth.mjs";
4
+
5
+ const namePattern = /^[a-zA-Z0-9][a-zA-Z0-9_-]*$/;
6
+ const text = (value) => typeof value === "string" && value.length > 0;
7
+ const requireValue = (condition, message) => { if (!condition) throw new Error(message); };
8
+
9
+ /** Branch: seed credentials belong only to a loopback origin. */
10
+ export function requireLocalhost(value) {
11
+ const url = new URL(value);
12
+ requireValue(["http:", "https:"].includes(url.protocol) && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && !url.username && !url.password, "seed-login requires localhost");
13
+ }
14
+
15
+ /** Record: validate the map before opening a browser or creating output files. */
16
+ export function parseMap(input) {
17
+ requireValue(input && typeof input === "object", "Expected a screen map");
18
+ requireValue(Array.isArray(input.widths) && input.widths.length > 0 && input.widths.every(w => Number.isInteger(w) && w > 0 && w <= 10000), "widths must contain positive integers up to 10000");
19
+ requireValue(input.targets && Object.keys(input.targets).length >= 2, "At least two targets are required");
20
+ for (const [name, target] of Object.entries(input.targets)) {
21
+ requireValue(namePattern.test(name) && name !== "pair", "Invalid target name");
22
+ const url = new URL(target.baseUrl);
23
+ requireValue(["http:", "https:"].includes(url.protocol) && !url.username && !url.password && url.port !== "5432", "Targets require HTTP URLs without credentials");
24
+ const auth = target.auth;
25
+ requireValue(auth && text(auth.signedIn), "auth.signedIn must identify a signed-in page");
26
+ if (auth.mode === "browser-session") {
27
+ requireValue(text(auth.domain) && /^[a-z0-9]+(?:[.-][a-z0-9]+)*$/i.test(auth.domain), "Invalid Auth0 domain");
28
+ } else if (auth.mode === "form") {
29
+ requireLocalhost(target.baseUrl);
30
+ for (const field of ["userSelector", "passwordSelector", "submitSelector"]) requireValue(text(auth[field]), `form requires ${field}`);
31
+ } else {
32
+ requireValue(auth.mode === "seed-login", "Unknown auth mode");
33
+ requireLocalhost(target.baseUrl);
34
+ for (const field of ["seedFile", "userField", "passwordField", "userSelector", "passwordSelector", "submitSelector"]) requireValue(text(auth[field]), `seed-login requires ${field}`);
35
+ }
36
+ }
37
+ requireValue(Array.isArray(input.screens) && input.screens.length > 0, "screens must be a nonempty array");
38
+ const names = new Set();
39
+ for (const screen of input.screens) {
40
+ requireValue(namePattern.test(screen.name) && !names.has(screen.name), "Invalid or duplicate screen name");
41
+ names.add(screen.name);
42
+ requireValue(screen.targets && Object.keys(screen.targets).length >= 2, "Each screen needs two targets");
43
+ for (const [name, route] of Object.entries(screen.targets)) {
44
+ requireValue(input.targets[name], `Unknown target ${name}`);
45
+ requireValue(text(route.path) && route.path.startsWith("/") && !route.path.startsWith("//") && !route.path.includes("\\"), "Screen paths must stay on the target origin");
46
+ requireValue(new URL(route.path, input.targets[name].baseUrl).origin === new URL(input.targets[name].baseUrl).origin, "Screen path changes origin");
47
+ if (route.masks !== undefined) requireValue(Array.isArray(route.masks) && route.masks.every(text), "masks must contain selectors");
48
+ if (route.clicks !== undefined) requireValue(Array.isArray(route.clicks) && route.clicks.every(step => text(step) || (step && text(step.selector) && typeof step.optional === "boolean")), "clicks must contain selectors or optional navigation steps");
49
+ if (route.ready !== undefined) requireValue(text(route.ready), "ready must be a selector");
50
+ if (route.idle !== undefined) requireValue(typeof route.idle === "boolean", "idle must be true or false");
51
+ }
52
+ }
53
+ return input;
54
+ }
55
+
56
+ /** Resource: resolve a seed file relative to its map. */
57
+ export function loadMap(file, { targets } = {}) {
58
+ const map = parseMap(resolveStackTargets(JSON.parse(readFileSync(file, "utf8")), targets));
59
+ if (map.catalog) map.catalog = path.resolve(path.dirname(file), map.catalog);
60
+ for (const target of Object.values(map.targets)) if (target.setup) target.setup = path.resolve(path.dirname(file), target.setup);
61
+ for (const target of Object.values(map.targets)) if (target.auth.mode === "seed-login") target.auth.seedFile = path.resolve(path.dirname(file), target.auth.seedFile);
62
+ return map;
63
+ }
@@ -0,0 +1,35 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { parseMap, requireLocalhost } from "./map.mjs";
4
+
5
+ const fixture = () => ({ widths: [2514, 390], targets: { old: { baseUrl: "https://old.example", auth: { mode: "browser-session", domain: "tenant.auth0.com", signedIn: "[data-user]" } }, next: { baseUrl: "http://localhost:5173", auth: { mode: "browser-session", domain: "tenant.auth0.com", signedIn: "[data-user]" } } }, screens: [{ name: "projects", targets: { old: { path: "/projects" }, next: { path: "/projects" } } }] });
6
+
7
+ test("map preserves widths and resolves target paths", () => {
8
+ const map = parseMap(fixture());
9
+ assert.deepEqual(map.widths, [2514, 390]);
10
+ assert.equal(map.screens[0].targets.old.path, "/projects");
11
+ });
12
+
13
+ test("map rejects traversal, duplicate names, unknown targets, and invalid widths", () => {
14
+ for (const mutate of [m => m.screens[0].name = "../escape", m => m.screens.push(m.screens[0]), m => m.widths = [0], m => m.screens[0].targets.unknown = { path: "/" }, m => m.screens[0].targets.old.path = "https://evil.example", m => m.targets.old.auth.domain = "../tenant"]) {
15
+ const map = fixture();
16
+ mutate(map);
17
+ assert.throws(() => parseMap(map));
18
+ }
19
+ });
20
+
21
+ test("seed login accepts only exact loopback hosts", () => {
22
+ for (const url of ["http://localhost:3000", "http://127.0.0.1:3000", "http://[::1]:3000"]) assert.doesNotThrow(() => requireLocalhost(url));
23
+ for (const url of ["https://cloud.example", "http://localhost.evil", "http://127.0.0.2", "file:///tmp", "http://localhost@evil.example"]) assert.throws(() => requireLocalhost(url));
24
+ const map = fixture();
25
+ map.targets.old.auth = { mode: "seed-login", signedIn: "main", seedFile: "seed.json", userField: "username", passwordField: "password", userSelector: "#user", passwordSelector: "#password", submitSelector: "#login" };
26
+ assert.throws(() => parseMap(map), /localhost/);
27
+ });
28
+
29
+ test("map accepts optional navigation for onboarding and rejects malformed steps", () => {
30
+ const map = fixture();
31
+ map.screens[0].targets.old.clicks = [{ selector: "[data-guide-skip]", optional: true }];
32
+ assert.doesNotThrow(() => parseMap(map));
33
+ map.screens[0].targets.old.clicks = [{ optional: true }];
34
+ assert.throws(() => parseMap(map));
35
+ });
@@ -0,0 +1,50 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import http from "node:http";
4
+ import { mkdtempSync, writeFileSync, rmSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { chromium } from "playwright";
8
+ import { runScreens } from "../cli/screens.mjs";
9
+
10
+ for (const mode of ["form", "seed-login"]) for (const allowWrites of [false, true]) {
11
+ test(`open ${mode} ${allowWrites ? "permits" : "blocks"} localhost POST`, async t => {
12
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-open-"));
13
+ t.after(() => rmSync(root, { recursive: true, force: true }));
14
+ t.mock.method(os, "homedir", () => root);
15
+ let posts = 0;
16
+ const server = http.createServer((request, response) => {
17
+ if (request.method === "POST") { posts++; response.end("ok"); return; }
18
+ response.setHeader("content-type", "text/html");
19
+ response.end('<main>Screen</main><script>fetch("/write", { method: "POST" }).then(() => window.result = "sent", () => window.result = "blocked")</script>');
20
+ });
21
+ t.after(() => new Promise(resolve => { server.closeAllConnections(); server.close(resolve); }));
22
+ await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
23
+ const baseUrl = `http://127.0.0.1:${server.address().port}`;
24
+ const auth = { mode, signedIn: "main", userSelector: "#user", passwordSelector: "#secret", submitSelector: "button", seedFile: "unused.json", userField: "user", passwordField: "secret" };
25
+ const target = { baseUrl, auth };
26
+ const mapFile = path.join(root, "map.json");
27
+ writeFileSync(mapFile, JSON.stringify({ widths: [390], targets: { local: target, other: target }, screens: [{ name: "screen", targets: { local: { path: "/screen" }, other: { path: "/screen" } } }] }));
28
+ const browser = await chromium.launch({ channel: "chrome" });
29
+ t.after(() => browser.close());
30
+ const context = await browser.newContext({ serviceWorkers: "block" });
31
+ const page = await context.newPage();
32
+ let passedOptions;
33
+ const messages = [];
34
+ const running = runScreens(["open", "screen", "--map", mapFile, "--target", "local", ...(allowWrites ? ["--allow-writes"] : [])], {
35
+ say: message => messages.push(message),
36
+ sessionFactory: async (_chromium, _target, options) => {
37
+ passedOptions = options;
38
+ return { context, page, close: () => context.close() };
39
+ },
40
+ });
41
+ await page.waitForURL(`${baseUrl}/screen`, { timeout: 5000 });
42
+ await page.waitForFunction(() => window.result, { timeout: 5000 });
43
+ const result = await page.evaluate(() => window.result);
44
+ await page.close();
45
+ assert.equal(await running, 0, messages.join("\n"));
46
+ assert.equal(result, allowWrites ? "sent" : "blocked");
47
+ assert.equal(posts, allowWrites ? 1 : 0);
48
+ assert.equal(passedOptions.allowWrites, allowWrites);
49
+ });
50
+ }
@@ -0,0 +1,137 @@
1
+ import pixelmatch from "pixelmatch";
2
+ import { PNG } from "pngjs";
3
+
4
+ function difference(a, b) {
5
+ if (a.width !== b.width || a.height !== b.height) throw new Error("Capture dimensions differ");
6
+ const mask = new PNG({ width: a.width, height: a.height });
7
+ pixelmatch(a.data, b.data, mask.data, a.width, a.height, { threshold: 0.1, includeAA: true, diffMask: true });
8
+ return mask;
9
+ }
10
+
11
+ /** Pipeline: accept two identical captures, or preserve the final unstable pixels after three retries. */
12
+ export async function stableCapture(capture) {
13
+ for (let attempt = 0; attempt <= 3; attempt++) {
14
+ const first = await capture();
15
+ const image = await capture();
16
+ const mask = difference(first, image);
17
+ if (!mask.data.some((value, index) => index % 4 === 3 && value)) return { image, unstable: null };
18
+ if (attempt === 3) return { image, unstable: mask };
19
+ }
20
+ }
21
+
22
+ function components(mask, gap) {
23
+ const cell = Math.max(1, gap);
24
+ const columns = Math.ceil(mask.width / cell);
25
+ const rows = Math.ceil(mask.height / cell);
26
+ const occupied = new Uint8Array(columns * rows);
27
+ for (let y = 0; y < mask.height; y++) for (let x = 0; x < mask.width; x++) {
28
+ if (mask.data[(y * mask.width + x) * 4 + 3]) occupied[Math.floor(y / cell) * columns + Math.floor(x / cell)] = 1;
29
+ }
30
+ const boxes = [];
31
+ for (let i = 0; i < occupied.length; i++) {
32
+ if (!occupied[i]) continue;
33
+ const queue = [i];
34
+ occupied[i] = 0;
35
+ let x0 = columns, y0 = rows, x1 = 0, y1 = 0;
36
+ for (let cursor = 0; cursor < queue.length; cursor++) {
37
+ const index = queue[cursor], x = index % columns, y = Math.floor(index / columns);
38
+ x0 = Math.min(x0, x); y0 = Math.min(y0, y); x1 = Math.max(x1, x); y1 = Math.max(y1, y);
39
+ for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
40
+ const nx = x + dx, ny = y + dy, next = ny * columns + nx;
41
+ if (nx >= 0 && nx < columns && ny >= 0 && ny < rows && occupied[next]) { occupied[next] = 0; queue.push(next); }
42
+ }
43
+ }
44
+ let minX = mask.width, minY = mask.height, maxX = -1, maxY = -1;
45
+ for (let y = y0 * cell; y < Math.min(mask.height, (y1 + 1) * cell); y++) for (let x = x0 * cell; x < Math.min(mask.width, (x1 + 1) * cell); x++) {
46
+ if (!mask.data[(y * mask.width + x) * 4 + 3]) continue;
47
+ minX = Math.min(minX, x); minY = Math.min(minY, y); maxX = Math.max(maxX, x); maxY = Math.max(maxY, y);
48
+ }
49
+ boxes.push({ x: minX, y: minY, width: maxX - minX + 1, height: maxY - minY + 1 });
50
+ }
51
+ return boxes;
52
+ }
53
+
54
+ const color = (image, x, y) => image.data.readUInt32LE((y * image.width + x) * 4);
55
+ function uniform(image, box) {
56
+ const x0 = Math.max(0, box.x - 1), y0 = Math.max(0, box.y - 1);
57
+ const first = color(image, x0, y0);
58
+ for (let y = y0; y < Math.min(image.height, box.y + box.height + 1); y++) for (let x = x0; x < Math.min(image.width, box.x + box.width + 1); x++) if (color(image, x, y) !== first) return false;
59
+ return true;
60
+ }
61
+
62
+ function shifted(a, b, box) {
63
+ const x0 = Math.max(0, box.x - 2), y0 = Math.max(0, box.y - 2);
64
+ const x1 = Math.min(a.width, box.x + box.width + 2), y1 = Math.min(a.height, box.y + box.height + 2);
65
+ const matches = (dx, dy, stride) => {
66
+ let compared = 0;
67
+ for (let y = y0; y < y1; y += stride) for (let x = x0; x < x1; x += stride) {
68
+ if (x + dx < 0 || x + dx >= b.width || y + dy < 0 || y + dy >= b.height) return false;
69
+ if (color(a, x, y) !== color(b, x + dx, y + dy)) return false;
70
+ compared++;
71
+ }
72
+ return compared > 0;
73
+ };
74
+ const stride = Math.max(1, Math.floor(Math.sqrt(box.width * box.height / 1000)));
75
+ for (let distance = 1; distance <= 40; distance++) for (const [dx, dy] of [[0, distance], [0, -distance], [distance, 0], [-distance, 0]]) {
76
+ if (matches(dx, dy, stride) && matches(dx, dy, 1)) return { dx, dy };
77
+ }
78
+ return null;
79
+ }
80
+
81
+ /** Pipeline: dilate differences on a grid, join components, and classify layout findings. */
82
+ export function findRegions(left, right, { unstable = [], gap = 6 } = {}) {
83
+ const mask = difference(left, right);
84
+ const instability = unstable.length === 2 && unstable[0]?.width ? difference(...unstable) : unstable.filter(Boolean)[0];
85
+ const unstableBoxes = instability ? components(instability, gap) : [];
86
+ if (instability) for (let i = 3; i < mask.data.length; i += 4) if (instability.data[i]) mask.data[i] = 0;
87
+ const regions = components(mask, gap).map(box => {
88
+ const shift = uniform(left, box) || uniform(right, box) ? null : shifted(left, right, box);
89
+ return { box, kind: shift ? "shift" : uniform(right, box) && !uniform(left, box) ? "missing" : uniform(left, box) && !uniform(right, box) ? "extra" : "changed", ...(shift ? { shift } : {}) };
90
+ });
91
+ for (let i = 0; i < regions.length; i++) for (let j = i + 1; j < regions.length; j++) {
92
+ const a = regions[i], b = regions[j];
93
+ if (a.kind !== "shift" || b.kind !== "shift" || a.shift.dx !== b.shift.dx || a.shift.dy !== b.shift.dy) continue;
94
+ if (Math.max(a.box.x, b.box.x) - Math.min(a.box.x + a.box.width, b.box.x + b.box.width) > 40 || Math.max(a.box.y, b.box.y) - Math.min(a.box.y + a.box.height, b.box.y + b.box.height) > 40) continue;
95
+ const x = Math.min(a.box.x, b.box.x), y = Math.min(a.box.y, b.box.y);
96
+ a.box = { x, y, width: Math.max(a.box.x + a.box.width, b.box.x + b.box.width) - x, height: Math.max(a.box.y + a.box.height, b.box.y + b.box.height) - y };
97
+ regions.splice(j--, 1);
98
+ }
99
+ regions.push(...unstableBoxes.map(box => ({ box, kind: "unstable" })));
100
+ regions.sort((a, b) => b.box.width * b.box.height - a.box.width * a.box.height);
101
+ for (const [index, region] of regions.entries()) {
102
+ region.id = index + 1;
103
+ if (region.kind === "shift") region.causedBy = regions.find(other => other !== region && other.kind !== "unstable" && other.kind !== "shift" && other.box.y <= region.box.y)?.id ?? null;
104
+ }
105
+ return regions;
106
+ }
107
+
108
+ /** Fragment: show baseline, comparison, and pixel difference with padding and nearest-neighbor scaling. */
109
+ export function regionCrop(left, right, box, padding = 8) {
110
+ const x = Math.max(0, box.x - padding), y = Math.max(0, box.y - padding);
111
+ const width = Math.min(left.width, box.x + box.width + padding) - x;
112
+ const height = Math.min(left.height, box.y + box.height + padding) - y;
113
+ const diff = difference(left, right);
114
+ const scale = Math.max(1, Math.ceil(600 / (width * 3)));
115
+ const crop = new PNG({ width: width * 3 * scale, height: height * scale });
116
+ [left, right, diff].forEach((source, panel) => {
117
+ for (let cy = 0; cy < height * scale; cy++) for (let cx = 0; cx < width * scale; cx++) {
118
+ const offset = ((y + Math.floor(cy / scale)) * source.width + x + Math.floor(cx / scale)) * 4;
119
+ source.data.copy(crop.data, (cy * crop.width + panel * width * scale + cx) * 4, offset, offset + 4);
120
+ }
121
+ });
122
+ return crop;
123
+ }
124
+
125
+ const digits = ["111101101101111", "010110010010111", "111001111100111", "111001111001111", "101101111001001", "111100111001111", "111100111101111", "111001001001001", "111101111101111", "111101111001111"];
126
+ /** Fragment: draw numbered boxes on both halves of the pair. */
127
+ export function boxPair(pair, regions) {
128
+ const half = pair.width / 2;
129
+ const pixel = (x, y) => { if (x >= 0 && x < pair.width && y >= 0 && y < pair.height) pair.data.set([255, 0, 0, 255], (y * pair.width + x) * 4); };
130
+ for (const region of regions) for (const offset of [0, half]) {
131
+ const { x, y, width, height } = region.box;
132
+ for (let dx = 0; dx < width; dx++) { pixel(x + offset + dx, y); pixel(x + offset + dx, y + height - 1); }
133
+ for (let dy = 0; dy < height; dy++) { pixel(x + offset, y + dy); pixel(x + offset + width - 1, y + dy); }
134
+ for (const [index, digit] of String(region.id).split("").entries()) for (let i = 0; i < 15; i++) if (digits[Number(digit)][i] === "1") for (let sy = 0; sy < 2; sy++) for (let sx = 0; sx < 2; sx++) pixel(offset + x + index * 8 + i % 3 * 2 + sx, Math.max(0, y - 12) + Math.floor(i / 3) * 2 + sy);
135
+ }
136
+ return pair;
137
+ }
@@ -0,0 +1,38 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { PNG } from "pngjs";
4
+ import { findRegions, stableCapture, regionCrop } from "./regions.mjs";
5
+
6
+ function image(box) {
7
+ const png = new PNG({ width: 120, height: 80 });
8
+ png.data.fill(255);
9
+ if (box) for (let y = box.y; y < box.y + box.height; y++) for (let x = box.x; x < box.x + box.width; x++) png.data.set([20, 40, 80, 255], (y * png.width + x) * 4);
10
+ return png;
11
+ }
12
+ test("unchanged layout finds zero regions", () => assert.deepEqual(findRegions(image(), image()), []));
13
+ test("a four pixel translation is one shift", () => {
14
+ const regions = findRegions(image({ x: 20, y: 20, width: 40, height: 20 }), image({ x: 20, y: 24, width: 40, height: 20 }));
15
+ assert.equal(regions.length, 1);
16
+ assert.equal(regions[0].kind, "shift");
17
+ assert.deepEqual(regions[0].shift, { dx: 0, dy: 4 });
18
+ });
19
+ test("removed and added controls receive directional kinds", () => {
20
+ const box = image({ x: 20, y: 20, width: 40, height: 20 });
21
+ assert.equal(findRegions(box, image())[0].kind, "missing");
22
+ assert.equal(findRegions(image(), box)[0].kind, "extra");
23
+ });
24
+ test("unstable areas never become layout findings", () => {
25
+ const a = image({ x: 20, y: 20, width: 40, height: 20 });
26
+ assert.equal(findRegions(a, image(), { unstable: [a, image()] })[0].kind, "unstable");
27
+ });
28
+ test("double capture retries three times and retains the instability mask", async () => {
29
+ let calls = 0;
30
+ const result = await stableCapture(async () => ++calls % 2 ? image() : image({ x: 20, y: 20, width: 40, height: 20 }));
31
+ assert.equal(calls, 8);
32
+ assert.ok(result.unstable);
33
+ });
34
+ test("region crops contain three padded panels scaled to 600 pixels", () => {
35
+ const crop = regionCrop(image(), image(), { x: 20, y: 20, width: 10, height: 10 });
36
+ assert.ok(crop.width >= 600);
37
+ assert.ok(crop.height > 0);
38
+ });
@@ -0,0 +1,39 @@
1
+ import { open, mkdir, rename, rm } from "node:fs/promises";
2
+ import { randomUUID } from "node:crypto";
3
+ import path from "node:path";
4
+ import { setTimeout } from "node:timers/promises";
5
+
6
+ /** Resource: one process owns each session while it reads, refreshes, and saves. */
7
+ export async function withFileLock(file, action, { timeout = 240000 } = {}) {
8
+ await mkdir(path.dirname(file), { recursive: true, mode: 0o700 });
9
+ const lock = `${file}.lock`;
10
+ const started = Date.now();
11
+ let handle;
12
+ while (!handle) {
13
+ try { handle = await open(lock, "wx", 0o600); }
14
+ catch (error) {
15
+ if (error.code !== "EEXIST") throw error;
16
+ if (Date.now() - started >= timeout) throw new Error("Session lock wait expired");
17
+ await setTimeout(50);
18
+ }
19
+ }
20
+ try { return await action(); }
21
+ finally { await handle.close(); await rm(lock, { force: true }); }
22
+ }
23
+
24
+ /** Resource: readers see either the complete old JSON or the complete new JSON. */
25
+ export async function atomicJson(file, value) {
26
+ const temporary = `${file}.${randomUUID()}.tmp`;
27
+ let handle;
28
+ try {
29
+ handle = await open(temporary, "wx", 0o600);
30
+ await handle.writeFile(JSON.stringify(value));
31
+ await handle.sync();
32
+ await handle.close();
33
+ handle = undefined;
34
+ await rename(temporary, file);
35
+ } finally {
36
+ if (handle) await handle.close();
37
+ await rm(temporary, { force: true });
38
+ }
39
+ }