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,51 @@
1
+ import { strict as assert } from "node:assert";
2
+ import path from "node:path";
3
+ import { test } from "node:test";
4
+ import { failedFiles, runRetryFailed } from "./retry-failed.mjs";
5
+
6
+ const ROOT = path.resolve("/repo");
7
+ const report = (...results) => JSON.stringify({ testResults: results.map(([name, status]) => ({ name: path.join(ROOT, name), status })) });
8
+
9
+ test("the failed files of a Jest or Vitest report are read relative to the root", () => {
10
+ assert.deepEqual(failedFiles(report(["src/a.test.ts", "failed"], ["src/b.test.ts", "passed"]), ROOT), ["src/a.test.ts"]);
11
+ assert.equal(failedFiles("not json", ROOT), null);
12
+ assert.equal(failedFiles("{}", ROOT), null);
13
+ });
14
+
15
+ /** A runner that answers from a list of exit codes, and records each command. */
16
+ function scripted(codes, ran) {
17
+ return async (command) => {
18
+ ran.push(command);
19
+ return codes.shift();
20
+ };
21
+ }
22
+
23
+ const deps = (overrides) => ({ cwd: ROOT, env: {}, say: () => {}, remove: () => {}, ...overrides });
24
+
25
+ test("a run that fails in two test files reruns only those files once, and passes when the rerun passes", async () => {
26
+ const ran = [];
27
+ const code = await runRetryFailed(["--report", "r.json", "--rerun", "pnpm vitest run", "--", "pnpm", "check:local"], deps({
28
+ run: scripted([1, 0], ran),
29
+ read: () => report(["src/a.test.ts", "failed"], ["src/b.test.ts", "failed"]),
30
+ }));
31
+ assert.equal(code, 0);
32
+ assert.deepEqual(ran, ["pnpm check:local", "pnpm vitest run src/a.test.ts src/b.test.ts"]);
33
+ });
34
+
35
+ test("a failure with no report, or with more failed files than the limit, is not rerun", async () => {
36
+ const ran = [];
37
+ const argv = ["--report", "r.json", "--rerun", "pnpm vitest run", "--max-files", "1", "--", "pnpm", "check:local"];
38
+ assert.equal(await runRetryFailed(argv, deps({ run: scripted([3], ran), read: () => null })), 3);
39
+ assert.equal(await runRetryFailed(argv, deps({ run: scripted([1], ran), read: () => report(["a.test.ts", "failed"], ["b.test.ts", "failed"]) })), 1);
40
+ assert.deepEqual(ran, ["pnpm check:local", "pnpm check:local"]);
41
+ });
42
+
43
+ test("the report of an earlier run is removed before the command runs", async () => {
44
+ const removed = [];
45
+ await runRetryFailed(["--report", "r.json", "--rerun", "x", "--", "y"], deps({ run: async () => 0, read: () => null, remove: (file) => removed.push(file) }));
46
+ assert.deepEqual(removed, [path.join(ROOT, "r.json")]);
47
+ });
48
+
49
+ test("a missing flag or command is a usage error", async () => {
50
+ assert.equal(await runRetryFailed(["--", "pnpm", "test"], deps({ run: async () => 0, read: () => null })), 2);
51
+ });
@@ -25,6 +25,11 @@ const KNOWN_EXTENSIONS = new Set(
25
25
  "mjs cjs js jsx ts tsx json md yml yaml sh sql css html cs py go rs toml txt xml csv".split(" "),
26
26
  );
27
27
 
28
+ const SCOPE_LINE = /^[ \t]*Scope:[ \t]*(\S.*?)[ \t]*$/im;
29
+
30
+ /** The scope on a prompt's `Scope:` line, in lowercase, or null. */
31
+ export const scopeOf = (prompt) => SCOPE_LINE.exec(String(prompt ?? ""))?.[1]?.toLowerCase() ?? null;
32
+
28
33
  const short = (sha) => (typeof sha === "string" ? sha.slice(0, 7) : "(none)");
29
34
  const pass = (note = null) => ({ refusal: null, note });
30
35
  const refuse = (refusal) => ({ refusal, note: null });
@@ -51,20 +56,24 @@ export const unreadableRefusal = (type, why) =>
51
56
  "Add a line `Worktree: <path>` that names a worktree whose checked-out branch is the branch under review, then dispatch.";
52
57
 
