architecture-harness 0.13.0 → 0.14.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.14.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,160 @@
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("a slot with no stop expires after slotMinutes", (t) => {
121
+ const ws = workspace(t);
122
+ decide(agentCall(ws.on, implementer), ws.tmp);
123
+ assert.notEqual(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)), null);
124
+ assert.equal(decide(agentCall(ws.on, implementer), ws.tmp, Date.now() + 61 * 60_000), null);
125
+ });
126
+
127
+ test("a resumed implementer holds the slot again", (t) => {
128
+ const ws = workspace(t);
129
+ decide(agentCall(ws.on, implementer), ws.tmp);
130
+ decide(subagentEvent(ws.on, "architecture:sdd-implementer"), ws.tmp);
131
+ decide(subagentEvent(ws.on, "architecture:sdd-implementer", "SubagentStart"), ws.tmp);
132
+ assert.match(reasonOf(decide(agentCall(ws.on, implementer), ws.tmp)) ?? "", /holds the one implementer slot/);
133
+ });
134
+
135
+ test("a config error reaches the session as context and never refuses", (t) => {
136
+ const ws = workspace(t, { slotMinutes: "soon" });
137
+ const output = decide(agentCall(ws.on, { prompt: "p" }), ws.tmp);
138
+ assert.equal(output.hookSpecificOutput.permissionDecision, undefined);
139
+ assert.match(output.hookSpecificOutput.additionalContext, /Dispatch guard is off: swarm\.dispatch\.slotMinutes/);
140
+ });
141
+
142
+ test("the hook runs as its own process and prints its refusal as JSON", (t) => {
143
+ const ws = workspace(t);
144
+ const result = spawnSync(process.execPath, [GUARD], {
145
+ input: JSON.stringify(agentCall(ws.on, { prompt: "p" })),
146
+ env: { ...process.env, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
147
+ encoding: "utf8",
148
+ });
149
+ assert.equal(result.status, 0, result.stderr);
150
+ assert.match(reasonOf(JSON.parse(result.stdout)) ?? "", /names no model/);
151
+ });
152
+
153
+ test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () => {
154
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
155
+ const matchersOf = (entries) =>
156
+ (entries ?? []).filter((entry) => entry.hooks.some((hook) => hook.command.includes("dispatch-guard.mjs"))).map((entry) => entry.matcher);
157
+ assert.deepEqual(matchersOf(hooks.PreToolUse), ["Agent"]);
158
+ assert.deepEqual(matchersOf(hooks.SubagentStart), [undefined]);
159
+ assert.deepEqual(matchersOf(hooks.SubagentStop), [undefined]);
160
+ });
@@ -0,0 +1,43 @@
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 } 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. Run one implementer at a time: a hook refuses a second while one runs. " +
12
+ "Name a model on any other dispatch, and pass each brief as a file path.";
13
+
14
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } });
15
+
16
+ /** @returns the hook output, or null when the checkout does not turn the section on. */
17
+ export function decide(call) {
18
+ let settings;
19
+ try {
20
+ settings = dispatchSettingsAt(call.cwd ?? process.cwd());
21
+ } catch (error) {
22
+ return context(`Dispatch guard is off: ${error.message}`);
23
+ }
24
+ return settings ? context(REMINDER) : null;
25
+ }
26
+
27
+ async function readStdin() {
28
+ let data = "";
29
+ for await (const chunk of process.stdin) data += chunk;
30
+ return data;
31
+ }
32
+
33
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
34
+ if (isEntryPoint) {
35
+ let call = null;
36
+ try {
37
+ call = JSON.parse(await readStdin());
38
+ } catch {
39
+ // Not hook input, so there is no checkout to read.
40
+ }
41
+ const result = call ? decide(call) : null;
42
+ if (result) process.stdout.write(JSON.stringify(result));
43
+ }
@@ -0,0 +1,78 @@
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
+
28
+ test("a checkout with no config, or no dispatch section, gets no note", (t) => {
29
+ const [plain, off] = checkouts(t, [null, { swarm: { toolCallBudget: 50 } }]);
30
+ assert.equal(decide(start(plain, "startup")), null);
31
+ assert.equal(decide(start(off, "startup")), null);
32
+ });
33
+
34
+ test("with the section on, every start adds the note, a compaction included", (t) => {
35
+ const [on] = checkouts(t, [{ swarm: { dispatch: {} } }]);
36
+ for (const source of ["startup", "resume", "clear", "compact", "fork"]) {
37
+ const output = decide(start(on, source));
38
+ assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart", source);
39
+ assert.equal(output.hookSpecificOutput.additionalContext, REMINDER, source);
40
+ }
41
+ });
42
+
43
+ test("the note names the workflow, the three types, and the one-implementer rule, in a short text", () => {
44
+ for (const word of [
45
+ "superpowers:subagent-driven-development",
46
+ "architecture:sdd-planner",
47
+ "architecture:sdd-implementer",
48
+ "architecture:sdd-reviewer",
49
+ "one implementer at a time",
50
+ ]) {
51
+ assert.ok(REMINDER.includes(word), word);
52
+ }
53
+ assert.ok(REMINDER.length < 600, `${REMINDER.length} characters`);
54
+ });
55
+
56
+ test("a config error reaches the session as context", (t) => {
57
+ const [bad] = checkouts(t, [{ swarm: { dispatch: { maxPromptChars: "long" } } }]);
58
+ assert.match(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, /Dispatch guard is off/);
59
+ });
60
+
61
+ test("the hook runs as its own process and prints the note as JSON, or nothing with no config", (t) => {
62
+ const [on, plain] = checkouts(t, [{ swarm: { dispatch: {} } }, null]);
63
+ const run = (cwd) => spawnSync(process.execPath, [NOTE], { input: JSON.stringify(start(cwd, "startup")), encoding: "utf8" });
64
+ const noted = run(on);
65
+ assert.equal(noted.status, 0, noted.stderr);
66
+ assert.equal(JSON.parse(noted.stdout).hookSpecificOutput.additionalContext, REMINDER);
67
+ const silent = run(plain);
68
+ assert.equal(silent.status, 0, silent.stderr);
69
+ assert.equal(silent.stdout, "");
70
+ });
71
+
72
+ test("hooks.json runs the note on every SessionStart source", () => {
73
+ const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
74
+ const entries = (hooks.SessionStart ?? []).filter((entry) =>
75
+ entry.hooks.some((hook) => hook.command.includes("dispatch-reminder.mjs")),
76
+ );
77
+ assert.deepEqual(entries.map((entry) => entry.matcher), [undefined]);
78
+ });
@@ -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
+ });
@@ -0,0 +1,84 @@
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, dispatchDefaults, load, merge } from "../config.mjs";
7
+ import { checkoutRootOf } from "./checkout-root.mjs";
8
+
9
+ const KEY = "swarm.dispatch";
10
+ const DEFAULT_TYPE = "general-purpose";
11
+ const FORK = "fork";
12
+
13
+ const isNameList = (value) => Array.isArray(value) && value.every((name) => typeof name === "string" && name !== "");
14
+ const wrong = (key, value, want) =>
15
+ new Error(`${KEY}.${key} in qc.config.json must be ${want}, got ${JSON.stringify(value)}`);
16
+
17
+ /** @returns the dispatch settings, or null when the section is absent; throws naming the key a repository got wrong. */
18
+ export function dispatchSettings(swarm = {}) {
19
+ const raw = swarm.dispatch;
20
+ if (raw === undefined || raw === null || raw === false) return null;
21
+ if (typeof raw !== "object" || Array.isArray(raw)) {
22
+ throw new Error(`${KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
23
+ }
24
+ const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes } = merge(dispatchDefaults, raw);
25
+ if (!isNameList(allowedTypes)) throw wrong("allowedTypes", allowedTypes, "a list of agent types");
26
+ if (!isNameList(implementerTypes)) throw wrong("implementerTypes", implementerTypes, "a list of agent types");
27
+ if (!Number.isInteger(maxPromptChars) || maxPromptChars < 1) {
28
+ throw wrong("maxPromptChars", maxPromptChars, "a positive whole number");
29
+ }
30
+ if (typeof slotMinutes !== "number" || !(slotMinutes > 0)) throw wrong("slotMinutes", slotMinutes, "a positive number");
31
+ return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes };
32
+ }
33
+
34
+ /** @returns the settings of the checkout that holds `cwd`, or null when it has no config or no section. */
35
+ export function dispatchSettingsAt(cwd) {
36
+ const root = checkoutRootOf(cwd);
37
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
38
+ return dispatchSettings(load(root).swarm);
39
+ }
40
+
41
+ /** The type a dispatch names, trimmed. The Agent tool runs general-purpose when it names none. */
42
+ export const typeOf = (input) =>
43
+ typeof input.subagent_type === "string" && input.subagent_type.trim() !== "" ? input.subagent_type.trim() : DEFAULT_TYPE;
44
+
45
+ export const isImplementer = (type, settings) => settings.implementerTypes.includes(type);
46
+
47
+ function modelRefusal(type, settings) {
48
+ const allowed = settings.allowedTypes.join(", ");
49
+ if (type === FORK) {
50
+ return (
51
+ "Dispatch guard: a fork runs on the session's model whatever `model` says, so it passes only when " +
52
+ `\`fork\` is in ${KEY}.allowedTypes in qc.config.json. Dispatch one of: ${allowed}, or another type with a model.`
53
+ );
54
+ }
55
+ return (
56
+ `Dispatch guard: the dispatch names no model, so the ${type} agent runs on the session's model. ` +
57
+ `Pass \`model\` with the cheapest tier that fits the task, or dispatch one of: ${allowed}. ` +
58
+ `To allow another type with no model, add it to ${KEY}.allowedTypes in qc.config.json.`
59
+ );
60
+ }
61
+
62
+ const promptRefusal = (length, max) =>
63
+ `Dispatch guard: the prompt has ${length} characters, over ${KEY}.maxPromptChars (${max}) in qc.config.json. ` +
64
+ "Write the brief to a file, and send a short prompt that names the brief and the report file.";
65
+
66
+ /** @returns the reason the dispatch breaks a rule that needs no state, or null to let it through. */
67
+ export function dispatchRefusal(input, settings) {
68
+ const type = typeOf(input);
69
+ const model = typeof input.model === "string" ? input.model.trim() : "";
70
+ const allowed = settings.allowedTypes.includes(type);
71
+ if (!allowed && (type === FORK || model === "")) return modelRefusal(type, settings);
72
+ const length = typeof input.prompt === "string" ? input.prompt.length : 0;
73
+ if (length > settings.maxPromptChars) return promptRefusal(length, settings.maxPromptChars);
74
+ return null;
75
+ }
76
+
77
+ /** The reason a second implementer waits, with the two ways the slot frees. */
78
+ export function slotRefusal({ type, claimedAt, expiresAt, slotFile }) {
79
+ return (
80
+ `Dispatch guard: an implementer holds the one implementer slot of this session since ${claimedAt.toISOString()}. ` +
81
+ `Wait for it to stop, then dispatch ${type}. The slot frees when it stops, or at ${expiresAt.toISOString()}. ` +
82
+ `If no implementer runs, because its dispatch was denied after this hook, delete ${slotFile}.`
83
+ );
84
+ }
@@ -0,0 +1,90 @@
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, 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
+ ]) {
32
+ assert.throws(() => dispatchSettings({ dispatch }), key, JSON.stringify(dispatch));
33
+ }
34
+ });
35
+
36
+ const on = dispatchSettings({ dispatch: { maxPromptChars: 20 } });
37
+
38
+ test("a dispatch with neither a model nor an allowed type is refused, and the reason names both fixes", () => {
39
+ for (const input of [{ prompt: "p" }, { subagent_type: "general-purpose", prompt: "p" }, { subagent_type: "Explore", model: " " }]) {
40
+ const reason = dispatchRefusal(input, on) ?? "";
41
+ assert.match(reason, /names no model/, JSON.stringify(input));
42
+ assert.match(reason, /swarm\.dispatch\.allowedTypes/);
43
+ assert.match(reason, /architecture:sdd-implementer/);
44
+ }
45
+ });
46
+
47
+ test("a named model or an allowed type passes", () => {
48
+ assert.equal(dispatchRefusal({ subagent_type: "general-purpose", model: "sonnet", prompt: "p" }, on), null);
49
+ assert.equal(dispatchRefusal({ model: "haiku" }, on), null);
50
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-reviewer" }, on), null);
51
+ });
52
+
53
+ test("a fork passes only as an allowed type, since it ignores the model", () => {
54
+ assert.match(dispatchRefusal({ subagent_type: "fork", model: "haiku" }, on) ?? "", /`fork` is in swarm\.dispatch\.allowedTypes/);
55
+ const withFork = dispatchSettings({ dispatch: { allowedTypes: ["fork"] } });
56
+ assert.equal(dispatchRefusal({ subagent_type: "fork" }, withFork), null);
57
+ });
58
+
59
+ test("a prompt over the limit is refused, and a prompt at the limit passes", () => {
60
+ const reason = dispatchRefusal({ model: "haiku", prompt: "x".repeat(21) }, on) ?? "";
61
+ assert.match(reason, /21 characters/);
62
+ assert.match(reason, /swarm\.dispatch\.maxPromptChars \(20\)/);
63
+ assert.match(reason, /Write the brief to a file/);
64
+ assert.equal(dispatchRefusal({ model: "haiku", prompt: "x".repeat(20) }, on), null);
65
+ });
66
+
67
+ test("the model rule comes before the length rule", () => {
68
+ assert.match(dispatchRefusal({ prompt: "x".repeat(21) }, on) ?? "", /names no model/);
69
+ });
70
+
71
+ test("an omitted type is general-purpose, and only a listed type is an implementer", () => {
72
+ assert.equal(typeOf({}), "general-purpose");
73
+ assert.equal(typeOf({ subagent_type: "" }), "general-purpose");
74
+ assert.equal(typeOf({ subagent_type: " \t" }), "general-purpose");
75
+ assert.equal(isImplementer("architecture:sdd-implementer", on), true);
76
+ assert.equal(isImplementer("sdd-implementer", on), true);
77
+ assert.equal(isImplementer("architecture:sdd-reviewer", on), false);
78
+ });
79
+
80
+ test("the slot refusal names the expiry and the file that frees the slot", () => {
81
+ const reason = slotRefusal({
82
+ type: "sdd-implementer",
83
+ claimedAt: new Date(0),
84
+ expiresAt: new Date(3_600_000),
85
+ slotFile: "/tmp/slot.claim",
86
+ });
87
+ assert.match(reason, /holds the one implementer slot/);
88
+ assert.match(reason, /1970-01-01T01:00:00\.000Z/);
89
+ assert.match(reason, /delete \/tmp\/slot\.claim/);
90
+ });
@@ -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
- const claimFileOf = (dir, key) => path.join(dir, `${createHash("sha256").update(key).digest("hex")}.claim`);
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,54 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { readFileSync, readdirSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { test } from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+ import { dispatchDefaults } from "../config.mjs";
7
+ import { REMINDER } from "./dispatch-reminder.mjs";
8
+
9
+ const AGENTS = fileURLToPath(new URL("../../../../agents/", import.meta.url));
10
+ const PLUGIN = "architecture";
11
+ 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"] },
15
+ };
16
+
17
+ /** The `key: value` lines between the two `---` fences. A checkout on Windows can carry CRLF. */
18
+ function frontmatterOf(file) {
19
+ const match = /^---\r?\n([\s\S]*?)\r?\n---/.exec(readFileSync(file, "utf8"));
20
+ assert.ok(match, `${file} has no frontmatter`);
21
+ return Object.fromEntries(
22
+ match[1].split(/\r?\n/).map((line) => {
23
+ const colon = line.indexOf(":");
24
+ return [line.slice(0, colon).trim(), line.slice(colon + 1).trim()];
25
+ }),
26
+ );
27
+ }
28
+
29
+ test("each subagent type runs on opus at its effort, and none can dispatch a subagent", () => {
30
+ assert.deepEqual(
31
+ readdirSync(AGENTS).sort(),
32
+ Object.keys(EXPECTED).map((name) => `${name}.md`).sort(),
33
+ "agents/ holds exactly the shipped types",
34
+ );
35
+ for (const [name, want] of Object.entries(EXPECTED)) {
36
+ const front = frontmatterOf(path.join(AGENTS, `${name}.md`));
37
+ assert.equal(front.name, name);
38
+ assert.equal(front.model, "opus", name);
39
+ assert.equal(front.effort, want.effort, name);
40
+ assert.ok(front.description.length > 0, name);
41
+ assert.deepEqual(front.disallowedTools.split(",").map((tool) => tool.trim()), want.disallowedTools, name);
42
+ }
43
+ });
44
+
45
+ test("the session note names only the types the plugin ships", () => {
46
+ const named = new Set([...REMINDER.matchAll(/architecture:([a-z-]+)/g)].map((match) => match[1]));
47
+ assert.deepEqual([...named].sort(), Object.keys(EXPECTED).sort());
48
+ });
49
+
50
+ test("the default allowed types are the shipped types, bare and scoped", () => {
51
+ const shipped = Object.keys(EXPECTED).flatMap((name) => [name, `${PLUGIN}:${name}`]);
52
+ assert.deepEqual([...dispatchDefaults.allowedTypes].sort(), shipped.sort());
53
+ assert.deepEqual(dispatchDefaults.implementerTypes, ["sdd-implementer", `${PLUGIN}:sdd-implementer`]);
54
+ });
package/src/config.mjs CHANGED
@@ -219,6 +219,8 @@ export const defaults = {
219
219
  isolation: { require: "off", protectedBranches: ["main", "master"], leaseHours: 8, allow: [] },
220
220
  // Tool calls per subagent. The hook reminds at seventy percent and denies all but the hand-off at the budget.
221
221
  toolCallBudget: 100,
222
+ // Off until a repository writes the section. `{}` turns it on, and `dispatchDefaults` fills each key it omits.
223
+ dispatch: null,
222
224
  },
