architecture-harness 0.22.0 → 0.23.1

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 (77) hide show
  1. package/LICENSE +21 -0
  2. package/package.json +23 -3
  3. package/src/cli/bash-command-guard.mjs +44 -5
  4. package/src/cli/bash-command-guard.test.mjs +35 -1
  5. package/src/cli/check-commands.mjs +82 -0
  6. package/src/cli/check-commands.test.mjs +190 -0
  7. package/src/cli/check.mjs +34 -13
  8. package/src/cli/ci-template.test.mjs +12 -0
  9. package/src/cli/cli.test.mjs +17 -1
  10. package/src/cli/codex-implement.mjs +7 -2
  11. package/src/cli/codex-implement.test.mjs +29 -0
  12. package/src/cli/commit-msg.mjs +5 -2
  13. package/src/cli/commit-msg.test.mjs +12 -0
  14. package/src/cli/dispatch-reminder.mjs +4 -1
  15. package/src/cli/dispatch-reminder.test.mjs +5 -1
  16. package/src/cli/generated-file-guard.mjs +10 -1
  17. package/src/cli/generated-file-guard.test.mjs +10 -0
  18. package/src/cli/git-hooks.test.mjs +5 -0
  19. package/src/cli/post-edit-gate.test.mjs +9 -2
  20. package/src/cli/pr-check.mjs +15 -2
  21. package/src/cli/pr-check.test.mjs +19 -9
  22. package/src/cli/qc.mjs +27 -3
  23. package/src/cli/screens-discovery.mjs +60 -0
  24. package/src/cli/screens.mjs +84 -0
  25. package/src/cli/shell-command.mjs +3 -1
  26. package/src/cli/stack.mjs +14 -0
  27. package/src/cli/stop-gate.test.mjs +17 -0
  28. package/src/cli/work-order-guard.mjs +2 -2
  29. package/src/config.mjs +15 -0
  30. package/src/config.test.mjs +33 -1
  31. package/src/eslint/rules/no-raw-fetch.mjs +42 -2
  32. package/src/eslint/rules.test.mjs +15 -0
  33. package/src/gates/audit-append-only.mjs +18 -4
  34. package/src/gates/audit-append-only.test.mjs +19 -0
  35. package/src/gates/tenant-predicate.mjs +147 -7
  36. package/src/gates/tenant-predicate.test.mjs +55 -0
  37. package/src/gates/tenant-tables.mjs +5 -2
  38. package/src/gates/tenant-tables.test.mjs +8 -0
  39. package/src/gates/threshold-ratchet.mjs +12 -9
  40. package/src/gates/threshold-ratchet.test.mjs +16 -0
  41. package/src/plugin.test.mjs +28 -0
  42. package/src/screens/auth-context.test.mjs +41 -0
  43. package/src/screens/auth-run.test.mjs +147 -0
  44. package/src/screens/auth.mjs +223 -0
  45. package/src/screens/auth.test.mjs +76 -0
  46. package/src/screens/capture-idle.test.mjs +27 -0
  47. package/src/screens/capture.browser-test.mjs +73 -0
  48. package/src/screens/capture.mjs +175 -0
  49. package/src/screens/capture.test.mjs +28 -0
  50. package/src/screens/catalog.browser-test.mjs +32 -0
  51. package/src/screens/catalog.mjs +72 -0
  52. package/src/screens/catalog.test.mjs +36 -0
  53. package/src/screens/chrome.mjs +21 -0
  54. package/src/screens/compare.mjs +40 -0
  55. package/src/screens/compare.test.mjs +30 -0
  56. package/src/screens/discovery.browser-test.mjs +29 -0
  57. package/src/screens/discovery.mjs +158 -0
  58. package/src/screens/discovery.test.mjs +27 -0
  59. package/src/screens/inventory.mjs +69 -0
  60. package/src/screens/inventory.test.mjs +10 -0
  61. package/src/screens/map.mjs +63 -0
  62. package/src/screens/map.test.mjs +35 -0
  63. package/src/screens/open.browser-test.mjs +50 -0
  64. package/src/screens/regions.mjs +137 -0
  65. package/src/screens/regions.test.mjs +38 -0
  66. package/src/screens/session-files.mjs +39 -0
  67. package/src/screens/session-files.test.mjs +39 -0
  68. package/src/screens/setup.browser-test.mjs +49 -0
  69. package/src/screens/setup.mjs +78 -0
  70. package/src/screens/stack-auth.browser-test.mjs +30 -0
  71. package/src/screens/stack-auth.mjs +106 -0
  72. package/src/screens/stack-auth.test.mjs +65 -0
  73. package/src/screens/write-guard.mjs +26 -0
  74. package/src/stack/stack.mjs +131 -0
  75. package/src/stack/stack.test.mjs +40 -0
  76. package/src/stack/supervisor.mjs +30 -0
  77. package/templates/github/workflows/ci.yml +13 -5