53
58
  function branchReviewRefusal({ records, branch, prompt }) {
54
- const last = records.findLast((record) => record.type === "verdict" && record.kind === "branch" && record.branch === branch);
59
+ const scope = scopeOf(prompt);
60
+ const counts = (record) =>
61
+ record.type === "verdict" && record.kind === "branch" && record.branch === branch && (scope === null || record.scope === scope);
62
+ const last = records.findLast(counts);
55
63
  if (!last) return null;
56
64
  const named = reviewedShaOf(prompt);
65
+ const which = scope === null ? "a branch review" : `a branch review of scope "${scope}"`;
57
66
  if (named === null) {
58
67
  return (
59
- `Task gate: ${branch} already has a branch review in the ledger (${short(last.sha)}), and a PR gets one. ` +
60
- `Send the incremental review: add a line \`Reviewed: ${short(last.sha)}\`, the last head a branch review named, and pass the delta diff ${short(last.sha)}..<head> in place of the whole branch.`
68
+ `Task gate: ${branch} already has ${which} in the ledger (${short(last.sha)}), and a PR gets one. ` +
69
+ `Send the incremental review: add a line \`Reviewed: ${short(last.sha)}\`, the last head a branch review named, and pass the delta diff ${short(last.sha)}..<head> in place of the whole branch. ` +
70
+ "A review of another part of the branch runs beside it with its own line `Scope: <name>`."
61
71
  );
62
72
  }
63
- const known = records.some((record) => record.type === "verdict" && record.kind === "branch" && record.branch === branch && shaMatches(record.sha, named));
64
- if (known) return null;
73
+ if (records.some((record) => counts(record) && shaMatches(record.sha, named))) return null;
65
74
  return (
66
- `Task gate: \`Reviewed: ${short(named)}\` is no head a branch review of ${branch} named. ` +
67
- `Write the last head a branch review named: \`Reviewed: ${short(last.sha)}\`.`
75
+ `Task gate: \`Reviewed: ${short(named)}\` is no head ${which} of ${branch} named. ` +
76
+ `Write the last head ${which} named: \`Reviewed: ${short(last.sha)}\`.`
68
77
  );
69
78
  }
70
79
 
