architecture-harness 0.16.0 → 0.17.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.
Files changed (109) hide show
  1. package/package.json +8 -3
  2. package/src/cli/bash-command-guard.mjs +25 -10
  3. package/src/cli/bash-command-guard.test.mjs +30 -0
  4. package/src/cli/bash-edit-guard.mjs +28 -7
  5. package/src/cli/bash-edit-guard.test.mjs +24 -0
  6. package/src/cli/check-registries.test.mjs +181 -0
  7. package/src/cli/check.mjs +130 -9
  8. package/src/cli/cli.test.mjs +215 -2
  9. package/src/cli/contract-history.mjs +46 -0
  10. package/src/cli/contract-history.test.mjs +118 -0
  11. package/src/cli/controller-guard.mjs +73 -0
  12. package/src/cli/controller-guard.test.mjs +119 -0
  13. package/src/cli/dispatch-guard.mjs +9 -3
  14. package/src/cli/dispatch-reminder.mjs +19 -11
  15. package/src/cli/dispatch-reminder.test.mjs +32 -0
  16. package/src/cli/dispatch.mjs +3 -0
  17. package/src/cli/dispatch.test.mjs +15 -1
  18. package/src/cli/doctor.mjs +2 -1
  19. package/src/cli/explore-guard.mjs +2 -2
  20. package/src/cli/gh-merge-command.mjs +228 -0
  21. package/src/cli/gh-merge-command.test.mjs +273 -0
  22. package/src/cli/gh-run.mjs +30 -0
  23. package/src/cli/gh-run.test.mjs +22 -0
  24. package/src/cli/git-hooks.test.mjs +28 -0
  25. package/src/cli/git-read.mjs +42 -0
  26. package/src/cli/git-read.test.mjs +94 -0
  27. package/src/cli/init.mjs +7 -3
  28. package/src/cli/issue-gate.mjs +169 -0
  29. package/src/cli/issue-gate.test.mjs +234 -0
  30. package/src/cli/ledger.mjs +136 -0
  31. package/src/cli/ledger.test.mjs +127 -0
  32. package/src/cli/merge-guard.mjs +193 -0
  33. package/src/cli/merge-guard.test.mjs +328 -0
  34. package/src/cli/plan-check.mjs +151 -0
  35. package/src/cli/plan-check.test.mjs +143 -0
  36. package/src/cli/plan-stop.mjs +101 -0
  37. package/src/cli/plan-stop.test.mjs +136 -0
  38. package/src/cli/plugin-agents.test.mjs +96 -8
  39. package/src/cli/pr-check.mjs +17 -5
  40. package/src/cli/pr-check.test.mjs +85 -4
  41. package/src/cli/prose.mjs +192 -0
  42. package/src/cli/prose.test.mjs +248 -0
  43. package/src/cli/qc.mjs +16 -0
  44. package/src/cli/registry-history.mjs +1 -1
  45. package/src/cli/report-stash.mjs +69 -0
  46. package/src/cli/report-stash.test.mjs +71 -0
  47. package/src/cli/report-stop.mjs +256 -0
  48. package/src/cli/report-stop.test.mjs +432 -0
  49. package/src/cli/shell-command.mjs +81 -6
  50. package/src/cli/shell-command.test.mjs +101 -1
  51. package/src/cli/task-gate.mjs +157 -0
  52. package/src/cli/task-gate.test.mjs +421 -0
  53. package/src/cli/workflow-hooks.test.mjs +72 -0
  54. package/src/cli/workflow-place.mjs +143 -0
  55. package/src/cli/workflow-place.test.mjs +146 -0
  56. package/src/cli/workflow-settings.mjs +77 -0
  57. package/src/cli/workflow-settings.test.mjs +79 -0
  58. package/src/cli/worktree.mjs +1 -1
  59. package/src/cli/worktree.test.mjs +19 -2
  60. package/src/config.mjs +84 -3
  61. package/src/config.test.mjs +38 -3
  62. package/src/descriptions.mjs +5 -1
  63. package/src/eslint/index.mjs +2 -0
  64. package/src/eslint/jsx.mjs +57 -0
  65. package/src/eslint/preset.mjs +32 -6
  66. package/src/eslint/preset.test.mjs +60 -0
  67. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  68. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  69. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  70. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  71. package/src/eslint/rules/registry-literal.mjs +36 -2
  72. package/src/eslint/rules.test.mjs +153 -0
  73. package/src/gates/call-args.mjs +90 -0
  74. package/src/gates/call-args.test.mjs +21 -0
  75. package/src/gates/config-floor.mjs +41 -20
  76. package/src/gates/config-floor.test.mjs +71 -1
  77. package/src/gates/contract-idempotency.mjs +103 -0
  78. package/src/gates/contract-idempotency.test.mjs +276 -0
  79. package/src/gates/contract-operations.mjs +120 -0
  80. package/src/gates/contract-operations.test.mjs +275 -0
  81. package/src/gates/contract-routes.mjs +82 -0
  82. package/src/gates/contract-routes.test.mjs +210 -0
  83. package/src/gates/registry-literal.mjs +79 -15
  84. package/src/gates/registry-literal.test.mjs +89 -0
  85. package/src/gates/saga-key.mjs +253 -0
  86. package/src/gates/saga-key.test.mjs +322 -0
  87. package/src/gates/scrub.mjs +108 -0
  88. package/src/gates/scrub.test.mjs +29 -0
  89. package/src/gates/tenant-isolation-test.mjs +80 -0
  90. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  91. package/src/gates/tenant-predicate.mjs +644 -91
  92. package/src/gates/tenant-predicate.test.mjs +662 -1
  93. package/src/prose-lines.mjs +49 -0
  94. package/src/prose-lines.test.mjs +63 -0
  95. package/src/registries.mjs +89 -0
  96. package/src/registries.test.mjs +44 -0
  97. package/src/vale-style.test.mjs +158 -0
  98. package/templates/docs/enforcement.md +26 -2
  99. package/templates/github/workflows/ci.yml +18 -1
  100. package/templates/quality-thresholds.json +1 -1
  101. package/templates/vale/.vale.ini +7 -0
  102. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  103. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  104. package/templates/vale/styles/Qc/Latin.yml +9 -0
  105. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  106. package/templates/vale/styles/Qc/Please.yml +6 -0
  107. package/templates/vale/styles/Qc/Progress.yml +9 -0
  108. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  109. package/templates/vale/styles/Qc/Utilize.yml +10 -0
