architecture-harness 0.16.0 → 0.18.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 (124) 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/budget-counter.mjs +25 -4
  7. package/src/cli/budget-guard.mjs +73 -4
  8. package/src/cli/budget-guard.test.mjs +111 -0
  9. package/src/cli/budget.mjs +3 -2
  10. package/src/cli/check-registries.test.mjs +181 -0
  11. package/src/cli/check.mjs +130 -9
  12. package/src/cli/cli.test.mjs +215 -2
  13. package/src/cli/context-signal.mjs +92 -0
  14. package/src/cli/context-signal.test.mjs +99 -0
  15. package/src/cli/contract-history.mjs +46 -0
  16. package/src/cli/contract-history.test.mjs +118 -0
  17. package/src/cli/controller-guard.mjs +73 -0
  18. package/src/cli/controller-guard.test.mjs +119 -0
  19. package/src/cli/dispatch-guard.mjs +14 -4
  20. package/src/cli/dispatch-guard.test.mjs +5 -6
  21. package/src/cli/dispatch-reminder.mjs +19 -11
  22. package/src/cli/dispatch-reminder.test.mjs +32 -0
  23. package/src/cli/dispatch.mjs +23 -2
  24. package/src/cli/dispatch.test.mjs +39 -1
  25. package/src/cli/doctor.mjs +2 -1
  26. package/src/cli/explore-guard.mjs +2 -2
  27. package/src/cli/explore-hint.mjs +67 -7
  28. package/src/cli/explore-hint.test.mjs +104 -4
  29. package/src/cli/gh-merge-command.mjs +228 -0
  30. package/src/cli/gh-merge-command.test.mjs +273 -0
  31. package/src/cli/gh-run.mjs +30 -0
  32. package/src/cli/gh-run.test.mjs +22 -0
  33. package/src/cli/git-hooks.test.mjs +28 -0
  34. package/src/cli/git-read.mjs +42 -0
  35. package/src/cli/git-read.test.mjs +94 -0
  36. package/src/cli/handoff-note.mjs +69 -0
  37. package/src/cli/handoff-note.test.mjs +71 -0
  38. package/src/cli/init.mjs +7 -3
  39. package/src/cli/issue-gate.mjs +169 -0
  40. package/src/cli/issue-gate.test.mjs +234 -0
  41. package/src/cli/ledger.mjs +138 -0
  42. package/src/cli/ledger.test.mjs +127 -0
  43. package/src/cli/merge-guard.mjs +193 -0
  44. package/src/cli/merge-guard.test.mjs +328 -0
  45. package/src/cli/plan-check.mjs +151 -0
  46. package/src/cli/plan-check.test.mjs +143 -0
  47. package/src/cli/plan-stop.mjs +101 -0
  48. package/src/cli/plan-stop.test.mjs +136 -0
  49. package/src/cli/plugin-agents.test.mjs +105 -8
  50. package/src/cli/pr-check.mjs +17 -5
  51. package/src/cli/pr-check.test.mjs +85 -4
  52. package/src/cli/prose.mjs +192 -0
  53. package/src/cli/prose.test.mjs +248 -0
  54. package/src/cli/qc.mjs +22 -0
  55. package/src/cli/registry-history.mjs +1 -1
  56. package/src/cli/report-stash.mjs +69 -0
  57. package/src/cli/report-stash.test.mjs +71 -0
  58. package/src/cli/report-stop.mjs +266 -0
  59. package/src/cli/report-stop.test.mjs +471 -0
  60. package/src/cli/shell-command.mjs +81 -6
  61. package/src/cli/shell-command.test.mjs +101 -1
  62. package/src/cli/task-gate.mjs +179 -0
  63. package/src/cli/task-gate.test.mjs +507 -0
  64. package/src/cli/tokens.mjs +239 -0
  65. package/src/cli/tokens.test.mjs +286 -0
  66. package/src/cli/transcript-usage.mjs +135 -0
  67. package/src/cli/transcript-usage.test.mjs +129 -0
  68. package/src/cli/workflow-hooks.test.mjs +72 -0
  69. package/src/cli/workflow-place.mjs +143 -0
  70. package/src/cli/workflow-place.test.mjs +146 -0
  71. package/src/cli/workflow-settings.mjs +77 -0
  72. package/src/cli/workflow-settings.test.mjs +79 -0
  73. package/src/cli/worktree.mjs +1 -1
  74. package/src/cli/worktree.test.mjs +19 -2
  75. package/src/config.mjs +99 -4
  76. package/src/config.test.mjs +38 -3
  77. package/src/descriptions.mjs +5 -1
  78. package/src/eslint/index.mjs +2 -0
  79. package/src/eslint/jsx.mjs +57 -0
  80. package/src/eslint/preset.mjs +32 -6
  81. package/src/eslint/preset.test.mjs +60 -0
  82. package/src/eslint/rules/durable-idempotency-key.mjs +26 -0
  83. package/src/eslint/rules/ime-safe-key.mjs +1 -50
  84. package/src/eslint/rules/mutation-control-pending.mjs +128 -0
  85. package/src/eslint/rules/no-supersession-trail.mjs +8 -4
  86. package/src/eslint/rules/registry-literal.mjs +36 -2
  87. package/src/eslint/rules.test.mjs +153 -0
  88. package/src/gates/call-args.mjs +90 -0
  89. package/src/gates/call-args.test.mjs +21 -0
  90. package/src/gates/config-floor.mjs +41 -20
  91. package/src/gates/config-floor.test.mjs +71 -1
  92. package/src/gates/contract-idempotency.mjs +103 -0
  93. package/src/gates/contract-idempotency.test.mjs +276 -0
  94. package/src/gates/contract-operations.mjs +120 -0
  95. package/src/gates/contract-operations.test.mjs +275 -0
  96. package/src/gates/contract-routes.mjs +82 -0
  97. package/src/gates/contract-routes.test.mjs +210 -0
  98. package/src/gates/registry-literal.mjs +79 -15
  99. package/src/gates/registry-literal.test.mjs +89 -0
  100. package/src/gates/saga-key.mjs +253 -0
  101. package/src/gates/saga-key.test.mjs +322 -0
  102. package/src/gates/scrub.mjs +108 -0
  103. package/src/gates/scrub.test.mjs +29 -0
  104. package/src/gates/tenant-isolation-test.mjs +80 -0
  105. package/src/gates/tenant-isolation-test.test.mjs +129 -0
  106. package/src/gates/tenant-predicate.mjs +644 -91
  107. package/src/gates/tenant-predicate.test.mjs +662 -1
  108. package/src/prose-lines.mjs +49 -0
  109. package/src/prose-lines.test.mjs +63 -0
  110. package/src/registries.mjs +89 -0
  111. package/src/registries.test.mjs +44 -0
  112. package/src/vale-style.test.mjs +158 -0
  113. package/templates/docs/enforcement.md +26 -2
  114. package/templates/github/workflows/ci.yml +18 -1
  115. package/templates/quality-thresholds.json +1 -1
  116. package/templates/vale/.vale.ini +7 -0
  117. package/templates/vale/styles/Qc/AndOr.yml +7 -0
  118. package/templates/vale/styles/Qc/InOrderTo.yml +6 -0
  119. package/templates/vale/styles/Qc/Latin.yml +9 -0
  120. package/templates/vale/styles/Qc/PassiveVoice.yml +21 -0
  121. package/templates/vale/styles/Qc/Please.yml +6 -0
  122. package/templates/vale/styles/Qc/Progress.yml +9 -0
  123. package/templates/vale/styles/Qc/SentenceLength.yml +6 -0
  124. package/templates/vale/styles/Qc/Utilize.yml +10 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "architecture-harness",
