architecture-harness 0.25.0 → 0.25.1

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 (164) hide show
  1. package/package.json +2 -5
  2. package/src/cli/branch-sync.mjs +126 -0
  3. package/src/cli/branch-sync.test.mjs +428 -0
  4. package/src/cli/budget-guard.mjs +74 -5
  5. package/src/cli/budget-guard.test.mjs +185 -2
  6. package/src/cli/budget-report.mjs +85 -0
  7. package/src/cli/budget-report.test.mjs +173 -0
  8. package/src/cli/budget.mjs +8 -5
  9. package/src/cli/check-commands.mjs +23 -8
  10. package/src/cli/check-commands.test.mjs +80 -0
  11. package/src/cli/check-feature-switches.test.mjs +110 -0
  12. package/src/cli/check-verdict.mjs +46 -0
  13. package/src/cli/check-verdict.test.mjs +32 -0
  14. package/src/cli/check.mjs +24 -4
  15. package/src/cli/checkpoint.mjs +143 -0
  16. package/src/cli/checkpoint.test.mjs +146 -0
  17. package/src/cli/ci-failures.mjs +266 -0
  18. package/src/cli/ci-failures.test.mjs +509 -0
  19. package/src/cli/ci-state.mjs +25 -29
  20. package/src/cli/ci-state.test.mjs +174 -2
  21. package/src/cli/ci-template.test.mjs +8 -0
  22. package/src/cli/claude-core.test.mjs +37 -0
  23. package/src/cli/codex-implement.mjs +243 -39
  24. package/src/cli/codex-implement.test.mjs +1184 -28
  25. package/src/cli/codex-limit.mjs +85 -0
  26. package/src/cli/codex-limit.test.mjs +179 -0
  27. package/src/cli/codex-reset.mjs +78 -0
  28. package/src/cli/codex-reset.test.mjs +192 -0
  29. package/src/cli/commit-guard.mjs +219 -0
  30. package/src/cli/commit-guard.test.mjs +803 -0
  31. package/src/cli/context-budgets.mjs +47 -0
  32. package/src/cli/context-budgets.test.mjs +96 -0
  33. package/src/cli/context-watch.mjs +116 -0
  34. package/src/cli/context-watch.test.mjs +395 -0
  35. package/src/cli/contract-history.mjs +1 -1
  36. package/src/cli/controller-guard.mjs +38 -0
  37. package/src/cli/controller-guard.test.mjs +66 -2
  38. package/src/cli/cost-stop.mjs +5 -1
  39. package/src/cli/cost-stop.test.mjs +26 -0
  40. package/src/cli/direct-lane.mjs +32 -19
  41. package/src/cli/direct-lane.test.mjs +21 -3
  42. package/src/cli/dispatch-guard.mjs +11 -0
  43. package/src/cli/dispatch-guard.test.mjs +138 -3
  44. package/src/cli/dispatch-reminder.mjs +5 -2
  45. package/src/cli/dispatch-reminder.test.mjs +17 -1
  46. package/src/cli/dispatch-route.mjs +54 -0
  47. package/src/cli/dispatch-route.test.mjs +101 -0
  48. package/src/cli/e2e-affected.mjs +15 -0
  49. package/src/cli/e2e-affected.test.mjs +73 -0
  50. package/src/cli/gh-merge-command.mjs +91 -28
  51. package/src/cli/gh-merge-command.test.mjs +70 -0
  52. package/src/cli/gh-run.mjs +20 -2
  53. package/src/cli/gh-run.test.mjs +36 -1
  54. package/src/cli/git-hooks.test.mjs +25 -3
  55. package/src/cli/integrate.mjs +114 -20
  56. package/src/cli/integrate.test.mjs +347 -1
  57. package/src/cli/integration-lane.mjs +64 -0
  58. package/src/cli/integration-lane.test.mjs +213 -0
  59. package/src/cli/ledger.mjs +4 -2
  60. package/src/cli/lint-changed.mjs +59 -10
  61. package/src/cli/lint-changed.test.mjs +112 -1
  62. package/src/cli/merge-guard.mjs +165 -46
  63. package/src/cli/merge-guard.test.mjs +585 -17
  64. package/src/cli/output-redaction.mjs +26 -0
  65. package/src/cli/output-redaction.test.mjs +117 -0
  66. package/src/cli/pause.mjs +93 -0
  67. package/src/cli/pause.test.mjs +109 -0
  68. package/src/cli/plan-check.mjs +84 -12
  69. package/src/cli/plan-check.test.mjs +152 -2
  70. package/src/cli/plan-stop.mjs +7 -4
  71. package/src/cli/plan-stop.test.mjs +87 -0
  72. package/src/cli/plugin-skills.test.mjs +25 -0
  73. package/src/cli/promotion-branch.mjs +2 -0
  74. package/src/cli/qc.mjs +86 -9
  75. package/src/cli/qc.test.mjs +59 -0
  76. package/src/cli/report-stop.mjs +5 -0
  77. package/src/cli/report-stop.test.mjs +23 -1
  78. package/src/cli/review-gate.mjs +24 -6
  79. package/src/cli/review-gate.test.mjs +116 -0
  80. package/src/cli/review-promotion.mjs +107 -0
  81. package/src/cli/review-promotion.test.mjs +251 -0
  82. package/src/cli/role-budget.mjs +50 -0
  83. package/src/cli/role-budget.test.mjs +91 -0
  84. package/src/cli/screens.mjs +2 -1
  85. package/src/cli/secret-patterns.mjs +16 -0
  86. package/src/cli/secret-patterns.test.mjs +73 -0
  87. package/src/cli/setup-block.mjs +24 -0
  88. package/src/cli/setup-block.test.mjs +96 -0
  89. package/src/cli/setup-checks.mjs +65 -0
  90. package/src/cli/setup-checks.test.mjs +158 -0
  91. package/src/cli/setup-compaction.mjs +55 -0
  92. package/src/cli/setup-compaction.test.mjs +115 -0
  93. package/src/cli/setup-skills.mjs +65 -0
  94. package/src/cli/setup-skills.test.mjs +171 -0
  95. package/src/cli/setup.mjs +107 -0
  96. package/src/cli/setup.test.mjs +275 -0
  97. package/src/cli/spawn-command.mjs +47 -0
  98. package/src/cli/spawn-command.test.mjs +64 -0
  99. package/src/cli/task-gate-review.test.mjs +21 -2
  100. package/src/cli/task-gate.mjs +25 -12
  101. package/src/cli/task-gate.test.mjs +43 -5
  102. package/src/cli/throwaway-db.mjs +9 -3
  103. package/src/cli/throwaway-db.test.mjs +54 -0
  104. package/src/cli/tokens.mjs +46 -3
  105. package/src/cli/tokens.test.mjs +103 -3
  106. package/src/cli/transcript-usage.mjs +27 -0
  107. package/src/cli/transcript-usage.test.mjs +34 -0
  108. package/src/cli/user-config-package.mjs +1 -1
  109. package/src/cli/user-config-toml.mjs +63 -7
  110. package/src/cli/user-config.mjs +39 -7
  111. package/src/cli/user-config.test.mjs +238 -5
  112. package/src/cli/watch-arm.mjs +39 -0
  113. package/src/cli/watch-arm.test.mjs +87 -0
  114. package/src/cli/watch.mjs +62 -30
  115. package/src/cli/watch.test.mjs +203 -21
  116. package/src/cli/workflow-hooks.test.mjs +17 -3
  117. package/src/cli/workflow-settings.mjs +43 -8
  118. package/src/cli/workflow-settings.test.mjs +113 -0
  119. package/src/cli/worktree.mjs +14 -1
  120. package/src/cli/worktree.test.mjs +20 -1
  121. package/src/config.mjs +110 -5
  122. package/src/config.test.mjs +252 -3
  123. package/src/consumer-package.mjs +31 -0
  124. package/src/consumer-package.test.mjs +69 -0
  125. package/src/descriptions.mjs +1 -0
  126. package/src/eslint/index.mjs +10 -0
  127. package/src/eslint/jsx.mjs +20 -0
  128. package/src/eslint/preset.mjs +14 -1
  129. package/src/eslint/preset.test.mjs +103 -1
  130. package/src/eslint/rules/no-arbitrary-class-value.mjs +32 -0
  131. package/src/eslint/rules/no-literal-color.mjs +94 -0
  132. package/src/eslint/rules/no-static-inline-style.mjs +41 -0
  133. package/src/eslint/rules/one-component-per-file.mjs +70 -0
  134. package/src/eslint/rules/raw-element-in-primitive.mjs +31 -0
  135. package/src/eslint/rules.test.mjs +155 -0
  136. package/src/eslint/ui-regressions.test.mjs +39 -0
  137. package/src/gates/contract-operations.mjs +3 -3
  138. package/src/gates/contract-operations.test.mjs +28 -0
  139. package/src/gates/feature-switches.mjs +19 -0
  140. package/src/gates/feature-switches.test.mjs +55 -0
  141. package/src/gates/runtime-imports.test.mjs +114 -0
  142. package/src/gates/saga-key.test.mjs +1 -1
  143. package/src/global-skills.mjs +9 -0
  144. package/src/global-skills.test.mjs +54 -0
  145. package/src/plugin.test.mjs +3 -2
  146. package/src/screens/capture-idle.test.mjs +3 -3
  147. package/src/screens/capture.mjs +2 -1
  148. package/src/screens/compare.mjs +3 -2
  149. package/src/screens/regions.mjs +3 -2
  150. package/src/screens/setup.mjs +2 -1
  151. package/src/screens/stack-auth.mjs +2 -1
  152. package/src/stack/stack.test.mjs +29 -9
  153. package/src/ui/class-sites.mjs +38 -6
  154. package/src/ui/codemod.mjs +4 -1
  155. package/src/ui/codemod.test.mjs +52 -0
  156. package/src/ui/components.mjs +5 -3
  157. package/src/ui/components.test.mjs +8 -0
  158. package/src/ui/dupes.test.mjs +18 -0
  159. package/templates/docs/ui.md +33 -0
  160. package/templates/githooks/pre-commit +1 -0
  161. package/templates/githooks/pre-push +11 -2
  162. package/templates/github/workflows/ci.yml +8 -1
  163. package/user-config/claude/CLAUDE.core.md +28 -0
  164. package/user-config/claude/settings.shared.json +41 -1
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- // The PreToolUse trigger for the tool-call budget of swarm.md. It runs on every call of every agent,
3
- // so it spawns no process and touches one small file. The main session has no agent id and is exempt.
2
+ // The PreToolUse trigger for tool-call and context budgets. It spawns no process.
3
+ // The main session gets only the orchestrator's compaction reminder while dispatch is on.
4
4
 