@@ -0,0 +1,73 @@
1
+ #!/usr/bin/env node
2
+ // The PreToolUse trigger that keeps the main session a controller while `swarm.dispatch` is on: it edits only `swarm.review.controllerPaths`.
3
+ // It guards Write, Edit, MultiEdit and NotebookEdit; a shell write is only reported, by `bash-edit-guard.mjs`.
4
+
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { globMatcher } from "../glob.mjs";
8
+ import { checkoutRootOf } from "./checkout-root.mjs";
9
+ import { pathKey } from "./git-read.mjs";
10
+ import { commonDirOf } from "./ledger.mjs";
11
+ import { workflowAt } from "./workflow-settings.mjs";
12
+
13
+ const EDIT_TOOLS = new Set(["Write", "Edit", "MultiEdit", "NotebookEdit"]);
14
+
15
+ const deny = (reason) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", permissionDecision: "deny", permissionDecisionReason: reason } });
16
+ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
17
+
18
+ function sameRepository(a, b) {
19
+ const [left, right] = [commonDirOf(a), commonDirOf(b)];
20
+ return left !== null && right !== null && pathKey(left) === pathKey(right);
21
+ }
22
+
23
+ /** True when `rel` matches a controller glob. Windows paths ignore case, so both sides are lowercased there. */
24
+ export function isControllerPath(rel, controllerPaths, platform = process.platform) {
25
+ if (platform !== "win32") return globMatcher(controllerPaths)(rel);
26
+ return globMatcher(controllerPaths.map((glob) => glob.toLowerCase()))(rel.toLowerCase());
27
+ }
28
+
29
+ /** The verdict on one edit. @returns the hook output, or null to let the edit run with no message. */
30
+ export function decide(call, platform = process.platform) {
31
+ if (call.hook_event_name !== "PreToolUse" || !EDIT_TOOLS.has(call.tool_name)) return null;
32
+ if (typeof call.agent_id === "string" && call.agent_id !== "") return null;
33
+ const input = call.tool_input ?? {};
34
+ const target = input.file_path ?? input.notebook_path;
35
+ if (typeof target !== "string" || target === "") return null;
36
+ const cwd = call.cwd ?? process.cwd();
37
+ let workflow;
38
+ try {
39
+ workflow = workflowAt(cwd);
40
+ } catch (error) {
41
+ return context(`Controller guard is off: ${error.message}`);
42
+ }
43
+ if (!workflow) return null;
44
+ const file = path.resolve(cwd, target);
45
+ const fileRoot = checkoutRootOf(path.dirname(file));
46
+ if (!fileRoot || !sameRepository(fileRoot, workflow.root)) return null;
47
+ const rel = path.relative(fileRoot, file).replaceAll("\\", "/");
48
+ const { controllerPaths } = workflow.review;
49
+ if (isControllerPath(rel, controllerPaths, platform)) return null;
50
+ return deny(
51
+ `Controller guard: while swarm.dispatch is on, the main session edits only swarm.review.controllerPaths (${controllerPaths.join(", ")}), ` +
52
+ `and ${rel} is outside them. Write a brief and dispatch an implementer for this change. ` +
53
+ "For a path the controller owns, add its glob to swarm.review.controllerPaths in qc.config.json.",
54
+ );
55
+ }
56
+
57
+ async function readStdin() {
58
+ let data = "";
59
+ for await (const chunk of process.stdin) data += chunk;
60
+ return data;
61
+ }
62
+
63
+ const isEntryPoint = process.argv[1] !== undefined && fileURLToPath(import.meta.url) === process.argv[1];
64
+ if (isEntryPoint) {
65
+ let call = null;
66
+ try {
67
+ call = JSON.parse(await readStdin());
68
+ } catch {
69
+ // Not hook input, so there is no edit to judge.
70
+ }
71
+ const output = call ? decide(call) : null;
72
+ if (output) process.stdout.write(JSON.stringify(output));
73
+ }
@@ -0,0 +1,119 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { test } from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+ import { decide, isControllerPath } from "./controller-guard.mjs";
9
+
10
+ const HOOK = fileURLToPath(new URL("./controller-guard.mjs", import.meta.url));
11
+ const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe", encoding: "utf8" }).trim();
12
+
13
+ /** A checkout with the checks on and a linked worktree, another repository, and a folder outside any checkout. */
14
+ function workspace(t, dispatchConfig = { swarm: { dispatch: {} } }) {
15
+ const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-controller-")));
16
+ t.after(() => rmSync(base, { recursive: true, force: true }));
17
+ const main = path.join(base, "main");
18
+ const other = path.join(base, "other");
19
+ git(base, "init", "-q", "-b", "main", main);
20
+ git(base, "init", "-q", "-b", "main", other);
21
+ for (const [key, value] of [["user.name", "qc"], ["user.email", "qc@example.com"], ["commit.gpgsign", "false"]]) {
22
+ git(main, "config", key, value);
23
+ }
24
+ writeFileSync(path.join(main, "a.txt"), "a\n");
25
+ git(main, "add", ".");
26
+ git(main, "commit", "-q", "-m", "init");
27
+ writeFileSync(path.join(main, "qc.config.json"), JSON.stringify(dispatchConfig));
28
+ const linked = path.join(base, "linked");
29
+ git(main, "worktree", "add", "-q", "-b", "feat/1-x", linked);
30
+ const scratch = path.join(base, "scratch");
31
+ mkdirSync(scratch);
32
+ return { main, other, linked, scratch };
33
+ }
34
+
35
+ const edit = (cwd, file_path, tool_name = "Edit", extra = {}) => ({
36
+ session_id: "s",
37
+ cwd,
38
+ hook_event_name: "PreToolUse",
39
+ tool_name,
40
+ tool_input: tool_name === "NotebookEdit" ? { notebook_path: file_path } : { file_path },
41
+ ...extra,
42
+ });
43
+ const denied = (output) => output?.hookSpecificOutput?.permissionDecisionReason ?? null;
44
+
45
+ test("with swarm.dispatch off, the main session edits anything", (t) => {
46
+ const ws = workspace(t, { swarm: {} });
47
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"))), null);
48
+ });
49
+
50
+ test("a subagent's edit is left alone", (t) => {
51
+ const ws = workspace(t);
52
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"), "Write", { agent_id: "agent-1" })), null);
53
+ });
54
+
55
+ test("the main session's edit of code in the checkout, or in its worktree, is refused", (t) => {
56
+ const ws = workspace(t);
57
+ for (const [file, rel] of [
58
+ [path.join(ws.main, "src", "a.ts"), "src/a.ts"],
59
+ [path.join(ws.main, "src", "notes.md"), "src/notes.md"],
60
+ [path.join(ws.linked, "src", "a.ts"), "src/a.ts"],
61
+ ]) {
62
+ assert.match(denied(decide(edit(ws.main, file))) ?? "", new RegExp(`${rel.replace(".", "\\.")} is outside them`), file);
63
+ }
64
+ assert.match(denied(decide(edit(ws.main, path.join(ws.main, "nb.ipynb"), "NotebookEdit"))) ?? "", /nb\.ipynb/);
65
+ });
66
+
67
+ test("the controller's own paths, a path outside the checkout, and another repository pass", (t) => {
68
+ const ws = workspace(t);
69
+ for (const file of [
70
+ path.join(ws.main, "docs", "plan.md"),
71
+ path.join(ws.main, "README.md"),
72
+ path.join(ws.main, "qc.config.json"),
73
+ path.join(ws.main, ".claude", "settings.json"),
74
+ path.join(ws.main, "pkg", ".claude", "rules", "a.md"),
75
+ path.join(ws.linked, "docs", "a.md"),
76
+ path.join(ws.scratch, "brief.md"),
77
+ path.join(ws.other, "src", "a.ts"),
78
+ ]) {
79
+ assert.equal(decide(edit(ws.main, file, "Write")), null, file);
80
+ }
81
+ });
82
+
83
+ test("a Windows path with either separator is judged the same", (t) => {
84
+ const ws = workspace(t);
85
+ const file = path.join(ws.main, "src", "a.ts");
86
+ assert.ok(denied(decide(edit(ws.main, file.replaceAll("\\", "/")))));
87
+ if (process.platform === "win32") assert.ok(denied(decide(edit(ws.main, file.replaceAll("/", "\\")))));
88
+ });
89
+
90
+ test("a repository replaces the controller paths", (t) => {
91
+ const ws = workspace(t, { swarm: { dispatch: {}, review: { controllerPaths: ["src/**"] } } });
92
+ assert.equal(decide(edit(ws.main, path.join(ws.main, "src", "a.ts"))), null);
93
+ assert.ok(denied(decide(edit(ws.main, path.join(ws.main, "docs", "a.md")))));
94
+ });
95
+
96
+ test("a config error is reported as context, never as a refusal", (t) => {
97
+ const ws = workspace(t, { swarm: { dispatch: "on" } });
98
+ const output = decide(edit(ws.main, path.join(ws.main, "src", "a.ts")));
99
+ assert.match(output?.hookSpecificOutput?.additionalContext ?? "", /Controller guard is off/);
100
+ });
101
+
102
+ test("the hook process prints the deny", (t) => {
103
+ const ws = workspace(t);
104
+ const result = spawnSync(process.execPath, [HOOK], { input: JSON.stringify(edit(ws.main, path.join(ws.main, "src", "a.ts"))), encoding: "utf8" });
105
+ assert.equal(result.status, 0, result.stderr);
106
+ assert.equal(JSON.parse(result.stdout).hookSpecificOutput.permissionDecision, "deny");
107
+ });
108
+
109
+ test("Windows reads a path with no regard to case, so the other systems do not", (t) => {
110
+ const ws = workspace(t);
111
+ const globs = ["docs/**", "*.md", "qc.config.json", "**/.claude/**"];
112
+ for (const rel of ["Docs/plan.md", "README.MD", "QC.config.json", "pkg/.CLAUDE/a.md"]) {
113
+ assert.equal(isControllerPath(rel, globs, "win32"), true, rel);
114
+ assert.equal(isControllerPath(rel, globs, "linux"), false, rel);
115
+ assert.equal(decide(edit(ws.main, path.join(ws.main, ...rel.split("/")), "Write"), "win32"), null, rel);
116
+ assert.ok(denied(decide(edit(ws.main, path.join(ws.main, ...rel.split("/")), "Write"), "linux")), rel);
117
+ }
118
+ assert.equal(isControllerPath("src/A.ts", globs, "win32"), false);
119
+ });
@@ -7,6 +7,7 @@ import os from "node:os";
7
7
  import { fileURLToPath } from "node:url";
