@indigoai-us/hq-cli 5.345.237 → 5.345.241

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 (115) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-repo.sh +7 -1
  3. package/assets/scaffold/core/scripts/hq-delegate-secrets.sh +95 -20
  4. package/assets/scaffold/core/scripts/hq-delegate-transfer.sh +57 -9
  5. package/dist/command-catalog.generated.d.ts +185 -3
  6. package/dist/command-catalog.generated.js +228 -3
  7. package/dist/command-registration-plan.d.ts +6 -0
  8. package/dist/command-registration-plan.js +1 -0
  9. package/dist/commands/bot.d.ts +2 -0
  10. package/dist/commands/bot.js +23 -0
  11. package/dist/commands/cloud-off-gate.d.ts +2 -1
  12. package/dist/commands/cloud-off-gate.js +17 -4
  13. package/dist/commands/cloud.d.ts +17 -2
  14. package/dist/commands/cloud.js +126 -24
  15. package/dist/commands/core-delegate-w1b.js +35 -10
  16. package/dist/commands/core-delegate.d.ts +2 -1
  17. package/dist/commands/core-delegate.js +207 -48
  18. package/dist/commands/deploy-comments.js +8 -2
  19. package/dist/commands/deploy-events.d.ts +40 -0
  20. package/dist/commands/deploy-events.js +300 -0
  21. package/dist/commands/doctor.d.ts +4 -4
  22. package/dist/commands/doctor.js +2 -2
  23. package/dist/commands/feedback.js +2 -3
  24. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  25. package/dist/commands/keyed-sync-pull.js +151 -0
  26. package/dist/commands/library-add.d.ts +5 -2
  27. package/dist/commands/library-add.js +22 -9
  28. package/dist/commands/mcp-registration.d.ts +4 -18
  29. package/dist/commands/mcp-registration.js +9 -29
  30. package/dist/commands/mesh.d.ts +4 -0
  31. package/dist/commands/mesh.js +25 -5
  32. package/dist/commands/pack-install.d.ts +2 -3
  33. package/dist/commands/pack-install.js +6 -8
  34. package/dist/commands/secrets.d.ts +3 -4
  35. package/dist/commands/secrets.js +3 -20
  36. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +307 -232
  37. package/dist/hq-cloud-sync-runner/package.json +1 -1
  38. package/dist/lib/agent-kit/inbox-state.d.ts +2 -1
  39. package/dist/lib/agent-kit/inbox-state.js +27 -3
  40. package/dist/lib/bot/api.d.ts +2 -1
  41. package/dist/lib/bot/api.js +2 -15
  42. package/dist/lib/bot/promote.d.ts +23 -0
  43. package/dist/lib/bot/promote.js +73 -0
  44. package/dist/lib/bot/promotion-hold-reconcile.d.ts +56 -0
  45. package/dist/lib/bot/promotion-hold-reconcile.js +155 -0
  46. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  47. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  48. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  49. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  50. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  51. package/dist/lib/daemon/jq-provision.js +155 -0
  52. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  53. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  54. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  55. package/dist/lib/daemon/mesh-owner.js +20 -0
  56. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  57. package/dist/lib/daemon/ops/policy.js +32 -4
  58. package/dist/lib/daemon/run.d.ts +17 -1
  59. package/dist/lib/daemon/run.js +24 -3
  60. package/dist/lib/daemon/server.d.ts +6 -0
  61. package/dist/lib/daemon/server.js +5 -0
  62. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  63. package/dist/lib/daemon/verified-jq.js +337 -0
  64. package/dist/lib/doctor/checks/jq.js +16 -0
  65. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  66. package/dist/lib/doctor/deep/executor.js +1 -1
  67. package/dist/lib/doctor/deep/parity.js +1 -27
  68. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  69. package/dist/lib/doctor/deep/sandbox.js +3 -19
  70. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  71. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  72. package/dist/lib/doctor/fixtures/discover.js +1 -1
  73. package/dist/lib/doctor/json-output.d.ts +1 -1
  74. package/dist/lib/doctor/registry.d.ts +6 -7
  75. package/dist/lib/doctor/registry.js +6 -7
  76. package/dist/lib/doctor/report.d.ts +9 -10
  77. package/dist/lib/doctor/report.js +4 -4
  78. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  79. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  80. package/dist/lib/jq/install.d.ts +27 -0
  81. package/dist/lib/jq/install.js +156 -0
  82. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  83. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  84. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  85. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  86. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  87. package/dist/lib/mesh/live/daemon/install.js +10 -0
  88. package/dist/lib/mesh/live/daemon/run.js +17 -0
  89. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  90. package/dist/lib/mesh/live/emit-retry.js +57 -4
  91. package/dist/lib/mesh/live/emit.js +25 -4
  92. package/dist/lib/mesh/live/flush.d.ts +2 -0
  93. package/dist/lib/mesh/live/flush.js +21 -8
  94. package/dist/lib/mesh/live/spool.d.ts +9 -1
  95. package/dist/lib/mesh/live/spool.js +41 -29
  96. package/dist/lib/sync-core/rollout-state.d.ts +9 -1
  97. package/dist/lib/sync-core/rollout-state.js +34 -4
  98. package/dist/lib/windows/jq.d.ts +4 -0
  99. package/dist/lib/windows/jq.js +10 -39
  100. package/dist/lib/workers-registry/index.js +7 -11
  101. package/dist/utils/callback-port-busy.d.ts +2 -2
  102. package/dist/utils/callback-port-busy.js +2 -2
  103. package/dist/utils/cli-network-lifecycle.js +1 -0
  104. package/dist/utils/client-health-contract.d.ts +2 -0
  105. package/dist/utils/client-health-contract.js +1 -1
  106. package/dist/utils/client-health.js +1 -9
  107. package/dist/utils/cognito-config.js +5 -0
  108. package/dist/utils/cognito-session.d.ts +4 -6
  109. package/dist/utils/cognito-session.js +4 -24
  110. package/dist/utils/incomplete-install-error.js +1 -11
  111. package/dist/utils/install-tree-torn.d.ts +11 -0
  112. package/dist/utils/install-tree-torn.js +1 -1
  113. package/dist/utils/resident-package-preload.js +2 -1
  114. package/docs/anywhere-runtime.md +8 -0
  115. package/package.json +9 -9
