@indigoai-us/hq-cli 5.345.238 → 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 (106) hide show
  1. package/CHANGELOG.md +25 -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/cloud-off-gate.d.ts +2 -1
  10. package/dist/commands/cloud-off-gate.js +17 -4
  11. package/dist/commands/cloud.d.ts +17 -2
  12. package/dist/commands/cloud.js +126 -24
  13. package/dist/commands/core-delegate-w1b.js +35 -10
  14. package/dist/commands/core-delegate.d.ts +2 -1
  15. package/dist/commands/core-delegate.js +207 -48
  16. package/dist/commands/deploy-comments.js +8 -2
  17. package/dist/commands/deploy-events.d.ts +40 -0
  18. package/dist/commands/deploy-events.js +300 -0
  19. package/dist/commands/doctor.d.ts +4 -4
  20. package/dist/commands/doctor.js +2 -2
  21. package/dist/commands/feedback.js +2 -3
  22. package/dist/commands/keyed-sync-pull.d.ts +12 -0
  23. package/dist/commands/keyed-sync-pull.js +151 -0
  24. package/dist/commands/library-add.d.ts +5 -2
  25. package/dist/commands/library-add.js +22 -9
  26. package/dist/commands/mcp-registration.d.ts +4 -18
  27. package/dist/commands/mcp-registration.js +9 -29
  28. package/dist/commands/mesh.d.ts +4 -0
  29. package/dist/commands/mesh.js +25 -5
  30. package/dist/commands/pack-install.d.ts +2 -3
  31. package/dist/commands/pack-install.js +6 -8
  32. package/dist/commands/secrets.d.ts +3 -4
  33. package/dist/commands/secrets.js +3 -20
  34. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +307 -232
  35. package/dist/hq-cloud-sync-runner/package.json +1 -1
  36. package/dist/lib/bot/api.d.ts +2 -1
  37. package/dist/lib/bot/api.js +2 -15
  38. package/dist/lib/capacity/collectors/claude-oauth.d.ts +0 -2
  39. package/dist/lib/capacity/collectors/claude-oauth.js +0 -5
  40. package/dist/lib/core-utils/delegate-helper-paths.d.ts +26 -0
  41. package/dist/lib/core-utils/delegate-helper-paths.js +33 -0
  42. package/dist/lib/daemon/jq-provision.d.ts +63 -0
  43. package/dist/lib/daemon/jq-provision.js +155 -0
  44. package/dist/lib/daemon/lanes-reconcile-guard.d.ts +4 -3
  45. package/dist/lib/daemon/lanes-reconcile-guard.js +4 -4
  46. package/dist/lib/daemon/mesh-owner.d.ts +4 -0
  47. package/dist/lib/daemon/mesh-owner.js +20 -0
  48. package/dist/lib/daemon/ops/policy.d.ts +3 -0
  49. package/dist/lib/daemon/ops/policy.js +32 -4
  50. package/dist/lib/daemon/run.js +1 -0
  51. package/dist/lib/daemon/server.d.ts +6 -0
  52. package/dist/lib/daemon/server.js +5 -0
  53. package/dist/lib/daemon/verified-jq.d.ts +96 -0
  54. package/dist/lib/daemon/verified-jq.js +337 -0
  55. package/dist/lib/doctor/checks/jq.js +16 -0
  56. package/dist/lib/doctor/deep/executor.d.ts +7 -0
  57. package/dist/lib/doctor/deep/executor.js +1 -1
  58. package/dist/lib/doctor/deep/parity.js +1 -27
  59. package/dist/lib/doctor/deep/sandbox.d.ts +2 -2
  60. package/dist/lib/doctor/deep/sandbox.js +3 -19
  61. package/dist/lib/doctor/fix/refresh-sync-handoff.js +52 -21
  62. package/dist/lib/doctor/fixtures/discover.d.ts +2 -0
  63. package/dist/lib/doctor/fixtures/discover.js +1 -1
  64. package/dist/lib/doctor/json-output.d.ts +1 -1
  65. package/dist/lib/doctor/registry.d.ts +6 -7
  66. package/dist/lib/doctor/registry.js +6 -7
  67. package/dist/lib/doctor/report.d.ts +9 -10
  68. package/dist/lib/doctor/report.js +4 -4
  69. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  70. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  71. package/dist/lib/jq/install.d.ts +27 -0
  72. package/dist/lib/jq/install.js +156 -0
  73. package/dist/lib/lanes/outpost-dispatch.d.ts +1 -1
  74. package/dist/lib/lanes/outpost-dispatch.js +13 -13
  75. package/dist/lib/lanes/outpost-pruner-install.js +1 -1
  76. package/dist/lib/mesh/live/daemon/doctor.js +7 -1
  77. package/dist/lib/mesh/live/daemon/install.d.ts +4 -0
  78. package/dist/lib/mesh/live/daemon/install.js +10 -0
  79. package/dist/lib/mesh/live/daemon/run.js +17 -0
  80. package/dist/lib/mesh/live/emit-retry.d.ts +20 -2
  81. package/dist/lib/mesh/live/emit-retry.js +57 -4
  82. package/dist/lib/mesh/live/emit.js +25 -4
  83. package/dist/lib/mesh/live/flush.d.ts +2 -0
  84. package/dist/lib/mesh/live/flush.js +21 -8
  85. package/dist/lib/mesh/live/spool.d.ts +9 -1
  86. package/dist/lib/mesh/live/spool.js +41 -29
  87. package/dist/lib/sync-core/rollout-state.d.ts +9 -1
  88. package/dist/lib/sync-core/rollout-state.js +34 -4
  89. package/dist/lib/windows/jq.d.ts +4 -0
  90. package/dist/lib/windows/jq.js +10 -39
  91. package/dist/lib/workers-registry/index.js +7 -11
  92. package/dist/utils/callback-port-busy.d.ts +2 -2
  93. package/dist/utils/callback-port-busy.js +2 -2
  94. package/dist/utils/cli-network-lifecycle.js +1 -0
  95. package/dist/utils/client-health-contract.d.ts +2 -0
  96. package/dist/utils/client-health-contract.js +1 -1
  97. package/dist/utils/client-health.js +1 -9
  98. package/dist/utils/cognito-config.js +5 -0
  99. package/dist/utils/cognito-session.d.ts +4 -6
  100. package/dist/utils/cognito-session.js +4 -24
  101. package/dist/utils/incomplete-install-error.js +1 -11
  102. package/dist/utils/install-tree-torn.d.ts +11 -0
  103. package/dist/utils/install-tree-torn.js +1 -1
  104. package/dist/utils/resident-package-preload.js +2 -1
  105. package/docs/anywhere-runtime.md +8 -0
  106. package/package.json +9 -9
