architecture-harness 0.21.2 → 0.22.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/package.json +8 -3
  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/codex-implement.mjs +72 -3
  7. package/src/cli/codex-implement.test.mjs +141 -4
  8. package/src/cli/dispatch-guard.mjs +24 -1
  9. package/src/cli/dispatch-guard.test.mjs +30 -0
  10. package/src/cli/dispatch-reminder.mjs +4 -4
  11. package/src/cli/dispatch-reminder.test.mjs +3 -3
  12. package/src/cli/dispatch-slot.mjs +12 -0
  13. package/src/cli/gate-slot.mjs +151 -0
  14. package/src/cli/gate-slot.test.mjs +90 -0
  15. package/src/cli/integrate.mjs +122 -0
  16. package/src/cli/integrate.test.mjs +94 -0
  17. package/src/cli/ledger.mjs +25 -3
  18. package/src/cli/ledger.test.mjs +9 -0
  19. package/src/cli/merge-guard.mjs +13 -3
  20. package/src/cli/merge-guard.test.mjs +24 -1
  21. package/src/cli/migrations.mjs +127 -0
  22. package/src/cli/migrations.test.mjs +94 -0
  23. package/src/cli/plugin-agents.test.mjs +35 -8
  24. package/src/cli/qc.mjs +44 -0
  25. package/src/cli/report-stop.mjs +3 -0
  26. package/src/cli/report-stop.test.mjs +8 -0
  27. package/src/cli/retry-failed.mjs +80 -0
  28. package/src/cli/retry-failed.test.mjs +51 -0
  29. package/src/cli/review-gate.mjs +16 -7
  30. package/src/cli/slot-guard.mjs +43 -0
  31. package/src/cli/slot-guard.test.mjs +28 -0
  32. package/src/cli/task-gate-review.test.mjs +10 -0
  33. package/src/cli/task-gate.mjs +39 -7
  34. package/src/cli/task-gate.test.mjs +45 -0
  35. package/src/cli/throwaway-db.mjs +127 -0
  36. package/src/cli/throwaway-db.test.mjs +83 -0
  37. package/src/cli/ui-reuse-hint.mjs +89 -0
  38. package/src/cli/ui-reuse-hint.test.mjs +60 -0
  39. package/src/cli/ui.mjs +181 -0
  40. package/src/cli/ui.test.mjs +137 -0
  41. package/src/cli/watch.mjs +211 -0
  42. package/src/cli/watch.test.mjs +246 -0
  43. package/src/config.mjs +27 -2
  44. package/src/descriptions.mjs +3 -0
  45. package/src/gates/contract-keys.mjs +33 -0
  46. package/src/gates/contract-keys.test.mjs +38 -0
  47. package/src/gates/migration-numbers.mjs +1 -1
  48. package/src/gates/migration-numbers.test.mjs +1 -0
  49. package/src/gates/ui-catalog.mjs +45 -0
  50. package/src/gates/ui-catalog.test.mjs +48 -0
  51. package/src/gates/ui-dupes.mjs +36 -0
  52. package/src/gates/ui-dupes.test.mjs +29 -0
  53. package/src/ui/catalog.mjs +87 -0
  54. package/src/ui/catalog.test.mjs +54 -0
  55. package/src/ui/class-sites.mjs +151 -0
  56. package/src/ui/class-sites.test.mjs +41 -0
  57. package/src/ui/codemod.mjs +138 -0
  58. package/src/ui/codemod.test.mjs +140 -0
  59. package/src/ui/components.mjs +176 -0
  60. package/src/ui/components.test.mjs +87 -0
  61. package/src/ui/dupes.mjs +141 -0
  62. package/src/ui/dupes.test.mjs +85 -0
  63. package/src/ui/find.mjs +45 -0
  64. package/src/ui/find.test.mjs +48 -0
  65. package/src/ui/options.mjs +40 -0
  66. package/src/ui/scan.mjs +78 -0
  67. package/src/ui/typescript.mjs +29 -0
  68. package/templates/github/workflows/ci.yml +54 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.21.2",
3
+ "version": "0.22.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -40,7 +40,8 @@
40
40
  "./preset": "./src/eslint/preset.mjs",
41
41
  "./config": "./src/config.mjs",
42
42
  "./gates/*": "./src/gates/*.mjs",
43
- "./package.json": "./package.json"
43
+ "./package.json": "./package.json",
44
+ "./ui/*": "./src/ui/*.mjs"
44
45
  },
45
46
  "files": [
46
47
  "src",
@@ -58,7 +59,8 @@
58
59
  "eslint-plugin-sonarjs": ">=3",
59
60
  "@commitlint/lint": ">=19",
60
61
  "@commitlint/config-conventional": ">=19",
61
- "yaml": ">=2"
62
+ "yaml": ">=2",
63
+ "typescript": ">=5"
62
64
  },
63
65
  "peerDependenciesMeta": {
64
66
  "@typescript-eslint/eslint-plugin": {
@@ -81,6 +83,9 @@
81
83
  },
82
84
  "yaml": {
83
85
  "optional": true
86
+ },
87
+ "typescript": {
88
+ "optional": true
84
89
  }
85
90
  },
