architecture-harness 0.16.0 → 0.18.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 (124) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/budget-counter.mjs +25 -4
  7. package/src/cli/budget-guard.mjs +73 -4
  8. package/src/cli/budget-guard.test.mjs +111 -0
  9. package/src/cli/budget.mjs +3 -2
  10. package/src/cli/check-registries.test.mjs +181 -0
  11. package/src/cli/check.mjs +130 -9
  12. package/src/cli/cli.test.mjs +215 -2
  13. package/src/cli/context-signal.mjs +92 -0
  14. package/src/cli/context-signal.test.mjs +99 -0
  15. package/src/cli/contract-history.mjs +46 -0
  16. package/src/cli/contract-history.test.mjs +118 -0
  17. package/src/cli/controller-guard.mjs +73 -0
  18. package/src/cli/controller-guard.test.mjs +119 -0
  19. package/src/cli/dispatch-guard.mjs +14 -4
  20. package/src/cli/dispatch-guard.test.mjs +5 -6
  21. package/src/cli/dispatch-reminder.mjs +19 -11
  22. package/src/cli/dispatch-reminder.test.mjs +32 -0
  23. package/src/cli/dispatch.mjs +23 -2
  24. package/src/cli/dispatch.test.mjs +39 -1
  25. package/src/cli/doctor.mjs +2 -1
  26. package/src/cli/explore-guard.mjs +2 -2
  27. package/src/cli/explore-hint.mjs +67 -7
  28. package/src/cli/explore-hint.test.mjs +104 -4
  29. package/src/cli/gh-merge-command.mjs +228 -0
  30. package/src/cli/gh-merge-command.test.mjs +273 -0
  31. package/src/cli/gh-run.mjs +30 -0
  32. package/src/cli/gh-run.test.mjs +22 -0
  33. package/src/cli/git-hooks.test.mjs +28 -0
  34. package/src/cli/git-read.mjs +42 -0
  35. package/src/cli/git-read.test.mjs +94 -0
  36. package/src/cli/handoff-note.mjs +69 -0
  37. package/src/cli/handoff-note.test.mjs +71 -0
  38. package/src/cli/init.mjs +7 -3
  39. package/src/cli/issue-gate.mjs +169 -0
  40. package/src/cli/issue-gate.test.mjs +234 -0
  41. package/src/cli/ledger.mjs +138 -0
  42. package/src/cli/ledger.test.mjs +127 -0
  43. package/src/cli/merge-guard.mjs +193 -0
  44. package/src/cli/merge-guard.test.mjs +328 -0
  45. package/src/cli/plan-check.mjs +151 -0
  46. package/src/cli/plan-check.test.mjs +143 -0
  47. package/src/cli/plan-stop.mjs +101 -0
  48. package/src/cli/plan-stop.test.mjs +136 -0
  49. package/src/cli/plugin-agents.test.mjs +105 -8
  50. package/src/cli/pr-check.mjs +17 -5
  51. package/src/cli/pr-check.test.mjs +85 -4
  52. package/src/cli/prose.mjs +192 -0
  53. package/src/cli/prose.test.mjs +248 -0
  54. package/src/cli/qc.mjs +22 -0
  55. package/src/cli/registry-history.mjs +1 -1
  56. package/src/cli/report-stash.mjs +69 -0
  57. package/src/cli/report-stash.test.mjs +71 -0
  58. package/src/cli/report-stop.mjs +266 -0
  59. package/src/cli/report-stop.test.mjs +471 -0
  60. package/src/cli/shell-command.mjs +81 -6
  61. package/src/cli/shell-command.test.mjs +101 -1
  62. package/src/cli/task-gate.mjs +179 -0
  63. package/src/cli/task-gate.test.mjs +507 -0
  64. package/src/cli/tokens.mjs +239 -0
  65. package/src/cli/tokens.test.mjs +286 -0
  66. package/src/cli/transcript-usage.mjs +135 -0
  67. package/src/cli/transcript-usage.test.mjs +129 -0
  68. package/src/cli/workflow-hooks.test.mjs +72 -0
  69. package/src/cli/workflow-place.mjs +143 -0
  70. package/src/cli/workflow-place.test.mjs +146 -0
  71. package/src/cli/workflow-settings.mjs +77 -0
  72. package/src/cli/workflow-settings.test.mjs +79 -0
  73. package/src/cli/worktree.mjs +1 -1
  74. package/src/cli/worktree.test.mjs +19 -2
  75. package/src/config.mjs +99 -4
  76. package/src/config.test.mjs +38 -3
  77. package/src/descriptions.mjs +5 -1
  78. package/src/eslint/index.mjs +2 -0
  79. package/src/eslint/jsx.mjs +57 -0
  80. package/src/eslint/preset.mjs +32 -6
  81. package/src/eslint/preset.test.mjs +60 -0
  82. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  83. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  84. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  85. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  86. package/src/eslint/rules/registry-literal.mjs +36 -2
  87. package/src/eslint/rules.test.mjs +153 -0
  88. package/src/gates/call-args.mjs +90 -0
  89. package/src/gates/call-args.test.mjs +21 -0
  90. package/src/gates/config-floor.mjs +41 -20
  91. package/src/gates/config-floor.test.mjs +71 -1
  92. package/src/gates/contract-idempotency.mjs +103 -0
  93. package/src/gates/contract-idempotency.test.mjs +276 -0
  94. package/src/gates/contract-operations.mjs +120 -0
  95. package/src/gates/contract-operations.test.mjs +275 -0
  96. package/src/gates/contract-routes.mjs +82 -0
  97. package/src/gates/contract-routes.test.mjs +210 -0
  98. package/src/gates/registry-literal.mjs +79 -15
  99. package/src/gates/registry-literal.test.mjs +89 -0
  100. package/src/gates/saga-key.mjs +253 -0
  101. package/src/gates/saga-key.test.mjs +322 -0
  102. package/src/gates/scrub.mjs +108 -0
  103. package/src/gates/scrub.test.mjs +29 -0
  104. package/src/gates/tenant-isolation-test.mjs +80 -0
  105. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  106. package/src/gates/tenant-predicate.mjs +644 -91
  107. package/src/gates/tenant-predicate.test.mjs +662 -1
  108. package/src/prose-lines.mjs +49 -0
  109. package/src/prose-lines.test.mjs +63 -0
  110. package/src/registries.mjs +89 -0
  111. package/src/registries.test.mjs +44 -0
  112. package/src/vale-style.test.mjs +158 -0
  113. package/templates/docs/enforcement.md +26 -2
  114. package/templates/github/workflows/ci.yml +18 -1
  115. package/templates/quality-thresholds.json +1 -1
  116. package/templates/vale/.vale.ini +7 -0
  117. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  118. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  119. package/templates/vale/styles/Qc/Latin.yml +9 -0
  120. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  121. package/templates/vale/styles/Qc/Please.yml +6 -0
  122. package/templates/vale/styles/Qc/Progress.yml +9 -0
  123. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  124. package/templates/vale/styles/Qc/Utilize.yml +10 -0