@@ -0,0 +1,60 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { discover, pairStates, catalogCoverage, scaffoldEntry } from "../screens/discovery.mjs";
4
+ import { targetSession } from "../screens/stack-auth.mjs";
5
+
6
+ /** Trigger: discovery artifacts drive pairing, coverage, and catalog scaffolds. */
7
+ export async function runDiscovery(command, map, values, { chromium, say }) {
8
+ const out = path.resolve(values.out ?? ".");
9
+ mkdirSync(out, { recursive: true });
10
+ const read = name => JSON.parse(readFileSync(path.join(out, `discovered-${name}.json`), "utf8"));
11
+ if (command === "discover") {
12
+ const target = map.targets[values.target];
13
+ if (!target) throw new Error("Choose --target from the map");
14
+ const timeout = Number(values.timeout ?? 15000);
15
+ const depth = Number(values.depth ?? 4);
16
+ const maxStates = Number(values["max-states"] ?? 500);
17
+ if (!Number.isInteger(depth) || depth < 0 || !Number.isInteger(maxStates) || maxStates < 1) throw new Error("Invalid depth or state bound");
18
+ const session = await targetSession(chromium, target, { timeout, signInTimeout: Number(values["sign-in-timeout"] ?? 180000), targetName: values.target, say });
19
+ try {
20
+ const routes = [...new Map(map.screens.flatMap(screen => screen.targets[values.target]?.path ? [screen.targets[values.target].path] : []).map(route => [route, route])).values()];
21
+ const result = await discover(session, { ...target, routes: target.routes ?? routes }, { out, targetName: values.target, widths: map.widths, depth, timeout, maxStates, allowWrites: values["allow-writes"], say });
22
+ say(JSON.stringify({ target: result.target, states: result.states.length, counts: result.counts, errors: result.errors.length, unresolvedRoutes: result.unresolvedRoutes, blockedRequests: result.blockedRequests, complete: result.complete }));
23
+ return result.complete ? 0 : 1;
24
+ } finally { await session.close(); }
25
+ }
26
+ if (command === "pair") {
27
+ const names = values.targets?.split(",");
28
+ if (names?.length !== 2) throw new Error("pair requires --targets <legacy,mono>");
29
+ const pairs = pairStates(read(names[0]).states, read(names[1]).states);
30
+ const result = { targets: names, pairs, counts: Object.fromEntries(["paired", "legacy-only", "mono-only"].map(kind => [kind, pairs.filter(item => item.kind === kind).length])) };
31
+ writeFileSync(path.join(out, "pairs.json"), JSON.stringify(result, null, 2));
32
+ say(JSON.stringify(result.counts));
33
+ return 0;
34
+ }
35
+ const names = values.target ? [values.target] : readdirSync(out).filter(name => /^discovered-.+\.json$/.test(name)).map(name => name.slice(11, -5));
36
+ if (!names.length) throw new Error("No discoveries found");
37
+ if (command === "coverage") {
38
+ const rows = names.map(name => {
39
+ const discovered = read(name);
40
+ return { target: name, complete: discovered.complete, ...catalogCoverage(discovered.states, map.screens, map.excluded, name) };
41
+ });
42
+ writeFileSync(path.join(out, "coverage.json"), JSON.stringify(rows, null, 2));
43
+ for (const row of rows) say(JSON.stringify({ target: row.target, complete: row.complete, covered: row.covered, total: row.total, missing: row.missing.length }));
44
+ return rows.some(row => !row.complete || row.missing.length) ? 1 : 0;
45
+ }
46
+ const directory = path.resolve(values["catalog-out"] ?? path.join(out, "catalog"));
47
+ mkdirSync(directory, { recursive: true });
48
+ let written = 0;
49
+ for (const name of names) {
50
+ const family = map.targets[name]?.family ?? name.split("-")[0];
51
+ for (const state of read(name).states) {
52
+ const file = path.join(directory, `${name}-${state.id}.ts`);
53
+ if (existsSync(file)) continue;
54
+ writeFileSync(file, scaffoldEntry(state, family), { flag: "wx" });
55
+ written++;
56
+ }
57
+ }
58
+ say(JSON.stringify({ directory, written }));
59
+ return 0;
60
+ }
@@ -0,0 +1,84 @@
1
+ import path from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ import { loadMap } from "../screens/map.mjs";
4
+ import { captureScreens } from "../screens/capture.mjs";
5
+ import { authStatus, targetSession } from "../screens/stack-auth.mjs";
6
+ import { applyCatalog, openScreen } from "../screens/catalog.mjs";
7
+ import { runDiscovery } from "./screens-discovery.mjs";
8
+ import { setupLocal } from "../screens/setup.mjs";
9
+ import { installWriteGuard } from "../screens/write-guard.mjs";
10
+
11
+ export const USAGE = `qc screens [run [names...]|list|open <name>|auth status|auth <target> --headed|setup]
12
+ qc screens discover|pair|coverage|scaffold --map <json> --out <dir>
13
+ --map <json> [--targets <left,right>] [--target <name>] [--out <dir>]
14
+ [--only <names>] [--changed <target>] [--height <pixels>]
15
+ [--timeout <milliseconds>] [--sign-in-timeout <milliseconds>]
16
+ [--depth <levels>] [--max-states <count>] [--allow-writes] [--catalog-out <dir>]
17
+
18
+ Chrome must be installed. Sessions stay in ~/.qc/screens.
19
+ Catalog modules live outside the kit. open waits until you close its window.`;
20
+
21
+ /** Trigger: screen commands share the same catalog, sessions, and map. */
22
+ export async function runScreens(argv, { say = console.error, sessionFactory = targetSession } = {}) {
23
+ let values, positionals;
24
+ const command = argv[0]?.startsWith("--") || !argv.length ? "run" : argv.shift();
25
+ const authTarget = command === "auth" ? argv.shift() : undefined;
26
+ const authCommand = command === "auth" && authTarget === "status";
27
+ try {
28
+ ({ values, positionals } = parseArgs({ args: argv, allowPositionals: true, strict: true, options: { map: { type: "string" }, targets: { type: "string" }, target: { type: "string" }, out: { type: "string" }, only: { type: "string" }, changed: { type: "string" }, height: { type: "string" }, timeout: { type: "string" }, "sign-in-timeout": { type: "string" }, depth: { type: "string" }, "max-states": { type: "string" }, "allow-writes": { type: "boolean" }, "catalog-out": { type: "string" }, headed: { type: "boolean" }, help: { type: "boolean" } } }));
29
+ if (values.help) { say(USAGE); return 0; }
30
+ if (!values.map) throw new Error("--map is required");
31
+ for (const field of ["height", "timeout", "sign-in-timeout"]) if (values[field] !== undefined && (!Number.isInteger(Number(values[field])) || Number(values[field]) < 1)) throw new Error(`--${field} must be a positive integer`);
32
+ const selectedTargets = values.targets?.split(",") ?? (values.target ? [values.target] : command === "auth" && !authCommand && authTarget ? [authTarget] : command === "list" ? [] : undefined);
33
+ const map = await applyCatalog(loadMap(path.resolve(values.map), { targets: selectedTargets }), path.resolve(values.map));
34
+ if (command === "list") {
35
+ for (const item of map.screens) say(`${item.name}\t${Object.keys(item.targets).join(", ")}`);
36
+ return 0;
37
+ }
38
+ const { chromium } = await import("playwright");
39
+ if (command === "setup") {
40
+ const target = map.targets[values.target];
41
+ if (!target) throw new Error("Choose --target from the map");
42
+ say(JSON.stringify(await setupLocal(target, values.target, { chromium, timeout: Number(values.timeout ?? 15000), signInTimeout: Number(values["sign-in-timeout"] ?? 180000), say })));
43
+ return 0;
44
+ }
45
+ if (["discover", "pair", "coverage", "scaffold"].includes(command)) return await runDiscovery(command, map, values, { chromium, say });
46
+ const timeout = Number(values.timeout ?? 15000);
47
+ const signInTimeout = Number(values["sign-in-timeout"] ?? 180000);
48
+ if (authCommand) {
49
+ const targets = values.target ? { [values.target]: map.targets[values.target] } : map.targets;
50
+ if (Object.values(targets).some(target => !target)) throw new Error("Unknown target");
51
+ for (const row of await authStatus(chromium, targets, { timeout })) say(JSON.stringify(row));
52
+ return 0;
53
+ }
54
+ if (command === "auth") {
55
+ const target = map.targets[authTarget];
56
+ if (!target || !values.headed) throw new Error("Choose auth <target> --headed from the map");
57
+ const session = await targetSession(chromium, target, { timeout, signInTimeout, say, targetName: authTarget, allowInteractive: true, headed: true });
58
+ await session.close();
59
+ say(`${authTarget}: signed in`);
60
+ return 0;
61
+ }
62
+ if (command === "open") {
63
+ const target = map.targets[values.target];
64
+ const item = map.screens.find(item => item.name === positionals[0]);
65
+ const route = item?.targets[values.target];
66
+ if (!target || !route) throw new Error("Choose a screen name and --target from the map");
67
+ const allowWrites = values["allow-writes"] === true;
68
+ const session = await sessionFactory(chromium, target, { timeout, signInTimeout, say, targetName: values.target, headed: true, allowWrites });
69
+ try {
70
+ await installWriteGuard(session.context, target, { allowWrites });
71
+ await session.page.setViewportSize({ width: map.widths[0], height: Number(values.height ?? 900) });
72
+ if (route.open) await openScreen(session.page, target, route, { targetName: values.target, screenName: item.name, out: path.resolve(values.out ?? "."), timeout });
73
+ else await session.page.goto(new URL(route.path, target.baseUrl).href, { timeout });
74
+ await new Promise(resolve => session.page.once("close", resolve));
75
+ } finally { await session.close().catch(() => {}); }
76
+ return 0;
77
+ }
78
+ if (command !== "run") throw new Error(`Unknown screens command ${command}`);
79
+ if (!values.targets || !values.out) throw new Error("--targets and --out are required");
80
+ const report = await captureScreens(map, { targets: values.targets.split(",").map(name => name.trim()), out: path.resolve(values.out), only: positionals.length ? positionals.join(",") : values.only, changed: values.changed, height: Number(values.height ?? 900), timeout, signInTimeout, allowWrites: values["allow-writes"] === true }, { chromium, say });
81
+ for (const row of report) say(JSON.stringify(row));
82
+ return report.some(row => row.error) ? 1 : 0;
83
+ } catch (error) { say(error.exitCode === 4 ? error.message : `qc screens: ${error.message}`); return error.exitCode === 4 ? 4 : 1; }
84
+ }
@@ -0,0 +1,43 @@
1
+ #!/usr/bin/env node
2
+ // PreToolUse on a shell command or an edit: a subagent may not touch a slot folder. The hooks and
3
+ // `qc gate-slot` own those files, and a hand edit leaves a slot claimed or frees one still in use.
4
+
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ const SLOT_FOLDER = /architecture-kit[\\/]+(?:dispatch|gate-slots)(?:[\\/"'\s]|$)/i;
8
+ const REASON =
9
+ "Slot guard: a subagent may not touch a slot folder. The hooks and `qc gate-slot` own those files. " +
10
+ "Wrap a heavy command in `npx qc gate-slot --`, and ask the controller to free a slot.";
11
+
12
+ const norm = (text) => text.replace(/\\+/g, "/").toLowerCase();
13
+
14
+ /** The text of a call that can name a path: its command, or its file path. */
15
+ const targetOf = (input) => [input?.command, input?.file_path, input?.notebook_path].filter((value) => typeof value === "string").join("\n");
16
+
17
+ /** @returns the hook output that denies the call, or null to let it run */
18
+ export function decide(call, env = process.env) {
19
+ if (call?.hook_event_name !== "PreToolUse") return null;
20
+ if (typeof call.agent_id !== "string" || call.agent_id === "") return null;
21
+ const text = targetOf(call.tool_input);
22
+ const custom = typeof env.QC_GATE_SLOT_DIR === "string" && env.QC_GATE_SLOT_DIR !== "" && norm(text).includes(norm(env.QC_GATE_SLOT_DIR));
23
+ if (!SLOT_FOLDER.test(text) && !custom) return null;
24
+ return { hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: REASON } };
25
+ }
26
+
27
+ async function readStdin() {
28
+ let data = "";
29
+ for await (const chunk of process.stdin) data += chunk;
30
+ return data;
31
+ }
32
+
33
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
34
+ if (isEntryPoint) {
35
+ let call = null;
36
+ try {
37
+ call = JSON.parse(await readStdin());
38
+ } catch {
39
+ // Not hook input, so there is nothing to judge.
40
+ }
41
+ const result = call ? decide(call) : null;
42
+ if (result) process.stdout.write(JSON.stringify(result));
43
+ }
@@ -0,0 +1,28 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { readFileSync } from "node:fs";
3
+ import { test } from "node:test";
4
+ import { fileURLToPath } from "node:url";
5
+ import { decide } from "./slot-guard.mjs";
6
+
7
+ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
8
+ const call = (tool_name, tool_input, agent_id = "agent-1") => ({ hook_event_name: "PreToolUse", tool_name, tool_input, agent_id });
9
+ const denied = (output) => output?.hookSpecificOutput?.permissionDecision === "deny";
10
+
11
+ test("a subagent may not touch a slot folder, by a command or by an edit", () => {
12
+ assert.ok(denied(decide(call("Bash", { command: "rm -rf /tmp/architecture-kit/gate-slots/slot-0.json" }), {})));
13
+ assert.ok(denied(decide(call("PowerShell", { command: "Remove-Item C:\\Temp\\architecture-kit\\dispatch\\s1 -Recurse" }), {})));
14
+ assert.ok(denied(decide(call("Write", { file_path: "C:/Temp/architecture-kit/gate-slots/slot-1.json" }), {})));
15
+ assert.ok(denied(decide(call("Bash", { command: "rm -rf D:/slots/slot-0.json" }), { QC_GATE_SLOT_DIR: "D:\\slots" })));
16
+ });
17
+
18
+ test("the main session, the gate-slot command, and the kit's own source pass", () => {
19
+ assert.equal(decide(call("Bash", { command: "rm -rf /tmp/architecture-kit/gate-slots" }, ""), {}), null);
20
+ assert.equal(decide(call("Bash", { command: "npx qc gate-slot -- pnpm check:local" }), {}), null);
21
+ assert.equal(decide(call("Edit", { file_path: "C:/GitHub/architecture-kit/packages/qc-harness/src/cli/dispatch-slot.mjs" }), {}), null);
22
+ });
23
+
24
+ test("hooks.json runs the slot guard before a shell command or an edit", () => {
25
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
26
+ const matchers = hooks.PreToolUse.filter((entry) => entry.hooks.some((hook) => hook.command.includes("slot-guard.mjs"))).map((entry) => entry.matcher);
27
+ assert.deepEqual(matchers, ["Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit"]);
28
+ });
@@ -0,0 +1,14 @@
1
+ import { parseArgs } from "node:util";
2
+ import { stackAction } from "../stack/stack.mjs";
3
+
4
+ /** Trigger: a repository plugin owns each stack's lifecycle. */
5
+ export async function runStack(argv, { say = console.log } = {}) {
6
+ try {
7
+ const [action, ...rest] = argv;
8
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { timeout: { type: "string", default: "120000" } } });
9
+ const timeout = Number(values.timeout);
10
+ if (!Number.isInteger(timeout) || timeout < 1) throw new Error("--timeout must be a positive integer");
11
+ for (const row of await stackAction(action, positionals, { timeout })) say(JSON.stringify(row));
12
+ return 0;
13
+ } catch (error) { say(`qc stack: ${error.message}`); return 1; }
14
+ }
@@ -223,3 +223,13 @@ test("the dispatch guard refuses a reviewer and claims no slot for it", (t) => {
223
223
  assert.equal(output.hookSpecificOutput.permissionDecision, "deny");
224
224
  assert.match(output.hookSpecificOutput.permissionDecisionReason, /^Task gate:/);
225
225
  });
