@indigoai-us/hq-cli 5.345.215 → 5.345.218

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 (161) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +46 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  6. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  7. package/dist/command-catalog.generated.d.ts +59 -4
  8. package/dist/command-catalog.generated.js +74 -4
  9. package/dist/command-help.js +3 -1
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/auth.d.ts +1 -1
  13. package/dist/commands/auth.js +11 -52
  14. package/dist/commands/bot.js +11 -4
  15. package/dist/commands/cloud-demote.d.ts +19 -4
  16. package/dist/commands/cloud-demote.js +85 -12
  17. package/dist/commands/cloud-provision.d.ts +5 -1
  18. package/dist/commands/cloud-provision.js +6 -2
  19. package/dist/commands/cloud.d.ts +37 -1
  20. package/dist/commands/cloud.js +110 -27
  21. package/dist/commands/core-hq-session-native.js +3 -0
  22. package/dist/commands/core.js +1 -0
  23. package/dist/commands/daemon.js +4 -1
  24. package/dist/commands/dm.js +7 -0
  25. package/dist/commands/doctor-usage.d.ts +8 -0
  26. package/dist/commands/doctor-usage.js +20 -0
  27. package/dist/commands/doctor.js +7 -1
  28. package/dist/commands/env.d.ts +18 -0
  29. package/dist/commands/env.js +82 -0
  30. package/dist/commands/install-global.js +3 -3
  31. package/dist/commands/lanes.js +100 -24
  32. package/dist/commands/logout.d.ts +7 -0
  33. package/dist/commands/logout.js +41 -34
  34. package/dist/commands/members.js +1 -1
  35. package/dist/commands/pack-start-bot.d.ts +1 -1
  36. package/dist/commands/pack-start-bot.js +2 -2
  37. package/dist/commands/pkg-update.js +1 -1
  38. package/dist/commands/sources.d.ts +8 -2
  39. package/dist/commands/sources.js +65 -9
  40. package/dist/commands/sync-narrow.js +1 -1
  41. package/dist/commands/team-sync.js +1 -1
  42. package/dist/commands/whoami.js +26 -1
  43. package/dist/data/command-states.json +22 -0
  44. package/dist/index.js +52 -4
  45. package/dist/lazy-commands.js +2 -1
  46. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  47. package/dist/lib/anywhere-person-setting.js +6 -3
  48. package/dist/lib/billing/usage-card.d.ts +25 -4
  49. package/dist/lib/billing/usage-card.js +76 -9
  50. package/dist/lib/billing/usage-cost.d.ts +3 -3
  51. package/dist/lib/billing/usage-cost.js +40 -15
  52. package/dist/lib/billing/usage-only.js +4 -2
  53. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  54. package/dist/lib/billing/usage-rate-card.js +3 -0
  55. package/dist/lib/bot/fleet-cron.js +93 -6
  56. package/dist/lib/bot/inflight.d.ts +9 -0
  57. package/dist/lib/bot/inflight.js +10 -0
  58. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  59. package/dist/lib/bot/pack-link.d.ts +2 -2
  60. package/dist/lib/bot/pack-link.js +2 -2
  61. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  62. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  63. package/dist/lib/bot/runtime/grok.js +1 -1
  64. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  65. package/dist/lib/daemon/flag-monitor.js +17 -6
  66. package/dist/lib/daemon/flag.d.ts +65 -1
  67. package/dist/lib/daemon/flag.js +190 -40
  68. package/dist/lib/daemon/hook-env.d.ts +32 -0
  69. package/dist/lib/daemon/hook-env.js +51 -0
  70. package/dist/lib/daemon/ops/policy.js +67 -8
  71. package/dist/lib/daemon/paths.d.ts +72 -2
  72. package/dist/lib/daemon/paths.js +154 -3
  73. package/dist/lib/daemon/run.js +32 -21
  74. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  75. package/dist/lib/daemon/selfcheck.js +40 -1
  76. package/dist/lib/daemon/server.d.ts +3 -1
  77. package/dist/lib/daemon/server.js +7 -22
  78. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  79. package/dist/lib/daemon/state-file-switch.js +88 -0
  80. package/dist/lib/daemon/state-file.d.ts +198 -0
  81. package/dist/lib/daemon/state-file.js +419 -0
  82. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  83. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  84. package/dist/lib/doctor/checks/host-core.d.ts +52 -0
  85. package/dist/lib/doctor/checks/host-core.js +337 -0
  86. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  87. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  88. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  89. package/dist/lib/doctor/registry.js +4 -0
  90. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  91. package/dist/lib/environment/credential-shapes.js +333 -0
  92. package/dist/lib/environment/profile.d.ts +239 -0
  93. package/dist/lib/environment/profile.js +239 -0
  94. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  95. package/dist/lib/hook-engine/coverage.js +124 -0
  96. package/dist/lib/hook-engine/reconcile.js +300 -94
  97. package/dist/lib/hook-engine/registration.d.ts +17 -1
  98. package/dist/lib/hook-engine/registration.js +62 -7
  99. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  100. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  101. package/dist/lib/hot-channels/alert.d.ts +2 -0
  102. package/dist/lib/hot-channels/alert.js +8 -1
  103. package/dist/lib/hot-channels/contract.d.ts +12 -0
  104. package/dist/lib/hot-channels/contract.js +7 -0
  105. package/dist/lib/hot-channels/loop.js +1 -0
  106. package/dist/lib/hot-channels/run.d.ts +6 -0
  107. package/dist/lib/hot-channels/run.js +4 -0
  108. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  109. package/dist/lib/hot-channels/signals-pass.js +21 -49
  110. package/dist/lib/install/claude-targets.d.ts +12 -1
  111. package/dist/lib/install/claude-targets.js +70 -5
  112. package/dist/lib/install/codex-pack-contributions.js +1 -1
  113. package/dist/lib/install/codex-targets.d.ts +2 -2
  114. package/dist/lib/install/codex-targets.js +48 -5
  115. package/dist/lib/install/hook-target.d.ts +4 -1
  116. package/dist/lib/install/hook-target.js +14 -1
  117. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  118. package/dist/lib/lanes/canonical-host.js +65 -0
  119. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  120. package/dist/lib/lanes/host-capacity.js +29 -3
  121. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  122. package/dist/lib/mesh/live/daemon/run.js +5 -2
  123. package/dist/lib/mesh/live/flush.d.ts +5 -1
  124. package/dist/lib/mesh/live/flush.js +12 -6
  125. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  126. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  127. package/dist/lib/mesh/live/spool.d.ts +7 -0
  128. package/dist/lib/mesh/live/spool.js +25 -0
  129. package/dist/lib/packages/setup-block.d.ts +2 -2
  130. package/dist/lib/packages/setup-block.js +2 -2
  131. package/dist/lib/packages/start-bot.d.ts +1 -1
  132. package/dist/lib/packages/start-bot.js +1 -1
  133. package/dist/lib/person-setting-cache.d.ts +38 -0
  134. package/dist/lib/person-setting-cache.js +98 -0
  135. package/dist/lib/safe-store.d.ts +245 -0
  136. package/dist/lib/safe-store.js +777 -0
  137. package/dist/lib/signals/engine.d.ts +29 -2
  138. package/dist/lib/signals/engine.js +103 -4
  139. package/dist/lib/signals/reply.js +73 -18
  140. package/dist/lib/signals/steps/adapters.js +7 -2
  141. package/dist/lib/signals/steps/extract.d.ts +13 -0
  142. package/dist/lib/signals/steps/extract.js +84 -4
  143. package/dist/main.js +47 -4
  144. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  145. package/dist/types.d.ts +1 -1
  146. package/dist/utils/auth-expiry.d.ts +8 -0
  147. package/dist/utils/auth-expiry.js +53 -0
  148. package/dist/utils/callback-port-busy.d.ts +1 -1
  149. package/dist/utils/callback-port-busy.js +4 -4
  150. package/dist/utils/cli-telemetry.d.ts +21 -0
  151. package/dist/utils/cli-telemetry.js +34 -0
  152. package/dist/utils/command-usage.d.ts +275 -0
  153. package/dist/utils/command-usage.js +797 -0
  154. package/dist/utils/hook-trust.d.ts +7 -0
  155. package/dist/utils/hook-trust.js +34 -4
  156. package/dist/utils/host-registration.d.ts +179 -0
  157. package/dist/utils/host-registration.js +505 -0
  158. package/dist/utils/resident-package-preload.js +2 -0
  159. package/package.json +10 -8
  160. package/scripts/bench-core.mjs +1096 -0
  161. package/scripts/check-function-manifest.mjs +702 -0
