@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,155 @@
1
+ /**
2
+ * Installs a pinned, checksum-verified jq for the daemon's own use when the
3
+ * machine has no working jq (see verified-jq.ts).
4
+ *
5
+ * Unix copies go to ~/.hq/daemon/tools/<version>/jq, outside the shell PATH.
6
+ * Windows shares ~/.local/bin/jq.exe with the global hook installer and doctor.
7
+ * Both paths use the same pinned download and safe staging implementation.
8
+ *
9
+ * Binaries and checksums are jqlang/jq's official release (sha256sum.txt of
10
+ * jq-1.8.2); the macOS values match the desktop app's pinned ones.
11
+ */
12
+ import * as path from "node:path";
13
+ import { installPinnedJq, matchesPinnedJq, UnsafeJqPathError } from "../jq/install.js";
14
+ import { windowsJqAsset, windowsJqPath } from "../windows/jq.js";
15
+ import { JqUnavailableError, VETTED_JQ_PATHS, probeJq, resolveVerifiedJq, } from "./verified-jq.js";
16
+ export const MANAGED_JQ_VERSION = "jq-1.8.2";
17
+ const MANAGED_JQ_ASSETS = {
18
+ "darwin-arm64": { asset: "jq-macos-arm64", sha256: "2d75340ba57a4b4b4c8708a21c2dc8e958a48aaa8bba13b27f77f6e4c0eca07e" },
19
+ "darwin-x64": { asset: "jq-macos-amd64", sha256: "e94b266e3c26690550006abe63152b782280f4e14374accdf04cbde844f00bc0" },
20
+ "linux-arm64": { asset: "jq-linux-arm64", sha256: "8b85c817833814ddca00a144c33705546355afccf0cf39b188f3cdb48b852309" },
21
+ "linux-x64": { asset: "jq-linux-amd64", sha256: "b1c22172dd303f3be49e935aa56aa48a8b7a46e0bc838b4997d3bb451495870f" },
22
+ };
23
+ /** Where the daemon keeps its own jq, or null on a platform it does not provision. */
24
+ export function managedJqPath(home, platform = process.platform) {
25
+ if (!home)
26
+ return null;
27
+ if (platform === "win32")
28
+ return windowsJqPath(home);
29
+ return path.posix.join(home, ".hq", "daemon", "tools", MANAGED_JQ_VERSION, "jq");
30
+ }
31
+ export function managedJqAsset(platform, arch) {
32
+ if (platform === "win32")
33
+ return windowsJqAsset(arch);
34
+ const entry = MANAGED_JQ_ASSETS[`${platform}-${arch}`];
35
+ if (!entry)
36
+ return null;
37
+ return { url: `https://github.com/jqlang/jq/releases/download/${MANAGED_JQ_VERSION}/${entry.asset}`, sha256: entry.sha256 };
38
+ }
39
+ /** After a failed install, how long callers get that failure before the next try. */
40
+ const RETRY_AFTER_FAILURE_MS = 10 * 60_000;
41
+ const provisions = new Map();
42
+ /** For tests. */
43
+ export function resetJqProvision() {
44
+ provisions.clear();
45
+ }
46
+ /**
47
+ * Install the managed jq. Concurrent callers share one install, and after a
48
+ * failure (offline, say) callers get that failure for ten minutes instead of
49
+ * starting a download per policy check.
50
+ */
51
+ export function provisionManagedJq(deps, now = Date.now) {
52
+ const platform = deps.platform ?? process.platform;
53
+ const asset = deps.asset ?? managedJqAsset(platform, deps.arch ?? process.arch);
54
+ const key = JSON.stringify([managedJqPath(deps.home, platform), asset]);
55
+ const state = provisions.get(key) ?? {};
56
+ provisions.set(key, state);
57
+ if (state.inFlight)
58
+ return state.inFlight;
59
+ if (state.failure && now() - state.failure.at < RETRY_AFTER_FAILURE_MS)
60
+ return Promise.resolve(state.failure.result);
61
+ state.inFlight = installManagedJq(deps)
62
+ .catch((err) => ({ ok: false, reason: `could not install jq: ${err.message}` }))
63
+ .then((result) => {
64
+ state.failure = result.ok ? undefined : { at: now(), result };
65
+ return result;
66
+ })
67
+ .finally(() => {
68
+ state.inFlight = undefined;
69
+ if (!state.failure && provisions.get(key) === state)
70
+ provisions.delete(key);
71
+ });
72
+ return state.inFlight;
73
+ }
74
+ /**
75
+ * The jq policy checks run with: the daemon's own managed copy or another jq
76
+ * that passes the probe; when there is none, install the managed copy (waiting
77
+ * up to `waitMs`) and look again. Throws JqUnavailableError when that fails or
78
+ * is still running, so the caller fails closed.
79
+ */
80
+ export async function resolveOrProvisionJq(deps) {
81
+ const platform = deps.platform ?? process.platform;
82
+ const home = platform === "win32" ? deps.env.USERPROFILE ?? deps.env.HOME : deps.env.HOME;
83
+ const managed = managedJqPath(home, platform);
84
+ const asset = deps.provision?.asset ?? managedJqAsset(platform, deps.provision?.arch ?? process.arch);
85
+ let trustedManaged = false;
86
+ let managedRefusal;
87
+ if (managed && asset) {
88
+ try {
89
+ trustedManaged = matchesPinnedJq(home, managed, asset);
90
+ }
91
+ catch (error) {
92
+ if (!(error instanceof UnsafeJqPathError))
93
+ throw new JqUnavailableError([], error.message);
94
+ managedRefusal = error;
95
+ }
96
+ }
97
+ const vettedPaths = [...(trustedManaged && managed ? [managed] : []), ...(deps.vettedPaths ?? VETTED_JQ_PATHS)];
98
+ const resolveDeps = {
99
+ ...deps, vettedPaths,
100
+ rejectedPaths: [...(deps.rejectedPaths ?? []), ...(!trustedManaged && managed ? [managed] : [])],
101
+ rejectedLocations: [...(deps.rejectedLocations ?? []), ...(managedRefusal ? [managedRefusal.path] : [])],
102
+ };
103
+ try {
104
+ return await resolveVerifiedJq(resolveDeps);
105
+ }
106
+ catch (err) {
107
+ if (!(err instanceof JqUnavailableError) || !managed)
108
+ throw err;
109
+ // An unsafe managed location must not prevent using a vetted system jq,
110
+ // but installing into that same location cannot repair its trust boundary.
111
+ if (managedRefusal) {
112
+ throw new JqUnavailableError([...err.rejected, { path: managed, reason: managedRefusal.message }]);
113
+ }
114
+ const pending = provisionManagedJq({ home, platform, run: deps.run, ...deps.provision });
115
+ let timer;
116
+ const waited = await Promise.race([
117
+ pending,
118
+ new Promise((resolve) => {
119
+ timer = setTimeout(() => resolve(null), deps.waitMs ?? 5_000);
120
+ }),
121
+ ]).finally(() => clearTimeout(timer));
122
+ if (waited?.ok)
123
+ return await resolveVerifiedJq({
124
+ ...resolveDeps, vettedPaths: [managed, ...vettedPaths], rejectedPaths: deps.rejectedPaths,
125
+ });
126
+ throw new JqUnavailableError(err.rejected, waited
127
+ ? `HQ tried to install a verified jq and could not (${waited.reason}); it tries again in a few minutes.`
128
+ : "HQ is installing a verified jq now; try again in a minute.");
129
+ }
130
+ }
131
+ async function installManagedJq(deps) {
132
+ const platform = deps.platform ?? process.platform;
133
+ const log = deps.log ?? (() => { });
134
+ const target = managedJqPath(deps.home, platform);
135
+ const asset = deps.asset ?? managedJqAsset(platform, deps.arch ?? process.arch);
136
+ if (!target || !asset)
137
+ return { ok: false, reason: `HQ has no jq download for ${platform}-${deps.arch ?? process.arch}` };
138
+ try {
139
+ log(`jq: provisioning ${MANAGED_JQ_VERSION} from ${asset.url}`);
140
+ await installPinnedJq({
141
+ home: deps.home, target, asset, fetch: deps.fetch,
142
+ verify: async (file) => {
143
+ const probe = await probeJq(file, deps.run);
144
+ if (!probe.ok)
145
+ throw new Error(`downloaded jq did not pass its check: ${probe.reason}`);
146
+ },
147
+ });
148
+ log(`jq: installed ${MANAGED_JQ_VERSION} at ${target}`);
149
+ return { ok: true, path: target };
150
+ }
151
+ catch (error) {
152
+ return { ok: false, reason: error.message };
153
+ }
154
+ }
155
+ //# sourceMappingURL=jq-provision.js.map
@@ -22,9 +22,9 @@
22
22
  *
