@indigoai-us/hq-cli 5.345.215 → 5.345.218

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +46 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  6. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  7. package/dist/command-catalog.generated.d.ts +59 -4
  8. package/dist/command-catalog.generated.js +74 -4
  9. package/dist/command-help.js +3 -1
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/auth.d.ts +1 -1
  13. package/dist/commands/auth.js +11 -52
  14. package/dist/commands/bot.js +11 -4
  15. package/dist/commands/cloud-demote.d.ts +19 -4
  16. package/dist/commands/cloud-demote.js +85 -12
  17. package/dist/commands/cloud-provision.d.ts +5 -1
  18. package/dist/commands/cloud-provision.js +6 -2
  19. package/dist/commands/cloud.d.ts +37 -1
  20. package/dist/commands/cloud.js +110 -27
  21. package/dist/commands/core-hq-session-native.js +3 -0
  22. package/dist/commands/core.js +1 -0
  23. package/dist/commands/daemon.js +4 -1
  24. package/dist/commands/dm.js +7 -0
  25. package/dist/commands/doctor-usage.d.ts +8 -0
  26. package/dist/commands/doctor-usage.js +20 -0
  27. package/dist/commands/doctor.js +7 -1
  28. package/dist/commands/env.d.ts +18 -0
  29. package/dist/commands/env.js +82 -0
  30. package/dist/commands/install-global.js +3 -3
  31. package/dist/commands/lanes.js +100 -24
  32. package/dist/commands/logout.d.ts +7 -0
  33. package/dist/commands/logout.js +41 -34
  34. package/dist/commands/members.js +1 -1
  35. package/dist/commands/pack-start-bot.d.ts +1 -1
  36. package/dist/commands/pack-start-bot.js +2 -2
  37. package/dist/commands/pkg-update.js +1 -1
  38. package/dist/commands/sources.d.ts +8 -2
  39. package/dist/commands/sources.js +65 -9
  40. package/dist/commands/sync-narrow.js +1 -1
  41. package/dist/commands/team-sync.js +1 -1
  42. package/dist/commands/whoami.js +26 -1
  43. package/dist/data/command-states.json +22 -0
  44. package/dist/index.js +52 -4
  45. package/dist/lazy-commands.js +2 -1
  46. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  47. package/dist/lib/anywhere-person-setting.js +6 -3
  48. package/dist/lib/billing/usage-card.d.ts +25 -4
  49. package/dist/lib/billing/usage-card.js +76 -9
  50. package/dist/lib/billing/usage-cost.d.ts +3 -3
  51. package/dist/lib/billing/usage-cost.js +40 -15
  52. package/dist/lib/billing/usage-only.js +4 -2
  53. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  54. package/dist/lib/billing/usage-rate-card.js +3 -0
  55. package/dist/lib/bot/fleet-cron.js +93 -6
  56. package/dist/lib/bot/inflight.d.ts +9 -0
  57. package/dist/lib/bot/inflight.js +10 -0
  58. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  59. package/dist/lib/bot/pack-link.d.ts +2 -2
  60. package/dist/lib/bot/pack-link.js +2 -2
  61. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  62. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  63. package/dist/lib/bot/runtime/grok.js +1 -1
  64. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  65. package/dist/lib/daemon/flag-monitor.js +17 -6
  66. package/dist/lib/daemon/flag.d.ts +65 -1
  67. package/dist/lib/daemon/flag.js +190 -40
  68. package/dist/lib/daemon/hook-env.d.ts +32 -0
  69. package/dist/lib/daemon/hook-env.js +51 -0
  70. package/dist/lib/daemon/ops/policy.js +67 -8
  71. package/dist/lib/daemon/paths.d.ts +72 -2
  72. package/dist/lib/daemon/paths.js +154 -3
  73. package/dist/lib/daemon/run.js +32 -21
  74. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  75. package/dist/lib/daemon/selfcheck.js +40 -1
  76. package/dist/lib/daemon/server.d.ts +3 -1
  77. package/dist/lib/daemon/server.js +7 -22
  78. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  79. package/dist/lib/daemon/state-file-switch.js +88 -0
  80. package/dist/lib/daemon/state-file.d.ts +198 -0
  81. package/dist/lib/daemon/state-file.js +419 -0
  82. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  83. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  84. package/dist/lib/doctor/checks/host-core.d.ts +52 -0
  85. package/dist/lib/doctor/checks/host-core.js +337 -0
  86. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  87. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  88. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  89. package/dist/lib/doctor/registry.js +4 -0
  90. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  91. package/dist/lib/environment/credential-shapes.js +333 -0
  92. package/dist/lib/environment/profile.d.ts +239 -0
  93. package/dist/lib/environment/profile.js +239 -0
  94. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  95. package/dist/lib/hook-engine/coverage.js +124 -0
  96. package/dist/lib/hook-engine/reconcile.js +300 -94
  97. package/dist/lib/hook-engine/registration.d.ts +17 -1
  98. package/dist/lib/hook-engine/registration.js +62 -7
  99. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  100. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  101. package/dist/lib/hot-channels/alert.d.ts +2 -0
  102. package/dist/lib/hot-channels/alert.js +8 -1
  103. package/dist/lib/hot-channels/contract.d.ts +12 -0
  104. package/dist/lib/hot-channels/contract.js +7 -0
  105. package/dist/lib/hot-channels/loop.js +1 -0
  106. package/dist/lib/hot-channels/run.d.ts +6 -0
  107. package/dist/lib/hot-channels/run.js +4 -0
  108. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  109. package/dist/lib/hot-channels/signals-pass.js +21 -49
  110. package/dist/lib/install/claude-targets.d.ts +12 -1
  111. package/dist/lib/install/claude-targets.js +70 -5
  112. package/dist/lib/install/codex-pack-contributions.js +1 -1
  113. package/dist/lib/install/codex-targets.d.ts +2 -2
  114. package/dist/lib/install/codex-targets.js +48 -5
  115. package/dist/lib/install/hook-target.d.ts +4 -1
  116. package/dist/lib/install/hook-target.js +14 -1
  117. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  118. package/dist/lib/lanes/canonical-host.js +65 -0
  119. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  120. package/dist/lib/lanes/host-capacity.js +29 -3
  121. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  122. package/dist/lib/mesh/live/daemon/run.js +5 -2
  123. package/dist/lib/mesh/live/flush.d.ts +5 -1
  124. package/dist/lib/mesh/live/flush.js +12 -6
  125. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  126. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  127. package/dist/lib/mesh/live/spool.d.ts +7 -0
  128. package/dist/lib/mesh/live/spool.js +25 -0
  129. package/dist/lib/packages/setup-block.d.ts +2 -2
  130. package/dist/lib/packages/setup-block.js +2 -2
  131. package/dist/lib/packages/start-bot.d.ts +1 -1
  132. package/dist/lib/packages/start-bot.js +1 -1
  133. package/dist/lib/person-setting-cache.d.ts +38 -0
  134. package/dist/lib/person-setting-cache.js +98 -0
  135. package/dist/lib/safe-store.d.ts +245 -0
  136. package/dist/lib/safe-store.js +777 -0
  137. package/dist/lib/signals/engine.d.ts +29 -2
  138. package/dist/lib/signals/engine.js +103 -4
  139. package/dist/lib/signals/reply.js +73 -18
  140. package/dist/lib/signals/steps/adapters.js +7 -2
  141. package/dist/lib/signals/steps/extract.d.ts +13 -0
  142. package/dist/lib/signals/steps/extract.js +84 -4
  143. package/dist/main.js +47 -4
  144. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  145. package/dist/types.d.ts +1 -1
  146. package/dist/utils/auth-expiry.d.ts +8 -0
  147. package/dist/utils/auth-expiry.js +53 -0
  148. package/dist/utils/callback-port-busy.d.ts +1 -1
  149. package/dist/utils/callback-port-busy.js +4 -4
  150. package/dist/utils/cli-telemetry.d.ts +21 -0
  151. package/dist/utils/cli-telemetry.js +34 -0
  152. package/dist/utils/command-usage.d.ts +275 -0
  153. package/dist/utils/command-usage.js +797 -0
  154. package/dist/utils/hook-trust.d.ts +7 -0
  155. package/dist/utils/hook-trust.js +34 -4
  156. package/dist/utils/host-registration.d.ts +179 -0
  157. package/dist/utils/host-registration.js +505 -0
  158. package/dist/utils/resident-package-preload.js +2 -0
  159. package/package.json +10 -8
  160. package/scripts/bench-core.mjs +1096 -0
  161. package/scripts/check-function-manifest.mjs +702 -0