223
225
 
224
226
  // Files a generator writes. The generated-file hook refuses a hand edit of one and names `command`.
@@ -410,6 +412,25 @@ export const defaults = {
410
412
  ignores: ["**/dist/**", "**/node_modules/**", "**/*.tsbuildinfo"],
411
413
  };
412
414
 
415
+ // What each key of `swarm.dispatch` means when a repository omits it. A list replaces its default.
416
+ export const dispatchDefaults = {
417
+ // Types that may omit `model`: the plugin's three, and the bare names of a user-level copy.
418
+ allowedTypes: [
419
+ "sdd-implementer",
420
+ "sdd-planner",
421
+ "sdd-reviewer",
422
+ "architecture:sdd-implementer",
423
+ "architecture:sdd-planner",
424
+ "architecture:sdd-reviewer",
425
+ ],
426
+ // Types that share one slot per session.
427
+ implementerTypes: ["sdd-implementer", "architecture:sdd-implementer"],
428
+ // The longest prompt, in characters. A brief belongs in a file.
429
+ maxPromptChars: 12000,
430
+ // A slot with no stop expires after this many minutes.
431
+ slotMinutes: 60,
432
+ };
433
+
413
434
  function isPlainObject(value) {
414
435
  return value !== null && typeof value === "object" && !Array.isArray(value);
415
436
  }