@@ -0,0 +1,92 @@
1
+ // The branch that turns an agent's context size into a note: nothing, keep new output small, or hand off.
2
+ // It reads no file and never refuses a call; the budget guard gives it the numbers and prints the note.
3
+
4
+ import { contextDefaults, merge } from "../config.mjs";
5
+
6
+ const KEY = "swarm.context";
7
+ export const LEVELS = ["none", "summarize", "handoff"];
8
+ const ESTIMATE_LINE = /^[ \t]*(?:\*\*)?Estimate:(?:\*\*)?[ \t]*(\d+)/im;
9
+
10
+ const isPlainObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
11
+ const wrong = (key, value, want) => new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
12
+
13
+ /** @returns the signal settings, or null when the repository turns it off; throws naming the key it got wrong. */
14
+ export function contextSettings(swarm = {}) {
15
+ const raw = swarm.context;
16
+ if (raw === false || raw === null) return null;
17
+ if (raw !== undefined && !isPlainObject(raw)) {
18
+ throw new Error(`${KEY} in qc.config.json must be an object or false, got ${JSON.stringify(raw)}`);
19
+ }
20
+ const settings = merge(contextDefaults, raw ?? {});
21
+ for (const key of ["every", "minCallsLeft", "repeatEvery"]) {
22
+ if (!Number.isInteger(settings[key]) || settings[key] < 1) throw wrong(key, settings[key], "a positive whole number");
23
+ }
24
+ if (typeof settings.summarizeRatio !== "number" || !(settings.summarizeRatio > 1)) {
25
+ throw wrong("summarizeRatio", settings.summarizeRatio, "a number above 1");
26
+ }
27
+ if (typeof settings.handoffRatio !== "number" || !(settings.handoffRatio > settings.summarizeRatio)) {
28
+ throw wrong("handoffRatio", settings.handoffRatio, "a number above summarizeRatio");
29
+ }
30
+ if (!Array.isArray(settings.handoffTypes) || !settings.handoffTypes.every((type) => typeof type === "string" && type !== "")) {
31
+ throw wrong("handoffTypes", settings.handoffTypes, "a list of agent types");
32
+ }
33
+ return settings;
34
+ }
35
+
36
+ /** The number on a prompt's `Estimate:` line, or null. */
37
+ export function estimateOf(prompt) {
38
+ const match = ESTIMATE_LINE.exec(String(prompt ?? ""));
39
+ return match ? Number(match[1]) : null;
40
+ }
41
+
42
+ /** The calls the task still needs: to the estimate while the count is under it, else to the budget. */
43
+ export function callsLeft({ count, budget, estimate = null }) {
44
+ const toBudget = Math.max(budget - count, 0);
45
+ return Number.isInteger(estimate) && estimate > count ? Math.min(estimate - count, toBudget) : toBudget;
46
+ }
47
+
48
+ function levelOf({ ratio, left, agentType }, settings) {
49
+ if (ratio >= settings.handoffRatio && left >= settings.minCallsLeft && settings.handoffTypes.includes(agentType)) return "handoff";
50
+ return ratio >= settings.summarizeRatio ? "summarize" : "none";
51
+ }
52
+
53
+ const thousands = (n) => `${Math.round(n / 1000)}K`;
54
+ const times = (ratio) => `${ratio.toFixed(1)}x`;
55
+
56
+ const summarizeText = ({ context, first, ratio }) =>
57
+ `Context signal: each call of this agent re-sends about ${thousands(context)} tokens, ${times(ratio)} its first call (${thousands(first)}). ` +
58
+ "New output adds to every later call: a line range costs less than a whole file, a summary of a long command output " +
59
+ "less than the output, and a file already in context needs no second read.";
60
+
61
+ const handoffText = ({ context, first, ratio, left }) =>
62
+ `Context signal: each call of this agent re-sends about ${thousands(context)} tokens, ${times(ratio)} its first call (${thousands(first)}), ` +
63
+ `with about ${left} calls of work left. A fresh agent starts near ${thousands(first)}, so the rest of the task costs less there. ` +
64
+ "The hand-off at the next green step: commit and push, write a note in a `handoffs/` folder beside the report file " +
65
+ "(lines `Brief:`, `Worktree:`, `Branch:`, and `Head:`; sections `## Done`, `## Left`, and `## Next step`), " +
66
+ "and send the report with a line `HANDOFF: <note path>`. The controller starts a fresh implementer from the note.";
67
+
68
+ /**
69
+ * The note for one check. `fired` is `{ level, at }` of the last note, or null.
70
+ * @returns `{ level, text }`, or null when there is nothing new to say
71
+ */
72
+ export function contextVerdict({ context, first, count, budget, estimate = null, agentType, fired = null }, settings) {
73
+ if (!(first > 0) || !(context > 0)) return null;
74
+ const ratio = context / first;
75
+ const left = callsLeft({ count, budget, estimate });
76
+ const level = levelOf({ ratio, left, agentType }, settings);
77
+ if (level === "none") return null;
78
+ const firedRank = fired ? Math.max(LEVELS.indexOf(fired.level), 0) : 0;
79
+ const repeat = level === "handoff" && fired?.level === "handoff" && count - fired.at >= settings.repeatEvery;
80
+ if (LEVELS.indexOf(level) <= firedRank && !repeat) return null;
81
+ const facts = { context, first, ratio, left };
82
+ return { level, text: level === "handoff" ? handoffText(facts) : summarizeText(facts) };
83
+ }
84
+
85
+ /** The line a hand-back gains when the agent ends large, so the controller can weigh a resume against a fresh agent. */
86
+ export function handbackStamp({ context, first }, settings) {
87
+ if (!(first > 0) || !(context > 0) || context / first < settings.summarizeRatio) return null;
88
+ return (
89
+ `CONTEXT: this agent ended at about ${thousands(context)} tokens per call, ${times(context / first)} its first call (${thousands(first)}). ` +
90
+ `A resume re-sends that on each call; a fresh agent of this type starts near ${thousands(first)}.`
91
+ );
92
+ }
@@ -0,0 +1,99 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { contextDefaults } from "../config.mjs";
4
+ import { LEVELS, callsLeft, contextSettings, contextVerdict, estimateOf, handbackStamp } from "./context-signal.mjs";
5
+
6
+ const settings = contextSettings();
7
+ const IMPL = "architecture:sdd-implementer";
8
+ const facts = (context, extra = {}) => ({ context, first: 40_000, count: 10, budget: 100, estimate: null, agentType: IMPL, fired: null, ...extra });
9
+
10
+ test("the signal is on with the defaults, and `false` turns it off", () => {
11
+ assert.deepEqual(contextSettings(), contextDefaults);
12
+ assert.deepEqual(contextSettings({ context: {} }), contextDefaults);
13
+ assert.equal(contextSettings({ context: false }), null);
14
+ assert.equal(contextSettings({ context: { every: 1 } }).every, 1);
15
+ assert.deepEqual(contextSettings({ context: { handoffTypes: ["x"] } }).handoffTypes, ["x"]);
16
+ });
17
+
18
+ test("a wrong key is a named config error", () => {
19
+ for (const context of [{ every: 0 }, { minCallsLeft: 1.5 }, { summarizeRatio: 1 }, { handoffRatio: 2 }, { handoffTypes: "x" }, "on"]) {
20
+ assert.throws(() => contextSettings({ context }), /swarm\.context/, JSON.stringify(context));
21
+ }
22
+ });
23
+
24
+ test("the calls left run to the prompt's estimate while the count is under it, else to the budget", () => {
25
+ assert.equal(callsLeft({ count: 10, budget: 100 }), 90);
26
+ assert.equal(callsLeft({ count: 10, budget: 100, estimate: 30 }), 20);
27
+ assert.equal(callsLeft({ count: 40, budget: 100, estimate: 30 }), 60);
28
+ assert.equal(callsLeft({ count: 120, budget: 100 }), 0);
29
+ });
30
+
31
+ test("an estimate line is read with or without bold", () => {
32
+ assert.equal(estimateOf("Brief: x\nEstimate: 25\n"), 25);
33
+ assert.equal(estimateOf("**Estimate:** 30 tool calls"), 30);
34
+ assert.equal(estimateOf("no line"), null);
35
+ assert.equal(estimateOf(null), null);
36
+ });
37
+
38
+ test("under summarizeRatio times the first call there is nothing to say", () => {
39
+ assert.equal(contextVerdict(facts(119_000), settings), null);
40
+ });
41
+
42
+ test("at summarizeRatio times the note says new output adds to every later call", () => {
43
+ const verdict = contextVerdict(facts(120_000), settings);
44
+ assert.equal(verdict.level, "summarize");
45
+ assert.match(verdict.text, /re-sends about 120K tokens, 3\.0x its first call \(40K\)/);
46
+ assert.match(verdict.text, /line range/);
47
+ assert.doesNotMatch(verdict.text, /HANDOFF/);
48
+ });
49
+
50
+ test("at handoffRatio times, with work left, a hand-off type gets the hand-off steps", () => {
51
+ const verdict = contextVerdict(facts(200_000), settings);
52
+ assert.equal(verdict.level, "handoff");
53
+ assert.match(verdict.text, /about 90 calls of work left/);
54
+ assert.match(verdict.text, /`HANDOFF: <note path>`/);
55
+ assert.match(verdict.text, /`handoffs\/`/);
56
+ });
57
+
58
+ test("too few calls left, or another type, keeps the note at summarize", () => {
59
+ assert.equal(contextVerdict(facts(200_000, { count: 90 }), settings).level, "summarize");
60
+ assert.equal(contextVerdict(facts(200_000, { estimate: 20 }), settings).level, "summarize");
61
+ assert.equal(contextVerdict(facts(200_000, { agentType: "architecture:sdd-reviewer" }), settings).level, "summarize");
62
+ });
63
+
64
+ test("each level fires once, and the hand-off repeats every repeatEvery calls", () => {
65
+ assert.equal(contextVerdict(facts(130_000, { fired: { level: "summarize", at: 5 } }), settings), null);
66
+ assert.equal(contextVerdict(facts(200_000, { fired: { level: "summarize", at: 5 } }), settings).level, "handoff");
67
+ assert.equal(contextVerdict(facts(200_000, { count: 20, fired: { level: "handoff", at: 10 } }), settings), null);
68
+ assert.equal(contextVerdict(facts(200_000, { count: 30, fired: { level: "handoff", at: 10 } }), settings).level, "handoff");
69
+ assert.equal(contextVerdict(facts(130_000, { count: 90, fired: { level: "handoff", at: 10 } }), settings), null);
70
+ assert.deepEqual(LEVELS, ["none", "summarize", "handoff"]);
71
+ });
72
+
73
+ test("a missing first or latest context says nothing", () => {
74
+ assert.equal(contextVerdict(facts(200_000, { first: 0 }), settings), null);
75
+ assert.equal(contextVerdict(facts(0), settings), null);
76
+ });
77
+
78
+ test("the hand-back stamp names the end context only at or over summarizeRatio", () => {
79
+ assert.equal(handbackStamp({ context: 100_000, first: 40_000 }, settings), null);
80
+ assert.match(handbackStamp({ context: 200_000, first: 40_000 }, settings), /^CONTEXT: this agent ended at about 200K tokens per call, 5\.0x its first call \(40K\)/);
81
+ assert.equal(handbackStamp({ context: 200_000, first: 0 }, settings), null);
82
+ });
83
+
84
+ test("an estimate far past the budget is capped at the budget", () => {
85
+ assert.equal(callsLeft({ count: 10, budget: 100, estimate: 500 }), 90);
86
+ });
87
+
88
+ test("exactly minCallsLeft calls left still hands off", () => {
89
+ assert.equal(contextVerdict(facts(200_000, { count: 85 }), settings).level, "handoff");
90
+ assert.equal(contextVerdict(facts(200_000, { count: 86 }), settings).level, "summarize");
91
+ });
92
+
93
+ test("the hand-back stamp fires at exactly summarizeRatio", () => {
94
+ assert.match(handbackStamp({ context: 120_000, first: 40_000 }, settings), /^CONTEXT: /);
95
+ });
96
+
97
+ test("a null context is the same as false", () => {
98
+ assert.equal(contextSettings({ context: null }), null);
99
+ });
@@ -0,0 +1,46 @@
1
+ // A resource: the operations of the contract and the ledger as they stood at the merge base with a
2
+ // ref. Git answers a missing ref or clone with a skip, never a failure. A base contract that does
3
+ // not parse is reported, because the check cannot say what it could not read.
4
+
5
+ import path from "node:path";
6
+ import { owesKey } from "../gates/contract-idempotency.mjs";
7
+ import { contractOperations } from "../gates/contract-operations.mjs";
8
+ import { git } from "./registry-history.mjs";
9
+
10
+ /** The ledger's ids as `git show` returned them. A missing or unreadable file is an empty ledger. */
11
+ function ledgerOf(text) {
12
+ try {
13
+ const parsed = JSON.parse(text ?? "[]");
14
+ return Array.isArray(parsed) ? parsed.filter((id) => typeof id === "string") : [];
15
+ } catch {
16
+ return [];
17
+ }
18
+ }
19
+
20
+ /**
21
+ * @param {string} root the repository root, or a folder inside one
22
+ * @param {{base: string, contract: string, legacy: string, fields: string[], exemptDeleteById: boolean}} options
23
+ * the paths are relative to `root`; `fields` and `exemptDeleteById` decide which operation `owed` its key
24
+ * @returns {Promise<{skip: string} | {unreadable: string} | {ledger: string[], operations: {id: string, method: string, path: string, owed: boolean}[]}>}
25
+ */
26
+ export async function contractHistory(root, { base, contract, legacy, fields, exemptDeleteById }) {
27
+ if (git(root, "rev-parse", "--verify", "--quiet", "HEAD") === null) return { skip: "no git, or no commit yet" };
28
+ if (git(root, "rev-parse", "--verify", "--quiet", base + "^{commit}") === null) return { skip: "no ref '" + base + "'" };
29
+ const mergeBase = git(root, "merge-base", base, "HEAD")?.trim();
30
+ if (!mergeBase) return { skip: "no merge base with '" + base + "', as in a shallow clone" };
31
+ const at = (file) => git(root, "show", mergeBase + ":./" + file.split(path.sep).join("/"));
32
+ const contractText = at(contract);
33
+ let operations = [];
34
+ try {
35
+ const found = contractText === null ? [] : await contractOperations(contractText);
36
+ operations = found.map((operation) => ({
37
+ id: operation.id,
38
+ method: operation.method,
39
+ path: operation.path,
40
+ owed: owesKey(operation, { fields, exemptDeleteById }),
41
+ }));
42
+ } catch (error) {
43
+ return { unreadable: "the contract at the merge base with '" + base + "' does not parse: " + error.message };
44
+ }
45
+ return { ledger: ledgerOf(at(legacy)), operations };
46
+ }
@@ -0,0 +1,118 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { execFileSync } from "node:child_process";
4
+ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { contractHistory } from "./contract-history.mjs";
8
+
9
+ const git = (dir, ...args) => execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", ...args], { cwd: dir, stdio: "pipe" });
10
+ const options = {
11
+ base: "main",
12
+ contract: "contracts/openapi.yaml",
13
+ legacy: "contracts/idempotency-legacy.json",
14
+ fields: ["mutationId"],
15
+ exemptDeleteById: true,
16
+ };
17
+ const CONTRACT = "paths:\n /v1/a:\n post:\n operationId: createA\n get:\n operationId: listA\n";
18
+
19
+ /** A repository whose one commit holds `files` under `folder`. The history is asked from `folder`. */
20
+ function committed(files, folder = "") {
21
+ const dir = mkdtempSync(path.join(tmpdir(), "qc-history-"));
22
+ git(dir, "init", "-q", "-b", "main");
23
+ for (const [name, text] of Object.entries(files)) {
24
+ const file = path.join(dir, folder, name);
25
+ mkdirSync(path.dirname(file), { recursive: true });
26
+ writeFileSync(file, text);
27
+ }
28
+ git(dir, "add", "-A");
29
+ git(dir, "commit", "-q", "-m", "base");
30
+ return { root: path.join(dir, folder), done: () => rmSync(dir, { recursive: true, force: true }) };
31
+ }
32
+
33
+ test("the operations and the ledger are read as they stood at the merge base, and owed marks a missing key", async () => {
34
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": '["createA"]' });
35
+ const found = await contractHistory(repo.root, options);
36
+ repo.done();
37
+ assert.deepEqual(found.ledger, ["createA"]);
38
+ assert.deepEqual(found.operations, [
39
+ { id: "createA", method: "post", path: "/v1/a", owed: true },
40
+ { id: "listA", method: "get", path: "/v1/a", owed: false },
41
+ ]);
42
+ });
43
+
44
+ test("a root that is a folder inside the repository reads its own files", async () => {
45
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": '["createA"]' }, "service");
46
+ const found = await contractHistory(repo.root, options);
47
+ repo.done();
48
+ assert.deepEqual(found.ledger, ["createA"]);
49
+ assert.equal(found.operations.length, 2);
50
+ });
51
+
52
+ test("a malformed base ledger reads as empty", async () => {
53
+ const repo = committed({ "contracts/openapi.yaml": CONTRACT, "contracts/idempotency-legacy.json": "{not json" });
54
+ const found = await contractHistory(repo.root, options);
55
+ repo.done();
56
+ assert.deepEqual(found.ledger, []);
57
+ assert.equal(found.operations.length, 2);
58
+ });
59
+
60
+ test("a contract absent at the base holds no operations, so every ledger id is new", async () => {
61
+ const repo = committed({ "README.md": "x\n" });
62
+ const found = await contractHistory(repo.root, options);
63
+ repo.done();
64
+ assert.deepEqual(found, { ledger: [], operations: [] });
65
+ });
66
+
67
+ test("a base contract that does not parse is reported, not skipped", async () => {
68
+ const repo = committed({ "contracts/openapi.yaml": "paths: [unclosed\n" });
69
+ const found = await contractHistory(repo.root, options);
70
+ repo.done();
71
+ assert.equal(found.skip, undefined);
72
+ assert.match(found.unreadable, /merge base/);
73
+ });
74
+
75
+ test("no ref, and no repository, skip with a reason", async () => {
76
+ const repo = committed({ "README.md": "x\n" });
77
+ assert.match((await contractHistory(repo.root, { ...options, base: "no-such-ref" })).skip, /no ref 'no-such-ref'/);
78
+ repo.done();
79
+ const bare = mkdtempSync(path.join(tmpdir(), "qc-history-"));
80
+ try {
81
+ assert.match((await contractHistory(bare, options)).skip, /no git/);
82
+ } finally {
83
+ rmSync(bare, { recursive: true, force: true });
84
+ }
85
+ });
86
+
87
+ test("a keyed POST and an exempt DELETE by id are not owed", async () => {
88
+ const contract = [
89
+ "paths:",
90
+ " /v1/a:",
91
+ " post:",
92
+ " operationId: createA",
93
+ " requestBody:",
94
+ " content:",
95
+ " application/json:",
96
+ " schema:",
97
+ " properties: { mutationId: {} }",
98
+ " /v1/a/{id}:",
99
+ " delete:",
100
+ " operationId: deleteA",
101
+ "",
102
+ ].join("\n");
103
+ const repo = committed({ "contracts/openapi.yaml": contract });
104
+ const found = await contractHistory(repo.root, options);
105
+ const judged = await contractHistory(repo.root, { ...options, exemptDeleteById: false });
106
+ repo.done();
107
+ assert.deepEqual(found.operations.map(({ id, owed }) => [id, owed]), [["createA", false], ["deleteA", false]]);
108
+ assert.deepEqual(judged.operations.map(({ id, owed }) => [id, owed]), [["createA", false], ["deleteA", true]]);
109
+ });
110
+
111
+ test("a base ref that resolves but shares no history with HEAD skips as having no merge base", async () => {
112
+ const repo = committed({ "README.md": "x\n" });
113
+ git(repo.root, "checkout", "-q", "--orphan", "other");
114
+ git(repo.root, "commit", "-q", "--allow-empty", "-m", "unrelated");
115
+ const found = await contractHistory(repo.root, options);
116
+ repo.done();
117
+ assert.match(found.skip, /no merge base with 'main'/);
118
+ });
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger that keeps the main session a controller while `swarm.dispatch` is on: it edits only `swarm.review.controllerPaths`.
3
+ // It guards Write, Edit, MultiEdit and NotebookEdit; a shell write is only reported, by `bash-edit-guard.mjs`.
4
+
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { globMatcher } from "../glob.mjs";
8
+ import { checkoutRootOf } from "./checkout-root.mjs";
9
+ import { pathKey } from "./git-read.mjs";
10
+ import { commonDirOf } from "./ledger.mjs";
11
+ import { workflowAt } from "./workflow-settings.mjs";
12
+
13
+ const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
14
+
15
+ const deny = (reason) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason } });
16
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
17
+
18
+ function sameRepository(a, b) {
19
+ const [left, right] = [commonDirOf(a), commonDirOf(b)];
20
+ return left !== null && right !== null && pathKey(left) === pathKey(right);
21
+ }
22
+
23
+ /** True when `rel` matches a controller glob. Windows paths ignore case, so both sides are lowercased there. */
24
+ export function isControllerPath(rel, controllerPaths, platform = process.platform) {
25
+ if (platform !== "win32") return globMatcher(controllerPaths)(rel);
26
+ return globMatcher(controllerPaths.map((glob) => glob.toLowerCase()))(rel.toLowerCase());
27
+ }
28
+
29
+ /** The verdict on one edit. @returns the hook output, or null to let the edit run with no message. */
30
+ export function decide(call, platform = process.platform) {
31
+ if (call.hook_event_name !== "PreToolUse" || !EDIT_TOOLS.has(call.tool_name)) return null;
32
+ if (typeof call.agent_id === "string" && call.agent_id !== "") return null;
33
+ const input = call.tool_input ?? {};
34
+ const target = input.file_path ?? input.notebook_path;
35
+ if (typeof target !== "string" || target === "") return null;
36
+ const cwd = call.cwd ?? process.cwd();
37
+ let workflow;
38
+ try {
39
+ workflow = workflowAt(cwd);
40
+ } catch (error) {
41
+ return context(`Controller guard is off: ${error.message}`);
42
+ }
43
+ if (!workflow) return null;
44
+ const file = path.resolve(cwd, target);
45
+ const fileRoot = checkoutRootOf(path.dirname(file));
46
+ if (!fileRoot || !sameRepository(fileRoot, workflow.root)) return null;
47
+ const rel = path.relative(fileRoot, file).replaceAll("\\", "/");
48
+ const { controllerPaths } = workflow.review;
49
+ if (isControllerPath(rel, controllerPaths, platform)) return null;
50
+ return deny(
51
+ `Controller guard: while swarm.dispatch is on, the main session edits only swarm.review.controllerPaths (${controllerPaths.join(", ")}), ` +
52
+ `and ${rel} is outside them. Write a brief and dispatch an implementer for this change. ` +
53
+ "For a path the controller owns, add its glob to swarm.review.controllerPaths in qc.config.json.",
54
+ );
55
+ }
56
+
57
+ async function readStdin() {
58
+ let data = "";
59
+ for await (const chunk of process.stdin) data += chunk;
60
+ return data;
61
+ }
62
+
63
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
64
+ if (isEntryPoint) {
65
+ let call = null;
66
+ try {
67
+ call = JSON.parse(await readStdin());
68
+ } catch {
69
+ // Not hook input, so there is no edit to judge.
70
+ }
71
+ const output = call ? decide(call) : null;
72
+ if (output) process.stdout.write(JSON.stringify(output));
73
+ }
@@ -0,0 +1,119 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { decide, isControllerPath } from "./controller-guard.mjs";
9
+
10
+ const HOOK = fileURLToPath(new URL("./controller-guard.mjs", import.meta.url));
11
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
12
+
13
+ /** A checkout with the checks on and a linked worktree, another repository, and a folder outside any checkout. */
14
+ function workspace(t, dispatchConfig = { swarm: { dispatch: {} } }) {
15
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-controller-")));
16
+ t.after(() => rmSync(base, { recursive: true, force: true }));
17
+ const main = path.join(base, "main");
18
+ const other = path.join(base, "other");
19
+ git(base, "init", "-q", "-b", "main", main);
20
+ git(base, "init", "-q", "-b", "main", other);
21
+ for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) {
22
+ git(main, "config", key, value);
23
+ }
24
+ writeFileSync(path.join(main, "a.txt"), "a\n");
25
+ git(main, "add", ".");
26
+ git(main, "commit", "-q", "-m", "init");
27
+ writeFileSync(path.join(main, "qc.config.json"), JSON.stringify(dispatchConfig));
28
+ const linked = path.join(base, "linked");
29
+ git(main, "worktree", "add", "-q", "-b", "feat/1-x", linked);
30
+ const scratch = path.join(base, "scratch");
31
+ mkdirSync(scratch);
32
+ return { main, other, linked, scratch };
33
+ }
34
+
35
+ const edit = (cwd, file_path, tool_name = "Edit", extra = {}) => ({
36
+ session_id: "s",
37
+ cwd,
38
+ hook_event_name: "PreToolUse",
39
+ tool_name,
40
+ tool_input: tool_name === "NotebookEdit" ? { notebook_path: file_path } : { file_path },
41
+ ...extra,
42
+ });
43
+ const denied = (output) => output?.hookSpecificOutput?.permissionDecisionReason ?? null;
44
+
45
+ test("with swarm.dispatch off, the main session edits anything", (t) => {
46
+ const ws = workspace(t, { swarm: {} });
47
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"))), null);
48
+ });
49
+
50
+ test("a subagent's edit is left alone", (t) => {
51
+ const ws = workspace(t);
52
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"), "Write", { agent_id: "agent-1" })), null);
53
+ });
54
+
55
+ test("the main session's edit of code in the checkout, or in its worktree, is refused", (t) => {
56
+ const ws = workspace(t);
57
+ for (const [file, rel] of [
58
+ [path.join(ws.main, "src", "a.ts"), "src/a.ts"],
59
+ [path.join(ws.main, "src", "notes.md"), "src/notes.md"],
60
+ [path.join(ws.linked, "src", "a.ts"), "src/a.ts"],
61
+ ]) {
62
+ assert.match(denied(decide(edit(ws.main, file))) ?? "", new RegExp(`${rel.replace(".", "\\.")} is outside them`), file);
63
+ }
64
+ assert.match(denied(decide(edit(ws.main, path.join(ws.main, "nb.ipynb"), "NotebookEdit"))) ?? "", /nb\.ipynb/);
65
+ });
66
+
67
+ test("the controller's own paths, a path outside the checkout, and another repository pass", (t) => {
68
+ const ws = workspace(t);
69
+ for (const file of [
70
+ path.join(ws.main, "docs", "plan.md"),
71
+ path.join(ws.main, "README.md"),
72
+ path.join(ws.main, "qc.config.json"),
73
+ path.join(ws.main, ".claude", "settings.json"),
74
+ path.join(ws.main, "pkg", ".claude", "rules", "a.md"),
75
+ path.join(ws.linked, "docs", "a.md"),
76
+ path.join(ws.scratch, "brief.md"),
77
+ path.join(ws.other, "src", "a.ts"),
78
+ ]) {
79
+ assert.equal(decide(edit(ws.main, file, "Write")), null, file);
80
+ }
81
+ });
82
+
83
+ test("a Windows path with either separator is judged the same", (t) => {
84
+ const ws = workspace(t);
85
+ const file = path.join(ws.main, "src", "a.ts");
86
+ assert.ok(denied(decide(edit(ws.main, file.replaceAll("\\", "/")))));
87
+ if (process.platform === "win32") assert.ok(denied(decide(edit(ws.main, file.replaceAll("/", "\\")))));
88
+ });
89
+
90
+ test("a repository replaces the controller paths", (t) => {
91
+ const ws = workspace(t, { swarm: { dispatch: {}, review: { controllerPaths: ["src/**"] } } });
92
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"))), null);
93
+ assert.ok(denied(decide(edit(ws.main, path.join(ws.main, "docs", "a.md")))));
94
+ });
95
+
96
+ test("a config error is reported as context, never as a refusal", (t) => {
97
+ const ws = workspace(t, { swarm: { dispatch: "on" } });
98
+ const output = decide(edit(ws.main, path.join(ws.main, "src", "a.ts")));
99
+ assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /Controller guard is off/);
100
+ });
101
+
102
+ test("the hook process prints the deny", (t) => {
103
+ const ws = workspace(t);
104
+ const result = spawnSync(process.execPath, [HOOK], { input: JSON.stringify(edit(ws.main, path.join(ws.main, "src", "a.ts"))), encoding: "utf8" });
105
+ assert.equal(result.status, 0, result.stderr);
106
+ assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
107
+ });
108
+
109
+ test("Windows reads a path with no regard to case, so the other systems do not", (t) => {
110
+ const ws = workspace(t);
111
+ const globs = ["docs/**", "*.md", "qc.config.json", "**/.claude/**"];
112
+ for (const rel of ["Docs/plan.md", "README.MD", "QC.config.json", "pkg/.CLAUDE/a.md"]) {
113
+ assert.equal(isControllerPath(rel, globs, "win32"), true, rel);
114
+ assert.equal(isControllerPath(rel, globs, "linux"), false, rel);
115
+ assert.equal(decide(edit(ws.main, path.join(ws.main, ...rel.split("/")), "Write"), "win32"), null, rel);
116
+ assert.ok(denied(decide(edit(ws.main, path.join(ws.main, ...rel.split("/")), "Write"), "linux")), rel);
117
+ }
118
+ assert.equal(isControllerPath("src/A.ts", globs, "win32"), false);
119
+ });
@@ -5,8 +5,9 @@
5
5
  import { existsSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
- import { dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
8
+ import { dispatchNote, dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
9
9
  import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
10
+ import { judgeTask, recordDispatch } from "./task-gate.mjs";
10
11
 
11
12
  const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", ...fields } });
12
13
  const deny = (reason) => output({ permissionDecision: "deny", permissionDecisionReason: reason });
@@ -49,18 +50,27 @@ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
49
50
  const input = call.tool_input ?? {};
50
51
  const refusal = dispatchRefusal(input, settings);
51
52
  if (refusal) return deny(refusal);
53
+ // The task gate judges before the slot is claimed, so a refused task holds no slot.
54
+ const task = judgeTask(call, tmp);
55
+ if (task.refusal) return deny(task.refusal);
56
+ const note = dispatchNote(input, settings);
52
57
  const type = typeOf(input);
53
- if (!isImplementer(type, settings)) return null;
58
+ if (!isImplementer(type, settings)) return noted(recordDispatch(task), note);
54
59
  let holder;
55
60
  try {
56
61
  holder = claimSlot(dir, settings, now, idOf(call.tool_use_id));
57
62
  } catch {
58
63
  // A busy or read-only temp folder is the hook's own problem, never a reason to refuse a dispatch.
59
- return null;
64
+ return noted(recordDispatch(task), note);
60
65
  }
61
- return holder ? deny(slotRefusal({ type, ...holder })) : null;
66
+ return holder ? deny(slotRefusal({ type, ...holder })) : noted(recordDispatch(task), note);
62
67
  }
63
68
 
69
+ const noted = (...notes) => {
70
+ const text = notes.filter(Boolean).join(" ");
71
+ return text ? context(text) : null;
72
+ };
73
+
64
74
  async function readStdin() {
65
75
  let data = "";
66
76
  for await (const chunk of process.stdin) data += chunk;
@@ -142,13 +142,12 @@ test("each allowed pair passes, including a full model id and a branch reviewer
142
142
  null,
143
143
  );
144
144
  decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
145
- assert.equal(
146
- decide(
147
- agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
148
- ws.tmp,
149
- ),
150
- null,
145
+ const pinned = decide(
146
+ agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
147
+ ws.tmp,
151
148
  );
149
+ assert.equal(pinned.hookSpecificOutput.permissionDecision, undefined);
150
+ assert.match(pinned.hookSpecificOutput.additionalContext, /share no prompt cache/);
152
151
  });
153
152
 
154
153
  test("a repository's models override replaces one type's families and leaves the rest at default", (t) => {