@@ -1 +1 @@
1
- {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.114","bundleSha256":"48442336bfcf5bf30f4bd9b6af8723cbc7cf72a6adc546aaebce2e1197917e15","formatVersion":1}
1
+ {"name":"hq-cli-daemon-sync-runner","type":"module","version":"6.18.117","bundleSha256":"425e7b51afda9223d469b19d2a657cd4ea6af5c2c0bbd1354b837dc682faecfc","formatVersion":1}
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import { vaultApiFetch } from "../../utils/vault-api.js";
9
9
  import { type BotLocalConfig } from "./local-config.js";
10
+ import { parseRetryAfterMs as retryAfterHeaderMs } from "../mesh/live/daemon/credentials.js";
10
11
  export type TokenSupplier = () => Promise<string>;
11
12
  /**
12
13
  * One agent-inbox item. DMs carry the base fields; room (channel / group chat)
@@ -170,7 +171,7 @@ export declare class InvalidDmRecipientError extends Error {
170
171
  constructor(recipient: string);
171
172
  }
172
173
  /** Parse a Retry-After header (delta-seconds or HTTP-date) to milliseconds. */
173
- export declare function retryAfterHeaderMs(value: string | null | undefined, nowMs?: number): number | undefined;
174
+ export { retryAfterHeaderMs };
174
175
  export interface BotApiOptions {
175
176
  token: TokenSupplier;
176
177
  baseUrl?: string;
@@ -9,6 +9,7 @@ import { vaultApiFetch } from "../../utils/vault-api.js";
9
9
  import { tokenAgentUid } from "../heartbeat-identity.js";
10
10
  import { assertNoSecretKeys } from "./local-config.js";
11
11
  import { isRecipientUid } from "../notify-recipient.js";
12
+ import { parseRetryAfterMs as retryAfterHeaderMs } from "../mesh/live/daemon/credentials.js";
12
13
  export class BotApiError extends Error {
13
14
  status;
14
15
  path;
@@ -36,21 +37,7 @@ export class InvalidDmRecipientError extends Error {
36
37
  }
37
38
  }
38
39
  /** Parse a Retry-After header (delta-seconds or HTTP-date) to milliseconds. */
39
- export function retryAfterHeaderMs(value, nowMs = Date.now()) {
40
- if (!value)
41
- return undefined;
42
- const trimmed = value.trim();
43
- if (!trimmed)
44
- return undefined;
45
- const seconds = Number(trimmed);
46
- if (Number.isFinite(seconds) && seconds >= 0) {
47
- return Math.round(seconds * 1000);
48
- }
49
- const dateMs = Date.parse(trimmed);
50
- if (!Number.isNaN(dateMs))
51
- return Math.max(0, dateMs - nowMs);
52
- return undefined;
53
- }
40
+ export { retryAfterHeaderMs };
54
41
  async function readError(res) {
55
42
  try {
56
43
  const body = (await res.json());
@@ -338,8 +338,6 @@ export declare function claudeOAuthRefreshLastPath(root: string): string;
338
338
  export declare function tokenFingerprint(token: string): string;
339
339
  /** Reads the last refresh outcome for a home. Exposed for the doctor command. */
340
340
  export declare function readClaudeRefreshLast(root: string, home: string): ClaudeRefreshLastEntry | null;
341
- /** @deprecated prefer {@link revokedMarkerForCurrentCredential}; this is the pre-fingerprint shim. */
342
- export declare function isAccountRevokedPersisted(root: string, accountId: string): boolean;
343
341
  /**
344
342
  * True when the capacity collector has recorded this refresh token as
345
343
  * revoked (by token fingerprint, under any account). Lanes use it to tell a
@@ -1657,11 +1657,6 @@ function clearAccountRevoked(root, accountId) {
1657
1657
  delete file.revokedAccounts[accountId];
1658
1658
  writeRefreshLast(root, file);
1659
1659
  }
1660
- /** @deprecated prefer {@link revokedMarkerForCurrentCredential}; this is the pre-fingerprint shim. */
1661
- export function isAccountRevokedPersisted(root, accountId) {
1662
- const file = readRefreshLast(root);
1663
- return Object.prototype.hasOwnProperty.call(file.revokedAccounts, accountId);
1664
- }
1665
1660
  /**
1666
1661
  * True when the capacity collector has recorded this refresh token as
1667
1662
  * revoked (by token fingerprint, under any account). Lanes use it to tell a
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Paths the native delegate steps print, spelled exactly as the hq-core
3
+ * helpers spell them: the HQ root as given, then literal forward slashes
4
+ * ("$HQ_ROOT/companies/..."). These strings appear in plans and error text
5
+ * that the parity tests compare byte for byte, so they must not depend on the
6
+ * platform path module. Node opens mixed-separator paths on every platform,
7
+ * so the same strings are used to read the files.
8
+ *
9
+ * This module imports nothing: core-delegate-paths.test.ts runs it under
10
+ * path.win32 semantics, and a path.join rewrite would fail there on any OS.
11
+ */
12
+ /** Schema sources as hq-delegate-secrets.sh builds them. */
13
+ export declare function secretsSourcePaths(root: string, company: string, project: string, repoRel: string): {
14
+ projectSchema: string;
15
+ prdFile: string;
16
+ repoSchema: string;
17
+ };
18
+ /**
19
+ * The repository directory as hq-delegate-repo.sh resolves it: an absolute
20
+ * repo.path (POSIX or a Windows drive path) is used as-is, otherwise
21
+ * "$HQ_ROOT/$REPO_REL".
22
+ */
23
+ export declare function delegateRepoDirectory(root: string, repoRel: string): string;
24
+ /** The company board as hq-delegate-transfer.sh spells it. */
25
+ export declare function delegateBoardPath(root: string, company: string): string;
26
+ //# sourceMappingURL=delegate-helper-paths.d.ts.map
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Paths the native delegate steps print, spelled exactly as the hq-core
3
+ * helpers spell them: the HQ root as given, then literal forward slashes
4
+ * ("$HQ_ROOT/companies/..."). These strings appear in plans and error text
5
+ * that the parity tests compare byte for byte, so they must not depend on the
6
+ * platform path module. Node opens mixed-separator paths on every platform,
7
+ * so the same strings are used to read the files.
8
+ *
9
+ * This module imports nothing: core-delegate-paths.test.ts runs it under
10
+ * path.win32 semantics, and a path.join rewrite would fail there on any OS.
11
+ */
12
+ /** Schema sources as hq-delegate-secrets.sh builds them. */
13
+ export function secretsSourcePaths(root, company, project, repoRel) {
14
+ const projectDir = `${root}/companies/${company}/projects/${project}`;
15
+ return {
16
+ projectSchema: `${projectDir}/.env.schema`,
17
+ prdFile: `${projectDir}/prd.json`,
18
+ repoSchema: repoRel ? `${root}/${repoRel}/.env.schema` : "",
19
+ };
20
+ }
21
+ /**
22
+ * The repository directory as hq-delegate-repo.sh resolves it: an absolute
23
+ * repo.path (POSIX or a Windows drive path) is used as-is, otherwise
24
+ * "$HQ_ROOT/$REPO_REL".
25
+ */
26
+ export function delegateRepoDirectory(root, repoRel) {
27
+ return /^\//.test(repoRel) || /^[A-Za-z]:[\\/]/.test(repoRel) ? repoRel : `${root}/${repoRel}`;
28
+ }
29
+ /** The company board as hq-delegate-transfer.sh spells it. */
30
+ export function delegateBoardPath(root, company) {
31
+ return `${root}/companies/${company}/board.json`;
32
+ }
33
+ //# sourceMappingURL=delegate-helper-paths.js.map
@@ -0,0 +1,63 @@
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 { type JqRunner, type ResolveJqDeps, type VerifiedJq } from "./verified-jq.js";
13
+ export declare const MANAGED_JQ_VERSION = "jq-1.8.2";
14
+ /** Where the daemon keeps its own jq, or null on a platform it does not provision. */
15
+ export declare function managedJqPath(home: string | undefined, platform?: NodeJS.Platform): string | null;
16
+ export declare function managedJqAsset(platform: NodeJS.Platform, arch: string): {
17
+ url: string;
18
+ sha256: string;
19
+ } | null;
20
+ export interface ProvisionJqDeps {
21
+ home: string | undefined;
22
+ platform?: NodeJS.Platform;
23
+ arch?: string;
24
+ fetch?: (url: string, init: {
25
+ signal: AbortSignal;
26
+ redirect: "follow";
27
+ }) => Promise<Response>;
28
+ run?: JqRunner;
29
+ log?: (line: string) => void;
30
+ /** Test seam: the download and its checksum. Defaults to managedJqAsset. */
31
+ asset?: {
32
+ url: string;
33
+ sha256: string;
34
+ };
35
+ }
36
+ export type ProvisionJqResult = {
37
+ ok: true;
38
+ path: string;
39
+ } | {
40
+ ok: false;
41
+ reason: string;
42
+ };
43
+ /** For tests. */
44
+ export declare function resetJqProvision(): void;
45
+ /**
46
+ * Install the managed jq. Concurrent callers share one install, and after a
47
+ * failure (offline, say) callers get that failure for ten minutes instead of
48
+ * starting a download per policy check.
49
+ */
50
+ export declare function provisionManagedJq(deps: ProvisionJqDeps, now?: () => number): Promise<ProvisionJqResult>;
51
+ export interface ResolveOrProvisionDeps extends ResolveJqDeps {
52
+ /** How long a caller waits for a fresh install before failing closed. */
53
+ waitMs?: number;
54
+ provision?: Partial<ProvisionJqDeps>;
55
+ }
56
+ /**
57
+ * The jq policy checks run with: the daemon's own managed copy or another jq
58
+ * that passes the probe; when there is none, install the managed copy (waiting
59
+ * up to `waitMs`) and look again. Throws JqUnavailableError when that fails or
60
+ * is still running, so the caller fails closed.
61
+ */
62
+ export declare function resolveOrProvisionJq(deps: ResolveOrProvisionDeps): Promise<VerifiedJq>;
63
+ //# sourceMappingURL=jq-provision.d.ts.map
@@ -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
@@ -1974,6 +1974,7 @@ export async function runDaemon(opts) {
1974
1974
  socketPath: hqdSocketPath(home, env),
1975
1975
  registryPath: registryFile(registryDir(home, env)),
1976
1976
  hqRoot,
1977
+ warmJq: true,
1977
1978
  log,
1978
1979
  flagSnapshots,
1979
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 = () => {