@@ -0,0 +1,337 @@
1
+ /**
2
+ * A jq the daemon can trust to run the hq-core hook scripts.
3
+ *
4
+ * The scope authorizer parses every hook payload with whatever `jq` is first on
5
+ * its PATH. The daemon's OS unit puts the login user's tool folders first
6
+ * (~/.local/bin, see tools.ts userToolDirs), and people keep homemade tools
7
+ * there. A `jq` that is not jq breaks the authorizer in both directions:
8
+ *
9
+ * - A stand-in that echoes stdin for the agent-field filter turned every
10
+ * main-thread check into "This call has an invalid agent_id".
11
+ * - A stand-in that echoes stdin for every filter makes the authorizer read no
12
+ * tool name or path at all, and it then allows Read, Write, Grep and Bash
13
+ * calls into another company's folder.
14
+ *
15
+ * So before the daemon runs a hook script it finds a jq that reports
16
+ * `jq-1.x` for `--version` and computes a known filter correctly, and gives the
17
+ * scripts a PATH whose `jq` is that binary and nothing else. If no candidate
18
+ * qualifies the caller fails closed.
19
+ *
20
+ * Probes run with stdin closed and a timeout: a stand-in that reads stdin and
21
+ * ignores flags hangs on `--version` otherwise.
22
+ */
23
+ import { spawn } from "node:child_process";
24
+ import * as fs from "node:fs";
25
+ import * as path from "node:path";
26
+ import { checkJqDirectory, checkSystemJqDirectory, UnsafeJqPathError } from "../jq/install.js";
27
+ export const JQ_VERSION_RE = /^jq-1\.\d+/;
28
+ /** Input, filter and exact output of the behavior probe. */
29
+ export const JQ_BEHAVIOR_PROBE = {
30
+ input: '{"a":null,"b":"x","c":[1,2],"d":{"e":"f"}}',
31
+ filter: '(if .a == null then "" else .a end) + "|" + (.b | ascii_upcase) + "|" + (.c | map(. * 2 | tostring) | join(",")) + "|" + (.d | to_entries | map(.key + "=" + .value) | join(";"))',
32
+ expected: "|X|2,4|e=f",
33
+ };
34
+ /** Per probe step; real jq answers in milliseconds. Keeps a cold check well under the client's timeout. */
35
+ const PROBE_TIMEOUT_MS = 2_000;
36
+ export class JqUnavailableError extends Error {
37
+ rejected;
38
+ note;
39
+ constructor(rejected, note) {
40
+ super(describeJqUnavailable(rejected, note));
41
+ this.rejected = rejected;
42
+ this.note = note;
43
+ this.name = "JqUnavailableError";
44
+ }
45
+ }
46
+ /** The plain-language reason a policy check gives when no jq qualifies. */
47
+ export function describeJqUnavailable(rejected, note) {
48
+ const head = "HQ could not run the company access check, so it is blocking this call: the check needs jq, and";
49
+ const tail = note ? ` ${note}` : " Updating HQ installs a verified copy.";
50
+ if (rejected.length === 0)
51
+ return `${head} no jq was found on this computer.${tail}`;
52
+ const found = rejected.map((r) => `${r.path} (${r.reason})`).join("; ");
53
+ return `${head} no working jq was found. Found: ${found}.${tail}`;
54
+ }
55
+ /** Run `file args` with no shell, a small clean environment and a hard timeout. */
56
+ export const runJq = (file, args, input, timeoutMs) => new Promise((resolve) => {
57
+ let child;
58
+ try {
59
+ child = spawn(file, args, {
60
+ stdio: [input === null ? "ignore" : "pipe", "pipe", "ignore"],
61
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" },
62
+ });
63
+ }
64
+ catch (err) {
65
+ resolve({ code: null, stdout: "", timedOut: false, error: err.message });
66
+ return;
67
+ }
68
+ let stdout = "";
69
+ let timedOut = false;
70
+ let settled = false;
71
+ const finish = (r) => {
72
+ if (settled)
73
+ return;
74
+ settled = true;
75
+ clearTimeout(timer);
76
+ resolve(r);
77
+ };
78
+ const timer = setTimeout(() => {
79
+ timedOut = true;
80
+ child.kill("SIGKILL");
81
+ finish({ code: null, stdout, timedOut: true });
82
+ }, timeoutMs);
83
+ child.stdout?.on("data", (c) => {
84
+ stdout += c.toString("utf8");
85
+ if (stdout.length > 64 * 1024)
86
+ child.kill("SIGKILL");
87
+ });
88
+ child.on("error", (err) => finish({ code: null, stdout, timedOut, error: err.message }));
89
+ child.on("close", (code) => finish({ code, stdout, timedOut }));
90
+ if (input !== null && child.stdin) {
91
+ child.stdin.on("error", () => {
92
+ // A candidate that exits without reading stdin is judged by its output.
93
+ });
94
+ child.stdin.end(input);
95
+ }
96
+ });
97
+ /** Whether `file` is real jq: `--version` says jq-1.x and a known filter computes correctly. */
98
+ export async function probeJq(file, run = runJq, timeoutMs = PROBE_TIMEOUT_MS) {
99
+ const v = await run(file, ["--version"], null, timeoutMs);
100
+ if (v.timedOut)
101
+ return { ok: false, version: null, reason: "jq --version did not answer" };
102
+ if (v.error)
103
+ return { ok: false, version: null, reason: `could not run it: ${v.error}` };
104
+ const version = v.stdout.trim().split(/\r?\n/)[0] ?? "";
105
+ if (v.code !== 0 || !JQ_VERSION_RE.test(version)) {
106
+ const shown = version.slice(0, 40).replace(/[^\x20-\x7e]/g, "?");
107
+ return { ok: false, version: null, reason: `jq --version printed "${shown}", not jq-1.x` };
108
+ }
109
+ const b = await run(file, ["-j", JQ_BEHAVIOR_PROBE.filter], JQ_BEHAVIOR_PROBE.input, timeoutMs);
110
+ if (b.timedOut)
111
+ return { ok: false, version, reason: "it did not answer a test filter" };
112
+ if (b.code !== 0 || b.stdout !== JQ_BEHAVIOR_PROBE.expected) {
113
+ return { ok: false, version, reason: "it answered a test filter wrongly, so it is not jq" };
114
+ }
115
+ return { ok: true, version, reason: "" };
116
+ }
117
+ /**
118
+ * Where to look, best first. Folders the user's own tools cannot shadow come
119
+ * first (Apple's /usr/bin/jq on macOS 15+, then Homebrew and /usr/local), then
120
+ * every PATH entry in order. Every candidate is probed regardless.
121
+ */
122
+ export const VETTED_JQ_PATHS = ["/usr/bin/jq", "/opt/homebrew/bin/jq", "/usr/local/bin/jq"];
123
+ export function jqCandidates(env, platform = process.platform, vettedPaths = VETTED_JQ_PATHS) {
124
+ const windows = platform === "win32";
125
+ const p = windows ? path.win32 : path.posix;
126
+ // Only files named jq: the hook scripts run `jq`, so another name on PATH
127
+ // could never be what they run.
128
+ const names = windows ? ["jq.exe", "jq"] : ["jq"];
129
+ const vetted = windows ? vettedPaths.filter((file) => /^[a-z]:[\\/]|^\\\\/i.test(file)) : vettedPaths;
130
+ const fromPath = [];
131
+ for (const dir of (env.PATH ?? env.Path ?? "").split(p.delimiter)) {
132
+ if (!dir || !p.isAbsolute(dir))
133
+ continue;
134
+ for (const name of names)
135
+ fromPath.push(p.join(dir, name));
136
+ }
137
+ return [...new Set([...vetted, ...fromPath])];
138
+ }
139
+ /** Probe results by real path, valid while the file's stat stamp is unchanged. */
140
+ const probeCache = new Map();
141
+ /** For tests. */
142
+ export function clearJqProbeCache() {
143
+ probeCache.clear();
144
+ }
145
+ function stampOf(file) {
146
+ try {
147
+ const st = fs.statSync(file);
148
+ if (!st.isFile())
149
+ return null;
150
+ return `${st.dev}:${st.ino}:${st.size}:${st.mtimeMs}:${st.mode}`;
151
+ }
152
+ catch {
153
+ return null;
154
+ }
155
+ }
156
+ function isExecutable(file, windows) {
157
+ if (windows)
158
+ return true;
159
+ try {
160
+ fs.accessSync(file, fs.constants.X_OK);
161
+ return true;
162
+ }
163
+ catch {
164
+ return false;
165
+ }
166
+ }
167
+ /** Point `<binDir>/jq` at `target`, replacing a link that points elsewhere. */
168
+ function linkJq(home, binDir, target) {
169
+ const link = path.join(binDir, "jq");
170
+ checkJqDirectory(home, binDir, true);
171
+ try {
172
+ if (fs.readlinkSync(link) === target)
173
+ return;
174
+ }
175
+ catch {
176
+ // Missing or not a link: (re)create below.
177
+ }
178
+ const tmp = `${link}.${process.pid}.${Date.now()}.tmp`;
179
+ fs.symlinkSync(target, tmp);
180
+ fs.renameSync(tmp, link);
181
+ checkJqDirectory(home, binDir);
182
+ }
183
+ function within(location, file) {
184
+ const relative = path.relative(location, file);
185
+ return !relative || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
186
+ }
187
+ function refusedLocation(file, realFile, locations) {
188
+ for (const location of locations) {
189
+ const roots = [path.resolve(location)];
190
+ try {
191
+ roots.push(fs.realpathSync(location));
192
+ }
193
+ catch (error) {
194
+ if (error.code !== "ENOENT") {
195
+ throw new JqUnavailableError([{ path: location, reason: `could not resolve refused location: ${error.message}` }]);
196
+ }
197
+ }
198
+ if (roots.some((root) => within(root, path.resolve(file)) || within(root, realFile)))
199
+ return location;
200
+ }
201
+ return undefined;
202
+ }
203
+ /**
204
+ * The first candidate that passes probeJq. Throws JqUnavailableError, listing
205
+ * what was refused and why, when none does.
206
+ */
207
+ export async function resolveVerifiedJq(deps) {
208
+ const platform = deps.platform ?? process.platform;
209
+ const windows = platform === "win32";
210
+ const run = deps.run ?? runJq;
211
+ const rejected = [];
212
+ const rejectedLocations = [...(deps.rejectedLocations ?? [])];
213
+ const home = windows ? deps.env.USERPROFILE ?? deps.env.HOME : deps.env.HOME;
214
+ const privateDir = windows ? undefined : deps.binDir ?? (home ? path.join(home, ".hq", "daemon", "verified-bin") : undefined);
215
+ let privateAllowed = Boolean(privateDir && home);
216
+ if (privateDir && home) {
217
+ try {
218
+ checkJqDirectory(home, privateDir);
219
+ }
220
+ catch (error) {
221
+ privateAllowed = false;
222
+ if (error instanceof UnsafeJqPathError)
223
+ rejectedLocations.push(error.path);
224
+ rejected.push({ path: privateDir, reason: error.message });
225
+ }
226
+ }
227
+ const seenReal = new Set();
228
+ for (const candidate of jqCandidates(deps.env, platform, deps.vettedPaths)) {
229
+ if (!fs.existsSync(candidate))
230
+ continue;
231
+ let realPath;
232
+ let candidateDir;
233
+ try {
234
+ realPath = fs.realpathSync(candidate);
235
+ candidateDir = fs.realpathSync(path.dirname(candidate));
236
+ }
237
+ catch {
238
+ continue;
239
+ }
240
+ const refused = refusedLocation(candidate, realPath, rejectedLocations) ??
241
+ refusedLocation(path.dirname(candidate), candidateDir, rejectedLocations);
242
+ if (refused) {
243
+ rejected.push({ path: candidate, reason: `inside refused jq location: ${refused}` });
244
+ continue;
245
+ }
246
+ if (deps.rejectedPaths?.some((rejected) => {
247
+ if (path.resolve(rejected) === realPath || path.resolve(rejected) === path.resolve(candidate))
248
+ return true;
249
+ // A refused path may itself contain a symlink (including a parent).
250
+ // Reject aliases of its referent before any executable probe as well.
251
+ try {
252
+ return fs.realpathSync(rejected) === realPath;
253
+ }
254
+ catch {
255
+ return false;
256
+ }
257
+ })) {
258
+ rejected.push({ path: candidate, reason: "managed jq failed its checksum or path safety checks" });
259
+ continue;
260
+ }
261
+ if (seenReal.has(realPath))
262
+ continue;
263
+ seenReal.add(realPath);
264
+ const stamp = stampOf(realPath);
265
+ if (stamp === null || !isExecutable(realPath, windows))
266
+ continue;
267
+ let probe = probeCache.get(realPath);
268
+ if (!probe || probe.stamp !== stamp) {
269
+ probe = { stamp, probe: await probeJq(realPath, run, deps.timeoutMs) };
270
+ // A verdict about replaced bytes must neither be cached nor used.
271
+ if (stampOf(realPath) !== stamp) {
272
+ probeCache.delete(realPath);
273
+ rejected.push({ path: candidate, reason: "jq changed while it was being checked" });
274
+ continue;
275
+ }
276
+ probeCache.set(realPath, probe);
277
+ }
278
+ if (!probe.probe.ok) {
279
+ rejected.push({ path: candidate, reason: probe.probe.reason });
280
+ continue;
281
+ }
282
+ const version = probe.probe.version ?? "jq-1";
283
+ if (!windows) {
284
+ // The private folder holds only `jq`, so the scripts' bash and other tools
285
+ // resolve exactly as before.
286
+ if (privateAllowed && home && privateDir && !refusedLocation(privateDir, path.resolve(privateDir), rejectedLocations)) {
287
+ try {
288
+ linkJq(home, privateDir, realPath);
289
+ return { path: candidate, realPath, version, binDir: privateDir };
290
+ }
291
+ catch (error) {
292
+ privateAllowed = false;
293
+ if (error instanceof UnsafeJqPathError)
294
+ rejectedLocations.push(error.path);
295
+ rejected.push({ path: privateDir, reason: error.message });
296
+ }
297
+ }
298
+ }
299
+ // Fallback: the candidate's own folder. Candidates are always named jq
300
+ // (jq.exe on Windows), so a `jq` lookup there reaches this candidate, not
301
+ // the binary's real folder, whose `jq` may be something else.
302
+ const p = windows ? path.win32 : path.posix;
303
+ const binDir = candidateDir;
304
+ const newlyRefused = refusedLocation(candidate, realPath, rejectedLocations) ??
305
+ refusedLocation(path.dirname(candidate), binDir, rejectedLocations);
306
+ if (newlyRefused) {
307
+ rejected.push({ path: candidate, reason: `inside refused jq location: ${newlyRefused}` });
308
+ continue;
309
+ }
310
+ try {
311
+ checkSystemJqDirectory(binDir);
312
+ }
313
+ catch (error) {
314
+ rejected.push({ path: candidate, reason: error.message });
315
+ continue;
316
+ }
317
+ if (windows && p.basename(candidate).toLowerCase() === "jq.exe" && fs.existsSync(p.join(binDir, "jq"))) {
318
+ // Git Bash would run the extensionless `jq` next to it instead.
319
+ rejected.push({ path: candidate, reason: "an unchecked jq script sits next to it" });
320
+ continue;
321
+ }
322
+ return { path: candidate, realPath, version, binDir };
323
+ }
324
+ throw new JqUnavailableError(rejected);
325
+ }
326
+ /** `env` with `binDir` first on PATH. */
327
+ export function withJqFirst(env, binDir, platform = process.platform) {
328
+ const delimiter = platform === "win32" ? ";" : ":";
329
+ const key = platform === "win32" && env.PATH === undefined && env.Path !== undefined ? "Path" : "PATH";
330
+ const rest = (env[key] ?? "").split(delimiter).filter((d) => d && d !== binDir);
331
+ // An environment with no PATH used to get the OS default search path; keep
332
+ // bash and the coreutils the scripts need reachable.
333
+ if (rest.length === 0 && platform !== "win32")
334
+ rest.push("/usr/bin", "/bin");
335
+ return { ...env, [key]: [binDir, ...rest].join(delimiter) };
336
+ }
337
+ //# sourceMappingURL=verified-jq.js.map
@@ -1,5 +1,6 @@
1
1
  import { execFileSync } from "node:child_process";