5
5
  import { existsSync } from "node:fs";
6
6
  import os from "node:os";
@@ -10,8 +10,12 @@ import { CONFIG_FILE, contextDefaults, load } from "../config.mjs";
10
10
  import { budgetOf, budgetVerdict } from "./budget.mjs";
11
11
  import { bumpCount, counterFileOf, readState, stateFileOf, writeState } from "./budget-counter.mjs";
12
12
  import { checkoutRootOf } from "./checkout-root.mjs";
13
+ import { budgetsOf } from "./context-budgets.mjs";
13
14
  import { contextSettings, contextVerdict, estimateOf, handbackStamp } from "./context-signal.mjs";
15
+ import { dispatchSettings } from "./dispatch.mjs";
16
+ import { budgetRoleOf, orchestratorVerdict, roleBudgetVerdict } from "./role-budget.mjs";
14
17
  import { agentTranscriptOf, contextOf, firstPromptOf, firstUsage, lastUsage } from "./transcript-usage.mjs";
18
+ import { checkpointNameOf } from "./checkpoint.mjs";
15
19
 
16
20
  const HANDBACK = "SubagentHandback";
17
21
 
@@ -20,14 +24,51 @@ const context = (text) => ({ hookSpecificOutput: { hookEventName: "PreToolUse",
20
24
  /** The verdict on one tool call. @returns the hook output, or null to let the call run with no message. */
21
25
  export function decide(call, tmp = os.tmpdir()) {
22
26
  const agentId = call.agent_id;
23
- if (typeof agentId !== "string" || agentId === "") return null;
27
+ if (typeof agentId !== "string" || agentId === "") return orchestratorOutput(call, tmp);
24
28
  const root = checkoutRootOf(call.cwd ?? process.cwd());
25
29
  if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
26
30
 
27
31
  let swarm;
28
- let budget;
29
32
  try {
30
33
  swarm = load(root).swarm;
34
+ } catch (error) {
35
+ return context(`Tool-call budget is off: ${error.message}`);
36
+ }
37
+ const output = toolCallOutput(call, root, swarm, tmp);
38
+ const roleOutput = roleBudgetOutput(call, root, swarm, tmp);
39
+ if (output?.hookSpecificOutput?.permissionDecision === "deny") return output;
40
+ if (roleOutput?.hookSpecificOutput?.permissionDecision === "deny") return roleOutput;
41
+ if (!roleOutput || call.tool_name === HANDBACK) return output;
42
+ const existing = output?.hookSpecificOutput?.additionalContext;
43
+ const note = roleOutput.hookSpecificOutput.additionalContext;
44
+ return context(existing ? `${existing}\n${note}` : note);
45
+ }
46
+
47
+ function orchestratorOutput(call, tmp) {
48
+ try {
49
+ const root = checkoutRootOf(call.cwd ?? process.cwd());
50
+ if (!root || !existsSync(path.join(root, CONFIG_FILE))) return null;
51
+ const config = load(root);
52
+ if (!dispatchSettings(config.swarm)) return null;
53
+ const budget = budgetsOf(config).orchestrator;
54
+ if (!budget) return null;
55
+ const session = call.session_id ?? "session";
56
+ const count = bumpCount(counterFileOf(session, "orchestrator", tmp));
57
+ if (count % contextDefaults.every !== 0) return null;
58
+ const tokens = contextOf(lastUsage(call.transcript_path));
59
+ const file = stateFileOf(session, "orchestrator", tmp);
60
+ const state = readState(file);
61
+ const note = orchestratorVerdict({ tokens, compactAt: budget.compactAt, count, state });
62
+ writeState(file, state);
63
+ return note ? context(`${note} Update the checkpoint now: ${checkpointNameOf(root, session)}.`) : null;
64
+ } catch {
65
+ return null;
66
+ }
67
+ }
68
+
69
+ function toolCallOutput(call, root, swarm, tmp) {
70
+ let budget;
71
+ try {
31
72
  budget = budgetOf(swarm);
32
73
  } catch (error) {
33
74
  // A config typo must not stop every agent; the agent sees the error and reports it.
@@ -36,7 +77,7 @@ export function decide(call, tmp = os.tmpdir()) {
36
77
  if (budget === null) return null;
37
78
  let count;
38
79
  try {
39
- count = bumpCount(counterFileOf(call.session_id ?? "session", agentId, tmp));
80
+ count = bumpCount(counterFileOf(call.session_id ?? "session", call.agent_id, tmp));
40
81
  } catch {
41
82
  // A busy or read-only temp folder is the hook's own problem, never a reason to stop the agent.
42
83
  return null;
@@ -46,6 +87,34 @@ export function decide(call, tmp = os.tmpdir()) {
46
87
  return withSignal(verdict, contextSignal(call, { swarm, count, budget, tmp }), call);
47
88
  }
48
89
 
90
+ // Read after the context signal so its keys survive this write.
91
+ function roleBudgetOutput(call, root, swarm, tmp) {
92
+ try {
93
+ const file = stateFileOf(call.session_id ?? "session", call.agent_id, tmp);
94
+ const state = readState(file);
95
+ let budgets;
96
+ let role;
97
+ try {
98
+ role = budgetRoleOf(call.agent_type, swarm);
99
+ if (!role) return null;
100
+ budgets = budgetsOf(load(root));
101
+ } catch (error) {
102
+ if (state.budgetError === error.message) return null;
103
+ writeState(file, { ...state, budgetError: error.message });
104
+ return context(`Context budget is off: ${error.message}`);
105
+ }
106
+ if (!role || !budgets[role]) return null;
107
+ const tokens = state.budgetClosed ? undefined : contextOf(lastUsage(agentTranscriptOf(call)));
108
+ const next = { ...state };
109
+ const verdict = roleBudgetVerdict({ role, tokens, budget: budgets[role], call, state: next });
110
+ if (next.budgetReminded !== state.budgetReminded || next.budgetClosed !== state.budgetClosed) writeState(file, next);
111
+ return verdict;
112
+ } catch {
113
+ // A missing transcript or an unwritable state file leaves the role budget off.
114
+ return null;
115
+ }
116
+ }
117
+
49
118
  /** The one note for an agent whose hook input names no transcript, and the state that keeps later calls quiet. */
50
119
  function noTranscriptNote(file, state) {
51
120
  writeState(file, { ...state, noTranscript: true });
@@ -9,7 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  const GUARD = fileURLToPath(new URL("./budget-guard.mjs", import.meta.url));
10
10
 
11
11
  /** An adopted checkout with a budget, a linked worktree of it, a checkout with no config, and a temp folder for the counters. */
12
- function workspace(t, swarm = { toolCallBudget: 3 }) {
12
+ function workspace(t, swarm = { toolCallBudget: 3 }, config = {}) {
13
13
  const base = realpathSync.native(mkdtempSync(path.join(os.tmpdir(), "qc-budget-")));
14
14
  t.after(() => rmSync(base, { recursive: true, force: true }));
15
15
  const git = (cwd, ...args) => execFileSync("git", args, { cwd, stdio: "pipe" });
@@ -19,7 +19,7 @@ function workspace(t, swarm = { toolCallBudget: 3 }) {
19
19
  const tmp = path.join(base, "tmp");
20
20
  for (const dir of [primary, plain, tmp]) mkdirSync(dir);
21
21
  git(primary, "init", "-q", "-b", "main");
22
- writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm }));
22
+ writeFileSync(path.join(primary, "qc.config.json"), JSON.stringify({ swarm, ...config }));
23
23
  git(primary, "add", ".");
24
24
  git(primary, "-c", "user.name=qc", "-c", "user.email=qc@example.com", "commit", "-q", "-m", "init");
25
25
  git(primary, "worktree", "add", "-q", linked, "-b", "feat/work-order");
@@ -121,6 +121,189 @@ const signalCall = (ws, main, agentType = "architecture:sdd-implementer", tool_n
121
121
  });
122
122
  const noteOf = (output) => output?.hookSpecificOutput?.additionalContext ?? null;
123
123
 
124
+ function mainCall(ws, tokens = 213_000) {
125
+ const transcript = path.join(ws.tmp, "main.jsonl");
126
+ const lines = [10_000, tokens].map((input_tokens) => ({
127
+ type: "assistant", message: { usage: { input_tokens } },
128
+ }));
129
+ writeFileSync(transcript, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`);
130
+ return { ...callOf(ws.linked, null), transcript_path: transcript };
131
+ }
132
+
133
+ test("the orchestrator gets the compaction note on its 5th call and not on the 4th", (t) => {
134
+ const ws = workspace(t, { dispatch: {} });
135
+ const call = mainCall(ws);
136
+ for (let count = 1; count <= 4; count++) assert.equal(runGuard(ws, call), null);
137
+ const output = runGuard(ws, call).hookSpecificOutput;
138
+ assert.match(output.additionalContext, /Context budget: this session sends about 213K tokens per call, past budgets\.orchestrator\.compactAt \(200000\)\. Run \/compact/);
139
+ assert.equal(output.permissionDecision, undefined);
140
+ assert.equal(countOf(ws, "orchestrator"), 5);
141
+ assert.equal(stateOf(ws, "orchestrator").budgetFiredAt, 5);
142
+ assert.match(output.additionalContext, /Update the checkpoint now/);
143
+ assert.match(output.additionalContext, /qc[\\/]checkpoints[\\/]/);
144
+ });
145
+
146
+ test("an invalid Git pointer preserves the orchestrator reminder", (t) => {
147
+ const ws = workspace(t, { dispatch: {} });
148
+ const call = mainCall(ws);
149
+ call.cwd = path.join(ws.tmp, "broken");
150
+ mkdirSync(call.cwd);
151
+ writeFileSync(path.join(call.cwd, ".git"), "invalid pointer");
152
+ writeFileSync(path.join(call.cwd, "qc.config.json"), JSON.stringify({ swarm: { dispatch: {} } }));
153
+ for (let count = 1; count < 5; count++) assert.equal(runGuard(ws, call), null);
154
+ const note = noteOf(runGuard(ws, call));
155
+ assert.match(note, /Run \/compact/);
156
+ assert.match(note, /Update the checkpoint now: the session checkpoint/);
157
+ assert.equal(stateOf(ws, "orchestrator").budgetFiredAt, 5);
158
+ });
159
+
160
+ test("the note repeats only after 20 more calls", (t) => {
161
+ const ws = workspace(t, { dispatch: {} });
162
+ const call = mainCall(ws);
163
+ for (let count = 1; count < 5; count++) runGuard(ws, call);
164
+ const first = runGuard(ws, call);
165
+ assert.match(noteOf(first), /Run \/compact/);
166
+ for (let count = 6; count < 25; count++) assert.equal(runGuard(ws, call), null);
167
+ assert.equal(stateOf(ws, "orchestrator").budgetFiredAt, 5);
168
+ assert.deepEqual(runGuard(ws, call), first);
169
+ assert.equal(stateOf(ws, "orchestrator").budgetFiredAt, 25);
170
+ });
171
+
172
+ test("a main session below compactAt gets nothing", (t) => {
173
+ const ws = workspace(t, { dispatch: {} });
174
+ const call = mainCall(ws, 199_999);
175
+ for (let count = 1; count <= 5; count++) assert.equal(runGuard(ws, call), null);
176
+ assert.equal(countOf(ws, "orchestrator"), 5);
177
+ });
178
+
179
+ test("budgets.orchestrator null gets nothing", (t) => {
180
+ const ws = workspace(t, { dispatch: {} }, { budgets: { orchestrator: null } });
181
+ const call = mainCall(ws);
182
+ for (let count = 1; count <= 5; count++) assert.equal(runGuard(ws, call), null);
183
+ assert.equal(existsSync(ws.counters), false);
184
+ });
185
+
186
+ test("with swarm.dispatch off the main session is not counted", (t) => {
187
+ const ws = workspace(t);
188
+ const call = mainCall(ws);
189
+ for (let count = 1; count <= 5; count++) assert.equal(runGuard(ws, call), null);
190
+ assert.equal(existsSync(ws.counters), false);
191
+ });
192
+
193
+ test("a main call with no transcript_path gets nothing and throws nothing", (t) => {
194
+ const ws = workspace(t, { dispatch: {} });
195
+ for (let count = 1; count <= 5; count++) assert.equal(runGuard(ws, callOf(ws.linked, null)), null);
196
+ });
197
+
198
+ test("main-session config and transcript errors leave the call alone", (t) => {
199
+ const ws = workspace(t, { dispatch: {} });
200
+ const call = mainCall(ws);
201
+ call.transcript_path = path.join(ws.tmp, "missing.jsonl");
202
+ for (let count = 1; count <= 5; count++) assert.equal(runGuard(ws, call), null);
203
+ writeFileSync(path.join(ws.linked, "qc.config.json"), "{");
204
+ assert.equal(runGuard(ws, call), null);
205
+ });
206
+
207
+ test("an implementer at the remind line gets one note", (t) => {
208
+ const ws = workspace(t, { dispatch: {} });
209
+ const call = signalCall(ws, transcripts(ws, "a1", [10_000, 110_000]));
210
+ assert.match(noteOf(runGuard(ws, call)), /Context budget: .*finish the current item/i);
211
+ assert.equal(runGuard(ws, call), null);
212
+ assert.equal(stateOf(ws, "a1").budgetReminded, true);
213
+ assert.equal(existsSync(ws.counters), false);
214
+ });
215
+
216
+ test("at handoffAt a non-hand-off call is denied and the hand-off still runs", (t) => {
217
+ const ws = workspace(t, { dispatch: {}, toolCallBudget: 100, context: { every: 1 } });
218
+ const main = transcripts(ws, "a1", [10_000, 160_000]);
219
+ const output = runGuard(ws, signalCall(ws, main)).hookSpecificOutput;
220
+ assert.equal(output.permissionDecision, "deny");
221
+ assert.match(output.permissionDecisionReason, /HANDOFF: <note path>/);
222
+ assert.equal(stateOf(ws, "a1").first, 10_000);
223
+ assert.equal(stateOf(ws, "a1").budgetClosed, true);
224
+ assert.equal(runGuard(ws, signalCall(ws, main, undefined, "Bash", { command: "git push" })), null);
225
+ const handback = runGuard(ws, signalCall(ws, main, undefined, "SubagentHandback", { message: "HANDOFF: note" }));
226
+ assert.match(handback.hookSpecificOutput.updatedInput.message, /CONTEXT:/);
227
+ assert.equal(noteOf(handback), null);
228
+ const lost = signalCall(ws, path.join(ws.tmp, "missing.jsonl"));
229
+ assert.equal(runGuard(ws, lost).hookSpecificOutput.permissionDecision, "deny");
230
+ });
231
+
232
+ test("a reviewer at its handoffAt is denied with the report text", (t) => {
233
+ const ws = workspace(t, { dispatch: {} });
234
+ const main = transcripts(ws, "a1", [10_000, 120_000]);
235
+ const output = runGuard(ws, signalCall(ws, main, "architecture:sdd-reviewer")).hookSpecificOutput;
236
+ assert.equal(output.permissionDecision, "deny");
237
+ assert.match(output.permissionDecisionReason, /VERDICT:.*UNREVIEWED:/);
238
+ assert.doesNotMatch(output.permissionDecisionReason, /HANDOFF:/);
239
+ });
240
+
241
+ test("budgets.implementer null fires nothing", (t) => {
242
+ const ws = workspace(t, { dispatch: {} }, { budgets: { implementer: null } });
243
+ assert.equal(runGuard(ws, signalCall(ws, transcripts(ws, "a1", [10_000, 160_000]))), null);
244
+ assert.equal(existsSync(ws.counters), false);
245
+ });
246
+
247
+ test("with swarm.dispatch off no role budget fires", (t) => {
248
+ const ws = workspace(t, {});
249
+ assert.equal(runGuard(ws, signalCall(ws, transcripts(ws, "a1", [10_000, 160_000]))), null);
250
+ });
251
+
252
+ test("unused invalid budgets stay silent with dispatch off or an unrelated agent", (t) => {
253
+ for (const swarm of [{}, { dispatch: {} }]) {
254
+ const ws = workspace(t, swarm, { budgets: false });
255
+ const call = signalCall(ws, transcripts(ws, "a1", [10_000, 160_000]));
256
+ if (swarm.dispatch) call.agent_type = "general-purpose";
257
+ assert.equal(runGuard(ws, call), null);
258
+ assert.equal(existsSync(ws.counters), false);
259
+ }
260
+ });
261
+
262
+ test("swarm.toolCallBudget still denies when the context is small", (t) => {
263
+ const ws = workspace(t, { dispatch: {}, toolCallBudget: 2 });
264
+ const call = signalCall(ws, transcripts(ws, "a1", [10_000, 12_000]));
265
+ runGuard(ws, call);
266
+ assert.match(runGuard(ws, call).hookSpecificOutput.permissionDecisionReason, /call 2 of 2/);
267
+ assert.equal(countOf(ws, "a1"), 2);
268
+ });
269
+
270
+ test("an agent with no transcript gets no deny", (t) => {
271
+ const ws = workspace(t, { dispatch: {} });
272
+ assert.equal(runGuard(ws, signalCall(ws, path.join(ws.tmp, "missing.jsonl"))), null);
273
+ assert.equal(existsSync(ws.counters), false);
274
+ });
275
+
276
+ test("a bad budgets value gives one note and the tool-call budget still counts", (t) => {
277
+ const ws = workspace(t, { dispatch: {}, toolCallBudget: 3 }, { budgets: { implementer: { remindAt: 0 } } });
278
+ const call = signalCall(ws, transcripts(ws, "a1", [10_000, 160_000]));
279
+ assert.match(noteOf(runGuard(ws, call)), /^Context budget is off: budgets\.implementer\.remindAt/);
280
+ assert.equal(runGuard(ws, call), null);
281
+ assert.match(runGuard(ws, call).hookSpecificOutput.permissionDecisionReason, /call 3 of 3/);
282
+ assert.equal(countOf(ws, "a1"), 3);
283
+ });
284
+
285
+ test("the context signal and both budget reminders keep their notes and state", (t) => {
286
+ const ws = workspace(t, { dispatch: {}, toolCallBudget: 1, context: { every: 1 } });
287
+ const call = signalCall(ws, transcripts(ws, "a1", [10_000, 110_000]));
288
+ assert.equal(runGuard(ws, call).hookSpecificOutput.permissionDecision, "deny");
289
+ const combined = workspace(t, { dispatch: {}, toolCallBudget: 10, context: { every: 7 } });
290
+ const combinedCall = signalCall(combined, transcripts(combined, "a1", [10_000, 12_000]));
291
+ for (let index = 0; index < 6; index += 1) assert.equal(runGuard(combined, combinedCall), null);
292
+ transcripts(combined, "a1", [10_000, 110_000]);
293
+ const note = noteOf(runGuard(combined, combinedCall));
294
+ assert.match(note, /Tool-call budget: this is call 7 of 10/);
295
+ assert.match(note, /Context signal/);
296
+ assert.match(note, /\nContext budget:/);
297
+ assert.equal(stateOf(combined, "a1").first, 10_000);
298
+ assert.equal(stateOf(combined, "a1").budgetReminded, true);
299
+ });
300
+
301
+ test("a role reminder on a hand-back adds no note", (t) => {
302
+ const ws = workspace(t, { dispatch: {} });
303
+ const main = transcripts(ws, "a1", [10_000, 110_000]);
304
+ assert.equal(runGuard(ws, signalCall(ws, main, undefined, "SubagentHandback", { message: "DONE" })), null);
305
+ });
306
+
124
307
  test("a large implementer context gets the hand-off note once, and never a deny", (t) => {
125
308
  const ws = workspace(t, { toolCallBudget: 100, context: { every: 1 } });
126
309
  const main = transcripts(ws, "a1", [10_000, 60_000]);
@@ -0,0 +1,85 @@
1
+ import { checkoutRootOf } from "./checkout-root.mjs";
2
+ import { budgetsOf } from "./context-budgets.mjs";
3
+ import { latestCosts, ledgerFileOf, readLedger } from "./ledger.mjs";
4
+
5
+ export function percentile(values, p) {
6
+ const sorted = [...values].sort((a, b) => a - b);
7
+ return sorted[Math.ceil(sorted.length * p / 100) - 1];
8
+ }
9
+
10
+ const size = (n) => `${Math.round(n / 1000)}K`;
11
+
12
+ /** A pipeline that reports estimate accuracy by cost role, without mixing reviewer samples. */
13
+ function estimateRows(costs, budgets) {
14
+ const roles = new Map();
15
+ for (const record of costs) {
16
+ const budgetRole = record.role === "branch-reviewer" ? "reviewer" : record.role;
17
+ if (budgets[budgetRole] === null || !Number.isFinite(record.estimate) || record.estimate <= 0 ||
18
+ !Number.isFinite(record.toolCalls) || record.toolCalls < 0) continue;
19
+ const ratios = roles.get(record.role) ?? [];
20
+ ratios.push(record.toolCalls / record.estimate);
21
+ roles.set(record.role, ratios);
22
+ }
23
+ return [...roles].map(([role, ratios]) => {
24
+ ratios.sort((a, b) => a - b);
25
+ const middle = Math.floor(ratios.length / 2);
26
+ const median = ratios.length % 2 ? ratios[middle] : (ratios[middle - 1] + ratios[middle]) / 2;
27
+ const advice = ratios.length < 5 ? "" : median > 1.5 ? "; raise maxTaskCalls" : median < 0.5 ? "; lower maxTaskCalls" : "";
28
+ return `${role}: estimate accuracy tasks ${ratios.length} median actual/estimate ${median.toFixed(2)}x${advice}`;
29
+ });
30
+ }
31
+
32
+ export function budgetReport(records, budgets) {
33
+ const costs = latestCosts(records);
34
+ const withContext = costs.filter((record) => Number.isFinite(record.endContext));
35
+ const lines = [];
36
+ for (const role of ["implementer", "reviewer"]) {
37
+ const budget = budgets[role];
38
+ if (budget == null) continue;
39
+ const tasks = withContext.filter((record) => record.role === role || (role === "reviewer" && record.role === "branch-reviewer"));
40
+ if (tasks.length === 0) {
41
+ lines.push(`${role}: no cost record with context figures`);
42
+ continue;
43
+ }
44
+ const contexts = tasks.map((record) => record.endContext);
45
+ const median = percentile(contexts, 50);
46
+ const p90 = percentile(contexts, 90);
47
+ const hits = tasks.filter((record) => record.peakContext >= budget.handoffAt).length;
48
+ const advice = hits / tasks.length > 0.1
49
+ ? "raise handoffAt: more than 10% of tasks hand off"
50
+ : p90 < budget.handoffAt / 2
51
+ ? "lower handoffAt: the 90th percentile is under half of it"
52
+ : "keep handoffAt";
53
+ lines.push(
54
+ `${role}: tasks ${tasks.length} median ${size(median)} p90 ${size(p90)} handoffAt ${size(budget.handoffAt)} ` +
55
+ `hit handoffAt ${hits} of ${tasks.length} (${Math.round(hits / tasks.length * 100)}%); ${advice}`,
56
+ );
57
+ }
58
+ const skipped = costs.length - withContext.length;
59
+ if (skipped > 0) lines.push(`skipped ${skipped} cost records with no context figure`);
60
+ lines.push(...estimateRows(costs, budgets));
61
+ lines.push("orchestrator and Codex: no cost record.");
62
+ return lines;
63
+ }
64
+
65
+ export function runBudget(config, args = []) {
66
+ if (args.length !== 1 || args[0] !== "report") {
67
+ console.error("Usage: qc budget report");
68
+ return 1;
69
+ }
70
+ const root = checkoutRootOf(config.root ?? process.cwd());
71
+ const file = root ? ledgerFileOf(root) : null;
72
+ if (!file) {
73
+ console.error("qc budget report: this folder is in no git checkout.");
74
+ return 1;
75
+ }
76
+ let budgets;
77
+ try {
78
+ budgets = budgetsOf(config);
79
+ } catch (error) {
80
+ console.error(error.message);
81
+ return 1;
82
+ }
83
+ for (const line of budgetReport(readLedger(file), budgets)) console.log(line);
84
+ return 0;
85
+ }
@@ -0,0 +1,173 @@
1
+ import { strict as assert } from "node:assert";
2
+ import { spawnSync } from "node:child_process";
3
+ import { mkdirSync, mkdtempSync, 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 { budgetReport, percentile, runBudget } from "./budget-report.mjs";
9
+ import { appendRecord, ledgerFileOf } from "./ledger.mjs";
10
+
11
+ const QC = fileURLToPath(new URL("./qc.mjs", import.meta.url));
12
+ const budgets = {
13
+ implementer: { remindAt: 110_000, handoffAt: 150_000 },
14
+ reviewer: { remindAt: 80_000, handoffAt: 120_000 },
15
+ };
16
+ const contexts = Array.from({ length: 10 }, (_, index) => 40_000 + index * 10_000);
17
+ const cost = (endContext, index, extra = {}) => ({
18
+ type: "cost", session: "s", agentId: `agent-${index}`, role: "implementer",
19
+ endContext, peakContext: endContext, ...extra,
20
+ });
21
+ const records = () => contexts.map((context, index) => cost(context, index));
22
+
23
+ const estimates = (ratios, role = "implementer") => ratios.map((ratio, index) =>
24
+ cost(undefined, `${role}-${index}`, { role, estimate: 20, toolCalls: ratio * 20 }));
25
+ const accuracy = (records) => budgetReport(records, budgets).filter((line) => line.includes("estimate accuracy"));
26
+
27
+ test("estimate accuracy uses the median actual to estimate ratio and advises only with five tasks", () => {
28
+ assert.match(accuracy(estimates([2, 2, 2, 2]))[0], /tasks 4.*2\.00x$/);
29
+ assert.match(accuracy(estimates([2, 2, 2, 2, 0]))[0], /tasks 5.*2\.00x; raise maxTaskCalls/);
30
+ assert.match(accuracy(estimates([0.4, 0.4, 0.4, 0.4, 10]))[0], /0\.40x; lower maxTaskCalls/);
31
+ for (const ratio of [0.5, 1, 1.5]) assert.doesNotMatch(accuracy(estimates(Array(5).fill(ratio)))[0], /maxTaskCalls/);
32
+ assert.match(accuracy(estimates([0, 0, 0, 2, 2, 2]))[0], /1\.00x$/);
33
+ });
34
+
35
+ test("estimate accuracy keeps roles separate and ignores invalid or missing estimates and actual counts", () => {
36
+ const lines = accuracy([...estimates([2, 2, 2, 2]), ...estimates([2, 2, 2, 2], "reviewer"), ...estimates([2], "branch-reviewer")]);
37
+ assert.equal(lines.length, 3);
38
+ assert.ok(lines.every((line) => !line.includes("maxTaskCalls")));
39
+ const invalid = [null, undefined, 0, -1, "20", Infinity, NaN].map((estimate, i) => cost(20_000, i, { estimate, toolCalls: 10 }));
40
+ for (const [i, toolCalls] of [undefined, null, -1, "10", Infinity, NaN].entries()) invalid.push(cost(20_000, `actual-${i}`, { estimate: 20, toolCalls }));
41
+ assert.deepEqual(accuracy(invalid), []);
42
+ });
43
+
44
+ test("estimate accuracy takes only the latest cost of a resumed agent", () => {
45
+ const samples = estimates([2, 2, 2, 2, 2]);
46
+ const replacement = { ...samples[0], estimate: null };
47
+ assert.match(accuracy([...samples, replacement])[0], /tasks 4.*2\.00x$/);
48
+ });
49
+
50
+ test("percentile uses the nearest rank without changing the input", () => {
51
+ const values = [...contexts].reverse();
52
+ assert.equal(percentile(values, 50), 80_000);
53
+ assert.equal(percentile(values, 90), 120_000);
54
+ assert.deepEqual(values, [...contexts].reverse());
55
+ assert.equal(percentile([60_000], 90), 60_000);
56
+ });
57
+
58
+ test("ten implementer tasks report their end context and keep handoffAt", () => {
59
+ const [line] = budgetReport(records(), budgets);
60
+ for (const text of ["implementer", "tasks 10", "median 80K", "p90 120K", "hit handoffAt 0 of 10 (0%)", "keep handoffAt"]) {
61
+ assert.ok(line.includes(text), line);
62
+ }
63
+ });
64
+
65
+ test("more than ten percent of peaks at handoffAt raises the limit", () => {
66
+ const costs = records();
67
+ costs[0].peakContext = 150_000;
68
+ costs[1].peakContext = 160_000;
69
+ const [line] = budgetReport(costs, budgets);
70
+ assert.match(line, /hit handoffAt 2 of 10 \(20%\)/);
71
+ assert.match(line, /raise handoffAt: more than 10% of tasks hand off/);
72
+ });
73
+
74
+ test("a p90 under half of handoffAt lowers the limit", () => {
75
+ const [line] = budgetReport(contexts.map((_, index) => cost(50_000, index)), budgets);
76
+ assert.match(line, /p90 50K/);
77
+ assert.match(line, /hit handoffAt 0 of 10 \(0%\)/);
78
+ assert.match(line, /lower handoffAt: the 90th percentile is under half of it/);
79
+ });
80
+
81
+ test("the raise rule takes priority over a low end context", () => {
82
+ const costs = contexts.map((_, index) => cost(50_000, index, { peakContext: index < 2 ? 150_000 : 50_000 }));
83
+ assert.match(budgetReport(costs, budgets)[0], /raise handoffAt/);
84
+ });
85
+
86
+ test("exactly ten percent and exactly half keep handoffAt", () => {
87
+ const costs = records();
88
+ costs[0].peakContext = 150_000;
89
+ assert.match(budgetReport(costs, budgets)[0], /hit handoffAt 1 of 10 \(10%\).*keep handoffAt/);
90
+ const half = contexts.map((_, index) => cost(75_000, index));
91
+ assert.match(budgetReport(half, budgets)[0], /p90 75K.*keep handoffAt/);
92
+ });
93
+
94
+ test("cost records with no endContext are skipped and counted", () => {
95
+ const old = Array.from({ length: 3 }, (_, index) => ({ type: "cost", session: "old", agentId: `old-${index}`, role: "implementer" }));
96
+ const lines = budgetReport([...records(), ...old, { type: "stop", role: "implementer" }], budgets);
97
+ assert.match(lines[0], /tasks 10/);
98
+ assert.ok(lines.includes("skipped 3 cost records with no context figure"));
99
+ });
100
+
101
+ test("a role with no record reports the absence of context figures", () => {
102
+ const lines = budgetReport(records(), budgets);
103
+ assert.equal(lines[1], "reviewer: no cost record with context figures");
104
+ assert.match(lines.at(-1), /orchestrator.*Codex.*no cost record/);
105
+ });
106
+
107
+ test("both cost review roles count as reviewer, after implementer", () => {
108
+ const costs = [cost(80_000, 1, { role: "reviewer" }), cost(100_000, 2, { role: "branch-reviewer", peakContext: 120_000 })];
109
+ const lines = budgetReport(costs, { reviewer: budgets.reviewer, implementer: budgets.implementer });
110
+ assert.match(lines[0], /^implementer:/);
111
+ assert.match(lines[1], /^reviewer:.*tasks 2.*median 80K.*p90 100K.*hit handoffAt 1 of 2 \(50%\).*raise handoffAt/);
112
+ });
113
+
114
+ test("only the newest cost record for each resumed agent counts", () => {
115
+ const old = { type: "cost", session: "s", agentId: "agent-0", role: "implementer" };
116
+ const lines = budgetReport([old, cost(160_000, 0), ...records(), cost(150_000, 0, { session: "another" })], budgets);
117
+ assert.match(lines[0], /tasks 11.*hit handoffAt 1 of 11 \(9%\).*keep handoffAt/);
118
+ assert.ok(lines.every((line) => !line.startsWith("skipped")));
119
+ });
120
+
121
+ test("null budgets omit the role", () => {
122
+ const lines = budgetReport(records(), { ...budgets, implementer: null });
123
+ assert.equal(lines.length, 2);
124
+ assert.match(lines[0], /^reviewer:/);
125
+ });
126
+
127
+ function workspace(t) {
128
+ const root = mkdtempSync(path.join(os.tmpdir(), "qc-budget-report-"));
129
+ t.after(() => rmSync(root, { recursive: true, force: true }));
130
+ mkdirSync(path.join(root, ".git"));
131
+ const nested = path.join(root, "packages", "app");
132
+ mkdirSync(nested, { recursive: true });
133
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ budgets }));
134
+ appendRecord(ledgerFileOf(root), cost(60_000, 0));
135
+ return { root, nested };
136
+ }
137
+
138
+ test("runBudget reads the checkout ledger and resolved budgets", (t) => {
139
+ const { nested } = workspace(t);
140
+ const log = t.mock.method(console, "log", () => {});
141
+ assert.equal(runBudget({ root: nested, budgets: { implementer: { remindAt: 70_000, handoffAt: 100_000 } } }, ["report"]), 0);
142
+ const lines = log.mock.calls.map(({ arguments: args }) => args[0]);
143
+ assert.match(lines[0], /implementer:.*tasks 1.*p90 60K.*keep handoffAt/);
144
+ assert.match(lines[1], /^reviewer: no cost record/);
145
+ });
146
+
147
+ test("qc budget report prints a budget error as one line and exits one", (t) => {
148
+ const { root } = workspace(t);
149
+ writeFileSync(path.join(root, "qc.config.json"), JSON.stringify({ budgets: false }));
150
+ const report = spawnSync(process.execPath, [QC, "budget", "report"], { cwd: root, encoding: "utf8" });
151
+ assert.equal(report.status, 1);
152
+ assert.equal(report.stdout, "");
153
+ assert.equal(report.stderr.trim(), "budgets in qc.config.json must be an object, got false");
154
+ });
155
+
156
+ test("only the exact report subcommand is accepted", (t) => {
157
+ const error = t.mock.method(console, "error", () => {});
158
+ for (const args of [[], ["other"], ["report", "extra"]]) {
159
+ assert.equal(runBudget({}, args), 1);
160
+ }
161
+ assert.equal(error.mock.calls.length, 3);
162
+ for (const { arguments: args } of error.mock.calls) assert.match(args[0], /qc budget report/);
163
+ });
164
+
165
+ test("qc routes budget report and rejects an unknown budget subcommand", (t) => {
166
+ const { nested } = workspace(t);
167
+ const report = spawnSync(process.execPath, [QC, "budget", "report"], { cwd: nested, encoding: "utf8" });
168
+ assert.equal(report.status, 0, report.stderr);
169
+ assert.match(report.stdout, /implementer:.*tasks 1/);
170
+ const invalid = spawnSync(process.execPath, [QC, "budget", "other"], { cwd: nested, encoding: "utf8" });
171
+ assert.equal(invalid.status, 1);
172
+ assert.match(invalid.stderr, /qc budget report/);
173
+ });
@@ -50,6 +50,13 @@ const remind = (count, budget) => ({
50
50
  },
51
51
  });
52
52
 
53
+ export const HANDOFF_STEPS =
54
+ "1. Commit and push green work with git add, git commit and git push. " +
55
+ "2. Write the hand-off note in a `handoffs/` folder beside the report file, outside every checkout: lines " +
56
+ "`Brief:`, `Worktree:`, `Branch:`, and `Head:`, and sections `## Done`, `## Left`, and `## Next step`. " +
57
+ "3. Send the final report with a line `HANDOFF: <note path>` in place of the GREEN line. " +
58
+ "Read and read-only commands still run.";
59
+
53
60
  const deny = (count, budget) => ({
54
61
  hookSpecificOutput: {
55
62
  hookEventName: "PreToolUse",
@@ -57,11 +64,7 @@ const deny = (count, budget) => ({
57
64
  permissionDecisionReason:
58
65
  `Tool-call budget spent: this is call ${count} of ${budget} (${KEY} in qc.config.json). ` +
59
66
  "Only the hand-off can run now. " +
60
- "1. Commit and push green work with git add, git commit and git push. " +
61
- "2. Write the hand-off note in a `handoffs/` folder beside the report file, outside every checkout: lines " +
62
- "`Brief:`, `Worktree:`, `Branch:`, and `Head:`, and sections `## Done`, `## Left`, and `## Next step`. " +
63
- "3. Send the final report with a line `HANDOFF: <note path>` in place of the GREEN line. " +
64
- "Read and read-only commands still run.",
67
+ HANDOFF_STEPS,
65
68
  },
66
69
  });
67
70