23
23
  * The paths below mirror `LANES_STORE_REL`, `LANE_RECORDS_DIR`,
24
24
  * `QUESTION_RECORDS_DIR` (lanes/store.ts), `LANES_CONFIG_REL` (lanes/config.ts)
25
- * and `LEAD_REGISTRY_REL` (lanes/autopilot-registry.ts). They are copied, not
26
- * imported, so the daemon does not load the lanes modules; a test pins them to
27
- * the originals.
25
+ * and `LEAD_REGISTRY_REL` (lanes/autopilot-registry.ts), and `KNOWN_LANE_STATES`
26
+ * mirrors `LANE_STATES` (lanes/types.ts). They are copied, not imported, so the
27
+ * daemon does not load the lanes modules; a test pins them to the originals.
28
28
  */
29
29
  import type { UnitPlan } from "./catalog.js";
30
30
  export type LanesReconcileVerdict = "spawn" | "idle" | "skip";
@@ -33,6 +33,7 @@ export declare const LANE_RECORDS_SUBDIR = "lanes";
33
33
  export declare const QUESTION_RECORDS_SUBDIR = "questions";
34
34
  export declare const LANES_CONFIG_FILE: string;
35
35
  export declare const LEAD_REGISTRY_FILE: string;
36
+ export declare const KNOWN_LANE_STATES: ReadonlySet<string>;
36
37
  export interface LanesReconcileGuardFs {
37
38
  readdirSync: (dir: string) => string[];
38
39
  readFileSync: (file: string, encoding: "utf8") => string;
@@ -22,9 +22,9 @@
22
22
  *
23
23
  * The paths below mirror `LANES_STORE_REL`, `LANE_RECORDS_DIR`,
24
24
  * `QUESTION_RECORDS_DIR` (lanes/store.ts), `LANES_CONFIG_REL` (lanes/config.ts)
25
- * and `LEAD_REGISTRY_REL` (lanes/autopilot-registry.ts). They are copied, not
26
- * imported, so the daemon does not load the lanes modules; a test pins them to
27
- * the originals.
25
+ * and `LEAD_REGISTRY_REL` (lanes/autopilot-registry.ts), and `KNOWN_LANE_STATES`
26
+ * mirrors `LANE_STATES` (lanes/types.ts). They are copied, not imported, so the
27
+ * daemon does not load the lanes modules; a test pins them to the originals.
28
28
  */
29
29
  import * as fs from "node:fs";
30
30
  import * as path from "node:path";
@@ -39,7 +39,7 @@ export const LEAD_REGISTRY_FILE = path.join("workspace", "lane-briefs", "juniors
39
39
  * keep-alive, which is checked separately.
40
40
  */
41
41
  const QUIET_LANE_STATES = new Set(["done", "failed", "interrupted", "cancelled", "killed", "blocked"]);
42
- const KNOWN_LANE_STATES = new Set([
42
+ export const KNOWN_LANE_STATES = new Set([
43
43
  "queued", "running", "awaiting_input", "blocked", "done", "failed", "interrupted", "cancelled", "killed",
44
44
  ]);
45
45
  const realFs = {
@@ -8,6 +8,10 @@ export interface MeshOwnerDeps {
8
8
  hosted?: (paths: ReturnType<typeof daemonPaths>) => boolean;
9
9
  }
10
10
  export declare function meshOwnerHere(home: string, env: NodeJS.ProcessEnv, deps?: MeshOwnerDeps): MeshOwner;
11
+ export declare function hqDaemonMeshService(home: string, env?: NodeJS.ProcessEnv, alive?: (pid: number) => boolean): {
12
+ daemonPid: number;
13
+ pid?: number;
14
+ } | null;
11
15
  export interface HqDaemonUnitRepair {
12
16
  repaired: boolean;
13
17
  action?: "replaced" | "removed";
@@ -30,6 +30,26 @@ export function meshOwnerHere(home, env, deps = {}) {
30
30
  }).type;
31
31
  return enabledServices(machineType, config, { engineVaults: engineVaultCount(home) }).includes("mesh") ? "hq-daemon" : "hq-daemon-mesh-off";
32
32
  }
33
+ export function hqDaemonMeshService(home, env = process.env, alive) {
34
+ const paths = daemonPaths(home, env);
35
+ const daemonPid = runningDaemonPid(paths.lockPath, alive);
36
+ if (daemonPid === null)
37
+ return null;
38
+ let state;
39
+ try {
40
+ state = JSON.parse(fs.readFileSync(paths.statePath, "utf8"));
41
+ }
42
+ catch {
43
+ return null;
44
+ }
45
+ if (!state || state.pid !== daemonPid || !Array.isArray(state.units))
46
+ return null;
47
+ const mesh = state.units
48
+ .find((unit) => unit?.id === "mesh");
49
+ if (!mesh || mesh.status !== "running")
50
+ return null;
51
+ return { daemonPid, ...(typeof mesh.pid === "number" ? { pid: mesh.pid } : {}) };
52
+ }
33
53
  function daemonRunsElsewhere(home, env) {
34
54
  const paths = daemonPaths(home, env);
35
55
  return hostedDaemonRunning(paths) || recentlyHostedDaemon(paths) || runningDaemonPid(paths.lockPath) !== null;
@@ -17,6 +17,7 @@
17
17
  * stream that starts asynchronously, so a change made right after a rebuild
18
18
  * re-arms the watchers is never reported.
19
19
  */
20
+ import { type ResolveJqDeps, type VerifiedJq } from "../verified-jq.js";
20
21
  export declare const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
21
22
  export declare const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
22
23
  export declare class PolicyOpError extends Error {
@@ -75,6 +76,8 @@ export interface PolicyCheckDeps {
75
76
  env?: NodeJS.ProcessEnv;
76
77
  now?: () => Date;
77
78
  timeoutMs?: number;
79
+ /** Finds the jq the hook scripts run with. Defaults to resolveOrProvisionJq. */
80
+ resolveJq?: (deps: ResolveJqDeps) => Promise<VerifiedJq>;
78
81
  }
79
82
  export declare function policyCheck(args: PolicyCheckArgs, deps: PolicyCheckDeps): Promise<PolicyCheckResult>;
80
83
  //# sourceMappingURL=policy.d.ts.map
@@ -22,6 +22,8 @@ import * as fs from "node:fs";
22
22
  import * as path from "node:path";
23
23
  import { isPendingManifestCompany, sessionMetaCompanies } from "../../core-utils/session-company.js";
24
24
  import { withoutHookEnv } from "../hook-env.js";
25
+ import { JqUnavailableError, withJqFirst } from "../verified-jq.js";
26
+ import { resolveOrProvisionJq } from "../jq-provision.js";
25
27
  export const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
26
28
  export const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
27
29
  const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
@@ -372,19 +374,45 @@ async function policyCheckUnmapped(args, deps) {
372
374
  });
373
375
  // Identity reaches the hook scripts through the payload above and nowhere
374
376
  // else. They trust HQ_HOOK_* over the payload, so nothing with that prefix
375
- // may pass from the daemon's environment (see ../hook-env.ts).
377
+ // may pass from the daemon's environment (see ../hook-env.ts). The one
378
+ // exception is the caller's agent identity, which is set and empty: this
379
+ // path never carries agent fields, so every check is a main-thread check,
380
+ // and the authorizer takes its environment branch instead of reading the
381
+ // agent fields out of the payload with jq.
382
+ const baseEnv = withoutHookEnv(deps.env ?? process.env);
383
+ const reasons = [];
384
+ const policies = () => ({ count: deps.index.list(args.company).length, version: deps.index.version });
385
+ // The hook scripts parse the payload with the first `jq` on PATH. A stand-in
386
+ // there can make the authorizer block every call or allow calls into another
387
+ // company, so they run only with a jq that passed ../verified-jq.ts.
388
+ let jq;
389
+ try {
390
+ jq = await (deps.resolveJq ?? resolveOrProvisionJq)({ env: baseEnv });
391
+ }
392
+ catch (err) {
393
+ const why = err instanceof JqUnavailableError ? err.message : `HQ could not run the company access check, so it is blocking this call: ${err.message}`;
394
+ reasons.push(why);
395
+ return {
396
+ decision: event === "PreToolUse" ? "block" : "allow",
397
+ reasons,
398
+ additionalContext: "",
399
+ session,
400
+ policies: policies(),
401
+ };
402
+ }
376
403
  const env = {
377
- ...withoutHookEnv(deps.env ?? process.env),
404
+ ...withJqFirst(baseEnv, jq.binDir),
378
405
  HQ_ROOT: hqRoot,
379
406
  CLAUDE_PROJECT_DIR: hqRoot,
380
407
  BASH_ENV: "/dev/null",
408
+ HQ_HOOK_AGENT_ID: "",
409
+ HQ_HOOK_AGENT_TYPE: "",
381
410
  };
382
411
  if (args.company === undefined)
383
412
  delete env.HQ_POLICY_COMPANY;
384
413
  else
385
414
  env.HQ_POLICY_COMPANY = args.company;
386
415
  const timeoutMs = deps.timeoutMs ?? 15_000;
387
- const reasons = [];
388
416
  let decision = "allow";
389
417
  if (event === "PreToolUse") {
390
418
  const r = await runScript(authorizer, payload, env, hqRoot, timeoutMs);
@@ -418,7 +446,7 @@ async function policyCheckUnmapped(args, deps) {
418
446
  reasons,
419
447
  additionalContext,
420
448
  session,
421
- policies: { count: deps.index.list(args.company).length, version: deps.index.version },
449
+ policies: policies(),
422
450
  };
423
451
  }
424
452
  //# sourceMappingURL=policy.js.map
@@ -6,7 +6,8 @@
6
6
  * signing in takes effect without restarting the daemon.
7
7
  */
8
8
  import { acquirePackageUseLease } from "../../utils/package-use-lease.js";
9
- import { type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
9
+ import { type PlanFleetBotsDeps } from "../bot/fleet-daemon.js";
10
+ import { type FleetBotPlan, type LegacySyncHolder, type PlanContext, type ServiceName, type UnitPlan } from "./catalog.js";
10
11
  import { type LegacyHandover } from "./legacy-handover.js";
11
12
  import { type SyncCoreVaultPlan } from "../sync-core/engine-home.js";
12
13
  import { type DaemonFlagRegistryRead, type DaemonFlagSnapshotSource } from "./flag.js";
@@ -143,6 +144,21 @@ export declare function daemonInstantSyncEnabled(env: NodeJS.ProcessEnv, configu
143
144
  * background service, so it is not one of them.
144
145
  */
145
146
  export declare function listLocalBots(root?: string): string[];
147
+ /** The plan's bots. A signed-in pass also lets held bots whose move HQ cancelled
148
+ * free themselves, in the background and rate-limited per bot.
149
+ */
150
+ export declare function daemonBotPlans(input: {
151
+ heldBots: {
152
+ kick(): Promise<void>;
153
+ };
154
+ signedIn: boolean;
155
+ services: readonly ServiceName[];
156
+ fleet: PlanFleetBotsDeps;
157
+ root?: string;
158
+ }): {
159
+ bots: string[];
160
+ fleetBots: FleetBotPlan[];
161
+ };
146
162
  /** Whose task `taskName` is: only the current user's own task may be taken over. */
147
163
  export declare function windowsTaskOwner(taskName: string): WindowsTaskOwner;
148
164
  export declare function probeLegacyUnits(platform: NodeJS.Platform, home: string): LegacyUnit[];
@@ -23,6 +23,7 @@ import { isLocalDependencyInstall, resolveRunningInstall } from "../../utils/ver
23
23
  import { agentKitPaths } from "../agent-kit/paths.js";
24
24
  import { HQ_FLEET_RUNTIME_ENGINE_ID, readBotConfig } from "../bot/config.js";
25
25
  import { clearStaleReadyBeforeGatewayStart, planFleetBots } from "../bot/fleet-daemon.js";
26
+ import { createHeldBotReconciler, heldBotThrottleDir } from "../bot/promotion-hold-reconcile.js";
26
27
  import { botsRoot } from "../bot/paths.js";
27
28
  import { CLAUDE_RUNNER_SCRIPT, CODEX_RUNNER_SCRIPT, enabledServices, planUnits, SEARCH_INDEX_WORKER_UNAVAILABLE, isLegacyRestartWait } from "./catalog.js";
28
29
  import { createLegacyHandover, LEGACY_HANDOVER_STUCK_FILE, writeLegacyHandoverStuck } from "./legacy-handover.js";
@@ -70,7 +71,7 @@ import { createHqdRuntimeEvents, observeHqdRuntimeFlag, startHqdRuntimeListener
70
71
  import { heartbeatFile, startHeartbeat } from "./heartbeat.js";
71
72
  import { daemonStartEnv } from "./hook-env.js";
72
73
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
73
- import { takeControlRequests } from "./requests.js";
74
+ import { takeControlRequests, writeControlRequest } from "./requests.js";
74
75
  import { currentHqCloud, currentHqCloudAfterLeaseRelease, hqCloudRunners, hqCloudVersionOlder } from "./hq-cloud.js";
75
76
  import { stageSyncRunnerBundle } from "./sync-runner-bundle.js";
76
77
  import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
@@ -553,6 +554,14 @@ export function listLocalBots(root = botsRoot()) {
553
554
  .map((d) => d.name)
554
555
  .sort();
555
556
  }
557
+ /** The plan's bots. A signed-in pass also lets held bots whose move HQ cancelled
558
+ * free themselves, in the background and rate-limited per bot.
559
+ */
560
+ export function daemonBotPlans(input) {
561
+ if (input.signedIn && input.services.includes("bots"))
562
+ void input.heldBots.kick();
563
+ return { bots: listLocalBots(input.root), fleetBots: planFleetBots(input.fleet) };
564
+ }
556
565
  /** Whose task `taskName` is: only the current user's own task may be taken over. */
557
566
  export function windowsTaskOwner(taskName) {
558
567
  const run = (cmd, args) => {
@@ -863,6 +872,13 @@ export async function runDaemon(opts) {
863
872
  const paths = daemonPaths(home, env);
864
873
  ensurePrivateDir(paths.syncPassRequestsDir);
865
874
  const log = makeLogger(paths, opts.foreground === true);
875
+ const heldBots = createHeldBotReconciler({
876
+ root: botsRoot(home, env),
877
+ platform,
878
+ throttle: { dir: heldBotThrottleDir(paths.root) },
879
+ requestStart: (unit) => { writeControlRequest(paths.requestsDir, { action: "restart", unit }); },
880
+ log,
881
+ });
866
882
  const syncRunnerBundleDirectory = opts.syncRunnerBundleDirectory ?? path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../hq-cloud-sync-runner");
867
883
  const cliPackageRoot = opts.cliPackageRoot === undefined ? resolveRunningInstall().packageRoot : opts.cliPackageRoot;
868
884
  const cliPackagePrefix = opts.cliPackagePrefix === undefined
@@ -1616,8 +1632,12 @@ export async function runDaemon(opts) {
1616
1632
  syncOwner === "daemon" && services.includes("sync") && !config.syncPaused &&
1617
1633
  !appManagesSync && Boolean(hqRoot && isSignedIn && runners.syncRunner),
1618
1634
  syncHeartbeatTimeoutMs: syncHeartbeatTimeoutMs(env),
1619
- bots: listLocalBots(),
1620
- fleetBots: planFleetBots({ platform, home, env, log: (message) => log("info", message) }),
1635
+ ...daemonBotPlans({
1636
+ heldBots,
1637
+ signedIn: isSignedIn,
1638
+ services,
1639
+ fleet: { platform, home, env, log: (message) => log("info", message) },
1640
+ }),
1621
1641
  legacyOwner: legacyOwnerLookup(legacy),
1622
1642
  cliSelfUpdatable: updatable,
1623
1643
  claudePath: findUserBinary("claude", env, home),
@@ -1954,6 +1974,7 @@ export async function runDaemon(opts) {
1954
1974
  socketPath: hqdSocketPath(home, env),
1955
1975
  registryPath: registryFile(registryDir(home, env)),
1956
1976
  hqRoot,
1977
+ warmJq: true,
1957
1978
  log,
1958
1979
  flagSnapshots,
1959
1980
  onRuntimeChange: () => hqdRuntimeEvents.emit(),
@@ -30,6 +30,12 @@ export interface HqdServerOptions {
30
30
  /** registry.json to resolve against (US-004). */
31
31
  registryPath?: string;
32
32
  hqRoot?: string;
33
+ /**
34
+ * Find (or install) the jq policy checks run with as soon as the server
35
+ * starts, so the first check does not wait for it. Off by default; the
36
+ * daemon turns it on.
37
+ */
38
+ warmJq?: boolean;
33
39
  version?: string;
34
40
  now?: () => Date;
35
41
  /** Called when the Windows named-pipe helper fails and hqd must stop. */
@@ -20,6 +20,8 @@ import { sessionMetaCompanies } from "../core-utils/session-company.js";
20
20
  import { journalAppend, JournalOpError } from "./ops/journal.js";
21
21
  import { parseSkillCommandArgs, runSkillCommand, SkillCommandOpError } from "./ops/skill-command.js";
22
22
  import { PolicyIndex, PolicyOpError, policyCheck } from "./ops/policy.js";
23
+ import { withoutHookEnv } from "./hook-env.js";
24
+ import { resolveOrProvisionJq } from "./jq-provision.js";
23
25
  import { defaultMcpToken, HqMcpBridge, jsonResult, McpOpError, runWorker } from "./ops/mcp.js";
24
26
  import { authenticateMachineCredentials, machineTokenExpiresAt, MachineLoginError, parseStdinMachineCredentials } from "./machine-login.js";
25
27
  import { HQ_MCP_TOOL_NAMES, HQD_NATIVE_TOOL_NAMES } from "../mcp/tools.js";
@@ -315,6 +317,9 @@ export async function startHqdServer(opts) {
315
317
  const clock = opts.now ?? (() => new Date());
316
318
  const env = opts.env ?? process.env;
317
319
  const policyIndex = opts.hqRoot ? new PolicyIndex(opts.hqRoot, log) : null;
320
+ if (opts.hqRoot && opts.warmJq) {
321
+ resolveOrProvisionJq({ env: withoutHookEnv(env), waitMs: 180_000, provision: { log: (line) => log("info", line) } }).then((jq) => log("info", `policy checks run with ${jq.version} at ${jq.realPath}`), (err) => log("warn", `policy checks have no working jq yet: ${err.message}`));
322
+ }
318
323
  let ephemeralMachineToken;
319
324
  let flagRevocationGeneration = 0;
320
325
  const requireRoot = () => {
@@ -0,0 +1,96 @@
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
+ export declare const JQ_VERSION_RE: RegExp;
24
+ /** Input, filter and exact output of the behavior probe. */
25
+ export declare const JQ_BEHAVIOR_PROBE: {
26
+ readonly input: "{\"a\":null,\"b\":\"x\",\"c\":[1,2],\"d\":{\"e\":\"f\"}}";
27
+ readonly filter: "(if .a == null then \"\" else .a end) + \"|\" + (.b | ascii_upcase) + \"|\" + (.c | map(. * 2 | tostring) | join(\",\")) + \"|\" + (.d | to_entries | map(.key + \"=\" + .value) | join(\";\"))";
28
+ readonly expected: "|X|2,4|e=f";
29
+ };
30
+ export interface JqProbe {
31
+ ok: boolean;
32
+ version: string | null;
33
+ /** Why the candidate was refused, in plain words. Empty when ok. */
34
+ reason: string;
35
+ }
36
+ export interface VerifiedJq {
37
+ /** The candidate as found (for example /opt/homebrew/bin/jq). */
38
+ path: string;
39
+ /** What that resolves to on disk. */
40
+ realPath: string;
41
+ version: string;
42
+ /** A folder to put first on PATH; its `jq` is this binary. */
43
+ binDir: string;
44
+ }
45
+ export interface JqRejection {
46
+ path: string;
47
+ reason: string;
48
+ }
49
+ export declare class JqUnavailableError extends Error {
50
+ readonly rejected: JqRejection[];
51
+ readonly note?: string | undefined;
52
+ constructor(rejected: JqRejection[], note?: string | undefined);
53
+ }
54
+ /** The plain-language reason a policy check gives when no jq qualifies. */
55
+ export declare function describeJqUnavailable(rejected: JqRejection[], note?: string): string;
56
+ export type JqRunner = (file: string, args: string[], input: string | null, timeoutMs: number) => Promise<{
57
+ code: number | null;
58
+ stdout: string;
59
+ timedOut: boolean;
60
+ error?: string;
61
+ }>;
62
+ /** Run `file args` with no shell, a small clean environment and a hard timeout. */
63
+ export declare const runJq: JqRunner;
64
+ /** Whether `file` is real jq: `--version` says jq-1.x and a known filter computes correctly. */
65
+ export declare function probeJq(file: string, run?: JqRunner, timeoutMs?: number): Promise<JqProbe>;
66
+ /**
67
+ * Where to look, best first. Folders the user's own tools cannot shadow come
68
+ * first (Apple's /usr/bin/jq on macOS 15+, then Homebrew and /usr/local), then
69
+ * every PATH entry in order. Every candidate is probed regardless.
70
+ */
71
+ export declare const VETTED_JQ_PATHS: readonly string[];
72
+ export declare function jqCandidates(env: NodeJS.ProcessEnv, platform?: NodeJS.Platform, vettedPaths?: readonly string[]): string[];
73
+ export interface ResolveJqDeps {
74
+ env: NodeJS.ProcessEnv;
75
+ /** Folder for the private `jq` link. Defaults to ~/.hq/daemon/verified-bin. */
76
+ binDir?: string;
77
+ platform?: NodeJS.Platform;
78
+ run?: JqRunner;
79
+ timeoutMs?: number;
80
+ /** Checked before PATH. Defaults to VETTED_JQ_PATHS. */
81
+ vettedPaths?: readonly string[];
82
+ /** Managed files which failed their checksum or path safety checks, including aliases. */
83
+ rejectedPaths?: readonly string[];
84
+ /** Refused locations: exclude their whole subtree, including realpath aliases. */
85
+ rejectedLocations?: readonly string[];
86
+ }
87
+ /** For tests. */
88
+ export declare function clearJqProbeCache(): void;
89
+ /**
90
+ * The first candidate that passes probeJq. Throws JqUnavailableError, listing
91
+ * what was refused and why, when none does.
92
+ */
93
+ export declare function resolveVerifiedJq(deps: ResolveJqDeps): Promise<VerifiedJq>;
94
+ /** `env` with `binDir` first on PATH. */
95
+ export declare function withJqFirst(env: NodeJS.ProcessEnv, binDir: string, platform?: NodeJS.Platform): NodeJS.ProcessEnv;
96
+ //# sourceMappingURL=verified-jq.d.ts.map