architecture-harness 0.25.0 → 0.26.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 (244) hide show
  1. package/package.json +3 -22
  2. package/src/cli/ask.mjs +42 -0
  3. package/src/cli/ask.test.mjs +40 -0
  4. package/src/cli/branch-sync.mjs +126 -0
  5. package/src/cli/branch-sync.test.mjs +428 -0
  6. package/src/cli/budget-guard.mjs +74 -5
  7. package/src/cli/budget-guard.test.mjs +185 -2
  8. package/src/cli/budget-report.mjs +85 -0
  9. package/src/cli/budget-report.test.mjs +173 -0
  10. package/src/cli/budget.mjs +8 -5
  11. package/src/cli/check-commands.mjs +123 -11
  12. package/src/cli/check-commands.test.mjs +360 -6
  13. package/src/cli/check-feature-switches.test.mjs +110 -0
  14. package/src/cli/check-full.test.mjs +152 -0
  15. package/src/cli/check-verdict.mjs +46 -0
  16. package/src/cli/check-verdict.test.mjs +32 -0
  17. package/src/cli/check.mjs +137 -4
  18. package/src/cli/check.test.mjs +45 -0
  19. package/src/cli/checkpoint.mjs +143 -0
  20. package/src/cli/checkpoint.test.mjs +146 -0
  21. package/src/cli/child-run.mjs +7 -2
  22. package/src/cli/child-run.test.mjs +17 -2
  23. package/src/cli/ci-failures.mjs +304 -0
  24. package/src/cli/ci-failures.test.mjs +615 -0
  25. package/src/cli/ci-preview.mjs +62 -0
  26. package/src/cli/ci-preview.test.mjs +85 -0
  27. package/src/cli/ci-state.mjs +25 -29
  28. package/src/cli/ci-state.test.mjs +174 -2
  29. package/src/cli/ci-template.test.mjs +86 -0
  30. package/src/cli/claude-core.test.mjs +37 -0
  31. package/src/cli/codex-implement.mjs +580 -47
  32. package/src/cli/codex-implement.test.mjs +1946 -29
  33. package/src/cli/codex-limit.mjs +85 -0
  34. package/src/cli/codex-limit.test.mjs +179 -0
  35. package/src/cli/codex-reset.mjs +78 -0
  36. package/src/cli/codex-reset.test.mjs +192 -0
  37. package/src/cli/codex-verify.mjs +230 -0
  38. package/src/cli/codex-verify.test.mjs +402 -0
  39. package/src/cli/comment-watch.mjs +391 -0
  40. package/src/cli/comment-watch.test.mjs +392 -0
  41. package/src/cli/commit-guard.mjs +219 -0
  42. package/src/cli/commit-guard.test.mjs +809 -0
  43. package/src/cli/context-budgets.mjs +47 -0
  44. package/src/cli/context-budgets.test.mjs +96 -0
  45. package/src/cli/context-watch.mjs +116 -0
  46. package/src/cli/context-watch.test.mjs +395 -0
  47. package/src/cli/contract-history.mjs +1 -1
  48. package/src/cli/controller-guard.mjs +38 -0
  49. package/src/cli/controller-guard.test.mjs +66 -2
  50. package/src/cli/cost-stop.mjs +5 -1
  51. package/src/cli/cost-stop.test.mjs +26 -0
  52. package/src/cli/diff-shape.mjs +162 -0
  53. package/src/cli/diff-shape.test.mjs +200 -0
  54. package/src/cli/direct-lane.mjs +32 -19
  55. package/src/cli/direct-lane.test.mjs +21 -3
  56. package/src/cli/dispatch-guard.mjs +11 -0
  57. package/src/cli/dispatch-guard.test.mjs +145 -10
  58. package/src/cli/dispatch-reminder.mjs +23 -10
  59. package/src/cli/dispatch-reminder.test.mjs +63 -11
  60. package/src/cli/dispatch-route.mjs +54 -0
  61. package/src/cli/dispatch-route.test.mjs +101 -0
  62. package/src/cli/dispatch-slot.mjs +2 -2
  63. package/src/cli/dispatch-slot.test.mjs +18 -19
  64. package/src/cli/dispatch.test.mjs +3 -3
  65. package/src/cli/e2e-affected.mjs +15 -0
  66. package/src/cli/e2e-affected.test.mjs +73 -0
  67. package/src/cli/fleet.mjs +180 -0
  68. package/src/cli/fleet.test.mjs +213 -0
  69. package/src/cli/gate-slot.mjs +2 -1
  70. package/src/cli/gh-merge-command.mjs +96 -31
  71. package/src/cli/gh-merge-command.test.mjs +74 -0
  72. package/src/cli/gh-run.mjs +64 -3
  73. package/src/cli/gh-run.test.mjs +66 -1
  74. package/src/cli/git-hooks.test.mjs +25 -3
  75. package/src/cli/git-read.mjs +2 -1
  76. package/src/cli/integrate-tree.mjs +47 -0
  77. package/src/cli/integrate.mjs +143 -40
  78. package/src/cli/integrate.test.mjs +347 -1
  79. package/src/cli/integration-lane.mjs +62 -0
  80. package/src/cli/integration-lane.test.mjs +213 -0
  81. package/src/cli/ledger.mjs +4 -2
  82. package/src/cli/ledger.test.mjs +12 -3
  83. package/src/cli/legs.mjs +53 -0
  84. package/src/cli/legs.test.mjs +70 -0
  85. package/src/cli/lint-changed.mjs +59 -10
  86. package/src/cli/lint-changed.test.mjs +112 -1
  87. package/src/cli/locked-tests.mjs +134 -0
  88. package/src/cli/locked-tests.test.mjs +188 -0
  89. package/src/cli/merge-guard.mjs +234 -62
  90. package/src/cli/merge-guard.test.mjs +768 -39
  91. package/src/cli/metrics.mjs +53 -0
  92. package/src/cli/metrics.test.mjs +73 -0
  93. package/src/cli/milestone.mjs +297 -0
  94. package/src/cli/milestone.test.mjs +294 -0
  95. package/src/cli/mutate.mjs +203 -0
  96. package/src/cli/mutate.test.mjs +134 -0
  97. package/src/cli/output-redaction.mjs +26 -0
  98. package/src/cli/output-redaction.test.mjs +117 -0
  99. package/src/cli/overview.mjs +131 -0
  100. package/src/cli/overview.test.mjs +137 -0
  101. package/src/cli/pause.mjs +93 -0
  102. package/src/cli/pause.test.mjs +109 -0
  103. package/src/cli/plan-check.mjs +84 -12
  104. package/src/cli/plan-check.test.mjs +152 -2
  105. package/src/cli/plan-stop.mjs +7 -4
  106. package/src/cli/plan-stop.test.mjs +87 -0
  107. package/src/cli/platform-risk.mjs +46 -0
  108. package/src/cli/platform-risk.test.mjs +38 -0
  109. package/src/cli/plugin-skills.test.mjs +25 -0
  110. package/src/cli/pr-guard.mjs +128 -0
  111. package/src/cli/pr-guard.test.mjs +154 -0
  112. package/src/cli/promotion-branch.mjs +2 -0
  113. package/src/cli/qc.mjs +160 -27
  114. package/src/cli/qc.test.mjs +93 -0
  115. package/src/cli/report-stop.mjs +5 -0
  116. package/src/cli/report-stop.test.mjs +23 -1
  117. package/src/cli/retry-failed.mjs +3 -1
  118. package/src/cli/review-gate.mjs +24 -6
  119. package/src/cli/review-gate.test.mjs +116 -0
  120. package/src/cli/review-promotion.mjs +107 -0
  121. package/src/cli/review-promotion.test.mjs +251 -0
  122. package/src/cli/role-budget.mjs +50 -0
  123. package/src/cli/role-budget.test.mjs +91 -0
  124. package/src/cli/run-log.mjs +73 -0
  125. package/src/cli/run-log.test.mjs +121 -0
  126. package/src/cli/secret-patterns.mjs +16 -0
  127. package/src/cli/secret-patterns.test.mjs +73 -0
  128. package/src/cli/setup-block.mjs +24 -0
  129. package/src/cli/setup-block.test.mjs +96 -0
  130. package/src/cli/setup-checks.mjs +65 -0
  131. package/src/cli/setup-checks.test.mjs +158 -0
  132. package/src/cli/setup-compaction.mjs +55 -0
  133. package/src/cli/setup-compaction.test.mjs +115 -0
  134. package/src/cli/setup-skills.mjs +65 -0
  135. package/src/cli/setup-skills.test.mjs +171 -0
  136. package/src/cli/setup.mjs +107 -0
  137. package/src/cli/setup.test.mjs +275 -0
  138. package/src/cli/skill-length.test.mjs +8 -0
  139. package/src/cli/spawn-command.mjs +47 -0
  140. package/src/cli/spawn-command.test.mjs +64 -0
  141. package/src/cli/task-gate-review.test.mjs +21 -2
  142. package/src/cli/task-gate.mjs +25 -12
  143. package/src/cli/task-gate.test.mjs +43 -5
  144. package/src/cli/tokens.mjs +46 -3
  145. package/src/cli/tokens.test.mjs +103 -3
  146. package/src/cli/tools.mjs +49 -0
  147. package/src/cli/tools.test.mjs +89 -0
  148. package/src/cli/transcript-usage.mjs +27 -0
  149. package/src/cli/transcript-usage.test.mjs +34 -0
  150. package/src/cli/user-config-package.mjs +1 -1
  151. package/src/cli/user-config-toml.mjs +63 -7
  152. package/src/cli/user-config.mjs +39 -7
  153. package/src/cli/user-config.test.mjs +238 -5
  154. package/src/cli/watch-arm.mjs +39 -0
  155. package/src/cli/watch-arm.test.mjs +87 -0
  156. package/src/cli/watch.mjs +80 -35
  157. package/src/cli/watch.test.mjs +233 -27
  158. package/src/cli/work-order-guard.mjs +2 -1
  159. package/src/cli/workflow-hooks.test.mjs +18 -4
  160. package/src/cli/workflow-settings.mjs +44 -8
  161. package/src/cli/workflow-settings.test.mjs +124 -1
  162. package/src/cli/worktree.mjs +14 -1
  163. package/src/cli/worktree.test.mjs +20 -1
  164. package/src/config.mjs +174 -7
  165. package/src/config.test.mjs +327 -5
  166. package/src/consumer-package.mjs +31 -0
  167. package/src/consumer-package.test.mjs +54 -0
  168. package/src/descriptions.mjs +2 -0
  169. package/src/eslint/index.mjs +12 -0
  170. package/src/eslint/jsx.mjs +20 -0
  171. package/src/eslint/preset.mjs +26 -2
  172. package/src/eslint/preset.test.mjs +104 -2
  173. package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
  174. package/src/eslint/rules/no-literal-color.mjs +94 -0
  175. package/src/eslint/rules/no-static-inline-style.mjs +41 -0
  176. package/src/eslint/rules/one-component-per-file.mjs +70 -0
  177. package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
  178. package/src/eslint/rules/timeless-comment.mjs +92 -0
  179. package/src/eslint/rules.test.mjs +189 -0
  180. package/src/eslint/ui-regressions.test.mjs +39 -0
  181. package/src/gates/contract-operations.mjs +3 -3
  182. package/src/gates/contract-operations.test.mjs +28 -0
  183. package/src/gates/feature-switches.mjs +19 -0
  184. package/src/gates/feature-switches.test.mjs +55 -0
  185. package/src/gates/plain-language.mjs +396 -0
  186. package/src/gates/plain-language.test.mjs +210 -0
  187. package/src/gates/runtime-imports.test.mjs +114 -0
  188. package/src/gates/saga-key.test.mjs +1 -1
  189. package/src/global-skills.mjs +9 -0
  190. package/src/global-skills.test.mjs +53 -0
  191. package/src/plugin.test.mjs +3 -2
  192. package/src/ui/class-sites.mjs +38 -6
  193. package/src/ui/codemod.mjs +4 -1
  194. package/src/ui/codemod.test.mjs +52 -0
  195. package/src/ui/components.mjs +5 -3
  196. package/src/ui/components.test.mjs +8 -0
  197. package/src/ui/dupes.test.mjs +18 -0
  198. package/templates/docs/enforcement.md +12 -2
  199. package/templates/docs/ui.md +33 -0
  200. package/templates/githooks/pre-commit +1 -0
  201. package/templates/githooks/pre-push +11 -2
  202. package/templates/github/workflows/ci.yml +57 -3
  203. package/user-config/claude/CLAUDE.core.md +28 -0
  204. package/user-config/claude/settings.shared.json +41 -1
  205. package/src/cli/screens-discovery.mjs +0 -60
  206. package/src/cli/screens.mjs +0 -84
  207. package/src/cli/stack.mjs +0 -14
  208. package/src/cli/throwaway-db.mjs +0 -127
  209. package/src/cli/throwaway-db.test.mjs +0 -83
  210. package/src/screens/auth-context.test.mjs +0 -41
  211. package/src/screens/auth-run.test.mjs +0 -147
  212. package/src/screens/auth.mjs +0 -223
  213. package/src/screens/auth.test.mjs +0 -76
  214. package/src/screens/capture-idle.test.mjs +0 -27
  215. package/src/screens/capture.browser-test.mjs +0 -73
  216. package/src/screens/capture.mjs +0 -175
  217. package/src/screens/capture.test.mjs +0 -28
  218. package/src/screens/catalog.browser-test.mjs +0 -32
  219. package/src/screens/catalog.mjs +0 -72
  220. package/src/screens/catalog.test.mjs +0 -36
  221. package/src/screens/chrome.mjs +0 -21
  222. package/src/screens/compare.mjs +0 -40
  223. package/src/screens/compare.test.mjs +0 -30
  224. package/src/screens/discovery.browser-test.mjs +0 -29
  225. package/src/screens/discovery.mjs +0 -158
  226. package/src/screens/discovery.test.mjs +0 -27
  227. package/src/screens/inventory.mjs +0 -69
  228. package/src/screens/inventory.test.mjs +0 -10
  229. package/src/screens/map.mjs +0 -63
  230. package/src/screens/map.test.mjs +0 -35
  231. package/src/screens/open.browser-test.mjs +0 -50
  232. package/src/screens/regions.mjs +0 -137
  233. package/src/screens/regions.test.mjs +0 -38
  234. package/src/screens/session-files.mjs +0 -39
  235. package/src/screens/session-files.test.mjs +0 -39
  236. package/src/screens/setup.browser-test.mjs +0 -49
  237. package/src/screens/setup.mjs +0 -78
  238. package/src/screens/stack-auth.browser-test.mjs +0 -30
  239. package/src/screens/stack-auth.mjs +0 -106
  240. package/src/screens/stack-auth.test.mjs +0 -65
  241. package/src/screens/write-guard.mjs +0 -26
  242. package/src/stack/stack.mjs +0 -131
  243. package/src/stack/stack.test.mjs +0 -40
  244. package/src/stack/supervisor.mjs +0 -30