2
2
  import { findExecutableOnPath } from "../../../utils/resolve-executable.js";
3
+ import { JQ_VERSION_RE } from "../../daemon/verified-jq.js";
3
4
  export const JQ_FAMILY_ID = "jq";
4
5
  export const JQ_CHECK_ID = "jq.on-path";
5
6
  /**
@@ -69,6 +70,21 @@ export function checkJq(_context, deps = defaultDeps) {
69
70
  },
70
71
  ];
71
72
  }
73
+ // A homemade or wrapper `jq` that is not jq breaks every
74
+ // hook payload parse, so it counts as missing. Real jq prints jq-1.x.
75
+ const firstLine = version.split(/\r?\n/)[0] ?? "";
76
+ if (!JQ_VERSION_RE.test(firstLine)) {
77
+ const shown = firstLine.slice(0, 40).replace(/[^\x20-\x7e]/g, "?");
78
+ return [
79
+ {
80
+ status: "FAIL",
81
+ checkId: JQ_CHECK_ID,
82
+ target: file,
83
+ message: `The jq on PATH at ${file} is not jq: \`jq --version\` printed "${shown}" instead of jq-1.x. HQ hooks cannot read tool calls with it.`,
84
+ remediation: `${jqInstallHint(deps.platform)} The HQ desktop app replaces a jq that is not jq when it next checks its tools.`,
85
+ },
86
+ ];
87
+ }
72
88
  return [
73
89
  {
74
90
  status: "PASS",
@@ -38,6 +38,7 @@
38
38
  */
