architecture-harness 0.14.0 → 0.16.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.
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env node
2
+ // The trigger for `swarm.explore`'s read budget: PreToolUse on Read refuses a whole-file read of a
3
+ // long text file and names the repository's own tools. The same file read the same way passes on
4
+ // a second attempt, so a real need for the whole file costs one retry, never a standing exemption.
5
+
6
+ import { createHash } from "node:crypto";
7
+ import {
8
+ closeSync,
9
+ existsSync,
10
+ mkdirSync,
11
+ openSync,
12
+ readdirSync,
13
+ readSync,
14
+ realpathSync,
15
+ statSync,
16
+ unlinkSync,
17
+ writeFileSync,
18
+ } from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { globMatcher } from "../glob.mjs";
23
+ import { checkoutRootOf } from "./checkout-root.mjs";
24
+ import { exploreSettingsAt } from "./dispatch.mjs";
25
+ import { slotDirOf } from "./dispatch-slot.mjs";
26
+
27
+ const BINARY_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "pdf", "ipynb"]);
28
+ const SNIFF_BYTES = 8192;
29
+ const REFUSED_SUFFIX = ".refused";
30
+ const MAX_REFUSED = 200;
31
+
32
+ const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", ...fields } });
33
+ const deny = (reason) => output({ permissionDecision: "deny", permissionDecisionReason: reason });
34
+ const context = (text) => output({ additionalContext: text });
35
+
36
+ /** The real path of `resolved`, so two spellings of one file or folder (a `..` segment, a
37
+ * case-folded drive letter, a symlink) resolve to one, everywhere this guard compares or hashes a
38
+ * path; falls back to `resolved` itself when the real path cannot be read. */
39
+ function realOf(resolved) {
40
+ try {
41
+ return realpathSync.native(resolved);
42
+ } catch {
43
+ return resolved;
44
+ }
45
+ }
46
+
47
+ // One marker file per refused path, named by its hash, never a shared list: two Read hooks of one
48
+ // batch each create their own marker, so neither call can lose the other's write.
49
+ const markerFileOf = (dir, realAbsolute) => path.join(dir, `${createHash("sha256").update(realAbsolute).digest("hex")}${REFUSED_SUFFIX}`);
50
+
51
+ /** Records one refusal. An existing marker (a concurrent refusal of the same path) is left as is. */
52
+ function recordRefusal(dir, realAbsolute) {
53
+ try {
54
+ mkdirSync(dir, { recursive: true });
55
+ writeFileSync(markerFileOf(dir, realAbsolute), "", { flag: "wx" });
56
+ } catch (error) {
57
+ if (error.code !== "EEXIST") return; // No memory of this refusal just refuses the next read again too.
58
+ }
59
+ capMarkers(dir);
60
+ }
61
+
62
+ /** True and consumed when `realAbsolute` was refused before: a second attempt passes, a third is refused anew. */
63
+ function consumeRefusal(dir, realAbsolute) {
64
+ try {
65
+ unlinkSync(markerFileOf(dir, realAbsolute));
66
+ return true;
67
+ } catch {
68
+ return false; // ENOENT (never refused), or a race that already consumed it — either way, not refused now.
69
+ }
70
+ }
71
+
72
+ /** Keeps at most `MAX_REFUSED` markers, dropping the oldest by mtime. Ignores a concurrent unlink of the same file. */
73
+ function capMarkers(dir) {
74
+ let names;
75
+ try {
76
+ names = readdirSync(dir).filter((name) => name.endsWith(REFUSED_SUFFIX));
77
+ } catch {
78
+ return;
79
+ }
80
+ const dated = names
81
+ .map((name) => {
82
+ try {
83
+ return { name, mtimeMs: statSync(path.join(dir, name)).mtimeMs };
84
+ } catch {
85
+ return null;
86
+ }
87
+ })
88
+ .filter((entry) => entry !== null)
89
+ .sort((a, b) => a.mtimeMs - b.mtimeMs);
90
+ for (const { name } of dated.slice(0, dated.length - MAX_REFUSED)) {
91
+ try {
92
+ unlinkSync(path.join(dir, name));
93
+ } catch {
94
+ // Already gone — another call raced this same cleanup, and the cap still holds.
95
+ }
96
+ }
97
+ }
98
+
99
+ function isBinaryByExtension(file) {
100
+ const ext = path.extname(file).slice(1).toLowerCase();
101
+ return BINARY_EXTENSIONS.has(ext);
102
+ }
103
+
104
+ /** A NUL byte in the first 8 KB, cheaply, the same signal `file`-type tools use. False on a read error. */
105
+ function isBinaryByContent(file) {
106
+ let fd;
107
+ try {
108
+ fd = openSync(file, "r");
109
+ } catch {
110
+ return false;
111
+ }
112
+ try {
113
+ const buf = Buffer.alloc(SNIFF_BYTES);
114
+ const read = readSync(fd, buf, 0, buf.length, null);
115
+ return buf.subarray(0, read).includes(0);
116
+ } catch {
117
+ return false;
118
+ } finally {
119
+ closeSync(fd);
120
+ }
121
+ }
122
+
123
+ /** True once more than `maxLines` newlines are seen, reading in chunks and stopping early. False on a read error. */
124
+ function exceedsLineBudget(file, maxLines) {
125
+ let fd;
126
+ try {
127
+ fd = openSync(file, "r");
128
+ } catch {
129
+ return false;
130
+ }
131
+ try {
132
+ const buf = Buffer.alloc(64 * 1024);
133
+ let count = 0;
134
+ for (;;) {
135
+ const read = readSync(fd, buf, 0, buf.length, null);
136
+ if (read === 0) return false;
137
+ for (let i = 0; i < read; i += 1) {
138
+ if (buf[i] === 10) {
139
+ count += 1;
140
+ if (count > maxLines) return true;
141
+ }
142
+ }
143
+ }
144
+ } catch {
145
+ return false;
146
+ } finally {
147
+ closeSync(fd);
148
+ }
149
+ }
150
+
151
+ function refusalMessage(tools) {
152
+ const lines = tools.map((tool) => `- ${tool.name}: ${tool.use} (${tool.how})`);
153
+ lines.push("Read a range with offset and limit, or read the same file again to read it whole.");
154
+ return lines.join("\n");
155
+ }
156
+
157
+ /** The verdict on one Read call. @returns the hook output, or null to let the call run with no message. */
158
+ export function decide(call, tmp = os.tmpdir()) {
159
+ if (call.hook_event_name !== "PreToolUse" || call.tool_name !== "Read") return null;
160
+ const input = call.tool_input ?? {};
161
+ const filePath = input.file_path;
162
+ if (typeof filePath !== "string" || filePath === "") return null;
163
+
164
+ let settings;
165
+ try {
166
+ settings = exploreSettingsAt(call.cwd ?? process.cwd());
167
+ } catch (error) {
168
+ // A config typo must not stop every read; the session sees the error and reports it.
169
+ return context(`Explore guard is off: ${error.message}`);
170
+ }
171
+ if (!settings) return null;
172
+
173
+ const cwd = call.cwd ?? process.cwd();
174
+ const absolute = path.resolve(cwd, filePath);
175
+ if (!existsSync(absolute)) return null;
176
+ const realAbsolute = realOf(absolute);
177
+
178
+ const root = checkoutRootOf(path.dirname(realAbsolute));
179
+ // A file in no checkout, or in a checkout other than the session's own, is not this one to judge.
180
+ if (!root || root !== checkoutRootOf(realOf(cwd))) return null;
181
+ const rel = path.relative(root, realAbsolute).split(path.sep).join("/");
182
+ if (globMatcher(settings.exempt)(rel)) return null;
183
+
184
+ if (input.offset !== undefined || input.limit !== undefined) return null;
185
+ if (isBinaryByExtension(realAbsolute) || isBinaryByContent(realAbsolute)) return null;
186
+ if (!exceedsLineBudget(realAbsolute, settings.maxReadLines)) return null;
187
+
188
+ const dir = slotDirOf(call.session_id ?? "session", tmp);
189
+ if (consumeRefusal(dir, realAbsolute)) return null;
190
+
191
+ recordRefusal(dir, realAbsolute);
192
+ return deny(refusalMessage(settings.tools));
193
+ }
194
+
195
+ async function readStdin() {
196
+ let data = "";
197
+ for await (const chunk of process.stdin) data += chunk;
198
+ return data;
199
+ }
200
+
201
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
202
+ if (isEntryPoint) {
203
+ let call = null;
204
+ try {
205
+ call = JSON.parse(await readStdin());
206
+ } catch {
207
+ // Not hook input, so there is nothing to judge.
208
+ }
209
+ const result = call ? decide(call) : null;
210
+ if (result) process.stdout.write(JSON.stringify(result));
211
+ }
@@ -0,0 +1,193 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { createHash } from "node:crypto";
4
+ import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { test } from "node:test";
8
+ import { decide } from "./explore-guard.mjs";
9
+ import { slotDirOf } from "./dispatch-slot.mjs";
10
+
11
+ const TOOLS = [{ name: "slm-rerank", use: "find the files for a concept", how: 'slm-rerank -q "<question>" --stub -k 5' }];
12
+ const markerNameOf = (absolute) => `${createHash("sha256").update(absolute).digest("hex")}.refused`;
13
+
14
+ /** A checkout with `swarm.explore` on, one with no config, and a temp folder for the guard's own state. */
15
+ function workspace(t, explore = { tools: TOOLS, maxReadLines: 5 }) {
16
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-explore-")));
17
+ t.after(() => rmSync(base, { recursive: true, force: true }));
18
+ const on = path.join(base, "on");
19
+ const plain = path.join(base, "plain");
20
+ const tmp = path.join(base, "tmp");
21
+ for (const dir of [on, plain]) {
22
+ mkdirSync(dir);
23
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
24
+ }
25
+ writeFileSync(path.join(on, "qc.config.json"), JSON.stringify({ swarm: { explore } }));
26
+ return { on, plain, tmp };
27
+ }
28
+
29
+ const readCall = (cwd, file_path, extra = {}) => ({
30
+ session_id: "session-aaaa",
31
+ cwd,
32
+ hook_event_name: "PreToolUse",
33
+ tool_name: "Read",
34
+ tool_input: { file_path, ...extra },
35
+ });
36
+
37
+ const longFile = (dir, name = "long.txt", lines = 20) => {
38
+ const file = path.join(dir, name);
39
+ writeFileSync(file, Array.from({ length: lines }, (_, i) => `line ${i}`).join("\n") + "\n");
40
+ return file;
41
+ };
42
+
43
+ const reasonOf = (result) =>
44
+ result?.hookSpecificOutput?.permissionDecision === "deny" ? result.hookSpecificOutput.permissionDecisionReason : null;
45
+
46
+ test("a whole-file read of a long text file is refused, naming the tool and the retry", (t) => {
47
+ const ws = workspace(t);
48
+ const file = longFile(ws.on);
49
+ const reason = reasonOf(decide(readCall(ws.on, file), ws.tmp));
50
+ assert.match(reason, /slm-rerank: find the files for a concept \(slm-rerank -q/);
51
+ assert.match(reason, /Read a range with offset and limit, or read the same file again to read it whole\./);
52
+ });
53
+
54
+ test("the same file read the same way passes on the second attempt", (t) => {
55
+ const ws = workspace(t);
56
+ const file = longFile(ws.on);
57
+ assert.notEqual(decide(readCall(ws.on, file), ws.tmp), null);
58
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
59
+ });
60
+
61
+ test("a ranged read passes even on the first attempt", (t) => {
62
+ const ws = workspace(t);
63
+ const file = longFile(ws.on);
64
+ assert.equal(decide(readCall(ws.on, file, { offset: 1, limit: 5 }), ws.tmp), null);
65
+ });
66
+
67
+ test("an exempt path passes", (t) => {
68
+ const ws = workspace(t, { tools: TOOLS, maxReadLines: 5, exempt: ["**/long.txt"] });
69
+ const file = longFile(ws.on);
70
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
71
+ });
72
+
73
+ test("a file within the line budget passes", (t) => {
74
+ const ws = workspace(t);
75
+ const file = longFile(ws.on, "short.txt", 3);
76
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
77
+ });
78
+
79
+ test("a binary file by extension passes with no line count", (t) => {
80
+ const ws = workspace(t);
81
+ const file = path.join(ws.on, "image.png");
82
+ writeFileSync(file, Buffer.from(Array.from({ length: 20 }, (_, i) => `line ${i}\n`).join(""), "utf8"));
83
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
84
+ });
85
+
86
+ test("a binary file by a NUL byte passes even with an unlisted extension", (t) => {
87
+ const ws = workspace(t);
88
+ const file = path.join(ws.on, "data.bin");
89
+ const body = Array.from({ length: 20 }, (_, i) => `line ${i}\n`).join("");
90
+ writeFileSync(file, Buffer.concat([Buffer.from(body, "utf8"), Buffer.from([0])]));
91
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
92
+ });
93
+
94
+ test("a checkout with no swarm.explore section sees no change", (t) => {
95
+ const ws = workspace(t);
96
+ const file = longFile(ws.plain);
97
+ assert.equal(decide(readCall(ws.plain, file), ws.tmp), null);
98
+ });
99
+
100
+ test("a bad key reports the error as context instead of refusing", (t) => {
101
+ const ws = workspace(t, { maxReadLines: "many" });
102
+ const file = longFile(ws.on);
103
+ const result = decide(readCall(ws.on, file), ws.tmp);
104
+ assert.match(result.hookSpecificOutput.additionalContext, /swarm\.explore\.maxReadLines/);
105
+ });
106
+
107
+ test("a refusal leaves one marker file named by the sha256 of the absolute path, nothing else", (t) => {
108
+ const ws = workspace(t);
109
+ const file = longFile(ws.on);
110
+ assert.notEqual(decide(readCall(ws.on, file), ws.tmp), null);
111
+ const dir = slotDirOf("session-aaaa", ws.tmp);
112
+ assert.deepEqual(readdirSync(dir), [markerNameOf(file)]);
113
+ });
114
+
115
+ test("two refusals of different files each leave their own marker; consuming one leaves the other", (t) => {
116
+ const ws = workspace(t);
117
+ const fileA = longFile(ws.on, "a.txt");
118
+ const fileB = longFile(ws.on, "b.txt");
119
+ assert.notEqual(decide(readCall(ws.on, fileA), ws.tmp), null);
120
+ assert.notEqual(decide(readCall(ws.on, fileB), ws.tmp), null);
121
+ const dir = slotDirOf("session-aaaa", ws.tmp);
122
+ assert.deepEqual(new Set(readdirSync(dir)), new Set([markerNameOf(fileA), markerNameOf(fileB)]));
123
+
124
+ assert.equal(decide(readCall(ws.on, fileA), ws.tmp), null);
125
+ assert.deepEqual(readdirSync(dir), [markerNameOf(fileB)]);
126
+ });
127
+
128
+ test("the session state folder holds only marker files, never a shared list file", (t) => {
129
+ const ws = workspace(t);
130
+ const fileA = longFile(ws.on, "a.txt");
131
+ const fileB = longFile(ws.on, "b.txt");
132
+ decide(readCall(ws.on, fileA), ws.tmp);
133
+ decide(readCall(ws.on, fileB), ws.tmp);
134
+ const dir = slotDirOf("session-aaaa", ws.tmp);
135
+ for (const name of readdirSync(dir)) assert.match(name, /^[0-9a-f]{64}\.refused$/);
136
+ });
137
+
138
+ test("a third whole read after a consumed marker is refused again", (t) => {
139
+ const ws = workspace(t);
140
+ const file = longFile(ws.on);
141
+ assert.notEqual(decide(readCall(ws.on, file), ws.tmp), null); // first: refused, marker recorded
142
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null); // second: passes, marker consumed
143
+ const dir = slotDirOf("session-aaaa", ws.tmp);
144
+ assert.equal(existsSync(path.join(dir, markerNameOf(file))), false);
145
+ assert.notEqual(decide(readCall(ws.on, file), ws.tmp), null); // third: refused again
146
+ });
147
+
148
+ test("a file outside the checkout passes with no judgment", (t) => {
149
+ const ws = workspace(t);
150
+ const outside = mkdtempSync(path.join(os.tmpdir(), "qc-outside-"));
151
+ t.after(() => rmSync(outside, { recursive: true, force: true }));
152
+ const file = longFile(outside);
153
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
154
+ });
155
+
156
+ test("a respelled path is refused on the first whole read, then a respelled retry consumes the marker", (t) => {
157
+ const ws = workspace(t);
158
+ const file = longFile(ws.on);
159
+
160
+ let respelled;
161
+ if (os.platform() === "win32") {
162
+ const drive = file[0];
163
+ respelled = (drive === drive.toUpperCase() ? drive.toLowerCase() : drive.toUpperCase()) + file.slice(1);
164
+ } else {
165
+ const link = path.join(path.dirname(ws.on), "link-to-on");
166
+ try {
167
+ symlinkSync(ws.on, link, "dir");
168
+ } catch (error) {
169
+ if (error.code === "EPERM") return t.skip("no permission to create a symlink");
170
+ throw error;
171
+ }
172
+ t.after(() => rmSync(link, { force: true }));
173
+ respelled = path.join(link, path.basename(file));
174
+ }
175
+
176
+ assert.notEqual(decide(readCall(ws.on, file), ws.tmp), null); // first, as spelled: refused, marker recorded under the real path
177
+ assert.equal(decide(readCall(ws.on, respelled), ws.tmp), null); // retry, respelled: passes, marker consumed
178
+
179
+ const dir = slotDirOf("session-aaaa", ws.tmp);
180
+ assert.deepEqual(readdirSync(dir), []); // nothing left behind, real or respelled
181
+ });
182
+
183
+ test("a file in a different checkout passes even though the session's own checkout turns the guard on", (t) => {
184
+ const ws = workspace(t);
185
+ const file = longFile(ws.plain);
186
+ assert.equal(decide(readCall(ws.on, file), ws.tmp), null);
187
+ });
188
+
189
+ test("a non-Read call, or a Read with no file_path, sees no change", (t) => {
190
+ const ws = workspace(t);
191
+ assert.equal(decide({ hook_event_name: "PreToolUse", tool_name: "Edit", tool_input: {} }, ws.tmp), null);
192
+ assert.equal(decide({ hook_event_name: "PreToolUse", tool_name: "Read", tool_input: {}, cwd: ws.on }, ws.tmp), null);
193
+ });
@@ -0,0 +1,85 @@
1
+ #!/usr/bin/env node
2
+ // The trigger for `swarm.explore`'s search and output hints: PostToolUse on Grep adds context naming
3
+ // the repository's own tools when the answer runs long, and PostToolUse on Bash or PowerShell adds
4
+ // context naming the summarizer when the output runs long. Neither refuses anything; both are a
5
+ // nudge the model can take or leave.
6
+
7
+ import { fileURLToPath } from "node:url";
8
+ import { exploreSettingsAt } from "./dispatch.mjs";
9
+
10
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PostToolUse", additionalContext: text } });
11
+
12
+ /** The tool's own answer, as plain text, from whatever shape `tool_response` carries. */
13
+ function textOf(response) {
14
+ if (typeof response === "string") return response;
15
+ if (response === null || response === undefined) return "";
16
+ if (typeof response.content === "string") return response.content;
17
+ if (Array.isArray(response.content)) {
18
+ return response.content.map((block) => (typeof block?.text === "string" ? block.text : "")).join("\n");
19
+ }
20
+ if (typeof response.stdout === "string" || typeof response.stderr === "string") {
21
+ return `${response.stdout ?? ""}${response.stderr ?? ""}`;
22
+ }
23
+ if (typeof response.output === "string") return response.output;
24
+ try {
25
+ return JSON.stringify(response, null, 1);
26
+ } catch {
27
+ return "";
28
+ }
29
+ }
30
+
31
+ /** Real newlines plus escaped `\n` sequences, the way a pretty-printed fallback hides them. */
32
+ function lineCountOf(text) {
33
+ if (text === "") return 0;
34
+ const realNewlines = (text.match(/\n/g) ?? []).length;
35
+ const escapedNewlines = (text.match(/\\n/g) ?? []).length;
36
+ return realNewlines + escapedNewlines + 1;
37
+ }
38
+
39
+ const grepHint = (tools) =>
40
+ `Explore hint: this Grep answer runs long. The repository's own tools may answer faster: ` +
41
+ `${tools.map((tool) => tool.name).join(", ")}.`;
42
+
43
+ const outputHint = (summarizer) => `Explore hint: this output runs long. Pipe it through the summarizer instead: ${summarizer}`;
44
+
45
+ /** The verdict on one finished Grep, Bash, or PowerShell call. @returns the hook output, or null for no change. */
46
+ export function decide(call) {
47
+ if (call.hook_event_name !== "PostToolUse") return null;
48
+ const tool = call.tool_name;
49
+ if (tool !== "Grep" && tool !== "Bash" && tool !== "PowerShell") return null;
50
+
51
+ let settings;
52
+ try {
53
+ settings = exploreSettingsAt(call.cwd ?? process.cwd());
54
+ } catch (error) {
55
+ // A config typo must not stop every call; the session sees the error and reports it.
56
+ return context(`Explore guard is off: ${error.message}`);
57
+ }
58
+ if (!settings) return null;
59
+
60
+ const text = textOf(call.tool_response);
61
+ if (tool === "Grep") {
62
+ return lineCountOf(text) > settings.maxGrepLines ? context(grepHint(settings.tools)) : null;
63
+ }
64
+
65
+ if (settings.summarizer === null) return null;
66
+ return text.length > settings.maxOutputChars ? context(outputHint(settings.summarizer)) : null;
67
+ }
68
+
69
+ async function readStdin() {
70
+ let data = "";
71
+ for await (const chunk of process.stdin) data += chunk;
72
+ return data;
73
+ }
74
+
75
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
76
+ if (isEntryPoint) {
77
+ let call = null;
78
+ try {
79
+ call = JSON.parse(await readStdin());
80
+ } catch {
81
+ // Not hook input, so there is nothing to judge.
82
+ }
83
+ const result = call ? decide(call) : null;
84
+ if (result) process.stdout.write(JSON.stringify(result));
85
+ }
@@ -0,0 +1,134 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { decide } from "./explore-hint.mjs";
9
+
10
+ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
11
+
12
+ const TOOLS = [{ name: "slm-rerank", use: "find the files for a concept", how: 'slm-rerank -q "<question>" --stub -k 5' }];
13
+
14
+ /** A checkout with `swarm.explore` on, and one with no config. */
15
+ function workspace(t, explore = { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, summarizer: "lfm-ask" }) {
16
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-explore-hint-")));
17
+ t.after(() => rmSync(base, { recursive: true, force: true }));
18
+ const on = path.join(base, "on");
19
+ const plain = path.join(base, "plain");
20
+ for (const dir of [on, plain]) {
21
+ mkdirSync(dir);
22
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
23
+ }
24
+ writeFileSync(path.join(on, "qc.config.json"), JSON.stringify({ swarm: { explore } }));
25
+ return { on, plain };
26
+ }
27
+
28
+ const call = (cwd, tool_name, tool_response) => ({
29
+ cwd,
30
+ hook_event_name: "PostToolUse",
31
+ tool_name,
32
+ tool_input: {},
33
+ tool_response,
34
+ });
35
+
36
+ const contextOf = (result) => result?.hookSpecificOutput?.additionalContext ?? null;
37
+
38
+ const lines = (n) => Array.from({ length: n }, (_, i) => `match ${i}`).join("\n");
39
+
40
+ test("a Grep answer over maxGrepLines adds context naming the tools", (t) => {
41
+ const ws = workspace(t);
42
+ const text = contextOf(decide(call(ws.on, "Grep", lines(10))));
43
+ assert.match(text, /slm-rerank/);
44
+ });
45
+
46
+ test("a Grep answer at or under maxGrepLines sees no change", (t) => {
47
+ const ws = workspace(t);
48
+ assert.equal(decide(call(ws.on, "Grep", lines(3))), null);
49
+ });
50
+
51
+ test("a command output over maxOutputChars adds context naming the summarizer", (t) => {
52
+ const ws = workspace(t);
53
+ const text = contextOf(decide(call(ws.on, "Bash", "x".repeat(30))));
54
+ assert.match(text, /lfm-ask/);
55
+ });
56
+
57
+ test("PowerShell is judged the same way as Bash", (t) => {
58
+ const ws = workspace(t);
59
+ const text = contextOf(decide(call(ws.on, "PowerShell", "x".repeat(30))));
60
+ assert.match(text, /lfm-ask/);
61
+ });
62
+
63
+ test("a command output at or under maxOutputChars sees no change", (t) => {
64
+ const ws = workspace(t);
65
+ assert.equal(decide(call(ws.on, "Bash", "x".repeat(10))), null);
66
+ });
67
+
68
+ test("no summarizer configured means no output hint even over the limit", (t) => {
69
+ const ws = workspace(t, { tools: TOOLS, maxGrepLines: 5, maxOutputChars: 20, summarizer: null });
70
+ assert.equal(decide(call(ws.on, "Bash", "x".repeat(30))), null);
71
+ });
72
+
73
+ test("a checkout with no swarm.explore section sees no change", (t) => {
74
+ const ws = workspace(t);
75
+ assert.equal(decide(call(ws.plain, "Grep", lines(10))), null);
76
+ assert.equal(decide(call(ws.plain, "Bash", "x".repeat(30))), null);
77
+ });
78
+
79
+ test("a non-Grep, non-Bash, non-PowerShell tool, or a non-PostToolUse call, sees no change", (t) => {
80
+ const ws = workspace(t);
81
+ assert.equal(decide(call(ws.on, "Read", "x".repeat(30))), null);
82
+ assert.equal(decide({ ...call(ws.on, "Grep", lines(10)), hook_event_name: "PreToolUse" }), null);
83
+ });
84
+
85
+ test("a bad key reports the error as context instead of a hint", (t) => {
86
+ const ws = workspace(t, { maxGrepLines: "many" });
87
+ const text = contextOf(decide(call(ws.on, "Grep", lines(10))));
88
+ assert.match(text, /swarm\.explore\.maxGrepLines/);
89
+ });
90
+
91
+ test("a Grep { content } shaped answer over maxGrepLines adds context naming the tools", (t) => {
92
+ const ws = workspace(t);
93
+ const text = contextOf(decide(call(ws.on, "Grep", { content: lines(10) })));
94
+ assert.match(text, /slm-rerank/);
95
+ });
96
+
97
+ test("a Grep { matches } shaped answer over maxGrepLines adds context naming the tools", (t) => {
98
+ const ws = workspace(t);
99
+ const matches = Array.from({ length: 10 }, (_, i) => `match ${i}`);
100
+ const text = contextOf(decide(call(ws.on, "Grep", { matches })));
101
+ assert.match(text, /slm-rerank/);
102
+ });
103
+
104
+ test("a Grep answer of unknown shape counts real newlines and escaped \\n sequences", (t) => {
105
+ const ws = workspace(t);
106
+ const text = contextOf(decide(call(ws.on, "Grep", { blob: lines(10) })));
107
+ assert.match(text, /slm-rerank/);
108
+ });
109
+
110
+ test("a Bash { stdout, stderr } shaped answer over maxOutputChars adds context naming the summarizer", (t) => {
111
+ const ws = workspace(t);
112
+ const text = contextOf(decide(call(ws.on, "Bash", { stdout: "x".repeat(15), stderr: "y".repeat(15) })));
113
+ assert.match(text, /lfm-ask/);
114
+ });
115
+
116
+ test("a Bash answer of unknown shape over maxOutputChars adds context naming the summarizer", (t) => {
117
+ const ws = workspace(t);
118
+ const text = contextOf(decide(call(ws.on, "Bash", { info: "x".repeat(30) })));
119
+ assert.match(text, /lfm-ask/);
120
+ });
121
+
122
+ test("a null tool_response sees no change", (t) => {
123
+ const ws = workspace(t);
124
+ assert.equal(decide(call(ws.on, "Grep", null)), null);
125
+ assert.equal(decide(call(ws.on, "Bash", null)), null);
126
+ });
127
+
128
+ test("hooks.json runs the hint on PostToolUse Grep and Bash|PowerShell", () => {
129
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
130
+ const matchers = (hooks.PostToolUse ?? [])
131
+ .filter((entry) => entry.hooks.some((hook) => hook.command.includes("explore-hint.mjs")))
132
+ .map((entry) => entry.matcher);
133
+ assert.deepEqual(matchers.sort(), ["Bash|PowerShell", "Grep"]);
134
+ });
@@ -4,14 +4,17 @@ import path from "node:path";
4
4
  import { test } from "node:test";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { dispatchDefaults } from "../config.mjs";
