architecture-harness 0.19.0 → 0.20.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -1,11 +1,12 @@
1
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`.
2
+ // The PreToolUse trigger that keeps the main session a controller while `swarm.dispatch` is on: it edits only `swarm.review.controllerPaths`,
3
+ // or a small fix inside `swarm.direct`. It guards the edit tools; a shell write is only reported, by `bash-edit-guard.mjs`.
4
4
 
5
5
  import path from "node:path";
6
6
  import { fileURLToPath } from "node:url";
7
- import { globMatcher } from "../glob.mjs";
7
+ import { pathMatcher } from "../glob.mjs";
8
8
  import { checkoutRootOf } from "./checkout-root.mjs";
9
+ import { editLane, sizeLine } from "./direct-lane.mjs";
9
10
  import { pathKey } from "./git-read.mjs";
10
11
  import { commonDirOf } from "./ledger.mjs";
11
12
  import { workflowAt } from "./workflow-settings.mjs";
@@ -20,11 +21,8 @@ function sameRepository(a, b) {
20
21
  return left !== null && right !== null && pathKey(left) === pathKey(right);
21
22
  }
22
23
 
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
- }
24
+ /** True when `rel` matches a controller glob, with no case on Windows. */
25
+ export const isControllerPath = (rel, controllerPaths, platform = process.platform) => pathMatcher(controllerPaths, platform)(rel);
28
26
 
29
27
  /** The verdict on one edit. @returns the hook output, or null to let the edit run with no message. */
30
28
  export function decide(call, platform = process.platform) {
@@ -47,10 +45,19 @@ export function decide(call, platform = process.platform) {
47
45
  const rel = path.relative(fileRoot, file).replaceAll("\\", "/");
48
46
  const { controllerPaths } = workflow.review;
49
47
  if (isControllerPath(rel, controllerPaths, platform)) return null;
48
+ const { direct } = workflow;
49
+ const lane = direct
50
+ ? editLane({ root: fileRoot, base: workflow.base, direct, protectedBranches: workflow.protectedBranches, rel, toolName: call.tool_name, input })
51
+ : workflow.directProblem && { problem: workflow.directProblem };
52
+ if (lane && lane.problem === null) {
53
+ return context(`Direct lane: with this edit the branch changes ${sizeLine(lane.size, direct)}, so the fix needs no implementer. Merge it with \`--match-head-commit <sha>\`.`);
54
+ }
55
+ const laneNote = lane ? ` The direct lane of swarm.direct does not apply: ${lane.problem}.` : "";
50
56
  return deny(
51
57
  `Controller guard: while swarm.dispatch is on, the main session edits only swarm.review.controllerPaths (${controllerPaths.join(", ")}), ` +
52
58
  `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.",
59
+ "For a path the controller owns, add its glob to swarm.review.controllerPaths in qc.config.json." +
60
+ laneNote,
54
61
  );
55
62
  }
56
63
 
@@ -117,3 +117,47 @@ test("Windows reads a path with no regard to case, so the other systems do not",
117
117
  }
118
118
  assert.equal(isControllerPath("src/A.ts", globs, "win32"), false);
119
119
  });
120
+
121
+ /** The workspace, with `origin/main` at the first commit so the linked worktree's branch has a base. */
122
+ function laneWorkspace(t, config) {
123
+ const ws = workspace(t, config);
124
+ git(ws.main, "update-ref", "refs/remotes/origin/main", "main");
125
+ return ws;
126
+ }
127
+
128
+ const small = { old_string: "a", new_string: "b" };
129
+
130
+ test("a small edit on a branch passes through the direct lane, with a note of its size", (t) => {
131
+ const ws = laneWorkspace(t);
132
+ const output = decide(edit(ws.main, path.join(ws.linked, "src", "a.ts"), "Edit", { tool_input: { file_path: path.join(ws.linked, "src", "a.ts"), ...small } }));
133
+ assert.equal(denied(output), null);
134
+ assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /Direct lane: with this edit the branch changes 2 of 20 lines in 1 of 2 files/);
135
+ });
136
+
137
+ test("an edit that leaves the direct lane is refused with the reason", (t) => {
138
+ const ws = laneWorkspace(t);
139
+ const big = { old_string: "a\n".repeat(11), new_string: "b\n".repeat(11) };
140
+ const linked = path.join(ws.linked, "src", "a.ts");
141
+ assert.match(denied(decide(edit(ws.main, linked, "Edit", { tool_input: { file_path: linked, ...big } }))) ?? "", /does not apply: the branch changes 22 of 20 lines/);
142
+ const onMain = path.join(ws.main, "src", "a.ts");
143
+ assert.match(denied(decide(edit(ws.main, onMain, "Edit", { tool_input: { file_path: onMain, ...small } }))) ?? "", /main is a protected branch/);
144
+ });
145
+
146
+ test("with swarm.direct false, the refusal is the controller's alone", (t) => {
147
+ const ws = laneWorkspace(t, { swarm: { dispatch: {}, direct: false } });
148
+ const linked = path.join(ws.linked, "src", "a.ts");
149
+ assert.equal(
150
+ denied(decide(edit(ws.main, linked, "Edit", { tool_input: { file_path: linked, ...small } }))),
151
+ "Controller guard: while swarm.dispatch is on, the main session edits only swarm.review.controllerPaths " +
152
+ "(docs/**, *.md, qc.config.json, **/.claude/**), and src/a.ts is outside them. Write a brief and dispatch an implementer for this change. " +
153
+ "For a path the controller owns, add its glob to swarm.review.controllerPaths in qc.config.json.",
154
+ );
155
+ });
156
+
157
+ test("a wrong swarm.direct closes the lane and keeps the guard on", (t) => {
158
+ const ws = laneWorkspace(t, { swarm: { dispatch: {}, direct: { maxLines: 0 } } });
159
+ const linked = path.join(ws.linked, "src", "a.ts");
160
+ const reason = denied(decide(edit(ws.main, linked, "Edit", { tool_input: { file_path: linked, ...small } }))) ?? "";
161
+ assert.match(reason, /^Controller guard: while swarm.dispatch is on/);
162
+ assert.match(reason, /does not apply: swarm.direct.maxLines in qc.config.json must be a positive whole number/);
163
+ });
@@ -0,0 +1,209 @@
1
+ // The branch that decides the direct lane of `swarm.direct`: a small fix that the main session edits and merges
2
+ // without the subagent workflow. The controller guard and the merge guard ask it. Every unknown fails closed.
3
+
4
+ import { closeSync, existsSync, openSync, readFileSync, readSync, statSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { CONFIG_FILE, directDefaults, load, merge } from "../config.mjs";
7
+ import { pathMatcher } from "../glob.mjs";
8
+ import { checkoutRootOf } from "./checkout-root.mjs";
9
+ import { branchesAt, gitOut, gitOutWithin } from "./git-read.mjs";
10
+ import { latestVerdictFor, shaMatches } from "./ledger.mjs";
11
+
12
+ const KEY = "swarm.direct";
13
+ const DIRECT_KEYS = Object.keys(directDefaults);
14
+ const KINDS = ["task", "branch"];
15
+ const GITLINK_MODE = "160000";
16
+ const SNIFF_BYTES = 8_000;
17
+ const MAX_TEXT_BYTES = 1_000_000;
18
+ // Under the 10 s timeout of a PreToolUse hook, for all git and gh reads of one call: a hook that times out lets its call run.
19
+ export const LANE_BUDGET_MS = 6_000;
20
+
21
+ const isGlobList = (value) => Array.isArray(value) && value.every((glob) => typeof glob === "string" && glob !== "");
22
+ const isCount = (value) => Number.isInteger(value) && value >= 1;
23
+ const wrong = (key, value, want) => new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
24
+
25
+ /** @returns the lane's limits, or null when `swarm.direct` is false; throws naming the key a repository got wrong. */
26
+ export function directSettings(swarm = {}) {
27
+ const raw = swarm.direct ?? {};
28
+ if (raw === false) return null;
29
+ if (typeof raw !== "object" || Array.isArray(raw)) {
30
+ throw new Error(`${KEY} in qc.config.json must be an object or false, got ${JSON.stringify(raw)}`);
31
+ }
32
+ const unknown = Object.keys(raw).find((key) => !DIRECT_KEYS.includes(key));
33
+ if (unknown !== undefined) throw new Error(`${KEY}.${unknown} in qc.config.json is not a direct lane setting; the keys are ${DIRECT_KEYS.join(", ")}`);
34
+ const settings = merge(directDefaults, raw);
35
+ for (const key of ["maxLines", "maxFiles"]) if (!isCount(settings[key])) throw wrong(key, settings[key], "a positive whole number");
36
+ for (const key of ["excludes", "reviewPaths"]) if (!isGlobList(settings[key])) throw wrong(key, settings[key], "a list of globs");
37
+ return settings;
38
+ }
39
+
40
+ /** @returns the lane's limits of the checkout that holds `cwd`, or null when it has no config or the lane is off. */
41
+ export function directSettingsAt(cwd) {
42
+ const root = checkoutRootOf(cwd);
43
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
44
+ return directSettings(load(root).swarm);
45
+ }
46
+
47
+ /** The lines of a text as git counts them: a last line with no newline still counts. */
48
+ export function lineCount(text) {
49
+ if (typeof text !== "string" || text === "") return 0;
50
+ return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
51
+ }
52
+
53
+ /** The lines one edit adds or removes in its own text. A Write or a NotebookEdit also replaces the old text, which `editLane` adds. */
54
+ export function pendingLines(toolName, input = {}) {
55
+ if (toolName === "Edit") return lineCount(input.old_string) + lineCount(input.new_string);
56
+ if (toolName === "MultiEdit") return (input.edits ?? []).reduce((sum, one) => sum + lineCount(one?.old_string) + lineCount(one?.new_string), 0);
57
+ if (toolName === "Write") return lineCount(input.content);
58
+ if (toolName === "NotebookEdit") return lineCount(input.new_source);
59
+ return 0;
60
+ }
61
+
62
+ /** A `gitOut` that shares one deadline, so the whole lane ends inside the hook's timeout. `late()` says it ran out. */
63
+ function gitBy(budgetMs) {
64
+ const deadline = Date.now() + budgetMs;
65
+ const read = (cwd, ...args) => {
66
+ const left = deadline - Date.now();
67
+ return left > 0 ? gitOutWithin(left, cwd, ...args) : null;
68
+ };
69
+ read.late = () => Date.now() >= deadline;
70
+ return read;
71
+ }
72
+
73
+ const gitFailed = (git, what) => (git.late?.() ? `git ran past the ${LANE_BUDGET_MS} ms budget of the lane` : what);
74
+
75
+ function startsWithNul(file) {
76
+ const fd = openSync(file, "r");
77
+ try {
78
+ const buffer = Buffer.alloc(SNIFF_BYTES);
79
+ return buffer.subarray(0, readSync(fd, buffer, 0, SNIFF_BYTES, 0)).includes(0);
80
+ } finally {
81
+ closeSync(fd);
82
+ }
83
+ }
84
+
85
+ /** The lines of a text file, null for a binary or a large file, whose size the lane cannot judge, or undefined when it cannot be read. */
86
+ function fileLines(root, rel) {
87
+ try {
88
+ const file = path.join(root, rel);
89
+ const stat = statSync(file);
90
+ if (!stat.isFile()) return undefined;
91
+ if (stat.size > MAX_TEXT_BYTES || startsWithNul(file)) return null;
92
+ return lineCount(readFileSync(file, "utf8"));
93
+ } catch {
94
+ return undefined;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * The changed files since the commit `fork`, each with its changed lines. With `head`, the commit's changes;
100
+ * without it, the working tree's, untracked files included. A binary file and a submodule have no size the lane
101
+ * can judge, so they map to null. The read of untracked files stops once there are more than `maxFiles`.
102
+ * @returns a Map from path to lines, or null when git cannot say.
103
+ */
104
+ export function changesSince(root, fork, { head = null, maxFiles = Infinity, git = gitOut } = {}) {
105
+ const out = git(root, "diff", "--raw", "--numstat", "--no-renames", "-z", fork, ...(head ? [head] : []));
106
+ if (out === null) return null;
107
+ const changes = new Map();
108
+ const gitlinks = new Set();
109
+ const fields = out.split("\0");
110
+ for (let i = 0; i < fields.length; i++) {
111
+ const field = fields[i];
112
+ if (field === "") continue;
113
+ if (field.startsWith(":")) {
114
+ const [oldMode, newMode] = field.slice(1).split(" ");
115
+ if (oldMode === GITLINK_MODE || newMode === GITLINK_MODE) gitlinks.add(fields[i + 1]);
116
+ i++;
117
+ continue;
118
+ }
119
+ const [added, deleted, file] = field.split("\t");
120
+ changes.set(file, added === "-" ? null : Number(added) + Number(deleted));
121
+ }
122
+ for (const file of gitlinks) changes.set(file, null);
123
+ if (head) return changes;
124
+ const others = git(root, "ls-files", "--others", "--exclude-standard", "-z");
125
+ if (others === null) return null;
126
+ for (const file of others.split("\0").filter(Boolean)) {
127
+ if (changes.size > maxFiles) break;
128
+ if (git.late?.()) return null;
129
+ const lines = fileLines(root, file);
130
+ if (lines === undefined) return null;
131
+ changes.set(file, lines);
132
+ }
133
+ return changes;
134
+ }
135
+
136
+ const sizeOf = (changes) => ({ files: changes.size, lines: [...changes.values()].reduce((sum, lines) => sum + (lines ?? 0), 0) });
137
+
138
+ /** One line that states the size of the branch against the limits. */
139
+ export const sizeLine = ({ files, lines }, direct) => `${lines} of ${direct.maxLines} lines in ${files} of ${direct.maxFiles} files`;
140
+
141
+ /** @returns why `changes` leave the lane, or null when they fit. */
142
+ export function sizeProblem(changes, direct) {
143
+ const excluded = pathMatcher(direct.excludes);
144
+ const hit = [...changes.keys()].find((file) => excluded(file));
145
+ if (hit !== undefined) return `${hit} matches ${KEY}.excludes`;
146
+ const opaque = [...changes.keys()].find((file) => changes.get(file) === null);
147
+ if (opaque !== undefined) return `${opaque} is a binary file, a large file, or a submodule, so the lane cannot judge its size`;
148
+ const size = sizeOf(changes);
149
+ if (size.files > direct.maxFiles || size.lines > direct.maxLines) return `the branch changes ${sizeLine(size, direct)}`;
150
+ return null;
151
+ }
152
+
153
+ /**
154
+ * Judges one main-session edit of `rel` in the checkout at `root`. The branch diff and the pending edit together
155
+ * must fit, on a branch that is not protected. @returns `{ problem }`, or `{ problem: null, size }` when it fits.
156
+ */
157
+ export function editLane({ root, base, direct, protectedBranches, rel, toolName, input, budgetMs = LANE_BUDGET_MS }) {
158
+ const git = gitBy(budgetMs);
159
+ const branch = git(root, "branch", "--show-current");
160
+ if (branch === null) return { problem: gitFailed(git, "git cannot name the checked-out branch") };
161
+ if (branch === "") return { problem: "the checkout has a detached head" };
162
+ if (protectedBranches.includes(branch)) return { problem: `${branch} is a protected branch, so start a branch for the fix` };
163
+ const fork = git(root, "merge-base", base, "HEAD");
164
+ const changes = fork ? changesSince(root, fork, { maxFiles: direct.maxFiles, git }) : null;
165
+ if (!changes) return { problem: gitFailed(git, `git cannot diff the branch against ${base}`) };
166
+ const old = toolName === "Write" || toolName === "NotebookEdit" ? fileLines(root, rel) : undefined;
167
+ const replaced = old === undefined ? 0 : old;
168
+ const before = changes.has(rel) ? changes.get(rel) : 0;
169
+ changes.set(rel, before === null || replaced === null ? null : before + replaced + pendingLines(toolName, input));
170
+ const problem = sizeProblem(changes, direct);
171
+ return problem ? { problem } : { problem: null, size: sizeOf(changes) };
172
+ }
173
+
174
+ /**
175
+ * Judges the merge of head `sha` with no review of the merge kind. A record belongs to the branch when it names
176
+ * a commit of the branch, or the name of a local branch at `sha`, so an amend or a rebase cannot drop it.
177
+ * The newest review on the branch must not ask for changes, and no implementer may have worked on it.
178
+ * @returns `{ problem }`, or `{ problem: null, size }` when the merge fits.
179
+ */
180
+ export function mergeLane({ root, base, direct, protectedBranches = [], sha, records, budgetMs = LANE_BUDGET_MS }) {
181
+ const git = gitBy(budgetMs);
182
+ const fork = git(root, "merge-base", base, sha);
183
+ if (!fork) return { problem: gitFailed(git, `git cannot find the merge base of ${base} and ${sha}`) };
184
+ const history = git(root, "rev-list", `${fork}..${sha}`);
185
+ const changes = history === null ? null : changesSince(root, fork, { head: sha, git });
186
+ if (!changes) return { problem: gitFailed(git, `git cannot diff ${sha} against ${base}`) };
187
+ const shas = history.split(/\r?\n/).filter(Boolean);
188
+ if (shas.length === 0) return { problem: `${sha} has no commit past ${base}, so the lane cannot measure what the PR merges` };
189
+ const branches = branchesAt(root, sha, git);
190
+ if (branches.length === 0) return { problem: gitFailed(git, `no local branch points at ${sha}, so the ledger cannot be tied to its branch`) };
191
+ const guarded = branches.find((branch) => protectedBranches.includes(branch));
192
+ if (guarded !== undefined) return { problem: `${sha} is the head of the protected branch ${guarded}` };
193
+ const ours = (record) => branches.includes(record.branch) || shas.some((one) => shaMatches(record.sha ?? record.head, one));
194
+ const latest = records.filter((record) => record.type === "verdict" && KINDS.includes(record.kind) && ours(record)).at(-1);
195
+ if (latest && latest.verdict !== "APPROVED") return { problem: `the latest review on the branch, of ${latest.sha}, is ${latest.verdict}` };
196
+ const committed = (record) => record.type === "stop" && record.role === "implementer" && typeof record.head === "string";
197
+ const dispatched = (record) => record.type === "dispatch" && record.task === true;
198
+ if (records.some((record) => (committed(record) || dispatched(record)) && ours(record))) {
199
+ return { problem: "an implementer worked on the branch, so it runs the subagent workflow" };
200
+ }
201
+ const problem = sizeProblem(changes, direct);
202
+ if (problem) return { problem };
203
+ const reviewed = pathMatcher(direct.reviewPaths);
204
+ const needsReview = [...changes.keys()].find((file) => reviewed(file));
205
+ if (needsReview !== undefined && latestVerdictFor(records, sha, KINDS)?.verdict !== "APPROVED") {
206
+ return { problem: `${needsReview} matches ${KEY}.reviewPaths, so dispatch the task reviewer (sdd-reviewer) on ${sha}` };
207
+ }
208
+ return { problem: null, size: sizeOf(changes) };
209
+ }
@@ -0,0 +1,196 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } 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 { directDefaults } from "../config.mjs";
8
+ import { directSettings, editLane, lineCount, mergeLane, pendingLines } from "./direct-lane.mjs";
9
+
10
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
11
+ const BASE = "origin/main";
12
+ const lines = (n) => Array.from({ length: n }, (_, i) => `line ${i}`).join("\n") + "\n";
13
+
14
+ /** A repository with `origin/main` at its first commit and a branch `feat/1-x` checked out. */
15
+ function repo(t) {
16
+ const root = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-direct-")));
17
+ t.after(() => rmSync(root, { recursive: true, force: true }));
18
+ git(root, "init", "-q", "-b", "main");
19
+ for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git(root, "config", key, value);
20
+ mkdirSync(path.join(root, "src"));
21
+ writeFileSync(path.join(root, "src", "a.ts"), lines(10));
22
+ git(root, "add", ".");
23
+ git(root, "commit", "-q", "-m", "init");
24
+ git(root, "update-ref", "refs/remotes/origin/main", "HEAD");
25
+ git(root, "switch", "-q", "-c", "feat/1-x");
26
+ return root;
27
+ }
28
+
29
+ const commit = (root, file, text) => {
30
+ mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
31
+ writeFileSync(path.join(root, file), text);
32
+ git(root, "add", ".");
33
+ git(root, "commit", "-q", "-m", `change ${file}`);
34
+ return git(root, "rev-parse", "HEAD");
35
+ };
36
+
37
+ const edit = (root, rel, input, direct = directDefaults) =>
38
+ editLane({ root, base: BASE, direct, protectedBranches: ["main"], rel, toolName: "Edit", input });
39
+
40
+ test("the settings fill their defaults, accept false, and name a wrong key", () => {
41
+ assert.deepEqual(directSettings({}), directDefaults);
42
+ assert.equal(directSettings({ direct: false }), null);
43
+ assert.equal(directSettings({ direct: { maxLines: 5 } }).maxLines, 5);
44
+ assert.throws(() => directSettings({ direct: { maxLines: 0 } }), /swarm\.direct\.maxLines/);
45
+ assert.throws(() => directSettings({ direct: { excludes: "a" } }), /swarm\.direct\.excludes/);
46
+ assert.throws(() => directSettings({ direct: { lines: 5 } }), /swarm\.direct\.lines in qc\.config\.json is not a direct lane setting/);
47
+ assert.throws(() => directSettings({ direct: true }), /must be an object or false/);
48
+ });
49
+
50
+ test("lines count as git counts them, and an edit counts both its old and its new text", () => {
51
+ assert.equal(lineCount(""), 0);
52
+ assert.equal(lineCount("a"), 1);
53
+ assert.equal(lineCount("a\nb\n"), 2);
54
+ assert.equal(pendingLines("Edit", { old_string: "a", new_string: "b" }), 2);
55
+ assert.equal(pendingLines("MultiEdit", { edits: [{ old_string: "a", new_string: "b\nc" }, { old_string: "d", new_string: "" }] }), 4);
56
+ assert.equal(pendingLines("Write", { content: lines(7) }), 7);
57
+ assert.equal(pendingLines("NotebookEdit", { new_source: "x\ny" }), 2);
58
+ });
59
+
60
+ test("a small edit on a branch fits, and the branch diff counts toward the limit", (t) => {
61
+ const root = repo(t);
62
+ const fit = edit(root, "src/a.ts", { old_string: "line 1", new_string: "line one" });
63
+ assert.equal(fit.problem, null);
64
+ assert.deepEqual(fit.size, { files: 1, lines: 2 });
65
+ commit(root, "src/a.ts", lines(10).replace("line 1\n", "x\n".repeat(10)));
66
+ assert.deepEqual(edit(root, "src/a.ts", { old_string: "line 2", new_string: "y" }).size, { files: 1, lines: 13 });
67
+ commit(root, "src/a.ts", lines(10).replace("line 1\n", "x\n".repeat(19)));
68
+ assert.match(edit(root, "src/a.ts", { old_string: "line 2", new_string: "y" }).problem, /changes 22 of 20 lines in 1 of 2 files/);
69
+ });
70
+
71
+ test("too many lines, too many files, or an excluded path leaves the lane", (t) => {
72
+ const root = repo(t);
73
+ assert.match(edit(root, "src/a.ts", { old_string: lines(11), new_string: lines(11) }).problem, /22 of 20 lines/);
74
+ writeFileSync(path.join(root, "src", "b.ts"), "b\n");
75
+ writeFileSync(path.join(root, "src", "c.ts"), "c\n");
76
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /in 3 of 2 files/);
77
+ rmSync(path.join(root, "src", "c.ts"));
78
+ assert.match(edit(root, "schemas/api.yaml", { old_string: "a", new_string: "b" }).problem, /schemas\/api\.yaml matches swarm\.direct\.excludes/);
79
+ });
80
+
81
+ test("an untracked file counts its lines", (t) => {
82
+ const root = repo(t);
83
+ writeFileSync(path.join(root, "src", "new.ts"), lines(19));
84
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /21 of 20 lines in 2 of 2 files/);
85
+ });
86
+
87
+ test("a protected branch, a detached head, or a missing base ref leaves the lane", (t) => {
88
+ const root = repo(t);
89
+ git(root, "switch", "-q", "main");
90
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /main is a protected branch/);
91
+ git(root, "switch", "-q", "--detach");
92
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /detached head/);
93
+ git(root, "switch", "-q", "feat/1-x");
94
+ git(root, "update-ref", "-d", "refs/remotes/origin/main");
95
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /cannot diff the branch against origin\/main/);
96
+ });
97
+
98
+ test("a small head with no review merges through the lane", (t) => {
99
+ const root = repo(t);
100
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
101
+ const fit = mergeLane({ root, base: BASE, direct: directDefaults, sha, records: [] });
102
+ assert.equal(fit.problem, null);
103
+ assert.deepEqual(fit.size, { files: 1, lines: 2 });
104
+ });
105
+
106
+ test("a review that is not APPROVED, an implementer commit, or a large head keeps the lane shut", (t) => {
107
+ const root = repo(t);
108
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
109
+ const changes = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha }];
110
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha, records: changes }).problem, /latest review on the branch, of .*, is CHANGES_REQUIRED/);
111
+ const stop = [{ type: "stop", role: "implementer", head: sha, branch: "feat/1-x" }];
112
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha, records: stop }).problem, /an implementer worked on the branch/);
113
+ const big = commit(root, "src/b.ts", lines(30));
114
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: big, records: [] }).problem, /32 of 20 lines/);
115
+ assert.match(mergeLane({ root, base: "origin/none", direct: directDefaults, sha, records: [] }).problem, /merge base of origin\/none/);
116
+ });
117
+
118
+ test("a head that touches a review path needs one APPROVED review of either kind", (t) => {
119
+ const root = repo(t);
120
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
121
+ const direct = { ...directDefaults, reviewPaths: ["src/**"] };
122
+ assert.match(mergeLane({ root, base: BASE, direct, sha, records: [] }).problem, /src\/a\.ts matches swarm\.direct\.reviewPaths/);
123
+ const approved = [{ type: "verdict", kind: "task", verdict: "APPROVED", sha }];
124
+ assert.equal(mergeLane({ root, base: BASE, direct, sha, records: approved }).problem, null);
125
+ });
126
+
127
+ test("a commit after a review that asked for changes stays out of the lane until a review approves it", (t) => {
128
+ const root = repo(t);
129
+ const first = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
130
+ const records = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha: first }];
131
+ const second = commit(root, "src/a.ts", lines(10).replace("line 3", "line 3!"));
132
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: second, records }).problem, /CHANGES_REQUIRED/);
133
+ records.push({ type: "verdict", kind: "task", verdict: "APPROVED", sha: second });
134
+ assert.equal(mergeLane({ root, base: BASE, direct: directDefaults, sha: second, records }).problem, null);
135
+ });
136
+
137
+ test("an amend after a review that asked for changes, or after an implementer commit, stays out of the lane", (t) => {
138
+ const root = repo(t);
139
+ const first = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
140
+ const verdicts = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha: first, branch: "feat/1-x" }];
141
+ const stops = [{ type: "stop", role: "implementer", head: first, branch: "feat/1-x" }];
142
+ writeFileSync(path.join(root, "src", "a.ts"), lines(10).replace("line 3", "line 3!"));
143
+ git(root, "commit", "-q", "--amend", "-am", "amended");
144
+ const amended = git(root, "rev-parse", "HEAD");
145
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: amended, records: verdicts }).problem, /CHANGES_REQUIRED/);
146
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: amended, records: stops }).problem, /an implementer worked/);
147
+ });
148
+
149
+ test("a head that no local branch points at stays out of the lane", (t) => {
150
+ const root = repo(t);
151
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
152
+ git(root, "reset", "-q", "--hard", "HEAD~1");
153
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha, records: [] }).problem, /no local branch points at/);
154
+ });
155
+
156
+ test("a binary file, a submodule, or an untracked binary has no size the lane can judge", (t) => {
157
+ const root = repo(t);
158
+ writeFileSync(path.join(root, "src", "lib.dll"), Buffer.from([0, 1, 2, 3]));
159
+ assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /src\/lib\.dll is a binary file/);
160
+ const binary = commit(root, "src/lib.dll", Buffer.from([0, 1, 2, 3]));
161
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: binary, records: [] }).problem, /src\/lib\.dll is a binary file/);
162
+ git(root, "reset", "-q", "--hard", "HEAD~1");
163
+ git(root, "update-index", "--add", "--cacheinfo", `160000,${git(root, "rev-parse", "HEAD")},vendor/sub`);
164
+ git(root, "commit", "-q", "-m", "submodule");
165
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: git(root, "rev-parse", "HEAD"), records: [] }).problem, /vendor\/sub is a binary file, a large file, or a submodule/);
166
+ });
167
+
168
+ test("a lane that runs out of time closes", (t) => {
169
+ const root = repo(t);
170
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
171
+ assert.match(editLane({ root, base: BASE, direct: directDefaults, protectedBranches: [], rel: "src/a.ts", toolName: "Edit", input: {}, budgetMs: 0 }).problem, /budget of the lane/);
172
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha, records: [], budgetMs: 0 }).problem, /budget of the lane/);
173
+ });
174
+
175
+ test("a Write over a file counts the lines it replaces", (t) => {
176
+ const root = repo(t);
177
+ const write = editLane({ root, base: BASE, direct: directDefaults, protectedBranches: [], rel: "src/a.ts", toolName: "Write", input: { content: lines(11) } });
178
+ assert.match(write.problem, /21 of 20 lines/);
179
+ });
180
+
181
+ test("a head with no commit past the base, the head of a protected branch, or a branch an implementer was sent to stays out of the lane", (t) => {
182
+ const root = repo(t);
183
+ const fork = git(root, "rev-parse", "HEAD");
184
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha: fork, records: [] }).problem, /has no commit past origin\/main/);
185
+ const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
186
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, protectedBranches: ["feat/1-x"], sha, records: [] }).problem, /head of the protected branch feat\/1-x/);
187
+ const sent = [{ type: "dispatch", task: true, branch: "feat/1-x", head: fork }];
188
+ assert.match(mergeLane({ root, base: BASE, direct: directDefaults, sha, records: sent }).problem, /an implementer worked on the branch/);
189
+ });
190
+
191
+ test("a Write over a tracked binary has no size the lane can judge", (t) => {
192
+ const root = repo(t);
193
+ commit(root, "src/lib.dll", Buffer.from([0, 1, 2, 3]));
194
+ const write = editLane({ root, base: BASE, direct: directDefaults, protectedBranches: [], rel: "src/lib.dll", toolName: "Write", input: { content: "x" } });
195
+ assert.match(write.problem, /src\/lib\.dll is a binary file/);
196
+ });
@@ -66,7 +66,7 @@ test("a checkout with no config, or a swarm section with no dispatch key, sees n
66
66
  test("the main session's dispatch with no model is refused, and one with a model passes", (t) => {
67
67
  const ws = workspace(t);
68
68
  assert.match(reasonOf(decide(agentCall(ws.on, { prompt: "p" }), ws.tmp)) ?? "", /names no model/);
69
- assert.equal(decide(agentCall(ws.on, { prompt: "p", model: "sonnet" }), ws.tmp), null);
69
+ assert.equal(decide(agentCall(ws.on, { prompt: "p", model: "gpt-6.1-sol" }), ws.tmp), null);
70
70
  });
71
71
 
72
72
  test("a subagent's dispatch is left to its own definition", (t) => {
@@ -125,29 +125,12 @@ test("the tier guard refuses a type on the wrong family, naming the type, the mo
125
125
  assert.match(refused({ model: "opus", prompt: "p" }), /general-purpose/);
126
126
  });
127
127
 
128
- test("each allowed pair passes, including a full model id and a branch reviewer on opus", (t) => {
128
+ test("every shipped role accepts GPT 6.1 Sol without a cache note", (t) => {
129
129
  const ws = workspace(t);
130
- assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", model: "opus", prompt: "p" }), ws.tmp), null);
131
- assert.equal(
132
- decide(agentCall(ws.on, { subagent_type: "architecture:sdd-branch-reviewer", model: "opus", prompt: "p" }), ws.tmp),
133
- null,
134
- );
135
- assert.equal(
136
- decide(agentCall(ws.on, { subagent_type: "architecture:sdd-reviewer", model: "sonnet", prompt: "p" }), ws.tmp),
137
- null,
138
- );
139
- assert.equal(decide(agentCall(ws.on, { model: "haiku", prompt: "p" }), ws.tmp), null);
140
- assert.equal(
141
- decide(agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "sonnet", prompt: "p" }), ws.tmp),
142
- null,
143
- );
144
- decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
145
- const pinned = decide(
146
- agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
147
- ws.tmp,
148
- );
149
- assert.equal(pinned.hookSpecificOutput.permissionDecision, undefined);
150
- assert.match(pinned.hookSpecificOutput.additionalContext, /share no prompt cache/);
130
+ for (const subagent_type of ["architecture:sdd-planner", "architecture:sdd-branch-reviewer", "architecture:sdd-reviewer", "architecture:sdd-implementer"]) {
131
+ assert.equal(decide(agentCall(ws.on, { subagent_type, model: "gpt-6.1-sol", prompt: "p" }), ws.tmp), null, subagent_type);
132
+ }
133
+ assert.equal(decide(agentCall(ws.on, { model: "gpt-6.1-sol", prompt: "p" }), ws.tmp), null);
151
134
  });
152
135
 
153
136
  test("a repository's models override replaces one type's families and leaves the rest at default", (t) => {
@@ -3,13 +3,14 @@
3
3
  // and fork, because a rule held only in the conversation is lost to a compaction.
4
4
 
5
5
  import { fileURLToPath } from "node:url";
6
+ import { directSettingsAt } from "./direct-lane.mjs";
6
7
  import { dispatchSettingsAt, exploreSettingsAt, exploreToolLines } from "./dispatch.mjs";
7
8
 
8
9
  export const REMINDER =
9
10
  "Subagent workflow (swarm.dispatch in qc.config.json): run a plan with superpowers:subagent-driven-development. " +
10
11
  "Dispatch architecture:sdd-planner to write a plan, architecture:sdd-implementer for one task, and " +
11
12
  "architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
12
- "whole branch. The planner and the branch reviewer run on opus, the implementer and the task reviewer on sonnet. " +
13
+ "whole branch. All four roles default to gpt-6.1-sol with high reasoning effort. " +
13
14
  "Run one implementer at a time: a hook refuses a second while one runs. Name a model on any other dispatch, and " +
14
15
  "pass each brief as a file path. Name the worktree on a prompt line `Worktree: <path>`. A reviewer starts with " +
15
16
  "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`.";
@@ -22,6 +23,20 @@ const slotsLine = ({ implementerSlots }) =>
22
23
  ? ` This repository allows up to ${implementerSlots} implementers at once, each in its own worktree, so the one-at-a-time rule above does not apply. A hook refuses one over the limit.`
23
24
  : "";
24
25
 
26
+ /** One added line for the direct lane of `swarm.direct`, or "" when it is off. */
27
+ function directLine(cwd) {
28
+ let direct;
29
+ try {
30
+ direct = directSettingsAt(cwd);
31
+ } catch (error) {
32
+ return ` Direct lane is off: ${error.message}`;
33
+ }
34
+ return direct
35
+ ? ` A fix of at most ${direct.maxLines} changed lines in ${direct.maxFiles} ${direct.maxFiles === 1 ? "file" : "files"} needs no subagent: edit it in the main session on a branch, ` +
36
+ "and merge it with `--match-head-commit <sha>` and no review. The guards measure the branch against its base (swarm.direct)."
37
+ : "";
38
+ }
39
+
25
40
  /** The explore tools, or null when the section is off, names none, or does not parse. */
26
41
  function exploreToolsAt(cwd) {
27
42
  let settings;
@@ -37,14 +52,14 @@ function exploreToolsAt(cwd) {
37
52
  /** One added line naming `swarm.explore`'s tools, or "" when there are none. */
38
53
  function exploreLine(cwd) {
39
54
  const tools = exploreToolsAt(cwd);
40
- return tools ? ` The repository's own explore tools: ${tools.map((tool) => tool.name).join(", ")}.` : "";
55
+ return tools ? ` Optional explore tools: ${tools.map((tool) => tool.name).join(", ")}. Read, Grep, and shell searches remain available.` : "";
41
56
  }
42
57
 
43
58
  /** A subagent may carry no MCP tool, so its note gives each tool's command, not only its name. */
44
59
  function decideSubagentStart(cwd) {
45
60
  const tools = exploreToolsAt(cwd);
46
61
  if (!tools) return null;
47
- const lines = ["The repository's own explore tools, and how to run each:", ...exploreToolLines(tools)];
62
+ const lines = ["Optional explore tools, and how to run each. Read, Grep, and shell searches remain available:", ...exploreToolLines(tools)];
48
63
  return context("SubagentStart", lines.join("\n"));
49
64
  }
50
65
 
@@ -59,7 +74,7 @@ function decideSessionStart(call) {
59
74
  }
60
75
  const explore = exploreLine(cwd);
61
76
  if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
62
- return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${explore}`);
77
+ return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${directLine(cwd)}${explore}`);
63
78
  }
64
79
 
65
80
  /** @returns the hook output, or null when there is nothing to add for this event. */