architecture-harness 0.15.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.15.0",
3
+ "version": "0.16.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -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;
@@ -204,3 +204,40 @@ test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () =>
204
204
  assert.deepEqual(matchersOf(hooks.SubagentStart), [undefined]);
205
205
  assert.deepEqual(matchersOf(hooks.SubagentStop), [undefined]);
206
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
+ });
@@ -15,6 +15,12 @@ export const REMINDER =
15
15
 
16
16
  const context = (eventName, text) => ({ hookSpecificOutput: { hookEventName: eventName, additionalContext: text } });
17
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
+
18
24
  /** One added line naming `swarm.explore`'s tools, or "" when the section is off or names none. */
19
25
  function exploreLine(cwd) {
20
26
  let settings;
@@ -45,7 +51,7 @@ function decideSessionStart(call) {
45
51
  }
46
52
  const explore = exploreLine(cwd);
47
53
  if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
48
- return context("SessionStart", `${REMINDER}${explore}`);
54
+ return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${explore}`);
49
55
  }
50
56
 
51
57
  /** @returns the hook output, or null when there is nothing to add for this event. */
@@ -129,3 +129,14 @@ test("hooks.json also runs the note on SubagentStart, all matchers, beside the e
129
129
  "the existing dispatch-guard.mjs SubagentStart entry stays",
130
130
  );
131
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 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.
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 { readFileSync, statSync, writeFileSync } from "node:fs";
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 { claimFileOf, claimPath, fileSafe, releasePath } from "./edit-batch-state.mjs";
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
- /** The claim file of the slot in one session folder. */
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(readFileSync(path.join(dir, SETTINGS_FILE), "utf8"));
21
- return Array.isArray(implementerTypes) && slotMinutes > 0 ? { implementerTypes, slotMinutes } : null;
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
- * 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
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
- export function claimSlot(dir, settings, now) {
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
- claimedMs = statSync(slotFile).mtimeMs;
97
+ writeFileSync(slotFileOf(dir, index), held, { flag: "wx" });
98
+ return true;
49
99
  } catch (error) {
50
- // The holder stopped between the claim and this read, so the slot is free again.
51
- if (error.code === "ENOENT") continue;
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
- /** 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) {
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)) claimPath(dir, KEY, now, settings.slotMinutes * MINUTE_MS);
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
- /** Frees the slot when an implementer stops. @returns true when the stopped agent is an implementer */
65
- export function releaseSlot(dir, agentType) {
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
- releasePath(dir, KEY);
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
  }
@@ -1,18 +1,29 @@
1
1
  import { strict as assert } from "node:assert";
2
- import { existsSync, mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from "node:fs";
2
+ import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
3
3
  import os from "node:os";
4
4
  import path from "node:path";
5
5
  import { test } from "node:test";
6
6
  import { dispatchDefaults } from "../config.mjs";
7
- import { claimSlot, reclaimSlot, releaseSlot, slotDirOf, slotFileOf } from "./dispatch-slot.mjs";
7
+ import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
8
8
 
9
- function sessionDir(t) {
9
+ function sessionDir(t, session = "s") {
10
10
  const tmp = mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-slot-"));
11
11
  t.after(() => rmSync(tmp, { recursive: true, force: true }));
12
- return slotDirOf("s", tmp);
12
+ return slotDirOf(session, tmp);
13
13
  }
14
14
 
15
15
  const settings = { ...dispatchDefaults, slotMinutes: 1 };
16
+ const withSlots = (implementerSlots) => ({ ...settings, implementerSlots });
17
+ const IMPLEMENTER = "sdd-implementer";
18
+
19
+ /** The claim files of one session folder, sorted, with no path. */
20
+ const claimFiles = (dir) => (existsSync(dir) ? readdirSync(dir).filter((name) => name.endsWith(".claim")).sort() : []);
21
+ /** What each claim file holds, sorted. */
22
+ const heldIn = (dir) => claimFiles(dir).map((name) => readFileSync(path.join(dir, name), "utf8")).sort();
23
+ const ageClaim = (dir, name, ms) => {
24
+ const old = new Date(Date.now() - ms);
25
+ utimesSync(path.join(dir, name), old, old);
26
+ };
16
27
 
17
28
  test("the slot folder is keyed on the session, with a file-safe name", () => {
18
29
  assert.equal(slotDirOf("sess/1:a", "/tmp"), path.join("/tmp", "architecture-kit", "dispatch", "sess_1_a"));
@@ -22,7 +33,8 @@ test("the first claim holds the slot, and a second claim with no stop between ge
22
33
  const dir = sessionDir(t);
23
34
  assert.equal(claimSlot(dir, settings, Date.now()), null);
24
35
  const holder = claimSlot(dir, settings, Date.now());
25
- assert.equal(holder.slotFile, slotFileOf(dir));
36
+ assert.equal(holder.slotFile, path.join(dir, claimFiles(dir)[0]));
37
+ assert.equal(holder.limit, 1);
26
38
  assert.equal(holder.expiresAt.getTime() - holder.claimedAt.getTime(), 60_000);
27
39
  });
28
40
 
@@ -30,7 +42,7 @@ test("a claim older than slotMinutes is taken over", (t) => {
30
42
  const dir = sessionDir(t);
31
43
  claimSlot(dir, settings, Date.now());
32
44
  const old = new Date(Date.now() - 120_000);
33
- utimesSync(slotFileOf(dir), old, old);
45
+ utimesSync(path.join(dir, claimFiles(dir)[0]), old, old);
34
46
  assert.equal(claimSlot(dir, settings, Date.now()), null);
35
47
  });
36
48
 
@@ -39,9 +51,9 @@ test("only an implementer's stop frees the slot, and an empty agent type frees n
39
51
  claimSlot(dir, settings, Date.now());
40
52
  assert.equal(releaseSlot(dir, ""), false);
41
53
  assert.equal(releaseSlot(dir, "architecture:sdd-reviewer"), false);
42
- assert.equal(existsSync(slotFileOf(dir)), true);
54
+ assert.equal(claimFiles(dir).length, 1);
43
55
  assert.equal(releaseSlot(dir, "architecture:sdd-implementer"), true);
44
- assert.equal(existsSync(slotFileOf(dir)), false);
56
+ assert.deepEqual(claimFiles(dir), []);
45
57
  assert.equal(claimSlot(dir, settings, Date.now()), null);
46
58
  });
47
59
 
@@ -57,7 +69,7 @@ test("a resumed implementer claims a free slot again, and a reviewer does not",
57
69
  claimSlot(dir, settings, Date.now());
58
70
  releaseSlot(dir, "sdd-implementer");
59
71
  reclaimSlot(dir, "architecture:sdd-reviewer", Date.now());
60
- assert.equal(existsSync(slotFileOf(dir)), false);
72
+ assert.deepEqual(claimFiles(dir), []);
61
73
  reclaimSlot(dir, "sdd-implementer", Date.now());
62
74
  assert.notEqual(claimSlot(dir, settings, Date.now()), null);
63
75
  });
@@ -69,12 +81,149 @@ test("a session folder with no settings, or settings that do not parse, changes
69
81
  writeFileSync(path.join(dir, "settings.json"), "not json");
70
82
  assert.equal(releaseSlot(dir, "sdd-implementer"), false);
71
83
  reclaimSlot(dir, "sdd-implementer", Date.now());
72
- assert.equal(existsSync(slotFileOf(dir)), false);
84
+ assert.deepEqual(claimFiles(dir), []);
73
85
  });
74
86
 
75
87
  test("a claim whose settings cannot be written is released, and the error reaches the caller", (t) => {
76
88
  const dir = sessionDir(t);
77
89
  mkdirSync(path.join(dir, "settings.json"), { recursive: true });
78
90
  assert.throws(() => claimSlot(dir, settings, Date.now()));
79
- assert.equal(existsSync(slotFileOf(dir)), false);
91
+ assert.deepEqual(claimFiles(dir), []);
92
+ });
93
+
94
+ test("the default limit is 1, and a second holder is refused with the limit and the first holder", (t) => {
95
+ const dir = sessionDir(t);
96
+ assert.equal(dispatchDefaults.implementerSlots, 1);
97
+ assert.equal(claimSlot(dir, settings, Date.now(), "use-1"), null);
98
+ const refused = claimSlot(dir, settings, Date.now(), "use-2");
99
+ assert.equal(refused.limit, 1);
100
+ assert.deepEqual(refused.holders.map((holder) => holder.id), ["use-1"]);
101
+ assert.deepEqual(claimFiles(dir).length, 1);
102
+ });
103
+
104
+ test("a limit of 3 holds three claims and refuses the fourth, naming the three holders", (t) => {
105
+ const dir = sessionDir(t);
106
+ for (const id of ["use-1", "use-2", "use-3"]) assert.equal(claimSlot(dir, withSlots(3), Date.now(), id), null);
107
+ const refused = claimSlot(dir, withSlots(3), Date.now(), "use-4");
108
+ assert.equal(refused.limit, 3);
109
+ assert.deepEqual(refused.holders.map((holder) => holder.id).sort(), ["use-1", "use-2", "use-3"]);
110
+ assert.equal(claimFiles(dir).length, 3);
111
+ });
112
+
113
+ test("a stop frees its own holder's claim only, so one slot opens and the others stay", (t) => {
114
+ const dir = sessionDir(t);
115
+ const three = withSlots(3);
116
+ for (const id of ["use-1", "use-2", "use-3"]) claimSlot(dir, three, Date.now(), id);
117
+ for (const id of ["agent-a", "agent-b", "agent-c"]) reclaimSlot(dir, IMPLEMENTER, Date.now(), id);
118
+ assert.equal(claimFiles(dir).length, 3);
119
+ assert.equal(releaseSlot(dir, IMPLEMENTER, "agent-b"), true);
120
+ assert.equal(claimFiles(dir).length, 2);
121
+ assert.deepEqual(heldIn(dir), ["agent:agent-a", "agent:agent-c"]);
122
+ assert.equal(claimSlot(dir, three, Date.now(), "use-4"), null);
123
+ assert.notEqual(claimSlot(dir, three, Date.now(), "use-5"), null);
124
+ });
125
+
126
+ test("a start after a dispatch binds the dispatch's claim and counts once", (t) => {
127
+ const dir = sessionDir(t);
128
+ const three = withSlots(3);
129
+ claimSlot(dir, three, Date.now(), "use-a");
130
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-a");
131
+ assert.equal(claimFiles(dir).length, 1);
132
+ assert.equal(claimSlot(dir, three, Date.now(), "use-b"), null);
133
+ assert.equal(claimSlot(dir, three, Date.now(), "use-c"), null);
134
+ assert.notEqual(claimSlot(dir, three, Date.now(), "use-d"), null);
135
+ });
136
+
137
+ test("a stop with no start before it frees one waiting claim", (t) => {
138
+ const dir = sessionDir(t);
139
+ claimSlot(dir, withSlots(2), Date.now(), "use-1");
140
+ claimSlot(dir, withSlots(2), Date.now(), "use-2");
141
+ assert.equal(releaseSlot(dir, IMPLEMENTER, "agent-x"), true);
142
+ assert.equal(claimFiles(dir).length, 1);
143
+ });
144
+
145
+ test("an expired claim frees its slot and the live claims stay", (t) => {
146
+ const dir = sessionDir(t);
147
+ const three = withSlots(3);
148
+ for (const id of ["use-1", "use-2", "use-3"]) claimSlot(dir, three, Date.now(), id);
149
+ assert.notEqual(claimSlot(dir, three, Date.now(), "use-4"), null);
150
+ ageClaim(dir, claimFiles(dir)[0], 120_000);
151
+ assert.equal(claimSlot(dir, three, Date.now(), "use-4"), null);
152
+ assert.equal(claimFiles(dir).length, 3);
153
+ });
154
+
155
+ test("the refusal names the holder that expires first", (t) => {
156
+ const dir = sessionDir(t);
157
+ const two = withSlots(2);
158
+ claimSlot(dir, two, Date.now(), "use-1");
159
+ claimSlot(dir, two, Date.now(), "use-2");
160
+ ageClaim(dir, claimFiles(dir).find((name) => readFileSync(path.join(dir, name), "utf8") === "pending:use-2"), 30_000);
161
+ const refused = claimSlot(dir, two, Date.now(), "use-3");
162
+ assert.ok(readFileSync(refused.slotFile, "utf8"), "pending:use-2");
163
+ assert.equal(refused.expiresAt.getTime() - refused.claimedAt.getTime(), 60_000);
164
+ });
165
+
166
+ test("a resumed implementer takes its own slot again while one is free, and never past the limit", (t) => {
167
+ const dir = sessionDir(t);
168
+ const two = withSlots(2);
169
+ claimSlot(dir, two, Date.now(), "use-1");
170
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-1");
171
+ releaseSlot(dir, IMPLEMENTER, "agent-1");
172
+ assert.deepEqual(claimFiles(dir), []);
173
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-1");
174
+ assert.equal(claimFiles(dir).length, 1);
175
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-1");
176
+ assert.equal(claimFiles(dir).length, 1);
177
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-2");
178
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-3");
179
+ assert.equal(claimFiles(dir).length, 2);
180
+ });
181
+
182
+ test("a claim lands in the first slot it creates: a pre-created slot-0 sends it to slot-1 at 2, and refuses it at 1", (t) => {
183
+ const dir = sessionDir(t);
184
+ mkdirSync(dir, { recursive: true });
185
+ writeFileSync(path.join(dir, "slot-0.claim"), "pending:other");
186
+ assert.equal(claimSlot(dir, withSlots(2), Date.now(), "use-1"), null);
187
+ assert.deepEqual(claimFiles(dir), ["slot-0.claim", "slot-1.claim"]);
188
+ assert.equal(readFileSync(path.join(dir, "slot-0.claim"), "utf8"), "pending:other");
189
+ assert.equal(readFileSync(path.join(dir, "slot-1.claim"), "utf8"), "pending:use-1");
190
+
191
+ const one = sessionDir(t, "one");
192
+ mkdirSync(one, { recursive: true });
193
+ writeFileSync(path.join(one, "slot-0.claim"), "pending:other");
194
+ const refused = claimSlot(one, withSlots(1), Date.now(), "use-1");
195
+ assert.deepEqual(refused.holders.map((holder) => holder.id), ["other"]);
196
+ assert.deepEqual(claimFiles(one), ["slot-0.claim"]);
197
+ });
198
+
199
+ test("every slot pre-created means the claim is refused and no file changes", (t) => {
200
+ const dir = sessionDir(t);
201
+ mkdirSync(dir, { recursive: true });
202
+ for (const index of [0, 1, 2]) writeFileSync(path.join(dir, `slot-${index}.claim`), `agent:a${index}`);
203
+ const refused = claimSlot(dir, withSlots(3), Date.now(), "use-1");
204
+ assert.equal(refused.limit, 3);
205
+ assert.deepEqual(heldIn(dir), ["agent:a0", "agent:a1", "agent:a2"]);
206
+ });
207
+
208
+ test("a repeat of one holder's claim leaves its slot alone and takes no second slot", (t) => {
209
+ const dir = sessionDir(t);
210
+ const three = withSlots(3);
211
+ assert.equal(claimSlot(dir, three, Date.now(), "use-1"), null);
212
+ ageClaim(dir, "slot-0.claim", 10_000);
213
+ const aged = statSync(path.join(dir, "slot-0.claim")).mtimeMs;
214
+ assert.equal(claimSlot(dir, three, Date.now(), "use-1"), null);
215
+ assert.equal(statSync(path.join(dir, "slot-0.claim")).mtimeMs, aged);
216
+ assert.deepEqual(claimFiles(dir), ["slot-0.claim"]);
217
+ });
218
+
219
+ test("the stop and the start read the limit recorded at the claim, and a record with no limit means 1", (t) => {
220
+ const dir = sessionDir(t);
221
+ claimSlot(dir, withSlots(2), Date.now(), "use-1");
222
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-1");
223
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-2");
224
+ assert.equal(claimFiles(dir).length, 2);
225
+ const { implementerTypes, slotMinutes } = settings;
226
+ writeFileSync(path.join(dir, "settings.json"), JSON.stringify({ implementerTypes, slotMinutes }));
227
+ reclaimSlot(dir, IMPLEMENTER, Date.now(), "agent-3");
228
+ assert.equal(claimFiles(dir).length, 2);
80
229
  });
@@ -40,15 +40,21 @@ export function dispatchSettings(swarm = {}) {
40
40
  if (typeof raw !== "object" || Array.isArray(raw)) {
41
41
  throw new Error(`${KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
42
42
  }
43
- const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, models } = merge(dispatchDefaults, raw);
43
+ const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models } = merge(
44
+ dispatchDefaults,
45
+ raw,
46
+ );
44
47
  if (!isNameList(allowedTypes)) throw wrong("allowedTypes", allowedTypes, "a list of agent types");