@@ -0,0 +1,78 @@
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
+ }
@@ -0,0 +1,30 @@
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
+ });
@@ -0,0 +1,106 @@
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
+ }
@@ -0,0 +1,65 @@
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
+ });
@@ -0,0 +1,26 @@
1
+ import { requireLocalhost } from "./map.mjs";
2
+
3
+ const mutationName = /save|delete|submit|send|complete|upload|confirm|保存|削除|登録|送信|確定|竣工|アップロード|完了|取消|解除/i;
4
+
5
+ /** Branch: all navigation shares one list of mutation controls. */
6
+ export function safeControl(control) {
7
+ return control.type !== "submit" && !mutationName.test(control.text ?? control.name ?? "");
8
+ }
9
+
10
+ /** Branch: only explicit local opt-in and Auth0 sign-in permit writes. */
11
+ export function permitsRequest(method, value, target, allowWrites = false) {
12
+ const url = new URL(value);
13
+ if (["GET", "HEAD", "OPTIONS"].includes(method)) return ["http:", "https:"].includes(url.protocol);
14
+ if (target.auth?.domain === url.hostname && url.protocol === "https:" && /^\/(?:u\/login(?:\/|$)|oauth\/token$|usernamepassword\/login$|co\/authenticate$)/.test(url.pathname)) return true;
15
+ if (!allowWrites) return false;
16
+ try { requireLocalhost(target.baseUrl); requireLocalhost(url.href); return true; } catch { return false; }
17
+ }
18
+
19
+ /** Resource: the browser aborts requests before they reach a write endpoint. */
20
+ export async function installWriteGuard(context, target, { allowWrites = false, onBlocked = () => {} } = {}) {
21
+ await context.route("**/*", async route => {
22
+ const request = route.request();
23
+ if (permitsRequest(request.method(), request.url(), target, allowWrites)) await route.fallback();
24
+ else { onBlocked(); await route.abort("blockedbyclient"); }
25
+ });
26
+ }
@@ -0,0 +1,131 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync, rmSync, openSync, closeSync } from "node:fs";
2
+ import { spawn, execFile } from "node:child_process";
3
+ import { promisify } from "node:util";
4
+ import { randomUUID } from "node:crypto";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import net from "node:net";
8
+ import { fileURLToPath } from "node:url";
9
+ import { requireLocalhost } from "../screens/map.mjs";
10
+
11
+ export const stackRoot = () => path.join(os.homedir(), ".qc", "stacks");
12
+ export const readRegistry = () => JSON.parse(readFileSync(path.join(os.homedir(), ".qc", "stacks.json"), "utf8"));
13
+ export const healthUrls = manifest => typeof manifest.health === "string" ? [manifest.health] : Object.values(manifest.health ?? {});
14
+
15
+ /** Record: plugins declare local resources before the lifecycle starts. */
16
+ export function validateManifest(manifest) {
17
+ if (!/^[a-z0-9][a-z0-9_-]*$/i.test(manifest.name ?? "")) throw new Error("Invalid stack name");
18
+ for (const [name, port] of Object.entries(manifest.ports ?? {})) {
19
+ if (!Number.isInteger(port) || port < 1024 || port > 65535) throw new Error(`Invalid port ${name}`);
20
+ }
21
+ for (const key of ["up", "down"]) if (typeof manifest[key] !== "string" || !manifest[key]) throw new Error(`Stack requires ${key}`);
22
+ if (!healthUrls(manifest).length) throw new Error("Stack requires health URLs");
23
+ for (const url of healthUrls(manifest)) requireLocalhost(url);
24
+ if (!["form", "auth0-session"].includes(manifest.login?.kind)) throw new Error("Stack login requires form or auth0-session");
25
+ if (manifest.login.kind === "form") requireLocalhost(new URL(manifest.login.url, healthUrls(manifest)[0]).href);
26
+ return manifest;
27
+ }
28
+
29
+ /** Resource: resolve a registered repository without copying its environment. */
30
+ export function loadStack(name, registry = readRegistry()) {
31
+ const repo = registry[name];
32
+ if (typeof repo !== "string") throw new Error(`Unknown stack ${name}`);
33
+ const manifest = validateManifest(JSON.parse(readFileSync(path.join(repo, "qc.stack.json"), "utf8")));
34
+ if (manifest.name !== name) throw new Error(`Stack name differs from registry: ${name}`);
35
+ return { repo: path.resolve(repo), manifest };
36
+ }
37
+
38
+ const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
39
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch { return false; } };
40
+
41
+ async function portBusy(port) {
42
+ for (const host of ["127.0.0.1", "::1"]) {
43
+ const server = net.createServer();
44
+ const busy = await new Promise((resolve, reject) => {
45
+ server.once("error", error => error.code === "EADDRINUSE" || error.code === "EACCES" ? resolve(true) : reject(error));
46
+ server.listen({ port, host, exclusive: true }, () => server.close(() => resolve(false)));
47
+ });
48
+ if (busy) return true;
49
+ }
50
+ return false;
51
+ }
52
+
53
+ /** Branch: health requires a successful response from every declared endpoint. */
54
+ export async function healthy(manifest) {
55
+ const checks = await Promise.all(healthUrls(manifest).map(async url => {
56
+ try { return (await fetch(url, { signal: AbortSignal.timeout(2000), redirect: "manual" })).ok; } catch { return false; }
57
+ }));
58
+ return checks.every(Boolean);
59
+ }
60
+
61
+ /** Resource: commands inherit the repository environment and have a fixed bound. */
62
+ export function pluginCommand(command, repo, { timeout = 30000, env = process.env, stdio = "ignore" } = {}) {
63
+ return new Promise((resolve, reject) => {
64
+ const child = spawn(command, { cwd: repo, shell: true, windowsHide: true, env, stdio });
65
+ const timer = setTimeout(async () => { await stopTree(child.pid); reject(new Error("Stack command timed out")); }, timeout);
66
+ child.once("error", error => { clearTimeout(timer); reject(error); });
67
+ child.once("exit", code => { clearTimeout(timer); code === 0 ? resolve() : reject(new Error(`Stack command exited ${code}`)); });
68
+ });
69
+ }
70
+
71
+ /** Resource: stop only the process tree created by the supervisor. */
72
+ export async function stopTree(pid) {
73
+ if (!pid || !alive(pid)) return;
74
+ if (process.platform === "win32") await promisify(execFile)("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }).catch(() => {});
75
+ else { try { process.kill(-pid, "SIGTERM"); } catch { try { process.kill(pid, "SIGTERM"); } catch {} } }
76
+ }
77
+
78
+ /** Pipeline: persist ownership, wait for health, and compensate failed starts. */
79
+ export async function stackAction(action, names = [], { registry = readRegistry(), stateRoot = stackRoot(), timeout = 120000 } = {}) {
80
+ if (!["up", "down", "status"].includes(action)) throw new Error("Choose stack up, down, or status");
81
+ mkdirSync(stateRoot, { recursive: true, mode: 0o700 });
82
+ const rows = [];
83
+ const entries = (names.length ? names : Object.keys(registry)).map(name => ({ name, ...loadStack(name, registry) }));
84
+ for (const { name, repo, manifest } of entries) {
85
+ const file = path.join(stateRoot, `${name}.json`);
86
+ let state = existsSync(file) ? JSON.parse(readFileSync(file, "utf8")) : null;
87
+ let running = Boolean(state?.pid && alive(state.pid) && existsSync(`${file}.${state.token}.live`));
88
+ if (action === "up" && !running) {
89
+ for (const port of Object.values(manifest.ports ?? {})) if (await portBusy(port)) throw new Error(`Stack ${name}: port ${port} is in use`);
90
+ const token = randomUUID();
91
+ state = { repo, manifest, token, startedAt: new Date().toISOString() };
92
+ writeFileSync(file, JSON.stringify(state), { mode: 0o600 });
93
+ const log = openSync(path.join(stateRoot, `${name}.log`), "a", 0o600);
94
+ const worker = spawn(process.execPath, [fileURLToPath(new URL("./supervisor.mjs", import.meta.url)), file], { detached: true, windowsHide: true, stdio: ["ignore", log, log] });
95
+ closeSync(log);
96
+ await new Promise((resolve, reject) => { worker.once("spawn", resolve); worker.once("error", reject); });
97
+ worker.unref();
98
+ const deadline = Date.now() + timeout;
99
+ try {
100
+ while (true) {
101
+ state = JSON.parse(readFileSync(file, "utf8"));
102
+ if (state.error) throw new Error(`Stack ${name}: ${state.error}`);
103
+ if (state.pid && alive(state.pid) && await healthy(manifest)) break;
104
+ if (Date.now() >= deadline) throw new Error(`Stack ${name}: health timed out`);
105
+ await pause(200);
106
+ }
107
+ } catch (error) {
108
+ writeFileSync(`${file}.${token}.stop`, "stop");
109
+ await pause(500);
110
+ throw error;
111
+ }
112
+ running = true;
113
+ }
114
+ if (action === "down" && running) {
115
+ writeFileSync(`${file}.${state.token}.stop`, "stop");
116
+ const deadline = Date.now() + timeout;
117
+ while (alive(state.pid) && existsSync(`${file}.${state.token}.live`)) {
118
+ if (Date.now() > deadline) throw new Error(`Stack ${name}: down timed out`);
119
+ await pause(100);
120
+ }
121
+ rmSync(file, { force: true });
122
+ running = false;
123
+ }
124
+ let pluginHealthy = true;
125
+ if (action === "status" && running && manifest.status) {
126
+ try { await pluginCommand(manifest.status, repo, { timeout: Math.min(timeout, 15000) }); } catch { pluginHealthy = false; }
127
+ }
128
+ rows.push({ name, running, healthy: running && pluginHealthy && await healthy(manifest), baseUrl: healthUrls(manifest)[0], startedAt: state?.startedAt ?? null });
129
+ }
130
+ return rows;
131
+ }
@@ -0,0 +1,40 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import net from "node:net";
7
+ import { stackAction, validateManifest } from "./stack.mjs";
8
+
9
+ test("stack up waits for health, status observes it, and down stops its process", async () => {
10
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-stack-"));
11
+ const probe = net.createServer();
12
+ await new Promise(resolve => probe.listen(0, "127.0.0.1", resolve));
13
+ const port = probe.address().port;
14
+ await new Promise(resolve => probe.close(resolve));
15
+ const manifest = { name: "fixture", up: "node server.cjs", down: "node -e \"process.exit(0)\"", status: "node -e \"process.exit(0)\"", ports: { web: port }, health: [`http://127.0.0.1:${port}`], login: { kind: "form", url: "/login" } };
16
+ writeFileSync(path.join(root, "qc.stack.json"), JSON.stringify(manifest));
17
+ writeFileSync(path.join(root, "server.cjs"), `require('node:http').createServer((q,s)=>s.end('ok')).listen(${port},'127.0.0.1')`);
18
+ try {
19
+ const options = { registry: { fixture: root }, stateRoot: path.join(root, "state"), timeout: 8000 };
20
+ assert.equal((await stackAction("up", ["fixture"], options))[0].healthy, true);
21
+ assert.equal((await stackAction("status", ["fixture"], options))[0].healthy, true);
22
+ const other = path.join(root, "other");
23
+ mkdirSync(other);
24
+ writeFileSync(path.join(other, "qc.stack.json"), JSON.stringify({ ...manifest, name: "other" }));
25
+ await assert.rejects(stackAction("up", ["fixture", "other"], { ...options, registry: { fixture: root, other } }), /Stack other: port .* is in use/);
26
+ assert.equal((await stackAction("down", ["fixture"], options))[0].running, false);
27
+ await new Promise(resolve => probe.listen(port, "127.0.0.1", resolve));
28
+ await assert.rejects(stackAction("up", ["fixture"], options), /in use/);
29
+ await new Promise(resolve => probe.close(resolve));
30
+ } finally { if (probe.listening) await new Promise(resolve => probe.close(resolve)); rmSync(root, { recursive: true, force: true }); }
31
+ });
32
+ test("stack accepts a database on port 5432", () => {
33
+ const manifest = { name: "x", up: "node app", down: "node stop", ports: { db: 5432 }, health: ["http://localhost:3000"], login: { kind: "auth0-session" } };
34
+ assert.equal(validateManifest(manifest).ports.db, 5432);
35
+ });
36
+ test("stack refuses remote health URLs", () => {
37
+ const manifest = { name: "x", up: "node app", down: "node stop", ports: { db: 5433 }, health: ["http://localhost:3000"], login: { kind: "auth0-session" } };
38
+ manifest.health = ["https://cloud.example"];
39
+ assert.throws(() => validateManifest(manifest), /localhost/);
40
+ });
@@ -0,0 +1,30 @@
1
+ import { existsSync, readFileSync, writeFileSync, rmSync } from "node:fs";
2
+ import { spawn } from "node:child_process";
3
+ import { pluginCommand, stopTree } from "./stack.mjs";
4
+
5
+ const file = process.argv[2];
6
+ const state = JSON.parse(readFileSync(file, "utf8"));
7
+ const live = `${file}.${state.token}.live`;
8
+ const stop = `${file}.${state.token}.stop`;
9
+ state.pid = process.pid;
10
+ writeFileSync(file, JSON.stringify(state), { mode: 0o600 });
11
+ writeFileSync(live, state.token, { mode: 0o600 });
12
+ const child = spawn(state.manifest.up, { cwd: state.repo, shell: true, detached: process.platform !== "win32", windowsHide: true, stdio: "inherit" });
13
+ child.on("error", () => { state.error = "Cannot start plugin command"; writeFileSync(file, JSON.stringify(state)); });
14
+ child.on("exit", code => { if (code) { state.error = `Plugin exited ${code}`; writeFileSync(file, JSON.stringify(state)); } });
15
+ let refreshing = false;
16
+ const timer = setInterval(async () => {
17
+ if (existsSync(stop)) {
18
+ clearInterval(timer);
19
+ try { await pluginCommand(state.manifest.down, state.repo); }
20
+ finally { await stopTree(child.pid); rmSync(live, { force: true }); rmSync(stop, { force: true }); process.exit(0); }
21
+ }
22
+ if (!refreshing && state.manifest.login.kind === "auth0-session") {
23
+ refreshing = true;
24
+ try {
25
+ const { refreshStackSessions } = await import("../screens/stack-auth.mjs");
26
+ await refreshStackSessions(state.manifest.name);
27
+ } catch { /* The refresh ledger delays a failed session until its next due time. */ }
28
+ finally { refreshing = false; }
29
+ }
30
+ }, 1000);
@@ -38,11 +38,19 @@ jobs:
38
38
  - if: github.event_name == 'pull_request'
39
39
  run: npx qc prose --base "origin/$GITHUB_BASE_REF" --pr-body-event
40
40
 
41
- # Uncomment each as the repository grows the thing it checks.
42
- # - run: pnpm typecheck
43
- # - run: pnpm lint
44
- # - run: pnpm dup:check
45
- # - run: pnpm test
41
+ # Typecheck and lint as the stop gate runs them: a root script wins, else the installed tool.
42
+ # CI is the one check an agent cannot skip, so each step is on, and without its tool it says it skipped.
43
+ - run: |
44
+ if node -e "process.exit(require('./package.json').scripts?.typecheck ? 0 : 1)"; then pnpm run typecheck
45
+ elif [ -x node_modules/.bin/tsc ]; then pnpm exec tsc -b --pretty false
46
+ else echo "::notice::typecheck skipped: no typecheck script and no tsc"
47
+ fi
48
+ - run: |
49
+ if node -e "process.exit(require('./package.json').scripts?.lint ? 0 : 1)"; then pnpm run lint
50
+ elif [ -x node_modules/.bin/eslint ]; then pnpm exec eslint . --max-warnings 0
51
+ else echo "::notice::lint skipped: no lint script and no eslint"
52
+ fi
53
+ - run: pnpm run --if-present dup:check
46
54
 
47
55
  # Unit tests in eight hosted shards. A self-hosted runner that goes offline leaves a job queued;
48
56
  # `qc watch --pr` reports a check queued for over 15 minutes. A repository with no test:unit script skips it.