3
- "version": "0.16.0",
3
+ "version": "0.18.0",
4
4
  "type": "module",
5
5
  "description": "Architecture gates, lint rules and scaffolding for the bounded-vertical-slice architecture",
6
6
  "license": "MIT",
@@ -57,7 +57,8 @@
57
57
  "eslint-plugin-boundaries": ">=5",
58
58
  "eslint-plugin-sonarjs": ">=3",
59
59
  "@commitlint/lint": ">=19",
60
- "@commitlint/config-conventional": ">=19"
60
+ "@commitlint/config-conventional": ">=19",
61
+ "yaml": ">=2"
61
62
  },
62
63
  "peerDependenciesMeta": {
63
64
  "@typescript-eslint/eslint-plugin": {
@@ -77,6 +78,9 @@
77
78
  },
78
79
  "@commitlint/config-conventional": {
79
80
  "optional": true
81
+ },
82
+ "yaml": {
83
+ "optional": true
80
84
  }
81
85
  },
82
86
  "devDependencies": {
@@ -87,6 +91,7 @@
87
91
  "eslint": "^9",
88
92
  "eslint-plugin-boundaries": "^5",
89
93
  "eslint-plugin-sonarjs": "^3",
90
- "typescript": "^5"
94
+ "typescript": "^5",
95
+ "yaml": "^2.9.1"
91
96
  }
92
97
  }
@@ -12,6 +12,7 @@ import { commandWords, gitCall, segmentsOf } from "./shell-command.mjs";
12
12
 
13
13
  const HOOK_SCRIPTS = [
14
14
  "work-order-guard.mjs", "budget-guard.mjs", "bash-edit-guard.mjs", "worktree-isolation.mjs", "pre-edit-guard.sh",
15
+ "report-stop.mjs", "plan-stop.mjs", "merge-guard.mjs", "issue-gate.mjs", "controller-guard.mjs",
15
16
  ];
16
17
  const NO_VERIFY = "--no-verify";
17
18
  // The shortest prefix git could still expand to `--no-verify`.