39
39
  import type { CheckContext, CheckResult } from "../types.js";
40
40
  import { type GateProfile } from "../hook-gate-profiles.js";
41
+ import { type HookFixture } from "../fixtures/schema.js";
41
42
  /** The id of the deep-test family the command appends under `--deep-test`. */
42
43
  export declare const DEEP_FAMILY_ID = "deep";
43
44
  /** Human title of the deep-test family. */
@@ -102,5 +103,11 @@ export declare function cleanupAllDeepSandboxes(): void;
102
103
  * an empty list — creating no sandbox — when there is nothing to run.
103
104
  */
104
105
  export declare function runDeepGuardTests(context: CheckContext, options?: DeepTestOptions): Promise<CheckResult[]>;
106
+ /**
107
+ * The pure-guard fixtures worth executing: valid (US-007 already reports the
108
+ * invalid, unknown-version and orphan cases), registered, non-empty, and not a
109
+ * side-effecting hook (those are US-009's sandboxed effect tier).
110
+ */
111
+ export declare function selectRunnableFixtures(hqRoot: string): HookFixture[];
105
112
  export {};
106
113
  //# sourceMappingURL=executor.d.ts.map
@@ -173,7 +173,7 @@ export async function runDeepGuardTests(context, options = {}) {
173
173
  * invalid, unknown-version and orphan cases), registered, non-empty, and not a