7
+ import { familyOf } from "./dispatch.mjs";
7
8
  import { REMINDER } from "./dispatch-reminder.mjs";
8
9
 
9
10
  const AGENTS = fileURLToPath(new URL("../../../../agents/", import.meta.url));
10
11
  const PLUGIN = "architecture";
12
+ const READ_ONLY_TOOLS = ["Agent", "Write", "Edit", "MultiEdit", "NotebookEdit"];
11
13
  const EXPECTED = {
12
- "sdd-implementer": { effort: "medium", disallowedTools: ["Agent"] },
13
- "sdd-planner": { effort: "high", disallowedTools: ["Agent"] },
14
- "sdd-reviewer": { effort: "high", disallowedTools: ["Agent", "Write", "Edit", "MultiEdit", "NotebookEdit"] },
14
+ "sdd-implementer": { model: "sonnet", effort: "high", disallowedTools: ["Agent"] },
15
+ "sdd-planner": { model: "opus", effort: "high", disallowedTools: ["Agent"] },
16
+ "sdd-reviewer": { model: "sonnet", effort: "high", disallowedTools: READ_ONLY_TOOLS },
17
+ "sdd-branch-reviewer": { model: "opus", effort: "high", disallowedTools: READ_ONLY_TOOLS },
15
18
  };