86
91
  "devDependencies": {
package/src/cli/check.mjs CHANGED
@@ -55,10 +55,15 @@ import { checkDocClaims, parseDocClaims } from "../gates/doc-claims.mjs";
55
55
  import { checkContractIdempotency, checkLedgerGrowth } from "../gates/contract-idempotency.mjs";
56
56
  import { contractHistory } from "./contract-history.mjs";
57
57
  import { contractOperations } from "../gates/contract-operations.mjs";
58
+ import { checkContractKeys } from "../gates/contract-keys.mjs";
58
59
  import { checkContractRoutes, declaredTriggerRoutes } from "../gates/contract-routes.mjs";
59
60
  import { ratchetInputs } from "./registry-history.mjs";
60
61
  import { hookDrift } from "./git-hooks.mjs";
61
62
  import { repoFiles } from "./repo-files.mjs";
63
+ import { checkUiCatalog } from "../gates/ui-catalog.mjs";
64
+ import { checkUiDupes } from "../gates/ui-dupes.mjs";
65
+ import { findDupes } from "../ui/dupes.mjs";
66
+ import { CATALOG_COMMAND, catalogText, scanComponents } from "../ui/scan.mjs";
62
67
 
63
68
  // Each skip is tested on "/" + the relative path, so it reads a path the way it read a full one.
64
69
  const SKIP = /node_modules|\/dist\/|\.test\.[cm]?[jt]sx?$/;
@@ -499,6 +504,24 @@ async function docClaims(config, lines) {
499
504
  return problems;
500
505
  }
501
506
 
507
+ /** No key of the composed contract ends with a dot or holds no value. */
508
+ async function contractKeys(config, lines) {
509
+ const { contract } = config;
510
+ const text = await read(path.join(config.root, contract));
511
+ if (text === null) return [];
512
+ let document;
513
+ try {
514
+ const { parse } = await import("yaml");
515
+ document = parse(text);
516
+ } catch (error) {
517
+ const rule = error?.code === "ERR_MODULE_NOT_FOUND" ? "contract-reader-unavailable" : "unreadable-contract";
518
+ return [{ path: contract, rule, detail: error.message }];
519
+ }
520
+ const problems = checkContractKeys(document, contract);
521
+ if (problems.length === 0) lines.push("OK contract no key ends with a dot, and every key holds a value");
522
+ return problems;
523
+ }
524
+
502
525
  /** Every write of the composed contract names its idempotency key, or sits in the ledger. */
503
526
  async function contractIdempotency(config, lines) {
504
527
  const { contract } = config;
@@ -555,6 +578,36 @@ async function contractRouteAgreement(config, routes, lines) {
555
578
  return problems;
556
579
  }
557
580
 
581
+ /** The UI gates: the catalog and its documentation, and the duplicates. A repository with no component under its roots passes both. */
582
+ async function uiAgreement(config, tree, lines) {
583
+ let scan;
584
+ try {
585
+ scan = await scanComponents(config, tree.files);
586
+ } catch (cause) {
587
+ return [{ path: "qc.config.json", rule: "ui-no-typescript", detail: cause.message }];
588
+ }
589
+ const { options, files, entries, ts } = scan;
590
+ const baselineOf = async (file, key) => parsedJson(await read(path.join(config.root, file)))?.[key] ?? null;
591
+ const problems = [];
592
+ if (enabled(config.gates, "ui-catalog")) {
593
+ const actual = await read(path.join(config.root, options.catalog));
594
+ problems.push(
595
+ ...checkUiCatalog(entries, {
596
+ catalog: { path: options.catalog, actual, expected: catalogText(entries, options), command: CATALOG_COMMAND },
597
+ baseline: await baselineOf(options.catalogBaseline, "undocumented"),
598
+ baselineFile: options.catalogBaseline,
599
+ }),
600
+ );
601
+ lines.push(`OK ui-catalog ${entries.length} component(s), each described, and ${options.catalog} matches the code`);
602
+ }
603
+ if (enabled(config.gates, "ui-dupes")) {
604
+ const found = ts ? findDupes(ts, files, { entries, callees: options.classCallees, ...options.dupes }) : [];
605
+ problems.push(...checkUiDupes(found, { baseline: await baselineOf(options.dupes.baseline, "findings"), baselineFile: options.dupes.baseline }));
606
+ lines.push("OK ui-dupes no class string, component name or JSX tree is written twice beyond the baseline");
607
+ }
608
+ return problems;
609
+ }
610
+
558
611
  /**
559
612
  * @param {object} config
560
613
  * @param {string | string[]} [only] files to check on the fast path a hook takes; none is the full check
@@ -877,5 +930,13 @@ export async function runCheck(config, only = [], { lister = repoFiles } = {}) {
877
930
  problems.push(...(await contractRouteAgreement(config, routes, lines)));
878
931
  }
879
932
 
933
+ if (enabled(config.gates, "contract-keys")) {
934
+ problems.push(...(await contractKeys(config, lines)));
935
+ }
936
+
937
+ if (enabled(config.gates, "ui-catalog") || enabled(config.gates, "ui-dupes")) {
938
+ problems.push(...(await uiAgreement(config, tree, lines)));
939
+ }
940
+
880
941
  return { problems, lines };
881
942
  }
@@ -0,0 +1,39 @@
1
+ // A fragment that runs one command line in the shell, the way a Windows `.cmd` shim such as `pnpm` needs.
2
+ // The caller ignores Ctrl+C while the command runs, so it can clean up after the command exits.
3
+
4
+ import { spawn } from "node:child_process";
5
+
6
+ /** One shell command line from argv words; a word with a space or a quote is quoted. */
7
+ export function commandLine(words) {
8
+ const args = words[0] === "--" ? words.slice(1) : words;
9
+ return args.map((arg) => (/^$|[\s"]/.test(arg) ? `"${arg.replaceAll('"', '\\"')}"` : arg)).join(" ");
10
+ }
11
+
12
+ /** Splits argv at its first `--`: the flags before it, and the command after it. */
13
+ export function splitAtDashes(argv) {
14
+ const at = argv.indexOf("--");
15
+ return at < 0 ? { flags: argv, command: [] } : { flags: argv.slice(0, at), command: argv.slice(at + 1) };
16
+ }
17
+
18
+ /** Runs `command` in the shell. @returns a promise of its exit code; a command ended by a signal returns 1 */
19
+ export function runInShell(command, env = process.env, cwd = process.cwd()) {
20
+ return new Promise((resolve, reject) => {
21
+ const child = spawn(command, { shell: true, stdio: "inherit", env, cwd, windowsHide: true });
22
+ const ignore = () => {};
23
+ const stop = () => child.kill("SIGTERM");
24
+ process.on("SIGINT", ignore);
25
+ process.on("SIGTERM", stop);
26
+ const done = () => {
27
+ process.off("SIGINT", ignore);
28
+ process.off("SIGTERM", stop);
29
+ };
30
+ child.on("error", (error) => {
31
+ done();
32
+ reject(error);
33
+ });
34
+ child.on("exit", (code) => {
35
+ done();
36
+ resolve(code ?? 1);
37
+ });
38
+ });
39
+ }
@@ -0,0 +1,16 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { commandLine, runInShell, splitAtDashes } from "./child-run.mjs";
4
+
5
+ test("a word with a space or a quote is quoted, and a leading -- is dropped", () => {
6
+ assert.equal(commandLine(["--", "pnpm", "vitest", "run", "a b.test.ts", 'say "hi"']), 'pnpm vitest run "a b.test.ts" "say \\"hi\\""');
7
+ });
8
+
9
+ test("argv splits at its first --", () => {
10
+ assert.deepEqual(splitAtDashes(["--port", "auto", "--", "pnpm", "--", "x"]), { flags: ["--port", "auto"], command: ["pnpm", "--", "x"] });
11
+ assert.deepEqual(splitAtDashes(["--status"]), { flags: ["--status"], command: [] });
12
+ });
13
+
14
+ test("the shell runs the command and returns its exit code", async () => {
15
+ assert.equal(await runInShell(`"${process.execPath}" -e "process.exit(3)"`), 3);
16
+ });
@@ -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 { parse } from "yaml";
6
+
7
+ const WORKFLOW = fileURLToPath(new URL("../../templates/github/workflows/ci.yml", import.meta.url));
8
+
9
+ test("the template runs unit tests in eight shards and integration tests in two, all on hosted runners", () => {
10
+ const workflow = parse(readFileSync(WORKFLOW, "utf8"));
11
+ assert.deepEqual(workflow.jobs.unit.strategy.matrix.shard, [1, 2, 3, 4, 5, 6, 7, 8]);
12
+ assert.deepEqual(workflow.jobs.integration.strategy.matrix.shard, [1, 2]);
13
+ assert.equal(workflow.jobs.unit.strategy["fail-fast"], false);
14
+ for (const [name, job] of Object.entries(workflow.jobs)) assert.equal(job["runs-on"], "ubuntu-latest", name);
15
+ });
16
+
17
+ test("the template runs the affected browser tests on a pull request and every one on a push", () => {
18
+ const steps = JSON.stringify(parse(readFileSync(WORKFLOW, "utf8")).jobs.e2e.steps);
19
+ assert.match(steps, /pnpm e2e:affected/);
20
+ assert.match(steps, /pnpm e2e"/);
21
+ });
22
+
23
+ test("the e2e job installs the browsers before it runs a spec", () => {
24
+ const steps = parse(readFileSync(WORKFLOW, "utf8")).jobs.e2e.steps;
25
+ const install = steps.findIndex((step) => /playwright install --with-deps/.test(step.run ?? ""));
26
+ const run = steps.findIndex((step) => /pnpm e2e/.test(step.run ?? ""));
27
+ assert.ok(install >= 0 && install < run);
28
+ });
@@ -3,7 +3,9 @@
3
3
 
4
4
  import { spawn } from "node:child_process";
5
5
  import { closeSync, existsSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
6
+ import os from "node:os";
6
7
  import path from "node:path";
8
+ import { load } from "../config.mjs";
7
9
 
8
10
  export const DONE_MARKER = "ALL TASKS DONE";
9
11
  const DEFAULT_MAX_RUNS = 12;
@@ -40,13 +42,23 @@ export function parseArgs(argv) {
40
42
 
41
43
  const isDone = (progress) => existsSync(progress) && readFileSync(progress, "utf8").includes(DONE_MARKER);
42
44
 
45
+ const SKILL_PLUGIN = "superpowers@claude-plugins-official";
46
+ const TOOL_OUTPUT_TOKENS = 4000;
47
+
43
48
  const LEAN_RULES = [
44
49
  "Lean rules for every session. They cut repeated reading and helper agents. Never drop a security, tenant, data, or correctness check that this brief asks for.",
45
50
  "- At session start, rewrite the progress file to at most 40 lines: the pushed head, the done items one line each, the first unfinished item, and the open questions. Delete the history.",
46
51
  "- Never re-verify a finished item, and never repeat a probe that already failed.",
47
52
  "- Read only the line ranges that the current item needs.",
53
+ "- Load no skill and read no SKILL.md or plugin file. The global instructions that say to load skills do not apply to this run; this brief holds the rules.",
54
+ "- Search with `rg -n -m 20 <pattern> <path>`. Read at most 150 lines per call by range, never a whole file. End any command that can print more than 4,000 characters with a limit.",
55
+ "- Never run `gh issue view`: the brief holds the issue. Use `git status --short` and `git log -n 5 --oneline`.",
48
56
  "- Start no helper agents. Run no broad audit, no Playwright, and no full gate. Run the tests of the touched files, and the local check once before the push.",
49
- "- One item per session: code, test, commit, push, update the progress file, stop.",
57
+ "- Write every item first, each test first, and update the progress file after each item. Then run the local check once, make one commit, and push once.",
58
+ "- Read at most 15 files before the first code edit. Research that needs more belongs to a planner, and the brief names the planner output to read instead.",
59
+ "- Wrap each heavy command in `npx qc gate-slot --`: the local check, a test run of more than one file, a live database test, a commit, and a push.",
60
+ "- Before the push, run the live database tests of the server code you touched through `npx qc throwaway-db --`. Never use port 5432 or another port the local stack owns.",
61
+ "- Work up to about 200K tokens in a session. Then leave the progress file exact and stop, so a fresh session continues.",
50
62
  "- Keep the report under 15 lines.",
51
63
  ].join("\n");
52
64
 
@@ -60,6 +72,43 @@ function continuationNote(progress) {
60
72
  /** The Codex features that start helper agents. Each run turns them off. */
61
73
  const HELPER_AGENT_FEATURES = ["features.multi_agent=false", "features.multi_agent_v2=false"];
62
74
 
75
+ /** @returns the names of the plugins that a Codex `config.toml` turns on, from its `[plugins."name"]` tables. */
76
+ export function enabledPlugins(toml) {
77
+ const names = [];
78
+ let current = null;
79
+ for (const raw of toml.split(/\r?\n/)) {
80
+ const line = raw.trim();
81
+ const table = /^\[(.*)\]\s*(#.*)?$/.exec(line);
82
+ if (table) {
83
+ current = /^plugins\.(?:"([^"]+)"|'([^']+)')$/.exec(table[1]);
84
+ current = current ? (current[1] ?? current[2]) : null;
85
+ } else if (current && /^enabled\s*=\s*true\s*(#.*)?$/.test(line)) {
86
+ names.push(current);
87
+ current = null;
88
+ }
89
+ }
90
+ return names;
91
+ }
92
+
93
+ /** The `-c` overrides that turn off each plugin the user enabled, and the skill plugin, for this run only. */
94
+ function pluginOverrides(env) {
95
+ const file = path.join(env.CODEX_HOME || path.join(os.homedir(), ".codex"), "config.toml");
96
+ let enabled = [];
97
+ try {
98
+ enabled = enabledPlugins(readFileSync(file, "utf8"));
99
+ } catch {
100
+ // A missing or unreadable config still lets the run start, with the superpowers override alone.
101
+ }
102
+ return [...new Set([...enabled, SKILL_PLUGIN])].flatMap((name) => ["-c", `plugins.${JSON.stringify(name)}.enabled=false`]);
103
+ }
104
+
105
+ /** @returns `codex.compactTokens` of the worktree's config; throws when it is not a positive whole number. */
106
+ function compactTokensOf(worktree) {
107
+ const value = load(worktree).codex.compactTokens;
108
+ if (!Number.isInteger(value) || value < 1) throw new Error(`codex.compactTokens in qc.config.json must be a positive whole number, got ${JSON.stringify(value)}`);
109
+ return value;
110
+ }
111
+
63
112
  /** The brief is read again for each run, so an edit reaches the next session. */
64
113
  const promptFor = (settings) => readFileSync(settings.brief, "utf8") + continuationNote(settings.progress);
65
114
 
@@ -83,11 +132,24 @@ function spawnRun({ command, args, env, log }, codexCommand) {
83
132
  });
84
133
  }
85
134
 
135
+ /** Writes one stdout line and resolves once it is flushed, so the `process.exit` that follows cannot cut it. */
136
+ const writeLine = (line) => new Promise((resolve) => process.stdout.write(`${line}
137
+ `, resolve));
138
+
86
139
  /**
140
+ * The last stdout line is `exit <code>` on every path, so a redirect of the runner into a wrapper log carries
141
+ * the end of the job for `qc watch --codex`, in any shell.
87
142
  * @param run `({ command, args, env, log }) => Promise<{ status, tail }>`; the default spawns `codexCommand`.
143
+ * @param out `(line) => Promise|void` writes the `exit` line; the default writes to stdout.
88
144
  * @returns the exit code: 0 done, 1 bad input or no codex, 2 a limit, 3 out of runs.
89
145
  */
90
- export async function runCodexImplement(argv, { run, codexCommand = ["codex"], env = process.env, say = (line) => console.error(line) } = {}) {
146
+ export async function runCodexImplement(argv, { out = writeLine, ...options } = {}) {
147
+ const code = await runJob(argv, options);
148
+ await out(`exit ${code}`);
149
+ return code;
150
+ }
151
+
152
+ async function runJob(argv, { run, codexCommand = ["codex"], env = process.env, say = (line) => console.error(line) } = {}) {
91
153
  let settings;
92
154
  try {
93
155
  settings = parseArgs(argv);
@@ -95,6 +157,12 @@ export async function runCodexImplement(argv, { run, codexCommand = ["codex"], e
95
157
  say(`qc codex-implement: ${error.message}\n${USAGE}`);
96
158
  return 1;
97
159
  }
160
+ let compactTokens;
161
+ try {
162
+ compactTokens = compactTokensOf(settings.worktree);
163
+ } catch (error) {
164
+ return finish(say, error.message, 1);
165
+ }
98
166
  const execute = run ?? ((call) => spawnRun(call, codexCommand));
99
167
  for (let count = 1; count <= settings.maxRuns; count += 1) {
100
168
  if (isDone(settings.progress)) return finish(say, `done after ${count - 1} run(s)`, 0);
@@ -105,7 +173,8 @@ export async function runCodexImplement(argv, { run, codexCommand = ["codex"], e
105
173
  return finish(say, `cannot read the brief: ${error.message}`, 1);
106
174
  }
107
175
  const helperOff = HELPER_AGENT_FEATURES.flatMap((feature) => ["-c", feature]);
108
- const args = ["exec", "-s", "danger-full-access", "-C", settings.worktree, ...helperOff, prompt];
176
+ const limits = ["-c", `model_auto_compact_token_limit=${compactTokens}`, "-c", `tool_output_token_limit=${TOOL_OUTPUT_TOKENS}`];
177
+ const args = ["exec", "-s", "danger-full-access", "-C", settings.worktree, ...helperOff, ...pluginOverrides(env), ...limits, prompt];
109
178
  let result;
110
179
  try {
111
180
  result = await execute({ command: codexCommand[0], args, env: { ...env, QC_ROLE: "implementer" }, log: settings.log });
@@ -1,11 +1,11 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { spawnSync } from "node:child_process";
3
- import { appendFileSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
3
+ import { appendFileSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { fileURLToPath } from "node:url";
8
- import { DONE_MARKER, parseArgs, runCodexImplement } from "./codex-implement.mjs";
8
+ import { DONE_MARKER, enabledPlugins, parseArgs, runCodexImplement } from "./codex-implement.mjs";
9
9
 
10
10
  const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
11
11
 
@@ -45,7 +45,7 @@ test("a run passes exec, the sandbox, the worktree and one prompt, with QC_ROLE=
45
45
  const prompt = call.args.at(-1);
46
46
  assert.equal(call.env.QC_ROLE, "implementer");
47
47
  assert.ok(prompt.startsWith(readFileSync(brief, "utf8")));
48
- assert.match(prompt, /git log --oneline/);
48
+ assert.match(prompt, /git log -n 5 --oneline/);
49
49
  assert.match(prompt, /git status --short/);
50
50
  assert.match(prompt, /first unfinished task/);
51
51
  assert.ok(prompt.includes(progress));
@@ -83,7 +83,11 @@ test("every run prompt carries the lean rules after the brief", async (t) => {
83
83
  assert.match(prompt, /re-verify/);
84
84
  assert.match(prompt, /line ranges/);
85
85
  assert.match(prompt, /helper agents/);
86
- assert.match(prompt, /one item per session/i);
86
+ assert.match(prompt, /Then run the local check once, make one commit, and push once\./);
87
+ assert.match(prompt, /npx qc gate-slot --/);
88
+ assert.match(prompt, /npx qc throwaway-db --/);
89
+ assert.match(prompt, /Never use port 5432/);
90
+ assert.match(prompt, /at most 15 files before the first code edit/i);
87
91
  assert.match(prompt, /under 15 lines/);
88
92
  assert.match(prompt, /never drop a security, tenant, data, or correctness check/i);
89
93
  }
@@ -103,6 +107,117 @@ test("a run turns off the Codex helper agents with -c, before the prompt", async
103
107
  assert.ok(index < args.length - 1, "the prompt stays the last argument");
104
108
  });
105
109
 
110
+ const CODEX_TOML = [
111
+ "model = 'x'",
112
+ '[plugins."browser@openai-bundled"]',
113
+ "enabled = true",
114
+ '[plugins."chrome@openai-bundled"]',
115
+ "enabled = false",
116
+ "[plugins.'pdf@openai-primary-runtime']",
117
+ "enabled = true # on",
118
+ '[projects."C:/repo"]',
119
+ "enabled = true",
120
+ '[plugins."superpowers@claude-plugins-official"]',
121
+ "enabled = true",
122
+ ].join("\n");
123
+
124
+ function codexHome(t, toml = CODEX_TOML) {
125
+ const home = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-codex-home-")));
126
+ t.after(() => rmSync(home, { recursive: true, force: true }));
127
+ if (toml !== null) writeFileSync(path.join(home, "config.toml"), toml);
128
+ return home;
129
+ }
130
+
131
+ async function firstCall(t, { env = {}, config } = {}) {
132
+ const { argv, progress, worktree } = setup(t);
133
+ if (config !== undefined) {
134
+ mkdirSync(worktree, { recursive: true });
135
+ writeFileSync(path.join(worktree, "qc.config.json"), JSON.stringify(config));
136
+ }
137
+ let call;
138
+ const run = async (made) => {
139
+ call = made;
140
+ appendFileSync(progress, `${DONE_MARKER}\n`);
141
+ return { status: 0, tail: "ok" };
142
+ };
143
+ const code = await runCodexImplement(argv, { run, say: quiet, env: { CODEX_HOME: codexHome(t), ...env } });
144
+ return { code, call };
145
+ }
146
+
147
+ const overrides = (args) => args.flatMap((arg, index) => (args[index - 1] === "-c" ? [arg] : []));
148
+
149
+ test("enabledPlugins lists the plugins the config file turns on, and no table that only looks like one", () => {
150
+ assert.deepEqual(enabledPlugins(CODEX_TOML), [
151
+ "browser@openai-bundled",
152
+ "pdf@openai-primary-runtime",
153
+ "superpowers@claude-plugins-official",
154
+ ]);
155
+ assert.deepEqual(enabledPlugins(""), []);
156
+ });
157
+
158
+ test("a run turns off every plugin the user's Codex config enables, and superpowers by name", async (t) => {
159
+ const { call } = await firstCall(t);
160
+ const set = overrides(call.args);
161
+ for (const name of ["browser@openai-bundled", "pdf@openai-primary-runtime", "superpowers@claude-plugins-official"]) {
162
+ assert.ok(set.includes(`plugins."${name}".enabled=false`), name);
163
+ }
164
+ assert.ok(!set.some((entry) => entry.includes("chrome@openai-bundled")), "a plugin already off needs no override");
165
+ assert.ok(set.includes("features.multi_agent=false"), "the helper-agent overrides stay");
166
+ assert.ok(set.includes("features.multi_agent_v2=false"));
167
+ });
168
+
169
+ test("superpowers is turned off when the config file is missing, and nothing else is", async (t) => {
170
+ const { call } = await firstCall(t, { env: { CODEX_HOME: codexHome(t, null) } });
171
+ const plugins = overrides(call.args).filter((entry) => entry.startsWith("plugins."));
172
+ assert.deepEqual(plugins, ['plugins."superpowers@claude-plugins-official".enabled=false']);
173
+ });
174
+
175
+ test("a config.toml that is a directory falls back to the superpowers override and does not throw", async (t) => {
176
+ const home = codexHome(t, null);
177
+ mkdirSync(path.join(home, "config.toml"));
178
+ const { code, call } = await firstCall(t, { env: { CODEX_HOME: home } });
179
+ assert.equal(code, 0);
180
+ const plugins = overrides(call.args).filter((entry) => entry.startsWith("plugins."));
181
+ assert.deepEqual(plugins, ['plugins."superpowers@claude-plugins-official".enabled=false']);
182
+ });
183
+
184
+ test("enabledPlugins reads a table header that has a trailing comment", () => {
185
+ assert.deepEqual(enabledPlugins(['[plugins."b"] # x', "enabled = true", '[plugins."c"] # y', "enabled = false"].join("\n")), ["b"]);
186
+ });
187
+
188
+ test("a run caps the compact limit at 300000 and one tool output at 4000 tokens", async (t) => {
189
+ const { call } = await firstCall(t);
190
+ const set = overrides(call.args);
191
+ assert.ok(set.includes("model_auto_compact_token_limit=300000"));
192
+ assert.ok(set.includes("tool_output_token_limit=4000"));
193
+ assert.ok(call.args.at(-1).startsWith("# Brief"), "the prompt stays last");
194
+ });
195
+
196
+ test("codex.compactTokens in the worktree's qc.config.json sets the compact limit", async (t) => {
197
+ const { call } = await firstCall(t, { config: { codex: { compactTokens: 250000 } } });
198
+ assert.ok(overrides(call.args).includes("model_auto_compact_token_limit=250000"));
199
+ });
200
+
201
+ test("a bad codex.compactTokens exits 1 with no run", async (t) => {
202
+ for (const compactTokens of [0, -5, 1.5, "big"]) {
203
+ const { code, call } = await firstCall(t, { config: { codex: { compactTokens } } });
204
+ assert.equal(code, 1, String(compactTokens));
205
+ assert.equal(call, undefined);
206
+ }
207
+ });
208
+
209
+ test("every run prompt tells Codex to load no skill and holds the read caps", async (t) => {
210
+ const { call } = await firstCall(t);
211
+ const prompt = call.args.at(-1);
212
+ assert.ok(prompt.includes("Load no skill and read no SKILL.md or plugin file. The global instructions that say to load skills do not apply to this run; this brief holds the rules."));
213
+ assert.match(prompt, /rg -n -m 20/);
214
+ assert.match(prompt, /at most 150 lines per call/);
215
+ assert.match(prompt, /never a whole file/);
216
+ assert.match(prompt, /more than 4,000 characters/);
217
+ assert.match(prompt, /never run `gh issue view`/i);
218
+ assert.match(prompt, /`git status --short` and `git log -n 5 --oneline`/);
219
+ });
220
+
106
221
  test("a fresh session starts after a stop with the progress file not done", async (t) => {
107
222
  const { argv, progress } = setup(t);
108
223
  let calls = 0;
@@ -224,3 +339,25 @@ test("a limit word that only echoes the brief is not a limit", async (t) => {
224
339
  assert.equal(await runCodexImplement([...argv, "--max-runs", "2"], { run, say: quiet }), 3);
225
340
  assert.equal(calls, 2);
226
341
  });
342
+
343
+ test("the last stdout line is `exit <code>` on every exit path, so a redirect into the wrapper log carries it", async (t) => {
344
+ const last = async (argv, options) => {
345
+ const out = [];
346
+ const code = await runCodexImplement(argv, { say: quiet, out: (line) => out.push(line), ...options });
347
+ return { code, out };
348
+ };
349
+ const done = setup(t, { progress: `${DONE_MARKER}\n` });
350
+ assert.deepEqual(await last(done.argv), { code: 0, out: ["exit 0"] });
351
+ const limit = setup(t);
352
+ const limited = await last(limit.argv, { run: async () => ({ status: 1, tail: "You have hit your usage limit" }) });
353
+ assert.deepEqual(limited, { code: 2, out: ["exit 2"] });
354
+ const spent = setup(t);
355
+ assert.deepEqual(await last([...spent.argv, "--max-runs", "1"], { run: async () => ({ status: 0, tail: "" }) }), { code: 3, out: ["exit 3"] });
356
+ assert.deepEqual(await last(["--nope", "x"]), { code: 1, out: ["exit 1"] });
357
+ });
358
+
359
+ test("the CLI prints `exit 1` as the last stdout line after a usage error", () => {
360
+ const result = spawnSync(process.execPath, [QC, "codex-implement"], { encoding: "utf8" });
361
+ assert.equal(result.status, 1);
362
+ assert.equal(result.stdout.trimEnd().split("\n").at(-1), "exit 1");
363
+ });
@@ -6,7 +6,7 @@ import { existsSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { dispatchNote, dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
9
- import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
9
+ import { claimSlot, clearSlots, reclaimSlot, releaseHolder, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
10
10
  import { judgeTask, recordDispatch } from "./task-gate.mjs";
11
11
 
12
12
  const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", ...fields } });
@@ -27,9 +27,32 @@ function onSubagent(call, dir, now) {
27
27
  }
28
28
  }
29
29
 
30
+ const FRESH_STARTS = new Set(["startup", "resume"]);
31
+
32
+ /** Frees the slot of the agent a TaskStop ended, since that agent sends no SubagentStop. */
33
+ function onTaskStop(call, dir) {
34
+ const id = idOf(call.tool_input?.task_id) ?? idOf(call.tool_input?.shell_id);
35
+ if (!id || !existsSync(dir)) return null;
36
+ try {
37
+ if (!releaseHolder(dir, id)) return null;
38
+ } catch {
39
+ return null;
40
+ }
41
+ return { hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: `Dispatch guard: freed the implementer slot that ${id} held.` } };
42
+ }
43
+
30
44
  /** The verdict on one hook event. `reads` replaces the task gate's CI and base reads, for a test. @returns the hook output, or null to let the call run with no message. */
31
45
  export function decide(call, tmp = os.tmpdir(), now = Date.now(), reads = {}) {
32
46
  const dir = slotDirOf(call.session_id ?? "session", tmp);
47
+ if (call.hook_event_name === "SessionStart") {
48
+ try {
49
+ if (FRESH_STARTS.has(call.source) && existsSync(dir)) clearSlots(dir);
50
+ } catch {
51
+ // A busy temp folder costs only a slot that still expires.
52
+ }
53
+ return null;
54
+ }
55
+ if (call.hook_event_name === "PostToolUse" && call.tool_name === "TaskStop") return onTaskStop(call, dir);
33
56
  if (call.hook_event_name === "SubagentStart" || call.hook_event_name === "SubagentStop") {
34
57
  onSubagent(call, dir, now);
35
58
  return null;
@@ -207,6 +207,8 @@ test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () =>
207
207
  const matchersOf = (entries) =>
208
208
  (entries ?? []).filter((entry) => entry.hooks.some((hook) => hook.command.includes("dispatch-guard.mjs"))).map((entry) => entry.matcher);
209
209
  assert.deepEqual(matchersOf(hooks.PreToolUse), ["Agent"]);
210
+ assert.deepEqual(matchersOf(hooks.PostToolUse), ["TaskStop"]);
211
+ assert.deepEqual(matchersOf(hooks.SessionStart), [undefined]);
210
212
  assert.deepEqual(matchersOf(hooks.SubagentStart), [undefined]);
211
213
  assert.deepEqual(matchersOf(hooks.SubagentStop), [undefined]);
212
214
  });
@@ -247,3 +249,31 @@ test("a dispatch with no tool_use_id still claims its own slot", (t) => {
247
249
  assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
248
250
  assert.match(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)) ?? "", /all 2 implementer slots/);
249
251
  });
252
+
253
+ const taskStop = (cwd, taskId) => ({
254
+ session_id: "session-aaaa",
255
+ cwd,
256
+ hook_event_name: "PostToolUse",
257
+ tool_name: "TaskStop",
258
+ tool_input: { task_id: taskId },
259
+ });
260
+
261
+ test("a TaskStop frees the slot of the agent it stopped, and a TaskStop of another task frees nothing", (t) => {
262
+ const ws = workspace(t);
263
+ assert.equal(decide(slotCall(ws.on, "use-a"), ws.tmp), null);
264
+ decide(agentEvent(ws.on, "agent-a", "SubagentStart"), ws.tmp);
265
+ assert.equal(decide(taskStop(ws.on, "shell-9"), ws.tmp), null);
266
+ assert.notEqual(reasonOf(decide(slotCall(ws.on, "use-b"), ws.tmp)), null);
267
+ assert.match(decide(taskStop(ws.on, "agent-a"), ws.tmp)?.hookSpecificOutput?.additionalContext ?? "", /freed the implementer slot/);
268
+ assert.equal(decide(slotCall(ws.on, "use-b"), ws.tmp), null);
269
+ });
270
+
271
+ test("a session startup or resume frees every slot of the session, and a compaction frees none", (t) => {
272
+ const ws = workspace(t);
273
+ assert.equal(decide(slotCall(ws.on, "use-a"), ws.tmp), null);
274
+ const start = (source) => ({ session_id: "session-aaaa", cwd: ws.on, hook_event_name: "SessionStart", source });
275
+ assert.equal(decide(start("compact"), ws.tmp), null);
276
+ assert.notEqual(reasonOf(decide(slotCall(ws.on, "use-b"), ws.tmp)), null);
277
+ assert.equal(decide(start("resume"), ws.tmp), null);
278
+ assert.equal(decide(slotCall(ws.on, "use-b"), ws.tmp), null);
279
+ });
@@ -29,10 +29,10 @@ export const CODEX_LINE =
29
29
  export const WORKER_NOTE =
30
30
  "Implementer worker mode (QC_ROLE=implementer): you are an implementer under a controller. Work inline. " +
31
31
  "Never use superpowers:subagent-driven-development, helper agents, task reviews, or fix-review rounds. " +
32
- "For each task in your brief: write the failing test, run only that test file, make it pass, " +
33
- "run typecheck and lint on what you touched, and commit that task at once. " +
34
- "Do not run the full local gate or e2e; CI runs them. " +
35
- "When every task in the brief is committed, append `ALL TASKS DONE` to the progress file the brief names. " +
32
+ "Write every task in your brief: write the failing test, run only that test file, make it pass, " +
33
+ "and run typecheck and lint on what you touched. Then run the local check once, make one commit, and push once. " +
34
+ "Do not run the full gate (`pnpm check`) or e2e; CI runs them. " +
35
+ "When every task in the brief is pushed, append `ALL TASKS DONE` to the progress file the brief names. " +
36
36
  "If your context gets large, write notes to the progress file and end the turn: a fresh session continues.";
37
37
 
38
38
  const ROLES = ["sdd-planner", "sdd-implementer", "sdd-reviewer", "sdd-branch-reviewer"];
@@ -287,15 +287,15 @@ test("QC_ROLE=implementer replaces the controller note with the worker note", (t
287
287
  assert.ok(!text.includes("sdd-planner"));
288
288
  });
289
289
 
290
- test("the worker note says to work inline, run one test file, commit each task, and write ALL TASKS DONE", () => {
290
+ test("the worker note says to work inline, write every task, check and commit once, and write ALL TASKS DONE", () => {
291
291
  for (const phrase of [
292
292
  /implementer under a controller/,
293
293
  /Work inline/,
294
294
  /Never use superpowers:subagent-driven-development, helper agents, task reviews, or fix-review rounds/,
295
295
  /failing test, run only that test file, make it pass/,
296
296
  /typecheck and lint on what you touched/,
297
- /commit that task at once/,
298
- /Do not run the full local gate or e2e; CI runs them/,
297
+ /Then run the local check once, make one commit, and push once./,
298
+ /Do not run the full gate \(`pnpm check`\) or e2e; CI runs them/,
299
299
  /append `ALL TASKS DONE` to the progress file the brief names/,
300
300
  /context gets large.*end the turn.*fresh session continues/,
301
301
  ]) {
@@ -183,3 +183,15 @@ export function releaseSlot(dir, agentType, agentId = "", now = Date.now()) {
183
183
  if (victim) rmSync(victim.file, { force: true });
184
184
  return true;
185
185
  }
186
+
187
+ /** Frees the slot that holds `agentId`, whatever its type. @returns true when a slot held it */
188
+ export function releaseHolder(dir, agentId) {
189
+ const own = slotsOf(dir).find((slot) => slot.held === `${AGENT}${agentId}`);
190
+ if (own) rmSync(own.file, { force: true });
191
+ return own !== undefined;
192
+ }
193
+
194
+ /** Frees every slot of a session: a new Claude Code process holds no subagent of the last one. */
195
+ export function clearSlots(dir) {
196
+ for (const slot of slotsOf(dir)) rmSync(slot.file, { force: true });
197
+ }