174
174
  * side-effecting hook (those are US-009's sandboxed effect tier).
175
175
  */
176
- function selectRunnableFixtures(hqRoot) {
176
+ export function selectRunnableFixtures(hqRoot) {
177
177
  const registered = new Set(registeredHookIds(hqRoot));
178
178
  const discovery = discoverFixtures(hqRoot);
179
179
  const runnable = [];
@@ -43,9 +43,7 @@ import { spawnSync } from "node:child_process";
43
43
  import * as fs from "node:fs";
44
44
  import * as os from "node:os";
45
45
  import * as path from "node:path";
46
- import { discoverFixtures, registeredHookIds } from "../fixtures/discover.js";
47
- import { isPureGuard } from "./classify.js";
48
- import { SANDBOX_COPY_RELPATHS } from "./executor.js";
46
+ import { SANDBOX_COPY_RELPATHS, selectRunnableFixtures } from "./executor.js";
49
47
  import { grokCanBlock, grokToSnakePayload, interpretExitBlock, interpretGrokBlock, PARITY_PLATFORMS, toClaudePayload, toCodexPayload, toGrokPayload, } from "../payload-shapes.js";
50
48
  /** The id of the parity family the command appends under `--deep-test`. */
51
49
  export const PARITY_FAMILY_ID = "deep-parity";
@@ -213,30 +211,6 @@ export async function runParityReplay(context, options = {}) {
213
211
  }
214
212
  }
215
213
  }
216
- /**
217
- * The pure-guard fixtures worth replaying: valid, registered, non-empty, and not
218
- * side-effecting (those are US-009's sandboxed effect tier and must never be
219
- * fired through an adapter). Mirrors US-008's executor selection so parity
220
- * replays exactly the set `--deep-test` executes.
221
- */
222
- function selectRunnableFixtures(hqRoot) {
223
- const registered = new Set(registeredHookIds(hqRoot));
224
- const discovery = discoverFixtures(hqRoot);
225
- const runnable = [];
226
- for (const discovered of discovery.fixtures) {
227
- if (discovered.parsed.status !== "ok")
228
- continue;
229
- const fixture = discovered.parsed.fixture;
230
- if (!registered.has(fixture.hookId))
231
- continue;
232
- if (fixture.cases.length === 0)
233
- continue;
234
- if (!isPureGuard(fixture))
235
- continue;
236
- runnable.push(fixture);
237
- }
238
- return runnable;
239
- }
240
214
  /**
241
215
  * Replay one case through all three platforms and classify the aggregate:
242
216
  * - any platform NA (Grok passive event) -> NA, naming the limitation.
@@ -61,7 +61,7 @@ export interface SeedResult {
61
61
  }
62
62
  /** Options for {@link seedSandbox}. */
63
63
  export interface SeedOptions {
64
- /** Tree entries copied from the live tree. Default: {@link SANDBOX_SEED_RELPATHS}. */
64
+ /** Tree entries copied from the live tree. Default: {@link SANDBOX_COPY_RELPATHS}. */
65
65
  seedRelpaths?: readonly string[];
66
66
  /** Which preconditions to seed. Default: {@link KNOWN_PRECONDITIONS}. */
67
67
  preconditions?: readonly Precondition[];
@@ -144,7 +144,7 @@ export declare function discoverSideEffectFixtures(hqRoot: string): SideEffectDi
144
144
  export interface SideEffectTestOptions {
145
145
  /** Per-case time bound. Default: {@link DEFAULT_PER_CASE_TIMEOUT_MS}. */
146
146
  perCaseTimeoutMs?: number;
147
- /** Tree entries copied into each sandbox. Default: {@link SANDBOX_SEED_RELPATHS}. */
147
+ /** Tree entries copied into each sandbox. Default: {@link SANDBOX_COPY_RELPATHS}. */
148
148
  seedRelpaths?: readonly string[];
149
149
  /** Preconditions the sandbox seeds. Default: {@link KNOWN_PRECONDITIONS}. */
150
150
  preconditions?: readonly Precondition[];
@@ -41,8 +41,9 @@ import * as path from "node:path";
41
41
  import * as yaml from "js-yaml";
42
42
  import { isRecord } from "../shared.js";
43
43
  import { classifyCaseStatus, looksLikeFixture, } from "../fixtures/schema.js";
44
- import { HOOK_TESTS_RELDIR, registeredHookIds } from "../fixtures/discover.js";
44
+ import { HOOK_TESTS_RELDIR, NON_FIXTURE_FILES, registeredHookIds, } from "../fixtures/discover.js";
45
45
  import { isSideEffectingHookId } from "./classify.js";
46
+ import { SANDBOX_COPY_RELPATHS } from "./executor.js";
46
47
  import { captureEffectBaseline, describeEffect, defaultGitProbe, evaluateEffects, parseEffectExpectations, } from "./effects.js";
47
48
  /** Default per-case time bound. No latency target, but no case may hang. */
48
49
  export const DEFAULT_PER_CASE_TIMEOUT_MS = 15_000;
@@ -52,25 +53,8 @@ const KNOWN_PRECONDITIONS = [
52
53
  "session-metadata",
53
54
  "company-scaffold",
54
55
  ];
55
- /**
56
- * Tree entries copied from the live tree into every sandbox — the same curated
57
- * set US-008 uses: the hook scripts and gate, the settings a hook may read, the
58
- * Codex/Grok mirrors, and `core/` (helpers hooks source). Missing entries are
59
- * skipped so a partial tree still sandboxes cleanly.
60
- */
61
- const SANDBOX_SEED_RELPATHS = [
62
- ".claude/hooks",
63
- ".claude/settings.json",
64
- ".claude/settings.local.json",
65
- ".codex/hooks",
66
- ".codex/hooks.json",
67
- ".grok",
68
- "core",
69
- ];
70
56
  /** A slug for the throwaway company the `company-scaffold` precondition seeds. */
71
57
  const SANDBOX_COMPANY_SLUG = "sandbox-co";
72
- /** `*.yaml` files under core/hook-tests that are configuration, not fixtures. */
73
- const NON_FIXTURE_FILES = new Set(["allowed-divergence.yaml"]);
74
58
  // --- sandbox lifecycle --------------------------------------------------------
75
59
  const trackedSandboxes = new Set();
76
60
  let sandboxExitHandlerRegistered = false;
@@ -117,7 +101,7 @@ function destroySandbox(root) {
117
101
  */
118
102
  export function seedSandbox(hqRoot, opts = {}) {
119
103
  ensureSandboxExitHandler();
120
- const relpaths = opts.seedRelpaths ?? SANDBOX_SEED_RELPATHS;
104
+ const relpaths = opts.seedRelpaths ?? SANDBOX_COPY_RELPATHS;
121
105
  const intended = new Set(opts.preconditions ?? KNOWN_PRECONDITIONS);
122
106
  const prefix = opts.prefix ?? "hq-doctor-sandbox-";
123
107
  const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), prefix)));
@@ -450,36 +450,67 @@ export function acquireRefreshSpawnLock(hqRoot, nowMs, identity) {
450
450
  const holder = parseSpawnLock(text);
451
451
  if (!holder || !ownerProvenGone(holder, identity))
452
452
  return null;
453
- // Take it over atomically: only the process whose rename succeeds removes
454
- // it. If the renamed file is not the holder we judged (a new holder raced
455
- // in), put it back and give up.
456
- const aside = `${file}.stale-${crypto.randomBytes(6).toString("hex")}`;
453
+ // Remove the dead holder's lock, then retry the O_EXCL create above.
454
+ if (!removeLockIfUnchanged(file, text, token, identity))
455
+ return null;
456
+ }
457
+ return null;
458
+ }
459
+ /**
460
+ * Remove `file` only while it still holds exactly `expected` (a holder judged
461
+ * gone), so that at most one process ever removes a given holder.
462
+ *
463
+ * The remover first creates `<file>.takeover-<hash of expected>` with O_EXCL.
464
+ * Only the process that creates it may remove `file`, and only after reading
465
+ * `expected` there again. A holder's text carries a random token and is never
466
+ * written twice, so once it is removed no later remover can match it: a new
467
+ * holder's lock is never removed by a taker that judged an older one.
468
+ *
469
+ * Returns true when this call removed `expected`. If a remover crashed while
470
+ * holding the claim file, the claim is cleared the same way, one level down,
471
+ * once its own owner is proven gone; this call then returns false and the
472
+ * next acquire can take the lock over.
473
+ */
474
+ function removeLockIfUnchanged(file, expected, token, identity, depth = 0) {
475
+ const digest = crypto.createHash("sha256").update(expected).digest("hex").slice(0, 16);
476
+ const claim = `${file}.takeover-${digest}`;
477
+ try {
478
+ fs.writeFileSync(claim, token, { flag: "wx", mode: 0o600 });
479
+ }
480
+ catch (error) {
481
+ if (error.code !== "EEXIST" || depth >= 2)
482
+ return false;
483
+ // Another process is removing this same holder now, or one crashed while
484
+ // doing so.
485
+ let claimText;
457
486
  try {
458
- fs.renameSync(file, aside);
487
+ claimText = fs.readFileSync(claim, "utf8");
459
488
  }
460
489
  catch {
461
- return null;
490
+ return false;
462
491
  }
463
- let moved = "";
492
+ const claimOwner = parseSpawnLock(claimText);
493
+ if (claimOwner && ownerProvenGone(claimOwner, identity)) {
494
+ removeLockIfUnchanged(claim, claimText, token, identity, depth + 1);
495
+ }
496
+ return false;
497
+ }
498
+ try {
499
+ let current;
464
500
  try {
465
- moved = fs.readFileSync(aside, "utf8");
501
+ current = fs.readFileSync(file, "utf8");
466
502
  }
467
503
  catch {
468
- moved = "";
504
+ current = null;
469
505
  }
470
- if (moved !== text) {
471
- try {
472
- fs.linkSync(aside, file);
473
- }
474
- catch {
475
- // someone already holds it again
476
- }
477
- fs.rmSync(aside, { force: true });
478
- return null;
479
- }
480
- fs.rmSync(aside, { force: true });
506
+ if (current !== expected)
507
+ return false;
508
+ fs.rmSync(file, { force: true });
509
+ return true;
510
+ }
511
+ finally {
512
+ fs.rmSync(claim, { force: true });
481
513
  }
482
- return null;
483
514
  }