@@ -2,40 +2,56 @@
2
2
  * Feature flags read by the daemon. The daemon runs for weeks, so each read
3
3
  * asks the registry again instead of holding a per-process answer, and it
4
4
  * reads as each flag's fallback unless the registry or a local override decides it.
5
+ *
6
+ * The daemon's timed monitors pass one shared DaemonFlagSnapshotSource, so the
7
+ * flags they watch are decided from one registry request per refresh interval
8
+ * instead of one request per flag.
5
9
  */
10
+ import { performance } from "node:perf_hooks";
6
11
  import { createFlagClient, readLocalOverride, } from "@indigoai-us/hq-flags-client";
7
12
  import { ensureCognitoIdToken } from "../../utils/cognito-session.js";
8
13
  import { resolveFlagRegistryEndpoint } from "../flag-registry-endpoint.js";
9
14
  import { resolveProcessFlagCompanyContext } from "../flag-registry.js";
10
15
  import { HQ_ANYWHERE_RUNTIME_FLAG, hqAnywhereRuntimeLocallyDisabled } from "../anywhere-runtime-flag-key.js";
16
+ import { DAEMON_FLAG_REFRESH_INTERVAL_MS } from "./flag-monitor.js";
11
17
  /** Outposts hand running services to the next daemon on a CLI update instead of restarting them all. */