@@ -0,0 +1,1096 @@
1
+ #!/usr/bin/env node
2
+ // bench-core.mjs: the speed gate for the HQ hook core.
3
+ //
4
+ // Measures what HQ adds to one tool call (PreToolUse plus PostToolUse) and to
5
+ // one prompt (UserPromptSubmit) for a host and a core, and reports pass or
6
+ // fail against 150 ms per tool call and 300 ms per prompt.
7
+ //
8
+ // It needs Node 20 or later and nothing else for the new core. The old core
9
+ // also needs bash (Git Bash on Windows). It opens no window and needs no
10
+ // desktop, so it runs over SSH on a bot box. The report is one JSON file plus
11
+ // a text copy beside it. The script ships in the hq-cli package, so a machine
12
+ // with hq installed has it at
13
+ // "$(npm root -g)/@indigoai-us/hq-cli/scripts/bench-core.mjs".
14
+ // It runs the same way on macOS, Linux and Windows: by hand over SSH, or on a
15
+ // CI runner of that platform with an HQ root checked out beside it.
16
+ //
17
+ // Usage (the root is a throwaway copy of an HQ root, for example a fresh clone
18
+ // of hq-core; not a linked git worktree, which the old core refuses to run
19
+ // from; hq-hook is the binary under test):
20
+ // node scripts/bench-core.mjs --root ~/bench/hq-copy --core old
21
+ // node scripts/bench-core.mjs --root ~/bench/hq-copy --core old,new --hq-hook ~/bin/hq-hook
22
+ // node scripts/bench-core.mjs --root ~/bench/hq-copy --core selected --host claude
23
+ // node scripts/bench-core.mjs --root ~/HQ --allow-live-root --home ~ --core selected
24
+ //
25
+ // Options:
26
+ // --root <dir> HQ root the hooks run against. Use a throwaway copy:
27
+ // the hooks write session and ledger files under it.
28
+ // --allow-live-root Run against a root that live sessions use (it has a
29
+ // host registration and session folders from a real
30
+ // host). Without it such a root is refused.
31
+ // --host <list> claude, codex, grok (default: all three).
32
+ // --core <list> old the old dispatcher of that host
33
+ // (master-hook.sh or the host's adapter script)
34
+ // new hq-hook run --host <host> <Event>
35
+ // selected whatever the host's registration under
36
+ // --root runs for the event
37
+ // or a name given with --core-cmd. Default: selected.
38
+ // --hq-hook <path> The hq-hook binary for --core new (default: hq-hook on PATH).
39
+ // --core-cmd <name>=<json array>
40
+ // A core given as a command line. {host} and {event} are
41
+ // replaced in each element. Repeatable.
42
+ // --tools <list> shell, read, edit (default: all three; a host without
43
+ // that tool skips it).
44
+ // --runs <n> Samples per measurement (default 15, at least 5).
45
+ // --warmup <n> Unrecorded rounds first (default 1).
46
+ // --home <dir> Home folder for the hook processes and for reading
47
+ // user-level registrations. Default: a new empty temp
48
+ // folder, removed afterwards, so the run stays away from
49
+ // the live daemon and the user's state. Pass the real
50
+ // home only to measure the user-level registrations.
51
+ // --targets <tool>,<prompt>
52
+ // Targets in ms (default 150,300, the speed gate). Other
53
+ // values are for tests; the report names them.
54
+ // --env NAME=VALUE Extra environment for the hook processes. Repeatable.
55
+ // --bash <path> bash to use for the old core.
56
+ // --max-load <x> Load average per CPU above which a slow result is not
57
+ // trusted (default 1.0).
58
+ // --timeout-ms <n> Per hook process (default 30000).
59
+ // --label <text> Machine name written in the report (default: hostname).
60
+ // --out <file> Report path (default: ./hq-bench-core-<platform>-<time>.json).
61
+ //
62
+ // Exit code: 0 every measurement passes, 1 at least one fails, 3 none fails
63
+ // but at least one is not decidable, 2 usage or setup error (including a core
64
+ // that is not under --root and --core selected with no registration; the
65
+ // report is still written).
66
+ //
67
+ // What the numbers leave out. The setup is synthetic and isolated: no
68
+ // transcript file, no flag snapshot, a session no project is bound to, an
69
+ // empty home by default, and the env block of settings.json is not applied.
70
+ // A core can do less work here than in a real session, so it can look faster
71
+ // than on a working machine. Hooks registered for one event are timed one
72
+ // after another and summed; a host that runs them in parallel would see less,
73
+ // so the sum errs toward fail.
74
+ //
75
+ // How a verdict is reached. Cores are run in turn inside each round and the
76
+ // order flips every round, so slow minutes land on every core alike. Each
77
+ // measurement keeps its samples, the median, the spread and a 95% interval
78
+ // for the median (order statistics, no distribution assumed). The one-minute
79
+ // load average is recorded with every sample.
80
+ // pass the whole interval is at or under the target. Load only adds time,
81
+ // so this holds at any load.
82
+ // fail the whole interval is over the target and either the load is at or
83
+ // under --max-load, or the fastest sample divided by the load per
84
+ // CPU is still over the target. The second case is a heuristic: it
85
+ // assumes load L stretches a run by at most about L times.
86
+ // not decidable at this load
87
+ // the interval is over the target, the load is over --max-load and
88
+ // the fastest sample divided by the load per CPU meets the target.
89
+ // not decidable
90
+ // the interval straddles the target, or a hook exited nonzero,
91
+ // refused or timed out on the harmless test payload (its time says nothing
92
+ // about a normal call).
93
+ // Windows has no load average; there the load rule does not apply and the
94
+ // report says so.
95
+
96
+ import { spawn } from "node:child_process";
97
+ import * as fs from "node:fs";
98
+ import * as os from "node:os";
99
+ import * as path from "node:path";
100
+ import { pathToFileURL } from "node:url";
101
+
102
+ export const REPORT_SCHEMA = "hq-bench-core.v1";
103
+ export const TARGETS_MS = Object.freeze({ tool_call: 150, prompt: 300 });
104
+ export const HOSTS = Object.freeze(["claude", "codex", "grok"]);
105
+ export const TOOLS = Object.freeze(["shell", "read", "edit"]);
106
+ const BUILTIN_CORES = ["old", "new", "selected"];
107
+
108
+ // The host's own name for each kind of tool. null: the host has no such tool
109
+ // (Codex reads files through its shell tool).
110
+ export const HOST_TOOLS = Object.freeze({
111
+ claude: { shell: "Bash", read: "Read", edit: "Edit" },
112
+ codex: { shell: "Bash", read: null, edit: "apply_patch" },
113
+ grok: { shell: "run_terminal_command", read: "read_file", edit: "search_replace" },
114
+ });
115
+
116
+ const OLD_ENTRY = Object.freeze({
117
+ claude: [".claude", "hooks", "master-hook.sh"],
118
+ codex: [".codex", "hooks", "hq-codex-hook-adapter.sh"],
119
+ grok: [".grok", "hooks", "hq-grok-hook-adapter.sh"],
120
+ });
121
+
122
+ const GROK_EVENT = Object.freeze({
123
+ PreToolUse: "pre_tool_use",
124
+ PostToolUse: "post_tool_use",
125
+ UserPromptSubmit: "user_prompt_submit",
126
+ });
127
+
128
+ export class UsageError extends Error {}
129
+
130
+ // ---------------------------------------------------------------- arguments
131
+
132
+ function list(value, allowed, flag) {
133
+ const items = String(value).split(",").map((item) => item.trim()).filter(Boolean);
134
+ if (items.length === 0) throw new UsageError(`${flag} needs a value`);
135
+ if (allowed) {
136
+ for (const item of items) {
137
+ if (!allowed.includes(item)) throw new UsageError(`${flag}: unknown value ${item} (use ${allowed.join(", ")})`);
138
+ }
139
+ }
140
+ return [...new Set(items)];
141
+ }
142
+
143
+ function wholeNumber(value, flag, min) {
144
+ if (!/^[0-9]+$/.test(String(value))) throw new UsageError(`${flag} needs a whole number`);
145
+ const number = Number(value);
146
+ if (number < min) throw new UsageError(`${flag} must be at least ${min}`);
147
+ return number;
148
+ }
149
+
150
+ export function parseArgs(argv) {
151
+ const options = {
152
+ root: null,
153
+ hosts: [...HOSTS],
154
+ cores: ["selected"],
155
+ tools: [...TOOLS],
156
+ runs: 15,
157
+ warmup: 1,
158
+ hqHook: "hq-hook",
159
+ coreCommands: {},
160
+ home: null,
161
+ env: {},
162
+ bash: null,
163
+ maxLoad: 1.0,
164
+ timeoutMs: 30000,
165
+ label: null,
166
+ out: null,
167
+ allowLiveRoot: false,
168
+ targets: { ...TARGETS_MS },
169
+ help: false,
170
+ };
171
+ for (let index = 0; index < argv.length; index += 1) {
172
+ const flag = argv[index];
173
+ if (flag === "-h" || flag === "--help") {
174
+ options.help = true;
175
+ continue;
176
+ }
177
+ if (flag === "--allow-live-root") {
178
+ options.allowLiveRoot = true;
179
+ continue;
180
+ }
181
+ const value = argv[index + 1];
182
+ if (value === undefined) throw new UsageError(`${flag} needs a value`);
183
+ index += 1;
184
+ switch (flag) {
185
+ case "--root": options.root = path.resolve(value); break;
186
+ case "--host": case "--hosts": options.hosts = list(value, HOSTS, flag); break;
187
+ case "--core": case "--cores": options.cores = list(value, null, flag); break;
188
+ case "--tools": options.tools = list(value, TOOLS, flag); break;
189
+ case "--runs": options.runs = wholeNumber(value, flag, 5); break;
190
+ case "--warmup": options.warmup = wholeNumber(value, flag, 0); break;
191
+ case "--hq-hook": options.hqHook = value; break;
192
+ case "--home": options.home = path.resolve(value); break;
193
+ case "--bash": options.bash = value; break;
194
+ case "--timeout-ms": options.timeoutMs = wholeNumber(value, flag, 100); break;
195
+ case "--label": options.label = value; break;
196
+ case "--out": options.out = path.resolve(value); break;
197
+ case "--targets": {
198
+ const parts = String(value).split(",");
199
+ if (parts.length !== 2) throw new UsageError("--targets needs <tool call ms>,<prompt ms>");
200
+ options.targets = { tool_call: wholeNumber(parts[0].trim(), flag, 1), prompt: wholeNumber(parts[1].trim(), flag, 1) };
201
+ break;
202
+ }
203
+ case "--max-load": {
204
+ const number = Number(value);
205
+ if (!Number.isFinite(number) || number <= 0) throw new UsageError("--max-load needs a number above 0");
206
+ options.maxLoad = number;
207
+ break;
208
+ }
209
+ case "--env": {
210
+ const at = value.indexOf("=");
211
+ if (at < 1) throw new UsageError("--env needs NAME=VALUE");
212
+ options.env[value.slice(0, at)] = value.slice(at + 1);
213
+ break;
214
+ }
215
+ case "--core-cmd": {
216
+ const at = value.indexOf("=");
217
+ if (at < 1) throw new UsageError("--core-cmd needs <name>=<json array>");
218
+ const name = value.slice(0, at);
219
+ if (BUILTIN_CORES.includes(name)) throw new UsageError(`--core-cmd: ${name} is a built-in core name`);
220
+ let command;
221
+ try {
222
+ command = JSON.parse(value.slice(at + 1));
223
+ } catch {
224
+ throw new UsageError(`--core-cmd ${name}: the command is not a JSON array`);
225
+ }
226
+ if (!Array.isArray(command) || command.length === 0 || !command.every((part) => typeof part === "string")) {
227
+ throw new UsageError(`--core-cmd ${name}: the command must be a JSON array of strings`);
228
+ }
229
+ options.coreCommands[name] = command;
230
+ break;
231
+ }
232
+ default: throw new UsageError(`unknown option: ${flag}`);
233
+ }
234
+ }
235
+ if (options.help) return options;
236
+ if (!options.root) throw new UsageError("--root is required");
237
+ for (const core of options.cores) {
238
+ if (!BUILTIN_CORES.includes(core) && !options.coreCommands[core]) {
239
+ throw new UsageError(`--core: unknown core ${core} (use old, new, selected or a --core-cmd name)`);
240
+ }
241
+ }
242
+ return options;
243
+ }
244
+
245
+ // --------------------------------------------------------------- statistics
246
+
247
+ function quantile(sorted, fraction) {
248
+ if (sorted.length === 0) return null;
249
+ const position = (sorted.length - 1) * fraction;
250
+ const low = Math.floor(position);
251
+ const high = Math.ceil(position);
252
+ return sorted[low] + (sorted[high] - sorted[low]) * (position - low);
253
+ }
254
+
255
+ // Median, spread and a 95% interval for the median from order statistics.
256
+ // With few samples the interval is the whole range.
257
+ export function summarize(samples) {
258
+ const sorted = [...samples].sort((a, b) => a - b);
259
+ const n = sorted.length;
260
+ if (n === 0) return { n: 0, median: null, min: null, max: null, p25: null, p75: null, ci95: [null, null] };
261
+ const half = (1.96 * Math.sqrt(n)) / 2;
262
+ const lowRank = Math.min(n, Math.max(1, Math.floor(n / 2 - half)));
263
+ const highRank = Math.min(n, Math.max(1, Math.ceil(1 + n / 2 + half)));
264
+ return {
265
+ n,
266
+ median: quantile(sorted, 0.5),
267
+ min: sorted[0],
268
+ max: sorted[n - 1],
269
+ p25: quantile(sorted, 0.25),
270
+ p75: quantile(sorted, 0.75),
271
+ ci95: [sorted[lowRank - 1], sorted[highRank - 1]],
272
+ };
273
+ }
274
+
275
+ export const VERDICT = Object.freeze({
276
+ pass: "pass",
277
+ fail: "fail",
278
+ load: "not decidable at this load",
279
+ unclear: "not decidable",
280
+ });
281
+
282
+ // stats: from summarize(). loadPerCpu: median one-minute load average divided
283
+ // by the CPU count, or null where the platform has none. bad: samples whose
284
+ // hook exited nonzero, refused the payload or timed out.
285
+ export function decide({ stats, targetMs, loadPerCpu, maxLoad, bad = 0 }) {
286
+ if (stats.n === 0) return { verdict: VERDICT.unclear, reason: "no samples" };
287
+ if (bad > 0) {
288
+ return {
289
+ verdict: VERDICT.unclear,
290
+ reason: `${bad} of ${stats.n} samples had a hook that exited nonzero, refused or timed out on the test payload`,
291
+ };
292
+ }
293
+ const [low, high] = stats.ci95;
294
+ if (high <= targetMs) {
295
+ return { verdict: VERDICT.pass, reason: `the 95% interval for the median (${fmt(low)} to ${fmt(high)} ms) is at or under ${targetMs} ms` };
296
+ }
297
+ if (low > targetMs) {
298
+ const loaded = loadPerCpu !== null && loadPerCpu > maxLoad;
299
+ if (!loaded) {
300
+ return { verdict: VERDICT.fail, reason: `the 95% interval for the median (${fmt(low)} to ${fmt(high)} ms) is over ${targetMs} ms` };
301
+ }
302
+ // Heuristic: at a load of L per CPU a process gets at worst about 1/L of
303
+ // a CPU, so load can stretch a sample by up to L times. Fail only when the
304
+ // fastest sample with that stretch taken out is still over the target.
305
+ const unloaded = stats.min / Math.max(1, loadPerCpu);
306
+ if (unloaded > targetMs) {
307
+ return {
308
+ verdict: VERDICT.fail,
309
+ reason: `the fastest sample (${fmt(stats.min)} ms) divided by the load of ${loadPerCpu.toFixed(2)} per CPU is ${fmt(unloaded)} ms, still over ${targetMs} ms (a heuristic: load is taken to stretch a run by at most that factor)`,
310
+ };
311
+ }
312
+ return {
313
+ verdict: VERDICT.load,
314
+ reason: `the median is over ${targetMs} ms but the load is ${loadPerCpu.toFixed(2)} per CPU (limit ${maxLoad}); the fastest sample (${fmt(stats.min)} ms) divided by that load is ${fmt(unloaded)} ms, which meets the target`,
315
+ };
316
+ }
317
+ return {
318
+ verdict: VERDICT.unclear,
319
+ reason: `the 95% interval for the median (${fmt(low)} to ${fmt(high)} ms) straddles ${targetMs} ms; run more samples or use a quieter machine`,
320
+ };
321
+ }
322
+
323
+ function fmt(value) {
324
+ return value === null || value === undefined ? "n/a" : String(Math.round(value));
325
+ }
326
+
327
+ const RANK = [VERDICT.pass, VERDICT.unclear, VERDICT.load, VERDICT.fail];
328
+
329
+ export function worstVerdict(verdicts) {
330
+ let worst = VERDICT.pass;
331
+ for (const verdict of verdicts) {
332
+ if (RANK.indexOf(verdict) > RANK.indexOf(worst)) worst = verdict;
333
+ }
334
+ return worst;
335
+ }
336
+
337
+ export function exitCodeFor(verdicts) {
338
+ if (verdicts.includes(VERDICT.fail)) return 1;
339
+ if (verdicts.some((verdict) => verdict !== VERDICT.pass)) return 3;
340
+ return 0;
341
+ }
342
+
343
+ // ------------------------------------------------------------------ payloads
344
+
345
+ // One harmless, synthetic event in the host's own payload shape.
346
+ export function buildPayload({ host, event, tool, root, sessionId, callId }) {
347
+ const hostTool = tool ? HOST_TOOLS[host][tool] : null;
348
+ const scratch = path.join(root, "workspace", "bench-scratch.md");
349
+ const readme = path.join(root, "README.md");
350
+ let input = null;
351
+ let response = null;
352
+ if (tool === "shell") {
353
+ input = { command: "echo bench" };
354
+ if (host === "claude") input.description = "bench";
355
+ response = host === "codex" ? { exit_code: 0 } : { stdout: "bench\n", stderr: "", interrupted: false };
356
+ } else if (tool === "read") {
357
+ input = host === "grok" ? { target_file: readme } : { file_path: readme };
358
+ response = { content: "bench" };
359
+ } else if (tool === "edit") {
360
+ if (host === "codex") {
361
+ input = { command: "*** Begin Patch\n*** Update File: workspace/bench-scratch.md\n@@\n-a\n+b\n*** End Patch" };
362
+ response = { exit_code: 0 };
363
+ } else {
364
+ input = { file_path: scratch, old_string: "a", new_string: "b" };
365
+ response = { filePath: scratch, structuredPatch: [] };
366
+ }
367
+ }
368
+ const toolEvent = event === "PreToolUse" || event === "PostToolUse";
369
+ if (host === "grok") {
370
+ const payload = {
371
+ hookEventName: GROK_EVENT[event] ?? event,
372
+ hook_event_name: event,
373
+ sessionId,
374
+ cwd: root,
375
+ workspaceRoot: root,
376
+ timestamp: new Date().toISOString(),
377
+ permissionMode: "default",
378
+ promptId: `${callId}-prompt`,
379
+ };
380
+ if (toolEvent) {
381
+ Object.assign(payload, { toolName: hostTool, toolInput: input, toolUseId: callId, toolInputTruncated: false });
382
+ if (event === "PostToolUse") Object.assign(payload, { toolResult: response, tool_response: response });
383
+ } else {
384
+ payload.prompt = benchPrompt(callId);
385
+ }
386
+ return payload;
387
+ }
388
+ const payload = { session_id: sessionId, transcript_path: null, cwd: root, hook_event_name: event, permission_mode: "default" };
389
+ if (host === "codex") Object.assign(payload, { model: "bench", turn_id: `${callId}-turn` });
390
+ if (toolEvent) {
391
+ Object.assign(payload, { tool_name: hostTool, tool_input: input, tool_use_id: callId });
392
+ if (event === "PostToolUse") payload.tool_response = response;
393
+ } else {
394
+ payload.prompt = benchPrompt(callId);
395
+ }
396
+ return payload;
397
+ }
398
+
399
+ // The call id makes every prompt payload different, so a core that skips a
400
+ // payload it has seen in the last few seconds still does the full work.
401
+ function benchPrompt(callId) {
402
+ return `bench ${callId}: what time is it`;
403
+ }
404
+
405
+ // ------------------------------------------------------------- registrations
406
+
407
+ function matcherApplies(matcher, toolName) {
408
+ if (matcher === undefined || matcher === null || matcher === "" || matcher === "*") return true;
409
+ if (!toolName) return true;
410
+ try {
411
+ return new RegExp(`^(?:${matcher})$`).test(toolName);
412
+ } catch {
413
+ return false;
414
+ }
415
+ }
416
+
417
+ function readJson(file) {
418
+ try {
419
+ return JSON.parse(fs.readFileSync(file, "utf8"));
420
+ } catch {
421
+ return null;
422
+ }
423
+ }
424
+
425
+ // Hook entries of a Claude settings file, a Codex hooks.json or a Grok hook
426
+ // file (one shape). hqOnly: keep only entries that run an HQ core, for files
427
+ // in the user's home where other tools register hooks too.
428
+ function jsonRegistrations(file, event, toolName, { platform = process.platform, hqOnly = false } = {}) {
429
+ const document = readJson(file);
430
+ const entries = document?.hooks?.[event];
431
+ if (!Array.isArray(entries)) return [];
432
+ const found = [];
433
+ for (const entry of entries) {
434
+ if (!matcherApplies(entry?.matcher, toolName)) continue;
435
+ for (const hook of entry?.hooks ?? []) {
436
+ if (typeof hook?.command !== "string") continue;
437
+ // A hook with an args list is run as that program and those arguments,
438
+ // with no shell (the form the native hook engine registers).
439
+ const args = Array.isArray(hook.args) && hook.args.every((arg) => typeof arg === "string") ? hook.args : null;
440
+ const windows = platform === "win32" && typeof hook.commandWindows === "string" ? hook.commandWindows : null;
441
+ const registration = { command: windows ?? hook.command, args: windows ? null : args, env: hook.env ?? {}, file, windowsForm: windows !== null };
442
+ if (hqOnly && describeCore([[hook.command, ...(args ?? [])].join(" ")]) === "unknown") continue;
443
+ found.push(registration);
444
+ }
445
+ }
446
+ return found;
447
+ }
448
+
449
+ function tomlString(text, key) {
450
+ const literal3 = new RegExp(`^${key}\\s*=\\s*'''([\\s\\S]*?)'''`, "m").exec(text);
451
+ if (literal3) return literal3[1];
452
+ const literal = new RegExp(`^${key}\\s*=\\s*'([^'\\n]*)'`, "m").exec(text);
453
+ if (literal) return literal[1];
454
+ const basic = new RegExp(`^${key}\\s*=\\s*("(?:[^"\\\\\\n]|\\\\.)*")`, "m").exec(text);
455
+ if (basic) {
456
+ try {
457
+ return JSON.parse(basic[1]);
458
+ } catch {
459
+ return null;
460
+ }
461
+ }
462
+ return null;
463
+ }
464
+
465
+ // The hook tables of a Codex config.toml. This reads only what HQ writes
466
+ // there: [[hooks.<Event>]] with an optional matcher, then
467
+ // [[hooks.<Event>.hooks]] with command and commandWindows.
468
+ export function codexRegistrations(text, event, toolName, platform = process.platform) {
469
+ const found = [];
470
+ const header = /^\[\[?([^\]\n]+)\]?\]\s*$/gm;
471
+ const sections = [];
472
+ let match;
473
+ while ((match = header.exec(text)) !== null) sections.push({ name: match[1].trim(), start: match.index, bodyStart: header.lastIndex });
474
+ let matcher = null;
475
+ sections.forEach((section, index) => {
476
+ const body = text.slice(section.bodyStart, sections[index + 1]?.start ?? text.length);
477
+ if (section.name === `hooks.${event}`) {
478
+ matcher = tomlString(body, "matcher");
479
+ } else if (section.name === `hooks.${event}.hooks`) {
480
+ if (!matcherApplies(matcher, toolName)) return;
481
+ const posix = tomlString(body, "command");
482
+ const windows = tomlString(body, "commandWindows");
483
+ const command = platform === "win32" ? windows ?? posix : posix;
484
+ if (command) found.push({ command, env: {}, windowsForm: platform === "win32" && windows !== null });
485
+ }
486
+ });
487
+ return found;
488
+ }
489
+
490
+ export function describeCore(commands) {
491
+ const text = commands.join("\n");
492
+ const native = /hq-hook(?:\.exe)?["']?\s+run\s+--host\b/.test(text);
493
+ const bash = /master-hook\.sh|hq-codex-hook-adapter\.sh|hq-codex-hook\.cmd|hq-grok-hook-adapter\.sh/.test(text);
494
+ // The native hook engine that replaces master-hook.sh today: a pinned
495
+ // hq-hook called with the event name, not with run --host.
496
+ const engine = /hq-hook(?:\.exe)?["']?\s+(?!run\b)[A-Z][A-Za-z]+\b/.test(text);
497
+ const kinds = [native && "new", bash && "old", engine && "engine"].filter(Boolean);
498
+ if (kinds.length > 1) return "mixed";
499
+ return kinds[0] ?? "unknown";
500
+ }
501
+
502
+ function defaultBash(platform) {
503
+ if (platform !== "win32") return "bash";
504
+ for (const base of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && path.join(process.env.LOCALAPPDATA, "Programs")]) {
505
+ if (!base) continue;
506
+ const candidate = path.join(base, "Git", "bin", "bash.exe");
507
+ if (fs.existsSync(candidate)) return candidate;
508
+ }
509
+ return "bash";
510
+ }
511
+
512
+ // The processes to start for one event of one host and core. Returns
513
+ // { steps: [{ file, args, env, cwd, display }], detected, missing }.
514
+ export function resolveInvocation({ host, core, event, tool, options, platform = process.platform }) {
515
+ const root = options.root;
516
+ const bash = options.bash ?? process.env.HQ_BASH_EXE ?? defaultBash(platform);
517
+ const rootEnv = { CLAUDE_PROJECT_DIR: root, HQ_ROOT: root };
518
+ const hostTool = tool ? HOST_TOOLS[host][tool] : null;
519
+
520
+ if (options.coreCommands[core]) {
521
+ const [file, ...args] = options.coreCommands[core].map((part) => part.replaceAll("{host}", host).replaceAll("{event}", event));
522
+ return { steps: [{ file, args, env: rootEnv, cwd: root, display: [file, ...args].join(" ") }], detected: core };
523
+ }
524
+
525
+ if (core === "new") {
526
+ const args = ["run", "--host", host, event];
527
+ return { steps: [{ file: options.hqHook, args, env: rootEnv, cwd: root, display: `${options.hqHook} ${args.join(" ")}` }], detected: "new" };
528
+ }
529
+
530
+ if (core === "old") {
531
+ const script = path.join(root, ...OLD_ENTRY[host]);
532
+ if (!fs.existsSync(script)) return { steps: [], detected: "old", missing: `the old core is not under --root (${script} is missing)` };
533
+ const args = host === "claude" ? [script, event] : [script];
534
+ const env = { ...rootEnv, BASH_ENV: os.devNull };
535
+ if (host === "grok") Object.assign(env, { GROK_WORKSPACE_ROOT: root, GROK_HOOK_EVENT: event });
536
+ return { steps: [{ file: bash, args, env, cwd: root, display: `bash ${args.join(" ")}` }], detected: "old" };
537
+ }
538
+
539
+ // selected: read the host's registration as it is on disk.
540
+ // Project files under --root are HQ's own; in the home folder only entries
541
+ // that run an HQ core count.
542
+ // With no home folder given, no user-level file is read.
543
+ const inHome = (...parts) => (options.home ? path.join(options.home, ...parts) : null);
544
+ const registrations = [];
545
+ if (host === "claude") {
546
+ for (const name of ["settings.json", "settings.local.json"]) {
547
+ registrations.push(...jsonRegistrations(path.join(root, ".claude", name), event, hostTool, { platform }));
548
+ }
549
+ registrations.push(...jsonRegistrations(inHome(".claude", "settings.json"), event, hostTool, { platform, hqOnly: true }));
550
+ } else if (host === "codex") {
551
+ for (const [file, hqOnly] of [[path.join(root, ".codex", "config.toml"), false], [inHome(".codex", "config.toml"), true]]) {
552
+ if (!file || !fs.existsSync(file)) continue;
553
+ for (const entry of codexRegistrations(fs.readFileSync(file, "utf8"), event, hostTool, platform)) {
554
+ if (hqOnly && describeCore([entry.command]) === "unknown") continue;
555
+ registrations.push({ ...entry, file });
556
+ }
557
+ }
558
+ registrations.push(...jsonRegistrations(inHome(".codex", "hooks.json"), event, hostTool, { platform, hqOnly: true }));
559
+ } else {
560
+ registrations.push(...jsonRegistrations(path.join(root, ".grok", "hooks", "hq-grok.json"), event, hostTool, { platform }));
561
+ registrations.push(...jsonRegistrations(inHome(".grok", "hooks", "hq-hq-bridge.json"), event, hostTool, { platform }));
562
+ }
563
+ if (registrations.length === 0) {
564
+ return { steps: [], detected: "none", missing: `no ${host} registration for ${event} under --root or in the home folder` };
565
+ }
566
+ const steps = registrations.map((registration) => {
567
+ const env = { ...rootEnv, ...registration.env };
568
+ let cwd = root;
569
+ if (host === "grok") {
570
+ Object.assign(env, { GROK_WORKSPACE_ROOT: root, GROK_HOOK_EVENT: event });
571
+ cwd = path.dirname(registration.file);
572
+ }
573
+ if (registration.args) {
574
+ return { file: registration.command, args: registration.args, env, cwd, display: [registration.command, ...registration.args].join(" ") };
575
+ }
576
+ if (registration.windowsForm) {
577
+ // Codex runs commandWindows through the session shell, PowerShell by default.
578
+ return { file: "powershell.exe", args: ["-NoProfile", "-Command", registration.command], env, cwd, display: registration.command };
579
+ }
580
+ return { file: bash, args: ["-c", registration.command], env, cwd, display: registration.command };
581
+ });
582
+ return { steps, detected: describeCore(steps.map((step) => step.display)) };
583
+ }
584
+
585
+ // ------------------------------------------------------------------- running
586
+
587
+ const PASS_THROUGH_ENV = [
588
+ "PATH", "Path", "HOME", "USERPROFILE", "TMPDIR", "TEMP", "TMP", "LANG", "LC_ALL", "SHELL", "USER", "LOGNAME",
589
+ "SystemRoot", "SYSTEMROOT", "ComSpec", "COMSPEC", "PATHEXT", "APPDATA", "LOCALAPPDATA", "ProgramFiles",
590
+ "ProgramFiles(x86)", "ProgramData", "HOMEDRIVE", "HOMEPATH", "windir", "HQ_BASH_EXE",
591
+ ];
592
+
593
+ // A small fixed environment, so a live session's variables do not reach the hooks.
594
+ export function childEnv(options, base = process.env) {
595
+ const env = {};
596
+ for (const name of PASS_THROUGH_ENV) {
597
+ if (base[name] !== undefined) env[name] = base[name];
598
+ }
599
+ if (options.home) {
600
+ env.HOME = options.home;
601
+ env.USERPROFILE = options.home;
602
+ }
603
+ return { ...env, ...options.env };
604
+ }
605
+
606
+ function runStep(step, input, baseEnv, timeoutMs) {
607
+ return new Promise((resolve) => {
608
+ const started = process.hrtime.bigint();
609
+ let settled = false;
610
+ let timedOut = false;
611
+ let ended = null;
612
+ let exitCode = null;
613
+ let graceTimer = null;
614
+ const chunks = [];
615
+ let kept = 0;
616
+ const finish = (error) => {
617
+ if (settled) return;
618
+ settled = true;
619
+ clearTimeout(timer);
620
+ clearTimeout(graceTimer);
621
+ const ms = Number((ended ?? process.hrtime.bigint()) - started) / 1e6;
622
+ const stdout = Buffer.concat(chunks).toString("utf8");
623
+ const stderr = Buffer.concat(errChunks).toString("utf8");
624
+ resolve({
625
+ ms,
626
+ code: exitCode,
627
+ timedOut,
628
+ refusal: timedOut || error ? null : refusalIn(stdout),
629
+ error: error ? String(error.message ?? error) : null,
630
+ stderrLine: firstLine(stderr),
631
+ });
632
+ };
633
+ // The start of stderr, so a hook that exits nonzero says why in the report.
634
+ const errChunks = [];
635
+ let errKept = 0;
636
+ let child;
637
+ try {
638
+ child = spawn(step.file, step.args, {
639
+ cwd: step.cwd,
640
+ env: { ...baseEnv, ...step.env },
641
+ stdio: ["pipe", "pipe", "pipe"],
642
+ windowsHide: true,
643
+ // Its own process group on POSIX, so a timeout can stop the whole tree.
644
+ detached: process.platform !== "win32",
645
+ });
646
+ } catch (error) {
647
+ resolve({ ms: 0, code: null, timedOut: false, refusal: null, error: String(error.message ?? error) });
648
+ return;
649
+ }
650
+ const timer = setTimeout(() => {
651
+ timedOut = true;
652
+ killTree(child);
653
+ }, timeoutMs);
654
+ child.stdout.on("data", (chunk) => {
655
+ if (kept >= MAX_STDOUT) return;
656
+ chunks.push(chunk);
657
+ kept += chunk.length;
658
+ });
659
+ child.stderr.on("data", (chunk) => {
660
+ if (errKept >= MAX_STDERR) return;
661
+ errChunks.push(chunk);
662
+ errKept += chunk.length;
663
+ });
664
+ child.on("error", (error) => finish(error));
665
+ // The time is taken when the hook exits, as the host sees it. Its output
666
+ // is read until the pipe closes, or for one more second when a process the
667
+ // hook left behind still holds the pipe open.
668
+ child.on("exit", (code) => {
669
+ ended = process.hrtime.bigint();
670
+ exitCode = code;
671
+ graceTimer = setTimeout(() => {
672
+ child.stdout.destroy();
673
+ child.stderr.destroy();
674
+ finish(null);
675
+ }, 1000);
676
+ });
677
+ child.on("close", () => finish(null));
678
+ child.stdin.on("error", () => {});
679
+ child.stdin.end(input);
680
+ });
681
+ }
682
+
683
+ const MAX_STDOUT = 256 * 1024;
684
+ const MAX_STDERR = 8 * 1024;
685
+
686
+ // The first line of a hook's stderr that has text, cut to 200 characters.
687
+ export function firstLine(text) {
688
+ const line = text.split(/\r?\n/).map((part) => part.trim()).find(Boolean);
689
+ if (!line) return null;
690
+ return line.length > 200 ? `${line.slice(0, 197)}...` : line;
691
+ }
692
+
693
+ function killTree(child) {
694
+ try {
695
+ if (process.platform === "win32") {
696
+ spawn("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true });
697
+ } else {
698
+ process.kill(-child.pid, "SIGKILL");
699
+ }
700
+ } catch {
701
+ try {
702
+ child.kill("SIGKILL");
703
+ } catch {
704
+ // Already gone.
705
+ }
706
+ }
707
+ }
708
+
709
+ // A refusal a hook writes to stdout while exiting 0: Claude Code and Codex
710
+ // read decision "block" or "deny", hookSpecificOutput.permissionDecision
711
+ // "deny" or "ask", and continue false; Grok Build reads the same names. The
712
+ // harmless test payload must not be refused; a refused sample says nothing
713
+ // about a normal call. Returns the refusal as text, or null.
714
+ export function refusalIn(stdout) {
715
+ const text = stdout.trim();
716
+ if (!text) return null;
717
+ let answer = null;
718
+ for (const candidate of [text, text.split("\n").filter(Boolean).pop()]) {
719
+ try {
720
+ answer = JSON.parse(candidate);
721
+ break;
722
+ } catch {
723
+ // Not JSON; try the last line.
724
+ }
725
+ }
726
+ if (!answer || typeof answer !== "object") return null;
727
+ const decision = String(answer.decision ?? "").toLowerCase();
728
+ if (decision === "block" || decision === "deny") return `decision ${decision}`;
729
+ const specific = answer.hookSpecificOutput ?? {};
730
+ const permission = String(specific.permissionDecision ?? "").toLowerCase();
731
+ if (permission === "deny" || permission === "ask") return `permissionDecision ${permission}`;
732
+ if (String(specific.decision?.behavior ?? "").toLowerCase() === "deny") return "decision behavior deny";
733
+ if (answer.continue === false) return "continue false";
734
+ return null;
735
+ }
736
+
737
+ function loadNow() {
738
+ if (process.platform === "win32") return null;
739
+ return os.loadavg()[0];
740
+ }
741
+
742
+ function cpuCount() {
743
+ return typeof os.availableParallelism === "function" ? os.availableParallelism() : os.cpus().length;
744
+ }
745
+
746
+ function median(values) {
747
+ return summarize(values).median;
748
+ }
749
+
750
+ // Plan: one entry per host, core and measurement.
751
+ export function buildPlan(options) {
752
+ const plan = [];
753
+ for (const host of options.hosts) {
754
+ for (const tool of options.tools) {
755
+ if (!HOST_TOOLS[host][tool]) continue;
756
+ for (const core of options.cores) {
757
+ plan.push({ host, core, measure: "tool_call", tool, events: ["PreToolUse", "PostToolUse"], targetMs: options.targets.tool_call });
758
+ }
759
+ }
760
+ for (const core of options.cores) {
761
+ plan.push({ host, core, measure: "prompt", tool: null, events: ["UserPromptSubmit"], targetMs: options.targets.prompt });
762
+ }
763
+ }
764
+ return plan;
765
+ }
766
+
767
+ // A root live sessions use: it registers an HQ core for a host and has session
768
+ // folders a real host made. A fresh copy or worktree has no session folders.
769
+ // Returns the reason as text, or null.
770
+ export function liveRootReason(root) {
771
+ const registered = [
772
+ path.join(root, ".claude", "settings.json"),
773
+ path.join(root, ".claude", "settings.local.json"),
774
+ path.join(root, ".codex", "config.toml"),
775
+ path.join(root, ".grok", "hooks", "hq-grok.json"),
776
+ ].filter((file) => {
777
+ try {
778
+ return describeCore([fs.readFileSync(file, "utf8")]) !== "unknown";
779
+ } catch {
780
+ return false;
781
+ }
782
+ });
783
+ if (registered.length === 0) return null;
784
+ let sessions = [];
785
+ try {
786
+ sessions = fs.readdirSync(path.join(root, "workspace", "sessions")).filter((name) => !name.startsWith("bench-") && !name.startsWith("."));
787
+ } catch {
788
+ return null;
789
+ }
790
+ if (sessions.length === 0) return null;
791
+ return `${path.relative(root, registered[0])} registers an HQ core and workspace/sessions holds ${sessions.length} session folder(s)`;
792
+ }
793
+
794
+ // A linked git worktree has a .git file pointing at the main repository.
795
+ export function isLinkedWorktree(root) {
796
+ try {
797
+ const marker = path.join(root, ".git");
798
+ return fs.lstatSync(marker).isFile() && fs.readFileSync(marker, "utf8").startsWith("gitdir:");
799
+ } catch {
800
+ return false;
801
+ }
802
+ }
803
+
804
+ export async function runBenchmark(given, log = () => {}) {
805
+ if (!fs.existsSync(given.root)) throw new UsageError(`--root does not exist: ${given.root}`);
806
+ const live = liveRootReason(given.root);
807
+ if (live && !given.allowLiveRoot) {
808
+ throw new UsageError(`--root looks like a root live sessions use (${live}). Use a throwaway copy, or pass --allow-live-root`);
809
+ }
810
+ if (isLinkedWorktree(given.root) && given.cores.some((core) => core === "old" || core === "selected")) {
811
+ throw new UsageError("--root is a linked git worktree, and the old core refuses to run from one (it exits 2 on every event). Use a fresh clone or a plain copy of the HQ root");
812
+ }
813
+ const tempHome = given.home ? null : fs.mkdtempSync(path.join(os.tmpdir(), "hq-bench-core-home-"));
814
+ const options = { ...given, home: given.home ?? tempHome };
815
+ try {
816
+ const report = await measure(options, log);
817
+ report.home = tempHome ? "temporary, empty, removed after the run" : "given with --home";
818
+ return report;
819
+ } finally {
820
+ if (tempHome) fs.rmSync(tempHome, { recursive: true, force: true });
821
+ }
822
+ }
823
+
824
+ async function measure(options, log) {
825
+ fs.mkdirSync(options.home, { recursive: true });
826
+ const baseEnv = childEnv(options);
827
+ const sessionId = `bench-core-${process.pid}-${Date.now()}`;
828
+ const cpus = cpuCount();
829
+ const plan = buildPlan(options).map((entry) => {
830
+ const invocations = entry.events.map((event) => resolveInvocation({ ...entry, event, options }));
831
+ return {
832
+ ...entry,
833
+ invocations,
834
+ missing: invocations.find((invocation) => invocation.missing)?.missing ?? null,
835
+ samples: [],
836
+ loads: [],
837
+ bad: 0,
838
+ timeouts: 0,
839
+ errors: new Set(),
840
+ };
841
+ });
842
+
843
+ // Group the plan so the cores of one measurement run next to each other.
844
+ const groups = new Map();
845
+ for (const entry of plan) {
846
+ const key = `${entry.host}/${entry.measure}/${entry.tool ?? ""}`;
847
+ if (!groups.has(key)) groups.set(key, []);
848
+ groups.get(key).push(entry);
849
+ }
850
+
851
+ let callNumber = 0;
852
+ const rounds = options.warmup + options.runs;
853
+ for (let round = 0; round < rounds; round += 1) {
854
+ const recorded = round >= options.warmup;
855
+ for (const group of groups.values()) {
856
+ const order = round % 2 === 0 ? group : [...group].reverse();
857
+ for (const entry of order) {
858
+ if (entry.missing) continue;
859
+ callNumber += 1;
860
+ const callId = `bench-call-${process.pid}-${callNumber}`;
861
+ const load = loadNow();
862
+ let total = 0;
863
+ let bad = false;
864
+ for (let index = 0; index < entry.events.length; index += 1) {
865
+ const payload = JSON.stringify(buildPayload({ host: entry.host, event: entry.events[index], tool: entry.tool, root: options.root, sessionId, callId }));
866
+ for (const step of entry.invocations[index].steps) {
867
+ const result = await runStep(step, payload, baseEnv, options.timeoutMs);
868
+ total += result.ms;
869
+ if (result.error) entry.errors.add(result.error);
870
+ if (result.timedOut) {
871
+ bad = true;
872
+ if (recorded) entry.timeouts += 1;
873
+ } else if (result.code !== 0) {
874
+ bad = true;
875
+ if (result.code !== null) entry.errors.add(`exit code ${result.code}${result.stderrLine ? `: ${result.stderrLine}` : ""}`);
876
+ } else if (result.refusal) {
877
+ bad = true;
878
+ entry.errors.add(`refused the test payload: ${result.refusal}`);
879
+ }
880
+ }
881
+ }
882
+ if (!recorded) continue;
883
+ entry.samples.push(total);
884
+ entry.loads.push(load);
885
+ if (bad) entry.bad += 1;
886
+ }
887
+ }
888
+ log(`round ${round + 1} of ${rounds}${recorded ? "" : " (warm-up)"} done`);
889
+ }
890
+
891
+ cleanUp(options.root, sessionId);
892
+
893
+ const results = plan.map((entry) => {
894
+ const stats = summarize(entry.samples);
895
+ const loads = entry.loads.filter((value) => value !== null);
896
+ const loadPerCpu = loads.length > 0 ? median(loads) / cpus : null;
897
+ const decision = entry.missing
898
+ ? { verdict: VERDICT.unclear, reason: entry.missing }
899
+ : decide({ stats, targetMs: entry.targetMs, loadPerCpu, maxLoad: options.maxLoad, bad: entry.bad });
900
+ return {
901
+ host: entry.host,
902
+ core: entry.core,
903
+ core_detected: entry.invocations[0].detected,
904
+ measure: entry.measure,
905
+ tool: entry.tool,
906
+ host_tool: entry.tool ? HOST_TOOLS[entry.host][entry.tool] : null,
907
+ events: entry.events,
908
+ commands: entry.invocations.flatMap((invocation) => invocation.steps.map((step) => step.display)),
909
+ target_ms: entry.targetMs,
910
+ n: stats.n,
911
+ median_ms: round1(stats.median),
912
+ min_ms: round1(stats.min),
913
+ p25_ms: round1(stats.p25),
914
+ p75_ms: round1(stats.p75),
915
+ max_ms: round1(stats.max),
916
+ ci95_ms: stats.ci95.map(round1),
917
+ load_per_cpu: loadPerCpu === null ? null : Number(loadPerCpu.toFixed(2)),
918
+ bad_samples: entry.bad,
919
+ timeouts: entry.timeouts,
920
+ errors: [...entry.errors].slice(0, 5),
921
+ verdict: decision.verdict,
922
+ reason: decision.reason,
923
+ samples_ms: entry.samples.map(round1),
924
+ sample_load1: entry.loads.map((value) => (value === null ? null : Number(value.toFixed(2)))),
925
+ };
926
+ });
927
+
928
+ const summary = [];
929
+ for (const host of options.hosts) {
930
+ for (const core of options.cores) {
931
+ const mine = results.filter((result) => result.host === host && result.core === core);
932
+ const toolCalls = mine.filter((result) => result.measure === "tool_call");
933
+ const prompt = mine.find((result) => result.measure === "prompt");
934
+ const medians = toolCalls.map((result) => result.median_ms).filter((value) => value !== null);
935
+ summary.push({
936
+ host,
937
+ core,
938
+ core_detected: mine[0]?.core_detected ?? null,
939
+ tool_call: {
940
+ target_ms: options.targets.tool_call,
941
+ median_ms: medians.length > 0 ? Math.max(...medians) : null,
942
+ verdict: toolCalls.length > 0 ? worstVerdict(toolCalls.map((result) => result.verdict)) : VERDICT.unclear,
943
+ },
944
+ prompt: {
945
+ target_ms: options.targets.prompt,
946
+ median_ms: prompt?.median_ms ?? null,
947
+ verdict: prompt?.verdict ?? VERDICT.unclear,
948
+ },
949
+ });
950
+ }
951
+ }
952
+
953
+ const allLoads = plan.flatMap((entry) => entry.loads).filter((value) => value !== null);
954
+ const verdicts = results.map((result) => result.verdict);
955
+ const missing = [...new Set(plan.filter((entry) => entry.missing).map((entry) => `${entry.host} ${entry.core}: ${entry.missing}`))];
956
+ return {
957
+ schema: REPORT_SCHEMA,
958
+ generated_at: new Date().toISOString(),
959
+ machine: {
960
+ label: options.label ?? os.hostname(),
961
+ platform: process.platform,
962
+ os_release: os.release(),
963
+ arch: process.arch,
964
+ cpus,
965
+ cpu_model: os.cpus()[0]?.model ?? null,
966
+ node: process.version,
967
+ },
968
+ root: options.root,
969
+ home: null,
970
+ targets_ms: options.targets,
971
+ gate_targets: options.targets.tool_call === TARGETS_MS.tool_call && options.targets.prompt === TARGETS_MS.prompt,
972
+ runs: options.runs,
973
+ warmup: options.warmup,
974
+ max_load_per_cpu: options.maxLoad,
975
+ load: allLoads.length > 0
976
+ ? { available: true, min: Math.min(...allLoads), median: Number(median(allLoads).toFixed(2)), max: Math.max(...allLoads), per_cpu_median: Number((median(allLoads) / cpus).toFixed(2)) }
977
+ : { available: false, note: "this platform has no load average; the load rule was not applied" },
978
+ verdict: worstVerdict(verdicts),
979
+ // A core that is not there is a setup error, as for a usage error.
980
+ exit_code: missing.length > 0 ? 2 : exitCodeFor(verdicts),
981
+ setup_errors: missing,
982
+ caveats: CAVEATS,
983
+ summary,
984
+ results,
985
+ };
986
+ }
987
+
988
+ export const CAVEATS = Object.freeze([
989
+ "The setup is synthetic and isolated: no transcript file, no flag snapshot, a session no project is bound to, an empty home unless --home is given, and the env block of settings.json is not applied. A core can do less work here than in a real session, so it can look faster than on a working machine.",
990
+ "Hooks registered for one event are timed one after another and summed. A host that runs them in parallel would see less, so the sum errs toward fail.",
991
+ "A fail under load is a heuristic: load is taken to stretch a run by at most the load per CPU.",
992
+ ]);
993
+
994
+ function round1(value) {
995
+ return value === null || value === undefined ? null : Math.round(value * 10) / 10;
996
+ }
997
+
998
+ // The old core writes files named after the session under --root. Only paths
999
+ // made from this run's own session id are removed.
1000
+ function cleanUp(root, sessionId) {
1001
+ try {
1002
+ fs.rmSync(path.join(root, "workspace", "sessions", sessionId), { recursive: true, force: true });
1003
+ } catch {
1004
+ // Nothing to remove.
1005
+ }
1006
+ }
1007
+
1008
+ // ------------------------------------------------------------------- report
1009
+
1010
+ export function formatReport(report) {
1011
+ const lines = [];
1012
+ const machine = report.machine;
1013
+ lines.push(`hq bench-core machine=${machine.label} platform=${machine.platform} ${machine.arch} cpus=${machine.cpus} node=${machine.node}`);
1014
+ lines.push(`root=${report.root} home=${report.home} runs=${report.runs} generated=${report.generated_at}`);
1015
+ if (!report.gate_targets) {
1016
+ lines.push(`targets: ${report.targets_ms.tool_call} ms per tool call, ${report.targets_ms.prompt} ms per prompt; these are not the speed gate's targets`);
1017
+ }
1018
+ lines.push(report.load.available
1019
+ ? `load average (1 min): min ${report.load.min.toFixed(2)}, median ${report.load.median.toFixed(2)}, max ${report.load.max.toFixed(2)}; ${report.load.per_cpu_median} per CPU (limit ${report.max_load_per_cpu})`
1020
+ : `load average: ${report.load.note}`);
1021
+ lines.push("");
1022
+ const header = ["host", "core", "measure", "target", "median", "95% interval", "min", "max", "n", "verdict"];
1023
+ const rows = report.results.map((result) => [
1024
+ result.host,
1025
+ result.core === result.core_detected ? result.core : `${result.core} (${result.core_detected})`,
1026
+ result.measure === "tool_call" ? `tool call: ${result.host_tool}` : "prompt",
1027
+ `${result.target_ms} ms`,
1028
+ `${fmt(result.median_ms)} ms`,
1029
+ `${fmt(result.ci95_ms[0])} to ${fmt(result.ci95_ms[1])}`,
1030
+ fmt(result.min_ms),
1031
+ fmt(result.max_ms),
1032
+ String(result.n),
1033
+ result.verdict,
1034
+ ]);
1035
+ const widths = header.map((title, column) => Math.max(title.length, ...rows.map((row) => row[column].length)));
1036
+ const line = (cells) => cells.map((cell, column) => cell.padEnd(widths[column])).join(" ").trimEnd();
1037
+ lines.push(line(header));
1038
+ for (const row of rows) lines.push(line(row));
1039
+ lines.push("");
1040
+ for (const result of report.results) {
1041
+ if (result.verdict !== VERDICT.pass) {
1042
+ lines.push(`${result.host} ${result.core} ${result.measure}${result.host_tool ? ` ${result.host_tool}` : ""}: ${result.verdict}: ${result.reason}`);
1043
+ }
1044
+ }
1045
+ lines.push("");
1046
+ for (const entry of report.summary) {
1047
+ lines.push(`${entry.host} / ${entry.core}: tool call ${fmt(entry.tool_call.median_ms)} ms against ${entry.tool_call.target_ms} ms: ${entry.tool_call.verdict}; prompt ${fmt(entry.prompt.median_ms)} ms against ${entry.prompt.target_ms} ms: ${entry.prompt.verdict}`);
1048
+ }
1049
+ lines.push(`overall: ${report.verdict}`);
1050
+ for (const error of report.setup_errors) lines.push(`setup error: ${error}`);
1051
+ lines.push("");
1052
+ for (const caveat of report.caveats) lines.push(`note: ${caveat}`);
1053
+ return `${lines.join("\n")}\n`;
1054
+ }
1055
+
1056
+ function usage() {
1057
+ const source = fs.readFileSync(new URL(import.meta.url), "utf8").split("\n");
1058
+ const start = source.findIndex((text) => text.startsWith("// Usage"));
1059
+ const end = source.findIndex((text, index) => index > start && !text.startsWith("//"));
1060
+ return `${source.slice(start, end).map((text) => text.replace(/^\/\/ ?/, "")).join("\n")}\n`;
1061
+ }
1062
+
1063
+ export async function main(argv, io = { out: process.stdout, err: process.stderr }) {
1064
+ let options;
1065
+ try {
1066
+ options = parseArgs(argv);
1067
+ } catch (error) {
1068
+ io.err.write(`bench-core: ${error.message}\n`);
1069
+ return 2;
1070
+ }
1071
+ if (options.help) {
1072
+ io.out.write(usage());
1073
+ return 0;
1074
+ }
1075
+ let report;
1076
+ try {
1077
+ report = await runBenchmark(options, (text) => io.err.write(`bench-core: ${text}\n`));
1078
+ } catch (error) {
1079
+ io.err.write(`bench-core: ${error.message}\n`);
1080
+ return 2;
1081
+ }
1082
+ const stamp = report.generated_at.replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
1083
+ const out = options.out ?? path.resolve(`hq-bench-core-${process.platform}-${stamp}.json`);
1084
+ const text = formatReport(report);
1085
+ fs.mkdirSync(path.dirname(out), { recursive: true });
1086
+ fs.writeFileSync(out, `${JSON.stringify(report, null, 2)}\n`);
1087
+ const textOut = out.replace(/\.json$/i, "") + ".txt";
1088
+ fs.writeFileSync(textOut, text);
1089
+ io.out.write(text);
1090
+ io.out.write(`report: ${out}\nreport (text): ${textOut}\n`);
1091
+ return report.exit_code;
1092
+ }
1093
+
1094
+ if (process.argv[1] && import.meta.url === pathToFileURL(fs.realpathSync(process.argv[1])).href) {
1095
+ process.exitCode = await main(process.argv.slice(2));
1096
+ }