45
48
  if (!isNameList(implementerTypes)) throw wrong("implementerTypes", implementerTypes, "a list of agent types");
46
49
  if (!Number.isInteger(maxPromptChars) || maxPromptChars < 1) {
47
50
  throw wrong("maxPromptChars", maxPromptChars, "a positive whole number");
48
51
  }
49
52
  if (typeof slotMinutes !== "number" || !(slotMinutes > 0)) throw wrong("slotMinutes", slotMinutes, "a positive number");
53
+ if (!Number.isInteger(implementerSlots) || implementerSlots < 1) {
54
+ throw wrong("implementerSlots", implementerSlots, "a positive whole number");
55
+ }
50
56
  checkModels(models);
51
- return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, models };
57
+ return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models };
52
58
  }
53
59
 
54
60
  /** @returns the settings of the checkout that holds `cwd`, or null when it has no config or no section. */
@@ -151,11 +157,20 @@ export function dispatchRefusal(input, settings) {
151
157
  return null;
152
158
  }
153
159
 
154
- /** The reason a second implementer waits, with the two ways the slot frees. */
155
- export function slotRefusal({ type, claimedAt, expiresAt, slotFile }) {
160
+ /** The reason an implementer over the limit waits, with the two ways a slot frees. */
161
+ export function slotRefusal({ type, claimedAt, expiresAt, slotFile, limit = 1, holders = [] }) {
162
+ const frees = `If no implementer runs, because its dispatch was denied after this hook, delete ${slotFile}.`;
163
+ if (limit === 1) {
164
+ return (
165
+ `Dispatch guard: an implementer holds the one implementer slot of this session since ${claimedAt.toISOString()}. ` +
166
+ `Wait for it to stop, then dispatch ${type}. The slot frees when it stops, or at ${expiresAt.toISOString()}. ` +
167
+ frees
168
+ );
169
+ }
170
+ const named = holders.map((holder) => `${holder.id} (since ${holder.claimedAt.toISOString()})`).join(", ");
156
171
  return (
157
- `Dispatch guard: an implementer holds the one implementer slot of this session since ${claimedAt.toISOString()}. ` +
158
- `Wait for it to stop, then dispatch ${type}. The slot frees when it stops, or at ${expiresAt.toISOString()}. ` +
159
- `If no implementer runs, because its dispatch was denied after this hook, delete ${slotFile}.`
172
+ `Dispatch guard: all ${limit} implementer slots of this session are held, by ${named}. ` +
173
+ `Wait for one to stop, then dispatch ${type}. A slot frees when its holder stops, and by ${expiresAt.toISOString()} at the latest. ` +
174
+ frees
160
175
  );
161
176
  }
@@ -28,6 +28,11 @@ test("a wrong value names its key", () => {
28
28
  [{ implementerTypes: [""] }, /swarm\.dispatch\.implementerTypes/],
29
29
  [{ maxPromptChars: 0 }, /swarm\.dispatch\.maxPromptChars/],
30
30
  [{ slotMinutes: -1 }, /swarm\.dispatch\.slotMinutes/],
31
+ [{ implementerSlots: 0 }, /swarm\.dispatch\.implementerSlots/],
32
+ [{ implementerSlots: -1 }, /swarm\.dispatch\.implementerSlots/],
33
+ [{ implementerSlots: 1.5 }, /swarm\.dispatch\.implementerSlots/],
34
+ [{ implementerSlots: "2" }, /swarm\.dispatch\.implementerSlots/],
35
+ [{ implementerSlots: null }, /swarm\.dispatch\.implementerSlots/],
31
36
  [{ models: "opus" }, /swarm\.dispatch\.models\b/],
32
37
  [{ models: ["opus"] }, /swarm\.dispatch\.models\b/],
33
38
  [{ models: { "sdd-planner": [] } }, /swarm\.dispatch\.models\.sdd-planner/],
@@ -152,3 +157,38 @@ test("the slot refusal names the expiry and the file that frees the slot", () =>
152
157
  assert.match(reason, /1970-01-01T01:00:00\.000Z/);
153
158
  assert.match(reason, /delete \/tmp\/slot\.claim/);
154
159
  });
160
+
161
+ test("implementerSlots defaults to 1, and a repository sets a whole number", () => {
162
+ assert.equal(dispatchSettings({ dispatch: {} }).implementerSlots, 1);
163
+ assert.equal(dispatchSettings({ dispatch: { implementerSlots: 3 } }).implementerSlots, 3);
164
+ });
165
+
166
+ test("a refusal over a limit above 1 names the limit and each holder, and one at 1 keeps its text", () => {
167
+ const holders = [
168
+ { id: "use-1", file: "/tmp/pending-use-1.claim", claimedAt: new Date(0) },
169
+ { id: "agent-2", file: "/tmp/agent-agent-2.claim", claimedAt: new Date(1000) },
170
+ ];
171
+ const reason = slotRefusal({
172
+ type: "sdd-implementer",
173
+ claimedAt: new Date(0),
174
+ expiresAt: new Date(3_600_000),
175
+ slotFile: "/tmp/pending-use-1.claim",
176
+ limit: 2,
177
+ holders,
178
+ });
179
+ assert.match(reason, /all 2 implementer slots/);
180
+ assert.match(reason, /use-1/);
181
+ assert.match(reason, /agent-2/);
182
+ assert.match(reason, /1970-01-01T01:00:00\.000Z/);
183
+ assert.match(reason, /delete \/tmp\/pending-use-1\.claim/);
184
+ const one = slotRefusal({
185
+ type: "sdd-implementer",
186
+ claimedAt: new Date(0),
187
+ expiresAt: new Date(3_600_000),
188
+ slotFile: "/tmp/slot.claim",
189
+ limit: 1,
190
+ holders: holders.slice(0, 1),
191
+ });
192
+ assert.match(one, /holds the one implementer slot/);
193
+ assert.doesNotMatch(one, /use-1/);
194
+ });
package/src/config.mjs CHANGED
@@ -425,12 +425,14 @@ export const dispatchDefaults = {
425
425
  "architecture:sdd-reviewer",
426
426
  "architecture:sdd-branch-reviewer",
427
427
  ],
428
- // Types that share one slot per session.
428
+ // Types that share the slots of a session.
429
429
  implementerTypes: ["sdd-implementer", "architecture:sdd-implementer"],
430
430
  // The longest prompt, in characters. A brief belongs in a file.
431
431
  maxPromptChars: 12000,
432
432
  // A slot with no stop expires after this many minutes.
433
433
  slotMinutes: 60,
434
+ // How many implementers run at once in a session. Each needs paths of its own, and a worktree.
435
+ implementerSlots: 1,
434
436
  // The model families each type's named `model` may carry. `"*"` covers every other type.
435
437
  models: {
436
438
  "sdd-planner": ["opus"],