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.
- package/package.json +1 -1
- package/src/cli/dispatch-guard.mjs +5 -3
- package/src/cli/dispatch-guard.test.mjs +83 -0
- package/src/cli/dispatch-reminder.mjs +45 -9
- package/src/cli/dispatch-reminder.test.mjs +66 -2
- package/src/cli/dispatch-slot.mjs +151 -36
- package/src/cli/dispatch-slot.test.mjs +160 -11
- package/src/cli/dispatch.mjs +100 -8
- package/src/cli/dispatch.test.mjs +105 -1
- 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 +11 -5
- package/src/config.mjs +33 -2
package/package.json
CHANGED
|
@@ -12,13 +12,15 @@ const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse",
|
|
|
12
12
|
const deny = (reason) => output({ permissionDecision: "deny", permissionDecisionReason: reason });
|
|
13
13
|
const context = (text) => output({ additionalContext: text });
|
|
14
14
|
|
|
15
|
+
const idOf = (value) => (typeof value === "string" && value !== "" ? value : undefined);
|
|
16
|
+
|
|
15
17
|
/** Claims or frees the slot as a subagent starts or stops. It reads no config, since the agent's cwd is its own. */
|
|
16
18
|
function onSubagent(call, dir, now) {
|
|
17
19
|
// Only a claim makes the folder, so a session with the guard off gets no file here.
|
|
18
20
|
if (!existsSync(dir)) return;
|
|
19
21
|
try {
|
|
20
|
-
if (call.hook_event_name === "SubagentStart") reclaimSlot(dir, call.agent_type, now);
|
|
21
|
-
else releaseSlot(dir, call.agent_type);
|
|
22
|
+
if (call.hook_event_name === "SubagentStart") reclaimSlot(dir, call.agent_type, now, idOf(call.agent_id));
|
|
23
|
+
else releaseSlot(dir, call.agent_type, idOf(call.agent_id) ?? "", now);
|
|
22
24
|
} catch {
|
|
23
25
|
// A busy or read-only temp folder is the hook's own problem, and the slot still expires.
|
|
24
26
|
}
|
|
@@ -51,7 +53,7 @@ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
|
|
|
51
53
|
if (!isImplementer(type, settings)) return null;
|
|
52
54
|
let holder;
|
|
53
55
|
try {
|
|
54
|
-
holder = claimSlot(dir, settings, now);
|
|
56
|
+
holder = claimSlot(dir, settings, now, idOf(call.tool_use_id));
|
|
55
57
|
} catch {
|
|
56
58
|
// A busy or read-only temp folder is the hook's own problem, never a reason to refuse a dispatch.
|
|
57
59
|
return null;
|
|
@@ -117,6 +117,52 @@ test("a planner and a reviewer run beside an implementer", (t) => {
|
|
|
117
117
|
assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", prompt: "p" }), ws.tmp), null);
|
|
118
118
|
});
|
|
119
119
|
|
|
120
|
+
test("the tier guard refuses a type on the wrong family, naming the type, the model and the allowed families", (t) => {
|
|
121
|
+
const ws = workspace(t);
|
|
122
|
+
const refused = (input) => reasonOf(decide(agentCall(ws.on, input), ws.tmp)) ?? "";
|
|
123
|
+
assert.match(refused({ subagent_type: "architecture:sdd-planner", model: "sonnet", prompt: "p" }), /architecture:sdd-planner/);
|
|
124
|
+
assert.match(refused({ subagent_type: "architecture:sdd-implementer", model: "opus", prompt: "p" }), /architecture:sdd-implementer/);
|
|
125
|
+
assert.match(refused({ model: "opus", prompt: "p" }), /general-purpose/);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
test("each allowed pair passes, including a full model id and a branch reviewer on opus", (t) => {
|
|
129
|
+
const ws = workspace(t);
|
|
130
|
+
assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", model: "opus", prompt: "p" }), ws.tmp), null);
|
|
131
|
+
assert.equal(
|
|
132
|
+
decide(agentCall(ws.on, { subagent_type: "architecture:sdd-branch-reviewer", model: "opus", prompt: "p" }), ws.tmp),
|
|
133
|
+
null,
|
|
134
|
+
);
|
|
135
|
+
assert.equal(
|
|
136
|
+
decide(agentCall(ws.on, { subagent_type: "architecture:sdd-reviewer", model: "sonnet", prompt: "p" }), ws.tmp),
|
|
137
|
+
null,
|
|
138
|
+
);
|
|
139
|
+
assert.equal(decide(agentCall(ws.on, { model: "haiku", prompt: "p" }), ws.tmp), null);
|
|
140
|
+
assert.equal(
|
|
141
|
+
decide(agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "sonnet", prompt: "p" }), ws.tmp),
|
|
142
|
+
null,
|
|
143
|
+
);
|
|
144
|
+
decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
|
|
145
|
+
assert.equal(
|
|
146
|
+
decide(
|
|
147
|
+
agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "claude-sonnet-5", prompt: "p" }),
|
|
148
|
+
ws.tmp,
|
|
149
|
+
),
|
|
150
|
+
null,
|
|
151
|
+
);
|
|
152
|
+
});
|
|
153
|
+
|
|
154
|
+
test("a repository's models override replaces one type's families and leaves the rest at default", (t) => {
|
|
155
|
+
const ws = workspace(t, { maxPromptChars: 80, models: { "architecture:sdd-planner": ["sonnet"] } });
|
|
156
|
+
assert.equal(
|
|
157
|
+
decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", model: "sonnet", prompt: "p" }), ws.tmp),
|
|
158
|
+
null,
|
|
159
|
+
);
|
|
160
|
+
assert.match(
|
|
161
|
+
reasonOf(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-implementer", model: "opus", prompt: "p" }), ws.tmp)) ?? "",
|
|
162
|
+
/architecture:sdd-implementer/,
|
|
163
|
+
);
|
|
164
|
+
});
|
|
165
|
+
|
|
120
166
|
test("a slot with no stop expires after slotMinutes", (t) => {
|
|
121
167
|
const ws = workspace(t);
|
|
122
168
|
decide(agentCall(ws.on, implementer), ws.tmp);
|
|
@@ -158,3 +204,40 @@ test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () =>
|
|
|
158
204
|
assert.deepEqual(matchersOf(hooks.SubagentStart), [undefined]);
|
|
159
205
|
assert.deepEqual(matchersOf(hooks.SubagentStop), [undefined]);
|
|
160
206
|
});
|
|
207
|
+
|
|
208
|
+
const slotCall = (cwd, toolUseId) => agentCall(cwd, implementer, { tool_use_id: toolUseId });
|
|
209
|
+
const agentEvent = (cwd, agentId, hook_event_name) => ({
|
|
210
|
+
...subagentEvent(cwd, "architecture:sdd-implementer", hook_event_name),
|
|
211
|
+
agent_id: agentId,
|
|
212
|
+
});
|
|
213
|
+
|
|
214
|
+
test("a limit of 3 lets three implementers run, refuses the fourth with the holders and the limit, and a stop frees one", (t) => {
|
|
215
|
+
const ws = workspace(t, { implementerSlots: 3 });
|
|
216
|
+
for (const id of ["a", "b", "c"]) {
|
|
217
|
+
assert.equal(decide(slotCall(ws.on, `use-${id}`), ws.tmp), null);
|
|
218
|
+
decide(agentEvent(ws.on, `agent-${id}`, "SubagentStart"), ws.tmp);
|
|
219
|
+
}
|
|
220
|
+
const fourth = reasonOf(decide(slotCall(ws.on, "use-d"), ws.tmp)) ?? "";
|
|
221
|
+
assert.match(fourth, /all 3 implementer slots/);
|
|
222
|
+
for (const id of ["agent-a", "agent-b", "agent-c"]) assert.ok(fourth.includes(id), fourth);
|
|
223
|
+
decide(agentEvent(ws.on, "agent-b", "SubagentStop"), ws.tmp);
|
|
224
|
+
assert.equal(decide(slotCall(ws.on, "use-d"), ws.tmp), null);
|
|
225
|
+
assert.match(reasonOf(decide(slotCall(ws.on, "use-e"), ws.tmp)) ?? "", /all 3 implementer slots/);
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
test("a resumed implementer takes its own slot again when the limit is above 1", (t) => {
|
|
229
|
+
const ws = workspace(t, { implementerSlots: 2 });
|
|
230
|
+
decide(slotCall(ws.on, "use-a"), ws.tmp);
|
|
231
|
+
decide(agentEvent(ws.on, "agent-a", "SubagentStart"), ws.tmp);
|
|
232
|
+
decide(agentEvent(ws.on, "agent-a", "SubagentStop"), ws.tmp);
|
|
233
|
+
decide(agentEvent(ws.on, "agent-a", "SubagentStart"), ws.tmp);
|
|
234
|
+
assert.equal(decide(slotCall(ws.on, "use-b"), ws.tmp), null);
|
|
235
|
+
assert.match(reasonOf(decide(slotCall(ws.on, "use-c"), ws.tmp)) ?? "", /all 2 implementer slots/);
|
|
236
|
+
});
|
|
237
|
+
|
|
238
|
+
test("a dispatch with no tool_use_id still claims its own slot", (t) => {
|
|
239
|
+
const ws = workspace(t, { implementerSlots: 2 });
|
|
240
|
+
assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
|
|
241
|
+
assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
|
|
242
|
+
assert.match(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)) ?? "", /all 2 implementer slots/);
|
|
243
|
+
});
|
|
@@ -3,25 +3,61 @@
|
|
|
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 { dispatchSettingsAt } from "./dispatch.mjs";
|
|
6
|
+
import { dispatchSettingsAt, exploreSettingsAt } from "./dispatch.mjs";
|
|
7
7
|
|
|
8
8
|
export const REMINDER =
|
|
9
9
|
"Subagent workflow (swarm.dispatch in qc.config.json): run a plan with superpowers:subagent-driven-development. " +
|
|
10
10
|
"Dispatch architecture:sdd-planner to write a plan, architecture:sdd-implementer for one task, and " +
|
|
11
|
-
"architecture:sdd-reviewer to review it
|
|
12
|
-
"
|
|
11
|
+
"architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
|
|
12
|
+
"whole branch. The planner and the branch reviewer run on opus, the implementer and the task reviewer on sonnet. " +
|
|
13
|
+
"Run one implementer at a time: a hook refuses a second while one runs. Name a model on any other dispatch, and " +
|
|
14
|
+
"pass each brief as a file path.";
|
|
13
15
|
|
|
14
|
-
const context = (text) => ({ hookSpecificOutput: { hookEventName:
|
|
16
|
+
const context = (eventName, text) => ({ hookSpecificOutput: { hookEventName: eventName, additionalContext: text } });
|
|
15
17
|
|
|
16
|
-
/**
|
|
17
|
-
|
|
18
|
+
/** One added line for a limit above 1, which overrides the one-at-a-time rule of the note. */
|
|
19
|
+
const slotsLine = ({ implementerSlots }) =>
|
|
20
|
+
implementerSlots > 1
|
|
21
|
+
? ` 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.`
|
|
22
|
+
: "";
|
|
23
|
+
|
|
24
|
+
/** One added line naming `swarm.explore`'s tools, or "" when the section is off or names none. */
|
|
25
|
+
function exploreLine(cwd) {
|
|
18
26
|
let settings;
|
|
19
27
|
try {
|
|
20
|
-
settings =
|
|
28
|
+
settings = exploreSettingsAt(cwd);
|
|
29
|
+
} catch {
|
|
30
|
+
// The explore guard and hint each report their own config error; the dispatch note stays unaffected.
|
|
31
|
+
return "";
|
|
32
|
+
}
|
|
33
|
+
if (!settings || settings.tools.length === 0) return "";
|
|
34
|
+
return ` The repository's own explore tools: ${settings.tools.map((tool) => tool.name).join(", ")}.`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @returns the hook output for a subagent's own start, or null when `swarm.explore` names no tools. */
|
|
38
|
+
function decideSubagentStart(cwd) {
|
|
39
|
+
const line = exploreLine(cwd).trim();
|
|
40
|
+
return line === "" ? null : context("SubagentStart", line);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @returns the hook output, or null when the checkout turns on neither `swarm.dispatch` nor `swarm.explore`. */
|
|
44
|
+
function decideSessionStart(call) {
|
|
45
|
+
const cwd = call.cwd ?? process.cwd();
|
|
46
|
+
let dispatch;
|
|
47
|
+
try {
|
|
48
|
+
dispatch = dispatchSettingsAt(cwd);
|
|
21
49
|
} catch (error) {
|
|
22
|
-
return context(`Dispatch guard is off: ${error.message}`);
|
|
50
|
+
return context("SessionStart", `Dispatch guard is off: ${error.message}`);
|
|
23
51
|
}
|
|
24
|
-
|
|
52
|
+
const explore = exploreLine(cwd);
|
|
53
|
+
if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
|
|
54
|
+
return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${explore}`);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @returns the hook output, or null when there is nothing to add for this event. */
|
|
58
|
+
export function decide(call) {
|
|
59
|
+
if (call.hook_event_name === "SubagentStart") return decideSubagentStart(call.cwd ?? process.cwd());
|
|
60
|
+
return decideSessionStart(call);
|
|
25
61
|
}
|
|
26
62
|
|
|
27
63
|
async function readStdin() {
|
|
@@ -24,6 +24,7 @@ function checkouts(t, configs) {
|
|
|
24
24
|
}
|
|
25
25
|
|
|
26
26
|
const start = (cwd, source) => ({ session_id: "s", cwd, hook_event_name: "SessionStart", source });
|
|
27
|
+
const subagentStart = (cwd) => ({ session_id: "s", cwd, hook_event_name: "SubagentStart", agent_type: "sonnet-implementer" });
|
|
27
28
|
|
|
28
29
|
test("a checkout with no config, or no dispatch section, gets no note", (t) => {
|
|
29
30
|
const [plain, off] = checkouts(t, [null, { swarm: { toolCallBudget: 50 } }]);
|
|
@@ -40,17 +41,58 @@ test("with the section on, every start adds the note, a compaction included", (t
|
|
|
40
41
|
}
|
|
41
42
|
});
|
|
42
43
|
|
|
43
|
-
test("the note names the workflow, the
|
|
44
|
+
test("the note names the workflow, the four types, the model tiers, and the one-implementer rule, in a short text", () => {
|
|
44
45
|
for (const word of [
|
|
45
46
|
"superpowers:subagent-driven-development",
|
|
46
47
|
"architecture:sdd-planner",
|
|
47
48
|
"architecture:sdd-implementer",
|
|
48
49
|
"architecture:sdd-reviewer",
|
|
50
|
+
"architecture:sdd-branch-reviewer",
|
|
49
51
|
"one implementer at a time",
|
|
50
52
|
]) {
|
|
51
53
|
assert.ok(REMINDER.includes(word), word);
|
|
52
54
|
}
|
|
53
|
-
assert.ok(REMINDER.length <
|
|
55
|
+
assert.ok(REMINDER.length < 800, `${REMINDER.length} characters`);
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
test("with swarm.explore also on, the note names its tools", (t) => {
|
|
59
|
+
const [on] = checkouts(t, [
|
|
60
|
+
{ swarm: { dispatch: {}, explore: { tools: [{ name: "slm-rerank", use: "u", how: "h" }, { name: "GitNexus", use: "u", how: "h" }] } } },
|
|
61
|
+
]);
|
|
62
|
+
const text = decide(start(on, "startup")).hookSpecificOutput.additionalContext;
|
|
63
|
+
assert.ok(text.startsWith(REMINDER));
|
|
64
|
+
assert.match(text, /slm-rerank, GitNexus/);
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
test("with swarm.explore off, or naming no tools, the note is exactly REMINDER", (t) => {
|
|
68
|
+
const [off, empty] = checkouts(t, [
|
|
69
|
+
{ swarm: { dispatch: {} } },
|
|
70
|
+
{ swarm: { dispatch: {}, explore: { tools: [] } } },
|
|
71
|
+
]);
|
|
72
|
+
assert.equal(decide(start(off, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
73
|
+
assert.equal(decide(start(empty, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
test("with swarm.explore on and swarm.dispatch off, the SessionStart note still names the tools", (t) => {
|
|
77
|
+
const [on] = checkouts(t, [{ swarm: { explore: { tools: [{ name: "slm-rerank", use: "u", how: "h" }] } } }]);
|
|
78
|
+
const output = decide(start(on, "startup"));
|
|
79
|
+
assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart");
|
|
80
|
+
assert.match(output.hookSpecificOutput.additionalContext, /slm-rerank/);
|
|
81
|
+
assert.ok(!output.hookSpecificOutput.additionalContext.startsWith(" "));
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
test("SubagentStart names the tools when swarm.explore is on, independent of swarm.dispatch", (t) => {
|
|
85
|
+
const [on] = checkouts(t, [{ swarm: { explore: { tools: [{ name: "slm-rerank", use: "u", how: "h" }] } } }]);
|
|
86
|
+
const output = decide(subagentStart(on));
|
|
87
|
+
assert.equal(output.hookSpecificOutput.hookEventName, "SubagentStart");
|
|
88
|
+
assert.match(output.hookSpecificOutput.additionalContext, /slm-rerank/);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
test("SubagentStart with no swarm.explore section, or none naming tools, is a no-op", (t) => {
|
|
92
|
+
const [plain, off, empty] = checkouts(t, [null, { swarm: { dispatch: {} } }, { swarm: { explore: { tools: [] } } }]);
|
|
93
|
+
assert.equal(decide(subagentStart(plain)), null);
|
|
94
|
+
assert.equal(decide(subagentStart(off)), null);
|
|
95
|
+
assert.equal(decide(subagentStart(empty)), null);
|
|
54
96
|
});
|
|
55
97
|
|
|
56
98
|
test("a config error reaches the session as context", (t) => {
|
|
@@ -76,3 +118,25 @@ test("hooks.json runs the note on every SessionStart source", () => {
|
|
|
76
118
|
);
|
|
77
119
|
assert.deepEqual(entries.map((entry) => entry.matcher), [undefined]);
|
|
78
120
|
});
|
|
121
|
+
|
|
122
|
+
test("hooks.json also runs the note on SubagentStart, all matchers, beside the existing entry", () => {
|
|
123
|
+
const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
|
|
124
|
+
const entries = hooks.SubagentStart ?? [];
|
|
125
|
+
const noteEntries = entries.filter((entry) => entry.hooks.some((hook) => hook.command.includes("dispatch-reminder.mjs")));
|
|
126
|
+
assert.deepEqual(noteEntries.map((entry) => entry.matcher), [undefined]);
|
|
127
|
+
assert.ok(
|
|
128
|
+
entries.some((entry) => entry.hooks.some((hook) => hook.command.includes("dispatch-guard.mjs"))),
|
|
129
|
+
"the existing dispatch-guard.mjs SubagentStart entry stays",
|
|
130
|
+
);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
test("a limit above 1 adds one line stating it, and a limit of 1 leaves the note as REMINDER", (t) => {
|
|
134
|
+
const [three, one] = checkouts(t, [
|
|
135
|
+
{ swarm: { dispatch: { implementerSlots: 3 } } },
|
|
136
|
+
{ swarm: { dispatch: { implementerSlots: 1 } } },
|
|
137
|
+
]);
|
|
138
|
+
const text = decide(start(three, "startup")).hookSpecificOutput.additionalContext;
|
|
139
|
+
assert.ok(text.startsWith(REMINDER));
|
|
140
|
+
assert.match(text, /up to 3 implementers at once/);
|
|
141
|
+
assert.equal(decide(start(one, "startup")).hookSpecificOutput.additionalContext, REMINDER);
|
|
142
|
+
});
|
|
@@ -1,70 +1,185 @@
|
|
|
1
|
-
// The resource for the implementer
|
|
2
|
-
// claim
|
|
1
|
+
// The resource for the implementer slots: one folder per session under the OS temp folder, with
|
|
2
|
+
// `implementerSlots` fixed slot files, `slot-0.claim` and up, and the settings of the claims. A stop reads
|
|
3
|
+
// those settings, since its cwd can hold no config.
|
|
4
|
+
//
|
|
5
|
+
// A slot file is made by an exclusive create and holds its holder's id. The Agent call does not know the new
|
|
6
|
+
// agent's id, so a dispatch holds `pending:<tool_use_id>`. The agent's start rewrites the slot it finds
|
|
7
|
+
// pending to `agent:<agent_id>`, and its stop removes the slot that holds its own id.
|
|
3
8
|
|
|
4
|
-
import {
|
|
9
|
+
import { randomUUID } from "node:crypto";
|
|
10
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
11
|
import path from "node:path";
|
|
6
|
-
import {
|
|
12
|
+
import { fileSafe } from "./edit-batch-state.mjs";
|
|
7
13
|
|
|
8
|
-
const KEY = "implementer";
|
|
9
14
|
const SETTINGS_FILE = "settings.json";
|
|
10
15
|
const MINUTE_MS = 60_000;
|
|
16
|
+
const PENDING = "pending:";
|
|
17
|
+
const AGENT = "agent:";
|
|
18
|
+
const SLOT_FILE = /^slot-(\d+)\.claim$/;
|
|
11
19
|
|
|
12
20
|
/** The slot folder of one session. */
|
|
13
21
|
export const slotDirOf = (sessionId, tmp) => path.join(tmp, "architecture-kit", "dispatch", fileSafe(sessionId));
|
|
14
22
|
|
|
15
|
-
|
|
16
|
-
export const slotFileOf = (dir) => claimFileOf(dir, KEY);
|
|
23
|
+
const slotFileOf = (dir, index) => path.join(dir, `slot-${index}.claim`);
|
|
17
24
|
|
|
18
25
|
function recordedSettings(dir) {
|
|
19
26
|
try {
|
|
20
|
-
const { implementerTypes, slotMinutes } = JSON.parse(
|
|
21
|
-
|
|
27
|
+
const { implementerTypes, slotMinutes, implementerSlots = 1 } = JSON.parse(
|
|
28
|
+
readFileSync(path.join(dir, SETTINGS_FILE), "utf8"),
|
|
29
|
+
);
|
|
30
|
+
const valid = Array.isArray(implementerTypes) && slotMinutes > 0 && Number.isInteger(implementerSlots) && implementerSlots > 0;
|
|
31
|
+
return valid ? { implementerTypes, slotMinutes, implementerSlots } : null;
|
|
22
32
|
} catch {
|
|
23
33
|
return null;
|
|
24
34
|
}
|
|
25
35
|
}
|
|
26
36
|
|
|
37
|
+
const mtimeOf = (file) => {
|
|
38
|
+
try {
|
|
39
|
+
return statSync(file).mtimeMs;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
if (error.code === "ENOENT") return null;
|
|
42
|
+
throw error;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
/** Deletes each slot file older than the lifetime. A file that another hook removed first is already gone. */
|
|
47
|
+
function expireSlots(dir, ttlMs, now) {
|
|
48
|
+
let names;
|
|
49
|
+
try {
|
|
50
|
+
names = readdirSync(dir).filter((name) => SLOT_FILE.test(name));
|
|
51
|
+
} catch (error) {
|
|
52
|
+
if (error.code === "ENOENT") return;
|
|
53
|
+
throw error;
|
|
54
|
+
}
|
|
55
|
+
for (const name of names) {
|
|
56
|
+
const file = path.join(dir, name);
|
|
57
|
+
const claimedMs = mtimeOf(file);
|
|
58
|
+
// The second read narrows the window in which a takeover by another hook is deleted.
|
|
59
|
+
if (claimedMs !== null && now - claimedMs >= ttlMs && now - (mtimeOf(file) ?? now) >= ttlMs) rmSync(file, { force: true });
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** The live slot files, oldest first, with the holder each holds. A file made but not yet written holds a pending claim. */
|
|
64
|
+
function slotsOf(dir) {
|
|
65
|
+
let names;
|
|
66
|
+
try {
|
|
67
|
+
names = readdirSync(dir).filter((name) => SLOT_FILE.test(name));
|
|
68
|
+
} catch (error) {
|
|
69
|
+
if (error.code === "ENOENT") return [];
|
|
70
|
+
throw error;
|
|
71
|
+
}
|
|
72
|
+
const slots = [];
|
|
73
|
+
for (const name of names) {
|
|
74
|
+
const file = path.join(dir, name);
|
|
75
|
+
let held;
|
|
76
|
+
let claimedMs;
|
|
77
|
+
try {
|
|
78
|
+
claimedMs = statSync(file).mtimeMs;
|
|
79
|
+
held = readFileSync(file, "utf8");
|
|
80
|
+
} catch {
|
|
81
|
+
continue; // The holder stopped between the listing and this read.
|
|
82
|
+
}
|
|
83
|
+
const kind = held.startsWith(AGENT) ? AGENT : PENDING;
|
|
84
|
+
const id = held.startsWith(kind) ? held.slice(kind.length) : held;
|
|
85
|
+
slots.push({ file, index: Number(SLOT_FILE.exec(name)[1]), kind, id, held, claimedMs });
|
|
86
|
+
}
|
|
87
|
+
return slots.sort((a, b) => a.claimedMs - b.claimedMs || a.index - b.index);
|
|
88
|
+
}
|
|
89
|
+
|
|
27
90
|
/**
|
|
28
|
-
*
|
|
29
|
-
* @returns
|
|
91
|
+
* Creates one slot file through an exclusive create, which leaves an existing file as it is.
|
|
92
|
+
* @returns true when this call made the file
|
|
30
93
|
*/
|
|
31
|
-
|
|
32
|
-
const ttlMs = settings.slotMinutes * MINUTE_MS;
|
|
33
|
-
const slotFile = slotFileOf(dir);
|
|
94
|
+
function createSlot(dir, index, held) {
|
|
34
95
|
for (;;) {
|
|
35
|
-
if (claimPath(dir, KEY, now, ttlMs)) {
|
|
36
|
-
const { implementerTypes, slotMinutes } = settings;
|
|
37
|
-
try {
|
|
38
|
-
writeFileSync(path.join(dir, SETTINGS_FILE), JSON.stringify({ implementerTypes, slotMinutes }));
|
|
39
|
-
} catch (error) {
|
|
40
|
-
// A claim with no settings is freed by no stop, so it would hold the slot until it expires.
|
|
41
|
-
releasePath(dir, KEY);
|
|
42
|
-
throw error;
|
|
43
|
-
}
|
|
44
|
-
return null;
|
|
45
|
-
}
|
|
46
|
-
let claimedMs;
|
|
47
96
|
try {
|
|
48
|
-
|
|
97
|
+
writeFileSync(slotFileOf(dir, index), held, { flag: "wx" });
|
|
98
|
+
return true;
|
|
49
99
|
} catch (error) {
|
|
50
|
-
|
|
51
|
-
|
|
100
|
+
if (error.code === "ENOENT") {
|
|
101
|
+
mkdirSync(dir, { recursive: true });
|
|
102
|
+
continue;
|
|
103
|
+
}
|
|
104
|
+
if (error.code === "EEXIST") return false;
|
|
52
105
|
throw error;
|
|
53
106
|
}
|
|
54
|
-
return { claimedAt: new Date(claimedMs), expiresAt: new Date(claimedMs + ttlMs), slotFile };
|
|
55
107
|
}
|
|
56
108
|
}
|
|
57
109
|
|
|
58
|
-
/**
|
|
59
|
-
|
|
110
|
+
/** The first free slot below the limit takes the claim. @returns the slot's index, or -1 when every slot is held */
|
|
111
|
+
function takeFreeSlot(dir, limit, held) {
|
|
112
|
+
for (let index = 0; index < limit; index += 1) if (createSlot(dir, index, held)) return index;
|
|
113
|
+
return -1;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** The slot that fills the limit and frees first, with the times the refusal states, and the holders it names. */
|
|
117
|
+
function refusalOf(slots, ttlMs, limit) {
|
|
118
|
+
const [first] = slots;
|
|
119
|
+
return {
|
|
120
|
+
claimedAt: new Date(first.claimedMs),
|
|
121
|
+
expiresAt: new Date(first.claimedMs + ttlMs),
|
|
122
|
+
slotFile: first.file,
|
|
123
|
+
limit,
|
|
124
|
+
holders: slots.map((slot) => ({ id: slot.id, file: slot.file, claimedAt: new Date(slot.claimedMs) })),
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Claims a slot for one holder. Each slot is an exclusive create, so no parallel block passes the limit.
|
|
130
|
+
* @param holderId the dispatch's `tool_use_id`; a random id when the call carries none
|
|
131
|
+
* @returns null when this call holds a slot, or the holders that fill the limit; throws on a file system error
|
|
132
|
+
*/
|
|
133
|
+
export function claimSlot(dir, settings, now, holderId = randomUUID()) {
|
|
134
|
+
const ttlMs = settings.slotMinutes * MINUTE_MS;
|
|
135
|
+
const limit = settings.implementerSlots ?? 1;
|
|
136
|
+
const held = `${PENDING}${holderId}`;
|
|
137
|
+
expireSlots(dir, ttlMs, now);
|
|
138
|
+
if (slotsOf(dir).some((slot) => slot.held === held)) return null;
|
|
139
|
+
const index = takeFreeSlot(dir, limit, held);
|
|
140
|
+
if (index < 0) {
|
|
141
|
+
const slots = slotsOf(dir);
|
|
142
|
+
// Every holder stopped between the create and this read, so a slot is free again.
|
|
143
|
+
return slots.length === 0 ? claimSlot(dir, settings, now, holderId) : refusalOf(slots, ttlMs, limit);
|
|
144
|
+
}
|
|
145
|
+
const { implementerTypes, slotMinutes } = settings;
|
|
146
|
+
try {
|
|
147
|
+
writeFileSync(path.join(dir, SETTINGS_FILE), JSON.stringify({ implementerTypes, slotMinutes, implementerSlots: limit }));
|
|
148
|
+
} catch (error) {
|
|
149
|
+
// A claim with no settings is freed by no stop, so it would hold the slot until it expires.
|
|
150
|
+
rmSync(slotFileOf(dir, index), { force: true });
|
|
151
|
+
throw error;
|
|
152
|
+
}
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Binds a starting implementer to a slot. It rewrites one waiting dispatch claim, which counts once, and a
|
|
158
|
+
* resumed implementer with none waiting takes a free slot. A start cannot refuse, so it never waits.
|
|
159
|
+
*/
|
|
160
|
+
export function reclaimSlot(dir, agentType, now, agentId = randomUUID()) {
|
|
60
161
|
const settings = recordedSettings(dir);
|
|
61
|
-
if (settings?.implementerTypes.includes(agentType))
|
|
162
|
+
if (!settings?.implementerTypes.includes(agentType)) return;
|
|
163
|
+
expireSlots(dir, settings.slotMinutes * MINUTE_MS, now);
|
|
164
|
+
const held = `${AGENT}${agentId}`;
|
|
165
|
+
const slots = slotsOf(dir);
|
|
166
|
+
if (slots.some((slot) => slot.held === held)) return;
|
|
167
|
+
const waiting = slots.find((slot) => slot.kind === PENDING);
|
|
168
|
+
if (waiting) writeFileSync(waiting.file, held);
|
|
169
|
+
else takeFreeSlot(dir, settings.implementerSlots, held);
|
|
62
170
|
}
|
|
63
171
|
|
|
64
|
-
/**
|
|
65
|
-
|
|
172
|
+
/**
|
|
173
|
+
* Frees the slot of a stopped implementer: the one that holds its own id, or when it holds none, one waiting slot.
|
|
174
|
+
* @returns true when the stopped agent is an implementer
|
|
175
|
+
*/
|
|
176
|
+
export function releaseSlot(dir, agentType, agentId = "", now = Date.now()) {
|
|
66
177
|
const settings = recordedSettings(dir);
|
|
67
178
|
if (!settings?.implementerTypes.includes(agentType)) return false;
|
|
68
|
-
|
|
179
|
+
expireSlots(dir, settings.slotMinutes * MINUTE_MS, now);
|
|
180
|
+
const slots = slotsOf(dir);
|
|
181
|
+
const own = agentId === "" ? undefined : slots.find((slot) => slot.held === `${AGENT}${agentId}`);
|
|
182
|
+
const victim = own ?? slots.find((slot) => slot.kind === PENDING) ?? (agentId === "" ? slots[0] : undefined);
|
|
183
|
+
if (victim) rmSync(victim.file, { force: true });
|
|
69
184
|
return true;
|
|
70
185
|
}
|