architecture-harness 0.19.1 → 0.20.1
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 +67 -1
- package/src/cli/direct-lane.mjs +269 -0
- package/src/cli/direct-lane.test.mjs +289 -0
- package/src/cli/dispatch-reminder.mjs +23 -1
- package/src/cli/dispatch-reminder.test.mjs +65 -6
- package/src/cli/gh-run.mjs +2 -2
- package/src/cli/git-read.mjs +3 -3
- package/src/cli/merge-guard.mjs +72 -21
- package/src/cli/merge-guard.test.mjs +146 -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
|
+
// The checkout's `swarm.direct` only turns the lane off; `editLane` reads the limits from the base.
|
|
49
|
+
const lane = workflow.direct
|
|
50
|
+
? editLane({ root: fileRoot, base: workflow.base, 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, lane.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
|
|
|
@@ -22,9 +22,9 @@ function workspace(t, dispatchConfig = { swarm: { dispatch: {} } }) {
|
|
|
22
22
|
git(main, "config", key, value);
|
|
23
23
|
}
|
|
24
24
|
writeFileSync(path.join(main, "a.txt"), "a\n");
|
|
25
|
+
if (dispatchConfig !== null) writeFileSync(path.join(main, "qc.config.json"), JSON.stringify(dispatchConfig));
|
|
25
26
|
git(main, "add", ".");
|
|
26
27
|
git(main, "commit", "-q", "-m", "init");
|
|
27
|
-
writeFileSync(path.join(main, "qc.config.json"), JSON.stringify(dispatchConfig));
|
|
28
28
|
const linked = path.join(base, "linked");
|
|
29
29
|
git(main, "worktree", "add", "-q", "-b", "feat/1-x", linked);
|
|
30
30
|
const scratch = path.join(base, "scratch");
|
|
@@ -117,3 +117,69 @@ 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
|
+
});
|
|
164
|
+
|
|
165
|
+
test("the lane reads its limits from the base, and names a base that holds no config", (t) => {
|
|
166
|
+
const ws = laneWorkspace(t, { swarm: { dispatch: {}, direct: { maxLines: 5 } } });
|
|
167
|
+
const linked = path.join(ws.linked, "src", "a.ts");
|
|
168
|
+
writeFileSync(path.join(ws.main, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
169
|
+
const output = decide(edit(ws.main, linked, "Edit", { tool_input: { file_path: linked, ...small } }));
|
|
170
|
+
assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /the branch changes 2 of 5 lines in 1 of 2 files/);
|
|
171
|
+
writeFileSync(path.join(ws.linked, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
172
|
+
const loosened = decide(edit(ws.main, linked, "Edit", { tool_input: { file_path: linked, ...small } }));
|
|
173
|
+
assert.match(denied(loosened) ?? "", /does not apply: qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
174
|
+
const bare = laneWorkspace(t, null);
|
|
175
|
+
writeFileSync(path.join(bare.main, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
|
|
176
|
+
const closed = decide(edit(bare.main, path.join(bare.linked, "src", "a.ts"), "Edit", { tool_input: { file_path: path.join(bare.linked, "src", "a.ts"), ...small } }));
|
|
177
|
+
assert.match(denied(closed) ?? "", /does not apply: git cannot read qc\.config\.json at origin\/main/);
|
|
178
|
+
});
|
|
179
|
+
|
|
180
|
+
test("a pending edit of qc.config.json leaves the lane when the controller does not own the file", (t) => {
|
|
181
|
+
const ws = laneWorkspace(t, { swarm: { dispatch: {}, review: { controllerPaths: ["docs/**"] } } });
|
|
182
|
+
const config = path.join(ws.linked, "qc.config.json");
|
|
183
|
+
const reason = denied(decide(edit(ws.main, config, "Edit", { tool_input: { file_path: config, ...small } }))) ?? "";
|
|
184
|
+
assert.match(reason, /does not apply: qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
185
|
+
});
|
|
@@ -0,0 +1,269 @@
|
|
|
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
|
+
const OBJECT_ID = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i;
|
|
19
|
+
const PR_BASE = "the PR base";
|
|
20
|
+
const NOTE_READ_MS = 2_000;
|
|
21
|
+
// 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.
|
|
22
|
+
export const LANE_BUDGET_MS = 6_000;
|
|
23
|
+
|
|
24
|
+
const isGlobList = (value) => Array.isArray(value) && value.every((glob) => typeof glob === "string" && glob !== "");
|
|
25
|
+
const isCount = (value) => Number.isInteger(value) && value >= 1;
|
|
26
|
+
const wrong = (key, value, want) => new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
|
|
27
|
+
|
|
28
|
+
/** @returns the lane's limits, or null when `swarm.direct` is false; throws naming the key a repository got wrong. */
|
|
29
|
+
export function directSettings(swarm = {}) {
|
|
30
|
+
const raw = swarm.direct ?? {};
|
|
31
|
+
if (raw === false) return null;
|
|
32
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
33
|
+
throw new Error(`${KEY} in qc.config.json must be an object or false, got ${JSON.stringify(raw)}`);
|
|
34
|
+
}
|
|
35
|
+
const unknown = Object.keys(raw).find((key) => !DIRECT_KEYS.includes(key));
|
|
36
|
+
if (unknown !== undefined) throw new Error(`${KEY}.${unknown} in qc.config.json is not a direct lane setting; the keys are ${DIRECT_KEYS.join(", ")}`);
|
|
37
|
+
const settings = merge(directDefaults, raw);
|
|
38
|
+
for (const key of ["maxLines", "maxFiles"]) if (!isCount(settings[key])) throw wrong(key, settings[key], "a positive whole number");
|
|
39
|
+
for (const key of ["excludes", "reviewPaths"]) if (!isGlobList(settings[key])) throw wrong(key, settings[key], "a list of globs");
|
|
40
|
+
return settings;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* @returns the lane's limits for the checkout that holds `cwd`, or null when it has no config or the lane is off. The
|
|
45
|
+
* checkout's `swarm.direct` can turn the lane off. The limits are the ones at `worktree.base` when one git read gets
|
|
46
|
+
* them, as the lane judges, and the checkout's own when it does not. The read waits `readMs` at most.
|
|
47
|
+
*/
|
|
48
|
+
export function directSettingsAt(cwd, { readMs = NOTE_READ_MS } = {}) {
|
|
49
|
+
const root = checkoutRootOf(cwd);
|
|
50
|
+
if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
|
|
51
|
+
const config = load(root);
|
|
52
|
+
const local = directSettings(config.swarm);
|
|
53
|
+
if (!local) return null;
|
|
54
|
+
const text = gitOutWithin(readMs, root, "show", `${config.worktree?.base ?? "origin/main"}:${CONFIG_FILE}`);
|
|
55
|
+
if (text === null) return local;
|
|
56
|
+
try {
|
|
57
|
+
return directSettings(JSON.parse(text).swarm);
|
|
58
|
+
} catch {
|
|
59
|
+
return local;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The lines of a text as git counts them: a last line with no newline still counts. */
|
|
64
|
+
export function lineCount(text) {
|
|
65
|
+
if (typeof text !== "string" || text === "") return 0;
|
|
66
|
+
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The lines one edit adds or removes in its own text. A Write or a NotebookEdit also replaces the old text, which `editLane` adds. */
|
|
70
|
+
export function pendingLines(toolName, input = {}) {
|
|
71
|
+
if (toolName === "Edit") return lineCount(input.old_string) + lineCount(input.new_string);
|
|
72
|
+
if (toolName === "MultiEdit") return (input.edits ?? []).reduce((sum, one) => sum + lineCount(one?.old_string) + lineCount(one?.new_string), 0);
|
|
73
|
+
if (toolName === "Write") return lineCount(input.content);
|
|
74
|
+
if (toolName === "NotebookEdit") return lineCount(input.new_source);
|
|
75
|
+
return 0;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** A `gitOut` that shares one deadline, so the whole lane ends inside the hook's timeout. `late()` says it ran out. */
|
|
79
|
+
function gitBy(budgetMs) {
|
|
80
|
+
const deadline = Date.now() + budgetMs;
|
|
81
|
+
const read = (cwd, ...args) => {
|
|
82
|
+
const left = deadline - Date.now();
|
|
83
|
+
return left > 0 ? gitOutWithin(left, cwd, ...args) : null;
|
|
84
|
+
};
|
|
85
|
+
read.late = () => Date.now() >= deadline;
|
|
86
|
+
return read;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const gitFailed = (git, what) => (git.late?.() ? `git ran past the ${LANE_BUDGET_MS} ms budget of the lane` : what);
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* The limits of `swarm.direct` in `qc.config.json` at the commit `base`, read through `git`. A branch cannot loosen its own
|
|
93
|
+
* limits, so the lane never reads the checkout's file. `label` names the base in a problem.
|
|
94
|
+
* @returns `{ direct }`, or `{ problem }` naming why the lane is closed.
|
|
95
|
+
*/
|
|
96
|
+
function directAtBase(root, base, git, label = base) {
|
|
97
|
+
const text = git(root, "show", `${base}:${CONFIG_FILE}`);
|
|
98
|
+
if (text === null) return { problem: gitFailed(git, `git cannot read ${CONFIG_FILE} at ${label}`) };
|
|
99
|
+
try {
|
|
100
|
+
const config = JSON.parse(text);
|
|
101
|
+
if (config === null || typeof config !== "object" || Array.isArray(config)) return { problem: `${CONFIG_FILE} at ${label} is not a JSON object` };
|
|
102
|
+
const { swarm } = config;
|
|
103
|
+
if (swarm !== undefined && (swarm === null || typeof swarm !== "object" || Array.isArray(swarm))) {
|
|
104
|
+
return { problem: `swarm in ${CONFIG_FILE} at ${label} must be an object, got ${JSON.stringify(swarm)}` };
|
|
105
|
+
}
|
|
106
|
+
const direct = directSettings(swarm);
|
|
107
|
+
return direct ? { direct } : { problem: `${KEY} is false at ${label}` };
|
|
108
|
+
} catch (error) {
|
|
109
|
+
return { problem: error instanceof SyntaxError ? `${CONFIG_FILE} at ${label} is not JSON` : error.message };
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// The checkout also sets `worktree.base` and `swarm.isolation.protectedBranches`, so a branch that edits the file could point `base` at looser settings.
|
|
114
|
+
const touchesConfig = (changes) => [...changes.keys()].some((file) => file.toLowerCase() === CONFIG_FILE);
|
|
115
|
+
const CONFIG_PROBLEM = `${CONFIG_FILE} changes on the branch, so it runs the subagent workflow`;
|
|
116
|
+
|
|
117
|
+
function startsWithNul(file) {
|
|
118
|
+
const fd = openSync(file, "r");
|
|
119
|
+
try {
|
|
120
|
+
const buffer = Buffer.alloc(SNIFF_BYTES);
|
|
121
|
+
return buffer.subarray(0, readSync(fd, buffer, 0, SNIFF_BYTES, 0)).includes(0);
|
|
122
|
+
} finally {
|
|
123
|
+
closeSync(fd);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 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. */
|
|
128
|
+
function fileLines(root, rel) {
|
|
129
|
+
try {
|
|
130
|
+
const file = path.join(root, rel);
|
|
131
|
+
const stat = statSync(file);
|
|
132
|
+
if (!stat.isFile()) return undefined;
|
|
133
|
+
if (stat.size > MAX_TEXT_BYTES || startsWithNul(file)) return null;
|
|
134
|
+
return lineCount(readFileSync(file, "utf8"));
|
|
135
|
+
} catch {
|
|
136
|
+
return undefined;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* The changed files since the commit `fork`, each with its changed lines. With `head`, the commit's changes;
|
|
142
|
+
* without it, the working tree's, untracked files included. A binary file and a submodule have no size the lane
|
|
143
|
+
* can judge, so they map to null. The read of untracked files stops once there are more than `maxFiles`.
|
|
144
|
+
* @returns a Map from path to lines, or null when git cannot say.
|
|
145
|
+
*/
|
|
146
|
+
export function changesSince(root, fork, { head = null, maxFiles = Infinity, git = gitOut } = {}) {
|
|
147
|
+
const out = git(root, "diff", "--raw", "--numstat", "--no-renames", "-z", fork, ...(head ? [head] : []));
|
|
148
|
+
if (out === null) return null;
|
|
149
|
+
const changes = new Map();
|
|
150
|
+
const gitlinks = new Set();
|
|
151
|
+
const fields = out.split("\0");
|
|
152
|
+
for (let i = 0; i < fields.length; i++) {
|
|
153
|
+
const field = fields[i];
|
|
154
|
+
if (field === "") continue;
|
|
155
|
+
if (field.startsWith(":")) {
|
|
156
|
+
const [oldMode, newMode] = field.slice(1).split(" ");
|
|
157
|
+
if (oldMode === GITLINK_MODE || newMode === GITLINK_MODE) gitlinks.add(fields[i + 1]);
|
|
158
|
+
i++;
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
const [added, deleted, file] = field.split("\t");
|
|
162
|
+
changes.set(file, added === "-" ? null : Number(added) + Number(deleted));
|
|
163
|
+
}
|
|
164
|
+
for (const file of gitlinks) changes.set(file, null);
|
|
165
|
+
if (head) return changes;
|
|
166
|
+
const others = git(root, "ls-files", "--others", "--exclude-standard", "-z");
|
|
167
|
+
if (others === null) return null;
|
|
168
|
+
for (const file of others.split("\0").filter(Boolean)) {
|
|
169
|
+
if (changes.size > maxFiles) break;
|
|
170
|
+
if (git.late?.()) return null;
|
|
171
|
+
const lines = fileLines(root, file);
|
|
172
|
+
if (lines === undefined) return null;
|
|
173
|
+
changes.set(file, lines);
|
|
174
|
+
}
|
|
175
|
+
return changes;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
const sizeOf = (changes) => ({ files: changes.size, lines: [...changes.values()].reduce((sum, lines) => sum + (lines ?? 0), 0) });
|
|
179
|
+
|
|
180
|
+
/** One line that states the size of the branch against the limits. */
|
|
181
|
+
export const sizeLine = ({ files, lines }, direct) => `${lines} of ${direct.maxLines} lines in ${files} of ${direct.maxFiles} files`;
|
|
182
|
+
|
|
183
|
+
/** @returns why `changes` leave the lane, or null when they fit. */
|
|
184
|
+
export function sizeProblem(changes, direct) {
|
|
185
|
+
const excluded = pathMatcher(direct.excludes);
|
|
186
|
+
const hit = [...changes.keys()].find((file) => excluded(file));
|
|
187
|
+
if (hit !== undefined) return `${hit} matches ${KEY}.excludes`;
|
|
188
|
+
const opaque = [...changes.keys()].find((file) => changes.get(file) === null);
|
|
189
|
+
if (opaque !== undefined) return `${opaque} is a binary file, a large file, or a submodule, so the lane cannot judge its size`;
|
|
190
|
+
const size = sizeOf(changes);
|
|
191
|
+
if (size.files > direct.maxFiles || size.lines > direct.maxLines) return `the branch changes ${sizeLine(size, direct)}`;
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Judges one main-session edit of `rel` in the checkout at `root`. The branch diff and the pending edit together
|
|
197
|
+
* must fit the limits at `base`, on a branch that is not protected, and neither may touch `qc.config.json`.
|
|
198
|
+
* @returns `{ problem }`, or `{ problem: null, size, direct }` when it fits.
|
|
199
|
+
*/
|
|
200
|
+
export function editLane({ root, base, protectedBranches, rel, toolName, input, budgetMs = LANE_BUDGET_MS }) {
|
|
201
|
+
const git = gitBy(budgetMs);
|
|
202
|
+
const branch = git(root, "branch", "--show-current");
|
|
203
|
+
if (branch === null) return { problem: gitFailed(git, "git cannot name the checked-out branch") };
|
|
204
|
+
if (branch === "") return { problem: "the checkout has a detached head" };
|
|
205
|
+
if (protectedBranches.includes(branch)) return { problem: `${branch} is a protected branch, so start a branch for the fix` };
|
|
206
|
+
const fork = git(root, "merge-base", base, "HEAD");
|
|
207
|
+
if (!fork) return { problem: gitFailed(git, `git cannot diff the branch against ${base}`) };
|
|
208
|
+
const settings = directAtBase(root, base, git);
|
|
209
|
+
if (!settings.direct) return settings;
|
|
210
|
+
const { direct } = settings;
|
|
211
|
+
const changes = changesSince(root, fork, { maxFiles: direct.maxFiles, git });
|
|
212
|
+
if (!changes) return { problem: gitFailed(git, `git cannot diff the branch against ${base}`) };
|
|
213
|
+
const old = toolName === "Write" || toolName === "NotebookEdit" ? fileLines(root, rel) : undefined;
|
|
214
|
+
const replaced = old === undefined ? 0 : old;
|
|
215
|
+
const before = changes.has(rel) ? changes.get(rel) : 0;
|
|
216
|
+
changes.set(rel, before === null || replaced === null ? null : before + replaced + pendingLines(toolName, input));
|
|
217
|
+
if (touchesConfig(changes)) return { problem: CONFIG_PROBLEM };
|
|
218
|
+
const problem = sizeProblem(changes, direct);
|
|
219
|
+
return problem ? { problem } : { problem: null, size: sizeOf(changes), direct };
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Judges the merge of head `sha` with no review of the merge kind. A record belongs to the branch when it names
|
|
224
|
+
* a commit of the branch, or the name of a local branch at `sha`, so an amend or a rebase cannot drop it.
|
|
225
|
+
* The newest review on the branch must not ask for changes, and no implementer may have worked on it.
|
|
226
|
+
* `baseOid` is the commit the PR merges into, as GitHub names it: the lane reads the limits at that commit and
|
|
227
|
+
* measures the branch from its merge base with it, so no local ref decides. A change to `qc.config.json` closes the lane.
|
|
228
|
+
* @returns `{ problem }`, or `{ problem: null, size, direct, review }` when the merge fits. `review` is the
|
|
229
|
+
* APPROVED verdict that a path of `reviewPaths` needed, or null.
|
|
230
|
+
*/
|
|
231
|
+
export function mergeLane({ root, baseOid, protectedBranches = [], sha, records, budgetMs = LANE_BUDGET_MS }) {
|
|
232
|
+
if (typeof baseOid !== "string" || !OBJECT_ID.test(baseOid)) return { problem: "gh returned no base commit for the PR, so the lane cannot tell what the PR merges into" };
|
|
233
|
+
const git = gitBy(budgetMs);
|
|
234
|
+
if (git(root, "cat-file", "-e", `${baseOid}^{commit}`) === null) {
|
|
235
|
+
return { problem: gitFailed(git, `the PR base commit ${baseOid.slice(0, 12)} is not in this repository, so run \`git fetch\``) };
|
|
236
|
+
}
|
|
237
|
+
const fork = git(root, "merge-base", baseOid, sha);
|
|
238
|
+
if (!fork) return { problem: gitFailed(git, `git cannot find the merge base of ${PR_BASE} and ${sha}`) };
|
|
239
|
+
const settings = directAtBase(root, baseOid, git, PR_BASE);
|
|
240
|
+
if (!settings.direct) return settings;
|
|
241
|
+
const { direct } = settings;
|
|
242
|
+
const history = git(root, "rev-list", `${fork}..${sha}`);
|
|
243
|
+
const changes = history === null ? null : changesSince(root, fork, { head: sha, git });
|
|
244
|
+
if (!changes) return { problem: gitFailed(git, `git cannot diff ${sha} against ${PR_BASE}`) };
|
|
245
|
+
if (touchesConfig(changes)) return { problem: CONFIG_PROBLEM };
|
|
246
|
+
const shas = history.split(/\r?\n/).filter(Boolean);
|
|
247
|
+
if (shas.length === 0) return { problem: `${sha} has no commit past ${PR_BASE}, so the lane cannot measure what the PR merges` };
|
|
248
|
+
const branches = branchesAt(root, sha, git);
|
|
249
|
+
if (branches.length === 0) return { problem: gitFailed(git, `no local branch points at ${sha}, so the ledger cannot be tied to its branch`) };
|
|
250
|
+
const guarded = branches.find((branch) => protectedBranches.includes(branch));
|
|
251
|
+
if (guarded !== undefined) return { problem: `${sha} is the head of the protected branch ${guarded}` };
|
|
252
|
+
const ours = (record) => branches.includes(record.branch) || shas.some((one) => shaMatches(record.sha ?? record.head, one));
|
|
253
|
+
const latest = records.filter((record) => record.type === "verdict" && KINDS.includes(record.kind) && ours(record)).at(-1);
|
|
254
|
+
if (latest && latest.verdict !== "APPROVED") return { problem: `the latest review on the branch, of ${latest.sha}, is ${latest.verdict}` };
|
|
255
|
+
const committed = (record) => record.type === "stop" && record.role === "implementer" && typeof record.head === "string";
|
|
256
|
+
const dispatched = (record) => record.type === "dispatch" && record.task === true;
|
|
257
|
+
if (records.some((record) => (committed(record) || dispatched(record)) && ours(record))) {
|
|
258
|
+
return { problem: "an implementer worked on the branch, so it runs the subagent workflow" };
|
|
259
|
+
}
|
|
260
|
+
const problem = sizeProblem(changes, direct);
|
|
261
|
+
if (problem) return { problem };
|
|
262
|
+
const reviewed = pathMatcher(direct.reviewPaths);
|
|
263
|
+
const needsReview = [...changes.keys()].find((file) => reviewed(file));
|
|
264
|
+
const approval = needsReview === undefined ? null : latestVerdictFor(records, sha, KINDS);
|
|
265
|
+
if (needsReview !== undefined && approval?.verdict !== "APPROVED") {
|
|
266
|
+
return { problem: `${needsReview} matches ${KEY}.reviewPaths, so dispatch the task reviewer (sdd-reviewer) on ${sha}` };
|
|
267
|
+
}
|
|
268
|
+
return { problem: null, size: sizeOf(changes), direct, review: approval };
|
|
269
|
+
}
|
|
@@ -0,0 +1,289 @@
|
|
|
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, which holds a `qc.config.json` with `swarm`, and a branch `feat/1-x` checked out. */
|
|
15
|
+
function repo(t, swarm = { dispatch: {} }, config = JSON.stringify({ swarm })) {
|
|
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
|
+
if (config !== null) writeFileSync(path.join(root, "qc.config.json"), config);
|
|
22
|
+
writeFileSync(path.join(root, "src", "a.ts"), lines(10));
|
|
23
|
+
git(root, "add", ".");
|
|
24
|
+
git(root, "commit", "-q", "-m", "init");
|
|
25
|
+
git(root, "update-ref", "refs/remotes/origin/main", "HEAD");
|
|
26
|
+
git(root, "switch", "-q", "-c", "feat/1-x");
|
|
27
|
+
return root;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const commit = (root, file, text) => {
|
|
31
|
+
mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
|
|
32
|
+
writeFileSync(path.join(root, file), text);
|
|
33
|
+
git(root, "add", ".");
|
|
34
|
+
git(root, "commit", "-q", "-m", `change ${file}`);
|
|
35
|
+
return git(root, "rev-parse", "HEAD");
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
/** The commit `origin/main` names: the base commit a PR merges into. */
|
|
39
|
+
const oidOf = (root) => git(root, "rev-parse", BASE);
|
|
40
|
+
|
|
41
|
+
const edit = (root, rel, input) =>
|
|
42
|
+
editLane({ root, base: BASE, protectedBranches: ["main"], rel, toolName: "Edit", input });
|
|
43
|
+
|
|
44
|
+
test("the settings fill their defaults, accept false, and name a wrong key", () => {
|
|
45
|
+
assert.deepEqual(directSettings({}), directDefaults);
|
|
46
|
+
assert.equal(directSettings({ direct: false }), null);
|
|
47
|
+
assert.equal(directSettings({ direct: { maxLines: 5 } }).maxLines, 5);
|
|
48
|
+
assert.throws(() => directSettings({ direct: { maxLines: 0 } }), /swarm\.direct\.maxLines/);
|
|
49
|
+
assert.throws(() => directSettings({ direct: { excludes: "a" } }), /swarm\.direct\.excludes/);
|
|
50
|
+
assert.throws(() => directSettings({ direct: { lines: 5 } }), /swarm\.direct\.lines in qc\.config\.json is not a direct lane setting/);
|
|
51
|
+
assert.throws(() => directSettings({ direct: true }), /must be an object or false/);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
test("lines count as git counts them, and an edit counts both its old and its new text", () => {
|
|
55
|
+
assert.equal(lineCount(""), 0);
|
|
56
|
+
assert.equal(lineCount("a"), 1);
|
|
57
|
+
assert.equal(lineCount("a\nb\n"), 2);
|
|
58
|
+
assert.equal(pendingLines("Edit", { old_string: "a", new_string: "b" }), 2);
|
|
59
|
+
assert.equal(pendingLines("MultiEdit", { edits: [{ old_string: "a", new_string: "b\nc" }, { old_string: "d", new_string: "" }] }), 4);
|
|
60
|
+
assert.equal(pendingLines("Write", { content: lines(7) }), 7);
|
|
61
|
+
assert.equal(pendingLines("NotebookEdit", { new_source: "x\ny" }), 2);
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
test("a small edit on a branch fits, and the branch diff counts toward the limit", (t) => {
|
|
65
|
+
const root = repo(t);
|
|
66
|
+
const fit = edit(root, "src/a.ts", { old_string: "line 1", new_string: "line one" });
|
|
67
|
+
assert.equal(fit.problem, null);
|
|
68
|
+
assert.deepEqual(fit.size, { files: 1, lines: 2 });
|
|
69
|
+
commit(root, "src/a.ts", lines(10).replace("line 1\n", "x\n".repeat(10)));
|
|
70
|
+
assert.deepEqual(edit(root, "src/a.ts", { old_string: "line 2", new_string: "y" }).size, { files: 1, lines: 13 });
|
|
71
|
+
commit(root, "src/a.ts", lines(10).replace("line 1\n", "x\n".repeat(19)));
|
|
72
|
+
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/);
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
test("too many lines, too many files, or an excluded path leaves the lane", (t) => {
|
|
76
|
+
const root = repo(t);
|
|
77
|
+
assert.match(edit(root, "src/a.ts", { old_string: lines(11), new_string: lines(11) }).problem, /22 of 20 lines/);
|
|
78
|
+
writeFileSync(path.join(root, "src", "b.ts"), "b\n");
|
|
79
|
+
writeFileSync(path.join(root, "src", "c.ts"), "c\n");
|
|
80
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /in 3 of 2 files/);
|
|
81
|
+
rmSync(path.join(root, "src", "c.ts"));
|
|
82
|
+
assert.match(edit(root, "schemas/api.yaml", { old_string: "a", new_string: "b" }).problem, /schemas\/api\.yaml matches swarm\.direct\.excludes/);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("an untracked file counts its lines", (t) => {
|
|
86
|
+
const root = repo(t);
|
|
87
|
+
writeFileSync(path.join(root, "src", "new.ts"), lines(19));
|
|
88
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /21 of 20 lines in 2 of 2 files/);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("a protected branch, a detached head, or a missing base ref leaves the lane", (t) => {
|
|
92
|
+
const root = repo(t);
|
|
93
|
+
git(root, "switch", "-q", "main");
|
|
94
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /main is a protected branch/);
|
|
95
|
+
git(root, "switch", "-q", "--detach");
|
|
96
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /detached head/);
|
|
97
|
+
git(root, "switch", "-q", "feat/1-x");
|
|
98
|
+
git(root, "update-ref", "-d", "refs/remotes/origin/main");
|
|
99
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /cannot diff the branch against origin\/main/);
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
test("a small head with no review merges through the lane", (t) => {
|
|
103
|
+
const root = repo(t);
|
|
104
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
105
|
+
const fit = mergeLane({ root, baseOid: oidOf(root), sha, records: [] });
|
|
106
|
+
assert.equal(fit.problem, null);
|
|
107
|
+
assert.deepEqual(fit.size, { files: 1, lines: 2 });
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("a review that is not APPROVED, an implementer commit, or a large head keeps the lane shut", (t) => {
|
|
111
|
+
const root = repo(t);
|
|
112
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
113
|
+
const changes = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha }];
|
|
114
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: changes }).problem, /latest review on the branch, of .*, is CHANGES_REQUIRED/);
|
|
115
|
+
const stop = [{ type: "stop", role: "implementer", head: sha, branch: "feat/1-x" }];
|
|
116
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: stop }).problem, /an implementer worked on the branch/);
|
|
117
|
+
const big = commit(root, "src/b.ts", lines(30));
|
|
118
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: big, records: [] }).problem, /32 of 20 lines/);
|
|
119
|
+
assert.match(mergeLane({ root, baseOid: "1".repeat(40), sha, records: [] }).problem, /is not in this repository, so run `git fetch`/);
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
test("a head that touches a review path needs one APPROVED review of either kind", (t) => {
|
|
123
|
+
const root = repo(t, { dispatch: {}, direct: { reviewPaths: ["src/**"] } });
|
|
124
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
125
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /src\/a\.ts matches swarm\.direct\.reviewPaths/);
|
|
126
|
+
const approved = [{ type: "verdict", kind: "task", verdict: "APPROVED", sha }];
|
|
127
|
+
assert.equal(mergeLane({ root, baseOid: oidOf(root), sha, records: approved }).problem, null);
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
test("a commit after a review that asked for changes stays out of the lane until a review approves it", (t) => {
|
|
131
|
+
const root = repo(t);
|
|
132
|
+
const first = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
133
|
+
const records = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha: first }];
|
|
134
|
+
const second = commit(root, "src/a.ts", lines(10).replace("line 3", "line 3!"));
|
|
135
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: second, records }).problem, /CHANGES_REQUIRED/);
|
|
136
|
+
records.push({ type: "verdict", kind: "task", verdict: "APPROVED", sha: second });
|
|
137
|
+
assert.equal(mergeLane({ root, baseOid: oidOf(root), sha: second, records }).problem, null);
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
test("an amend after a review that asked for changes, or after an implementer commit, stays out of the lane", (t) => {
|
|
141
|
+
const root = repo(t);
|
|
142
|
+
const first = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
143
|
+
const verdicts = [{ type: "verdict", kind: "task", verdict: "CHANGES_REQUIRED", sha: first, branch: "feat/1-x" }];
|
|
144
|
+
const stops = [{ type: "stop", role: "implementer", head: first, branch: "feat/1-x" }];
|
|
145
|
+
writeFileSync(path.join(root, "src", "a.ts"), lines(10).replace("line 3", "line 3!"));
|
|
146
|
+
git(root, "commit", "-q", "--amend", "-am", "amended");
|
|
147
|
+
const amended = git(root, "rev-parse", "HEAD");
|
|
148
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: amended, records: verdicts }).problem, /CHANGES_REQUIRED/);
|
|
149
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: amended, records: stops }).problem, /an implementer worked/);
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
test("a head that no local branch points at stays out of the lane", (t) => {
|
|
153
|
+
const root = repo(t);
|
|
154
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
155
|
+
git(root, "reset", "-q", "--hard", "HEAD~1");
|
|
156
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /no local branch points at/);
|
|
157
|
+
});
|
|
158
|
+
|
|
159
|
+
test("a binary file, a submodule, or an untracked binary has no size the lane can judge", (t) => {
|
|
160
|
+
const root = repo(t);
|
|
161
|
+
writeFileSync(path.join(root, "src", "lib.dll"), Buffer.from([0, 1, 2, 3]));
|
|
162
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /src\/lib\.dll is a binary file/);
|
|
163
|
+
const binary = commit(root, "src/lib.dll", Buffer.from([0, 1, 2, 3]));
|
|
164
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: binary, records: [] }).problem, /src\/lib\.dll is a binary file/);
|
|
165
|
+
git(root, "reset", "-q", "--hard", "HEAD~1");
|
|
166
|
+
git(root, "update-index", "--add", "--cacheinfo", `160000,${git(root, "rev-parse", "HEAD")},vendor/sub`);
|
|
167
|
+
git(root, "commit", "-q", "-m", "submodule");
|
|
168
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: git(root, "rev-parse", "HEAD"), records: [] }).problem, /vendor\/sub is a binary file, a large file, or a submodule/);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
test("a lane that runs out of time closes", (t) => {
|
|
172
|
+
const root = repo(t);
|
|
173
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
174
|
+
assert.match(editLane({ root, base: BASE, protectedBranches: [], rel: "src/a.ts", toolName: "Edit", input: {}, budgetMs: 0 }).problem, /budget of the lane/);
|
|
175
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [], budgetMs: 0 }).problem, /budget of the lane/);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
test("a Write over a file counts the lines it replaces", (t) => {
|
|
179
|
+
const root = repo(t);
|
|
180
|
+
const write = editLane({ root, base: BASE, protectedBranches: [], rel: "src/a.ts", toolName: "Write", input: { content: lines(11) } });
|
|
181
|
+
assert.match(write.problem, /21 of 20 lines/);
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
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) => {
|
|
185
|
+
const root = repo(t);
|
|
186
|
+
const fork = git(root, "rev-parse", "HEAD");
|
|
187
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha: fork, records: [] }).problem, /has no commit past the PR base/);
|
|
188
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
189
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), protectedBranches: ["feat/1-x"], sha, records: [] }).problem, /head of the protected branch feat\/1-x/);
|
|
190
|
+
const sent = [{ type: "dispatch", task: true, branch: "feat/1-x", head: fork }];
|
|
191
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: sent }).problem, /an implementer worked on the branch/);
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
test("a Write over a tracked binary has no size the lane can judge", (t) => {
|
|
195
|
+
const root = repo(t);
|
|
196
|
+
commit(root, "src/lib.dll", Buffer.from([0, 1, 2, 3]));
|
|
197
|
+
const write = editLane({ root, base: BASE, protectedBranches: [], rel: "src/lib.dll", toolName: "Write", input: { content: "x" } });
|
|
198
|
+
assert.match(write.problem, /src\/lib\.dll is a binary file/);
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
const withDirect = (direct) => ({ dispatch: {}, direct });
|
|
202
|
+
|
|
203
|
+
test("the lane judges with the limits of the base, not the limits of the checkout", (t) => {
|
|
204
|
+
const root = repo(t, withDirect({ maxLines: 5 }));
|
|
205
|
+
const big = { old_string: "a\n".repeat(3), new_string: "b\n".repeat(3) };
|
|
206
|
+
const fit = edit(root, "src/a.ts", big);
|
|
207
|
+
assert.match(fit.problem, /changes 6 of 5 lines in 1 of 2 files/);
|
|
208
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "x\n".repeat(5)));
|
|
209
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /changes 7 of 5 lines/);
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
test("a base that sets reviewPaths holds a merge to its review, though the checkout drops the setting", (t) => {
|
|
213
|
+
const root = repo(t, withDirect({ reviewPaths: ["**"] }));
|
|
214
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
215
|
+
writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
|
|
216
|
+
const loose = mergeLane({ root, baseOid: oidOf(root), sha, records: [] });
|
|
217
|
+
assert.match(loose.problem, /src\/a\.ts matches swarm\.direct\.reviewPaths/);
|
|
218
|
+
const approved = [{ type: "verdict", kind: "task", verdict: "APPROVED", sha }];
|
|
219
|
+
const fit = mergeLane({ root, baseOid: oidOf(root), sha, records: approved });
|
|
220
|
+
assert.equal(fit.problem, null);
|
|
221
|
+
assert.equal(fit.review.kind, "task");
|
|
222
|
+
assert.equal(fit.review.sha, sha);
|
|
223
|
+
});
|
|
224
|
+
|
|
225
|
+
test("a base with no qc.config.json closes the lane", (t) => {
|
|
226
|
+
const root = repo(t, undefined, null);
|
|
227
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
228
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /git cannot read qc\.config\.json at the PR base/);
|
|
229
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /git cannot read qc\.config\.json at origin\/main/);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
test("a base config that is not JSON, or holds a wrong swarm or swarm.direct, closes the lane and names the cause", (t) => {
|
|
233
|
+
for (const [config, cause] of [
|
|
234
|
+
["{ not json", /qc\.config\.json at (?:origin\/main|the PR base) is not JSON/],
|
|
235
|
+
["null", /qc\.config\.json at (?:origin\/main|the PR base) is not a JSON object/],
|
|
236
|
+
[JSON.stringify({ swarm: null }), /swarm in qc\.config\.json at (?:origin\/main|the PR base) must be an object, got null/],
|
|
237
|
+
[JSON.stringify({ swarm: [] }), /swarm in qc\.config\.json at (?:origin\/main|the PR base) must be an object, got \[\]/],
|
|
238
|
+
[JSON.stringify({ swarm: { direct: { maxLines: 0 } } }), /swarm\.direct\.maxLines in qc\.config\.json must be a positive whole number/],
|
|
239
|
+
]) {
|
|
240
|
+
const root = repo(t, undefined, config);
|
|
241
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
242
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, cause);
|
|
243
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, cause);
|
|
244
|
+
}
|
|
245
|
+
});
|
|
246
|
+
|
|
247
|
+
test("a base that sets swarm.direct to false closes the lane", (t) => {
|
|
248
|
+
const root = repo(t, withDirect(false));
|
|
249
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
250
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /swarm\.direct is false at the PR base/);
|
|
251
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /swarm\.direct is false at origin\/main/);
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
test("a branch that changes qc.config.json leaves the lane, and so does a pending edit of it", (t) => {
|
|
255
|
+
const root = repo(t);
|
|
256
|
+
const sha = commit(root, "qc.config.json", JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
257
|
+
assert.match(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, /qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
258
|
+
assert.match(edit(root, "src/a.ts", { old_string: "a", new_string: "b" }).problem, /qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
259
|
+
const clean = repo(t);
|
|
260
|
+
assert.match(edit(clean, "qc.config.json", { old_string: "{", new_string: "{ " }).problem, /qc\.config\.json changes on the branch/);
|
|
261
|
+
assert.match(editLane({ root: clean, base: BASE, protectedBranches: [], rel: "qc.config.json", toolName: "Write", input: { content: "{}" } }).problem, /qc\.config\.json changes on the branch/);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
test("a config change in a folder below the root does not close the lane", (t) => {
|
|
265
|
+
const root = repo(t);
|
|
266
|
+
const sha = commit(root, "pkg/qc.config.json", "{}\n");
|
|
267
|
+
assert.equal(mergeLane({ root, baseOid: oidOf(root), sha, records: [] }).problem, null);
|
|
268
|
+
});
|
|
269
|
+
|
|
270
|
+
test("a merge with no base commit, or a base commit the repository lacks, closes the lane", (t) => {
|
|
271
|
+
const root = repo(t);
|
|
272
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
273
|
+
assert.match(mergeLane({ root, baseOid: undefined, sha, records: [] }).problem, /no base commit/);
|
|
274
|
+
assert.match(mergeLane({ root, baseOid: "origin/main", sha, records: [] }).problem, /no base commit/);
|
|
275
|
+
assert.match(mergeLane({ root, baseOid: "1".repeat(40), sha, records: [] }).problem, /the PR base commit 111111111111 is not in this repository, so run `git fetch`/);
|
|
276
|
+
});
|
|
277
|
+
|
|
278
|
+
test("the lane measures the merge from the base commit it is given, not from a local ref", (t) => {
|
|
279
|
+
const root = repo(t, withDirect({ reviewPaths: ["**"] }));
|
|
280
|
+
git(root, "switch", "-q", "-c", "tip", BASE);
|
|
281
|
+
writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
|
|
282
|
+
git(root, "commit", "-q", "-am", "loosen");
|
|
283
|
+
git(root, "update-ref", "refs/remotes/origin/main", "HEAD");
|
|
284
|
+
const sha = commit(root, "src/a.ts", lines(10).replace("line 3", "line three"));
|
|
285
|
+
const loose = mergeLane({ root, baseOid: git(root, "rev-parse", BASE), sha, records: [] });
|
|
286
|
+
assert.equal(loose.problem, null, "the local ref is the base here");
|
|
287
|
+
const strict = mergeLane({ root, baseOid: git(root, "rev-parse", `${BASE}~1`), sha, records: [] });
|
|
288
|
+
assert.match(strict.problem, /qc\.config\.json changes on the branch/);
|
|
289
|
+
});
|
|
@@ -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,27 @@ 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>\`${reviewClause(direct.reviewPaths)} The guards measure the branch against its base (swarm.direct).`
|
|
37
|
+
: "";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The end of the merge sentence: no review, or the one APPROVED review that `swarm.direct.reviewPaths` asks for. */
|
|
41
|
+
function reviewClause(reviewPaths) {
|
|
42
|
+
if (reviewPaths.length === 0) return " and no review.";
|
|
43
|
+
if (reviewPaths.includes("**")) return ". Every direct merge needs one APPROVED review of the head (sdd-reviewer).";
|
|
44
|
+
return ". A merge needs one APPROVED review of the head (sdd-reviewer) when a changed path matches swarm.direct.reviewPaths.";
|
|
45
|
+
}
|
|
46
|
+
|
|
25
47
|
/** The explore tools, or null when the section is off, names none, or does not parse. */
|
|
26
48
|
function exploreToolsAt(cwd) {
|
|
27
49
|
let settings;
|
|
@@ -59,7 +81,7 @@ function decideSessionStart(call) {
|
|
|
59
81
|
}
|
|
60
82
|
const explore = exploreLine(cwd);
|
|
61
83
|
if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
|
|
62
|
-
return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${explore}`);
|
|
84
|
+
return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${directLine(cwd)}${explore}`);
|
|
63
85
|
}
|
|
64
86
|
|
|
65
87
|
/** @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,66 @@ 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
|
+
});
|
|
196
|
+
|
|
197
|
+
test("the direct lane note says when a merge needs a review", (t) => {
|
|
198
|
+
const [none, some, every] = checkouts(t, [
|
|
199
|
+
{ swarm: { dispatch: {} } },
|
|
200
|
+
{ swarm: { dispatch: {}, direct: { reviewPaths: ["src/**", "api/**"] } } },
|
|
201
|
+
{ swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } } },
|
|
202
|
+
]);
|
|
203
|
+
const noteOf = (dir) => decide(start(dir, "startup")).hookSpecificOutput.additionalContext;
|
|
204
|
+
assert.match(noteOf(none), /--match-head-commit <sha>` and no review\./);
|
|
205
|
+
const partial = noteOf(some);
|
|
206
|
+
assert.match(partial, /--match-head-commit <sha>`\. A merge needs one APPROVED review of the head \(sdd-reviewer\) when a changed path matches swarm\.direct\.reviewPaths\./);
|
|
207
|
+
assert.doesNotMatch(partial, /no review/);
|
|
208
|
+
const all = noteOf(every);
|
|
209
|
+
assert.match(all, /--match-head-commit <sha>`\. Every direct merge needs one APPROVED review of the head \(sdd-reviewer\)\./);
|
|
210
|
+
assert.doesNotMatch(all, /no review/);
|
|
211
|
+
});
|
|
212
|
+
|
|
213
|
+
test("the direct lane note reads the limits at worktree.base, and the checkout's when that read fails", (t) => {
|
|
214
|
+
const [dir] = checkouts(t, [{ swarm: { dispatch: {}, direct: { maxLines: 5, reviewPaths: ["**"] } } }]);
|
|
215
|
+
const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe" });
|
|
216
|
+
for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git("config", key, value);
|
|
217
|
+
git("add", ".");
|
|
218
|
+
git("commit", "-q", "-m", "init");
|
|
219
|
+
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
|
220
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
221
|
+
const noteOf = () => decide(start(dir, "startup")).hookSpecificOutput.additionalContext;
|
|
222
|
+
const text = noteOf();
|
|
223
|
+
assert.match(text, /at most 5 changed lines in 2 files needs no subagent/);
|
|
224
|
+
assert.match(text, /Every direct merge needs one APPROVED review/);
|
|
225
|
+
git("update-ref", "-d", "refs/remotes/origin/main");
|
|
226
|
+
assert.match(noteOf(), /at most 500 changed lines in 2 files needs no subagent/);
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
test("a local swarm.direct of false turns the direct lane note off, whatever the base says", (t) => {
|
|
230
|
+
const [dir] = checkouts(t, [{ swarm: { dispatch: {} } }]);
|
|
231
|
+
const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe" });
|
|
232
|
+
for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) git("config", key, value);
|
|
233
|
+
git("add", ".");
|
|
234
|
+
git("commit", "-q", "-m", "init");
|
|
235
|
+
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
|
236
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: false } }));
|
|
237
|
+
assert.doesNotMatch(decide(start(dir, "startup")).hookSpecificOutput.additionalContext, /needs no subagent/);
|
|
238
|
+
});
|
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,69 @@ 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 the PR of `merge` merges into, as gh reads it before the merge: `{ name, oid }`, or null. `oid` is null when gh names none. */
|
|
64
|
+
function prBaseOf(merge, cwd, gh, timeoutMs) {
|
|
65
|
+
const args = ["pr", "view", ...(merge.selector ? [merge.selector] : []), ...(merge.repo ? ["-R", merge.repo] : []), "--json", "baseRefName,baseRefOid"];
|
|
66
|
+
try {
|
|
67
|
+
const pr = JSON.parse(gh(args, { cwd, env: merge.env, timeoutMs }) ?? "null");
|
|
68
|
+
return typeof pr?.baseRefName === "string" ? { name: pr.baseRefName, oid: pr.baseRefOid ?? null } : null;
|
|
69
|
+
} catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* The direct lane of one workflow, as `mergeVerdict` asks it. Null while the checkout's `swarm.direct` is false; a wrong
|
|
76
|
+
* value names itself. The lane judges against the base commit that gh names for the PR, so no local ref decides.
|
|
77
|
+
* A PR into a branch other than `worktree.base` stays out of it. The merges of one call share one time budget.
|
|
78
|
+
*/
|
|
79
|
+
function laneOf(workflow, records, cwd, gh) {
|
|
80
|
+
const { direct, directProblem, base } = workflow;
|
|
81
|
+
if (!direct) return directProblem ? () => ({ problem: directProblem }) : null;
|
|
82
|
+
const deadline = Date.now() + LANE_BUDGET_MS;
|
|
83
|
+
return (merge) => {
|
|
84
|
+
const left = deadline - Date.now();
|
|
85
|
+
const pr = left > 0 ? prBaseOf(merge, cwd, gh, left) : null;
|
|
86
|
+
if (pr === null) return { problem: "gh cannot read the base branch of the PR within the time budget of the lane" };
|
|
87
|
+
if (pr.name !== base && `origin/${pr.name}` !== base) return { problem: `the PR merges into ${pr.name}, and the lane measures against ${base}` };
|
|
88
|
+
const fit = mergeLane({ root: workflow.root, baseOid: pr.oid, protectedBranches: workflow.protectedBranches, sha: merge.sha, records, budgetMs: deadline - Date.now() });
|
|
89
|
+
if (fit.problem !== null) return fit;
|
|
90
|
+
const reviewed = fit.review ? `the APPROVED ${fit.review.kind} review of ${fit.review.sha}` : "no review";
|
|
91
|
+
return { problem: null, note: `Merge guard: ${merge.sha} merges through the direct lane, with ${sizeLine(fit.size, fit.direct)} and ${reviewed}.` };
|
|
92
|
+
};
|
|
45
93
|
}
|
|
46
94
|
|
|
47
95
|
/**
|
|
@@ -158,21 +206,24 @@ export function decide(call, { gh = runGh } = {}) {
|
|
|
158
206
|
if (merges.length === 0) return null;
|
|
159
207
|
const { origin, own, other } = partition(merges, workflow.root);
|
|
160
208
|
if (event === "PreToolUse") {
|
|
161
|
-
let
|
|
209
|
+
let verdict = { refusal: null, direct: [] };
|
|
162
210
|
if (own.length > 0) {
|
|
163
211
|
try {
|
|
164
|
-
|
|
212
|
+
const records = readLedger(workflow.ledger);
|
|
213
|
+
verdict = mergeVerdict(own, records, workflow.review.merge, laneOf(workflow, records, call.cwd ?? process.cwd(), gh));
|
|
165
214
|
} catch (error) {
|
|
166
|
-
|
|
215
|
+
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
216
|
}
|
|
168
217
|
}
|
|
169
|
-
if (refusal) return deny(refusal);
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
218
|
+
if (verdict.refusal) return deny(verdict.refusal);
|
|
219
|
+
const notes = [...verdict.direct];
|
|
220
|
+
if (other.length > 0) {
|
|
221
|
+
notes.push(
|
|
222
|
+
`Merge guard passes ${[...new Set(other.map((merge) => merge.repo))].join(", ")}: it is not this checkout's repository (${origin}), ` +
|
|
223
|
+
"so its reviews are not in this ledger. The guard records nothing for it.",
|
|
224
|
+
);
|
|
225
|
+
}
|
|
226
|
+
return notes.length > 0 ? context(notes.join(" ")) : null;
|
|
176
227
|
}
|
|
177
228
|
const notes = own.map((merge) => recordMerge(merge, call, workflow, gh)).filter(Boolean);
|
|
178
229
|
return notes.length > 0 ? { systemMessage: notes.join(" ") } : null;
|
|
@@ -345,3 +345,149 @@ 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`. `tracked: false` keeps the config out of that commit. */
|
|
350
|
+
function laneRepo(t, config = { swarm: { dispatch: {} } }, { tracked = true } = {}) {
|
|
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
|
+
if (tracked) 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
|
+
if (!tracked) writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
|
|
361
|
+
git("update-ref", "refs/remotes/origin/main", "HEAD");
|
|
362
|
+
git("switch", "-q", "-c", "feat/1-x");
|
|
363
|
+
writeFileSync(path.join(dir, "a.ts"), "one\n2\n");
|
|
364
|
+
git("commit", "-q", "-am", "fix");
|
|
365
|
+
return { dir, head: git("rev-parse", "HEAD"), base: git("rev-parse", "origin/main"), ledger: path.join(dir, ".git", "qc", "ledger.jsonl") };
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/** What `gh pr view --json baseRefName,baseRefOid` answers for a PR into `main` whose base commit is `oid`. */
|
|
369
|
+
const prView = (oid, name = "main") => JSON.stringify({ baseRefName: name, baseRefOid: oid });
|
|
370
|
+
|
|
371
|
+
test("a small head with no review merges through the direct lane, with a note", (t) => {
|
|
372
|
+
const { dir, head, base } = laneRepo(t);
|
|
373
|
+
const { gh, calls } = fakeGh(prView(base));
|
|
374
|
+
const output = decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh });
|
|
375
|
+
assert.equal(denied(output), null);
|
|
376
|
+
assert.deepEqual(calls[0].args, ["pr", "view", "7", "--json", "baseRefName,baseRefOid"]);
|
|
377
|
+
assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /merges through the direct lane, with 2 of 20 lines in 1 of 2 files and no review/);
|
|
378
|
+
assert.match(denied(decide(shell(dir, "gh pr merge 7 --squash"))) ?? "", /--match-head-commit <sha>/);
|
|
379
|
+
});
|
|
380
|
+
|
|
381
|
+
test("a review that asked for changes keeps a small head out of the direct lane", (t) => {
|
|
382
|
+
const { dir, head, base, ledger } = laneRepo(t);
|
|
383
|
+
appendRecord(ledger, verdict("task", "CHANGES_REQUIRED", head));
|
|
384
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh })) ?? "";
|
|
385
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
386
|
+
assert.match(reason, /The direct lane of swarm\.direct does not apply: the latest review on the branch, of .*, is CHANGES_REQUIRED/);
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
test("with swarm.direct false, a small head needs its review as before", (t) => {
|
|
390
|
+
const { dir, head } = laneRepo(t, { swarm: { dispatch: {}, direct: false } });
|
|
391
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`))) ?? "";
|
|
392
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
393
|
+
assert.doesNotMatch(reason, /direct lane/);
|
|
394
|
+
});
|
|
395
|
+
|
|
396
|
+
test("a wrong swarm.direct closes the lane and keeps the merge guard on", (t) => {
|
|
397
|
+
const { dir, head } = laneRepo(t, { swarm: { dispatch: {}, direct: { maxLines: 0 } } });
|
|
398
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`))) ?? "";
|
|
399
|
+
assert.match(reason, /no APPROVED branch review/);
|
|
400
|
+
assert.match(reason, /does not apply: swarm.direct.maxLines/);
|
|
401
|
+
});
|
|
402
|
+
|
|
403
|
+
test("a PR into another base, or a PR whose base gh cannot read, stays out of the direct lane", (t) => {
|
|
404
|
+
const { dir, head, base } = laneRepo(t);
|
|
405
|
+
const merge = shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`);
|
|
406
|
+
assert.match(denied(decide(merge, { gh: fakeGh(prView(base, "release/2.0")).gh })) ?? "", /the PR merges into release\/2\.0, and the lane measures against origin\/main/);
|
|
407
|
+
assert.match(denied(decide(merge, { gh: fakeGh(null).gh })) ?? "", /gh cannot read the base branch of the PR/);
|
|
408
|
+
});
|
|
409
|
+
|
|
410
|
+
test("a head that a review path covers merges through the lane after an APPROVED review, and the note names that review", (t) => {
|
|
411
|
+
const { dir, head, base, ledger } = laneRepo(t, { swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } } });
|
|
412
|
+
const merge = shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`);
|
|
413
|
+
const gh = fakeGh(prView(base)).gh;
|
|
414
|
+
assert.match(denied(decide(merge, { gh })) ?? "", /a\.ts matches swarm\.direct\.reviewPaths/);
|
|
415
|
+
appendRecord(ledger, verdict("task", "APPROVED", head));
|
|
416
|
+
const output = decide(merge, { gh });
|
|
417
|
+
assert.equal(denied(output), null);
|
|
418
|
+
const note = output?.hookSpecificOutput?.additionalContext ?? "";
|
|
419
|
+
assert.match(note, new RegExp(`merges through the direct lane, with 2 of 20 lines in 1 of 2 files and the APPROVED task review of ${head}\.`));
|
|
420
|
+
assert.doesNotMatch(note, /no review/);
|
|
421
|
+
});
|
|
422
|
+
|
|
423
|
+
test("the merge guard judges with the limits of the base, so a loosened checkout does not open the lane", (t) => {
|
|
424
|
+
const { dir, head, base } = laneRepo(t, { swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } } });
|
|
425
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
|
|
426
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh })) ?? "";
|
|
427
|
+
assert.match(reason, /does not apply: a\.ts matches swarm\.direct\.reviewPaths/);
|
|
428
|
+
});
|
|
429
|
+
|
|
430
|
+
test("a head that changes qc.config.json stays out of the direct lane", (t) => {
|
|
431
|
+
const { dir, base } = laneRepo(t);
|
|
432
|
+
const git = (...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
|
|
433
|
+
git("switch", "-q", "-c", "feat/2-y", "origin/main");
|
|
434
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
435
|
+
git("commit", "-q", "-am", "loosen");
|
|
436
|
+
const merge = shell(dir, `gh pr merge 7 --squash --match-head-commit ${git("rev-parse", "HEAD")}`);
|
|
437
|
+
const reason = denied(decide(merge, { gh: fakeGh(prView(base)).gh })) ?? "";
|
|
438
|
+
assert.match(reason, /does not apply: qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
439
|
+
});
|
|
440
|
+
|
|
441
|
+
test("a base that holds no qc.config.json keeps the head out of the direct lane", (t) => {
|
|
442
|
+
const { dir, head, base } = laneRepo(t, { swarm: { dispatch: {} } }, { tracked: false });
|
|
443
|
+
const reason = denied(decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh })) ?? "";
|
|
444
|
+
assert.match(reason, /does not apply: git cannot read qc\.config\.json at the PR base/);
|
|
445
|
+
});
|
|
446
|
+
|
|
447
|
+
test("the note states the size against the limits of the base, not the checkout", (t) => {
|
|
448
|
+
const { dir, head, base } = laneRepo(t, { swarm: { dispatch: {}, direct: { maxLines: 5 } } });
|
|
449
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { maxLines: 500 } } }));
|
|
450
|
+
const output = decide(shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`), { gh: fakeGh(prView(base)).gh });
|
|
451
|
+
assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /with 2 of 5 lines in 1 of 2 files and no review/);
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
const gitIn = (dir, ...args) => execFileSync("git", args, { cwd: dir, stdio: "pipe", encoding: "utf8" }).trim();
|
|
455
|
+
const merge7 = (dir, head) => shell(dir, `gh pr merge 7 --squash --match-head-commit ${head}`);
|
|
456
|
+
|
|
457
|
+
test("a loosening commit on the local base ref, absent from the PR base commit, does not open the lane", (t) => {
|
|
458
|
+
const strict = { swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } }, worktree: { base: "main" } };
|
|
459
|
+
const { dir, base } = laneRepo(t, strict);
|
|
460
|
+
gitIn(dir, "switch", "-q", "main");
|
|
461
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} }, worktree: { base: "main" } }));
|
|
462
|
+
gitIn(dir, "commit", "-q", "-am", "loosen");
|
|
463
|
+
gitIn(dir, "switch", "-q", "-c", "fix/2-y");
|
|
464
|
+
writeFileSync(path.join(dir, "a.ts"), "one\nthree\n");
|
|
465
|
+
gitIn(dir, "commit", "-q", "-am", "one-line fix");
|
|
466
|
+
const reason = denied(decide(merge7(dir, gitIn(dir, "rev-parse", "HEAD")), { gh: fakeGh(prView(base)).gh })) ?? "";
|
|
467
|
+
assert.match(reason, /does not apply: qc\.config\.json changes on the branch, so it runs the subagent workflow/);
|
|
468
|
+
});
|
|
469
|
+
|
|
470
|
+
test("a stale local base ref does not hide the review paths that the PR base commit sets", (t) => {
|
|
471
|
+
const { dir } = laneRepo(t);
|
|
472
|
+
gitIn(dir, "switch", "-q", "-c", "newbase", "origin/main");
|
|
473
|
+
writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: { reviewPaths: ["**"] } } }));
|
|
474
|
+
gitIn(dir, "commit", "-q", "-am", "require reviews");
|
|
475
|
+
const newBase = gitIn(dir, "rev-parse", "HEAD");
|
|
476
|
+
gitIn(dir, "switch", "-q", "feat/1-x");
|
|
477
|
+
gitIn(dir, "rebase", "-q", newBase);
|
|
478
|
+
const head = gitIn(dir, "rev-parse", "HEAD");
|
|
479
|
+
const reason = denied(decide(merge7(dir, head), { gh: fakeGh(prView(newBase)).gh })) ?? "";
|
|
480
|
+
assert.match(reason, /does not apply: a\.ts matches swarm\.direct\.reviewPaths/);
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
test("a PR base commit that the local repository lacks closes the lane and says to fetch", (t) => {
|
|
484
|
+
const { dir, head } = laneRepo(t);
|
|
485
|
+
const reason = denied(decide(merge7(dir, head), { gh: fakeGh(prView("1234567890123456789012345678901234567890")).gh })) ?? "";
|
|
486
|
+
assert.match(reason, /does not apply: the PR base commit 1234567890\w* is not in this repository, so run `git fetch`/);
|
|
487
|
+
});
|
|
488
|
+
|
|
489
|
+
test("a gh answer with no base commit closes the lane", (t) => {
|
|
490
|
+
const { dir, head } = laneRepo(t);
|
|
491
|
+
const reason = denied(decide(merge7(dir, head), { gh: fakeGh(JSON.stringify({ baseRefName: "main" })).gh })) ?? "";
|
|
492
|
+
assert.match(reason, /does not apply: gh returned no base commit for the PR/);
|
|
493
|
+
});
|
|
@@ -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, whose limits come from the commit the PR merges into | `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, whose limits come from the base | `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
|