@indigoai-us/hq-cli 5.345.204 → 5.345.206

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 (80) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/command-catalog.generated.d.ts +51 -1
  3. package/dist/command-catalog.generated.js +63 -1
  4. package/dist/commands/bot.d.ts +67 -0
  5. package/dist/commands/bot.js +301 -39
  6. package/dist/commands/cloud-off-gate.d.ts +9 -2
  7. package/dist/commands/cloud-off-gate.js +49 -13
  8. package/dist/commands/feedback.d.ts +26 -0
  9. package/dist/commands/feedback.js +91 -5
  10. package/dist/commands/install-global.d.ts +3 -1
  11. package/dist/commands/install-global.js +15 -4
  12. package/dist/commands/lanes.d.ts +2 -0
  13. package/dist/commands/lanes.js +9 -3
  14. package/dist/commands/mcp-serve.d.ts +5 -2
  15. package/dist/commands/mcp-serve.js +45 -3
  16. package/dist/commands/mcp-status.d.ts +3 -1
  17. package/dist/commands/mcp-status.js +24 -14
  18. package/dist/commands/secrets.js +11 -1
  19. package/dist/commands/sources.js +10 -15
  20. package/dist/index.js +7 -2
  21. package/dist/lib/bot/executive-settings.d.ts +13 -0
  22. package/dist/lib/bot/executive-settings.js +20 -17
  23. package/dist/lib/bot/executive-sync.d.ts +12 -0
  24. package/dist/lib/bot/executive-sync.js +36 -0
  25. package/dist/lib/bot/executive.d.ts +51 -0
  26. package/dist/lib/bot/executive.js +144 -0
  27. package/dist/lib/bot/fleet-cron.d.ts +7 -0
  28. package/dist/lib/bot/fleet-cron.js +2 -1
  29. package/dist/lib/bot/fleet-local.js +9 -9
  30. package/dist/lib/bot/jobs/executive-handover.d.ts +6 -0
  31. package/dist/lib/bot/jobs/executive-handover.js +33 -0
  32. package/dist/lib/bot/jobs/hot-signal-sync.d.ts +22 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.js +47 -0
  34. package/dist/lib/bot/listed-running.d.ts +16 -0
  35. package/dist/lib/bot/listed-running.js +16 -0
  36. package/dist/lib/bot/pending-switch.d.ts +51 -0
  37. package/dist/lib/bot/pending-switch.js +103 -0
  38. package/dist/lib/bot/run.js +27 -3
  39. package/dist/lib/bot/runtime-failure.js +19 -3
  40. package/dist/lib/bot/status.d.ts +20 -0
  41. package/dist/lib/company-skill-wrapper.js +29 -0
  42. package/dist/lib/daemon/hq-child-bootstrap.mjs +197 -2
  43. package/dist/lib/daemon/resolver.d.ts +14 -0
  44. package/dist/lib/daemon/resolver.js +96 -0
  45. package/dist/lib/daemon/run.d.ts +11 -0
  46. package/dist/lib/daemon/run.js +58 -6
  47. package/dist/lib/daemon/server.d.ts +2 -9
  48. package/dist/lib/daemon/server.js +3 -89
  49. package/dist/lib/doctor/checks/claude-wiring.js +41 -0
  50. package/dist/lib/doctor/checks/sync-health.d.ts +8 -0
  51. package/dist/lib/doctor/checks/sync-health.js +34 -2
  52. package/dist/lib/doctor/duplicate-hook-registrations.d.ts +34 -0
  53. package/dist/lib/doctor/duplicate-hook-registrations.js +130 -0
  54. package/dist/lib/doctor/fix/apply.js +79 -3
  55. package/dist/lib/doctor/fix/remediation.d.ts +1 -1
  56. package/dist/lib/doctor/fix/remediation.js +15 -0
  57. package/dist/lib/doctor/types.d.ts +1 -1
  58. package/dist/lib/doctor/types.js +1 -0
  59. package/dist/lib/lanes/links.d.ts +2 -0
  60. package/dist/lib/lanes/links.js +12 -1
  61. package/dist/lib/mcp/local-native-tools.d.ts +40 -0
  62. package/dist/lib/mcp/local-native-tools.js +111 -0
  63. package/dist/lib/mcp/tools.d.ts +2 -0
  64. package/dist/lib/mcp/tools.js +2 -0
  65. package/dist/lib/signals/steps/extract.d.ts +1 -1
  66. package/dist/lib/signals/steps/extract.js +4 -16
  67. package/dist/sentry-init.js +6 -0
  68. package/dist/utils/cli-network-lifecycle.d.ts +11 -1
  69. package/dist/utils/cli-network-lifecycle.js +36 -2
  70. package/dist/utils/daemon-helper-lifetime.d.ts +39 -0
  71. package/dist/utils/daemon-helper-lifetime.js +209 -0
  72. package/dist/utils/daemon-helper-markers.d.ts +24 -0
  73. package/dist/utils/daemon-helper-markers.js +53 -0
  74. package/dist/utils/mcp-launcher.d.ts +28 -0
  75. package/dist/utils/mcp-launcher.js +117 -0
  76. package/dist/utils/package-use-lease.d.ts +10 -0
  77. package/dist/utils/package-use-lease.js +31 -0
  78. package/dist/utils/resident-package-preload.js +4 -1
  79. package/docs/anywhere-runtime.md +7 -0
  80. package/package.json +7 -7