484
515
  /** A spawn lock still held after this long is reported by `hq doctor`. */
485
516
  export const REFRESH_SPAWN_LOCK_WARN_MS = 10 * 60 * 1000;
@@ -30,6 +30,8 @@ import { type ParsedFixture } from "./schema.js";
30
30
  export declare const HOOK_TESTS_RELDIR: string;
31
31
  /** checkId of the single coverage-ratio result the report surfaces in its summary. */
32
32
  export declare const FIXTURE_COVERAGE_CHECK_ID = "hooks.fixtures.coverage";
33
+ /** A `*.yaml` file in `core/hook-tests/` that is not a fixture and must be skipped. */
34
+ export declare const NON_FIXTURE_FILES: Set<string>;
33
35
  /**
34
36
  * The hook ids the wiring tier found registered, deduplicated and sorted. A hook
35
37
  * id is the identity a fixture is keyed by: the id passed to `hook-gate.sh` when
@@ -36,7 +36,7 @@ const FIXTURES_FAMILY_ID = "fixtures";
36
36
  /** checkId of the single coverage-ratio result the report surfaces in its summary. */
37
37
  export const FIXTURE_COVERAGE_CHECK_ID = "hooks.fixtures.coverage";
38
38
  /** A `*.yaml` file in `core/hook-tests/` that is not a fixture and must be skipped. */