@@ -1,50 +0,0 @@
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
- }
@@ -1,137 +0,0 @@
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
- }
@@ -1,38 +0,0 @@
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
- });
@@ -1,39 +0,0 @@
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
- }
@@ -1,39 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { spawn } from "node:child_process";
7
- import { atomicJson, withFileLock } from "./session-files.mjs";
8
-
9
- test("parallel processes serialize ledger updates and leave complete private JSON files", async () => {
10
- const root = mkdtempSync(path.join(os.tmpdir(), "qc-lock-"));
11
- const file = path.join(root, "ledger.json");
12
- const module = new URL("./session-files.mjs", import.meta.url).href;
13
- const code = `import { readFileSync } from 'node:fs'; import { atomicJson, withFileLock } from ${JSON.stringify(module)}; const file = process.argv[1]; for(let i=0;i<10;i++) await withFileLock(file, async () => { const value = JSON.parse(readFileSync(file)); await new Promise(r => setTimeout(r, 2)); await atomicJson(file, { count: value.count + 1 }); });`;
14
- try {
15
- await atomicJson(file, { count: 0 });
16
- await Promise.all(Array.from({ length: 4 }, () => new Promise((resolve, reject) => {
17
- const child = spawn(process.execPath, ["--input-type=module", "-e", code, file]);
18
- let stderr = "";
19
- child.stderr.on("data", data => stderr += data);
20
- child.on("error", reject);
21
- child.on("exit", code => code === 0 ? resolve() : reject(new Error(stderr)));
22
- })));
23
- assert.deepEqual(JSON.parse(readFileSync(file)), { count: 40 });
24
- assert.deepEqual(readdirSync(root), ["ledger.json"]);
25
- } finally { rmSync(root, { recursive: true, force: true }); }
26
- });
27
-
28
- test("a failed writer releases its lock and preserves the previous JSON", async () => {
29
- const root = mkdtempSync(path.join(os.tmpdir(), "qc-lock-fail-"));
30
- const file = path.join(root, "state.json");
31
- try {
32
- await atomicJson(file, { old: true });
33
- await assert.rejects(withFileLock(file, async () => { throw new Error("failed"); }), /failed/);
34
- assert.deepEqual(JSON.parse(readFileSync(file)), { old: true });
35
- await withFileLock(file, () => atomicJson(file, { renewed: true }));
36
- assert.deepEqual(JSON.parse(readFileSync(file)), { renewed: true });
37
- assert.deepEqual(readdirSync(root), ["state.json"]);
38
- } finally { rmSync(root, { recursive: true, force: true }); }
39
- });
@@ -1,49 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import http from "node:http";
4
- import { mkdtempSync, rmSync, readFileSync } from "node:fs";
5
- import os from "node:os";
6
- import path from "node:path";
7
- import { chromium } from "playwright";
8
- import { setupLocal, fixturePlan } from "./setup.mjs";
9
-
10
- test("setup refuses cloud before launching a browser", async () => {
11
- await assert.rejects(setupLocal({ baseUrl: "https://cloud.example" }, "cloud", {}), /localhost/);
12
- });
13
-
14
- test("local UI setup makes real requests, resumes ids, and creates no duplicates", async () => {
15
- const records = new Map();
16
- let writes = 0;
17
- const server = http.createServer((request, response) => {
18
- const kind = new URL(request.url, "http://localhost").searchParams.get("kind");
19
- if (request.method === "POST") { records.set(kind, `id-${kind}`); writes++; response.writeHead(303, { location: `/?kind=${kind}` }).end(); return; }
20
- response.setHeader("content-type", "text/html");
21
- response.end(`<main>${records.has(kind) ? `<a data-testid="record" href="/records/${records.get(kind)}">QC-PARITY-TEST</a>` : '<form method="post"><label>Name<input name="name"></label><button>Create</button></form>'}</main>`);
22
- });
23
- await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
24
- const root = mkdtempSync(path.join(os.tmpdir(), "qc-setup-"));
25
- const browser = await chromium.launch({ channel: "chrome", headless: true });
26
- const target = { baseUrl: `http://127.0.0.1:${server.address().port}`, auth: { signedIn: "main" } };
27
- const adapter = Object.fromEntries(fixturePlan.map(item => [item.kind, {
28
- async find(page, ctx) {
29
- await page.goto(`${ctx.baseUrl}/?kind=${item.kind}`);
30
- return await page.getByTestId("record").count() ? (await page.getByTestId("record").getAttribute("href")).split("/").at(-1) : null;
31
- },
32
- async create(page, ctx) {
33
- await page.getByRole("textbox", { name: "Name" }).fill(ctx.item.name);
34
- await page.getByRole("button", { name: "Create" }).click();
35
- await page.getByTestId("record").waitFor();
36
- return (await page.getByTestId("record").getAttribute("href")).split("/").at(-1);
37
- },
38
- }]));
39
- const sessionFactory = async () => { const context = await browser.newContext({ serviceWorkers: "block" }); return { context, page: await context.newPage(), close: () => context.close() }; };
40
- try {
41
- const options = { chromium, adapter, stateRoot: root, sessionFactory, timeout: 3000 };
42
- const first = await setupLocal(target, "fixture", options);
43
- assert.equal(Object.keys(first).length, fixturePlan.length);
44
- assert.equal(writes, fixturePlan.length);
45
- assert.deepEqual(await setupLocal(target, "fixture", options), first);
46
- assert.equal(writes, fixturePlan.length);
47
- assert.deepEqual(JSON.parse(readFileSync(path.join(root, "fixtures-fixture.json"))), first);
48
- } finally { await browser.close(); await new Promise(resolve => server.close(resolve)); rmSync(root, { recursive: true, force: true }); }
49
- });
@@ -1,78 +0,0 @@
1
- import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync } from "node:fs";
2
- import path from "node:path";
3
- import { pathToFileURL } from "node:url";
4
- import { PNG } from "pngjs";
5
- import { requireLocalhost } from "./map.mjs";
6
- import { targetSession } from "./stack-auth.mjs";
7
- import { privateRoot } from "./auth.mjs";
8
- import { navigationContext } from "./catalog.mjs";
9
-
10
- /** Record: both applications receive the same named test content. */
11
- export const fixturePlan = [
12
- { kind: "project", name: "QC-PARITY-TEST" },
13
- { kind: "folder", name: "QC-PARITY-FOLDER" },
14
- { kind: "photo", name: "qc-parity-photo.png", asset: "photo" },
15
- { kind: "drawing", name: "qc-parity-drawing.pdf", asset: "drawing" },
16
- { kind: "document", name: "qc-parity-document.txt", asset: "document" },
17
- { kind: "blackboard", name: "QC-PARITY-BLACKBOARD" },
18
- { kind: "inspection", name: "QC-PARITY-INSPECTION" },
19
- { kind: "delivery", name: "QC-PARITY-DELIVERY" },
20
- ];
21
-
22
- /** Resource: deterministic upload files need neither downloads nor app secrets. */
23
- export function fixtureAssets(root) {
24
- mkdirSync(root, { recursive: true });
25
- const photo = new PNG({ width: 120, height: 80 });
26
- for (let y = 0; y < photo.height; y++) for (let x = 0; x < photo.width; x++) photo.data.set([x < 60 ? 32 : 200, 100, y < 40 ? 220 : 80, 255], (y * photo.width + x) * 4);
27
- const content = "BT /F1 20 Tf 36 150 Td (QC PARITY DRAWING) Tj ET\n";
28
- const objects = ["<< /Type /Catalog /Pages 2 0 R >>", "<< /Type /Pages /Kids [3 0 R] /Count 1 >>", "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] /Resources << /Font << /F1 4 0 R >> >> /Contents 5 0 R >>", "<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>", `<< /Length ${content.length} >>\nstream\n${content}endstream`];
29
- let pdf = "%PDF-1.4\n";
30
- const offsets = [0];
31
- for (const [index, object] of objects.entries()) { offsets.push(Buffer.byteLength(pdf)); pdf += `${index + 1} 0 obj\n${object}\nendobj\n`; }
32
- const xref = Buffer.byteLength(pdf);
33
- pdf += `xref\n0 6\n0000000000 65535 f \n${offsets.slice(1).map(offset => `${String(offset).padStart(10, "0")} 00000 n \n`).join("")}trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n${xref}\n%%EOF\n`;
34
- const files = { photo: ["qc-parity-photo.png", PNG.sync.write(photo)], drawing: ["qc-parity-drawing.pdf", pdf], document: ["qc-parity-document.txt", "QC-PARITY-TEST\nDeterministic local fixture.\n"] };
35
- return Object.fromEntries(Object.entries(files).map(([kind, [name, bytes]]) => { const file = path.join(root, name); writeFileSync(file, bytes); return [kind, file]; }));
36
- }
37
-
38
- /** Pipeline: verify or create each resource through the app's UI and persist its id. */
39
- export async function setupLocal(target, targetName, { chromium, adapter, stateRoot = privateRoot(), timeout = 15000, signInTimeout = 180000, say = console.error, sessionFactory = targetSession } = {}) {
40
- requireLocalhost(target.baseUrl);
41
- try { await fetch(target.baseUrl, { signal: AbortSignal.timeout(timeout), redirect: "manual" }); }
42
- catch { throw new Error(`Local target ${targetName} does not answer; start its stack first`); }
43
- if (!adapter) {
44
- if (!target.setup) throw new Error("Target requires a setup module with UI find and create functions");
45
- adapter = (await import(pathToFileURL(target.setup).href)).default;
46
- }
47
- for (const item of fixturePlan) if (typeof adapter[item.kind]?.find !== "function" || typeof adapter[item.kind]?.create !== "function") throw new Error(`Setup module requires ${item.kind}.find and create`);
48
- mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
49
- const file = path.join(stateRoot, `fixtures-${targetName}.json`);
50
- const fixtures = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : {};
51
- const assets = fixtureAssets(path.join(stateRoot, "fixture-assets"));
52
- const session = await sessionFactory(chromium, target, { timeout, signInTimeout, targetName, allowWrites: true, say });
53
- try {
54
- const { page, context } = session;
55
- page.setDefaultTimeout(timeout);
56
- await context.route("**/*", async route => {
57
- try { requireLocalhost(route.request().url()); await route.fallback(); }
58
- catch { await route.abort("blockedbyclient"); }
59
- });
60
- const navigation = navigationContext(page, target, targetName, "setup", stateRoot);
61
- const ctx = { ...navigation, fixtures, assets };
62
- for (const item of fixturePlan) {
63
- ctx.item = item;
64
- let id = await ctx.step(`Find ${item.kind}`, () => adapter[item.kind].find(page, ctx));
65
- if (!id) {
66
- requireLocalhost(page.url());
67
- id = await ctx.step(`Create ${item.kind}`, () => adapter[item.kind].create(page, ctx));
68
- }
69
- requireLocalhost(page.url());
70
- if (typeof id !== "string" || !id) throw new Error(`Setup ${item.kind} returned no id`);
71
- fixtures[item.kind] = id;
72
- writeFileSync(`${file}.tmp`, `${JSON.stringify(fixtures, null, 2)}\n`, { mode: 0o600 });
73
- renameSync(`${file}.tmp`, file);
74
- say(`Ready local fixture ${item.kind}`);
75
- }
76
- return fixtures;
77
- } finally { await session.close(); }
78
- }
@@ -1,30 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import http from "node:http";
4
- import { randomUUID } from "node:crypto";
5
- import { chromium } from "playwright";
6
- import { seedSession } from "./auth.mjs";
7
-
8
- test("localhost form signs in automatically and saved state passes a real request", async () => {
9
- let submitted = false;
10
- const server = http.createServer((request, response) => {
11
- response.setHeader("content-type", "text/html; charset=utf-8");
12
- if (request.method === "POST") {
13
- submitted = true;
14
- response.writeHead(302, { "set-cookie": "signed=yes; Path=/; HttpOnly", location: "/projects" }).end();
15
- } else if (request.url === "/projects") response.end(request.headers.cookie?.includes("signed=yes") ? '<main id="signed">Projects</main>' : "Expired");
16
- else response.end('<form method="post"><input id="user" name="user"><input id="pass" name="password" type="password"><button id="submit">Login</button></form>');
17
- });
18
- await new Promise(resolve => server.listen(0, "127.0.0.1", resolve));
19
- const target = { baseUrl: `http://127.0.0.1:${server.address().port}`, auth: { mode: "form", path: "/login", signedIn: "#signed", userSelector: "#user", passwordSelector: "#pass", submitSelector: "#submit" } };
20
- try {
21
- const session = await seedSession(chromium, target, { credentials: { user: randomUUID(), password: randomUUID() } });
22
- await session.close();
23
- assert.equal(submitted, true);
24
- submitted = false;
25
- const saved = await seedSession(chromium, target, { savedOnly: true, timeout: 3000 });
26
- await saved.close();
27
- assert.equal(submitted, false);
28
- await assert.rejects(seedSession(chromium, { ...target, baseUrl: "https://cloud.example" }), /localhost/);
29
- } finally { await new Promise(resolve => server.close(resolve)); }
30
- });
@@ -1,106 +0,0 @@
1
- import { existsSync, readFileSync } from "node:fs";
2
- import { atomicJson, withFileLock } from "./session-files.mjs";
3
- import { createHash } from "node:crypto";
4
- import os from "node:os";
5
- import path from "node:path";
6
- import { requireLocalhost } from "./map.mjs";
7
- import { loadStack, healthUrls } from "../stack/stack.mjs";
8
- import { browserSession, seedSession, privateRoot } from "./auth.mjs";
9
-
10
- /** Resource: read credentials as literals without evaluating shell expressions. */
11
- export function accountFields(file = path.join(os.homedir(), ".qc", "accounts.env")) {
12
- const source = readFileSync(file, "utf8");
13
- const get = key => {
14
- const value = source.match(new RegExp(`^\\s*(?:export\\s+)?${key}\\s*=\\s*(.*)$`, "m"))?.[1]?.trim();
15
- if (!value) throw new Error("accounts.env requires QC_TEST_EMAIL and QC_TEST_PASSWORD");
16
- return /^["']/.test(value) && value.at(-1) === value[0] ? value.slice(1, -1) : value;
17
- };
18
- return { user: get("QC_TEST_EMAIL"), password: get("QC_TEST_PASSWORD") };
19
- }
20
-
21
- /** Branch: each plugin selects one real sign-in flow. */
22
- export function applyStackLogin(target, manifest) {
23
- const login = manifest.login;
24
- if (login.kind === "auth0-session") {
25
- target.auth = { ...target.auth, mode: "browser-session", path: login.url ?? "/bff/login?returnTo=%2Fprojects" };
26
- } else if (login.kind === "form") {
27
- requireLocalhost(target.baseUrl);
28
- const url = new URL(login.url, target.baseUrl);
29
- requireLocalhost(url.href);
30
- if (url.origin !== new URL(target.baseUrl).origin) throw new Error("Form login must use the target origin");
31
- target.auth = { ...target.auth, mode: "form", path: url.pathname + url.search, userSelector: login.selectors?.email, passwordSelector: login.selectors?.secret ?? login.selectors?.password, submitSelector: login.selectors?.submit };
32
- } else throw new Error(`Unsupported login kind: ${login.kind}`);
33
- return target;
34
- }
35
-
36
- /** Pipeline: resolve current stack URLs before validating the screen map. */
37
- export function resolveStackTargets(input, names) {
38
- for (const [name, target] of Object.entries(input.targets)) if (target.stack && (!names || names.includes(name))) {
39
- const { manifest } = loadStack(target.stack);
40
- target.baseUrl = new URL(healthUrls(manifest)[0]).origin;
41
- applyStackLogin(target, manifest);
42
- }
43
- return input;
44
- }
45
-
46
- const metadataFile = target => path.join(privateRoot(), `session-${createHash("sha256").update(target.baseUrl).digest("hex").slice(0, 16)}.json`);
47
-
48
- /** Ledger: refresh times belong to each application rather than its shared tenant. */
49
- export async function recordRefresh(target) {
50
- const file = metadataFile(target);
51
- await withFileLock(file, () => atomicJson(file, { target, lastRefreshed: new Date().toISOString() }));
52
- }
53
-
54
- export function refreshDue(record, now = Date.now()) {
55
- const lastTry = Math.max(Date.parse(record?.lastRefreshed) || 0, Date.parse(record?.lastAttempted) || 0);
56
- return !lastTry || now - lastTry >= 23 * 60 * 60 * 1000;
57
- }
58
-
59
- /** Pipeline: authenticate each target through its declared mechanism. */
60
- export async function targetSession(chromium, target, options = {}) {
61
- let credentials;
62
- try { if (target.auth.mode === "form") credentials = accountFields(); }
63
- catch { throw new Error(`${options.targetName ?? target.baseUrl}: form sign-in failed at the account file`); }
64
- const session = await (target.auth.mode === "browser-session" ? browserSession(chromium, target, options) : seedSession(chromium, target, { ...options, credentials }));
65
- try { await recordRefresh({ ...target, name: options.targetName ?? target.name }); }
66
- catch { await session.close(); throw new Error(`${options.targetName ?? target.baseUrl}: ${target.auth.mode} sign-in failed at the refresh ledger`); }
67
- return session;
68
- }
69
-
70
- /** Pipeline: validate saved state without opening an interactive window. */
71
- export async function authStatus(chromium, targets, options = {}) {
72
- const rows = [];
73
- for (const [name, target] of Object.entries(targets)) {
74
- const file = metadataFile(target);
75
- let lastRefreshed = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")).lastRefreshed : null;
76
- let valid = false;
77
- try {
78
- const session = await (target.auth.mode === "browser-session" ? browserSession(chromium, target, { ...options, targetName: name, allowInteractive: false }) : seedSession(chromium, target, { ...options, targetName: name, savedOnly: true }));
79
- await session.close();
80
- await recordRefresh({ ...target, name });
81
- lastRefreshed = JSON.parse(readFileSync(file, "utf8")).lastRefreshed;
82
- valid = true;
83
- } catch {}
84
- rows.push({ target: name, valid, lastRefreshed });
85
- }
86
- return rows;
87
- }
88
-
89
- /** Trigger: a running stack slides its real Auth0 session before a day elapses. */
90
- export async function refreshStackSessions(stack) {
91
- const { readdirSync } = await import("node:fs");
92
- for (const name of readdirSync(privateRoot()).filter(name => /^session-.*\.json$/.test(name))) {
93
- const file = path.join(privateRoot(), name);
94
- const record = await withFileLock(file, async () => {
95
- const current = JSON.parse(readFileSync(file, "utf8"));
96
- if (current.target.stack !== stack || !refreshDue(current)) return null;
97
- await atomicJson(file, { ...current, lastAttempted: new Date(Date.now()).toISOString() });
98
- return current;
99
- });
100
- if (!record) continue;
101
- const { chromium } = await import("playwright");
102
- const target = { ...record.target, auth: { ...record.target.auth, path: "/bff/login?returnTo=%2Fprojects" } };
103
- const session = await targetSession(chromium, target, { timeout: 15000, signInTimeout: 180000, allowInteractive: false });
104
- await session.close();
105
- }
106
- }
@@ -1,65 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
4
- import path from "node:path";
5
- import os from "node:os";
6
- import { randomUUID } from "node:crypto";
7
- import { accountFields, applyStackLogin, refreshDue, recordRefresh, refreshStackSessions } from "./stack-auth.mjs";
8
- import { chromium } from "playwright";
9
- import { parseMap } from "./map.mjs";
10
-
11
- test("a failed stack refresh waits the normal interval before retrying", async t => {
12
- const root = mkdtempSync(path.join(os.tmpdir(), "qc-refresh-"));
13
- t.after(() => rmSync(root, { recursive: true, force: true }));
14
- t.mock.method(os, "homedir", () => root);
15
- const target = { stack: "fixture", baseUrl: "http://localhost:4567", auth: { mode: "browser-session", domain: "tenant.test", signedIn: "main" } };
16
- await recordRefresh(target);
17
- const directory = path.join(root, ".qc", "screens", "state");
18
- mkdirSync(directory);
19
- writeFileSync(path.join(directory, "tenant.test.json"), JSON.stringify({ cookies: [], origins: [] }));
20
- let now = Date.now() + 24 * 60 * 60 * 1000;
21
- t.mock.method(Date, "now", () => now);
22
- let launches = 0;
23
- t.mock.method(chromium, "launch", async () => {
24
- launches++;
25
- throw new Error("Browser unavailable");
26
- });
27
- for (let tick = 0; tick < 5; tick++) {
28
- await refreshStackSessions("fixture").catch(() => {});
29
- now += 1000;
30
- }
31
- assert.equal(launches, 1);
32
- now += 23 * 60 * 60 * 1000;
33
- await assert.rejects(refreshStackSessions("fixture"));
34
- assert.equal(launches, 2);
35
- });
36
-
37
- test("stack form login reads the legacy email, secret, and submit selectors", () => {
38
- const target = { baseUrl: "http://localhost:3300", auth: { signedIn: "main" } };
39
- applyStackLogin(target, { login: { kind: "form", url: "/login", selectors: { email: "#username", secret: "#password", submit: "[data-testid=button-login-submit]" } } });
40
- const map = parseMap({ widths: [390], targets: { legacy: target, other: structuredClone(target) }, screens: [{ name: "projects", targets: { legacy: { path: "/projects" }, other: { path: "/projects" } } }] });
41
- assert.equal(map.targets.legacy.auth.userSelector, "#username");
42
- assert.equal(map.targets.legacy.auth.passwordSelector, "#password");
43
- assert.equal(map.targets.legacy.auth.submitSelector, "[data-testid=button-login-submit]");
44
- });
45
-
46
- test("accounts read named environment fields without evaluation", () => {
47
- const root = mkdtempSync(path.join(os.tmpdir(), "qc-account-"));
48
- const file = path.join(root, "accounts.env");
49
- try {
50
- const value = `${randomUUID()}$(never-run)`;
51
- writeFileSync(file, `# account\nQC_TEST_EMAIL="a@example.test"\nQC_TEST_PASSWORD=${value}\n`);
52
- assert.deepEqual(accountFields(file), { user: "a@example.test", password: value });
53
- } finally { rmSync(root, { recursive: true, force: true }); }
54
- });
55
-
56
- test("stack auth keeps mono on its real Auth0 flow and limits form login to localhost", () => {
57
- const target = { baseUrl: "http://localhost:5173", auth: { domain: "tenant.auth0.com", signedIn: "main" } };
58
- applyStackLogin(target, { login: { kind: "auth0-session" } });
59
- assert.equal(target.auth.mode, "browser-session");
60
- assert.equal(target.auth.path, "/bff/login?returnTo=%2Fprojects");
61
- assert.throws(() => applyStackLogin({ baseUrl: "https://cloud.test", auth: {} }, { login: { kind: "form", url: "/login" } }), /localhost/);
62
- assert.throws(() => applyStackLogin(target, { login: { kind: "local-token" } }), /Unsupported/);
63
- assert.equal(refreshDue({ lastRefreshed: new Date(Date.now() - 86400000).toISOString() }), true);
64
- assert.equal(refreshDue({ lastRefreshed: new Date().toISOString() }), false);
65
- });