@@ -6,6 +6,7 @@
6
6
  import { createHash, randomBytes } from "node:crypto";
7
7
  import { spawn } from "node:child_process";
8
8
  import * as fs from "node:fs";
9
+ import * as net from "node:net";
9
10
  import * as os from "node:os";
10
11
  import * as path from "node:path";
11
12
  import { performance } from "node:perf_hooks";
@@ -73,6 +74,15 @@ function updateRequestIsActive(requestPath) {
73
74
  }
74
75
  let requestedSignal = null;
75
76
  let child = null;
77
+ // Keep these in step with src/utils/daemon-helper-lifetime.ts. This file is
78
+ // staged alone and cannot import that module.
79
+ const OWNER_POLL_MS = 500;
80
+ const OWNER_HANDOFF_RECHECK_MS = 1_000;
81
+ const OWNER_HANDOFF_MAX_AGE_MS = 5 * 60_000;
82
+ const CHILD_STOP_GRACE_MS = 2_000;
83
+ let ownerState = "bound";
84
+ let ownerPoll;
85
+ const ownerSockets = [];
76
86
  const forwardedSignals = process.platform === "win32"
77
87
  ? ["SIGINT", "SIGTERM"]
78
88
  : ["SIGINT", "SIGTERM", "SIGHUP"];
@@ -83,10 +93,179 @@ for (const signal of forwardedSignals) {
83
93
  child.kill(signal);
84
94
  });
85
95
  }
