architecture-harness 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/src/cli/dispatch-guard.mjs +78 -0
- package/src/cli/dispatch-guard.test.mjs +206 -0
- package/src/cli/dispatch-reminder.mjs +73 -0
- package/src/cli/dispatch-reminder.test.mjs +131 -0
- package/src/cli/dispatch-slot.mjs +70 -0
- package/src/cli/dispatch-slot.test.mjs +80 -0
- package/src/cli/dispatch.mjs +161 -0
- package/src/cli/dispatch.test.mjs +154 -0
- package/src/cli/edit-batch-state.mjs +5 -2
- package/src/cli/explore-guard.mjs +211 -0
- package/src/cli/explore-guard.test.mjs +193 -0
- package/src/cli/explore-hint.mjs +85 -0
- package/src/cli/explore-hint.test.mjs +134 -0
- package/src/cli/plugin-agents.test.mjs +60 -0
- package/src/config.mjs +50 -0
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
// The branch that judges one Agent dispatch against `swarm.dispatch`: a named model or an allowed
|
|
2
|
+
// type, and a prompt short enough to point at a brief file. The implementer slot is dispatch-slot's.
|
|
3
|
+
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import path from "node:path";
|
|
6
|
+
import { CONFIG_FILE, MODEL_FAMILIES, dispatchDefaults, exploreDefaults, load, merge } from "../config.mjs";
|
|
7
|
+
import { checkoutRootOf } from "./checkout-root.mjs";
|
|
8
|
+
|
|
9
|
+
const KEY = "swarm.dispatch";
|
|
10
|
+
const EXPLORE_KEY = "swarm.explore";
|
|
11
|
+
const DEFAULT_TYPE = "general-purpose";
|
|
12
|
+
const FORK = "fork";
|
|
13
|
+
const WILDCARD_TYPE = "*";
|
|
14
|
+
|
|
15
|
+
const isNameList = (value) => Array.isArray(value) && value.every((name) => typeof name === "string" && name !== "");
|
|
16
|
+
const isFamilyList = (value) => Array.isArray(value) && value.length > 0 && value.every((name) => MODEL_FAMILIES.includes(name));
|
|
17
|
+
const wrong = (key, value, want) =>
|
|
18
|
+
new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
|
|
19
|
+
|
|
20
|
+
function checkModels(models) {
|
|
21
|
+
const wantFamilies = `a non-empty list of known families (${MODEL_FAMILIES.join(", ")})`;
|
|
22
|
+
if (typeof models !== "object" || models === null || Array.isArray(models)) {
|
|
23
|
+
throw wrong("models", models, "an object mapping an agent type to its model families");
|
|
24
|
+
}
|
|
25
|
+
for (const [type, families] of Object.entries(models)) {
|
|
26
|
+
if (!isFamilyList(families)) throw wrong(`models.${type}`, families, wantFamilies);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** The first family name a model string contains, lower-cased. Null when it names none the guard knows. */
|
|
31
|
+
export function familyOf(model) {
|
|
32
|
+
const lower = model.toLowerCase();
|
|
33
|
+
return MODEL_FAMILIES.find((family) => lower.includes(family)) ?? null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @returns the dispatch settings, or null when the section is absent; throws naming the key a repository got wrong. */
|
|
37
|
+
export function dispatchSettings(swarm = {}) {
|
|
38
|
+
const raw = swarm.dispatch;
|
|
39
|
+
if (raw === undefined || raw === null || raw === false) return null;
|
|
40
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
41
|
+
throw new Error(`${KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
|
|
42
|
+
}
|
|
43
|
+
const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, models } = merge(dispatchDefaults, raw);
|
|
44
|
+
if (!isNameList(allowedTypes)) throw wrong("allowedTypes", allowedTypes, "a list of agent types");
|
|
45
|
+
if (!isNameList(implementerTypes)) throw wrong("implementerTypes", implementerTypes, "a list of agent types");
|
|
46
|
+
if (!Number.isInteger(maxPromptChars) || maxPromptChars < 1) {
|
|
47
|
+
throw wrong("maxPromptChars", maxPromptChars, "a positive whole number");
|
|
48
|
+
}
|
|
49
|
+
if (typeof slotMinutes !== "number" || !(slotMinutes > 0)) throw wrong("slotMinutes", slotMinutes, "a positive number");
|
|
50
|
+
checkModels(models);
|
|
51
|
+
return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, models };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @returns the settings of the checkout that holds `cwd`, or null when it has no config or no section. */
|
|
55
|
+
export function dispatchSettingsAt(cwd) {
|
|
56
|
+
const root = checkoutRootOf(cwd);
|
|
57
|
+
if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
|
|
58
|
+
return dispatchSettings(load(root).swarm);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const isToolEntry = (entry) =>
|
|
62
|
+
isPlainRecord(entry) && ["name", "use", "how"].every((key) => typeof entry[key] === "string" && entry[key] !== "");
|
|
63
|
+
const isPlainRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
64
|
+
const wrongExplore = (key, value, want) =>
|
|
65
|
+
new Error(`${EXPLORE_KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
|
|
66
|
+
|
|
67
|
+
/** @returns the explore settings, or null when the section is absent; throws naming the key a repository got wrong. */
|
|
68
|
+
export function exploreSettings(swarm = {}) {
|
|
69
|
+
const raw = swarm.explore;
|
|
70
|
+
if (raw === undefined || raw === null || raw === false) return null;
|
|
71
|
+
if (typeof raw !== "object" || Array.isArray(raw)) {
|
|
72
|
+
throw new Error(`${EXPLORE_KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
|
|
73
|
+
}
|
|
74
|
+
const { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt } = merge(exploreDefaults, raw);
|
|
75
|
+
if (!Array.isArray(tools) || !tools.every(isToolEntry)) {
|
|
76
|
+
throw wrongExplore("tools", tools, 'a list of { "name", "use", "how" } strings');
|
|
77
|
+
}
|
|
78
|
+
if (summarizer !== null && (typeof summarizer !== "string" || summarizer === "")) {
|
|
79
|
+
throw wrongExplore("summarizer", summarizer, "a non-empty string or null");
|
|
80
|
+
}
|
|
81
|
+
for (const [key, value] of [
|
|
82
|
+
["maxReadLines", maxReadLines],
|
|
83
|
+
["maxGrepLines", maxGrepLines],
|
|
84
|
+
["maxOutputChars", maxOutputChars],
|
|
85
|
+
]) {
|
|
86
|
+
if (!Number.isInteger(value) || value < 1) throw wrongExplore(key, value, "a positive whole number");
|
|
87
|
+
}
|
|
88
|
+
if (!isNameList(exempt)) throw wrongExplore("exempt", exempt, "a list of globs");
|
|
89
|
+
return { tools, summarizer, maxReadLines, maxGrepLines, maxOutputChars, exempt };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @returns the explore settings of the checkout that holds `cwd`, or null when it has no config or no section. */
|
|
93
|
+
export function exploreSettingsAt(cwd) {
|
|
94
|
+
const root = checkoutRootOf(cwd);
|
|
95
|
+
if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
|
|
96
|
+
return exploreSettings(load(root).swarm);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** The type a dispatch names, trimmed. The Agent tool runs general-purpose when it names none. */
|
|
100
|
+
export const typeOf = (input) =>
|
|
101
|
+
typeof input.subagent_type === "string" && input.subagent_type.trim() !== "" ? input.subagent_type.trim() : DEFAULT_TYPE;
|
|
102
|
+
|
|
103
|
+
export const isImplementer = (type, settings) => settings.implementerTypes.includes(type);
|
|
104
|
+
|
|
105
|
+
function modelRefusal(type, settings) {
|
|
106
|
+
const allowed = settings.allowedTypes.join(", ");
|
|
107
|
+
if (type === FORK) {
|
|
108
|
+
return (
|
|
109
|
+
"Dispatch guard: a fork runs on the session's model whatever `model` says, so it passes only when " +
|
|
110
|
+
`\`fork\` is in ${KEY}.allowedTypes in qc.config.json. Dispatch one of: ${allowed}, or another type with a model.`
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
return (
|
|
114
|
+
`Dispatch guard: the dispatch names no model, so the ${type} agent runs on the session's model. ` +
|
|
115
|
+
`Pass \`model\` with the cheapest tier that fits the task, or dispatch one of: ${allowed}. ` +
|
|
116
|
+
`To allow another type with no model, add it to ${KEY}.allowedTypes in qc.config.json.`
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const promptRefusal = (length, max) =>
|
|
121
|
+
`Dispatch guard: the prompt has ${length} characters, over ${KEY}.maxPromptChars (${max}) in qc.config.json. ` +
|
|
122
|
+
"Write the brief to a file, and send a short prompt that names the brief and the report file.";
|
|
123
|
+
|
|
124
|
+
function tierRefusal(type, model, families) {
|
|
125
|
+
return (
|
|
126
|
+
`Dispatch guard: ${type} may run only on ${families.join(", ")}, so it refuses model "${model}". ` +
|
|
127
|
+
`Name a model of one of those families, or dispatch a type in ${KEY}.models with one that fits.`
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @returns the reason a named model breaks its type's tier, or null when it fits. */
|
|
132
|
+
function tierRefusalFor(type, model, settings) {
|
|
133
|
+
const families = settings.models[type] ?? settings.models[WILDCARD_TYPE];
|
|
134
|
+
const family = familyOf(model);
|
|
135
|
+
if (family && families.includes(family)) return null;
|
|
136
|
+
return tierRefusal(type, model, families);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** @returns the reason the dispatch breaks a rule that needs no state, or null to let it through. */
|
|
140
|
+
export function dispatchRefusal(input, settings) {
|
|
141
|
+
const type = typeOf(input);
|
|
142
|
+
const model = typeof input.model === "string" ? input.model.trim() : "";
|
|
143
|
+
const allowed = settings.allowedTypes.includes(type);
|
|
144
|
+
if (!allowed && (type === FORK || model === "")) return modelRefusal(type, settings);
|
|
145
|
+
if (model !== "" && type !== FORK) {
|
|
146
|
+
const refusal = tierRefusalFor(type, model, settings);
|
|
147
|
+
if (refusal) return refusal;
|
|
148
|
+
}
|
|
149
|
+
const length = typeof input.prompt === "string" ? input.prompt.length : 0;
|
|
150
|
+
if (length > settings.maxPromptChars) return promptRefusal(length, settings.maxPromptChars);
|
|
151
|
+
return null;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The reason a second implementer waits, with the two ways the slot frees. */
|
|
155
|
+
export function slotRefusal({ type, claimedAt, expiresAt, slotFile }) {
|
|
156
|
+
return (
|
|
157
|
+
`Dispatch guard: an implementer holds the one implementer slot of this session since ${claimedAt.toISOString()}. ` +
|
|
158
|
+
`Wait for it to stop, then dispatch ${type}. The slot frees when it stops, or at ${expiresAt.toISOString()}. ` +
|
|
159
|
+
`If no implementer runs, because its dispatch was denied after this hook, delete ${slotFile}.`
|
|
160
|
+
);
|
|
161
|
+
}
|
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
import { strict as assert } from "node:assert";
|
|
2
|
+
import { test } from "node:test";
|
|
3
|
+
import { defaults, dispatchDefaults, merge } from "../config.mjs";
|
|
4
|
+
import { dispatchRefusal, dispatchSettings, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
|
|
5
|
+
|
|
6
|
+
test("a swarm section with no dispatch key keeps the guard off", () => {
|
|
7
|
+
assert.equal(dispatchSettings({}), null);
|
|
8
|
+
assert.equal(dispatchSettings(merge(defaults, { swarm: { toolCallBudget: 5 } }).swarm), null);
|
|
9
|
+
assert.equal(dispatchSettings({ dispatch: false }), null);
|
|
10
|
+
assert.equal(dispatchSettings({ dispatch: null }), null);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
test("an empty dispatch section turns the guard on with every default", () => {
|
|
14
|
+
assert.deepEqual(dispatchSettings(merge(defaults, { swarm: { dispatch: {} } }).swarm), dispatchDefaults);
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
test("a list in the section replaces its default rather than extending it", () => {
|
|
18
|
+
const settings = dispatchSettings({ dispatch: { allowedTypes: ["Explore"] } });
|
|
19
|
+
assert.deepEqual(settings.allowedTypes, ["Explore"]);
|
|
20
|
+
assert.deepEqual(settings.implementerTypes, dispatchDefaults.implementerTypes);
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
test("a wrong value names its key", () => {
|
|
24
|
+
for (const [dispatch, key] of [
|
|
25
|
+
["on", /swarm\.dispatch in qc\.config\.json must be an object/],
|
|
26
|
+
[["Explore"], /swarm\.dispatch in qc\.config\.json must be an object/],
|
|
27
|
+
[{ allowedTypes: "Explore" }, /swarm\.dispatch\.allowedTypes/],
|
|
28
|
+
[{ implementerTypes: [""] }, /swarm\.dispatch\.implementerTypes/],
|
|
29
|
+
[{ maxPromptChars: 0 }, /swarm\.dispatch\.maxPromptChars/],
|
|
30
|
+
[{ slotMinutes: -1 }, /swarm\.dispatch\.slotMinutes/],
|
|
31
|
+
[{ models: "opus" }, /swarm\.dispatch\.models\b/],
|
|
32
|
+
[{ models: ["opus"] }, /swarm\.dispatch\.models\b/],
|
|
33
|
+
[{ models: { "sdd-planner": [] } }, /swarm\.dispatch\.models\.sdd-planner/],
|
|
34
|
+
[{ models: { "sdd-planner": ["gpt"] } }, /swarm\.dispatch\.models\.sdd-planner/],
|
|
35
|
+
]) {
|
|
36
|
+
assert.throws(() => dispatchSettings({ dispatch }), key, JSON.stringify(dispatch));
|
|
37
|
+
}
|
|
38
|
+
});
|
|
39
|
+
|
|
40
|
+
test("a repository's models merges key by key with the defaults", () => {
|
|
41
|
+
const settings = dispatchSettings({ dispatch: { models: { "architecture:sdd-planner": ["sonnet"] } } });
|
|
42
|
+
assert.deepEqual(settings.models["architecture:sdd-planner"], ["sonnet"]);
|
|
43
|
+
assert.deepEqual(settings.models["architecture:sdd-implementer"], dispatchDefaults.models["architecture:sdd-implementer"]);
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
test("familyOf finds the first known family a model string contains, lower-cased", () => {
|
|
47
|
+
assert.equal(familyOf("sonnet"), "sonnet");
|
|
48
|
+
assert.equal(familyOf("claude-sonnet-5"), "sonnet");
|
|
49
|
+
assert.equal(familyOf("opus[1m]"), "opus");
|
|
50
|
+
assert.equal(familyOf("OPUS"), "opus");
|
|
51
|
+
assert.equal(familyOf("gpt-4"), null);
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
const on = dispatchSettings({ dispatch: { maxPromptChars: 20 } });
|
|
55
|
+
|
|
56
|
+
test("a dispatch with neither a model nor an allowed type is refused, and the reason names both fixes", () => {
|
|
57
|
+
for (const input of [{ prompt: "p" }, { subagent_type: "general-purpose", prompt: "p" }, { subagent_type: "Explore", model: " " }]) {
|
|
58
|
+
const reason = dispatchRefusal(input, on) ?? "";
|
|
59
|
+
assert.match(reason, /names no model/, JSON.stringify(input));
|
|
60
|
+
assert.match(reason, /swarm\.dispatch\.allowedTypes/);
|
|
61
|
+
assert.match(reason, /architecture:sdd-implementer/);
|
|
62
|
+
}
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
test("a named model or an allowed type passes", () => {
|
|
66
|
+
assert.equal(dispatchRefusal({ subagent_type: "general-purpose", model: "sonnet", prompt: "p" }, on), null);
|
|
67
|
+
assert.equal(dispatchRefusal({ model: "haiku" }, on), null);
|
|
68
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-reviewer" }, on), null);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
test("a fork passes only as an allowed type, since it ignores the model", () => {
|
|
72
|
+
assert.match(dispatchRefusal({ subagent_type: "fork", model: "haiku" }, on) ?? "", /`fork` is in swarm\.dispatch\.allowedTypes/);
|
|
73
|
+
const withFork = dispatchSettings({ dispatch: { allowedTypes: ["fork"] } });
|
|
74
|
+
assert.equal(dispatchRefusal({ subagent_type: "fork" }, withFork), null);
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
test("a prompt over the limit is refused, and a prompt at the limit passes", () => {
|
|
78
|
+
const reason = dispatchRefusal({ model: "haiku", prompt: "x".repeat(21) }, on) ?? "";
|
|
79
|
+
assert.match(reason, /21 characters/);
|
|
80
|
+
assert.match(reason, /swarm\.dispatch\.maxPromptChars \(20\)/);
|
|
81
|
+
assert.match(reason, /Write the brief to a file/);
|
|
82
|
+
assert.equal(dispatchRefusal({ model: "haiku", prompt: "x".repeat(20) }, on), null);
|
|
83
|
+
});
|
|
84
|
+
|
|
85
|
+
test("the model rule comes before the length rule", () => {
|
|
86
|
+
assert.match(dispatchRefusal({ prompt: "x".repeat(21) }, on) ?? "", /names no model/);
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
test("a planner on sonnet is refused, and an implementer on opus is refused", () => {
|
|
90
|
+
const planner = dispatchRefusal({ subagent_type: "architecture:sdd-planner", model: "sonnet" }, on) ?? "";
|
|
91
|
+
assert.match(planner, /architecture:sdd-planner/);
|
|
92
|
+
assert.match(planner, /"sonnet"/);
|
|
93
|
+
assert.match(planner, /opus/);
|
|
94
|
+
const implementer = dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "opus" }, on) ?? "";
|
|
95
|
+
assert.match(implementer, /architecture:sdd-implementer/);
|
|
96
|
+
assert.match(implementer, /"opus"/);
|
|
97
|
+
assert.match(implementer, /sonnet/);
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
test("a general-purpose dispatch on opus is refused, naming the wildcard's families", () => {
|
|
101
|
+
const reason = dispatchRefusal({ model: "opus" }, on) ?? "";
|
|
102
|
+
assert.match(reason, /general-purpose/);
|
|
103
|
+
assert.match(reason, /sonnet, haiku/);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
test("a model string with no known family is refused", () => {
|
|
107
|
+
assert.match(dispatchRefusal({ model: "gpt-4" }, on) ?? "", /general-purpose/);
|
|
108
|
+
});
|
|
109
|
+
|
|
110
|
+
test("each allowed pair passes, including a full model id that resolves to its family", () => {
|
|
111
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-planner", model: "opus" }, on), null);
|
|
112
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-branch-reviewer", model: "opus" }, on), null);
|
|
113
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "sonnet" }, on), null);
|
|
114
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-reviewer", model: "sonnet" }, on), null);
|
|
115
|
+
assert.equal(dispatchRefusal({ model: "haiku" }, on), null);
|
|
116
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5" }, on), null);
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
test("a fork keeps its current rule and never reaches the tier check", () => {
|
|
120
|
+
assert.match(
|
|
121
|
+
dispatchRefusal({ subagent_type: "fork", model: "gpt-4" }, on) ?? "",
|
|
122
|
+
/`fork` is in swarm\.dispatch\.allowedTypes/,
|
|
123
|
+
);
|
|
124
|
+
});
|
|
125
|
+
|
|
126
|
+
test("a repository override replaces one type's families and leaves the rest at default", () => {
|
|
127
|
+
const withOverride = dispatchSettings({ dispatch: { models: { "architecture:sdd-planner": ["sonnet"] } } });
|
|
128
|
+
assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-planner", model: "sonnet" }, withOverride), null);
|
|
129
|
+
assert.match(
|
|
130
|
+
dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "opus" }, withOverride) ?? "",
|
|
131
|
+
/architecture:sdd-implementer/,
|
|
132
|
+
);
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
test("an omitted type is general-purpose, and only a listed type is an implementer", () => {
|
|
136
|
+
assert.equal(typeOf({}), "general-purpose");
|
|
137
|
+
assert.equal(typeOf({ subagent_type: "" }), "general-purpose");
|
|
138
|
+
assert.equal(typeOf({ subagent_type: " \t" }), "general-purpose");
|
|
139
|
+
assert.equal(isImplementer("architecture:sdd-implementer", on), true);
|
|
140
|
+
assert.equal(isImplementer("sdd-implementer", on), true);
|
|
141
|
+
assert.equal(isImplementer("architecture:sdd-reviewer", on), false);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test("the slot refusal names the expiry and the file that frees the slot", () => {
|
|
145
|
+
const reason = slotRefusal({
|
|
146
|
+
type: "sdd-implementer",
|
|
147
|
+
claimedAt: new Date(0),
|
|
148
|
+
expiresAt: new Date(3_600_000),
|
|
149
|
+
slotFile: "/tmp/slot.claim",
|
|
150
|
+
});
|
|
151
|
+
assert.match(reason, /holds the one implementer slot/);
|
|
152
|
+
assert.match(reason, /1970-01-01T01:00:00\.000Z/);
|
|
153
|
+
assert.match(reason, /delete \/tmp\/slot\.claim/);
|
|
154
|
+
});
|
|
@@ -5,14 +5,17 @@ import { createHash } from "node:crypto";
|
|
|
5
5
|
import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
|
|
8
|
-
const fileSafe = (id) => String(id).replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
9
8
|
const BATCH_AWARE = "batch-aware";
|
|
10
9
|
|
|
10
|
+
/** An id as a file name: each character outside letters, digits, `_`, `.` and `-` becomes `_`. */
|
|
11
|
+
export const fileSafe = (id) => String(id).replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
12
|
+
|
|
11
13
|
/** The batch folder of one agent in one session. */
|
|
12
14
|
export const batchDirOf = (sessionId, agentKey, tmp) =>
|
|
13
15
|
path.join(tmp, "architecture-kit", "edit-batch", `${fileSafe(sessionId)}-${fileSafe(agentKey)}`);
|
|
14
16
|
|
|
15
|
-
|
|
17
|
+
/** The claim file of one key in one folder. A hash names it, so a key may hold any character. */
|
|
18
|
+
export const claimFileOf = (dir, key) => path.join(dir, `${createHash("sha256").update(key).digest("hex")}.claim`);
|
|
16
19
|
|
|
17
20
|
/**
|
|
18
21
|
* Claims one path through an exclusive create, so two hooks that run at once cannot both win.
|
|
@@ -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
|
+
}
|