12
18
  export const SUPERVISOR_HANDOFF_FLAG = "daemon.supervisor-handoff";
13
19
  /** Self-updates build the new CLI beside the running one and swap it in, so `hq` never disappears mid-update. */
14
20
  export const STAGED_SELF_UPDATE_FLAG = "cli.staged-self-update";
15
21
  const READ_TIMEOUT_MS = 5_000;
16
- export async function readDaemonFlag(flagKey, options = {}) {
17
- const env = options.env ?? process.env;
18
- if (flagKey === HQ_ANYWHERE_RUNTIME_FLAG && hqAnywhereRuntimeLocallyDisabled(env))
19
- return false;
20
- const fallback = options.fallback ?? flagKey === HQ_ANYWHERE_RUNTIME_FLAG;
21
- const override = readLocalOverride(flagKey, env);
22
- const localOverrideMode = options.localOverrideMode ?? "respect";
23
- if (override !== null && (localOverrideMode === "respect" || (localOverrideMode === "off-only" && !override)))
24
- return override;
25
- let failed = false;
26
- let reportedError;
27
- const onError = (error) => {
28
- failed = true;
29
- reportedError ??= error;
30
- options.onError?.(error);
31
- };
22
+ /**
23
+ * How long a loaded registry snapshot may answer further daemon flag reads
24
+ * that arrive between refresh ticks: the monitors' first reads at daemon
25
+ * start, a restarted hqd server's first read, and a request-driven refresh.
26
+ * It is the most a shared read can add to the time a flag change takes to
27
+ * reach one of those reads. A refresh tick never uses it: each tick discards
28
+ * the held snapshot and any request already in flight, so the tick's reads are
29
+ * decided from a request sent on that tick, as they were before sharing.
30
+ *
31
+ * One case differs from a monitor on its own timer: a monitor whose first
32
+ * read is still pending when the shared tick arrives skips that tick (its
33
+ * refresh joins its own pending read), so its next refresh is up to one
34
+ * pending read later than 30 seconds after its first. That applies to the hqd
35
+ * runtime gate just after the server starts, not to the kill switches.
36
+ */
37
+ export const DAEMON_FLAG_SNAPSHOT_TTL_MS = 5_000;
38
+ function closeQuietly(client) {
39
+ try {
40
+ client?.close();
41
+ }
42
+ catch {
43
+ // closing a one-shot client cannot change the answer
44
+ }
45
+ }
46
+ async function loadDaemonFlagRegistry(env, options) {
47
+ const errors = [];
32
48
  let client;
33
49
  try {
34
50
  const company = resolveProcessFlagCompanyContext(env);
35
51
  // Signed out reads as the flag fallback without reaching the registry.
36
52
  const token = await (options.getToken ?? (() => ensureCognitoIdToken({ interactive: false })))();
37
53
  if (typeof token !== "string" || token.trim() === "")
38
- return fallback;
54
+ return { signedOut: true, errors };
39
55
  client = (options.createClient ?? createFlagClient)({
40
56
  endpoint: resolveFlagRegistryEndpoint(undefined, env),
41
57
  getToken: () => token,
@@ -44,43 +60,177 @@ export async function readDaemonFlag(flagKey, options = {}) {
44
60
  requestTimeoutMs: READ_TIMEOUT_MS,
45
61
  ...(company.companyUid ? { companyUid: company.companyUid } : {}),
46
62
  ...(company.companySlug ? { companyIdentifiers: [company.companySlug] } : {}),
47
- onError,
63
+ onError: (error) => { errors.push(error); },
48
64
  });
49
65
  try {
50
66
  await client.ready();
51
67
  }
52
68
  catch (error) {
53
- onError(error);
54
- }
55
- const resolution = client.explain(flagKey, { fallback });
56
- if (failed) {
57
- if (options.throwOnError && !fallback) {
58
- throw new Error("hq-flags registry read failed", { cause: reportedError });
59
- }
60
- return fallback;
69
+ errors.push(error);
61
70
  }
62
- if (resolution.source === "snapshot")
63
- return resolution.value === true;
64
- return fallback && resolution.value === true;
65
71
  }
66
72
  catch (error) {
67
- if (!failed)
68
- onError(error);
69
- if (failed) {
70
- if (options.throwOnError && !fallback) {
71
- throw new Error("hq-flags registry read failed", { cause: reportedError ?? error });
73
+ if (errors.length === 0)
74
+ errors.push(error);
75
+ }
76
+ return { signedOut: false, errors, ...(client ? { client } : {}) };
77
+ }
78
+ /**
79
+ * Share registry requests between the daemon's timed flag reads.
80
+ *
81
+ * Reads that arrive while a request is in flight join it, and a loaded
82
+ * snapshot answers further reads for `ttlMs`. A failed or signed-out request
83
+ * is handed to the reads that joined it and is never kept, so the next read
84
+ * asks again and each flag keeps its own failure behavior.
85
+ */
86
+ export function createDaemonFlagSnapshotSource(options = {}) {
87
+ const ttlMs = options.ttlMs ?? DAEMON_FLAG_SNAPSHOT_TTL_MS;
88
+ const intervalMs = options.intervalMs ?? DAEMON_FLAG_REFRESH_INTERVAL_MS;
89
+ const now = options.now ?? (() => performance.now());
90
+ let held;
91
+ let inFlight;
92
+ let closed = false;
93
+ const ticks = new Set();
94
+ let timer;
95
+ const drop = () => {
96
+ closeQuietly(held?.read.client);
97
+ held = undefined;
98
+ };
99
+ /** A request this source will not keep: the reads waiting on it decide in this turn, then it is closed. */
100
+ const unkept = (read) => {
101
+ const client = read.client;
102
+ if (client)
103
+ setImmediate(() => closeQuietly(client));
104
+ return read;
105
+ };
106
+ return {
107
+ schedule(tick) {
108
+ // A distinct wrapper per call, so cancelling one registration never removes another.
109
+ const entry = () => tick();
110
+ ticks.add(entry);
111
+ if (!timer && !closed) {
112
+ timer = setInterval(() => {
113
+ // A tick is decided from a request sent on this tick, never from an earlier one.
114
+ drop();
115
+ inFlight = undefined;
116
+ for (const run of [...ticks]) {
117
+ try {
118
+ run();
119
+ }
120
+ catch {
121
+ // one monitor's refresh cannot stop the others
122
+ }
123
+ }
124
+ }, intervalMs);
125
+ timer.unref?.();
126
+ }
127
+ return () => {
128
+ ticks.delete(entry);
129
+ if (ticks.size === 0 && timer) {
130
+ clearInterval(timer);
131
+ timer = undefined;
132
+ }
133
+ };
134
+ },
135
+ load(env, readOptions) {
136
+ if (closed)
137
+ return loadDaemonFlagRegistry(env, readOptions).then(unkept);
138
+ let key;
139
+ try {
140
+ const company = resolveProcessFlagCompanyContext(env);
141
+ key = JSON.stringify([
142
+ resolveFlagRegistryEndpoint(undefined, env),
143
+ company.companyUid ?? null,
144
+ company.companySlug ?? null,
145
+ ]);
146
+ }
147
+ catch {
148
+ // The unshared read reports this failure the way it always has.
149
+ return loadDaemonFlagRegistry(env, readOptions).then(unkept);
150
+ }
151
+ if (held && held.key === key && now() - held.at < ttlMs)
152
+ return Promise.resolve(held.read);
153
+ if (inFlight && inFlight.key === key)
154
+ return inFlight.promise;
155
+ // Age counts from when the request was sent, so the bound covers the request time too.
156
+ const startedAt = now();
157
+ const promise = loadDaemonFlagRegistry(env, readOptions).then((read) => {
158
+ try {
159
+ options.onRead?.(read, env);
160
+ }
161
+ catch {
162
+ // an observer cannot change the answer
163
+ }
164
+ const reusable = !closed && !read.signedOut && read.errors.length === 0 && read.client !== undefined;
165
+ // A request overtaken by a newer one (a tick started the newer one) is used once and not kept.
166
+ if (!reusable || (held && held.at > startedAt))
167
+ return unkept(read);
168
+ drop();
169
+ held = { key, at: startedAt, read };
170
+ return read;
171
+ }).finally(() => {
172
+ if (inFlight?.promise === promise)
173
+ inFlight = undefined;
174
+ });
175
+ inFlight = { key, promise };
176
+ return promise;
177
+ },
178
+ close() {
179
+ closed = true;
180
+ ticks.clear();
181
+ if (timer)
182
+ clearInterval(timer);
183
+ timer = undefined;
184
+ drop();
185
+ },
186
+ };
187
+ }
188
+ export async function readDaemonFlag(flagKey, options = {}) {
189
+ const env = options.env ?? process.env;
190
+ if (flagKey === HQ_ANYWHERE_RUNTIME_FLAG && hqAnywhereRuntimeLocallyDisabled(env))
191
+ return false;
192
+ const fallback = options.fallback ?? flagKey === HQ_ANYWHERE_RUNTIME_FLAG;
193
+ const override = readLocalOverride(flagKey, env);
194
+ const localOverrideMode = options.localOverrideMode ?? "respect";
195
+ if (override !== null && (localOverrideMode === "respect" || (localOverrideMode === "off-only" && !override)))
196
+ return override;
197
+ const shared = options.snapshots;
198
+ const read = await (shared ? shared.load(env, options) : loadDaemonFlagRegistry(env, options));
199
+ try {
200
+ let reportedError = read.errors[0];
201
+ let failed = read.errors.length > 0;
202
+ for (const error of read.errors) {
203
+ try {
204
+ options.onError?.(error);
205
+ }
206
+ catch {
207
+ // an error reporter cannot change the answer
72
208
  }
209
+ }
210
+ if (read.signedOut)
73
211
  return fallback;
212
+ if (!failed) {
213
+ try {
214
+ const resolution = read.client.explain(flagKey, { fallback });
215
+ if (resolution.source === "snapshot")
216
+ return resolution.value === true;
217
+ return fallback && resolution.value === true;
218
+ }
219
+ catch (error) {
220
+ failed = true;
221
+ reportedError = error;
222
+ options.onError?.(error);
223
+ }
224
+ }
225
+ if (options.throwOnError && !fallback) {
226
+ throw new Error("hq-flags registry read failed", { cause: reportedError });
74
227
  }
75
228
  return fallback;
76
229
  }
77
230
  finally {
78
- try {
79
- client?.close();
80
- }
81
- catch {
82
- // closing a one-shot client cannot change the answer
83
- }
231
+ // A shared source owns its client and closes it when the snapshot is replaced.
232
+ if (!shared)
233
+ closeQuietly(read.client);
84
234
  }
85
235
  }
86
236
  //# sourceMappingURL=flag.js.map
@@ -0,0 +1,32 @@
1
+ /**
2
+ * HQ_HOOK_* belongs to one hook dispatch, never to the daemon.
3
+ *
4
+ * master-hook.sh exports the fields it parsed from a hook payload
5
+ * (HQ_HOOK_SESSION_ID, HQ_HOOK_AGENT_ID, HQ_HOOK_AGENT_TYPE, HQ_HOOK_CWD,
6
+ * HQ_HOOK_TOOL_NAME, HQ_HOOK_EVENT, HQ_HOOK_COMMAND, ...) so its child hooks can
7
+ * skip their own parse. A hook script that finds one of them set trusts it over
8
+ * the payload on stdin. The daemon runs hook scripts with a payload it builds
9
+ * itself, so any HQ_HOOK_* it holds describes some other call: a daemon started
10
+ * from inside a hook, or from a shell that exported one, would otherwise answer
11
+ * every check with that call's identity (a stale HQ_HOOK_AGENT_ID turns each
12
+ * main-thread check into "This call has an invalid agent_id").
13
+ *
14
+ * The whole prefix goes, tuning knobs included: the daemon's OS unit never
15
+ * carries any of them (its environment is an allowlist), so a hand-started
16
+ * daemon behaves the same as a managed one.
17
+ */
18
+ /** The HQ_HOOK_* names set in `env`, sorted. Names only: values may be private. */
19
+ export declare function hookEnvNames(env: NodeJS.ProcessEnv): string[];
20
+ /** `env` without any HQ_HOOK_* name. Returns `env` itself when it has none. */
21
+ export declare function withoutHookEnv(env: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
22
+ /**
23
+ * The environment `hq daemon run` works with. HQ_HOOK_* is deleted from the
24
+ * live process environment, because hqd and the services read it directly, and
25
+ * left out of a caller-supplied one. `removed` names what was dropped, for the
26
+ * daemon log.
27
+ */
28
+ export declare function daemonStartEnv(given: NodeJS.ProcessEnv | undefined, processEnv?: NodeJS.ProcessEnv): {
29
+ env: NodeJS.ProcessEnv;
30
+ removed: string[];
31
+ };
32
+ //# sourceMappingURL=hook-env.d.ts.map
@@ -0,0 +1,51 @@
1
+ /**
2
+ * HQ_HOOK_* belongs to one hook dispatch, never to the daemon.
3
+ *
4
+ * master-hook.sh exports the fields it parsed from a hook payload
5
+ * (HQ_HOOK_SESSION_ID, HQ_HOOK_AGENT_ID, HQ_HOOK_AGENT_TYPE, HQ_HOOK_CWD,
6
+ * HQ_HOOK_TOOL_NAME, HQ_HOOK_EVENT, HQ_HOOK_COMMAND, ...) so its child hooks can
7
+ * skip their own parse. A hook script that finds one of them set trusts it over
8
+ * the payload on stdin. The daemon runs hook scripts with a payload it builds
9
+ * itself, so any HQ_HOOK_* it holds describes some other call: a daemon started
10
+ * from inside a hook, or from a shell that exported one, would otherwise answer
11
+ * every check with that call's identity (a stale HQ_HOOK_AGENT_ID turns each
12
+ * main-thread check into "This call has an invalid agent_id").
13
+ *
14
+ * The whole prefix goes, tuning knobs included: the daemon's OS unit never
15
+ * carries any of them (its environment is an allowlist), so a hand-started
16
+ * daemon behaves the same as a managed one.
17
+ */
18
+ const HOOK_ENV_NAME = /^HQ_HOOK_/i;
19
+ /** The HQ_HOOK_* names set in `env`, sorted. Names only: values may be private. */
20
+ export function hookEnvNames(env) {
21
+ return Object.keys(env)
22
+ .filter((key) => HOOK_ENV_NAME.test(key))
23
+ .sort();
24
+ }
25
+ /** `env` without any HQ_HOOK_* name. Returns `env` itself when it has none. */
26
+ export function withoutHookEnv(env) {
27
+ const names = hookEnvNames(env);
28
+ if (names.length === 0)
29
+ return env;
30
+ const clean = { ...env };
31
+ for (const name of names)
32
+ delete clean[name];
33
+ return clean;
34
+ }
35
+ /**
36
+ * The environment `hq daemon run` works with. HQ_HOOK_* is deleted from the
37
+ * live process environment, because hqd and the services read it directly, and
38
+ * left out of a caller-supplied one. `removed` names what was dropped, for the
39
+ * daemon log.
40
+ */
41
+ export function daemonStartEnv(given, processEnv = process.env) {
42
+ const removed = new Set(hookEnvNames(processEnv));
43
+ for (const name of removed)
44
+ delete processEnv[name];
45
+ if (given === undefined || given === processEnv)
46
+ return { env: processEnv, removed: [...removed].sort() };
47
+ for (const name of hookEnvNames(given))
48
+ removed.add(name);
49
+ return { env: withoutHookEnv(given), removed: [...removed].sort() };
50
+ }
51
+ //# sourceMappingURL=hook-env.js.map
@@ -20,6 +20,8 @@
20
20
  import { spawn } from "node:child_process";
21
21
  import * as fs from "node:fs";
22
22
  import * as path from "node:path";
23
+ import { sessionMetaCompanies } from "../../core-utils/session-company.js";
24
+ import { withoutHookEnv } from "../hook-env.js";
23
25
  export const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorizer.sh";
24
26
  export const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
25
27
  const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
@@ -194,8 +196,17 @@ function runScript(script, payload, env, cwd, timeoutMs) {
194
196
  * workspace/sessions/<sid>/meta.yaml (or scope-capability.json). hqd binds a
195
197
  * session id of its own per company + caller, so a check never borrows the
196
198
  * binding of an unrelated session.
199
+ *
200
+ * The synthetic session still has to carry the caller's lock set. hq-session.sh
201
+ * add company updates the real session's meta.yaml; policy.check used to stamp
202
+ * only company_slug A onto hqd-A-<id> and skip rewrites while that primary
203
+ * stayed put, so later reads of an added company B were blocked
204
+ * (feedback_a4a04ca0, feedback_cf07aef6). Copy the caller's company_slugs onto
205
+ * the synthetic session and remint the capability the authorizer actually
206
+ * reads. sessionMetaCompanies already ignores hqd-* ids, so this cannot borrow
207
+ * another check's bind.
197
208
  */
198
- function bindCheckSession(hqRoot, company, callerSession, now) {
209
+ function bindCheckSession(hqRoot, company, callerSession, now, env) {
199
210
  const caller = (callerSession ?? "default").replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 80) || "default";
200
211
  const scope = company ?? "personal";
201
212
  const sid = `hqd-${scope}-${caller}`;
@@ -203,7 +214,18 @@ function bindCheckSession(hqRoot, company, callerSession, now) {
203
214
  throw new PolicyOpError("bad_args", "sessionId has no usable characters");
204
215
  const dir = path.join(hqRoot, "workspace", "sessions", sid);
205
216
  const meta = path.join(dir, "meta.yaml");
206
- const body = `session_id: ${sid}\nstarted_at: ${now.toISOString()}\nsenior: user\n${company ? `company_slug: ${company}\n` : ""}source: hqd\n`;
217
+ const cap = path.join(dir, "scope-capability.json");
218
+ const callerLock = callerSession ? sessionMetaCompanies(hqRoot, callerSession, env) : [];
219
+ // The scope authorizer requires company_slugs[0] === company_slug, so the
220
+ // check company leads; this only reorders the caller's own lock set. A check
221
+ // company outside that lock is bound alone, never merged with the lock, so a
222
+ // caller cannot gain a company it did not lock.
223
+ const slugs = company
224
+ ? callerLock.includes(company)
225
+ ? [company, ...callerLock.filter((s) => s !== company)]
226
+ : [company]
227
+ : callerLock;
228
+ const slugLine = slugs.length > 1 ? `company_slugs: ${slugs.join(",")}\n` : "";
207
229
  let current = "";
208
230
  try {
209
231
  current = fs.readFileSync(meta, "utf8");
@@ -212,14 +234,50 @@ function bindCheckSession(hqRoot, company, callerSession, now) {
212
234
  if (err.code !== "ENOENT")
213
235
  throw err;
214
236
  }
215
- if (company
237
+ const started = current.match(/^started_at:\s*(\S+)/m)?.[1] ?? now.toISOString();
238
+ const body = `session_id: ${sid}\nstarted_at: ${started}\nsenior: user\n${company ? `company_slug: ${company}\n` : ""}${slugLine}source: hqd\n`;
239
+ const primaryWrong = company
216
240
  ? !current.includes(`\ncompany_slug: ${company}\n`)
217
- : !current.includes(`session_id: ${sid}\n`) || current.includes("\ncompany_slug:")) {
241
+ : !current.includes(`session_id: ${sid}\n`) || current.includes("\ncompany_slug:");
242
+ const slugsWrong = slugs.length > 1 ? !current.includes(`\ncompany_slugs: ${slugs.join(",")}\n`) : current.includes("\ncompany_slugs:");
243
+ if (primaryWrong || slugsWrong) {
218
244
  fs.mkdirSync(dir, { recursive: true });
219
245
  const tmp = `${meta}.${process.pid}.tmp`;
220
246
  fs.writeFileSync(tmp, body);
221
247
  fs.renameSync(tmp, meta);
222
248
  }
249
+ if (company && slugs.length > 0) {
250
+ const desired = {
251
+ session_id: sid,
252
+ company_slug: company,
253
+ minted_at: now.toISOString(),
254
+ company_slugs: slugs,
255
+ };
256
+ let capCurrent = "";
257
+ try {
258
+ capCurrent = fs.readFileSync(cap, "utf8");
259
+ }
260
+ catch (err) {
261
+ if (err.code !== "ENOENT")
262
+ throw err;
263
+ }
264
+ let capSlugs;
265
+ try {
266
+ capSlugs = JSON.parse(capCurrent).company_slugs;
267
+ }
268
+ catch {
269
+ capSlugs = undefined;
270
+ }
271
+ if (JSON.stringify(capSlugs) !== JSON.stringify(slugs)) {
272
+ fs.mkdirSync(dir, { recursive: true });
273
+ const tmp = `${cap}.${process.pid}.tmp`;
274
+ fs.writeFileSync(tmp, `${JSON.stringify(desired)}\n`);
275
+ fs.renameSync(tmp, cap);
276
+ }
277
+ }
278
+ else if (fs.existsSync(cap)) {
279
+ fs.unlinkSync(cap);
280
+ }
223
281
  return sid;
224
282
  }
225
283
  function extractContext(stdout) {
@@ -263,7 +321,7 @@ export async function policyCheck(args, deps) {
263
321
  throw new PolicyOpError("policy_engine_unavailable", `scope authorizer not found at ${authorizer}`);
264
322
  }
265
323
  const event = args.event ?? "PreToolUse";
266
- const session = bindCheckSession(hqRoot, args.company, args.sessionId, (deps.now ?? (() => new Date()))());
324
+ const session = bindCheckSession(hqRoot, args.company, args.sessionId, (deps.now ?? (() => new Date()))(), deps.env ?? process.env);
267
325
  const payload = JSON.stringify({
268
326
  session_id: session,
269
327
  hook_event_name: event,
@@ -271,8 +329,11 @@ export async function policyCheck(args, deps) {
271
329
  tool_input: args.input ?? {},
272
330
  cwd: args.cwd ?? hqRoot,
273
331
  });
332
+ // Identity reaches the hook scripts through the payload above and nowhere
333
+ // else. They trust HQ_HOOK_* over the payload, so nothing with that prefix
334
+ // may pass from the daemon's environment (see ../hook-env.ts).
274
335
  const env = {
275
- ...(deps.env ?? process.env),
336
+ ...withoutHookEnv(deps.env ?? process.env),
276
337
  HQ_ROOT: hqRoot,
277
338
  CLAUDE_PROJECT_DIR: hqRoot,
278
339
  BASH_ENV: "/dev/null",
@@ -281,8 +342,6 @@ export async function policyCheck(args, deps) {
281
342
  delete env.HQ_POLICY_COMPANY;
282
343
  else
283
344
  env.HQ_POLICY_COMPANY = args.company;
284
- delete env.HQ_HOOK_SESSION_ID;
285
- delete env.HQ_HOOK_TOOL_NAME;
286
345
  const timeoutMs = deps.timeoutMs ?? 15_000;
287
346
  const reasons = [];
288
347
  let decision = "allow";
@@ -3,6 +3,7 @@
3
3
  * under ~/.hq/daemon and never under a synced HQ folder. Service logs can hold
4
4
  * private output, so the folders are 0700 and the files 0600.
5
5
  */
6
+ import { type SafeStoreOperation, type SafeStorePoint, type SafeStoreRefusal, type SafeStoreRefusalCode } from "../safe-store.js";
6
7
  export interface DaemonPaths {
7
8
  root: string;
8
9
  configPath: string;
@@ -21,8 +22,77 @@ export interface DaemonPaths {
21
22
  unitProtocolPath: (unitId: string) => string;
22
23
  }
23
24
  export declare function daemonPaths(home?: string, env?: NodeJS.ProcessEnv): DaemonPaths;
24
- /** Create `dir` (and any missing parents) readable only by its owner, and tighten it if it already exists. */
25
- export declare function ensurePrivateDir(dir: string): void;
25
+ /**
26
+ * Create `dir` (and any missing parents) readable only by its owner, and
27
+ * tighten it if it already exists. The folder is checked before any chmod: it
28
+ * must be a real folder (not a symlink or junction) owned by this user, or
29
+ * EACCES is thrown and nothing is changed. The tightening runs through a
30
+ * descriptor opened with O_DIRECTORY|O_NOFOLLOW (fchmod), so a folder swapped
31
+ * for a link after the check is not followed. Windows, which cannot open a
32
+ * folder, checks by lstat and tightens by path (modes are no-ops there).
33
+ *
34
+ * The check came with the daemon state file (#2624) and sits behind its
35
+ * switch (state-file-switch.ts, default on). With the switch off, a folder the
36
+ * check refuses is handled as before #2624: it is tightened by path with
37
+ * chmod (following a link), and a chmod failure (EPERM on a folder another
38
+ * user owns) is thrown. One exception, which is new and not pre-#2624
39
+ * behavior: for the daemon root itself (`daemonPaths().root`, ~/.hq/daemon or
40
+ * HQ_DAEMON_DIR) a chmod failure is reported on stderr and the folder is used
41
+ * as it is, so a symlinked or foreign-owned daemon root does not stop the
42
+ * daemon. Every other folder (requests, bundle stages, config, logs, ...)
43
+ * still throws. The switch is read only when the check refuses, so the usual
44
+ * call reads no flag.
45
+ */
46
+ export declare function ensurePrivateDir(dir: string, options?: EnsurePrivateDirOptions): void;
47
+ export interface EnsurePrivateDirOptions {
48
+ /** The state file switch (tests). Default: daemonStateFileEnabled(). */
49
+ stateFileEnabled?: () => boolean;
50
+ /** Replaces fs.chmodSync in the switched-off fallback (tests). */
51
+ chmod?: (dir: string, mode: number) => void;
52
+ /** The daemon root (tests). Default: daemonPaths().root for this process. */
53
+ daemonRoot?: string;
54
+ }
55
+ /** Points and operations at which a test can act during a store write (see src/lib/safe-store.ts). */
56
+ export type StoreWriteHook = (point: SafeStorePoint, operation: SafeStoreOperation) => void;
57
+ export interface StoreFileWriteOptions {
58
+ /** Create the folder (0700) when missing and tighten it to 0700 through the held descriptor. */
59
+ create?: boolean;
60
+ /** Waits in milliseconds between rename attempts on EPERM, EACCES or EBUSY. Empty: no retry. */
61
+ renameRetryDelaysMs?: readonly number[];
62
+ /** Synchronous wait between rename attempts (tests). */
63
+ sleep?: (ms: number) => void;
64
+ /** Replaces fs.renameSync (tests). */
65
+ renameFile?: (from: string, to: string) => void;
66
+ /** Test seam (see SafeStorePoint). */
67
+ at?: StoreWriteHook;
68
+ /** Platform whose rules apply (tests). */
69
+ platform?: NodeJS.Platform;
70
+ }
71
+ /** A refused store operation as an error: `code` is the safe-store refusal code, or the errno of an io-error. */
72
+ export declare class StoreRefusedError extends Error {
73
+ readonly code: string;
74
+ readonly refusal: SafeStoreRefusalCode;
75
+ constructor(refused: SafeStoreRefusal);
76
+ }
77
+ /** The store folder itself is unusable: a link, not a folder, foreign, shared, or under an unsafe parent. */
78
+ export declare function isUnsafeFolderRefusal(code: SafeStoreRefusalCode): boolean;
79
+ /**
80
+ * Replace `file` with `text` through src/lib/safe-store.ts: the folder is held
81
+ * open and checked, the temporary file has a random name and O_EXCL, and the
82
+ * write is refused if the folder path is replaced (the helper's comment names
83
+ * the remaining window). A refusal is thrown as StoreRefusedError.
84
+ */
85
+ export declare function writeStoreFile(file: string, text: string, options?: StoreFileWriteOptions): void;
86
+ /**
87
+ * A small file's contents and modification time, read through
88
+ * src/lib/safe-store.ts (a regular single-link file of this user in a checked
89
+ * folder, opened without following a link), or null when it is missing,
90
+ * refused or larger than `maxBytes`.
91
+ */
92
+ export declare function readStoreFile(file: string, maxBytes: number): {
93
+ text: string;
94
+ mtimeMs: number;
95
+ } | null;
26
96
  /** Open a log file for appending, creating it (and its folder) owner-only. */
27
97
  export declare function openPrivateAppend(file: string): number;
28
98
  export declare function appendPrivate(file: string, text: string): void;