96
+ function readProcStart(pid) {
97
+ try {
98
+ const text = fs.readFileSync(`/proc/${pid}/stat`, "utf8");
99
+ const close = text.lastIndexOf(")");
100
+ if (close < 0)
101
+ return null;
102
+ const rest = text.slice(close + 1).trim().split(/\s+/);
103
+ if (rest[0] === "Z" || rest[0] === "X")
104
+ return null;
105
+ const start = Number(rest[19]);
106
+ return Number.isInteger(start) ? start : null;
107
+ }
108
+ catch {
109
+ return null;
110
+ }
111
+ }
112
+ function parentStillOwns(pid, start) {
113
+ if (!Number.isInteger(pid) || pid <= 1)
114
+ return false;
115
+ try {
116
+ process.kill(pid, 0);
117
+ }
118
+ catch (error) {
119
+ if (error.code !== "EPERM")
120
+ return false;
121
+ }
122
+ if (start === null)
123
+ return true;
124
+ const current = readProcStart(pid);
125
+ if (current === null)
126
+ return false;
127
+ return current === start;
128
+ }
129
+ function handoffKeepsUs() {
130
+ const file = process.env.HQ_DAEMON_HANDOFF_PATH;
131
+ if (!file)
132
+ return false;
133
+ let record;
134
+ try {
135
+ record = JSON.parse(fs.readFileSync(file, "utf8"));
136
+ }
137
+ catch {
138
+ return false;
139
+ }
140
+ const releasedAt = record.releasedAt;
141
+ if (typeof releasedAt !== "number" || !Number.isFinite(releasedAt))
142
+ return false;
143
+ if (Date.now() - releasedAt > OWNER_HANDOFF_MAX_AGE_MS)
144
+ return false;
145
+ if (!Array.isArray(record.units))
146
+ return false;
147
+ const selfStart = readProcStart(process.pid);
148
+ return record.units.some((unit) => {
149
+ if (!unit || typeof unit !== "object")
150
+ return false;
151
+ const row = unit;
152
+ if (row.pid !== process.pid)
153
+ return false;
154
+ if (typeof row.start === "number" && selfStart !== null && row.start !== selfStart)
155
+ return false;
156
+ return true;
157
+ });
158
+ }
159
+ function descriptorIsPipe(fd) {
160
+ try {
161
+ const stat = fs.fstatSync(fd);
162
+ // Node's "pipe" stdio is a socketpair on macOS and Linux, not a FIFO.
163
+ // /dev/null is a character device, so ignored stdin still does not match.
164
+ return stat.isFIFO() || stat.isSocket();
165
+ }
166
+ catch {
167
+ return false;
168
+ }
169
+ }
170
+ function stopOwnerWatch() {
171
+ if (ownerPoll)
172
+ clearInterval(ownerPoll);
173
+ ownerPoll = undefined;
174
+ for (const socket of ownerSockets.splice(0)) {
175
+ socket.removeAllListeners("end");
176
+ socket.removeAllListeners("close");
177
+ socket.on("error", () => { });
178
+ socket.destroy();
179
+ }
180
+ }
181
+ function stopOwnedChild() {
182
+ if (!child?.pid || child.exitCode !== null || child.signalCode !== null)
183
+ return;
184
+ try {
185
+ child.kill("SIGTERM");
186
+ }
187
+ catch {
188
+ // The command is already gone.
189
+ }
190
+ const timer = setTimeout(() => {
191
+ if (child && child.exitCode === null && child.signalCode === null) {
192
+ try {
193
+ child.kill("SIGKILL");
194
+ }
195
+ catch {
196
+ // The command is already gone.
197
+ }
198
+ }
199
+ }, CHILD_STOP_GRACE_MS);
200
+ timer.unref();
201
+ }
202
+ async function onOwnerLost() {
203
+ if (ownerState !== "bound")
204
+ return;
205
+ ownerState = "stopping";
206
+ if (process.env.HQ_DAEMON_HANDOFF_PATH) {
207
+ const deadline = Date.now() + OWNER_HANDOFF_RECHECK_MS;
208
+ while (Date.now() < deadline) {
209
+ if (handoffKeepsUs()) {
210
+ ownerState = "detached";
211
+ stopOwnerWatch();
212
+ return;
213
+ }
214
+ await new Promise((resolve) => setTimeout(resolve, 50));
215
+ }
216
+ }
217
+ if (handoffKeepsUs()) {
218
+ ownerState = "detached";
219
+ stopOwnerWatch();
220
+ return;
221
+ }
222
+ stopOwnerWatch();
223
+ stopOwnedChild();
224
+ }
225
+ function watchPipeEof(fd) {
226
+ // /dev/null is a character device, not a pipe, so its immediate EOF is not
227
+ // the parent leaving. A FIFO or a Node pipe socket is an owner-control channel.
228
+ // fs.ReadStream has no unref, and a referenced stream would keep this process
229
+ // up after the command exits. A socket can be unref'd.
230
+ if (!descriptorIsPipe(fd))
231
+ return;
232
+ let socket;
233
+ try {
234
+ socket = new net.Socket({ fd, readable: true, writable: false });
235
+ }
236
+ catch {
237
+ return;
238
+ }
239
+ ownerSockets.push(socket);
240
+ socket.on("end", () => { void onOwnerLost(); });
241
+ socket.on("error", () => { });
242
+ socket.resume();
243
+ socket.unref();
244
+ }
245
+ function startOwnerWatch() {
246
+ const parentPid = process.ppid;
247
+ const parentStart = readProcStart(parentPid);
248
+ // stdin "ignore" is /dev/null, which is not a pipe, so this stays quiet.
249
+ // An inherited extra fd is not the owner channel unless the daemon passed
250
+ // HQ_DAEMON_OWNER_CONTROL_FD with the pipe it opened for us.
251
+ watchPipeEof(0);
252
+ const controlFd = Number(process.env.HQ_DAEMON_OWNER_CONTROL_FD);
253
+ if (Number.isInteger(controlFd) && controlFd >= 0)
254
+ watchPipeEof(controlFd);
255
+ if (parentPid <= 1)
256
+ return;
257
+ ownerPoll = setInterval(() => {
258
+ if (!parentStillOwns(parentPid, parentStart))
259
+ void onOwnerLost();
260
+ }, OWNER_POLL_MS);
261
+ ownerPoll.unref();
262
+ }
86
263
  async function waitForRequestToClear(requestPath, started) {
87
264
  while (updateRequestIsActive(requestPath)) {
88
265
  if (requestedSignal)
89
266
  throw new Error(`Interrupted by ${requestedSignal}`);
267
+ if (ownerState === "stopping")
268
+ throw new Error("The daemon parent exited");
90
269
  if (Date.now() - started >= LEASE_WAIT_MS)
91
270
  throw new Error("The HQ CLI package is being updated; retry after it finishes");
92
271
  await new Promise((resolve) => setTimeout(resolve, 100));
@@ -157,6 +336,7 @@ async function run() {
157
336
  const [prefix, version, ...rawArgs] = process.argv.slice(2);
158
337
  if (!prefix || !version)
159
338
  throw new Error("The daemon hq bootstrap arguments are invalid");
339
+ startOwnerWatch();
160
340
  const watchHandoff = rawArgs[0] !== "--handoff-watch=off";
161
341
  const args = watchHandoff ? rawArgs : rawArgs.slice(1);
162
342
  const lease = await acquireBootstrapLease(prefix, version);
@@ -173,14 +353,29 @@ async function run() {
173
353
  try {
174
354
  if (requestedSignal)
175
355
  return relaySignal(requestedSignal);
356
+ if (ownerState === "stopping")
357
+ throw new Error("The daemon parent exited");
176
358
  // This resolution is deliberately after the update request is clear and
177
359
  // after the bootstrap lease record protects the package from replacement.
178
360
  const entry = resolveInstalledEntry(prefix);
179
361
  child = spawn(process.execPath, [entry, ...args], {
180
- env: { ...process.env, [HANDOFF_ENV]: token },
181
- stdio: "inherit",
362
+ env: {
363
+ ...process.env,
364
+ [HANDOFF_ENV]: token,
365
+ // The CLI consumes these before it starts anything else. A grandchild
366
+ // must not inherit them: it would exit when its own launcher exited.
367
+ HQ_DAEMON_BOOTSTRAP_CHILD: "1",
368
+ HQ_DAEMON_OWNER_CONTROL_FD: "3",
369
+ },
370
+ // fd 3 is a pipe this process holds. When we exit, including by SIGKILL,
371
+ // the command sees EOF and leaves. stdin stays the parent's stdin.
372
+ stdio: ["inherit", "inherit", "inherit", "pipe"],
182
373
  windowsHide: true,
183
374
  });
375
+ const ownedControl = child.stdio[3];
376
+ if (ownedControl && typeof ownedControl.unref === "function") {
377
+ ownedControl.unref();
378
+ }
184
379
  child.once("error", (error) => {
185
380
  process.stderr.write(`hq daemon child bootstrap could not start the CLI (${error.code ?? error.name})\n`);
186
381
  });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * cwd -> company resolution through the per-user registry, shared by hqd and
3
+ * by `hq mcp serve` when it answers local tools without hqd.
4
+ */
5
+ import { readRegistry, type ResolveResult } from "../registry/registry.js";
6
+ import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
7
+ /** Resolve cwd → company through the registry, cached until registry.json changes. */
8
+ export declare function createResolver(registryPath: string, options?: {
9
+ hqRoot?: string;
10
+ log?: (level: "info" | "warn" | "error", message: string) => void;
11
+ readRegistry?: typeof readRegistry;
12
+ readCompaniesManifest?: typeof readCompaniesManifestMap;
13
+ }): (cwd: string) => ResolveResult;
14
+ //# sourceMappingURL=resolver.d.ts.map
@@ -0,0 +1,96 @@
1
+ /**
2
+ * cwd -> company resolution through the per-user registry, shared by hqd and
3
+ * by `hq mcp serve` when it answers local tools without hqd.
4
+ */
5
+ import * as fs from "node:fs";
6
+ import * as path from "node:path";
7
+ import { canonicalDir, emptyRegistry, readRegistry, resolveCompanyForDir } from "../registry/registry.js";
8
+ import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
9
+ /** Resolve cwd → company through the registry, cached until registry.json changes. */
10
+ export function createResolver(registryPath, options = {}) {
11
+ const loadRegistry = options.readRegistry ?? readRegistry;
12
+ const loadCompaniesManifest = options.readCompaniesManifest ?? readCompaniesManifestMap;
13
+ const cache = new Map();
14
+ let registryStamp = "";
15
+ let registry = emptyRegistry();
16
+ let registryLoadFailed = false;
17
+ let manifestStamp = "";
18
+ let companies = null;
19
+ let manifestLoadFailed = false;
20
+ return (cwd) => {
21
+ let currentRegistryStamp = "missing";
22
+ try {
23
+ const st = fs.statSync(registryPath);
24
+ currentRegistryStamp = `${st.mtimeMs}:${st.ctimeMs}:${st.size}:${st.ino}:${st.mode}`;
25
+ }
26
+ catch (err) {
27
+ const code = err.code;
28
+ if (code !== "ENOENT") {
29
+ cache.clear();
30
+ const detail = err instanceof Error ? err.message : String(err);
31
+ options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
32
+ return { company: null, reason: "HQ registry is unavailable; using personal context." };
33
+ }
34
+ }
35
+ if (currentRegistryStamp !== registryStamp) {
36
+ cache.clear();
37
+ registryStamp = currentRegistryStamp;
38
+ registryLoadFailed = false;
39
+ if (currentRegistryStamp === "missing") {
40
+ registry = emptyRegistry();
41
+ }
42
+ else {
43
+ try {
44
+ registry = loadRegistry(registryPath);
45
+ }
46
+ catch (err) {
47
+ registryLoadFailed = true;
48
+ const detail = err instanceof Error ? err.message : String(err);
49
+ options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
50
+ }
51
+ }
52
+ }
53
+ if (registryLoadFailed) {
54
+ return { company: null, reason: "HQ registry is unavailable; using personal context." };
55
+ }
56
+ const key = canonicalDir(cwd);
57
+ const result = cache.get(key) ?? resolveCompanyForDir(registry, key);
58
+ cache.set(key, result);
59
+ if (result.company && options.hqRoot) {
60
+ const manifestPath = path.join(options.hqRoot, "companies", "manifest.yaml");
61
+ let currentManifestStamp;
62
+ try {
63
+ const st = fs.statSync(manifestPath);
64
+ currentManifestStamp = `${st.mtimeMs}:${st.ctimeMs}:${st.size}:${st.ino}:${st.mode}`;
65
+ }
66
+ catch (err) {
67
+ const code = err.code;
68
+ currentManifestStamp = code === "ENOENT" ? "missing" : `unavailable:${code ?? "unknown"}`;
69
+ }
70
+ if (currentManifestStamp !== manifestStamp) {
71
+ manifestStamp = currentManifestStamp;
72
+ companies = null;
73
+ manifestLoadFailed = false;
74
+ if (currentManifestStamp === "missing" || currentManifestStamp.startsWith("unavailable:")) {
75
+ manifestLoadFailed = true;
76
+ }
77
+ else {
78
+ companies = loadCompaniesManifest(options.hqRoot);
79
+ manifestLoadFailed = companies === null;
80
+ }
81
+ if (manifestLoadFailed) {
82
+ options.log?.("warn", "hqd companies/manifest.yaml unavailable or malformed; using personal context");
83
+ }
84
+ }
85
+ if (manifestLoadFailed || !companies) {
86
+ return { company: null, reason: "HQ company manifest is unavailable; using personal context." };
87
+ }
88
+ if (!Object.hasOwn(companies, result.company)) {
89
+ options.log?.("warn", `hqd registry company ${result.company} is not present in companies/manifest.yaml; using personal context`);
90
+ return { company: null, reason: `Registry company ${result.company} is not present in companies/manifest.yaml; using personal context.` };
91
+ }
92
+ }
93
+ return result;
94
+ };
95
+ }
96
+ //# sourceMappingURL=resolver.js.map
@@ -140,6 +140,16 @@ export declare function rotateLogs(logsDir: string, maxBytes?: number): number;
140
140
  * an on-failure unit down. The daemon's updater handles CLI updates.
141
141
  */
142
142
  export declare function unitProcessEnv(base: NodeJS.ProcessEnv, unit: UnitPlan): NodeJS.ProcessEnv;
143
+ /**
144
+ * Environment added on top of `unitProcessEnv` for one spawned process.
145
+ * An hq command gets the handoff path, when this daemon can leave services
146
+ * behind for the next one, and an owner-control fd so it can see the parent
147
+ * leave even if it is killed before it can signal. Node and exec runners do
148
+ * not get either value.
149
+ */
150
+ export declare function daemonChildOwnershipEnv(base: NodeJS.ProcessEnv, unit: UnitPlan, handoffPath: string | null): NodeJS.ProcessEnv;
151
+ type DaemonStdioSlot = "ignore" | "pipe" | "inherit" | number;
152
+ export declare function daemonChildStdio(stdio: readonly [DaemonStdioSlot, DaemonStdioSlot, DaemonStdioSlot], trackOwner: boolean): DaemonStdioSlot[];
143
153
  /**
144
154
  * A systemd system unit starts the daemon as the login user without the
145
155
  * variables a login session sets, so `systemctl --user` from its services
@@ -152,4 +162,5 @@ export declare function withUserRuntimeDir(env: NodeJS.ProcessEnv, host: {
152
162
  exists: (dir: string) => boolean;
153
163
  }): NodeJS.ProcessEnv;
154
164
  export declare function runDaemon(opts: RunDaemonOptions): Promise<number>;
165
+ export {};
155
166
  //# sourceMappingURL=run.d.ts.map
@@ -532,6 +532,17 @@ function makeLogger(paths, foreground) {
532
532
  (level === "info" ? process.stdout : process.stderr).write(line);
533
533
  };
534
534
  }
535
+ /**
536
+ * One-shot marks the direct hq helper consumes. A node or exec runner never
537
+ * enters the CLI, so it never clears them. Copying them onto that runner makes
538
+ * every hq it starts skip Sentry and arm the owner watch.
539
+ */
540
+ const DAEMON_CHILD_ONE_SHOT_KEYS = [
541
+ "HQ_DAEMON_BOOTSTRAP_CHILD",
542
+ "HQ_DAEMON_RESIDENT",
543
+ "HQ_DAEMON_OWNER_CONTROL_FD",
544
+ "HQ_DAEMON_HANDOFF_PATH",
545
+ ];
535
546
  /**
536
547
  * Environment for one service process. The CLI's own update check is off:
537
548
  * a child that updates itself exits 0 and asks to be rerun, which would leave
@@ -539,10 +550,43 @@ function makeLogger(paths, foreground) {
539
550
  */
540
551
  export function unitProcessEnv(base, unit) {
541
552
  const env = { ...base, ...unit.env, HQ_DAEMON_UNIT: unit.id, HQ_NO_UPDATE_CHECK: "1" };
553
+ for (const key of DAEMON_CHILD_ONE_SHOT_KEYS)
554
+ delete env[key];
555
+ // Scheduled hq commands stay eligible for Sentry. The resident mark goes only
556
+ // to a long-running hq command, which clears it before starting another hq
557
+ // command. A sync runner, sync-core engine, or outpost node runner must not
558
+ // carry the mark.
559
+ if (unit.kind === "long-running" && unit.command?.type === "hq")
560
+ env.HQ_DAEMON_RESIDENT = "1";
542
561
  if (unit.service === "sync")
543
562
  env.NODE_OPTIONS = syncRunnerNodeOptions(env);
544
563
  return env;
545
564
  }
565
+ /**
566
+ * Environment added on top of `unitProcessEnv` for one spawned process.
567
+ * An hq command gets the handoff path, when this daemon can leave services
568
+ * behind for the next one, and an owner-control fd so it can see the parent
569
+ * leave even if it is killed before it can signal. Node and exec runners do
570
+ * not get either value.
571
+ */
572
+ export function daemonChildOwnershipEnv(base, unit, handoffPath) {
573
+ const env = unitProcessEnv(base, unit);
574
+ if (unit.command?.type === "hq") {
575
+ if (handoffPath)
576
+ env.HQ_DAEMON_HANDOFF_PATH = handoffPath;
577
+ env.HQ_DAEMON_OWNER_CONTROL_FD = "3";
578
+ }
579
+ return env;
580
+ }
581
+ export function daemonChildStdio(stdio, trackOwner) {
582
+ return trackOwner ? [...stdio, "pipe"] : [...stdio];
583
+ }
584
+ function unrefDaemonOwnerControl(child) {
585
+ const control = child.stdio[3];
586
+ if (control && typeof control.unref === "function") {
587
+ control.unref();
588
+ }
589
+ }
546
590
  function isFifo(file) {
547
591
  try {
548
592
  return fs.lstatSync(file).isFIFO();
@@ -1154,6 +1198,8 @@ export async function runDaemon(opts) {
1154
1198
  [file, args] = backgroundQosCommand([file, args], unit.backgroundQos === true);
1155
1199
  const logPath = paths.unitLogPath(unit.id);
1156
1200
  const cwd = unit.env.HQ_ROOT && fs.existsSync(unit.env.HQ_ROOT) ? unit.env.HQ_ROOT : home;
1201
+ const childEnv = daemonChildOwnershipEnv(env, unit, succession ? succession.handoffPath : null);
1202
+ const trackOwner = command.type === "hq";
1157
1203
  if (unit.heartbeatTimeoutMs && succession) {
1158
1204
  // The supervisor reads this unit's protocol heartbeats from stdout. Where
1159
1205
  // services can outlive the daemon, stdout is a FIFO (see protocol-tail.ts)
@@ -1166,10 +1212,12 @@ export async function runDaemon(opts) {
1166
1212
  try {
1167
1213
  const child = spawn(file, args, {
1168
1214
  cwd,
1169
- env: unitProcessEnv(env, unit),
1170
- stdio: ["ignore", outFd, errFd],
1215
+ env: childEnv,
1216
+ stdio: daemonChildStdio(["ignore", outFd, errFd], trackOwner),
1171
1217
  windowsHide: true,
1172
1218
  });
1219
+ if (trackOwner)
1220
+ unrefDaemonOwnerControl(child);
1173
1221
  spawned.add(child);
1174
1222
  if (unit.service === "sync" && child.pid !== undefined)
1175
1223
  daemonSyncRunnerPids.add(child.pid);
@@ -1210,10 +1258,12 @@ export async function runDaemon(opts) {
1210
1258
  logStream.on("error", (err) => log("error", `could not write ${unit.id} log ${logPath}: ${err.message}`));
1211
1259
  const child = spawn(file, args, {
1212
1260
  cwd,
1213
- env: unitProcessEnv(env, unit),
1214
- stdio: ["ignore", "pipe", "pipe"],
1261
+ env: childEnv,
1262
+ stdio: daemonChildStdio(["ignore", "pipe", "pipe"], trackOwner),
1215
1263
  windowsHide: true,
1216
1264
  });
1265
+ if (trackOwner)
1266
+ unrefDaemonOwnerControl(child);
1217
1267
  spawned.add(child);
1218
1268
  if (unit.service === "sync" && child.pid !== undefined)
1219
1269
  daemonSyncRunnerPids.add(child.pid);
@@ -1231,10 +1281,12 @@ export async function runDaemon(opts) {
1231
1281
  try {
1232
1282
  const child = spawn(file, args, {
1233
1283
  cwd,
1234
- env: unitProcessEnv(env, unit),
1235
- stdio: ["ignore", fd, fd],
1284
+ env: childEnv,
1285
+ stdio: daemonChildStdio(["ignore", fd, fd], trackOwner),
1236
1286
  windowsHide: true,
1237
1287
  });
1288
+ if (trackOwner)
1289
+ unrefDaemonOwnerControl(child);
1238
1290
  spawned.add(child);
1239
1291
  if (unit.service === "sync" && child.pid !== undefined)
1240
1292
  daemonSyncRunnerPids.add(child.pid);
@@ -7,8 +7,8 @@
7
7
  * register themselves here.
8
8
  */
9
9
  import * as fs from "node:fs";
10
- import { readRegistry, type ResolveResult } from "../registry/registry.js";
11
- import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
10
+ import { createResolver } from "./resolver.js";
11
+ export { createResolver };
12
12
  import { SessionRegistry } from "./session-registry.js";
13
13
  import { HqMcpBridge, type RunWorkerRequest } from "./ops/mcp.js";
14
14
  import { type StdinMachineCredentials } from "./machine-login.js";
@@ -61,13 +61,6 @@ export interface HqdServer {
61
61
  sessions: SessionRegistry;
62
62
  close(): Promise<void>;
63
63
  }
64
- /** Resolve cwd → company through the registry, cached until registry.json changes. */
65
- export declare function createResolver(registryPath: string, options?: {
66
- hqRoot?: string;
67
- log?: HqdServerOptions["log"];
68
- readRegistry?: typeof readRegistry;
69
- readCompaniesManifest?: typeof readCompaniesManifestMap;
70
- }): (cwd: string) => ResolveResult;
71
64
  /** Marker beside the hqd socket; hook shims fail closed only where it (or the socket) exists. */
72
65
  export declare const HQD_ENABLED_MARKER = "hqd.enabled";
73
66
  /**
@@ -11,8 +11,9 @@ import * as net from "node:net";
11
11
  import * as path from "node:path";
12
12
  import { performance } from "node:perf_hooks";
13
13
  import { CLI_VERSION } from "../../cli-version.js";
14
- import { canonicalDir, emptyRegistry, readRegistry, registryFile, resolveCompanyForDir } from "../registry/registry.js";
15
- import { readCompaniesManifestMap } from "../work-context/repo-remote.js";
14
+ import { canonicalDir, registryFile } from "../registry/registry.js";
15
+ import { createResolver } from "./resolver.js";
16
+ export { createResolver };
16
17
  import { createLineSplitter, encodeMessage, HQD_DEFAULT_REQUEST_TIMEOUT_MS, HQD_MAX_LINE_BYTES, parseRequestLine } from "./protocol.js";
17
18
  import { SessionRegistry } from "./session-registry.js";
18
19
  import { sessionMetaCompany } from "../core-utils/session-company.js";
@@ -110,93 +111,6 @@ function stringArg(args, name, required = true) {
110
111
  return undefined;
111
112
  throw new OpError("bad_args", `${name} must be a non-empty string`);
112
113
  }
113
- /** Resolve cwd → company through the registry, cached until registry.json changes. */
114
- export function createResolver(registryPath, options = {}) {
115
- const loadRegistry = options.readRegistry ?? readRegistry;
116
- const loadCompaniesManifest = options.readCompaniesManifest ?? readCompaniesManifestMap;
117
- const cache = new Map();
118
- let registryStamp = "";
119
- let registry = emptyRegistry();
120
- let registryLoadFailed = false;
121
- let manifestStamp = "";
122
- let companies = null;
123
- let manifestLoadFailed = false;
124
- return (cwd) => {
125
- let currentRegistryStamp = "missing";
126
- try {
127
- const st = fs.statSync(registryPath);
128
- currentRegistryStamp = `${st.mtimeMs}:${st.ctimeMs}:${st.size}:${st.ino}:${st.mode}`;
129
- }
130
- catch (err) {
131
- const code = err.code;
132
- if (code !== "ENOENT") {
133
- cache.clear();
134
- const detail = err instanceof Error ? err.message : String(err);
135
- options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
136
- return { company: null, reason: "HQ registry is unavailable; using personal context." };
137
- }
138
- }
139
- if (currentRegistryStamp !== registryStamp) {
140
- cache.clear();
141
- registryStamp = currentRegistryStamp;
142
- registryLoadFailed = false;
143
- if (currentRegistryStamp === "missing") {
144
- registry = emptyRegistry();
145
- }
146
- else {
147
- try {
148
- registry = loadRegistry(registryPath);
149
- }
150
- catch (err) {
151
- registryLoadFailed = true;
152
- const detail = err instanceof Error ? err.message : String(err);
153
- options.log?.("warn", `hqd registry unavailable; using personal context: ${detail}`);
154
- }
155
- }
156
- }
157
- if (registryLoadFailed) {
158
- return { company: null, reason: "HQ registry is unavailable; using personal context." };
159
- }
160
- const key = canonicalDir(cwd);
161
- const result = cache.get(key) ?? resolveCompanyForDir(registry, key);
162
- cache.set(key, result);
163
- if (result.company && options.hqRoot) {
164
- const manifestPath = path.join(options.hqRoot, "companies", "manifest.yaml");
165
- let currentManifestStamp;
166
- try {
167
- const st = fs.statSync(manifestPath);
168
- currentManifestStamp = `${st.mtimeMs}:${st.ctimeMs}:${st.size}:${st.ino}:${st.mode}`;
169
- }
170
- catch (err) {
171
- const code = err.code;
172
- currentManifestStamp = code === "ENOENT" ? "missing" : `unavailable:${code ?? "unknown"}`;
173
- }
174
- if (currentManifestStamp !== manifestStamp) {
175
- manifestStamp = currentManifestStamp;
176
- companies = null;
177
- manifestLoadFailed = false;
178
- if (currentManifestStamp === "missing" || currentManifestStamp.startsWith("unavailable:")) {
179
- manifestLoadFailed = true;
180
- }
181
- else {
182
- companies = loadCompaniesManifest(options.hqRoot);
183
- manifestLoadFailed = companies === null;
184
- }
185
- if (manifestLoadFailed) {
186
- options.log?.("warn", "hqd companies/manifest.yaml unavailable or malformed; using personal context");
187
- }
188
- }
189
- if (manifestLoadFailed || !companies) {
190
- return { company: null, reason: "HQ company manifest is unavailable; using personal context." };
191
- }
192
- if (!Object.hasOwn(companies, result.company)) {
193
- options.log?.("warn", `hqd registry company ${result.company} is not present in companies/manifest.yaml; using personal context`);
194
- return { company: null, reason: `Registry company ${result.company} is not present in companies/manifest.yaml; using personal context.` };
195
- }
196
- }
197
- return result;
198
- };
199
- }
200
114
  /** Is something answering on this socket? */
201
115
  function socketIsLive(socketPath) {
202
116
  return new Promise((resolve) => {
@@ -26,6 +26,7 @@ import * as path from "node:path";
26
26
  import { GATE_PROFILES, activeGateProfile, gateMembership, parseHookGateProfiles, requiredMissingProfiles, } from "../hook-gate-profiles.js";
27
27
  import { modeIsExecutable } from "../shared.js";
28
28
  import { countStrayGateEntries } from "../stray-gate-entries.js";
29
+ import { findDuplicateHookRegistrations } from "../duplicate-hook-registrations.js";
29
30
  /** Common id prefix for every result this check family emits. */
30
31
  export const CLAUDE_WIRING_PREFIX = "hooks.claude";
31
32
  /**
@@ -88,6 +89,46 @@ export function checkClaudeWiring(context) {
88
89
  message: `.claude/${file} has no stray matcher-less hook-gate registrations.`,
89
90
  });
90
91
  }
92
+ // --- Doubled hooks: the same registration in both settings files ------------
93
+ // Claude Code runs every registered command, so a hook present in
94
+ // settings.json and again in settings.local.json (or twice in one file) runs
95
+ // twice per event (feedback a73db922). Local copies are auto-fixable; a repeat
96
+ // inside the release-owned settings.json is reported only.
97
+ if (base.present && !base.invalid) {
98
+ const localValue = local.present && !local.invalid ? local.value : {};
99
+ const dupes = findDuplicateHookRegistrations(base.value, localValue);
100
+ const baseTarget = path.join(claudeDir, "settings.json");
101
+ const localTarget = path.join(claudeDir, "settings.local.json");
102
+ if (dupes.localDuplicates > 0) {
103
+ const n = dupes.localDuplicates;
104
+ results.push({
105
+ status: "WARN",
106
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
107
+ target: localTarget,
108
+ message: `.claude/settings.local.json registers ${n} hook command${n === 1 ? "" : "s"} that settings.json (or an earlier line of the same file) already registers for the same event, ` +
109
+ `so ${n === 1 ? "it runs" : "they run"} twice. Doubled hooks enqueue every Work Mesh event twice and start extra background sessions.`,
110
+ remediation: "Run `hq doctor --fix` to remove only the repeated entries from .claude/settings.local.json (settings.json is not touched and the file is backed up first).",
111
+ });
112
+ }
113
+ if (dupes.baseInternalDuplicates > 0) {
114
+ const n = dupes.baseInternalDuplicates;
115
+ results.push({
116
+ status: "WARN",
117
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
118
+ target: baseTarget,
119
+ message: `.claude/settings.json registers ${n} hook command${n === 1 ? "" : "s"} more than once for the same event, so ${n === 1 ? "it runs" : "they run"} twice.`,
120
+ remediation: "settings.json is release-owned: run /update-hq to restore it instead of editing it by hand.",
121
+ });
122
+ }
123
+ if (dupes.localDuplicates === 0 && dupes.baseInternalDuplicates === 0 && local.present && !local.invalid) {
124
+ results.push({
125
+ status: "PASS",
126
+ checkId: `${CLAUDE_WIRING_PREFIX}.duplicate-registration`,
127
+ target: localTarget,
128
+ message: "No hook command is registered twice for the same event across settings.json and settings.local.json.",
129
+ });
130
+ }
131
+ }
91
132
  const scans = registrations.map((reg) => ({
92
133
  reg,
93
134
  scan: scanHookCommand(reg.command),