226
+
227
+ test("branch reviews of distinct scopes run on one head, and a second review of one scope needs a Reviewed line", (t) => {
228
+ const ws = workspace(t);
229
+ const head = git(ws.linked, "rev-parse", "HEAD");
230
+ appendRecord(ws.ledger, { type: "verdict", kind: "branch", verdict: "APPROVED", sha: head, branch: "feat/1-x", scope: "photos" });
231
+ assert.equal(judge(ws, BRANCH_REVIEWER, reviewPrompt(ws, "Scope: Inspections")).refusal, null);
232
+ assert.match(judge(ws, BRANCH_REVIEWER, reviewPrompt(ws, "Scope: photos")).refusal ?? "", /scope "photos".*Reviewed: /s);
233
+ assert.match(judge(ws, BRANCH_REVIEWER, reviewPrompt(ws)).refusal ?? "", /Scope: <name>/);
234
+ assert.equal(judge(ws, BRANCH_REVIEWER, reviewPrompt(ws, `Scope: photos\nReviewed: ${head.slice(0, 7)}`)).refusal, null);
235
+ });
@@ -10,28 +10,33 @@ import { handoffPathOf, resolveHandoff } from "./handoff-note.mjs";
10
10
  import { gitOutWithin, linkedWorktrees, pathKey } from "./git-read.mjs";
