architecture-harness 0.19.1 → 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 +1 -1
- package/src/cli/controller-guard.mjs +16 -9
- package/src/cli/controller-guard.test.mjs +44 -0
- package/src/cli/direct-lane.mjs +209 -0
- package/src/cli/direct-lane.test.mjs +196 -0
- package/src/cli/dispatch-reminder.mjs +16 -1
- package/src/cli/dispatch-reminder.test.mjs +22 -6
- package/src/cli/gh-run.mjs +2 -2
- package/src/cli/git-read.mjs +3 -3
- package/src/cli/merge-guard.mjs +70 -21
- package/src/cli/merge-guard.test.mjs +57 -0
- package/src/cli/workflow-settings.mjs +18 -1
- package/src/config.mjs +15 -0
- package/src/glob.mjs +7 -0
- package/templates/docs/enforcement.md +2 -2
package/package.json
CHANGED
|
@@ -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
|
|
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 {
|
|
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
|
|
24
|
-
export
|
|
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
|
+
});
|
|
@@ -3,6 +3,7 @@
|
|
|
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 =
|
|
@@ -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;
|
|
@@ -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. */
|
|
@@ -33,7 +33,7 @@ test("a checkout with no config, or no dispatch section, gets no note", (t) => {
|
|
|
33
33
|
});
|
|
34
34
|
|
|
35
35
|
test("with the section on, every start adds the note, a compaction included", (t) => {
|
|
36
|
-
const [on] = checkouts(t, [{ swarm: { dispatch: {} } }]);
|
|
36
|
+
const [on] = checkouts(t, [{ swarm: { direct: false, dispatch: {} } }]);
|
|
37
37
|
for (const source of ["startup", "resume", "clear", "compact", "fork"]) {
|
|
38
38
|
const output = decide(start(on, source));
|
|
39
39
|
assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart", source);
|
|
@@ -72,8 +72,8 @@ test("with swarm.explore also on, the note names its tools", (t) => {
|
|
|
72
72
|
|
|
73
73
|
test("with swarm.explore off, or naming no tools, the note is exactly REMINDER", (t) => {
|
|
74
74
|
const [off, empty] = checkouts(t, [
|
|
75
|
-
{ swarm: { dispatch: {} } },
|
|
76
|
-
{ swarm: { dispatch: {}, explore: { tools: [] } } },
|
|
75
|
+
{ swarm: { direct: false, dispatch: {} } },
|
|
76
|
+
{ swarm: { direct: false, dispatch: {}, explore: { tools: [] } } },
|
|
77
77
|
]);
|
|
78
78
|
assert.equal(decide(start(off, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
79
79
|
assert.equal(decide(start(empty, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
@@ -109,7 +109,7 @@ test("a config error reaches the session as context", (t) => {
|
|
|
109
109
|
});
|
|
110
110
|
|
|
111
111
|
test("the hook runs as its own process and prints the note as JSON, or nothing with no config", (t) => {
|
|
112
|
-
const [on, plain] = checkouts(t, [{ swarm: { dispatch: {} } }, null]);
|
|
112
|
+
const [on, plain] = checkouts(t, [{ swarm: { direct: false, dispatch: {} } }, null]);
|
|
113
113
|
const run = (cwd) => spawnSync(process.execPath, [NOTE], { input: JSON.stringify(start(cwd, "startup")), encoding: "utf8" });
|
|
114
114
|
const noted = run(on);
|
|
115
115
|
assert.equal(noted.status, 0, noted.stderr);
|
|
@@ -141,7 +141,7 @@ test("hooks.json also runs the note on SubagentStart, all matchers, beside the e
|
|
|
141
141
|
test("a limit above 1 adds one line stating it, and a limit of 1 leaves the note as REMINDER", (t) => {
|
|
142
142
|
const [three, one] = checkouts(t, [
|
|
143
143
|
{ swarm: { dispatch: { implementerSlots: 3 } } },
|
|
144
|
-
{ swarm: { dispatch: { implementerSlots: 1 } } },
|
|
144
|
+
{ swarm: { direct: false, dispatch: { implementerSlots: 1 } } },
|
|
145
145
|
]);
|
|
146
146
|
const text = decide(start(three, "startup")).hookSpecificOutput.additionalContext;
|
|
147
147
|
assert.ok(text.startsWith(REMINDER));
|
|
@@ -173,7 +173,23 @@ test("SubagentStart gives each tool's use and command, in config order, since a
|
|
|
173
173
|
});
|
|
174
174
|
|
|
175
175
|
test("a swarm.explore section that does not parse leaves SubagentStart silent and the session note as REMINDER", (t) => {
|
|
176
|
-
const [bad] = checkouts(t, [{ swarm: { dispatch: {}, explore: { tools: "CocoIndex" } } }]);
|
|
176
|
+
const [bad] = checkouts(t, [{ swarm: { direct: false, dispatch: {}, explore: { tools: "CocoIndex" } } }]);
|
|
177
177
|
assert.equal(decide(subagentStart(bad)), null);
|
|
178
178
|
assert.equal(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
179
179
|
});
|
|
180
|
+
|
|
181
|
+
test("with the direct lane on by default, the note names its limits after REMINDER", (t) => {
|
|
182
|
+
const [lane, custom] = checkouts(t, [{ swarm: { dispatch: {} } }, { swarm: { dispatch: {}, direct: { maxLines: 5, maxFiles: 1 } } }]);
|
|
183
|
+
const text = decide(start(lane, "startup")).hookSpecificOutput.additionalContext;
|
|
184
|
+
assert.ok(text.startsWith(REMINDER));
|
|
185
|
+
assert.match(text, /at most 20 changed lines in 2 files needs no subagent/);
|
|
186
|
+
assert.match(text, /--match-head-commit <sha>/);
|
|
187
|
+
assert.match(decide(start(custom, "startup")).hookSpecificOutput.additionalContext, /at most 5 changed lines in 1 file needs/);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
test("a swarm.direct section that does not parse names the key and leaves the rest of the note", (t) => {
|
|
191
|
+
const [bad] = checkouts(t, [{ swarm: { dispatch: {}, direct: { maxLines: 0 } } }]);
|
|
192
|
+
const text = decide(start(bad, "startup")).hookSpecificOutput.additionalContext;
|
|
193
|
+
assert.ok(text.startsWith(REMINDER));
|
|
194
|
+
assert.match(text, /Direct lane is off: swarm\.direct\.maxLines/);
|
|
195
|
+
});
|
package/src/cli/gh-run.mjs
CHANGED
|
@@ -18,12 +18,12 @@ export function expandHome(env) {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
/** @returns gh's stdout on exit 0, or null when gh fails, times out, or is not installed. */
|
|
21
|
-
export function runGh(args, { cwd = process.cwd(), env = {} } = {}) {
|
|
21
|
+
export function runGh(args, { cwd = process.cwd(), env = {}, timeoutMs = GH_TIMEOUT_MS } = {}) {
|
|
22
22
|
const result = spawnSync("gh", args, {
|
|
23
23
|
cwd,
|
|
24
24
|
encoding: "utf8",
|
|
25
25
|
windowsHide: true,
|
|
26
|
-
timeout:
|
|
26
|
+
timeout: timeoutMs,
|
|
27
27
|
env: { ...process.env, ...expandHome(env) },
|
|
28
28
|
});
|
|
29
29
|
return result.status === 0 ? (result.stdout ?? "") : null;
|
package/src/cli/git-read.mjs
CHANGED
|
@@ -22,9 +22,9 @@ export const commitOf = (cwd, ref) => gitOut(cwd, "rev-parse", "--verify", "--qu
|
|
|
22
22
|
/** @returns the branch checked out at `dir`, or null on a detached head. */
|
|
23
23
|
export const branchAt = (dir) => gitOut(dir, "branch", "--show-current") || null;
|
|
24
24
|
|
|
25
|
-
/** @returns the local branches whose head is `sha`, in ref order. */
|
|
26
|
-
export const branchesAt = (cwd, sha) =>
|
|
27
|
-
(
|
|
25
|
+
/** @returns the local branches whose head is `sha`, in ref order. `read` replaces `gitOut`, for a time budget. */
|
|
26
|
+
export const branchesAt = (cwd, sha, read = gitOut) =>
|
|
27
|
+
(read(cwd, "for-each-ref", "--points-at", sha, "--format=%(refname:short)", "refs/heads") ?? "").split(/\r?\n/).filter(Boolean);
|
|
28
28
|
|
|
29
29
|
/** @returns each linked worktree of the repository at `root`, with its branch and head; the primary checkout is left out. */
|
|
30
30
|
export function linkedWorktrees(root) {
|
package/src/cli/merge-guard.mjs
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// The trigger that holds `gh pr merge` to its review. Before the call it needs `--match-head-commit` and an
|
|
3
|
-
// APPROVED review of `swarm.review.merge` for that sha
|
|
3
|
+
// APPROVED review of `swarm.review.merge` for that sha, or a head inside the direct lane of `swarm.direct`.
|
|
4
|
+
// After the call it records the merge and its issues.
|
|
4
5
|
// A merge that names another repository than the checkout's `origin` is that repository's own, so it passes.
|
|
5
6
|
// With `swarm.dispatch` off, the record is still written for the worktree check of QC-015, and nothing is judged.
|
|
6
7
|
|
|
7
8
|
import { spawnSync } from "node:child_process";
|
|
8
9
|
import { fileURLToPath } from "node:url";
|
|
9
10
|
import { PARSERS } from "./bash-command-guard.mjs";
|
|
11
|
+
import { LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
|
|
10
12
|
import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
|
|
11
13
|
import { runGh } from "./gh-run.mjs";
|
|
12
14
|
import { appendRecord, latestVerdictFor, readLedger } from "./ledger.mjs";
|
|
@@ -25,23 +27,67 @@ const REVIEWER = { branch: "the branch reviewer (sdd-branch-reviewer)", task: "t
|
|
|
25
27
|
const deny = (reason) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason } });
|
|
26
28
|
const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
|
|
27
29
|
|
|
28
|
-
/**
|
|
29
|
-
|
|
30
|
+
/**
|
|
31
|
+
* Judges each merge: an APPROVED review of `kind` on its head, or else the direct lane that `lane(merge)` decides.
|
|
32
|
+
* @returns `{ refusal }` for the first merge that may not run, or `{ refusal: null, direct }` with the lane notes.
|
|
33
|
+
*/
|
|
34
|
+
export function mergeVerdict(merges, records, kind, lane = null) {
|
|
35
|
+
const direct = [];
|
|
30
36
|
for (const merge of merges) {
|
|
31
37
|
if (!merge.sha) {
|
|
32
|
-
return `Merge guard: \`gh pr merge\` must pass \`--match-head-commit <sha>\` with the head the ${kind} review approved, so a push after the review cannot merge unreviewed. Add it
|
|
38
|
+
return { refusal: `Merge guard: \`gh pr merge\` must pass \`--match-head-commit <sha>\` with the head the ${kind} review approved, so a push after the review cannot merge unreviewed. Add it.` };
|
|
33
39
|
}
|
|
34
40
|
const verdict = latestVerdictFor(records, merge.sha, [kind]);
|
|
35
|
-
if (verdict?.verdict
|
|
36
|
-
|
|
37
|
-
|
|
41
|
+
if (verdict?.verdict === "APPROVED") continue;
|
|
42
|
+
const fit = lane ? lane(merge) : null;
|
|
43
|
+
if (fit && fit.problem === null) {
|
|
44
|
+
direct.push(fit.note);
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
const latest = verdict ? ` (the latest is ${verdict.verdict})` : "";
|
|
48
|
+
const laneNote = fit ? ` The direct lane of swarm.direct does not apply: ${fit.problem}.` : "";
|
|
49
|
+
return {
|
|
50
|
+
refusal:
|
|
38
51
|
`Merge guard: the ledger holds no APPROVED ${kind} review of ${merge.sha}${latest}. ` +
|
|
39
52
|
`Dispatch ${REVIEWER[kind]} on that head, and merge after it approves. ` +
|
|
40
|
-
"`qc ledger` lists the verdicts, and swarm.review.merge names the kind that counts."
|
|
41
|
-
|
|
42
|
-
}
|
|
53
|
+
"`qc ledger` lists the verdicts, and swarm.review.merge names the kind that counts." +
|
|
54
|
+
laneNote,
|
|
55
|
+
};
|
|
43
56
|
}
|
|
44
|
-
return null;
|
|
57
|
+
return { refusal: null, direct };
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @returns the reason the first of `merges` may not run, or null when each pins an approved head. */
|
|
61
|
+
export const mergeRefusal = (merges, records, kind, lane = null) => mergeVerdict(merges, records, kind, lane).refusal;
|
|
62
|
+
|
|
63
|
+
/** The base branch the PR of `merge` merges into, as gh reads it before the merge, or null. */
|
|
64
|
+
function prBaseOf(merge, cwd, gh, timeoutMs) {
|
|
65
|
+
const args = ["pr", "view", ...(merge.selector ? [merge.selector] : []), ...(merge.repo ? ["-R", merge.repo] : []), "--json", "baseRefName"];
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(gh(args, { cwd, env: merge.env, timeoutMs }) ?? "null")?.baseRefName ?? null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The direct lane of one workflow, as `mergeVerdict` asks it. Null while `swarm.direct` is false; a wrong value
|
|
75
|
+
* names itself. The lane measures against `worktree.base`, so a PR into another base stays out of it.
|
|
76
|
+
* The merges of one call share one time budget.
|
|
77
|
+
*/
|
|
78
|
+
function laneOf(workflow, records, cwd, gh) {
|
|
79
|
+
const { direct, directProblem, base } = workflow;
|
|
80
|
+
if (!direct) return directProblem ? () => ({ problem: directProblem }) : null;
|
|
81
|
+
const deadline = Date.now() + LANE_BUDGET_MS;
|
|
82
|
+
return (merge) => {
|
|
83
|
+
const fit = mergeLane({ root: workflow.root, base, direct, protectedBranches: workflow.protectedBranches, sha: merge.sha, records, budgetMs: deadline - Date.now() });
|
|
84
|
+
if (fit.problem !== null) return fit;
|
|
85
|
+
const left = deadline - Date.now();
|
|
86
|
+
const prBase = left > 0 ? prBaseOf(merge, cwd, gh, left) : null;
|
|
87
|
+
if (prBase === null) return { problem: "gh cannot read the base branch of the PR within the time budget of the lane" };
|
|
88
|
+
if (prBase !== base && `origin/${prBase}` !== base) return { problem: `the PR merges into ${prBase}, and the lane measures against ${base}` };
|
|
89
|
+
return { problem: null, note: `Merge guard: ${merge.sha} merges through the direct lane, with ${sizeLine(fit.size, direct)} and no review.` };
|
|
90
|
+
};
|
|
45
91
|
}
|
|
46
92
|
|
|
47
93
|
/**
|
|
@@ -158,21 +204,24 @@ export function decide(call, { gh = runGh } = {}) {
|
|
|
158
204
|
if (merges.length === 0) return null;
|
|
159
205
|
const { origin, own, other } = partition(merges, workflow.root);
|
|
160
206
|
if (event === "PreToolUse") {
|
|
161
|
-
let
|
|
207
|
+
let verdict = { refusal: null, direct: [] };
|
|
162
208
|
if (own.length > 0) {
|
|
163
209
|
try {
|
|
164
|
-
|
|
210
|
+
const records = readLedger(workflow.ledger);
|
|
211
|
+
verdict = mergeVerdict(own, records, workflow.review.merge, laneOf(workflow, records, call.cwd ?? process.cwd(), gh));
|
|
165
212
|
} catch (error) {
|
|
166
|
-
|
|
213
|
+
verdict = { refusal: `Merge guard: the ledger cannot be read (${error.message}), so no review can be checked. Fix the ledger file, and merge again.` };
|
|
167
214
|
}
|
|
168
215
|
}
|
|
169
|
-
if (refusal) return deny(refusal);
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
216
|
+
if (verdict.refusal) return deny(verdict.refusal);
|
|
217
|
+
const notes = [...verdict.direct];
|
|
218
|
+
if (other.length > 0) {
|
|
219
|
+
notes.push(
|
|
220
|
+
`Merge guard passes ${[...new Set(other.map((merge) => merge.repo))].join(", ")}: it is not this checkout's repository (${origin}), ` +
|
|
221
|
+
"so its reviews are not in this ledger. The guard records nothing for it.",
|
|
222
|
+
);
|
|
223
|
+
}
|
|
224
|
+
return notes.length > 0 ? context(notes.join(" ")) : null;
|
|
176
225
|
}
|
|
177
226
|
const notes = own.map((merge) => recordMerge(merge, call, workflow, gh)).filter(Boolean);
|
|
178
227
|
return notes.length > 0 ? { systemMessage: notes.join(" ") } : null;
|
|
@@ -345,3 +345,60 @@ test("with swarm.dispatch off, a merge whose command failed after GitHub merged
|
|
|
345
345
|
assert.equal(decide(shell(ws.off, "gh pr merge 60 --squash --delete-branch", "PostToolUseFailure"), { gh: fakeGh(MERGED).gh }), null);
|
|
346
346
|
assert.deepEqual(readLedger(ws.ledgerOf(ws.off)).map(({ type, pr }) => ({ type, pr })), [{ type: "merge", pr: 60 }]);
|
|
347
347
|
});
|
|
348
|
+
|
|
349
|
+
/** A checkout with the checks on, `origin/main` at its first commit, and a small fix on `feat/1-x`. */
|
|
350
|
+
function laneRepo(t, config = { swarm: { dispatch: {} } }) {
|
|
351
|
+
const dir = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-merge-lane-")));
|
|
352
|
+
t.after(() => rmSync(dir, { recursive: true, force: true }));
|
|
353
|
+
const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
|
|
354
|
+
git("init", "-q", "-b", "main");
|
|
355
|
+
for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git("config", key, value);
|
|
356
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
|
|
357
|
+
writeFileSync(path.join(dir, "a.ts"), "one\ntwo\n");
|
|
358
|
+
git("add", ".");
|
|
359
|
+
git("commit", "-q", "-m", "init");
|
|
360
|
+
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
|
361
|
+
git("switch", "-q", "-c", "feat/1-x");
|
|
362
|
+
writeFileSync(path.join(dir, "a.ts"), "one\n2\n");
|
|
363
|
+
git("commit", "-q", "-am", "fix");
|
|
364
|
+
return { dir, head: git("rev-parse", "HEAD"), ledger: path.join(dir, ".git", "qc", "ledger.jsonl") };
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
test("a small head with no review merges through the direct lane, with a note", (t) => {
|
|
368
|
+
const { dir, head } = laneRepo(t);
|
|
369
|
+
const { gh, calls } = fakeGh(JSON.stringify({ baseRefName: "main" }));
|
|
370
|
+
const output = decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh });
|
|
371
|
+
assert.equal(denied(output), null);
|
|
372
|
+
assert.deepEqual(calls[0].args, ["pr", "view", "7", "--json", "baseRefName"]);
|
|
373
|
+
assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /merges through the direct lane, with 2 of 20 lines in 1 of 2 files and no review/);
|
|
374
|
+
assert.match(denied(decide(shell(dir, "gh pr merge 7 --squash"))) ?? "", /--match-head-commit <sha>/);
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
test("a review that asked for changes keeps a small head out of the direct lane", (t) => {
|
|
378
|
+
const { dir, head, ledger } = laneRepo(t);
|
|
379
|
+
appendRecord(ledger, verdict("task", "CHANGES_REQUIRED", head));
|
|
380
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`))) ?? "";
|
|
381
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
382
|
+
assert.match(reason, /The direct lane of swarm\.direct does not apply: the latest review on the branch, of .*, is CHANGES_REQUIRED/);
|
|
383
|
+
});
|
|
384
|
+
|
|
385
|
+
test("with swarm.direct false, a small head needs its review as before", (t) => {
|
|
386
|
+
const { dir, head } = laneRepo(t, { swarm: { dispatch: {}, direct: false } });
|
|
387
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`))) ?? "";
|
|
388
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
389
|
+
assert.doesNotMatch(reason, /direct lane/);
|
|
390
|
+
});
|
|
391
|
+
|
|
392
|
+
test("a wrong swarm.direct closes the lane and keeps the merge guard on", (t) => {
|
|
393
|
+
const { dir, head } = laneRepo(t, { swarm: { dispatch: {}, direct: { maxLines: 0 } } });
|
|
394
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`))) ?? "";
|
|
395
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
396
|
+
assert.match(reason, /does not apply: swarm.direct.maxLines/);
|
|
397
|
+
});
|
|
398
|
+
|
|
399
|
+
test("a PR into another base, or a PR whose base gh cannot read, stays out of the direct lane", (t) => {
|
|
400
|
+
const { dir, head } = laneRepo(t);
|
|
401
|
+
const merge = shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`);
|
|
402
|
+
assert.match(denied(decide(merge, { gh: fakeGh(JSON.stringify({ baseRefName: "release/2.0" })).gh })) ?? "", /the PR merges into release\/2\.0, and the lane measures against origin\/main/);
|
|
403
|
+
assert.match(denied(decide(merge, { gh: fakeGh(null).gh })) ?? "", /gh cannot read the base branch of the PR/);
|
|
404
|
+
});
|
|
@@ -5,6 +5,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
|
5
5
|
import path from "node:path";
|
|
6
6
|
import { CONFIG_FILE, load, merge, reviewDefaults } from "../config.mjs";
|
|
7
7
|
import { checkoutRootOf } from "./checkout-root.mjs";
|
|
8
|
+
import { directSettings } from "./direct-lane.mjs";
|
|
8
9
|
import { dispatchSettings } from "./dispatch.mjs";
|
|
9
10
|
import { fileSafe } from "./edit-batch-state.mjs";
|
|
10
11
|
import { ledgerFileOf } from "./ledger.mjs";
|
|
@@ -46,7 +47,23 @@ export function workflowAt(cwd) {
|
|
|
46
47
|
const review = reviewSettings(config.swarm);
|
|
47
48
|
const ledger = review ? ledgerFileOf(root) : null;
|
|
48
49
|
if (!review || !ledger) return null;
|
|
49
|
-
|
|
50
|
+
// A wrong `swarm.direct` closes the lane only: the guards that read this workflow keep their checks.
|
|
51
|
+
let direct = null;
|
|
52
|
+
let directProblem = null;
|
|
53
|
+
try {
|
|
54
|
+
direct = directSettings(config.swarm);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
directProblem = error.message;
|
|
57
|
+
}
|
|
58
|
+
return {
|
|
59
|
+
root,
|
|
60
|
+
ledger,
|
|
61
|
+
review,
|
|
62
|
+
direct,
|
|
63
|
+
directProblem,
|
|
64
|
+
base: config.worktree?.base ?? "origin/main",
|
|
65
|
+
protectedBranches: config.swarm.isolation?.protectedBranches ?? [],
|
|
66
|
+
};
|
|
50
67
|
}
|
|
51
68
|
|
|
52
69
|
/** The workflow folder of one session under the OS temp folder. */
|
package/src/config.mjs
CHANGED
|
@@ -249,6 +249,8 @@ export const defaults = {
|
|
|
249
249
|
dispatch: null,
|
|
250
250
|
// Read only while `dispatch` is on. `reviewDefaults` fills each key it omits.
|
|
251
251
|
review: null,
|
|
252
|
+
// Read only while `dispatch` is on, and on by default then. `false` turns it off; `directDefaults` fills each key it omits.
|
|
253
|
+
direct: null,
|
|
252
254
|
},
|
|
253
255
|
|
|
254
256
|
// Files a generator writes. The generated-file hook refuses a hand edit of one and names `command`.
|
|
@@ -551,6 +553,19 @@ export const reviewDefaults = {
|
|
|
551
553
|
plannerTypes: ["sdd-planner", "architecture:sdd-planner"],
|
|
552
554
|
};
|
|
553
555
|
|
|
556
|
+
// What each key of `swarm.direct` means when a repository omits it. A fix inside these limits skips the
|
|
557
|
+
// subagent workflow: the main session edits it and merges it with no review. A list replaces its default.
|
|
558
|
+
export const directDefaults = {
|
|
559
|
+
// The most changed lines, added plus deleted, of the branch against its merge base.
|
|
560
|
+
maxLines: 20,
|
|
561
|
+
// The most changed files of the branch against its merge base.
|
|
562
|
+
maxFiles: 2,
|
|
563
|
+
// Globs a direct fix may not touch. A change to one of these runs the subagent workflow.
|
|
564
|
+
excludes: ["schemas/**", "**/migrations/**"],
|
|
565
|
+
// Globs a direct fix may touch only with one APPROVED review of its head, of either kind.
|
|
566
|
+
reviewPaths: [],
|
|
567
|
+
};
|
|
568
|
+
|
|
554
569
|
function isPlainObject(value) {
|
|
555
570
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
556
571
|
}
|
package/src/glob.mjs
CHANGED
|
@@ -21,3 +21,10 @@ export function globMatcher(globs) {
|
|
|
21
21
|
const patterns = globs.map(globToRegExp);
|
|
22
22
|
return (rel) => patterns.some((pattern) => pattern.test(rel) || pattern.test(`/${rel}`));
|
|
23
23
|
}
|
|
24
|
+
|
|
25
|
+
/** A `globMatcher` over file paths. Windows paths ignore case, so both sides are lowercased there. */
|
|
26
|
+
export function pathMatcher(globs, platform = process.platform) {
|
|
27
|
+
if (platform !== "win32") return globMatcher(globs);
|
|
28
|
+
const matches = globMatcher(globs.map((glob) => glob.toLowerCase()));
|
|
29
|
+
return (rel) => matches(rel.toLowerCase());
|
|
30
|
+
}
|
|
@@ -67,9 +67,9 @@ recorded.
|
|
|
67
67
|
| An implementer reports the failing test before the passing one | `report-stop.mjs` |
|
|
68
68
|
| A task is reviewed before the next implementer starts on its branch | `dispatch-guard.mjs`, through `task-gate.mjs` |
|
|
69
69
|
| A fix round goes back to the implementer that wrote the task | `dispatch-guard.mjs`, through `task-gate.mjs` |
|
|
70
|
-
| A merge pins the head that an APPROVED review named | `merge-guard.mjs` |
|
|
70
|
+
| A merge pins the head that an APPROVED review named, or a head inside the direct lane | `merge-guard.mjs`, through `direct-lane.mjs` |
|
|
71
71
|
| An issue that a merge names is closed, or has a comment after the merge | `issue-gate.mjs`, on `Stop` |
|
|
72
|
-
| The controller edits only its own paths | `controller-guard.mjs` |
|
|
72
|
+
| The controller edits only its own paths, or a small fix inside the direct lane | `controller-guard.mjs`, through `direct-lane.mjs` |
|
|
73
73
|
| A plan task names its files, a test step, and a commit step, within the budget | `qc plan-check`, and `plan-stop.mjs` |
|
|
74
74
|
|
|
75
75
|
## Worktrees — QC-015
|