39
- const NON_FIXTURE_FILES = new Set(["allowed-divergence.yaml"]);
39
+ export const NON_FIXTURE_FILES = new Set(["allowed-divergence.yaml"]);
40
40
  // --- registered-hook enumeration ----------------------------------------------
41
41
  /**
42
42
  * The hook ids the wiring tier found registered, deduplicated and sorted. A hook
@@ -71,7 +71,7 @@ export interface DoctorJsonResult {
71
71
  export interface DoctorJsonDocument {
72
72
  /** Output-contract version. See {@link DOCTOR_JSON_SCHEMA_VERSION}. */
73
73
  schemaVersion: number;
74
- /** The detected agent platform and its evidence (placeholder until US-003). */
74
+ /** The detected agent platform and its evidence. */
75
75
  platform: DoctorPlatform;
76
76
  /** The resolved HQ tree root. */
77
77
  hqRoot: string;
@@ -1,6 +1,5 @@
1
1
  /**
2
- * The doctor engine — an ordered set of check families — and the first family
3
- * (hooks).
2
+ * The doctor engine — an ordered set of check families — and the hooks family.
4
3
  *
5
4
  * The engine is deliberately ignorant of any specific family: `register`
6
5
  * accepts any object implementing {@link CheckFamily}, and `run` iterates them
@@ -8,10 +7,10 @@
8
7
  * added by registering it — never by editing this class — which is exactly the
9
8
  * property US-002 requires and later stories rely on.
10
9
  *
11
- * The hooks family here is intentionally a skeleton: it establishes the family
12
- * so the wiring/parity/runtime checks (US-004+) have somewhere to live, and
13
- * reports only the presence and validity of `.claude/settings.json`. Those
14
- * later stories add per-item results to this family without touching the engine.
10
+ * The hooks family checks `.claude/settings.json` (presence, validity and
11
+ * required command-hook events), Codex and Grok hook wiring, and the runtime
12
+ * probe. The default registry below also registers the other families (hook
13
+ * engine, jq, sync health, integrations, bots, search index and more).
15
14
  */
16
15
  import type { CheckContext, CheckFamily, FamilyRun } from "./types.js";
17
16
  /**
@@ -44,7 +43,7 @@ export declare class DoctorRegistry {
44
43
  /** Run every family in order and collect grouped results. */
45
44
  run(context: CheckContext): Promise<FamilyRun[]>;
46
45
  }
47
- /** The id of the hooks family — the first, and for now only, check family. */
46
+ /** The id of the hooks family, the first family the default registry runs. */
48
47
  export declare const HOOKS_FAMILY_ID = "hooks";
49
48
  /**
50
49
  * The hooks check family. US-002 shipped the skeleton (Claude settings presence