11
11
  import { appendRecord, latestVerdictFor, latestVerdictOn, readLedger, shaMatches } from "./ledger.mjs";
12
12
  import { resolveNamedWorktree, workflowOfRepo, worktreeNamed } from "./workflow-place.mjs";
13
- import { READ_MS, branchOfCheckout, briefCheck, defaultReads, headOf, reviewerCheck, unreadableRefusal } from "./review-gate.mjs";
13
+ import { READ_MS, branchOfCheckout, briefCheck, defaultReads, headOf, reviewerCheck, scopeOf, unreadableRefusal } from "./review-gate.mjs";
14
14
  import { rememberSession, workflowAt } from "./workflow-settings.mjs";
15
15
 
16
16
  export { worktreeNamed };
17
17
 
18
18
  const NO_RESUME_LINE = /^[ \t]*NO-RESUME:[ \t]*(\S.*?)[ \t]*$/im;
19
+ const FIX_LINE = /^[ \t]*Fix:[ \t]*(ci|review)[ \t]*$/im;
19
20
  const short = (sha) => (typeof sha === "string" ? sha.slice(0, 7) : "(none)");
20
21
 
21
22
  /** The reason on a prompt's `NO-RESUME:` line, or null. */
22
23
  export const noResumeReason = (prompt) => NO_RESUME_LINE.exec(prompt)?.[1] ?? null;
23
24
 
25
+ /** The purpose on a prompt's `Fix:` line, `ci` or `review`, or null. */
26
+ export const fixOf = (prompt) => FIX_LINE.exec(prompt)?.[1]?.toLowerCase() ?? null;
27
+
24
28
  const fixRoundRefusal = (branch, sha, type) =>
25
29
  `Task gate: the last review on ${branch} (${short(sha)}) is CHANGES_REQUIRED, so the fix goes back to the implementer that wrote it. ` +
26
30
  "Resume it with SendMessage and the findings, then have the fix reviewed. " +
27
- `If a resume cannot work, such as a spent tool-call budget, add a line \`NO-RESUME: <reason>\` to the ${type} prompt; the ledger records the reason.`;
31
+ `If a resume cannot work, such as a spent tool-call budget, add a line \`NO-RESUME: <reason>\` to the ${type} prompt; the ledger records the reason. ` +
32
+ "A fresh agent that fixes the review findings adds a line `Fix: review` instead.";
28
33
 