8
8
  import { dispatchRefusal, dispatchSettingsAt, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
9
9
  import { claimSlot, reclaimSlot, releaseSlot, slotDirOf } from "./dispatch-slot.mjs";
10
+ import { judgeTask, recordDispatch } from "./task-gate.mjs";
10
11
 
11
12
  const output = (fields) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", ...fields } });
12
13
  const deny = (reason) => output({ permissionDecision: "deny", permissionDecisionReason: reason });
@@ -49,18 +50,23 @@ export function decide(call, tmp = os.tmpdir(), now = Date.now()) {
49
50
  const input = call.tool_input ?? {};
50
51
  const refusal = dispatchRefusal(input, settings);
51
52
  if (refusal) return deny(refusal);
53
+ // The task gate judges before the slot is claimed, so a refused task holds no slot.
54
+ const task = judgeTask(call, tmp);
55
+ if (task.refusal) return deny(task.refusal);
52
56
  const type = typeOf(input);
53
- if (!isImplementer(type, settings)) return null;
57
+ if (!isImplementer(type, settings)) return noted(recordDispatch(task));
54
58
  let holder;
55
59
  try {
56
60
  holder = claimSlot(dir, settings, now, idOf(call.tool_use_id));
57
61
  } catch {
58
62
  // A busy or read-only temp folder is the hook's own problem, never a reason to refuse a dispatch.
59
- return null;
63
+ return noted(recordDispatch(task));
60
64
  }
61
- return holder ? deny(slotRefusal({ type, ...holder })) : null;
65
+ return holder ? deny(slotRefusal({ type, ...holder })) : noted(recordDispatch(task));
62
66
  }
63
67
 
68
+ const noted = (note) => (note ? context(note) : null);
69
+
64
70
  async function readStdin() {
65
71
  let data = "";
66
72
  for await (const chunk of process.stdin) data += chunk;
@@ -3,7 +3,7 @@
3
3
  // and fork, because a rule held only in the conversation is lost to a compaction.
4
4
 
5
5
  import { fileURLToPath } from "node:url";
6
- import { dispatchSettingsAt, exploreSettingsAt } from "./dispatch.mjs";
6
+ import { dispatchSettingsAt, exploreSettingsAt, exploreToolLines } from "./dispatch.mjs";
7
7
 
8
8
  export const REMINDER =
9
9
  "Subagent workflow (swarm.dispatch in qc.config.json): run a plan with superpowers:subagent-driven-development. " +
@@ -11,7 +11,8 @@ export const REMINDER =
11
11
  "architecture:sdd-reviewer to review it; before merge, dispatch architecture:sdd-branch-reviewer to review the " +
12
12
  "whole branch. The planner and the branch reviewer run on opus, the implementer and the task reviewer on sonnet. " +
13
13
  "Run one implementer at a time: a hook refuses a second while one runs. Name a model on any other dispatch, and " +
14
- "pass each brief as a file path.";
14
+ "pass each brief as a file path. Name the worktree on a prompt line `Worktree: <path>`. A reviewer starts with " +
15
+ "`VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>`, and a merge passes `--match-head-commit <sha>`.";
15
16
 
16
17
  const context = (eventName, text) => ({ hookSpecificOutput: { hookEventName: eventName, additionalContext: text } });
17
18
 
@@ -21,23 +22,30 @@ const slotsLine = ({ implementerSlots }) =>
21
22
  ? ` 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
  : "";
23
24
 
24
- /** One added line naming `swarm.explore`'s tools, or "" when the section is off or names none. */
25
- function exploreLine(cwd) {
25
+ /** The explore tools, or null when the section is off, names none, or does not parse. */
26
+ function exploreToolsAt(cwd) {
26
27
  let settings;
27
28
  try {
28
29
  settings = exploreSettingsAt(cwd);
29
30
  } catch {
30
- // The explore guard and hint each report their own config error; the dispatch note stays unaffected.
31
- return "";
31
+ // The explore guard and hint each report their own config error; the notes stay unaffected.
32
+ return null;
32
33
  }
33
- if (!settings || settings.tools.length === 0) return "";
34
- return ` The repository's own explore tools: ${settings.tools.map((tool) => tool.name).join(", ")}.`;
34
+ return settings && settings.tools.length > 0 ? settings.tools : null;
35
+ }
36
+
37
+ /** One added line naming `swarm.explore`'s tools, or "" when there are none. */
38
+ function exploreLine(cwd) {
39
+ const tools = exploreToolsAt(cwd);
40
+ return tools ? ` The repository's own explore tools: ${tools.map((tool) => tool.name).join(", ")}.` : "";
35
41
  }
36
42
 
37
- /** @returns the hook output for a subagent's own start, or null when `swarm.explore` names no tools. */
43
+ /** A subagent may carry no MCP tool, so its note gives each tool's command, not only its name. */
38
44
  function decideSubagentStart(cwd) {
39
- const line = exploreLine(cwd).trim();
40
- return line === "" ? null : context("SubagentStart", line);
45
+ const tools = exploreToolsAt(cwd);
46
+ if (!tools) return null;
47
+ const lines = ["The repository's own explore tools, and how to run each:", ...exploreToolLines(tools)];
48
+ return context("SubagentStart", lines.join("\n"));
41
49
  }
42
50
 
43
51
  /** @returns the hook output, or null when the checkout turns on neither `swarm.dispatch` nor `swarm.explore`. */
@@ -49,6 +49,9 @@ test("the note names the workflow, the four types, the model tiers, and the one-
49
49
  "architecture:sdd-reviewer",
50
50
  "architecture:sdd-branch-reviewer",
51
51
  "one implementer at a time",
52
+ "Worktree: <path>",
53
+ "VERDICT: <APPROVED|CHANGES_REQUIRED> <sha>",
54
+ "--match-head-commit <sha>",
52
55
  ]) {
53
56
  assert.ok(REMINDER.includes(word), word);
54
57
  }
