architecture-harness 0.20.1 → 0.20.3

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.20.1",
3
+ "version": "0.20.3",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -117,12 +117,15 @@ function worktreeAddPath(args) {
117
117
  return null;
118
118
  }
119
119
 
120
- /** A path as a shell resolves it from `cwd`. PowerShell also reads a backslash as a separator on Linux and macOS. */
121
- function resolveFrom(cwd, spelled, parse) {
120
+ /** A path as the shell spells it, in the form of this platform. PowerShell also reads a backslash as a separator on Linux and macOS. */
121
+ function spelledPath(spelled, parse) {
122
122
  const word = parse === powershellSegments ? spelled.replace(/\\/g, "/") : spelled;
123
- return path.resolve(cwd, nativePath(word.replace(/^~(?=$|[\\/])/, os.homedir())));
123
+ return nativePath(word.replace(/^~(?=$|[\\/])/, os.homedir()));
124
124
  }
125
125
 
126
+ /** A path as a shell resolves it from `cwd`. */
127
+ const resolveFrom = (cwd, spelled, parse) => path.resolve(cwd, spelledPath(spelled, parse));
128
+
126
129
  /** True when `target` is one folder directly under `folder`, as `qc worktree add` makes it. */
127
130
  function inFolder(folder, target) {
128
131
  const parts = path.relative(keyOf(folder), keyOf(target)).split(path.sep);
@@ -138,16 +141,35 @@ const REASONS = {
138
141
  script:
139
142
  "a hand run of a hook script writes a lease or a ledger record under a made-up session id, and that lease blocks later " +
140
143
  "edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
144
+ explicitDir:
145
+ "`--git-dir`, `GIT_DIR`, `--work-tree`, and `GIT_WORK_TREE` make git read the repository from a path it resolves after every `-C`, " +
146
+ "so this guard cannot tell which repository gets the worktree. Run `git worktree add` from inside the target repository instead: " +
147
+ "use `-C <repository>`, `cd <repository>`, or `Set-Location <repository>`, and drop the git directory and work tree settings.",
141
148
  worktree:
142
149
  "a worktree lives in the worktree folder of the main checkout, so git ignores it and `qc worktree remove` finds it. " +
143
150
  "Run `npx qc worktree add <name> <branch>` from the repository, or give `git worktree add` a path one level under that folder.",
144
151
  };
145
152
 
146
153
  /**
147
- * @param {{cwd: string, folder: string} | null} [place] the working directory and the worktree folder; null skips the worktree rule
154
+ * The worktree folder that judges `git worktree add`: the one of the repository the command targets. A `cd`,
155
+ * `Set-Location`, or `-C` into a repository names it, and else the session's own
156
+ * repository does. The path that `add` names never decides, because git adds the worktree to the repository
157
+ * of the working directory wherever the path is. `null` means the targeted repository is not guarded.
158
+ */
159
+ function folderFor(place, from) {
160
+ // `undefined` means no checkout holds `from`, and `null` means one does that is not guarded.
161
+ const worked = place.folderAt(from);
162
+ return worked === undefined ? place.folder : worked;
163
+ }
164
+
165
+ /**
166
+ * @param {{cwd: string, folder: string, folderAt: (dir: string) => string | null | undefined} | null} [place] the working directory,
167
+ * the session's worktree folder, and the folder of the repository that holds a directory (`undefined` when none does, `null` when
168
+ * it is not guarded); null skips the worktree rule
169
+ * @param {string[]} [refused] receives the folder of each refused worktree path
148
170
  * @returns the reasons the command breaks a rule, in a stable order.
149
171
  */
150
- export function violations(command, parse = segmentsOf, place = null) {
172
+ export function violations(command, parse = segmentsOf, place = null, refused = []) {
151
173
  const segments = parse(command);
152
174
  const found = new Set();
153
175
  let cwd = place?.cwd;
@@ -158,17 +180,29 @@ export function violations(command, parse = segmentsOf, place = null) {
158
180
  if (git && skipsHooks(git)) found.add("hooks");
159
181
  if (git && setsHooksPath(git)) found.add("hooksPath");
160
182
  const added = place && git?.sub === "worktree" ? worktreeAddPath(git.args) : null;
161
- if (added !== null) {
183
+ if (added !== null && git.explicitDir) {
184
+ // The session is guarded, because `place` exists only then.
185
+ found.add("explicitDir");
186
+ } else if (added !== null) {
162
187
  const from = git.dirs.filter(Boolean).reduce((dir, next) => resolveFrom(dir, next, parse), cwd);
163
- if (!inFolder(place.folder, resolveFrom(from, added, parse))) found.add("worktree");
188
+ const folder = folderFor(place, from);
189
+ if (folder !== null && !inFolder(folder, resolveFrom(from, added, parse))) {
190
+ found.add("worktree");
191
+ refused.push(folder);
192
+ }
164
193
  }
165
194
  const nested = nestedCommand(segment);
166
- if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd })) found.add(key);
195
+ if (nested) for (const key of violations(nested.command, nested.parse, place && { ...place, cwd }, refused)) found.add(key);
167
196
  }
168
197
  if (!segments.some(runsTests) && segments.some(runsHookScript)) found.add("script");
169
198
  return Object.keys(REASONS).filter((key) => found.has(key));
170
199
  }
171
200
 
201
+ /** The worktree folder of the repository that holds `dir`: undefined when none does, null when it has no config or turns the rule off. */
202
+ function folderAt(dir) {
203
+ return checkoutRootOf(dir) === null ? undefined : (worktreeRuleAt(dir)?.folder ?? null);
204
+ }
205
+
172
206
  /** The verdict on one Bash or PowerShell call. @returns the hook output, or null to let the call run with no message. */
173
207
  export function decide(call) {
174
208
  const command = call.tool_input?.command;
@@ -179,9 +213,11 @@ export function decide(call) {
179
213
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
180
214
  // The config is read only for a command that can add a worktree, so every other call stays cheap.
181
215
  const rule = /\bworktree\b/i.test(command) ? worktreeRuleAt(cwd) : null;
182
- const found = violations(command, parse, rule && { cwd: path.resolve(cwd), folder: rule.folder });
216
+ const refused = [];
217
+ const place = rule && { cwd: path.resolve(cwd), folder: rule.folder, folderAt };
218
+ const found = violations(command, parse, place, refused);
183
219
  if (found.length === 0) return null;
184
- const reasonOf = (key) => (key === "worktree" ? `${REASONS.worktree} The folder is ${rule.folder}.` : REASONS[key]);
220
+ const reasonOf = (key) => (key === "worktree" ? `${REASONS.worktree} The folder is ${[...new Set(refused)].join(" or ")}.` : REASONS[key]);
185
221
  return {
186
222
  hookSpecificOutput: {
187
223
  hookEventName: "PreToolUse",
@@ -234,3 +234,122 @@ test("inside a linked worktree, the folder is the main checkout's", (t) => {
234
234
  assert.equal(decide(bash(linked, "git worktree add ../x")), null);
235
235
  assert.ok(outsideFolder(decide(bash(linked, "git worktree add x"))), "a worktree nested in a worktree is refused");
236
236
  });
237
+
238
+ /** The adopted checkout plus a second adopted checkout, `kit`, and a checkout with no config. Forward slashes, as a Bash command spells a path. */
239
+ function twoRepos(t) {
240
+ const ws = workspace(t);
241
+ const kit = path.join(path.dirname(ws.adopted), "kit");
242
+ mkdirSync(kit);
243
+ execFileSync("git", ["init", "-q"], { cwd: kit, stdio: "pipe" });
244
+ writeFileSync(path.join(kit, "qc.config.json"), "{}");
245
+ return { ...ws, kit, slash: (dir) => dir.replaceAll("\\", "/") };
246
+ }
247
+
248
+ test("a worktree add judges the repository the command targets, through -C, cd, or Set-Location", (t) => {
249
+ const ws = twoRepos(t);
250
+ const kit = ws.slash(ws.kit);
251
+ for (const command of [
252
+ `git -C ${kit} worktree add ${kit}/.worktree/x -b feat/x`,
253
+ `git -C ${kit} worktree add .worktree/x`,
254
+ `cd ${kit} && git worktree add .worktree/x`,
255
+ `cd ${kit} && git worktree add ${kit}/.worktree/x`,
256
+ `bash -c 'cd ${kit} && git worktree add .worktree/x'`,
257
+ ]) {
258
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
259
+ }
260
+ for (const command of [`Set-Location ${kit}; git worktree add .worktree/x`, `Set-Location ${kit}; git worktree add ${kit}/.worktree/x`, `git -C ${kit} worktree add .worktree/x`]) {
261
+ assert.equal(decide(powershell(ws.adopted, command)), null, command);
262
+ }
263
+ });
264
+
265
+ test("a worktree add in the targeted repository is still held to that repository's folder, and the deny names it", (t) => {
266
+ const ws = twoRepos(t);
267
+ const kit = ws.slash(ws.kit);
268
+ for (const command of [`git -C ${kit} worktree add ../x`, `git -C ${kit} worktree add ${ws.slash(ws.adopted)}/.worktree/x`, `cd ${kit} && git worktree add x`]) {
269
+ const reason = reasonOf(decide(bash(ws.adopted, command))) ?? "";
270
+ assert.match(reason, /npx qc worktree add <name> <branch>/, command);
271
+ assert.ok(reason.includes(`The folder is ${path.join(ws.kit, ".worktree")}.`), `${command}: ${reason}`);
272
+ }
273
+ });
274
+
275
+ test("an absolute worktree path alone does not name the repository: git adds to the session's repository", (t) => {
276
+ const ws = twoRepos(t);
277
+ const kit = ws.slash(ws.kit);
278
+ for (const command of [`git worktree add ${kit}/.worktree/x`, `git worktree add ${kit}/x`, `git worktree add ../x`]) {
279
+ const reason = reasonOf(decide(bash(ws.adopted, command))) ?? "";
280
+ assert.ok(reason.includes(`The folder is ${path.join(ws.adopted, ".worktree")}.`), `${command}: ${reason}`);
281
+ }
282
+ assert.equal(decide(bash(ws.adopted, `git worktree add ${ws.slash(ws.adopted)}/.worktree/x`)), null);
283
+ });
284
+
285
+ /** The refusal for an explicit git directory or work tree: it says to run `git worktree add` from inside the target repository. */
286
+ const explicitDirReason = (output) => {
287
+ const reason = reasonOf(output) ?? "";
288
+ assert.match(reason, /--git-dir|GIT_DIR|--work-tree|GIT_WORK_TREE/, reason);
289
+ assert.match(reason, /from inside the target repository/, reason);
290
+ assert.match(reason, /-C/, reason);
291
+ return reason;
292
+ };
293
+
294
+ test("a worktree add with --git-dir, GIT_DIR, --work-tree, or GIT_WORK_TREE is refused from a guarded session", (t) => {
295
+ const ws = twoRepos(t);
296
+ const kit = ws.slash(ws.kit);
297
+ const plain = ws.slash(ws.plain);
298
+ const adopted = ws.slash(ws.adopted);
299
+ for (const command of [
300
+ `git --git-dir=${kit}/.git worktree add ${kit}/.worktree/x`,
301
+ `git --git-dir ${kit}/.git worktree add ${kit}/.worktree/x`,
302
+ `GIT_DIR=${kit}/.git git worktree add ${kit}/.worktree/x`,
303
+ `git -C ${kit} --git-dir=${kit}/.git worktree add .worktree/x`,
304
+ `git -C ${plain} --git-dir=${kit}/.git worktree add ${kit}/.worktree/x`,
305
+ `git --git-dir=${kit}/.git worktree add ../x`,
306
+ `GIT_DIR=${kit}/.git git worktree add ../x`,
307
+ `git --git-dir=${kit}/.git worktree add .worktree/x`,
308
+ `GIT_DIR=${kit}/.git git worktree add .worktree/x`,
309
+ `cd ${plain} && git --git-dir=${kit}/.git worktree add .worktree/x`,
310
+ `git -C ${plain} --git-dir=${adopted}/.git worktree add ../x`,
311
+ `git --git-dir=${plain}/.git worktree add ../x`,
312
+ `git --git-dir=${adopted}/.git worktree add ${adopted}/.worktree/x`,
313
+ `env GIT_DIR=${kit}/.git git worktree add ../x`,
314
+ `bash -c 'git --git-dir=${kit}/.git worktree add ../x'`,
315
+ `git --work-tree=${plain} worktree add ../x`,
316
+ `git --work-tree ${plain} worktree add ../x`,
317
+ `GIT_WORK_TREE=${plain} git worktree add ../x`,
318
+ `git --work-tree=${kit} worktree add ../x`,
319
+ `GIT_WORK_TREE=${kit} git worktree add ../x`,
320
+ `git --work-tree=${plain} worktree add .worktree/x`,
321
+ ]) {
322
+ explicitDirReason(decide(bash(ws.adopted, command)));
323
+ }
324
+ explicitDirReason(decide(powershell(ws.adopted, `git --git-dir=${kit}/.git worktree add ../x`)));
325
+ });
326
+
327
+ test("git resolves a relative git dir from the working directory after every -C, so these probes are refused", (t) => {
328
+ const ws = twoRepos(t);
329
+ const adopted = ws.slash(ws.adopted);
330
+ const plain = ws.slash(ws.plain);
331
+ // Real git adds ../x1 as a worktree of `adopted` from these.
332
+ for (const command of [
333
+ `cd ${plain} && git --git-dir=.git -C ${adopted} worktree add ../x1`,
334
+ `cd ${plain} && GIT_DIR=.git git -C ${adopted} worktree add ../x1`,
335
+ ]) {
336
+ explicitDirReason(decide(bash(ws.adopted, command)));
337
+ }
338
+ });
339
+
340
+ test("an explicit git dir on a command other than worktree add is not refused by the worktree rule", (t) => {
341
+ const ws = twoRepos(t);
342
+ const kit = ws.slash(ws.kit);
343
+ for (const command of [`git --git-dir=${kit}/.git status`, `git --git-dir=${kit}/.git worktree list`, `GIT_DIR=${kit}/.git git log`]) {
344
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
345
+ }
346
+ });
347
+
348
+ test("a worktree add in a repository with no qc.config.json is not guarded", (t) => {
349
+ const ws = twoRepos(t);
350
+ const plain = ws.slash(ws.plain);
351
+ for (const command of [`git -C ${plain} worktree add ../x`, `cd ${plain} && git worktree add ../x`]) {
352
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
353
+ }
354
+ assert.equal(decide(bash(ws.plain, "git worktree add ../x")), null, "a session in it is not guarded either");
355
+ });
@@ -0,0 +1,46 @@
1
+ // The CI state of a commit, read from its GitHub check runs. The task gate asks it before a review: a
2
+ // head whose CI is not green changes before it is reviewed, so the review waits.
3
+
4
+ import { runGh } from "./gh-run.mjs";
5
+ import { originOf } from "./git-read.mjs";
6
+
7
+ // The hook that asks has a 10 second limit, and a hook that the limit kills lets the call through. The two reads
8
+ // together stay well under it, so a slow gh leaves the head unknown and the review refusal stands.
9
+ const GH_TIMEOUT_MS = 3_000;
10
+ const ORIGIN_TIMEOUT_MS = 1_000;
11
+ const FAILED = new Set(["failure", "cancelled", "timed_out", "action_required"]);
12
+ const short = (sha) => sha.slice(0, 7);
13
+
14
+ /**
15
+ * @param runs the `check_runs` array of the GitHub API
16
+ * @returns why the head is not green, naming the run, or null when every run completed without a failure
17
+ * or when there are no runs, because a head with no CI is unknown.
18
+ */
19
+ export function notGreenReason(runs) {
20
+ const failed = runs.find((entry) => entry.status === "completed" && FAILED.has(entry.conclusion));
21
+ if (failed) return `${failed.name} ended ${failed.conclusion}`;
22
+ const open = runs.find((entry) => entry.status !== "completed");
23
+ return open ? `${open.name} is ${open.status}` : null;
24
+ }
25
+
26
+ /**
27
+ * @returns the reason CI on `sha` is not green, as `CI on <short sha>: <why>`, or null when it is green or
28
+ * unknown: gh fails, times out, answers with no check runs, or the checkout has no `origin`.
29
+ * `gh` and `origin` replace the real reads, for a test.
30
+ */
31
+ export function ciNotGreen(sha, cwd, { gh = runGh, origin = originOf } = {}) {
32
+ if (typeof sha !== "string" || sha === "") return null;
33
+ const repo = origin(cwd, ORIGIN_TIMEOUT_MS);
34
+ if (repo === null) return null;
35
+ const out = gh(["api", `repos/${repo}/commits/${sha}/check-runs?per_page=100`], { cwd, timeoutMs: GH_TIMEOUT_MS });
36
+ if (out === null) return null;
37
+ let runs;
38
+ try {
39
+ runs = JSON.parse(out)?.check_runs;
40
+ } catch {
41
+ return null;
42
+ }
43
+ if (!Array.isArray(runs)) return null;
44
+ const why = notGreenReason(runs);
45
+ return why === null ? null : `CI on ${short(sha)}: ${why}`;
46
+ }
@@ -0,0 +1,62 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { test } from "node:test";
3
+ import { ciNotGreen, notGreenReason } from "./ci-state.mjs";
4
+
5
+ const SHA = "a".repeat(40);
6
+ const run = (name, status, conclusion = null) => ({ name, status, conclusion });
7
+ const reply = (...runs) => JSON.stringify({ total_count: runs.length, check_runs: runs });
8
+
9
+ test("a head whose check runs all completed green is green", () => {
10
+ assert.equal(notGreenReason([run("lint", "completed", "success"), run("docs", "completed", "skipped"), run("x", "completed", "neutral")]), null);
11
+ });
12
+
13
+ test("each failing conclusion makes the head not green, and the reason names the run", () => {
14
+ for (const conclusion of ["failure", "cancelled", "timed_out", "action_required"]) {
15
+ assert.match(notGreenReason([run("ok", "completed", "success"), run("build", "completed", conclusion)]) ?? "", new RegExp(`build.*${conclusion}`));
16
+ }
17
+ });
18
+
19
+ test("a run that has not completed makes the head not green", () => {
20
+ for (const status of ["queued", "in_progress", "waiting", "pending"]) {
21
+ assert.match(notGreenReason([run("build", status)]) ?? "", new RegExp(`build.*${status}`));
22
+ }
23
+ });
24
+
25
+ test("a head with no check runs is unknown, not red", () => {
26
+ assert.equal(notGreenReason([]), null);
27
+ });
28
+
29
+ test("ciNotGreen reads the check runs of the sha from the repository of origin", () => {
30
+ const calls = [];
31
+ const gh = (args, options) => {
32
+ calls.push({ args, options });
33
+ return reply(run("build", "completed", "failure"));
34
+ };
35
+ const reason = ciNotGreen(SHA, "/checkout", { gh, origin: () => "o/r" });
36
+ assert.match(reason ?? "", /^CI on aaaaaaa:.*build.*failure/);
37
+ assert.equal(calls.length, 1);
38
+ assert.equal(calls[0].args[0], "api");
39
+ assert.ok(calls[0].args[1].startsWith(`repos/o/r/commits/${SHA}/check-runs`));
40
+ assert.equal(calls[0].options.cwd, "/checkout");
41
+ });
42
+
43
+ test("ciNotGreen is null when the head is green, gh fails, the reply is not JSON, or origin is unknown", () => {
44
+ const origin = () => "o/r";
45
+ assert.equal(ciNotGreen(SHA, "/c", { gh: () => reply(run("a", "completed", "success")), origin }), null);
46
+ assert.equal(ciNotGreen(SHA, "/c", { gh: () => null, origin }), null);
47
+ assert.equal(ciNotGreen(SHA, "/c", { gh: () => "not json", origin }), null);
48
+ assert.equal(ciNotGreen(SHA, "/c", { gh: () => "{}", origin }), null);
49
+ assert.equal(ciNotGreen(SHA, "/c", { gh: () => reply(run("a", "completed", "failure")), origin: () => null }), null);
50
+ assert.equal(ciNotGreen(null, "/c", { gh: () => reply(run("a", "completed", "failure")), origin }), null);
51
+ });
52
+
53
+ test("ciNotGreen bounds its reads so the whole gate stays under the hook's 10 second limit", () => {
54
+ let ghOptions;
55
+ let originTimeout;
56
+ const gh = (_args, options) => ((ghOptions = options), null);
57
+ const origin = (_cwd, timeoutMs) => ((originTimeout = timeoutMs), "o/r");
58
+ assert.equal(ciNotGreen(SHA, "/c", { gh, origin }), null, "a gh that timed out leaves the head unknown, so the review refusal stands");
59
+ assert.ok(ghOptions.timeoutMs > 0 && ghOptions.timeoutMs <= 3000, `gh timeout ${ghOptions.timeoutMs}`);
60
+ assert.ok(originTimeout > 0 && originTimeout <= 1000, `origin timeout ${originTimeout}`);
61
+ assert.ok(ghOptions.timeoutMs + originTimeout < 5000);
62
+ });
@@ -11,6 +11,9 @@ const GUARD = fileURLToPath(new URL("./dispatch-guard.mjs", import.meta.url));
11
11
  const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
12
12
 
13
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
+ // The guard process below runs under Codex, whatever runtime runs the test.
15
+ process.env.QC_RUNTIME = "codex";
16
+
14
17
  function workspace(t, dispatch = { maxPromptChars: 80 }) {
15
18
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-dispatch-")));
16
19
  t.after(() => rmSync(base, { recursive: true, force: true }));
@@ -178,6 +181,19 @@ test("the hook runs as its own process and prints its refusal as JSON", (t) => {
178
181
  assert.match(reasonOf(JSON.parse(result.stdout)) ?? "", /names no model/);
179
182
  });
180
183
 
184
+ test("a hook process under Claude Code sees only CLAUDE_PROJECT_DIR, and still refuses a role dispatch with no model", (t) => {
185
+ const ws = workspace(t);
186
+ const { QC_RUNTIME, CLAUDECODE, ...inherited } = process.env;
187
+ const env = Object.fromEntries(Object.entries(inherited).filter(([key]) => !key.startsWith("CODEX_")));
188
+ const result = spawnSync(process.execPath, [GUARD], {
189
+ input: JSON.stringify(agentCall(ws.on, implementer)),
190
+ env: { ...env, CLAUDE_PROJECT_DIR: ws.on, TEMP: ws.tmp, TMP: ws.tmp, TMPDIR: ws.tmp },
191
+ encoding: "utf8",
192
+ });
193
+ assert.equal(result.status, 0, result.stderr);
194
+ assert.match(reasonOf(JSON.parse(result.stdout)) ?? "", /inherits the session's model.*Pass `model` with sonnet/);
195
+ });
196
+
181
197
  test("hooks.json runs the guard on Agent, SubagentStart and SubagentStop", () => {
182
198
  const { hooks } = JSON.parse(readFileSync(HOOKS, "utf8"));
183
199
  const matchersOf = (entries) =>
@@ -10,10 +10,22 @@ export const REMINDER =
10
10
  "Subagent workflow (swarm.dispatch in qc.config.json): run a plan with superpowers:subagent-driven-development. " +
11
11
  "Dispatch architecture:sdd-planner to write a plan, architecture:sdd-implementer for one task, and " +
12
12
  "architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
13
- "whole branch. All four roles default to gpt-6.1-sol with high reasoning effort. " +
14
- "Run one implementer at a time: a hook refuses a second while one runs. Name a model on any other dispatch, and " +
13
+ "whole branch. " +
14
+ "Run one implementer at a time: a hook refuses a second. Name a model on any other dispatch, and " +
15
15
  "pass each brief as a file path. Name the worktree on a prompt line `Worktree: <path>`. A reviewer starts with " +
16
- "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`.";
16
+ "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`. " +
17
+ "Review a head only once CI on it is green: fix a CI failure first. After an APPROVED review, review each fix round " +
18
+ "once, by its increment: add `Reviewed: <sha>`.";
19
+
20
+ const ROLES = ["sdd-planner", "sdd-implementer", "sdd-reviewer", "sdd-branch-reviewer"];
21
+
22
+ /** One added line naming each role's models for the session's runtime, so a dispatch names the right one. */
23
+ export function modelsLine({ models, runtime }) {
24
+ const roles = ROLES.map((role) => `${role} ${(models[`architecture:${role}`] ?? models[role] ?? models["*"] ?? ["the session's model"]).join(" or ")}`);
25
+ const how = runtime === "claude" ? "Name that model on each dispatch: the guard refuses a role dispatch with no model." : "A role with no named model inherits the session's.";
26
+ const where = runtime ? `the ${runtime} runtime` : "an unknown runtime (set QC_RUNTIME to claude or codex)";
27
+ return ` Models for ${where}: ${roles.join(", ")}. ${how}`;
28
+ }
17
29
 
18
30
  const context = (eventName, text) => ({ hookSpecificOutput: { hookEventName: eventName, additionalContext: text } });
19
31
 
@@ -81,7 +93,7 @@ function decideSessionStart(call) {
81
93
  }
82
94
  const explore = exploreLine(cwd);
83
95
  if (!dispatch) return explore === "" ? null : context("SessionStart", explore.trim());
84
- return context("SessionStart", `${REMINDER}${slotsLine(dispatch)}${directLine(cwd)}${explore}`);
96
+ return context("SessionStart", `${REMINDER}${modelsLine(dispatch)}${slotsLine(dispatch)}${directLine(cwd)}${explore}`);
85
97
  }
86
98
 
87
99
  /** @returns the hook output, or null when there is nothing to add for this event. */
@@ -5,7 +5,12 @@ import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { test } from "node:test";
7
7
  import { fileURLToPath } from "node:url";
8
- import { REMINDER, decide } from "./dispatch-reminder.mjs";
8
+ import { runtimeModels } from "../config.mjs";
9
+ import { REMINDER, decide, modelsLine } from "./dispatch-reminder.mjs";
10
+
11
+ // The checkouts below run under Codex, whatever runtime runs the test.
12
+ process.env.QC_RUNTIME = "codex";
13
+ const BASE = `${REMINDER}${modelsLine({ models: runtimeModels.codex, runtime: "codex" })}`;
9
14
 
10
15
  const NOTE = fileURLToPath(new URL("./dispatch-reminder.mjs", import.meta.url));
11
16
  const HOOKS = fileURLToPath(new URL("../../../../hooks/hooks.json", import.meta.url));
@@ -37,11 +42,11 @@ test("with the section on, every start adds the note, a compaction included", (t
37
42
  for (const source of ["startup", "resume", "clear", "compact", "fork"]) {
38
43
  const output = decide(start(on, source));
39
44
  assert.equal(output.hookSpecificOutput.hookEventName, "SessionStart", source);
40
- assert.equal(output.hookSpecificOutput.additionalContext, REMINDER, source);
45
+ assert.equal(output.hookSpecificOutput.additionalContext, BASE, source);
41
46
  }
42
47
  });
43
48
 
44
- test("the note names the workflow, the four types, the model tiers, and the one-implementer rule, in a short text", () => {
49
+ test("the note names the workflow, the four types, and the one-implementer rule, in a short text", () => {
45
50
  for (const word of [
46
51
  "superpowers:subagent-driven-development",
47
52
  "architecture:sdd-planner",
@@ -49,8 +54,6 @@ test("the note names the workflow, the four types, the model tiers, and the one-
49
54
  "architecture:sdd-reviewer",
50
55
  "architecture:sdd-branch-reviewer",
51
56
  "one implementer at a time",
52
- "gpt-6.1-sol",
53
- "high reasoning effort",
54
57
  "Worktree: <path>",
55
58
  "VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>",
56
59
  "--match-head-commit <sha>",
@@ -60,23 +63,34 @@ test("the note names the workflow, the four types, the model tiers, and the one-
60
63
  assert.ok(REMINDER.length < 800, `${REMINDER.length} characters`);
61
64
  });
62
65
 
66
+ test("the note says to review a green head only, to fix CI first, and to review a fix round by its increment", () => {
67
+ for (const phrase of [
68
+ /only once CI on it is green/,
69
+ /fix a CI failure first/,
70
+ /`Reviewed: <sha>`/,
71
+ /review each fix round once, by its increment/,
72
+ ]) {
73
+ assert.match(REMINDER, phrase);
74
+ }
75
+ });
76
+
63
77
  test("with swarm.explore also on, the note names its tools", (t) => {
64
78
  const [on] = checkouts(t, [
65
79
  { swarm: { dispatch: {}, explore: { tools: [{ name: "CocoIndex", use: "u", how: "h" }, { name: "GitNexus", use: "u", how: "h" }] } } },
66
80
  ]);
67
81
  const text = decide(start(on, "startup")).hookSpecificOutput.additionalContext;
68
- assert.ok(text.startsWith(REMINDER));
82
+ assert.ok(text.startsWith(BASE));
69
83
  assert.match(text, /CocoIndex, GitNexus/);
70
84
  assert.match(text, /optional/i);
71
85
  });
72
86
 
73
- test("with swarm.explore off, or naming no tools, the note is exactly REMINDER", (t) => {
87
+ test("with swarm.explore off, or naming no tools, the note is exactly the base note", (t) => {
74
88
  const [off, empty] = checkouts(t, [
75
89
  { swarm: { direct: false, dispatch: {} } },
76
90
  { swarm: { direct: false, dispatch: {}, explore: { tools: [] } } },
77
91
  ]);
78
- assert.equal(decide(start(off, "startup")).hookSpecificOutput.additionalContext, REMINDER);
79
- assert.equal(decide(start(empty, "startup")).hookSpecificOutput.additionalContext, REMINDER);
92
+ assert.equal(decide(start(off, "startup")).hookSpecificOutput.additionalContext, BASE);
93
+ assert.equal(decide(start(empty, "startup")).hookSpecificOutput.additionalContext, BASE);
80
94
  });
81
95
 
82
96
  test("with swarm.explore on and swarm.dispatch off, the SessionStart note still names the tools", (t) => {
@@ -113,7 +127,7 @@ test("the hook runs as its own process and prints the note as JSON, or nothing w
113
127
  const run = (cwd) => spawnSync(process.execPath, [NOTE], { input: JSON.stringify(start(cwd, "startup")), encoding: "utf8" });
114
128
  const noted = run(on);
115
129
  assert.equal(noted.status, 0, noted.stderr);
116
- assert.equal(JSON.parse(noted.stdout).hookSpecificOutput.additionalContext, REMINDER);
130
+ assert.equal(JSON.parse(noted.stdout).hookSpecificOutput.additionalContext, BASE);
117
131
  const silent = run(plain);
118
132
  assert.equal(silent.status, 0, silent.stderr);
119
133
  assert.equal(silent.stdout, "");
@@ -138,15 +152,15 @@ test("hooks.json also runs the note on SubagentStart, all matchers, beside the e
138
152
  );
139
153
  });
140
154
 
141
- test("a limit above 1 adds one line stating it, and a limit of 1 leaves the note as REMINDER", (t) => {
155
+ test("a limit above 1 adds one line stating it, and a limit of 1 leaves the note as the base note", (t) => {
142
156
  const [three, one] = checkouts(t, [
143
157
  { swarm: { dispatch: { implementerSlots: 3 } } },
144
158
  { swarm: { direct: false, dispatch: { implementerSlots: 1 } } },
145
159
  ]);
146
160
  const text = decide(start(three, "startup")).hookSpecificOutput.additionalContext;
147
- assert.ok(text.startsWith(REMINDER));
161
+ assert.ok(text.startsWith(BASE));
148
162
  assert.match(text, /up to 3 implementers at once/);
149
- assert.equal(decide(start(one, "startup")).hookSpecificOutput.additionalContext, REMINDER);
163
+ assert.equal(decide(start(one, "startup")).hookSpecificOutput.additionalContext, BASE);
150
164
  });
151
165
 
152
166
  test("SubagentStart gives each tool's use and command, in config order, since a plugin agent carries no MCP tool", (t) => {
@@ -172,16 +186,16 @@ test("SubagentStart gives each tool's use and command, in config order, since a
172
186
  );
173
187
  });
174
188
 
175
- test("a swarm.explore section that does not parse leaves SubagentStart silent and the session note as REMINDER", (t) => {
189
+ test("a swarm.explore section that does not parse leaves SubagentStart silent and the session note as the base note", (t) => {
176
190
  const [bad] = checkouts(t, [{ swarm: { direct: false, dispatch: {}, explore: { tools: "CocoIndex" } } }]);
177
191
  assert.equal(decide(subagentStart(bad)), null);
178
- assert.equal(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, REMINDER);
192
+ assert.equal(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, BASE);
179
193
  });
180
194
 
181
- test("with the direct lane on by default, the note names its limits after REMINDER", (t) => {
195
+ test("with the direct lane on by default, the note names its limits after the base note", (t) => {
182
196
  const [lane, custom] = checkouts(t, [{ swarm: { dispatch: {} } }, { swarm: { dispatch: {}, direct: { maxLines: 5, maxFiles: 1 } } }]);
183
197
  const text = decide(start(lane, "startup")).hookSpecificOutput.additionalContext;
184
- assert.ok(text.startsWith(REMINDER));
198
+ assert.ok(text.startsWith(BASE));
185
199
  assert.match(text, /at most 20 changed lines in 2 files needs no subagent/);
186
200
  assert.match(text, /--match-head-commit <sha>/);
187
201
  assert.match(decide(start(custom, "startup")).hookSpecificOutput.additionalContext, /at most 5 changed lines in 1 file needs/);
@@ -190,7 +204,7 @@ test("with the direct lane on by default, the note names its limits after REMIND
190
204
  test("a swarm.direct section that does not parse names the key and leaves the rest of the note", (t) => {
191
205
  const [bad] = checkouts(t, [{ swarm: { dispatch: {}, direct: { maxLines: 0 } } }]);
192
206
  const text = decide(start(bad, "startup")).hookSpecificOutput.additionalContext;
193
- assert.ok(text.startsWith(REMINDER));
207
+ assert.ok(text.startsWith(BASE));
194
208
  assert.match(text, /Direct lane is off: swarm\.direct\.maxLines/);
195
209
  });
196
210
 
@@ -236,3 +250,12 @@ test("a local swarm.direct of false turns the direct lane note off, whatever the
236
250
  writeFileSync(path.join(dir, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {}, direct: false } }));
237
251
  assert.doesNotMatch(decide(start(dir, "startup")).hookSpecificOutput.additionalContext, /needs no subagent/);
238
252
  });
253
+
254
+ test("the models line names each role's models for the runtime, and how to dispatch it", () => {
255
+ const claude = modelsLine({ models: runtimeModels.claude, runtime: "claude" });
256
+ assert.match(claude, /the claude runtime: sdd-planner opus, sdd-implementer sonnet, sdd-reviewer sonnet, sdd-branch-reviewer opus\./);
257
+ assert.match(claude, /Name that model on each dispatch/);
258
+ const codex = modelsLine({ models: runtimeModels.codex, runtime: "codex" });
259
+ assert.match(codex, /the codex runtime: sdd-planner gpt-6\.1-sol, sdd-implementer gpt-6\.1-sol/);
260
+ assert.match(modelsLine({ models: {}, runtime: null }), /unknown runtime \(set QC_RUNTIME to claude or codex\): sdd-planner the session's model/);
261
+ });
@@ -3,7 +3,7 @@
3
3
 
4
4
  import { existsSync } from "node:fs";
5
5
  import path from "node:path";
6
- import { CONFIG_FILE, MODEL_FAMILIES, dispatchDefaults, exploreDefaults, load, merge } from "../config.mjs";
6
+ import { CONFIG_FILE, MODEL_FAMILIES, dispatchDefaults, exploreDefaults, load, merge, runtimeModels } from "../config.mjs";
7
7
  import { checkoutRootOf } from "./checkout-root.mjs";
8
8
 
9
9
  const KEY = "swarm.dispatch";
@@ -34,17 +34,31 @@ export function familyOf(model) {
34
34
  return MODEL_FAMILIES.find((family) => !family.startsWith("gpt-") && lower.includes(family)) ?? null;
35
35
  }
36
36
 
37
+ /** The SDD role types, whose definitions say `model: inherit`. */
38
+ const ROLE_TYPES = Object.keys(runtimeModels.claude).filter((type) => type !== WILDCARD_TYPE);
39
+
40
+ /**
41
+ * The runtime that runs this session, from a positive signal: `QC_RUNTIME`, then Claude Code's `CLAUDECODE`
42
+ * or `CLAUDE_PROJECT_DIR`, then any `CODEX_` variable. Null when none is set, or when `QC_RUNTIME` names no
43
+ * runtime the kit knows. Claude Code sets `CLAUDECODE` in its shells, but a hook process gets only
44
+ * `CLAUDE_PROJECT_DIR`.
45
+ */
46
+ export function runtimeOf(env = process.env) {
47
+ const named = typeof env.QC_RUNTIME === "string" ? env.QC_RUNTIME.trim().toLowerCase() : "";
48
+ if (named !== "") return Object.hasOwn(runtimeModels, named) ? named : null;
49
+ if (env.CLAUDECODE === "1" || (env.CLAUDE_PROJECT_DIR ?? "") !== "") return "claude";
50
+ return Object.keys(env).some((key) => key.startsWith("CODEX_")) ? "codex" : null;
51
+ }
52
+
37
53
  /** @returns the dispatch settings, or null when the section is absent; throws naming the key a repository got wrong. */
38
- export function dispatchSettings(swarm = {}) {
54
+ export function dispatchSettings(swarm = {}, runtime = runtimeOf()) {
39
55
  const raw = swarm.dispatch;
40
56
  if (raw === undefined || raw === null || raw === false) return null;
41
57
  if (typeof raw !== "object" || Array.isArray(raw)) {
42
58
  throw new Error(`${KEY} in qc.config.json must be an object, got ${JSON.stringify(raw)}`);
43
59
  }
44
- const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models } = merge(
45
- dispatchDefaults,
46
- raw,
47
- );
60
+ const defaults = { ...dispatchDefaults, models: (runtime && runtimeModels[runtime]) ?? {} };
61
+ const { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models } = merge(defaults, raw);
48
62
  if (!isNameList(allowedTypes)) throw wrong("allowedTypes", allowedTypes, "a list of agent types");
49
63
  if (!isNameList(implementerTypes)) throw wrong("implementerTypes", implementerTypes, "a list of agent types");
50
64
  if (!Number.isInteger(maxPromptChars) || maxPromptChars < 1) {
@@ -55,14 +69,14 @@ export function dispatchSettings(swarm = {}) {
55
69
  throw wrong("implementerSlots", implementerSlots, "a positive whole number");
56
70
  }
57
71
  checkModels(models);
58
- return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models };
72
+ return { allowedTypes, implementerTypes, maxPromptChars, slotMinutes, implementerSlots, models, runtime };
59
73
  }
60
74
 
61
75
  /** @returns the settings of the checkout that holds `cwd`, or null when it has no config or no section. */
62
- export function dispatchSettingsAt(cwd) {
76
+ export function dispatchSettingsAt(cwd, runtime = runtimeOf()) {
63
77
  const root = checkoutRootOf(cwd);
64
78
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
65
- return dispatchSettings(load(root).swarm);
79
+ return dispatchSettings(load(root).swarm, runtime);
66
80
  }
67
81
 
68
82
  const isToolEntry = (entry) =>
@@ -143,9 +157,22 @@ function tierRefusal(type, model, families) {
143
157
  );
144
158
  }
145
159
 
160
+ const runtimeRefusal = (type) =>
161
+ `Dispatch guard: the session's runtime is unknown, so ${KEY}.models lists no model for ${type}. ` +
162
+ "Set QC_RUNTIME to claude or codex, or list the type in swarm.dispatch.models in qc.config.json.";
163
+
164
+ /** Under Claude Code a role's definition inherits the session's model, so the dispatch names the role's tier. */
165
+ function inheritRefusal(type, families) {
166
+ return (
167
+ `Dispatch guard: ${type} inherits the session's model unless the dispatch names one. ` +
168
+ `Pass \`model\` with ${families.join(" or ")}, the tier of this role.`
169
+ );
170
+ }
171
+
146
172
  /** @returns the reason a named model breaks its type's tier, or null when it fits. */
147
173
  function tierRefusalFor(type, model, settings) {
148
174
  const families = settings.models[type] ?? settings.models[WILDCARD_TYPE];
175
+ if (!families) return runtimeRefusal(type);
149
176
  const family = familyOf(model);
150
177
  if (family && families.includes(family)) return null;
151
178
  return tierRefusal(type, model, families);
@@ -157,6 +184,9 @@ export function dispatchRefusal(input, settings) {
157
184
  const model = typeof input.model === "string" ? input.model.trim() : "";
158
185
  const allowed = settings.allowedTypes.includes(type);
159
186
  if (!allowed && (type === FORK || model === "")) return modelRefusal(type, settings);
187
+ if (model === "" && settings.runtime === "claude" && ROLE_TYPES.includes(type) && Object.hasOwn(settings.models, type)) {
188
+ return inheritRefusal(type, settings.models[type]);
189
+ }
160
190
  if (model !== "" && type !== FORK) {
161
191
  const refusal = tierRefusalFor(type, model, settings);
162
192
  if (refusal) return refusal;
@@ -174,8 +204,8 @@ export function dispatchNote(input, settings) {
174
204
  if (MODEL_FAMILIES.includes(model.toLowerCase())) return null;
175
205
  return (
176
206
  `Dispatch note: ${type} sets its own model, and "${model}" is a full model id. Requests to different models share no prompt cache, ` +
177
- `so this dispatch pays the type's shared first-call prefix again when the id differs from the definition's model. ` +
178
- "A dispatch of this type with no `model` shares one cache with the others."
207
+ `so this dispatch pays the type's shared first-call prefix again when other dispatches of the type use another id. ` +
208
+ "Name the bare family, such as `sonnet`, to share one cache with them."
179
209
  );
180
210
  }
181
211
 
@@ -1,7 +1,10 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
- import { defaults, dispatchDefaults, merge } from "../config.mjs";
4
- import { dispatchNote, dispatchRefusal, dispatchSettings, exploreSettings, exploreToolLines, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
3
+ import { defaults, dispatchDefaults, merge, runtimeModels } from "../config.mjs";
4
+ import { dispatchNote, dispatchRefusal, dispatchSettings, exploreSettings, exploreToolLines, familyOf, isImplementer, runtimeOf, slotRefusal, typeOf } from "./dispatch.mjs";
5
+
6
+ // The settings below default to Codex, whatever runtime runs the test.
7
+ process.env.QC_RUNTIME = "codex";
5
8
 
6
9
  test("a swarm section with no dispatch key keeps the guard off", () => {
7
10
  assert.equal(dispatchSettings({}), null);
@@ -11,7 +14,8 @@ test("a swarm section with no dispatch key keeps the guard off", () => {
11
14
  });
12
15
 
13
16
  test("an empty dispatch section turns the guard on with every default", () => {
14
- assert.deepEqual(dispatchSettings(merge(defaults, { swarm: { dispatch: {} } }).swarm), dispatchDefaults);
17
+ const expected = { ...dispatchDefaults, models: runtimeModels.codex, runtime: "codex" };
18
+ assert.deepEqual(dispatchSettings(merge(defaults, { swarm: { dispatch: {} } }).swarm), expected);
15
19
  });
16
20
 
17
21
  test("a list in the section replaces its default rather than extending it", () => {
@@ -45,7 +49,7 @@ test("a wrong value names its key", () => {
45
49
  test("a repository's models merges key by key with the defaults", () => {
46
50
  const settings = dispatchSettings({ dispatch: { models: { "architecture:sdd-planner": ["sonnet"] } } });
47
51
  assert.deepEqual(settings.models["architecture:sdd-planner"], ["sonnet"]);
48
- assert.deepEqual(settings.models["architecture:sdd-implementer"], dispatchDefaults.models["architecture:sdd-implementer"]);
52
+ assert.deepEqual(settings.models["architecture:sdd-implementer"], runtimeModels.codex["architecture:sdd-implementer"]);
49
53
  });
50
54
 
51
55
  test("familyOf finds the first known family a model string contains, lower-cased", () => {
@@ -238,3 +242,41 @@ test("an excerptChars the repository sets must be smaller than maxOutputChars",
238
242
  assert.throws(() => exploreSettings({ explore: { maxOutputChars: 20, excerptChars } }), /swarm\.explore\.excerptChars .*smaller than maxOutputChars \(20\)/);
239
243
  }
240
244
  });
245
+
246
+ test("the runtime comes from QC_RUNTIME, then CLAUDECODE or CLAUDE_PROJECT_DIR, then a CODEX_ variable, and is null with no signal", () => {
247
+ assert.equal(runtimeOf({ QC_RUNTIME: "Codex", CLAUDECODE: "1" }), "codex");
248
+ assert.equal(runtimeOf({ QC_RUNTIME: "other", CLAUDECODE: "1" }), null);
249
+ assert.equal(runtimeOf({ CLAUDECODE: "1", CODEX_HOME: "x" }), "claude");
250
+ assert.equal(runtimeOf({ CLAUDE_PROJECT_DIR: "/repo", CODEX_HOME: "x" }), "claude");
251
+ assert.equal(runtimeOf({ CLAUDE_PROJECT_DIR: "", CODEX_HOME: "x" }), "codex");
252
+ assert.equal(runtimeOf({ CODEX_HOME: "x" }), "codex");
253
+ assert.equal(runtimeOf({}), null);
254
+ });
255
+
256
+ test("under Claude Code the no-model refusal covers only the four roles, not another type a repository lists", () => {
257
+ const settings = dispatchSettings({ dispatch: { allowedTypes: [...dispatchDefaults.allowedTypes, "Explore"], models: { Explore: ["haiku"] } } }, "claude");
258
+ assert.equal(dispatchRefusal({ subagent_type: "Explore", prompt: "p" }, settings), null);
259
+ });
260
+
261
+ test("under Claude Code each role takes its Claude tier, and a role dispatch must name it", () => {
262
+ const settings = dispatchSettings({ dispatch: {} }, "claude");
263
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "sonnet", prompt: "p" }, settings), null);
264
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-branch-reviewer", model: "opus", prompt: "p" }, settings), null);
265
+ assert.match(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "gpt-6.1-sol" }, settings) ?? "", /may run only on sonnet/);
266
+ assert.match(dispatchRefusal({ subagent_type: "architecture:sdd-planner", prompt: "p" }, settings) ?? "", /inherits the session's model.*Pass `model` with opus/);
267
+ assert.equal(dispatchRefusal({ subagent_type: "Explore", model: "haiku", prompt: "p" }, settings), null);
268
+ });
269
+
270
+ test("under Codex a role dispatch with no model inherits the session's GPT model", () => {
271
+ const settings = dispatchSettings({ dispatch: {} }, "codex");
272
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", prompt: "p" }, settings), null);
273
+ assert.match(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "sonnet" }, settings) ?? "", /may run only on gpt-6\.1-sol/);
274
+ });
275
+
276
+ test("an unknown runtime refuses a named model with no listed families, and a repository's models still apply", () => {
277
+ const unknown = dispatchSettings({ dispatch: {} }, null);
278
+ assert.match(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "sonnet" }, unknown) ?? "", /runtime is unknown.*QC_RUNTIME/);
279
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", prompt: "p" }, unknown), null);
280
+ const listed = dispatchSettings({ dispatch: { models: { "architecture:sdd-implementer": ["sonnet"] } } }, null);
281
+ assert.equal(dispatchRefusal({ subagent_type: "architecture:sdd-implementer", model: "sonnet", prompt: "p" }, listed), null);
282
+ });
@@ -6,6 +6,7 @@ import { spawnSync } from "node:child_process";
6
6
  export { keyOf as pathKey } from "./worktree.mjs";
7
7
 
8
8
  const GIT_TIMEOUT_MS = 10_000;
9
+ const ORIGIN_TIMEOUT_MS = 5_000;
9
10
 
10
11
  /** @returns git's trimmed stdout, or null on a non-zero exit or after `timeoutMs`. */
11
12
  export function gitOutWithin(timeoutMs, cwd, ...args) {
@@ -16,6 +17,18 @@ export function gitOutWithin(timeoutMs, cwd, ...args) {
16
17
  /** @returns git's trimmed stdout, or null on a non-zero exit or a timeout. */
17
18
  export const gitOut = (cwd, ...args) => gitOutWithin(GIT_TIMEOUT_MS, cwd, ...args);
18
19
 
20
+ /** `owner/repo` from a git remote URL in the https, ssh, or scp spelling, or from gh's `[HOST/]OWNER/REPO`; lower case. */
21
+ export function repoOfSpelling(spelled) {
22
+ const parts = String(spelled).trim().replace(/\/+$/, "").replace(/\.git$/i, "").split(/[/:]/).filter(Boolean);
23
+ return parts.length >= 2 ? parts.slice(-2).join("/").toLowerCase() : null;
24
+ }
25
+
26
+ /** The repository of the checkout's `origin` remote, or null when git cannot say or `timeoutMs` passes. */
27
+ export const originOf = (root, timeoutMs = ORIGIN_TIMEOUT_MS) => {
28
+ const url = gitOutWithin(timeoutMs, root, "remote", "get-url", "origin");
29
+ return url === null ? null : repoOfSpelling(url);
30
+ };
31
+
19
32
  /** @returns the full sha that `ref` names as a commit, or null when the repository holds none. */
20
33
  export const commitOf = (cwd, ref) => gitOut(cwd, "rev-parse", "--verify", "--quiet", `${ref}^{commit}`);
21
34
 
@@ -108,6 +108,8 @@ const short = (sha) => (typeof sha === "string" ? sha.slice(0, MIN_SHA) : "");
108
108
  const SUMMARIES = {
109
109
  dispatch: (r) =>
110
110
  `${r.agentType} ${r.task ? `${r.branch} ${short(r.head)}` : "(no task)"}${r.resumeReason ? ` NO-RESUME: ${r.resumeReason}` : ""}${
111
+ r.ciPass ? ` CI-PASS: ${short(r.ciPass.sha)} ${r.ciPass.reason}` : ""
112
+ }${
111
113
  r.handoff ? ` HANDOFF: ${r.handoff}` : ""
112
114
  }`,
113
115
  stop: (r) => `${r.role} ${r.agentType} ${r.agentId}${r.plan ? ` ${r.plan}` : ""}${r.handoff ? ` HANDOFF: ${r.handoff}` : ""}`,
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
8
8
  import {
9
9
  appendRecord,
10
10
  commonDirOf,
11
+ formatRecord,
11
12
  lastTaskDispatchOn,
12
13
  latestVerdictFor,
13
14
  latestVerdictOn,
@@ -125,3 +126,16 @@ test("an append after a torn last line keeps the new record whole", (t) => {
125
126
  appendRecord(file, { type: "stop", role: "task" });
126
127
  assert.equal(readLedger(file).length, 3, "a file that ends in a newline gets no blank line");
127
128
  });
129
+
130
+ test("a dispatch that passed on a CI failure shows the sha and the reason in the ledger line", () => {
131
+ const line = formatRecord({
132
+ at: "t",
133
+ type: "dispatch",
134
+ agentType: "sdd-implementer",
135
+ task: true,
136
+ branch: "feat/1-x",
137
+ head: "abcdef1234",
138
+ ciPass: { sha: "1234567890abcdef", reason: "CI on 1234567: build ended failure" },
139
+ });
140
+ assert.match(line, /CI-PASS: 1234567 CI on 1234567: build ended failure/);
141
+ });
@@ -5,12 +5,12 @@
5
5
  // A merge that names another repository than the checkout's `origin` is that repository's own, so it passes.
6
6
  // With `swarm.dispatch` off, the record is still written for the worktree check of QC-015, and nothing is judged.
7
7
 
8
- import { spawnSync } from "node:child_process";
9
8
  import { fileURLToPath } from "node:url";
10
9
  import { PARSERS } from "./bash-command-guard.mjs";
11
10
  import { LANE_BUDGET_MS, mergeLane, sizeLine } from "./direct-lane.mjs";
12
11
  import { ghApiMerges, ghMerges } from "./gh-merge-command.mjs";
13
12
  import { runGh } from "./gh-run.mjs";
13
+ import { originOf, repoOfSpelling } from "./git-read.mjs";
14
14
  import { appendRecord, latestVerdictFor, readLedger } from "./ledger.mjs";
15
15
  import { workflowAt } from "./workflow-settings.mjs";
16
16
  import { worktreeRuleAt } from "./worktree-settings.mjs";
@@ -19,7 +19,6 @@ const VIEW_FIELDS = "number,url,state,mergedAt,baseRefName,headRefName,body,clos
19
19
  const MAYBE_GH = /\bgh(?:\.exe)?\b/i;
20
20
  const BODY_REF = /(?<![\w/#])#(\d+)\b/g;
21
21
  const REF_LINE = /^\s*(?:[-*]\s+)?(?:refs|closes|fixes|resolves)\b/i;
22
- const ORIGIN_TIMEOUT_MS = 5_000;
23
22
  const PR_URL = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+/;
24
23
  const POST_EVENTS = new Set(["PostToolUse", "PostToolUseFailure"]);
25
24
  const REVIEWER = { branch: "the branch reviewer (sdd-branch-reviewer)", task: "the task reviewer (sdd-reviewer)" };
@@ -112,18 +111,6 @@ export function namedIssues(pr, repo) {
112
111
  return [...found.values()];
113
112
  }
114
113
 
115
- /** `owner/repo` from a git remote URL in the https, ssh, or scp spelling, or from gh's `[HOST/]OWNER/REPO`; lower case. */
116
- function repoOfSpelling(spelled) {
117
- const parts = String(spelled).trim().replace(/\/+$/, "").replace(/\.git$/i, "").split(/[/:]/).filter(Boolean);
118
- return parts.length >= 2 ? parts.slice(-2).join("/").toLowerCase() : null;
119
- }
120
-
121
- /** The repository of the checkout's `origin` remote, or null when git cannot say. */
122
- function originOf(root) {
123
- const result = spawnSync("git", ["remote", "get-url", "origin"], { cwd: root, encoding: "utf8", windowsHide: true, timeout: ORIGIN_TIMEOUT_MS });
124
- return result.status === 0 ? repoOfSpelling(result.stdout) : null;
125
- }
126
-
127
114
  /** Splits the merges into those of this checkout's repository and those that name another repository. */
128
115
  function partition(merges, root) {
129
116
  const origin = merges.some((merge) => merge.repo) ? originOf(root) : null;
@@ -3,8 +3,7 @@ import { readFileSync, readdirSync } from "node:fs";
3
3
  import path from "node:path";
4
4
  import { test } from "node:test";
5
5
  import { fileURLToPath } from "node:url";
6
- import { dispatchDefaults } from "../config.mjs";
7
- import { familyOf } from "./dispatch.mjs";
6
+ import { dispatchDefaults, runtimeModels } from "../config.mjs";
8
7
  import { REMINDER } from "./dispatch-reminder.mjs";
9
8
 
10
9
  const AGENTS = fileURLToPath(new URL("../../../../agents/", import.meta.url));
@@ -41,10 +40,10 @@ const ALWAYS_PRESENT = ["Read", "Bash"];
41
40
  const READ_TOOLS = ["Read", "Grep", "Glob", "Bash", "PowerShell"];
42
41
  const EDIT_TOOLS = [...READ_TOOLS, "Skill", "Edit", "Write"];
43
42
  const EXPECTED = {
44
- "sdd-implementer": { model: "gpt-6.1-sol", effort: "high", tools: EDIT_TOOLS },
45
- "sdd-planner": { model: "gpt-6.1-sol", effort: "high", tools: EDIT_TOOLS },
46
- "sdd-reviewer": { model: "gpt-6.1-sol", effort: "high", tools: READ_TOOLS },
47
- "sdd-branch-reviewer": { model: "gpt-6.1-sol", effort: "high", tools: READ_TOOLS },
43
+ "sdd-implementer": { model: "inherit", effort: "high", tools: EDIT_TOOLS },
44
+ "sdd-planner": { model: "inherit", effort: "high", tools: EDIT_TOOLS },
45
+ "sdd-reviewer": { model: "inherit", effort: "high", tools: READ_TOOLS },
46
+ "sdd-branch-reviewer": { model: "inherit", effort: "high", tools: READ_TOOLS },
48
47
  };
49
48
  // Fields Claude Code ignores on a plugin agent, and the one that drops a repository's CLAUDE.md and rules.
50
49
  const FORBIDDEN_FIELDS = ["disallowedTools", "hooks", "mcpServers", "permissionMode", "omitClaudeMd"];
@@ -81,7 +80,7 @@ function readmeToolsOf(markdown) {
81
80
 
82
81
  const frontOf = (name) => frontmatterOf(path.join(AGENTS, `${name}.md`));
83
82
 
84
- test("each subagent type runs on its model tier at its effort, with its own tool list", () => {
83
+ test("each subagent type inherits the session model, has a model in every runtime, and keeps its effort and tool list", () => {
85
84
  assert.deepEqual(
86
85
  readdirSync(AGENTS).sort(),
87
86
  Object.keys(EXPECTED).map((name) => `${name}.md`).sort(),
@@ -94,9 +93,10 @@ test("each subagent type runs on its model tier at its effort, with its own tool
94
93
  assert.equal(front.effort, want.effort, name);
95
94
  assert.ok(front.description.length > 0, name);
96
95
  assert.deepEqual(listOf(front.tools), want.tools, name);
97
- const family = familyOf(front.model);
98
- assert.ok(dispatchDefaults.models[name]?.includes(family), name);
99
- assert.ok(dispatchDefaults.models[`${PLUGIN}:${name}`]?.includes(family), name);
96
+ for (const models of Object.values(runtimeModels)) {
97
+ assert.ok(models[name]?.length > 0, name);
98
+ assert.deepEqual(models[`${PLUGIN}:${name}`], models[name], name);
99
+ }
100
100
  }
101
101
  });
102
102
 
@@ -155,3 +155,14 @@ test("no type pins a prompt cache lifetime, so a user's own setting decides it",
155
155
  assert.equal(front.cacheTtl, undefined, `${name} sets cacheTtl`);
156
156
  }
157
157
  });
158
+
159
+ test("both reviewers review only the increment when the dispatch carries a Reviewed line, and still put the verdict first", () => {
160
+ for (const name of ["sdd-reviewer", "sdd-branch-reviewer"]) {
161
+ const text = readFileSync(path.join(AGENTS, `${name}.md`), "utf8").replace(/\r/g, "");
162
+ assert.match(text, /`Reviewed: <sha>`/, name);
163
+ assert.match(text, /<sha>\.\.<head>/, name);
164
+ assert.match(text, /only that increment|only the increment/i, name);
165
+ assert.match(text, /Without the line, review as before/, name);
166
+ assert.ok(text.indexOf("`Reviewed: <sha>`") < text.indexOf("`VERDICT: APPROVED <sha>`"), `${name} keeps the verdict line rule last`);
167
+ }
168
+ });
@@ -49,4 +49,5 @@ test("the checkout directories are each location change and each git -C director
49
49
  ["C:\\repo\\a", "C:\\b c", "..\\d", "C:\\e"],
50
50
  );
51
51
  assert.deepEqual(checkoutDirs("Get-ChildItem"), []);
52
+ assert.deepEqual(checkoutDirs("Set-Content f x; git -C"), []);
52
53
  });
@@ -233,21 +233,29 @@ export const commandEnv = (segment) => unwrap(segment.words).env;
233
233
  const isGit = (word) => /(^|[\\/])git(\.exe)?$/i.test(word ?? "");
234
234
 
235
235
  /**
236
- * @returns the git subcommand, each `-C` directory, each `-c` setting and the words after the
237
- * subcommand, or null when the segment is no git call.
236
+ * @returns the git subcommand, each `-C` directory, each `-c` setting and the words after the subcommand, or null
237
+ * when the segment is no git call. `explicitDir` is true when the call names a git directory or a work tree, through
238
+ * `--git-dir`, `--work-tree`, `GIT_DIR` or `GIT_WORK_TREE`. It is never resolved: git reads a relative one from the
239
+ * working directory after every `-C`, so no later reader can know which repository it picks.
238
240
  */
239
241
  export function gitCall(segment) {
240
242
  const [program, ...words] = commandWords(segment);
241
243
  if (!isGit(program)) return null;
244
+ const { GIT_DIR, GIT_WORK_TREE } = commandEnv(segment);
245
+ let explicitDir = Boolean(GIT_DIR || GIT_WORK_TREE);
242
246
  const dirs = [];
243
247
  const configs = [];
244
248
  for (let i = 0; i < words.length; i++) {
245
249
  const word = words[i];
246
250
  if (word === "-C") dirs.push(words[++i]);
251
+ else if (word === "--git-dir" || word === "--work-tree") {
252
+ explicitDir = true;
253
+ i++;
254
+ } else if (/^--(git-dir|work-tree)=/.test(word)) explicitDir = true;
247
255
  else if (word === "-c") configs.push(words[++i]);
248
- else if (!word.startsWith("-")) return { sub: word, dirs, configs, args: words.slice(i + 1) };
256
+ else if (!word.startsWith("-")) return { sub: word, dirs, explicitDir, configs, args: words.slice(i + 1) };
249
257
  }
250
- return { sub: null, dirs, configs, args: [] };
258
+ return { sub: null, dirs, explicitDir, configs, args: [] };
251
259
  }
252
260
 
253
261
  /** @returns the directory a `cd` or `pushd` segment moves to, or null. */
@@ -32,9 +32,28 @@ test("a redirect target is recorded apart from the words, and a descriptor copy
32
32
  assert.deepEqual(segmentsOf("cat log >> all.log")[0].redirects, ["all.log"]);
33
33
  });
34
34
 
35
+ test("a git call flags an explicit git dir or work tree, and does not resolve it", () => {
36
+ const explicitOf = (command) => gitCall(segmentsOf(command)[0]).explicitDir;
37
+ for (const command of [
38
+ "git --git-dir=/r/.git status",
39
+ "git --git-dir /r/.git status",
40
+ "GIT_DIR=/r/.git git status",
41
+ "env GIT_DIR=/r/.git git status",
42
+ "git -C /a --git-dir=/r/.git status",
43
+ "git --work-tree=/r status",
44
+ "git --work-tree /r status",
45
+ "GIT_WORK_TREE=/r git status",
46
+ ]) {
47
+ assert.equal(explicitOf(command), true, command);
48
+ }
49
+ for (const command of ["git status", "git -C /a status", "git -c core.x=y status"]) assert.equal(explicitOf(command), false, command);
50
+ assert.deepEqual(gitCall(segmentsOf("git -C /a --git-dir /r/.git status")[0]).dirs, ["/a"], "the git dir is no checkout directory");
51
+ assert.equal(gitCall(segmentsOf("git --git-dir /r/.git status")[0]).sub, "status", "the value is not the subcommand");
52
+ });
53
+
35
54
  test("a git call names its subcommand and every -C directory", () => {
36
55
  const [segment] = segmentsOf(`GIT_PAGER=cat git -C "C:/a b" -c core.x=y --no-pager commit -m x`);
37
- assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"], configs: ["core.x=y"], args: ["-m", "x"] });
56
+ assert.deepEqual(gitCall(segment), { sub: "commit", dirs: ["C:/a b"], explicitDir: false, configs: ["core.x=y"], args: ["-m", "x"] });
38
57
  assert.equal(gitCall(segmentsOf("gitk --all")[0]), null);
39
58
  });
40
59
 
@@ -92,6 +111,7 @@ test("the checkout directories are every cd target and every git -C directory, i
92
111
  "/repo/d",
93
112
  ]);
94
113
  assert.deepEqual(checkoutDirs("ls"), []);
114
+ assert.deepEqual(checkoutDirs("echo x > f; git -C"), []);
95
115
  });
96
116
 
97
117
  test("a git call carries each -c setting and the words after its subcommand", () => {
@@ -99,10 +119,11 @@ test("a git call carries each -c setting and the words after its subcommand", ()
99
119
  assert.deepEqual(gitCall(segment), {
100
120
  sub: "commit",
101
121
  dirs: ["repo"],
122
+ explicitDir: false,
102
123
  configs: ["core.hooksPath=/dev/null"],
103
124
  args: ["-m", "a b", "--no-verify"],
104
125
  });
105
- assert.deepEqual(gitCall(segmentsOf("git --version")[0]), { sub: null, dirs: [], configs: [], args: [] });
126
+ assert.deepEqual(gitCall(segmentsOf("git --version")[0]), { sub: null, dirs: [], explicitDir: false, configs: [], args: [] });
106
127
  });
107
128
 
108
129
  test("the PowerShell escape keeps a backslash literal and escapes with a backtick", () => {
@@ -4,6 +4,7 @@
4
4
  import os from "node:os";
5
5
  import path from "node:path";
6
6
  import { checkoutRootOf } from "./checkout-root.mjs";
7
+ import { ciNotGreen } from "./ci-state.mjs";
7
8
  import { typeOf } from "./dispatch.mjs";
8
9
  import { handoffPathOf, resolveHandoff } from "./handoff-note.mjs";
9
10
  import { branchAt, gitOut, linkedWorktrees, pathKey } from "./git-read.mjs";
@@ -27,6 +28,7 @@ const fixRoundRefusal = (branch, sha, type) =>
27
28
  const unreviewedRefusal = (branch, stopHead, head) =>
28
29
  `Task gate: an implementer stopped on ${branch} at ${short(stopHead)}, and no review in the ledger names ${short(stopHead)} or a later commit. ` +
29
30
  `Dispatch the task reviewer on ${short(head)} first; its first line \`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>\` records the review. ` +
31
+ `The review runs once CI on the head is green: when CI on ${short(stopHead)} has failed or still runs, the next implementer continues the task and this gate passes it. ` +
30
32
  `If that stop handed off, its report named \`HANDOFF: <note path>\`; the same line in the next implementer prompt continues the task. ` +
31
33
  `\`qc ledger ${branch}\` lists what is recorded.`;
32
34
 
@@ -72,22 +74,32 @@ export function continuedStop(records, branch, handoff) {
72
74
  }
73
75
 
74
76
  /**
75
- * @returns the reason an implementer may not start on `branch` now, or null. Only implementer commits need a
76
- * review, so a controller commit after a reviewed head passes. `cwd` is any checkout; `git` reads it.
77
+ * The task gate's answer for an implementer on `branch`: `refusal` is the reason it may not start now, or null.
78
+ * `ciPass` is `{ sha, reason }` when an unreviewed stop head passes because CI on it is not green, else absent.
79
+ * Only implementer commits need a review, so a controller commit after a reviewed head passes. `cwd` is any
80
+ * checkout; `git` reads it, and `ci` answers why CI on a sha is not green, or null.
77
81
  */
78
- export function gateRefusal({ records, branch, head, reason, type, cwd, git = gitOut, handoff = null }) {
82
+ export function gateVerdict({ records, branch, head, reason, type, cwd, git = gitOut, handoff = null, ci = (sha) => ciNotGreen(sha, cwd) }) {
79
83
  // A continuation of the newest stop's hand-off is the same task, so it is neither a fix round nor a new task.
80
84
  const continued = continuedStop(records, branch, handoff);
81
85
  const why = reason ?? (continued ? `continues the hand-off ${continued.handoff}` : null);
82
86
  const last = latestVerdictOn(records, branch);
83
- if (last?.verdict === "CHANGES_REQUIRED" && why === null) return fixRoundRefusal(branch, last.sha, type);
87
+ if (last?.verdict === "CHANGES_REQUIRED" && why === null) return { refusal: fixRoundRefusal(branch, last.sha, type) };
84
88
  const unreviewed = unreviewedImplementerStop({ records, branch, head, cwd, git });
85
- if (unreviewed && unreviewed !== continued) return unreviewedRefusal(branch, unreviewed.head, head);
89
+ if (unreviewed && unreviewed !== continued) {
90
+ // A head that CI failed changes before a review, so a review now would be spent on a commit that is replaced.
91
+ const notGreen = ci(unreviewed.head);
92
+ if (notGreen === null) return { refusal: unreviewedRefusal(branch, unreviewed.head, head) };
93
+ return { refusal: null, ciPass: { sha: unreviewed.head, reason: notGreen } };
94
+ }
86
95
  const current = latestVerdictFor(records, head, ["task", "branch"]);
87
- if (current?.verdict === "CHANGES_REQUIRED" && why === null) return fixRoundRefusal(branch, current.sha, type);
88
- return null;
96
+ if (current?.verdict === "CHANGES_REQUIRED" && why === null) return { refusal: fixRoundRefusal(branch, current.sha, type) };
97
+ return { refusal: null };
89
98
  }
90
99
 
100
+ /** @returns the reason an implementer may not start on `branch` now, or null. `gateVerdict` has the inputs. */
101
+ export const gateRefusal = (input) => gateVerdict(input).refusal;
102
+
91
103
  const pass = (workflow, record, note = null) => ({ refusal: null, workflow, record, note });
92
104
  const refuse = (refusal) => ({ refusal, workflow: null, record: null, note: null });
93
105
 
@@ -97,9 +109,10 @@ const taskTypeIn = (type, review) =>
97
109
  /**
98
110
  * Judges one main-session Agent call. The repository of the worktree the prompt names decides, and the
99
111
  * repository of the cwd decides only when the prompt names none.
112
+ * `ci` replaces the CI read of the task gate, for a test.
100
113
  * @returns the refusal, or the record to write once the dispatch runs.
101
114
  */
102
- export function judgeTask(call, tmp = os.tmpdir()) {
115
+ export function judgeTask(call, tmp = os.tmpdir(), { ci } = {}) {
103
116
  const cwd = call.cwd ?? process.cwd();
104
117
  let own;
105
118
  try {
@@ -161,10 +174,11 @@ export function judgeTask(call, tmp = os.tmpdir()) {
161
174
  const reason = noResumeReason(prompt);
162
175
  const spelled = handoffPathOf(prompt);
163
176
  const handoff = spelled === null ? null : resolveHandoff(spelled, cwd);
164
- const refusal = gateRefusal({ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff });
177
+ const { refusal, ciPass } = gateVerdict({ records, branch: worktree.branch, head: worktree.head, reason, type, cwd: workflow.root, handoff, ...(ci ? { ci } : {}) });
165
178
  if (refusal) return refuse(refusal);
166
179
  const continues = handoff ? { handoff } : {};
167
- return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason, ...continues });
180
+ const unreviewed = ciPass ? { ciPass } : {};
181
+ return pass(workflow, { ...base, task: true, worktree: worktree.path, branch: worktree.branch, head: worktree.head, resumeReason: reason, ...continues, ...unreviewed });
168
182
  }
169
183
 
170
184
  /** Writes the dispatch record of a judged call. @returns a note for the session, or null. */
@@ -7,9 +7,12 @@ import { test } from "node:test";
7
7
  import { decide as dispatchDecide } from "./dispatch-guard.mjs";
8
8
  import { appendRecord, readLedger } from "./ledger.mjs";
9
9
  import { gitOut } from "./git-read.mjs";
10
- import { continuedStop, gateRefusal, judgeTask, noResumeReason, recordDispatch, worktreeNamed } from "./task-gate.mjs";
10
+ import { continuedStop, gateRefusal, gateVerdict, judgeTask, noResumeReason, recordDispatch, worktreeNamed } from "./task-gate.mjs";
11
11
  import { sessionDirOf } from "./workflow-settings.mjs";
12
12
 
13
+ // The guard processes below run under Codex, whatever runtime runs the test.
14
+ process.env.QC_RUNTIME = "codex";
15
+
13
16
  const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
14
17
 
15
18
  /** A checkout with the checks on and a linked worktree on feat/1-x, one without the checks, and a temp folder. */
@@ -505,3 +508,61 @@ test("a later verdict on the branch ends the continuation, whatever commit it na
505
508
  assert.equal(continuedStop(readLedger(ws.ledger), "feat/1-x", note), null);
506
509
  assert.match(refusalOf(ws, `HANDOFF: ${note}`) ?? "", /CHANGES_REQUIRED/);
507
510
  });
511
+
512
+ test("a stop head with CI that is not green lets the next implementer continue, and the dispatch record holds the reason", (t) => {
513
+ const ws = workspace(t);
514
+ recordDispatch(judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp));
515
+ const moved = commitIn(ws.linked, "b.txt");
516
+ implementerStop(ws, moved);
517
+ const asked = [];
518
+ const ci = (sha) => {
519
+ asked.push(sha);
520
+ return `CI on ${sha.slice(0, 7)}: build ended failure`;
521
+ };
522
+ const task = judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci });
523
+ assert.equal(task.refusal, null);
524
+ assert.deepEqual(asked, [moved]);
525
+ assert.deepEqual(task.record.ciPass, { sha: moved, reason: `CI on ${moved.slice(0, 7)}: build ended failure` });
526
+ recordDispatch(task);
527
+ const [, written] = readLedger(ws.ledger).filter((record) => record.type === "dispatch");
528
+ assert.deepEqual(written.ciPass, task.record.ciPass);
529
+ });
530
+
531
+ test("a stop head with green or unknown CI keeps the refusal, and the refusal says the review waits for green CI", (t) => {
532
+ const ws = workspace(t);
533
+ implementerStop(ws, commitIn(ws.linked, "b.txt"));
534
+ const refusal = judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci: () => null }).refusal;
535
+ assert.match(refusal ?? "", /no review in the ledger/);
536
+ assert.match(refusal ?? "", /once CI on the head is green/);
537
+ });
538
+
539
+ test("the CI pass does not skip a review that is already on record", (t) => {
540
+ const ws = workspace(t);
541
+ const moved = commitIn(ws.linked, "b.txt");
542
+ implementerStop(ws, moved);
543
+ verdict(ws, moved);
544
+ let asked = 0;
545
+ const task = judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci: () => (asked += 1, "red") });
546
+ assert.equal(task.refusal, null);
547
+ assert.equal(asked, 0);
548
+ assert.equal(task.record.ciPass, undefined);
549
+ });
550
+
551
+ test("a CI pass does not lift a CHANGES_REQUIRED fix round", (t) => {
552
+ const ws = workspace(t);
553
+ const moved = commitIn(ws.linked, "b.txt");
554
+ implementerStop(ws, moved);
555
+ verdict(ws, moved, "CHANGES_REQUIRED");
556
+ assert.match(judgeTask(dispatch(ws.main, taskPrompt(ws.linked)), ws.tmp, { ci: () => "red" }).refusal ?? "", /CHANGES_REQUIRED/);
557
+ });
558
+
559
+ test("gateVerdict reports the stop and the reason of a CI pass, and gateRefusal still answers with the refusal alone", (t) => {
560
+ const ws = workspace(t);
561
+ const moved = commitIn(ws.linked, "b.txt");
562
+ implementerStop(ws, moved);
563
+ const input = { records: readLedger(ws.ledger), branch: "feat/1-x", head: moved, reason: null, type: "sdd-implementer", cwd: ws.linked };
564
+ assert.deepEqual(gateVerdict({ ...input, ci: () => "red" }), { refusal: null, ciPass: { sha: moved, reason: "red" } });
565
+ assert.match(gateVerdict({ ...input, ci: () => null }).refusal ?? "", /no review/);
566
+ assert.match(gateRefusal({ ...input, ci: () => null }) ?? "", /no review/);
567
+ assert.equal(gateRefusal({ ...input, ci: () => "red" }), null);
568
+ });
package/src/config.mjs CHANGED
@@ -493,21 +493,29 @@ export const dispatchDefaults = {
493
493
  slotMinutes: 60,
494
494
  // How many implementers run at once in a session. Each needs paths of its own, and a worktree.
495
495
  implementerSlots: 1,
496
- // The model families each type's named `model` may carry. `"*"` covers every other type.
497
- models: {
498
- "sdd-planner": ["gpt-6.1-sol"],
499
- "architecture:sdd-planner": ["gpt-6.1-sol"],
500
- "sdd-branch-reviewer": ["gpt-6.1-sol"],
501
- "architecture:sdd-branch-reviewer": ["gpt-6.1-sol"],
502
- "sdd-implementer": ["gpt-6.1-sol"],
503
- "architecture:sdd-implementer": ["gpt-6.1-sol"],
504
- "sdd-reviewer": ["gpt-6.1-sol"],
505
- "architecture:sdd-reviewer": ["gpt-6.1-sol"],
506
- "*": ["gpt-6.1-sol"],
507
- },
496
+ // The model families each type's named `model` may carry, over the runtime's own in `runtimeModels`.
497
+ models: {},
498
+ };
499
+
500
+ const roleModels = (planning, working, other) => ({
501
+ "sdd-planner": planning,
502
+ "architecture:sdd-planner": planning,
503
+ "sdd-branch-reviewer": planning,
504
+ "architecture:sdd-branch-reviewer": planning,
505
+ "sdd-implementer": working,
506
+ "architecture:sdd-implementer": working,
507
+ "sdd-reviewer": working,
508
+ "architecture:sdd-reviewer": working,
509
+ "*": other,
510
+ });
511
+
512
+ // The default `swarm.dispatch.models` of each runtime that can run a session. A runtime calls only its own models.
513
+ export const runtimeModels = {
514
+ claude: roleModels(["opus"], ["sonnet"], ["sonnet", "haiku"]),
515
+ codex: roleModels(["gpt-6.1-sol"], ["gpt-6.1-sol"], ["gpt-6.1-sol"]),
508
516
  };
509
517
 
510
- // GPT uses an exact model id; Claude families remain available for repository overrides.
518
+ // GPT uses an exact model id; a Claude family matches any model id that contains it.
511
519
  export const MODEL_FAMILIES = ["gpt-6.1-sol", "opus", "sonnet", "haiku", "fable"];
512
520
 
513
521
  // What each key of `swarm.explore` means when a repository omits it. The kit names no tool; a
@@ -65,7 +65,7 @@ recorded.
65
65
  |---|---|
66
66
  | A review states its verdict and the sha it reviewed on its first line | `report-stop.mjs`, on `SubagentHandback` and `SubagentStop` |
67
67
  | An implementer reports the failing test before the passing one | `report-stop.mjs` |
68
- | A task is reviewed before the next implementer starts on its branch | `dispatch-guard.mjs`, through `task-gate.mjs` |
68
+ | A task is reviewed before the next implementer starts on its branch, unless CI on the stop head is not green: the review runs once CI is green | `dispatch-guard.mjs`, through `task-gate.mjs` |
69
69
  | A fix round goes back to the implementer that wrote the task | `dispatch-guard.mjs`, through `task-gate.mjs` |
70
70
  | A merge pins the head that an APPROVED review named, or a head inside the direct lane, whose limits come from the commit the PR merges into | `merge-guard.mjs`, through `direct-lane.mjs` |
71
71
  | An issue that a merge names is closed, or has a comment after the merge | `issue-gate.mjs`, on `Stop` |