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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.13.0",
3
+ "version": "0.15.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -0,0 +1,78 @@
1
+ #!/usr/bin/env node
2
+ // The trigger for `swarm.dispatch`. PreToolUse on Agent judges a dispatch and claims the implementer
3
+ // slot. SubagentStart claims it again for a resumed implementer, and SubagentStop frees it.
4
+
5
+ import { existsSync } from "node:fs";
6
+ import os from "node:os";
7
+ import { fileURLToPath } from "node:url";
8
+ import { dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
9
+ import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
10
+
11
+ const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", ...fields } });
12
+ const deny = (reason) => output({ permissionDecision: "deny", permissionDecisionReason: reason });
13
+ const context = (text) => output({ additionalContext: text });
14
+
15
+ /** Claims or frees the slot as a subagent starts or stops. It reads no config, since the agent's cwd is its own. */
16
+ function onSubagent(call, dir, now) {
17
+ // Only a claim makes the folder, so a session with the guard off gets no file here.
18
+ if (!existsSync(dir)) return;
19
+ try {
20
+ if (call.hook_event_name === "SubagentStart") reclaimSlot(dir, call.agent_type, now);
21
+ else releaseSlot(dir, call.agent_type);
22
+ } catch {
23
+ // A busy or read-only temp folder is the hook's own problem, and the slot still expires.
24
+ }
25
+ }
26
+
27
+ /** The verdict on one hook event. @returns the hook output, or null to let the call run with no message. */
28
+ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
29
+ const dir = slotDirOf(call.session_id ?? "session", tmp);
30
+ if (call.hook_event_name === "SubagentStart" || call.hook_event_name === "SubagentStop") {
31
+ onSubagent(call, dir, now);
32
+ return null;
33
+ }
34
+ if (call.hook_event_name !== "PreToolUse" || call.tool_name !== "Agent") return null;
35
+ // A subagent's dispatch follows its own definition, often another plugin's; the orchestrator is the main session.
36
+ if (typeof call.agent_id === "string" && call.agent_id !== "") return null;
37
+
38
+ let settings;
39
+ try {
40
+ settings = dispatchSettingsAt(call.cwd ?? process.cwd());
41
+ } catch (error) {
42
+ // A config typo must not stop every dispatch; the session sees the error and reports it.
43
+ return context(`Dispatch guard is off: ${error.message}`);
44
+ }
45
+ if (!settings) return null;
46
+
47
+ const input = call.tool_input ?? {};
48
+ const refusal = dispatchRefusal(input, settings);
49
+ if (refusal) return deny(refusal);
50
+ const type = typeOf(input);
51
+ if (!isImplementer(type, settings)) return null;
52
+ let holder;
53
+ try {
54
+ holder = claimSlot(dir, settings, now);
55
+ } catch {
56
+ // A busy or read-only temp folder is the hook's own problem, never a reason to refuse a dispatch.
57
+ return null;
58
+ }
59
+ return holder ? deny(slotRefusal({ type, ...holder })) : null;
60
+ }
61
+
62
+ async function readStdin() {
63
+ let data = "";
64
+ for await (const chunk of process.stdin) data += chunk;
65
+ return data;
66
+ }
67
+
68
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
69
+ if (isEntryPoint) {
70
+ let call = null;
71
+ try {
72
+ call = JSON.parse(await readStdin());
73
+ } catch {
74
+ // Not hook input, so there is nothing to judge.
75
+ }
76
+ const result = call ? decide(call) : null;
77
+ if (result) process.stdout.write(JSON.stringify(result));
78
+ }
@@ -0,0 +1,206 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, 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 "./dispatch-guard.mjs";
9
+
10
+ const GUARD = fileURLToPath(new URL("./dispatch-guard.mjs", import.meta.url));
11
+ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
12
+
13
+ /** A checkout that turns the guard on, one whose swarm section has no dispatch key, one with no config, and a temp folder. */
14
+ function workspace(t, dispatch = { maxPromptChars: 80 }) {
15
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-")));
16
+ t.after(() => rmSync(base, { recursive: true, force: true }));
17
+ const on = path.join(base, "on");
18
+ const off = path.join(base, "off");
19
+ const plain = path.join(base, "plain");
20
+ const tmp = path.join(base, "tmp");
21
+ for (const dir of [on, off, plain]) {
22
+ mkdirSync(dir);
23
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
24
+ }
25
+ mkdirSync(tmp);
26
+ mkdirSync(path.join(on, "src"));
27
+ writeFileSync(path.join(on, "qc.config.json"), JSON.stringify({ swarm: { dispatch } }));
28
+ writeFileSync(path.join(off, "qc.config.json"), JSON.stringify({ swarm: { toolCallBudget: 50 } }));
29
+ return { on, off, plain, tmp, slots: path.join(tmp, "architecture-kit", "dispatch") };
30
+ }
31
+
32
+ const agentCall = (cwd, tool_input, extra = {}) => ({
33
+ session_id: "session-aaaa",
34
+ cwd,
35
+ hook_event_name: "PreToolUse",
36
+ tool_name: "Agent",
37
+ tool_input,
38
+ ...extra,
39
+ });
40
+ const subagentEvent = (cwd, agent_type, hook_event_name = "SubagentStop") => ({
41
+ session_id: "session-aaaa",
42
+ cwd,
43
+ hook_event_name,
44
+ agent_id: "agent-1",
45
+ agent_type,
46
+ });
47
+ const reasonOf = (output) =>
48
+ output?.hookSpecificOutput?.permissionDecision === "deny" ? output.hookSpecificOutput.permissionDecisionReason : null;
49
+ const implementer = {
50
+ subagent_type: "architecture:sdd-implementer",
51
+ description: "Task 1",
52
+ prompt: "Read the brief at plans/task-1-brief.md.",
53
+ };
54
+
55
+ test("a checkout with no config, or a swarm section with no dispatch key, sees no change", (t) => {
56
+ const ws = workspace(t);
57
+ for (const cwd of [ws.off, ws.plain]) {
58
+ assert.equal(decide(agentCall(cwd, { prompt: "x".repeat(500) }), ws.tmp), null);
59
+ assert.equal(decide(agentCall(cwd, implementer), ws.tmp), null);
60
+ assert.equal(decide(agentCall(cwd, implementer), ws.tmp), null);
61
+ assert.equal(decide(subagentEvent(cwd, "architecture:sdd-implementer"), ws.tmp), null);
62
+ }
63
+ assert.equal(existsSync(ws.slots), false);
64
+ });
65
+
66
+ test("the main session's dispatch with no model is refused, and one with a model passes", (t) => {
67
+ const ws = workspace(t);
68
+ assert.match(reasonOf(decide(agentCall(ws.on, { prompt: "p" }), ws.tmp)) ?? "", /names no model/);
69
+ assert.equal(decide(agentCall(ws.on, { prompt: "p", model: "sonnet" }), ws.tmp), null);
70
+ });
71
+
72
+ test("a subagent's dispatch is left to its own definition", (t) => {
73
+ const ws = workspace(t);
74
+ const extra = { agent_id: "agent-9", agent_type: "claude-security:patch-generator" };
75
+ assert.equal(decide(agentCall(ws.on, { subagent_type: "claude-security:explore", prompt: "p" }, extra), ws.tmp), null);
76
+ assert.equal(decide(agentCall(ws.on, implementer, extra), ws.tmp), null);
77
+ assert.equal(existsSync(ws.slots), false);
78
+ });
79
+
80
+ test("the config of the checkout that holds the cwd decides", (t) => {
81
+ const ws = workspace(t);
82
+ assert.match(reasonOf(decide(agentCall(path.join(ws.on, "src"), { prompt: "p" }), ws.tmp)) ?? "", /names no model/);
83
+ });
84
+
85
+ test("a prompt over the limit is refused, and the refusal claims no slot", (t) => {
86
+ const ws = workspace(t);
87
+ const long = { ...implementer, prompt: "x".repeat(81) };
88
+ assert.match(reasonOf(decide(agentCall(ws.on, long), ws.tmp)) ?? "", /81 characters/);
89
+ assert.equal(existsSync(ws.slots), false);
90
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
91
+ });
92
+
93
+ test("a second implementer is refused until the first one stops, and the refusal names the slot file", (t) => {
94
+ const ws = workspace(t);
95
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
96
+ const second = reasonOf(decide(agentCall(ws.on, { ...implementer, subagent_type: "sdd-implementer" }), ws.tmp)) ?? "";
97
+ assert.match(second, /holds the one implementer slot/);
98
+ assert.ok(second.includes(ws.slots), second);
99
+ decide(subagentEvent(ws.on, ""), ws.tmp);
100
+ decide(subagentEvent(ws.on, "architecture:sdd-reviewer"), ws.tmp);
101
+ assert.notEqual(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)), null);
102
+ decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
103
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
104
+ });
105
+
106
+ test("a stop in a worktree with no config still frees the slot", (t) => {
107
+ const ws = workspace(t);
108
+ decide(agentCall(ws.on, implementer), ws.tmp);
109
+ decide(subagentEvent(ws.plain, "architecture:sdd-implementer"), ws.tmp);
110
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp), null);
111
+ });
112
+
113
+ test("a planner and a reviewer run beside an implementer", (t) => {
114
+ const ws = workspace(t);
115
+ decide(agentCall(ws.on, implementer), ws.tmp);
116
+ assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-reviewer", prompt: "p" }), ws.tmp), null);
117
+ assert.equal(decide(agentCall(ws.on, { subagent_type: "architecture:sdd-planner", prompt: "p" }), ws.tmp), null);
118
+ });
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
+
166
+ test("a slot with no stop expires after slotMinutes", (t) => {
167
+ const ws = workspace(t);
168
+ decide(agentCall(ws.on, implementer), ws.tmp);
169
+ assert.notEqual(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)), null);
170
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp, Date.now() + 61 * 60_000), null);
171
+ });
172
+
173
+ test("a resumed implementer holds the slot again", (t) => {
174
+ const ws = workspace(t);
175
+ decide(agentCall(ws.on, implementer), ws.tmp);
176
+ decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
177
+ decide(subagentEvent(ws.on, "architecture:sdd-implementer", "SubagentStart"), ws.tmp);
178
+ assert.match(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)) ?? "", /holds the one implementer slot/);
179
+ });
180
+
181
+ test("a config error reaches the session as context and never refuses", (t) => {
182
+ const ws = workspace(t, { slotMinutes: "soon" });
183
+ const output = decide(agentCall(ws.on, { prompt: "p" }), ws.tmp);
184
+ assert.equal(output.hookSpecificOutput.permissionDecision, undefined);
185
+ assert.match(output.hookSpecificOutput.additionalContext, /Dispatch guard is off: swarm\.dispatch\.slotMinutes/);
186
+ });
187
+
188
+ test("the hook runs as its own process and prints its refusal as JSON", (t) => {
189
+ const ws = workspace(t);
190
+ const result = spawnSync(process.execPath, [GUARD], {
191
+ input: JSON.stringify(agentCall(ws.on, { prompt: "p" })),
192
+ env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
193
+ encoding: "utf8",
194
+ });
195
+ assert.equal(result.status, 0, result.stderr);
196
+ assert.match(reasonOf(JSON.parse(result.stdout)) ?? "", /names no model/);
197
+ });
198
+
199
+ test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () => {
200
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
201
+ const matchersOf = (entries) =>
202
+ (entries ?? []).filter((entry) => entry.hooks.some((hook) => hook.command.includes("dispatch-guard.mjs"))).map((entry) => entry.matcher);
203
+ assert.deepEqual(matchersOf(hooks.PreToolUse), ["Agent"]);
204
+ assert.deepEqual(matchersOf(hooks.SubagentStart), [undefined]);
205
+ assert.deepEqual(matchersOf(hooks.SubagentStop), [undefined]);
206
+ });
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // The SessionStart trigger for `swarm.dispatch`: one short note at each start, resume, clear, compaction
3
+ // and fork, because a rule held only in the conversation is lost to a compaction.
4
+
5
+ import { fileURLToPath } from "node:url";
6
+ import { dispatchSettingsAt, exploreSettingsAt } from "./dispatch.mjs";
7
+
8
+ export const REMINDER =
9
+ "Subagent workflow (swarm.dispatch in qc.config.json): run a plan with superpowers:subagent-driven-development. " +
10
+ "Dispatch architecture:sdd-planner to write a plan, architecture:sdd-implementer for one task, and " +
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.";
15
+
16
+ const context = (eventName, text) => ({ hookSpecificOutput: { hookEventName: eventName, additionalContext: text } });
17
+
18
+ /** One added line naming `swarm.explore`'s tools, or "" when the section is off or names none. */
19
+ function exploreLine(cwd) {
20
+ let settings;
21
+ try {
22
+ settings = exploreSettingsAt(cwd);
23
+ } catch {
24
+ // The explore guard and hint each report their own config error; the dispatch note stays unaffected.
25
+ return "";
26
+ }
27
+ if (!settings || settings.tools.length === 0) return "";
28
+ return ` The repository's own explore tools: ${settings.tools.map((tool) => tool.name).join(", ")}.`;
29
+ }
30
+
31
+ /** @returns the hook output for a subagent's own start, or null when `swarm.explore` names no tools. */
32
+ function decideSubagentStart(cwd) {
33
+ const line = exploreLine(cwd).trim();
34
+ return line === "" ? null : context("SubagentStart", line);
35
+ }
36
+
37
+ /** @returns the hook output, or null when the checkout turns on neither `swarm.dispatch` nor `swarm.explore`. */
38
+ function decideSessionStart(call) {
39
+ const cwd = call.cwd ?? process.cwd();
40
+ let dispatch;
41
+ try {
42
+ dispatch = dispatchSettingsAt(cwd);
43
+ } catch (error) {
44
+ return context("SessionStart", `Dispatch guard is off: ${error.message}`);
45
+ }
46
+ const explore = exploreLine(cwd);
47
+ if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
48
+ return context("SessionStart", `${REMINDER}${explore}`);
49
+ }
50
+
51
+ /** @returns the hook output, or null when there is nothing to add for this event. */
52
+ export function decide(call) {
53
+ if (call.hook_event_name === "SubagentStart") return decideSubagentStart(call.cwd ?? process.cwd());
54
+ return decideSessionStart(call);
55
+ }
56
+
57
+ async function readStdin() {
58
+ let data = "";
59
+ for await (const chunk of process.stdin) data += chunk;
60
+ return data;
61
+ }
62
+
63
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
64
+ if (isEntryPoint) {
65
+ let call = null;
66
+ try {
67
+ call = JSON.parse(await readStdin());
68
+ } catch {
69
+ // Not hook input, so there is no checkout to read.
70
+ }
71
+ const result = call ? decide(call) : null;
72
+ if (result) process.stdout.write(JSON.stringify(result));
73
+ }
@@ -0,0 +1,131 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } 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 { REMINDER, decide } from "./dispatch-reminder.mjs";
9
+
10
+ const NOTE = fileURLToPath(new URL("./dispatch-reminder.mjs", import.meta.url));
11
+ const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
12
+
13
+ /** Three checkouts: one per config, and `null` writes no config at all. */
14
+ function checkouts(t, configs) {
15
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-note-")));
16
+ t.after(() => rmSync(base, { recursive: true, force: true }));
17
+ return configs.map((config, index) => {
18
+ const dir = path.join(base, String(index));
19
+ mkdirSync(dir);
20
+ execFileSync("git", ["init", "-q"], { cwd: dir, stdio: "pipe" });
21
+ if (config !== null) writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify(config));
22
+ return dir;
23
+ });
24
+ }
25
+
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" });
28
+
29
+ test("a checkout with no config, or no dispatch section, gets no note", (t) => {
30
+ const [plain, off] = checkouts(t, [null, { swarm: { toolCallBudget: 50 } }]);
31
+ assert.equal(decide(start(plain, "startup")), null);
32
+ assert.equal(decide(start(off, "startup")), null);
33
+ });
34
+
35
+ test("with the section on, every start adds the note, a compaction included", (t) => {
36
+ const [on] = checkouts(t, [{ swarm: { dispatch: {} } }]);
37
+ for (const source of ["startup", "resume", "clear", "compact", "fork"]) {
38
+ const output = decide(start(on, source));
39
+ assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart", source);
40
+ assert.equal(output.hookSpecificOutput.additionalContext, REMINDER, source);
41
+ }
42
+ });
43
+
44
+ test("the note names the workflow, the four types, the model tiers, and the one-implementer rule, in a short text", () => {
45
+ for (const word of [
46
+ "superpowers:subagent-driven-development",
47
+ "architecture:sdd-planner",
48
+ "architecture:sdd-implementer",
49
+ "architecture:sdd-reviewer",
50
+ "architecture:sdd-branch-reviewer",
51
+ "one implementer at a time",
52
+ ]) {
53
+ assert.ok(REMINDER.includes(word), word);
54
+ }
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);
96
+ });
97
+
98
+ test("a config error reaches the session as context", (t) => {
99
+ const [bad] = checkouts(t, [{ swarm: { dispatch: { maxPromptChars: "long" } } }]);
100
+ assert.match(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, /Dispatch guard is off/);
101
+ });
102
+
103
+ test("the hook runs as its own process and prints the note as JSON, or nothing with no config", (t) => {
104
+ const [on, plain] = checkouts(t, [{ swarm: { dispatch: {} } }, null]);
105
+ const run = (cwd) => spawnSync(process.execPath, [NOTE], { input: JSON.stringify(start(cwd, "startup")), encoding: "utf8" });
106
+ const noted = run(on);
107
+ assert.equal(noted.status, 0, noted.stderr);
108
+ assert.equal(JSON.parse(noted.stdout).hookSpecificOutput.additionalContext, REMINDER);
109
+ const silent = run(plain);
110
+ assert.equal(silent.status, 0, silent.stderr);
111
+ assert.equal(silent.stdout, "");
112
+ });
113
+
114
+ test("hooks.json runs the note on every SessionStart source", () => {
115
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
116
+ const entries = (hooks.SessionStart ?? []).filter((entry) =>
117
+ entry.hooks.some((hook) => hook.command.includes("dispatch-reminder.mjs")),
118
+ );
119
+ assert.deepEqual(entries.map((entry) => entry.matcher), [undefined]);
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
+ });
@@ -0,0 +1,70 @@
1
+ // The resource for the implementer slot: one folder per session under the OS temp folder, with one
2
+ // claim file and the settings of the claim. A stop reads those settings, since its cwd can hold no config.
3
+
4
+ import { readFileSync, statSync, writeFileSync } from "node:fs";
5
+ import path from "node:path";
6
+ import { claimFileOf, claimPath, fileSafe, releasePath } from "./edit-batch-state.mjs";
7
+
8
+ const KEY = "implementer";
9
+ const SETTINGS_FILE = "settings.json";
10
+ const MINUTE_MS = 60_000;
11
+
12
+ /** The slot folder of one session. */
13
+ export const slotDirOf = (sessionId, tmp) => path.join(tmp, "architecture-kit", "dispatch", fileSafe(sessionId));
14
+
15
+ /** The claim file of the slot in one session folder. */
16
+ export const slotFileOf = (dir) => claimFileOf(dir, KEY);
17
+
18
+ function recordedSettings(dir) {
19
+ try {
20
+ const { implementerTypes, slotMinutes } = JSON.parse(readFileSync(path.join(dir, SETTINGS_FILE), "utf8"));
21
+ return Array.isArray(implementerTypes) && slotMinutes > 0 ? { implementerTypes, slotMinutes } : null;
22
+ } catch {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Claims the slot through an exclusive create, so two dispatches in one block cannot both win.
29
+ * @returns null when this call holds the slot, or the holder's times and file; throws on a file system error
30
+ */
31
+ export function claimSlot(dir, settings, now) {
32
+ const ttlMs = settings.slotMinutes * MINUTE_MS;
33
+ const slotFile = slotFileOf(dir);
34
+ 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
+ try {
48
+ claimedMs = statSync(slotFile).mtimeMs;
49
+ } catch (error) {
50
+ // The holder stopped between the claim and this read, so the slot is free again.
51
+ if (error.code === "ENOENT") continue;
52
+ throw error;
53
+ }
54
+ return { claimedAt: new Date(claimedMs), expiresAt: new Date(claimedMs + ttlMs), slotFile };
55
+ }
56
+ }
57
+
58
+ /** Claims a free slot for an implementer that starts, as a resumed one does. A start cannot refuse, so it never waits. */
59
+ export function reclaimSlot(dir, agentType, now) {
60
+ const settings = recordedSettings(dir);
61
+ if (settings?.implementerTypes.includes(agentType)) claimPath(dir, KEY, now, settings.slotMinutes * MINUTE_MS);
62
+ }
63
+
64
+ /** Frees the slot when an implementer stops. @returns true when the stopped agent is an implementer */
65
+ export function releaseSlot(dir, agentType) {
66
+ const settings = recordedSettings(dir);
67
+ if (!settings?.implementerTypes.includes(agentType)) return false;
68
+ releasePath(dir, KEY);
69
+ return true;
70
+ }
@@ -0,0 +1,80 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import { test } from "node:test";
6
+ import { dispatchDefaults } from "../config.mjs";
7
+ import { claimSlot, reclaimSlot, releaseSlot, slotDirOf, slotFileOf } from "./dispatch-slot.mjs";
8
+
9
+ function sessionDir(t) {
10
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-slot-"));
11
+ t.after(() => rmSync(tmp, { recursive: true, force: true }));
12
+ return slotDirOf("s", tmp);
13
+ }
14
+
15
+ const settings = { ...dispatchDefaults, slotMinutes: 1 };
16
+
17
+ test("the slot folder is keyed on the session, with a file-safe name", () => {
18
+ assert.equal(slotDirOf("sess/1:a", "/tmp"), path.join("/tmp", "architecture-kit", "dispatch", "sess_1_a"));
19
+ });
20
+
21
+ test("the first claim holds the slot, and a second claim with no stop between gets the holder", (t) => {
22
+ const dir = sessionDir(t);
23
+ assert.equal(claimSlot(dir, settings, Date.now()), null);
24
+ const holder = claimSlot(dir, settings, Date.now());
25
+ assert.equal(holder.slotFile, slotFileOf(dir));
26
+ assert.equal(holder.expiresAt.getTime() - holder.claimedAt.getTime(), 60_000);
27
+ });
28
+
29
+ test("a claim older than slotMinutes is taken over", (t) => {
30
+ const dir = sessionDir(t);
31
+ claimSlot(dir, settings, Date.now());
32
+ const old = new Date(Date.now() - 120_000);
33
+ utimesSync(slotFileOf(dir), old, old);
34
+ assert.equal(claimSlot(dir, settings, Date.now()), null);
35
+ });
36
+
37
+ test("only an implementer's stop frees the slot, and an empty agent type frees nothing", (t) => {
38
+ const dir = sessionDir(t);
39
+ claimSlot(dir, settings, Date.now());
40
+ assert.equal(releaseSlot(dir, ""), false);
41
+ assert.equal(releaseSlot(dir, "architecture:sdd-reviewer"), false);
42
+ assert.equal(existsSync(slotFileOf(dir)), true);
43
+ assert.equal(releaseSlot(dir, "architecture:sdd-implementer"), true);
44
+ assert.equal(existsSync(slotFileOf(dir)), false);
45
+ assert.equal(claimSlot(dir, settings, Date.now()), null);
46
+ });
47
+
48
+ test("the stop reads the list recorded at the claim", (t) => {
49
+ const dir = sessionDir(t);
50
+ claimSlot(dir, { ...settings, implementerTypes: ["builder"] }, Date.now());
51
+ assert.equal(releaseSlot(dir, "sdd-implementer"), false);
52
+ assert.equal(releaseSlot(dir, "builder"), true);
53
+ });
54
+
55
+ test("a resumed implementer claims a free slot again, and a reviewer does not", (t) => {
56
+ const dir = sessionDir(t);
57
+ claimSlot(dir, settings, Date.now());
58
+ releaseSlot(dir, "sdd-implementer");
59
+ reclaimSlot(dir, "architecture:sdd-reviewer", Date.now());
60
+ assert.equal(existsSync(slotFileOf(dir)), false);
61
+ reclaimSlot(dir, "sdd-implementer", Date.now());
62
+ assert.notEqual(claimSlot(dir, settings, Date.now()), null);
63
+ });
64
+
65
+ test("a session folder with no settings, or settings that do not parse, changes nothing", (t) => {
66
+ const dir = sessionDir(t);
67
+ mkdirSync(dir, { recursive: true });
68
+ assert.equal(releaseSlot(dir, "sdd-implementer"), false);
69
+ writeFileSync(path.join(dir, "settings.json"), "not json");
70
+ assert.equal(releaseSlot(dir, "sdd-implementer"), false);
71
+ reclaimSlot(dir, "sdd-implementer", Date.now());
72
+ assert.equal(existsSync(slotFileOf(dir)), false);
73
+ });
74
+
75
+ test("a claim whose settings cannot be written is released, and the error reaches the caller", (t) => {
76
+ const dir = sessionDir(t);
77
+ mkdirSync(path.join(dir, "settings.json"), { recursive: true });
78
+ assert.throws(() => claimSlot(dir, settings, Date.now()));
79
+ assert.equal(existsSync(slotFileOf(dir)), false);
80
+ });