@@ -26,11 +27,17 @@ const VALUE_OPTIONS = new Set([
26
27
  const COMMIT_VALUE_FLAGS = new Set(["m", "F", "C", "c", "t"]);
27
28
 
28
29
  /** The parser for each guarded tool. */
29
- const PARSERS = { Bash: segmentsOf, PowerShell: powershellSegments };
30
- /** The shells whose `-c` or `-Command` argument is a command line of its own, and the parser that reads it. */
31
- const NESTED = { bash: segmentsOf, sh: segmentsOf, pwsh: powershellSegments, powershell: powershellSegments };
30
+ export const PARSERS = { Bash: segmentsOf, PowerShell: powershellSegments };
31
+ /** A POSIX shell reads a command line from `-c`, alone or in a cluster of short flags: `-lc`, `-ic`, `-lic`, `-cl`. */
32
+ const POSIX_COMMAND_FLAG = /^-[A-Za-z]*c[A-Za-z]*$/;
33
+ const POWERSHELL_COMMAND_FLAG = /^-(c|command)$/i;
34
+ /** The shells whose `-c` or `-Command` argument is a command line of its own, the flag that names it, and the parser that reads it. */
35
+ const NESTED = Object.fromEntries([
36
+ ...["bash", "sh", "zsh", "dash", "ksh"].map((name) => [name, { flag: POSIX_COMMAND_FLAG, parse: segmentsOf }]),
37
+ ...["pwsh", "powershell"].map((name) => [name, { flag: POWERSHELL_COMMAND_FLAG, parse: powershellSegments }]),
38
+ ]);
32
39
 
33
- const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
40
+ export const programName = (word) => path.basename(word ?? "").toLowerCase().replace(/\.exe$/, "");
34
41
  const isNoVerify = (arg) => arg.length >= NO_VERIFY_MIN && NO_VERIFY.startsWith(arg);
35
42
 
36
43
  /** True when a commit or push names `--no-verify`, or a commit names `-n` alone or in a flag cluster. */
@@ -75,12 +82,20 @@ function runsTests(segment) {
75
82
  return [program, ...args].some((word) => programName(word) === "vitest");
76
83
  }
77
84
 
78
- /** @returns the command line a shell runs from `-c` or `-Command`, with its parser, or null. */
79
- function nestedCommand(segment) {
85
+ /**
86
+ * @returns the command line a shell runs from `-c` or `-Command`, or that `eval` runs from its words joined with spaces,
87
+ * with its parser, or null.
88
+ */
89
+ export function nestedCommand(segment) {
80
90
  const [program, ...args] = commandWords(segment);
81
- const parse = NESTED[programName(program)];
82
- const at = args.findIndex((arg) => /^-(c|command)$/i.test(arg));
83
- return parse && at !== -1 && args[at + 1] !== undefined ? { command: args[at + 1], parse } : null;
91
+ const name = programName(program);
92
+ if (name === "eval") return args.length > 0 ? { command: args.join(" "), parse: segmentsOf } : null;
93
+ const shell = Object.hasOwn(NESTED, name) ? NESTED[name] : null;
94
+ const at = shell ? args.findIndex((arg) => shell.flag.test(arg)) : -1;
95
+ if (at === -1) return null;
96
+ // A POSIX shell takes the first word after its flags as the command line, so `-c -- 'cmd'` and `-c +x 'cmd'` still find it.
97
+ const command = shell.parse === segmentsOf ? args.slice(at + 1).find((arg) => !/^[-+]/.test(arg)) : args[at + 1];
98
+ return command === undefined ? null : { command, parse: shell.parse };
84
99
  }
85
100
 
86
101
  const REASONS = {
@@ -90,7 +105,7 @@ const REASONS = {
90
105
  hooksPath:
91
106
  "`-c core.hooksPath=` points git away from the installed hooks, so the gates never run. Remove it.",
92
107
  script:
93
- "a hand run of a hook script writes a lease under a made-up session id, and that lease blocks later " +
108
+ "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 " +
94
109
  "edits in the worktree for hours. Test a hook only through its own suite (`node --test`), in temporary folders.",
95
110
  };
96
111
 
@@ -42,6 +42,31 @@ test("a commit or push that skips the git hooks is denied", (t) => {
42
42
  }
43
43
  });
44
44
 
45
+ test("git commit --no-verify inside bash -lc, env, sudo, and an if block is refused", (t) => {
46
+ const ws = workspace(t);
47
+ for (const command of [
48
+ `bash -lc 'git commit --no-verify -m x'`,
49
+ `bash -ic "git commit -n -m x"`,
50
+ `sh -c 'git push --no-verify'`,
51
+ `env git commit -n -m x`,
52
+ `env -i HOME=/h git commit --no-verify -m x`,
53
+ `sudo -u ci git push --no-verify`,
54
+ `command git commit -n -m x`,
55
+ `timeout 60 git commit --no-verify -m x`,
56
+ `eval 'git commit --no-verify -m x'`,
57
+ `eval git commit -n -m x`,
58
+ `if true; then git commit --no-verify -m x; fi`,
59
+ `if git diff --quiet; then git push --no-verify; fi`,
60
+ `env bash -lc 'if true; then git commit -n -m x; fi'`,
61
+ `sudo env git -c core.hooksPath=/dev/null commit -m x`,
62
+ ]) {
63
+ assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /skips the git hooks|core\.hooksPath/, command);
64
+ }
65
+ for (const command of [`bash -lc 'git commit -m x'`, `env git status`, `if true; then git commit -m x; fi`, `eval 'git log'`]) {
66
+ assert.equal(decide(bash(ws.adopted, command)), null, command);
67
+ }
68
+ });
69
+
45
70
  test("a git call that points core.hooksPath elsewhere is denied", (t) => {
46
71
  const ws = workspace(t);
47
72
  for (const command of ["git -c core.hooksPath=/dev/null commit -m x", "git -c core.hookspath= push"]) {
@@ -58,6 +83,11 @@ test("a hand run of a hook script is denied, and the reason names the lease", (t
58
83
  "node.exe src/cli/worktree-isolation.mjs",
59
84
  "bash hooks/pre-edit-guard.sh",
60
85
  "./hooks/pre-edit-guard.sh < input.json",
86
+ "node packages/qc-harness/src/cli/report-stop.mjs < stop.json",
87
+ "node ./merge-guard.mjs",
88
+ "node src/cli/issue-gate.mjs",
89
+ "node src/cli/plan-stop.mjs",
90
+ "node src/cli/controller-guard.mjs",
61
91
  ]) {
62
92
  assert.match(reasonOf(decide(bash(ws.adopted, command))) ?? "", /writes a lease/, command);
63
93
  }
@@ -11,16 +11,20 @@ import { fileURLToPath } from "node:url";
11
11
  import { promisify } from "node:util";
12
12
  import { load } from "../config.mjs";
13
13
  import { checkoutRootOf } from "./checkout-root.mjs";
14
+ import { isControllerPath } from "./controller-guard.mjs";
14
15
  import { ignoredPaths } from "./ignored-paths.mjs";
15
16
  import * as powershell from "./powershell-command.mjs";
16
17
  import * as posix from "./shell-command.mjs";
17
18
  import { isAllowed } from "./work-order-guard.mjs";
18
19
  import { MANIFEST_FILE, readManifest } from "./work-order-manifest.mjs";
20
+ import { nativePath } from "./workflow-place.mjs";
21
+ import { workflowAt } from "./workflow-settings.mjs";
19
22
  import { OFF, isolationSettings } from "./worktree-isolation.mjs";
20
23
 
21
24
  const execFileAsync = promisify(execFile);
22
25
  const slashed = (file) => file.split(path.sep).join("/");
23
26
  const MAX_LISTED = 40;
27
+ const CONTROLLER_RULE = "outside the controller paths";
24
28
 
25
29
  /** The paths `git status --porcelain -z` names, with both sides of a rename. */
26
30
  export function changedPaths(porcelain) {
@@ -46,8 +50,7 @@ const native = (dir) => {
46
50
 
47
51
  /** A directory as the command wrote it, resolved the way the shell would, or null when it does not exist. */
48
52
  function resolveDir(cwd, dir) {
49
- let spelled = dir.replace(/^~(?=$|[\\/])/, os.homedir());
50
- if (process.platform === "win32") spelled = spelled.replace(/^\/([A-Za-z])(?=\/|$)/, "$1:");
53
+ const spelled = nativePath(dir.replace(/^~(?=$|[\\/])/, os.homedir()));
51
54
  const absolute = path.resolve(cwd, spelled);
52
55
  return existsSync(absolute) ? absolute : null;
53
56
  }
@@ -73,7 +76,7 @@ async function gitFacts(root) {
73
76
  }
74
77
 
75
78
  /** @returns each changed path in one checkout that breaks a rule, with the rules it breaks. */
76
- async function findingsIn(root, manifest, projectRoot) {
79
+ async function findingsIn(root, manifest, projectRoot, isMainSession) {
77
80
  let settings = null;
78
81
  try {
79
82
  settings = isolationSettings(load(root).swarm);
@@ -81,7 +84,15 @@ async function findingsIn(root, manifest, projectRoot) {
81
84
  // A config error is the edit guard's to name; this guard judges the declaration alone.
82
85
  }
83
86
  const guardsBranch = settings !== null && settings.require !== OFF;
84
- if (!manifest && !guardsBranch) return [];
87
+ let controllerPaths = null;
88
+ if (isMainSession) {
89
+ try {
90
+ controllerPaths = workflowAt(root)?.review.controllerPaths ?? null;
91
+ } catch {
92
+ // A config error is the controller guard's to name.
93
+ }
94
+ }
95
+ if (!manifest && !guardsBranch && !controllerPaths) return [];
85
96
 
86
97
  let facts;
87
98
  try {
@@ -98,6 +109,11 @@ async function findingsIn(root, manifest, projectRoot) {
98
109
  add(rel, `outside the work order's declared paths (${MANIFEST_FILE}: ${patterns.join(", ")})`);
99
110
  }
100
111
  }
112
+ if (controllerPaths) {
113
+ for (const rel of facts.changed.filter((changed) => !isControllerPath(changed, controllerPaths))) {
114
+ add(rel, `${CONTROLLER_RULE} (${controllerPaths.join(", ")}), which the main session edits while swarm.dispatch is on`);
115
+ }
116
+ }
101
117
  if (guardsBranch && settings.protectedBranches.includes(facts.branch)) {
102
118
  const candidates = facts.changed.filter((rel) => !(settings.allow.length > 0 && isAllowed(rel, settings.allow)));
103
119
  const ignored = await ignoredPaths(root, candidates);
@@ -126,7 +142,8 @@ export async function report(call, projectRoot) {
126
142
  // The edit guard names a manifest that does not parse.
127
143
  }
128
144
  const findings = [];
129
- for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project)));
145
+ const isMainSession = !(typeof call.agent_id === "string" && call.agent_id !== "");
146
+ for (const root of checkoutsOf(cwd, command, dialect)) findings.push(...(await findingsIn(root, manifest, project, isMainSession)));
130
147
  if (findings.length === 0) return null;
131
148
 
132
149
  const listed = findings.slice(0, MAX_LISTED).map((line) => `- ${line}`);
@@ -137,8 +154,12 @@ export async function report(call, projectRoot) {
137
154
  additionalContext: [
138
155
  "Bash edit guard: the checkout holds uncommitted changes that the swarm rules do not allow.",
139
156
  ...listed,
140
- "Revert a change only if your work order made it and should not have. " +
141
- "For any other change, stop and tell the orchestrator. The guard does not revert anything.",
157
+ ...(findings.some((line) => line.includes(CONTROLLER_RULE))
158
+ ? ["Dispatch an implementer for a change outside the controller paths. Revert a change only if you made it by mistake. The guard does not revert anything."]
159
+ : [
160
+ "Revert a change only if your work order made it and should not have. " +
161
+ "For any other change, stop and tell the orchestrator. The guard does not revert anything.",
162
+ ]),
142
163
  ].join("\n"),
143
164
  },
144
165
  };
@@ -108,6 +108,30 @@ test("a checkout with no isolation and no work order is silent", async (t) => {
108
108
  assert.equal(await report(bash(ws.plain, "node x.mjs"), ws.plain), null);
109
109
  });
110
110
 
111
+ test("while swarm.dispatch is on, a main-session shell write outside the controller paths is reported, and a subagent's is not", async (t) => {
112
+ const ws = workspace(t);
113
+ writeFileSync(path.join(ws.plain, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
114
+ ws.put(ws.plain, "src/a.ts");
115
+ ws.put(ws.plain, "docs/b.md");
116
+ const call = bash(ws.plain, "sed -i 's/a/b/' src/a.ts");
117
+ const output = await report(call, ws.plain);
118
+ assert.equal(output.hookSpecificOutput.hookEventName, "PostToolUse");
119
+ const text = contextOf(output);
120
+ assert.match(text, /src\/a\.ts: outside the controller paths \(docs\/\*\*, /);
121
+ assert.doesNotMatch(text, /docs\/b\.md/);
122
+ assert.match(text, /dispatch an implementer/i);
123
+ assert.doesNotMatch(text, /work order|orchestrator/);
124
+ assert.equal(await report({ ...call, agent_id: "agent-1" }, ws.plain), null);
125
+ assert.equal(await report(bash(ws.plain, "cat src/a.ts"), ws.plain), null);
126
+ });
127
+
128
+ test("with swarm.dispatch off, a shell write breaks no controller rule", async (t) => {
129
+ const ws = workspace(t);
130
+ writeFileSync(path.join(ws.plain, "qc.config.json"), JSON.stringify({ swarm: {} }));
131
+ ws.put(ws.plain, "src/a.ts");
132
+ assert.equal(await report(bash(ws.plain, "sed -i 's/a/b/' src/a.ts"), ws.plain), null);
133
+ });
134
+
111
135
  test("porcelain output names each changed path, and both sides of a rename", () => {
112
136
  const status = [" M src/a.ts", "?? docs/new file.md", "R lib/new.ts", "lib/old.ts", ""].join("\u0000");
113
137
  assert.deepEqual(changedPaths(status), ["src/a.ts", "docs/new file.md", "lib/new.ts", "lib/old.ts"]);
@@ -19,11 +19,9 @@ function readCount(file) {
19
19
  }
20
20
  }
21
21
 
22
- /** Adds one to the count and writes it through a rename. @returns the new count; throws on a write error. */
23
- export function bumpCount(file, now = Date.now()) {
24
- const count = readCount(file) + 1;
22
+ /** Writes one small JSON payload through a rename; throws on a write error. */
23
+ function writeJson(file, payload) {
25
24
  const temp = `${file}.${process.pid}.tmp`;
26
- const payload = JSON.stringify({ count, updatedAt: new Date(now).toISOString() });
27
25
  try {
28
26
  writeFileSync(temp, payload);
29
27
  } catch {
@@ -36,5 +34,28 @@ export function bumpCount(file, now = Date.now()) {
36
34
  rmSync(temp, { force: true });
37
35
  throw error;
38
36
  }
37
+ }
38
+
39
+ /** Adds one to the count and writes it through a rename. @returns the new count; throws on a write error. */
40
+ export function bumpCount(file, now = Date.now()) {
41
+ const count = readCount(file) + 1;
42
+ writeJson(file, JSON.stringify({ count, updatedAt: new Date(now).toISOString() }));
39
43
  return count;
40
44
  }
45
+
46
+ /** The file that holds one agent's context-signal state: its first context, its estimate, and the last note. */
47
+ export const stateFileOf = (sessionId, agentId, tmp) =>
48
+ path.join(tmp, "architecture-kit", "context", `${fileSafe(sessionId)}-${fileSafe(agentId)}.json`);
49
+
50
+ /** @returns the state, or {} for a missing or unreadable file. */
51
+ export function readState(file) {
52
+ try {
53
+ const state = JSON.parse(readFileSync(file, "utf8"));
54
+ return state !== null && typeof state === "object" && !Array.isArray(state) ? state : {};
55
+ } catch {
56
+ return {};
57
+ }
58
+ }
59
+
60
+ /** Writes the state through a rename; throws on a write error. */
61
+ export const writeState = (file, state) => writeJson(file, JSON.stringify(state));
@@ -6,10 +6,14 @@ import { existsSync } from "node:fs";
6
6
  import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { fileURLToPath } from "node:url";
9
- import { CONFIG_FILE, load } from "../config.mjs";
9
+ import { CONFIG_FILE, contextDefaults, load } from "../config.mjs";
10
10
  import { budgetOf, budgetVerdict } from "./budget.mjs";
11
- import { bumpCount, counterFileOf } from "./budget-counter.mjs";
11
+ import { bumpCount, counterFileOf, readState, stateFileOf, writeState } from "./budget-counter.mjs";
12
12
  import { checkoutRootOf } from "./checkout-root.mjs";
13
+ import { contextSettings, contextVerdict, estimateOf, handbackStamp } from "./context-signal.mjs";
14
+ import { agentTranscriptOf, contextOf, firstPromptOf, firstUsage, lastUsage } from "./transcript-usage.mjs";
15
+
16
+ const HANDBACK = "SubagentHandback";
13
17
 
14
18
  const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse", additionalContext: text } });
15
19
 
@@ -20,9 +24,11 @@ export function decide(call, tmp = os.tmpdir()) {
20
24
  const root = checkoutRootOf(call.cwd ?? process.cwd());
21
25
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
22
26
 
27
+ let swarm;
23
28
  let budget;
24
29
  try {
25
- budget = budgetOf(load(root).swarm);
30
+ swarm = load(root).swarm;
31
+ budget = budgetOf(swarm);
26
32
  } catch (error) {
27
33
  // A config typo must not stop every agent; the agent sees the error and reports it.
28
34
  return context(`Tool-call budget is off: ${error.message}`);
@@ -34,7 +40,70 @@ export function decide(call, tmp = os.tmpdir()) {
34
40
  // A busy or read-only temp folder is the hook's own problem, never a reason to stop the agent.
35
41
  return null;
36
42
  }
37
- return budgetVerdict({ count, budget, call });
43
+ const verdict = budgetVerdict({ count, budget, call });
44
+ if (verdict?.hookSpecificOutput?.permissionDecision === "deny") return verdict;
45
+ return withSignal(verdict, contextSignal(call, { swarm, count, budget, tmp }), call);
46
+ }
47
+
48
+ /** What the context signal adds to this call: `{ note }`, `{ stamp }`, or null. It never throws. */
49
+ function contextSignal(call, { swarm, count, budget, tmp }) {
50
+ let settings;
51
+ try {
52
+ settings = contextSettings(swarm);
53
+ } catch (error) {
54
+ return count % contextDefaults.every === 0 ? { note: `Context signal is off: ${error.message}` } : null;
55
+ }
56
+ if (!settings) return null;
57
+ const handback = call.tool_name === HANDBACK;
58
+ if (!handback && count % settings.every !== 0) return null;
59
+ try {
60
+ const transcript = agentTranscriptOf(call);
61
+ if (!transcript) return null;
62
+ const file = stateFileOf(call.session_id ?? "session", call.agent_id, tmp);
63
+ const state = readState(file);
64
+ const first = state.first > 0 ? state.first : contextOf(firstUsage(transcript));
65
+ if (!(first > 0)) return null;
66
+ const estimate = "estimate" in state ? state.estimate : estimateOf(firstPromptOf(transcript));
67
+ const latest = contextOf(lastUsage(transcript));
68
+ const next = { ...state, first, estimate };
69
+ let signal = null;
70
+ if (handback) {
71
+ const stamp = handbackStamp({ context: latest, first }, settings);
72
+ signal = stamp ? { stamp } : null;
73
+ } else {
74
+ const fired = state.fired ?? null;
75
+ const verdict = contextVerdict({ context: latest, first, count, budget, estimate, agentType: call.agent_type, fired }, settings);
76
+ if (verdict) {
77
+ next.fired = { level: verdict.level, at: count };
78
+ signal = { note: verdict.text };
79
+ }
80
+ }
81
+ if (state.first !== first || state.estimate !== estimate || next.fired !== state.fired) writeState(file, next);
82
+ return signal;
83
+ } catch {
84
+ // An unreadable transcript or a busy temp folder is the hook's own problem, never the agent's.
85
+ return null;
86
+ }
87
+ }
88
+
89
+ /** The budget verdict with the signal added: the note joins its context, and a stamp rewrites the hand-back. */
90
+ function withSignal(verdict, signal, call) {
91
+ if (!signal) return verdict;
92
+ if (signal.stamp) {
93
+ const input = call.tool_input ?? {};
94
+ return {
95
+ hookSpecificOutput: {
96
+ hookEventName: "PreToolUse",
97
+ permissionDecision: "allow",
98
+ updatedInput: { ...input, message: `${String(input.message ?? "")}
99
+
100
+ ${signal.stamp}` },
101
+ },
102
+ };
103
+ }
104
+ const existing = verdict?.hookSpecificOutput?.additionalContext;
105
+ return context(existing ? `${existing}
106
+ ${signal.note}` : signal.note);
38
107
  }
39
108
 
40
109
  async function readStdin() {
@@ -88,3 +88,114 @@ test("the default budget reminds at its seventieth call", (t) => {
88
88
  const output = runGuard(ws, callOf(ws.linked, "agent-1"));
89
89
  assert.match(output.hookSpecificOutput.additionalContext, /call 70 of 100/);
90
90
  });
91
+
92
+ /** One subagent transcript in the layout Claude Code keeps, with one request per context size. @returns the main transcript path */
93
+ function transcripts(ws, agentId, contexts, prompt = "Read the brief.") {
94
+ const project = path.join(ws.tmp, "projects", "p");
95
+ const dir = path.join(project, "sess", "subagents");
96
+ mkdirSync(dir, { recursive: true });
97
+ const main = path.join(project, "sess.jsonl");
98
+ writeFileSync(main, "");
99
+ const lines = [
100
+ { type: "user", message: { role: "user", content: prompt } },
101
+ ...contexts.map((n, index) => ({
102
+ type: "assistant",
103
+ timestamp: new Date(index * 1000).toISOString(),
104
+ message: { id: `m${index}`, model: "claude-sonnet-5-5", role: "assistant", content: [], usage: { input_tokens: 2, cache_read_input_tokens: n - 2, cache_creation_input_tokens: 0 } },
105
+ })),
106
+ ];
107
+ writeFileSync(path.join(dir, `agent-${agentId}.jsonl`), `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`);
108
+ return main;
109
+ }
110
+
111
+ const signalCall = (ws, main, agentType = "architecture:sdd-implementer", tool_name = "Bash", tool_input = { command: "npm test" }) => ({
112
+ ...callOf(ws.linked, "a1", tool_name, tool_input),
113
+ agent_type: agentType,
114
+ transcript_path: main,
115
+ });
116
+ const noteOf = (output) => output?.hookSpecificOutput?.additionalContext ?? null;
117
+
118
+ test("a large implementer context gets the hand-off note once, and never a deny", (t) => {
119
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
120
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
121
+ const first = runGuard(ws, signalCall(ws, main));
122
+ assert.equal(first.hookSpecificOutput.permissionDecision, undefined);
123
+ assert.match(noteOf(first), /re-sends about 60K tokens, 6\.0x its first call \(10K\)/);
124
+ assert.match(noteOf(first), /`HANDOFF: <note path>`/);
125
+ assert.equal(runGuard(ws, signalCall(ws, main)), null, "the same level does not fire twice in a row");
126
+ });
127
+
128
+ test("a reviewer, or a prompt estimate with few calls left, gets only the keep-it-small note", (t) => {
129
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
130
+ const reviewer = runGuard(ws, signalCall(ws, transcripts(ws, "a1", [10_000, 60_000]), "architecture:sdd-reviewer"));
131
+ assert.match(noteOf(reviewer), /line range/);
132
+ assert.doesNotMatch(noteOf(reviewer), /HANDOFF/);
133
+ const ws2 = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
134
+ const estimated = runGuard(ws2, signalCall(ws2, transcripts(ws2, "a1", [10_000, 60_000], "Brief: b.md\nEstimate: 12")));
135
+ assert.doesNotMatch(noteOf(estimated), /HANDOFF/);
136
+ });
137
+
138
+ test("the check runs only every `every` calls", (t) => {
139
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 3 } });
140
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
141
+ assert.equal(runGuard(ws, signalCall(ws, main)), null);
142
+ assert.equal(runGuard(ws, signalCall(ws, main)), null);
143
+ assert.match(noteOf(runGuard(ws, signalCall(ws, main))) ?? "", /Context signal/);
144
+ });
145
+
146
+ test("a hand-back of a large agent gains a CONTEXT line through updatedInput", (t) => {
147
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 50 } });
148
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
149
+ const output = runGuard(ws, signalCall(ws, main, "architecture:sdd-reviewer", "SubagentHandback", { message: "VERDICT: APPROVED abc1234" }));
150
+ assert.equal(output.hookSpecificOutput.permissionDecision, "allow");
151
+ assert.match(output.hookSpecificOutput.updatedInput.message, /^VERDICT: APPROVED abc1234\n\nCONTEXT: this agent ended at about 60K tokens per call/);
152
+ });
153
+
154
+ test("a small hand-back, a missing transcript, and `context: false` change nothing", (t) => {
155
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
156
+ const small = transcripts(ws, "a1", [10_000, 12_000]);
157
+ assert.equal(runGuard(ws, signalCall(ws, small, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" })), null);
158
+ assert.equal(runGuard(ws, signalCall(ws, path.join(ws.tmp, "none", "x.jsonl"))), null);
159
+ const off = workspace(t, { toolCallBudget: 100, context: false });
160
+ assert.equal(runGuard(off, signalCall(off, transcripts(off, "a1", [10_000, 60_000]))), null);
161
+ });
162
+
163
+ test("a wrong context key is reported as context at a check, and the budget still counts", (t) => {
164
+ const ws = workspace(t, { toolCallBudget: 100, context: { every: 0 } });
165
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
166
+ for (let index = 1; index < 5; index += 1) assert.equal(runGuard(ws, signalCall(ws, main)), null);
167
+ assert.match(noteOf(runGuard(ws, signalCall(ws, main))) ?? "", /Context signal is off: swarm\.context\.every/);
168
+ assert.equal(countOf(ws, "a1"), 5);
169
+ });
170
+
171
+ test("the budget reminder and the context note share one additionalContext", (t) => {
172
+ const ws = workspace(t, { toolCallBudget: 10, context: { every: 7 } });
173
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
174
+ let output = null;
175
+ for (let index = 0; index < 7; index += 1) output = runGuard(ws, signalCall(ws, main));
176
+ assert.match(noteOf(output), /Tool-call budget: this is call 7 of 10/);
177
+ assert.match(noteOf(output), /Context signal/);
178
+ });
179
+
180
+ test("a budget deny stays a deny, and a large context adds no note to it", (t) => {
181
+ const ws = workspace(t, { toolCallBudget: 3, context: { every: 3 } });
182
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
183
+ runGuard(ws, signalCall(ws, main));
184
+ runGuard(ws, signalCall(ws, main));
185
+ const denied = runGuard(ws, signalCall(ws, main));
186
+ assert.equal(denied.hookSpecificOutput.permissionDecision, "deny");
187
+ assert.match(denied.hookSpecificOutput.permissionDecisionReason, /call 3 of 3/);
188
+ assert.equal(noteOf(denied), null);
189
+ assert.doesNotMatch(JSON.stringify(denied), /Context signal/);
190
+ });
191
+
192
+ test("a hand-back stamp replaces the budget reminder on the same call, because the agent is ending", (t) => {
193
+ const ws = workspace(t, { toolCallBudget: 10, context: { every: 50 } });
194
+ const main = transcripts(ws, "a1", [10_000, 60_000]);
195
+ for (let index = 1; index < 7; index += 1) assert.equal(runGuard(ws, signalCall(ws, main)), null);
196
+ const output = runGuard(ws, signalCall(ws, main, "architecture:sdd-reviewer", "SubagentHandback", { message: "DONE" }));
197
+ assert.equal(countOf(ws, "a1"), 7, "call 7 of 10 is a reminder call");
198
+ assert.match(output.hookSpecificOutput.updatedInput.message, /CONTEXT: this agent ended/);
199
+ assert.equal(noteOf(output), null);
200
+ assert.doesNotMatch(JSON.stringify(output), /Tool-call budget/);
201
+ });
@@ -59,8 +59,9 @@ const deny = (count, budget) => ({
59
59
  `Tool-call budget spent: this is call ${count} of ${budget} (${KEY} in qc.config.json). ` +
60
60
  "Only the hand-off can run now. " +
61
61
  "1. Commit and push green work with git add, git commit and git push. " +
62
- "2. Write the hand-off note to a path under /handoffs/: what is done, what is left in order, and the exact next step. " +
63
- "3. Send the final report, and name the note. " +
62
+ "2. Write the hand-off note in a `handoffs/` folder beside the report file, outside every checkout: lines " +
63
+ "`Brief:`, `Worktree:`, `Branch:`, and `Head:`, and sections `## Done`, `## Left`, and `## Next step`. " +
64
+ "3. Send the final report with a line `HANDOFF: <note path>` in place of the GREEN line. " +
64
65
  "Read and read-only commands still run.",
65
66
  },
66
67
  });