@@ -140,3 +143,32 @@ test("a limit above 1 adds one line stating it, and a limit of 1 leaves the note
140
143
  assert.match(text, /up to 3 implementers at once/);
141
144
  assert.equal(decide(start(one, "startup")).hookSpecificOutput.additionalContext, REMINDER);
142
145
  });
146
+
147
+ test("SubagentStart gives each tool's use and command, in config order, since a plugin agent carries no MCP tool", (t) => {
148
+ const [on] = checkouts(t, [
149
+ {
150
+ swarm: {
151
+ explore: {
152
+ tools: [
153
+ { name: "slm-rerank", use: "find the files for a concept", how: 'slm-rerank -q "<question>" --stub -k 5' },
154
+ { name: "GitNexus", use: "callers and callees", how: "gitnexus context <symbol> -r repo" },
155
+ ],
156
+ },
157
+ },
158
+ },
159
+ ]);
160
+ assert.equal(
161
+ decide(subagentStart(on)).hookSpecificOutput.additionalContext,
162
+ [
163
+ "The repository's own explore tools, and how to run each:",
164
+ '- slm-rerank: find the files for a concept (slm-rerank -q "<question>" --stub -k 5)',
165
+ "- GitNexus: callers and callees (gitnexus context <symbol> -r repo)",
166
+ ].join("\n"),
167
+ );
168
+ });
169
+
170
+ test("a swarm.explore section that does not parse leaves SubagentStart silent and the session note as REMINDER", (t) => {
171
+ const [bad] = checkouts(t, [{ swarm: { dispatch: {}, explore: { tools: "slm-rerank" } } }]);
172
+ assert.equal(decide(subagentStart(bad)), null);
173
+ assert.equal(decide(start(bad, "startup")).hookSpecificOutput.additionalContext, REMINDER);
174
+ });
@@ -102,6 +102,9 @@ export function exploreSettingsAt(cwd) {
102
102
  return exploreSettings(load(root).swarm);
103
103
  }