29
34
  const unreviewedRefusal = (branch, stopHead, head) =>
30
35
  `Task gate: an implementer stopped on ${branch} at ${short(stopHead)}, and no review in the ledger names ${short(stopHead)} or a later commit. ` +
31
36
  `Dispatch the task reviewer on ${short(head)} first; its first line \`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>\` records the review. ` +
32
37
  `The review runs once CI on the head is green: when CI on ${short(stopHead)} has failed or still runs, the next implementer continues the task and this gate passes it. ` +
33
38
  `If that stop handed off, its report named \`HANDOFF: <note path>\`; the same line in the next implementer prompt continues the task. ` +
34
- `\`qc ledger ${branch}\` lists what is recorded.`;
39
+ `\`qc ledger ${branch}\` lists what is recorded. A CI fix adds a line \`Fix: ci\`, and a review fix adds \`Fix: review\`.`;
35
40
 
36
41
  const HISTORY_LIMIT = 5000;
37
42
  // A read is capped, so the whole dispatch guard ends inside the Agent hook's 30 second limit.
@@ -76,13 +81,31 @@ export function continuedStop(records, branch, handoff) {
76
81
  return reviewed ? null : stop;
77
82
  }
78
83
 
84
+ /** A CI fix or a review fix may start on a red or unreviewed head; a CI fix on a head whose CI is green is refused. */
85
+ function fixVerdict({ records, branch, head, fix, ciStatus }) {
86
+ if (fix === "ci") {
87
+ const state = ciStatus(head);
88
+ if (state.reason === null) {
89
+ const why = state.unknown === null ? "is green" : `is not known to be red (${state.unknown})`;
90
+ return { refusal: `Task gate: \`Fix: ci\` names a CI fix, and CI on ${short(head)} ${why}. A CI fix needs a red run. Dispatch the reviewer, or drop the line.` };
91
+ }
92
+ return { refusal: null, fix };
93
+ }
94
+ const last = latestVerdictOn(records, branch);
95
+ if (last?.verdict !== "CHANGES_REQUIRED") {
96
+ return { refusal: `Task gate: \`Fix: review\` on ${branch}, where no review in the ledger asks for changes. Drop the line, or dispatch the reviewer first.` };
97
+ }
98
+ return { refusal: null, fix };
99
+ }
100
+
79
101
  /**
80
102
  * The task gate's answer for an implementer on `branch`: `refusal` is the reason it may not start now, or null.
81
103
  * `ciPass` is `{ sha, reason }` when an unreviewed stop head passes because CI on it is not green, else absent.
82
104
  * Only implementer commits need a review, so a controller commit after a reviewed head passes. `cwd` is any
83
105
  * checkout; `git` reads it, and `ci` answers why CI on a sha is not green, or null.
84
106
  */
85
- export function gateVerdict({ records, branch, head, reason, type, cwd, git = gitRead, handoff = null, ci = (sha) => ciNotGreen(sha, cwd) }) {
107
+ export function gateVerdict({ records, branch, head, reason, type, cwd, git = gitRead, handoff = null, ci = (sha) => ciNotGreen(sha, cwd), fix = null, ciStatus = (sha) => readCiState(sha, cwd) }) {
108
+ if (fix !== null) return fixVerdict({ records, branch, head, fix, ciStatus });
86
109
  // A continuation of the newest stop's hand-off is the same task, so it is neither a fix round nor a new task.
87
110
  const continued = continuedStop(records, branch, handoff);
88
111
  const why = reason ?? (continued ? `continues the hand-off ${continued.handoff}` : null);
@@ -180,7 +203,9 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
180
203
  }
181
204
  const checked = reviewerCheck({ type, prompt, review: workflow.review, base: workflow.base, records, root, branch, head, ciState: state, reads });
182
205
  if (checked.refusal) return refuse(checked.refusal);
183
- return pass(workflow, { ...base, worktree: root, branch, head }, [ledgerNote, checked.note].filter(Boolean).join(" ") || null);
206
+ const scope = scopeOf(prompt);
207
+ const scoped = scope && workflow.review.reviewerTypes.branch.includes(type) ? { scope } : {};
208
+ return pass(workflow, { ...base, worktree: root, branch, head, ...scoped }, [ledgerNote, checked.note].filter(Boolean).join(" ") || null);
184
209
  }
185
210
  if (named === null) return pass(workflow, base, briefNote);
186
211
  const key = pathKey(abs);
@@ -198,11 +223,18 @@ export function judgeTask(call, tmp = os.tmpdir(), { ci, ciState, reads = defaul
198
223
  const reason = noResumeReason(prompt);
199
224
  const spelled = handoffPathOf(prompt);
200
225
  const handoff = spelled === null ? null : resolveHandoff(spelled, cwd);
201
- const { refusal, ciPass } = gateVerdict({ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff, ...(ci ? { ci } : {}) });
226
+ const fix = fixOf(prompt);
227
+ const { refusal, ciPass, note: fixNote } = gateVerdict({
228
+ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff, fix,
229
+ ...(ci ? { ci } : {}),
230
+ ...(ciState ? { ciStatus: ciState } : {}),
231
+ });
202
232
  if (refusal) return refuse(refusal);
203
233
  const continues = handoff ? { handoff } : {};
204
234
  const unreviewed = ciPass ? { ciPass } : {};
205
- return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason, ...continues, ...unreviewed }, briefNote);
235
+ const purpose = fix ? { fix } : {};
236
+ const notes = [briefNote, fixNote].filter(Boolean).join(" ") || null;
237
+ return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason, ...continues, ...unreviewed, ...purpose }, notes);
206
238
  }