16
19
 
17
20
  /** The `key: value` lines between the two `---` fences. A checkout on Windows can carry CRLF. */
@@ -26,7 +29,7 @@ function frontmatterOf(file) {
26
29
  );
27
30
  }
28
31
 
29
- test("each subagent type runs on opus at its effort, and none can dispatch a subagent", () => {
32
+ test("each subagent type runs on its model tier at its effort, and none can dispatch a subagent", () => {
30
33
  assert.deepEqual(
31
34
  readdirSync(AGENTS).sort(),
32
35
  Object.keys(EXPECTED).map((name) => `${name}.md`).sort(),
@@ -35,10 +38,13 @@ test("each subagent type runs on opus at its effort, and none can dispatch a sub
35
38
  for (const [name, want] of Object.entries(EXPECTED)) {
36
39
  const front = frontmatterOf(path.join(AGENTS, `${name}.md`));
37
40
  assert.equal(front.name, name);
38
- assert.equal(front.model, "opus", name);
41
+ assert.equal(front.model, want.model, name);
39
42
  assert.equal(front.effort, want.effort, name);
40
43
  assert.ok(front.description.length > 0, name);
41
44
  assert.deepEqual(front.disallowedTools.split(",").map((tool) => tool.trim()), want.disallowedTools, name);
45
+ const family = familyOf(front.model);
46
+ assert.ok(dispatchDefaults.models[name]?.includes(family), name);
47
+ assert.ok(dispatchDefaults.models[`${PLUGIN}:${name}`]?.includes(family), name);
42
48
  }
43
49
  });
44
50