104
104
 
105
+ /** One `- name: use (how)` line per explore tool: the form every explore note and refusal shares. */
106
+ export const exploreToolLines = (tools) => tools.map((tool) => `- ${tool.name}: ${tool.use} (${tool.how})`);
107
+
105
108
  /** The type a dispatch names, trimmed. The Agent tool runs general-purpose when it names none. */
106
109
  export const typeOf = (input) =>
107
110
  typeof input.subagent_type === "string" && input.subagent_type.trim() !== "" ? input.subagent_type.trim() : DEFAULT_TYPE;
@@ -1,7 +1,7 @@
1
1
  import { strict as assert } from "node:assert";
2
2
  import { test } from "node:test";
3
3
  import { defaults, dispatchDefaults, merge } from "../config.mjs";
4
- import { dispatchRefusal, dispatchSettings, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
4
+ import { dispatchRefusal, dispatchSettings, exploreToolLines, familyOf, isImplementer, slotRefusal, typeOf } from "./dispatch.mjs";
5
5
 
6
6
  test("a swarm section with no dispatch key keeps the guard off", () => {
7
7
  assert.equal(dispatchSettings({}), null);
@@ -192,3 +192,17 @@ test("a refusal over a limit above 1 names the limit and each holder, and one at
192
192
  assert.match(one, /holds the one implementer slot/);
193
193
  assert.doesNotMatch(one, /use-1/);
194
194
  });
195
+
196
+ test("exploreToolLines gives one `- name: use (how)` line per tool, in config order", () => {
197
+ assert.deepEqual(
198
+ exploreToolLines([
199
+ { name: "slm-rerank", use: "find the files for a concept", how: 'slm-rerank -q "<question>" --stub -k 5' },
200
+ { name: "GitNexus", use: "callers and callees", how: "gitnexus context <symbol> -r repo" },
201
+ ]),
202
+ [
203
+ '- slm-rerank: find the files for a concept (slm-rerank -q "<question>" --stub -k 5)',
204
+ "- GitNexus: callers and callees (gitnexus context <symbol> -r repo)",
205
+ ],
206
+ );
207
+ assert.deepEqual(exploreToolLines([]), []);
208
+ });
@@ -9,6 +9,7 @@ import { execFile } from "node:child_process";
9
9
  import { existsSync, readFileSync, readdirSync } from "node:fs";
10
10
  import path from "node:path";
11
11
  import { promisify } from "node:util";
12
+ import { requiredHooks } from "../config.mjs";
12
13
  import { hookDrift } from "./git-hooks.mjs";
13
14
 
14
15
  const execFileAsync = promisify(execFile);
@@ -125,7 +126,7 @@ export async function runDoctor(config) {
125
126
 
126
127
  /** @returns true when an installed git hook lacks a call `hooks.required` names. */
127
128
  function reportHooks(config) {
128
- const { problems, notes } = hookDrift(config.root, config.hooks?.required ?? {});
129
+ const { problems, notes } = hookDrift(config.root, requiredHooks(config));
129
130
  for (const problem of problems) console.error(`FAIL hooks ${problem.path}: ${problem.detail}`);
130
131
  for (const note of notes) console.log(`NOTE hooks ${note}`);
131
132
  if (problems.length === 0) console.log("OK hooks each git hook makes the calls hooks.required names");
@@ -21,7 +21,7 @@ import path from "node:path";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import { globMatcher } from "../glob.mjs";
23
23
  import { checkoutRootOf } from "./checkout-root.mjs";
24
- import { exploreSettingsAt } from "./dispatch.mjs";
24
+ import { exploreSettingsAt, exploreToolLines } from "./dispatch.mjs";
25
25
  import { slotDirOf } from "./dispatch-slot.mjs";
26
26
 
27
27
  const BINARY_EXTENSIONS = new Set(["png", "jpg", "jpeg", "gif", "webp", "svg", "pdf", "ipynb"]);
@@ -149,7 +149,7 @@ function exceedsLineBudget(file, maxLines) {
149
149
  }
150
150
 
151
151
  function refusalMessage(tools) {
152
- const lines = tools.map((tool) => `- ${tool.name}: ${tool.use} (${tool.how})`);
152
+ const lines = exploreToolLines(tools);
153
153
  lines.push("Read a range with offset and limit, or read the same file again to read it whole.");
154
154
  return lines.join("\n");
155
155
  }
@@ -0,0 +1,228 @@
1
+ // A fragment that finds each `gh pr merge` in a Bash or PowerShell command line, with the head sha it pins,
2
+ // the PR and repository it names, and the GH_* settings the command makes for gh.
3
+ // It also finds each `gh api` call to a PR's merge endpoint or with a `mergePullRequest` mutation, which merge with no review check.
4
+
5
+ import { readFileSync, statSync } from "node:fs";
6
+ import os from "node:os";
7
+ import path from "node:path";
8
+ import { nestedCommand, programName } from "./bash-command-guard.mjs";
9
+ import { commandEnv, commandWords } from "./shell-command.mjs";
10
+ import { nativePath } from "./workflow-place.mjs";
11
+
12
+ const GH_SETTINGS = ["GH_CONFIG_DIR", "GH_HOST", "GH_REPO"];
13
+ const VALUE_FLAGS = new Set(["-b", "--body", "-F", "--body-file", "-t", "--subject", "-A", "--author-email", "--match-head-commit", "--repo"]);
14
+ const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)=(.*)$/s;
15
+ const POWERSHELL_ENV = /^\$env:([A-Za-z_][A-Za-z0-9_]*)(?:=(.*))?$/is;
16
+ const MERGE_ENDPOINT = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?(?:repos\/[^/]+\/[^/]+\/)?pulls\/\d+\/merge\/?(?:\?.*)?$/;
17
+ const MERGE_MUTATION = /\bmergePullRequest\b/;
18
+ const GRAPHQL_ENDPOINT = /(?:^|\/)graphql\/?(?:\?.*)?$/;
19
+ const FIELD_FLAGS = new Set(["--field"]);
20
+ const PR_URL = /^https?:\/\/[^/]+\/([^/]+\/[^/]+)\/pull\/\d+/;
21
+ const REST_PATH = /^(?:https?:\/\/[^/]+\/(?:api\/v3\/)?)?\/?repos\//;
22
+ /** The short flags of `gh pr merge` and of `gh api` that take a value, and the long flags of `gh api` that do. */
23
+ const MERGE_VALUE_LETTERS = "bFtAR";
24
+ const API_VALUE_LETTERS = "FfHXqtp";
25
+ const API_VALUE_FLAGS = new Set(["--field", "--raw-field", "--header", "--method", "--jq", "--template", "--input", "--hostname", "--cache", "--preview"]);
26
+ const MAX_QUERY_BYTES = 1024 * 1024;
27
+
28
+ /** Only the settings that choose gh's account or host; a token is a credential and is never kept. */
29
+ const kept = (env) => Object.fromEntries(Object.entries(env).filter(([name]) => GH_SETTINGS.includes(name)));
30
+
31
+ /** The settings one segment makes for the segments after it: `export NAME=value`, or PowerShell's `$env:NAME = value`. */
32
+ function settingsMadeBy(segment) {
33
+ const [first, second, third] = segment.words;
34
+ if (first === "export") {
35
+ return kept(Object.fromEntries(segment.words.slice(1).map((word) => ASSIGNMENT.exec(word)).filter(Boolean).map((m) => [m[1], m[2]])));
36
+ }
37
+ const powershell = POWERSHELL_ENV.exec(first ?? "");
38
+ if (!powershell) return {};
39
+ const value = powershell[2] ?? (second === "=" ? third : undefined);
40
+ return value === undefined ? {} : kept({ [powershell[1].toUpperCase()]: value });
41
+ }
42
+
43
+ /** The settings a command makes for gh alone: its `NAME=value` words, before it and after `env` or `sudo`. */
44
+ const prefixOf = (segment) => kept(commandEnv(segment));
45
+
46
+ /** The repository a `-R` or `--repo` flag names, as `-R o/r`, `-Ro/r`, `-R=o/r`, `--repo o/r` or `--repo=o/r`. */
47
+ const REPO_FLAG = /^(?:-R(.+)|-R|--repo(?:=(.*))?)$/s;
48
+
49
+ /** Skips the flags gh reads before its group and between its group and verb, and keeps the repository they name. */
50
+ function leadingFlags(words) {
51
+ let repo = null;
52
+ let i = 0;
53
+ for (; i < words.length && words[i].startsWith("-") && words[i] !== "-"; i++) {
54
+ const match = REPO_FLAG.exec(words[i]);
55
+ if (!match) continue;
56
+ // `-R=o/r` keeps its `=` in the first group; `--repo=` with nothing after it names no repository.
57
+ const attached = match[1]?.replace(/^=/, "") ?? match[2];
58
+ repo = attached === undefined ? (words[++i] ?? null) : attached || null;
59
+ }
60
+ return { repo, rest: words.slice(i) };
61
+ }
62
+
63
+ /**
64
+ * The words after `gh` as a command: its group, its verb, the words after the verb, and the repository a flag before the verb names.
65
+ * `gh pr -R o/r merge 60` and `gh -R o/r pr merge 60` are `pr merge 60`. `rest` holds every word after the group, flags kept.
66
+ */
67
+ function ghCommand(words) {
68
+ const first = leadingFlags(words);
69
+ const [group, ...rest] = first.rest;
70
+ const second = leadingFlags(rest);
71
+ const [verb, ...args] = second.rest;
72
+ return { group, verb, args, rest, repo: second.repo ?? first.repo };
73
+ }
74
+
75
+ function mergeOf(args) {
76
+ const merge = { sha: null, repo: null, selector: null, auto: false };
77
+ for (let i = 0; i < args.length; i++) {
78
+ const arg = args[i];
79
+ // pflag reads `-Rvalue`, `-R=value`, and a cluster of short flags that ends in -R (`-sRvalue`, `-sR value`).
80
+ const cluster = /^-([A-Za-z]*)R(.*)$/s.exec(arg);
81
+ if (cluster && !new RegExp(`[${MERGE_VALUE_LETTERS}]`).test(cluster[1])) {
82
+ const value = cluster[2] === "" ? args[++i] : cluster[2].replace(/^=/, "");
83
+ merge.repo = value ?? null;
84
+ continue;
85
+ }
86
+ const at = arg.startsWith("--") ? arg.indexOf("=") : -1;
87
+ const flag = at === -1 ? arg : arg.slice(0, at);
88
+ if (flag === "--disable-auto") return null;
89
+ if (flag === "--auto") merge.auto = true;
90
+ if (VALUE_FLAGS.has(flag)) {
91
+ const value = at === -1 ? args[++i] : arg.slice(at + 1);
92
+ if (flag === "--match-head-commit") merge.sha = value ?? null;
93
+ if (flag === "--repo") merge.repo = value ?? null;
94
+ } else if (!arg.startsWith("-") && merge.selector === null) {
95
+ merge.selector = arg;
96
+ }
97
+ }
98
+ return merge;
99
+ }
100
+
101
+ /** Every gh call in the command, in order, as `{ words, env }` with the words after `gh`; a nested shell's lines count. */
102
+ function ghCalls(command, parse) {
103
+ const calls = [];
104
+ let env = {};
105
+ for (const segment of parse(command)) {
106
+ env = { ...env, ...settingsMadeBy(segment) };
107
+ const nested = nestedCommand(segment);
108
+ if (nested) {
109
+ calls.push(...ghCalls(nested.command, nested.parse).map((call) => ({ ...call, env: { ...env, ...prefixOf(segment), ...call.env } })));
110
+ continue;
111
+ }
112
+ const [program, ...words] = commandWords(segment);
113
+ if (programName(program) === "gh") calls.push({ words, env: { ...env, ...prefixOf(segment) } });
114
+ }
115
+ return calls;
116
+ }
117
+
118
+ /** Every `gh pr merge` in the command, in order, the lines of a nested `bash -c` or `pwsh -Command` included. */
119
+ export function ghMerges(command, parse) {
120
+ const merges = [];
121
+ for (const { words, env } of ghCalls(command, parse)) {
122
+ const { group, verb, args, repo } = ghCommand(words);
123
+ if (group !== "pr" || verb !== "merge") continue;
124
+ const merge = mergeOf(args);
125
+ if (!merge) continue;
126
+ // The repository comes from a PR URL first, then -R or --repo (the one written last), then GH_REPO. GH_REPO is no setting to keep.
127
+ const { GH_REPO: fromEnv, ...settings } = env;
128
+ merge.repo = PR_URL.exec(merge.selector ?? "")?.[1] ?? merge.repo ?? repo ?? fromEnv ?? null;
129
+ merges.push({ ...merge, env: settings });
130
+ }
131
+ return merges;
132
+ }
133
+
134
+ /** A file path as the command wrote it: `~` and a Git Bash `/c/...` spelling resolve the way the shell would. */
135
+ function fileOf(cwd, spelled) {
136
+ const file = nativePath(spelled.replace(/^~(?=$|[\\/])/, os.homedir()));
137
+ return path.resolve(cwd, file);
138
+ }
139
+
140
+ /**
141
+ * The files a `gh api` call reads its body from: each `-F key=@file`, and `--input file`. `-` is standard input.
142
+ * pflag reads a short flag with its value attached (`-Fkey=@file`, `-F=key=@file`) and a cluster of short flags
143
+ * that ends in `-F` (`-iFkey=@file`, `-iF key=@file`). A letter that takes a value ends a cluster, so it hides an `F` after it.
144
+ */
145
+ function bodyFiles(args) {
146
+ const files = [];
147
+ const add = (field) => {
148
+ if (/^[^=]*=@/.test(field)) files.push(field.slice(field.indexOf("@") + 1));
149
+ };
150
+ for (let i = 0; i < args.length; i++) {
151
+ const arg = args[i];
152
+ const cluster = /^-([A-Za-z]*)F(.*)$/s.exec(arg);
153
+ if (cluster && !/[fFHXqt]/.test(cluster[1])) {
154
+ const value = cluster[2] === "" ? args[++i] : cluster[2].replace(/^=/, "");
155
+ if (value !== undefined) add(value);
156
+ continue;
157
+ }
158
+ const at = arg.startsWith("--") ? arg.indexOf("=") : -1;
159
+ const flag = at === -1 ? arg : arg.slice(0, at);
160
+ if (flag !== "--input" && !FIELD_FLAGS.has(flag)) continue;
161
+ const value = at === -1 ? args[++i] : arg.slice(at + 1);
162
+ if (value === undefined) continue;
163
+ if (flag === "--input") files.push(value);
164
+ else add(value);
165
+ }
166
+ return files;
167
+ }
168
+
169
+ /** The text of a query file, or null when it is standard input, too large, or unreadable. */
170
+ function queryText(cwd, spelled) {
171
+ if (spelled === "-") return null;
172
+ try {
173
+ const file = fileOf(cwd, spelled);
174
+ if (statSync(file).size > MAX_QUERY_BYTES) return null;
175
+ return readFileSync(file, "utf8");
176
+ } catch {
177
+ return null;
178
+ }
179
+ }
180
+
181
+ /** True for a `repos/` path that stays inside `repos/`: no `..` segment, spelled or percent-encoded, and no end at `graphql`. */
182
+ const isRestPath = (endpoint) => REST_PATH.test(endpoint) && !/(?:^|\/)(?:\.|%2e){2}(?:\/|$)/i.test(endpoint) && !GRAPHQL_ENDPOINT.test(endpoint);
183
+
184
+ /** The endpoint of a `gh api` call: its first word that is no flag and no flag's value, or null. */
185
+ function apiEndpoint(args) {
186
+ for (let i = 0; i < args.length; i++) {
187
+ const arg = args[i];
188
+ if (arg.startsWith("--")) {
189
+ if (!arg.includes("=") && API_VALUE_FLAGS.has(arg)) i++;
190
+ } else if (arg.startsWith("-") && arg.length > 1) {
191
+ // A value letter takes the rest of the word, or the next word when it ends the cluster.
192
+ const letter = [...arg.slice(1)].findIndex((char) => API_VALUE_LETTERS.includes(char));
193
+ if (letter !== -1 && letter === arg.length - 2) i++;
194
+ } else {
195
+ return arg;
196
+ }
197
+ }
198
+ return null;
199
+ }
200
+
201
+ /**
202
+ * Each `gh api` call that merges with no review check, as `{ endpoint, unreadable }`. `endpoint` is the PR merge
203
+ * endpoint as written, or the GraphQL URL as written (`graphql` when the call spells none). A call holds a
204
+ * `mergePullRequest` mutation when any argument, or any query file it reads, names it, whatever the URL spelling.
205
+ * A GraphQL call whose query file the guard cannot read fails closed, and `unreadable` names that file.
206
+ * A call whose endpoint is a `repos/` REST path that stays inside it holds no mutation, so its arguments and files are not searched.
207
+ * @param options.cwd the folder a relative query file resolves against
208
+ */
209
+ export function ghApiMerges(command, parse, { cwd = process.cwd() } = {}) {
210
+ return ghCalls(command, parse)
211
+ .map(({ words }) => ghCommand(words))
212
+ .filter(({ group }) => group === "api")
213
+ .flatMap(({ rest: args }) => {
214
+ const found = args.filter((word) => MERGE_ENDPOINT.test(word)).map((endpoint) => ({ endpoint }));
215
+ if (isRestPath(apiEndpoint(args) ?? "")) return found;
216
+ const graphql = args.find((word) => GRAPHQL_ENDPOINT.test(word));
217
+ let mutation = args.some((word) => MERGE_MUTATION.test(word));
218
+ let unreadable;
219
+ for (const file of bodyFiles(args)) {
220
+ const text = queryText(cwd, file);
221
+ if (text === null) unreadable ??= file;
222
+ else if (MERGE_MUTATION.test(text)) mutation = true;
223
+ }
224
+ if (mutation) found.push({ endpoint: graphql ?? "graphql" });
225
+ else if (graphql !== undefined && unreadable !== undefined) found.push({ endpoint: graphql, unreadable });
226
+ return found;
227
+ });
228
+ }