207
239
 
208
240
  /** Writes the dispatch record of a judged call. @returns a note for the session, or null. */
@@ -567,3 +567,48 @@ test("gateVerdict reports the stop and the reason of a CI pass, and gateRefusal
567
567
  assert.match(gateRefusal({ ...input, ci: () => null }) ?? "", /no review/);
568
568
  assert.equal(gateRefusal({ ...input, ci: () => "red" }), null);
569
569
  });
570
+
571
+ test("a Fix: ci line passes an unreviewed implementer commit while CI on the head is not green, and records the purpose", (t) => {
572
+ const ws = workspace(t);
573
+ implementerStop(ws, commitIn(ws.linked, "b.txt"));
574
+ const call = dispatch(ws.main, taskPrompt(ws.linked, "Fix: ci"));
575
+ const red = () => ({ reason: "CI on abc1234: unit ended failure", unknown: null });
576
+ const passed = judgeTask(call, ws.tmp, { ci: () => null, ciState: red });
577
+ assert.equal(passed.refusal, null);
578
+ recordDispatch(passed);
579
+ assert.equal(readLedger(ws.ledger).at(-1).fix, "ci");
580
+ const green = () => ({ reason: null, unknown: null });
581
+ assert.match(judgeTask(call, ws.tmp, { ci: () => null, ciState: green }).refusal ?? "", /`Fix: ci`.*green/);
582
+ assert.match(refusalOf(ws) ?? "", /Fix: ci/);
583
+ });
584
+
585
+ test("a Fix: review line passes a fresh implementer after CHANGES_REQUIRED and over an unreviewed fix commit", (t) => {
586
+ const ws = workspace(t);
587
+ const moved = commitIn(ws.linked, "b.txt");
588
+ implementerStop(ws, moved);
589
+ verdict(ws, moved, "CHANGES_REQUIRED", "branch");
590
+ implementerStop(ws, commitIn(ws.linked, "c.txt"));
591
+ assert.notEqual(refusalOf(ws), null);
592
+ assert.equal(refusalOf(ws, "Fix: review"), null);
593
+ });
594
+
595
+ test("a Fix: review line is refused when no verdict on the branch asks for changes", (t) => {
596
+ const ws = workspace(t);
597
+ assert.match(refusalOf(ws, "Fix: review") ?? "", /Fix: review.*no review/s);
598
+ verdict(ws, commitIn(ws.linked, "b.txt"), "APPROVED", "branch");
599
+ assert.match(refusalOf(ws, "Fix: review") ?? "", /Fix: review.*no review/s);
600
+ });
601
+
602
+ test("a Fix: ci line is refused while CI on the head is unknown", (t) => {
603
+ const ws = workspace(t);
604
+ implementerStop(ws, commitIn(ws.linked, "b.txt"));
605
+ const unknown = () => ({ reason: null, unknown: "gh is not signed in" });
606
+ assert.match(judgeTask(dispatch(ws.main, taskPrompt(ws.linked, "Fix: ci")), ws.tmp, { ci: () => null, ciState: unknown }).refusal ?? "", /Fix: ci.*not known to be red/s);
607
+ });
608
+
609
+ test("a branch reviewer dispatch records its scope", (t) => {
610
+ const ws = workspace(t);
611
+ const prompt = `Review.\nWorktree: ${ws.linked}\nScope: Photos\n`;
612
+ const task = judgeTask(dispatch(ws.main, prompt, "architecture:sdd-branch-reviewer"), ws.tmp, { ci: () => null, ciState: () => ({ reason: null, unknown: null }) });
613
+ assert.equal(task.record?.scope, "photos");
614
+ });
@@ -0,0 +1,127 @@
1
+ // `qc throwaway-db -- <command>`: run a command on a database of its own, in a container on a free port.
2
+ // It never takes a port the local stack owns, and it removes the container once the command exits.
3
+
4
+ import { spawnSync } from "node:child_process";
5
+ import { randomBytes } from "node:crypto";
6
+ import net from "node:net";
7
+ import { parseArgs } from "node:util";
8
+ import { merge } from "../config.mjs";
9
+ import { commandLine, runInShell, splitAtDashes } from "./child-run.mjs";
10
+
11
+ export const USAGE = `qc throwaway-db — run a command on a database of its own
12
+
13
+ qc throwaway-db [--port <n>|auto] -- <command...>
14
+ start a postgres container on a free port (auto by default), wait until it is ready, run the
15
+ command with the variables of throwawayDb.env filled in, and remove the container after.
16
+
17
+ qc.config.json "throwawayDb": image, user, database, env (each value may hold {url},
18
+ {host}, {port}, {user}, {password}, {database}), avoidPorts, and readySeconds. The password is random for each run.`;
19
+
20
+ export const throwawayDefaults = {
21
+ image: "postgres:17-alpine",
22
+ user: "postgres",
23
+ database: "app",
24
+ env: { DATABASE_URL: "{url}" },
25
+ avoidPorts: [5432],
26
+ readySeconds: 60,
27
+ };
28
+
29
+ const HOST = "127.0.0.1";
30
+ const PORT_TRIES = 10;
31
+
32
+ function listenOnZero() {
33
+ return new Promise((resolve, reject) => {
34
+ const server = net.createServer();
35
+ server.unref();
36
+ server.on("error", reject);
37
+ server.listen(0, HOST, () => {
38
+ const { port } = server.address();
39
+ server.close(() => resolve(port));
40
+ });
41
+ });
42
+ }
43
+
44
+ /** A port the OS calls free, never one of `avoid`. */
45
+ export async function freePort(avoid = [], open = listenOnZero) {
46
+ for (let tries = 0; tries < PORT_TRIES; tries += 1) {
47
+ const port = await open();
48
+ if (!avoid.includes(port)) return port;
49
+ }
50
+ throw new Error(`no free port outside ${avoid.join(", ")} after ${PORT_TRIES} tries`);
51
+ }
52
+
53
+ /** Each variable of the template, with `{name}` replaced by its value; an unknown name stays as written. */
54
+ export function fillEnv(template, values) {
55
+ return Object.fromEntries(
56
+ Object.entries(template).map(([name, value]) => [name, String(value).replace(/\{(\w+)\}/g, (whole, key) => (key in values ? String(values[key]) : whole))]),
57
+ );
58
+ }
59
+
60
+ /** The `docker run` arguments: a detached container that removes itself, published on the loopback address only. */
61
+ export function dockerRunArgs(settings, name, port, password) {
62
+ return [
63
+ "run", "--detach", "--rm", "--name", name, "--publish", `${HOST}:${port}:5432`,
64
+ "--env", `POSTGRES_USER=${settings.user}`, "--env", `POSTGRES_PASSWORD=${password}`, "--env", `POSTGRES_DB=${settings.database}`,
65
+ settings.image,
66
+ ];
67
+ }
68
+
69
+ function dockerSync(args) {
70
+ const result = spawnSync("docker", args, { encoding: "utf8", windowsHide: true });
71
+ return { code: result.status ?? 1, err: (result.stderr ?? "").trim() || (result.error?.message ?? "") };
72
+ }
73
+
74
+ /** `qc throwaway-db`. @returns the command's exit code, 1 when the database did not start, or 2 on a usage error */
75
+ export async function runThrowawayDb(config, argv, deps = {}) {
76
+ const {
77
+ docker = dockerSync,
78
+ run = runInShell,
79
+ open = listenOnZero,
80
+ sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
81
+ now = Date.now,
82
+ env = process.env,
83
+ say = (line) => console.error(line),
84
+ name = `qc-throwaway-${randomBytes(4).toString("hex")}`,
85
+ password = randomBytes(16).toString("hex"),
86
+ } = deps;
87
+ const merged = merge(throwawayDefaults, config.throwawayDb ?? {});
88
+ const settings = { ...merged, avoidPorts: [...new Set([5432, ...merged.avoidPorts])] };
89
+ const { flags, command } = splitAtDashes(argv);
90
+ let port;
91
+ try {
92
+ const { values } = parseArgs({ args: flags, options: { port: { type: "string" } }, strict: true });
93
+ if (command.length === 0) throw new Error("name the command after --");
94
+ const asked = values.port ?? "auto";
95
+ if (asked === "auto") port = await freePort(settings.avoidPorts, open);
96
+ else {
97
+ port = Number(asked);
98
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error(`--port must be auto or a port number, got ${asked}`);
99
+ if (settings.avoidPorts.includes(port)) throw new Error(`port ${port} is in throwawayDb.avoidPorts; use --port auto`);
100
+ }
101
+ } catch (error) {
102
+ say(`qc throwaway-db: ${error.message}\n\n${USAGE}`);
103
+ return 2;
104
+ }
105
+ say(`qc throwaway-db: starting ${name} on port ${port}`);
106
+ const started = docker(dockerRunArgs(settings, name, port, password));
107
+ if (started.code !== 0) {
108
+ say(`qc throwaway-db: docker run failed: ${started.err}`);
109
+ return 1;
110
+ }
111
+ try {
112
+ const deadline = now() + settings.readySeconds * 1000;
113
+ while (docker(["exec", name, "pg_isready", "-h", HOST, "-U", settings.user, "-d", settings.database]).code !== 0) {
114
+ if (now() >= deadline) {
115
+ say(`qc throwaway-db: ${name} was not ready after ${settings.readySeconds} s`);
116
+ return 1;
117
+ }
118
+ await sleep(1000);
119
+ }
120
+ const url = `postgres://${encodeURIComponent(settings.user)}:${encodeURIComponent(password)}@${HOST}:${port}/${settings.database}`;
121
+ const values = { url, host: HOST, port, user: settings.user, password, database: settings.database };
122
+ return await run(commandLine(command), { ...env, ...fillEnv(settings.env, values) });
123
+ } finally {
124
+ say(`qc throwaway-db: removing ${name}`);
125
+ if (docker(["rm", "--force", name]).code !== 0) say(`qc throwaway-db: remove it by hand: docker rm --force ${name}`);
126
+ }
127
+ }