@indigoai-us/hq-cli 5.345.270 → 5.345.272

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 (52) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/run.d.ts +1 -1
  19. package/dist/lib/daemon/run.js +65 -51
  20. package/dist/lib/daemon/supervisor.js +0 -2
  21. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  22. package/dist/lib/hook-engine/coverage.js +98 -5
  23. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  24. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  25. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  26. package/dist/lib/hot-channels/signals-pass.js +13 -3
  27. package/dist/lib/signals/engine.d.ts +0 -2
  28. package/dist/lib/signals/engine.js +12 -7
  29. package/dist/lib/signals/reply.js +35 -82
  30. package/dist/lib/signals/run-lock.d.ts +8 -0
  31. package/dist/lib/signals/run-lock.js +42 -7
  32. package/dist/lib/signals/run-record.js +2 -1
  33. package/dist/lib/signals/settings.d.ts +9 -4
  34. package/dist/lib/signals/settings.js +7 -5
  35. package/dist/lib/signals/steps/extract.d.ts +37 -10
  36. package/dist/lib/signals/steps/extract.js +88 -111
  37. package/dist/lib/signals/steps/types.d.ts +3 -2
  38. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  39. package/dist/lib/sync-core/reconcile.js +105 -18
  40. package/dist/lib/sync-core/release.d.ts +52 -2
  41. package/dist/lib/sync-core/release.js +172 -11
  42. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  43. package/dist/lib/sync-core/rollout-state.js +16 -0
  44. package/dist/utils/client-health-contract.d.ts +32 -0
  45. package/dist/utils/client-health-contract.js +35 -0
  46. package/dist/utils/client-health.d.ts +43 -0
  47. package/dist/utils/client-health.js +106 -3
  48. package/dist/utils/login-browser.d.ts +1 -0
  49. package/dist/utils/login-browser.js +31 -6
  50. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  51. package/dist/utils/spawn-detached-hidden.js +222 -0
  52. package/package.json +7 -7
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Daemon-side handlers for the four request note kinds left by the native
3
+ * Work Mesh core-shims member (`crates/hq-hook/src/work_mesh_shims.rs`):
4
+ *
5
+ * - `work-mesh-register`: `bash <root>/core/hooks/work-mesh-register.sh __bg__`
6
+ * - `work-mesh-sweep`: `bash <root>/core/hooks/work-mesh-close.sh __sweep_bg__`
7
+ * - `work-mesh-ground`: `bash <root>/core/hooks/work-mesh-ground.sh <event>`
8
+ * (prompt in `.body`, passed on stdin as JSON)
9
+ * - `work-mesh-close`: `bash <root>/core/hooks/work-mesh-close.sh __close_bg__`
10
+ *
11
+ * Each note carries validated typed fields only (never an argv or environment
12
+ * dump). A root without the target body script is done (`code: 0`). Output
13
+ * goes to `<root>/workspace/logs/work-mesh-hook.log`, matching the detached
14
+ * shell jobs. A run that ends on its own is done (`code: 0`); a timeout,
15
+ * abort, spawn failure, or unreadable log file is a failed try (`code: 1`).
16
+ */
17
+ import * as fs from "node:fs";
18
+ import * as path from "node:path";
19
+ // A cycle with hook-requests.ts, which dispatches to this module: each side uses the other only inside functions.
20
+ import { spawnRequestProgram } from "./hook-requests.js";
21
+ export const WORK_MESH_SHIM_SCRIPTS = {
22
+ "work-mesh-register": "core/hooks/work-mesh-register.sh",
23
+ "work-mesh-sweep": "core/hooks/work-mesh-close.sh",
24
+ "work-mesh-ground": "core/hooks/work-mesh-ground.sh",
25
+ "work-mesh-close": "core/hooks/work-mesh-close.sh",
26
+ };
27
+ export const WORK_MESH_SHIM_LOG = "workspace/logs/work-mesh-hook.log";
28
+ const SAFE_SESSION = /^[A-Za-z0-9][A-Za-z0-9._-]{0,511}$/;
29
+ const SAFE_SLUG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
30
+ const SAFE_UID = /^[A-Za-z0-9._-]{1,128}$/;
31
+ const SAFE_EVENT = /^[A-Za-z]{1,64}$/;
32
+ const plain = (s) => typeof s === "string" && !s.includes("\0");
33
+ const bounded = (s, maxBytes, nonEmpty = false) => plain(s) && (!nonEmpty || s.length > 0) && Buffer.byteLength(s) <= maxBytes;
34
+ const exactKeys = (args, expected) => {
35
+ const keys = Object.keys(args).sort();
36
+ return keys.length === expected.length && keys.every((key, i) => key === expected[i]);
37
+ };
38
+ export function isWorkMeshShimKind(kind) {
39
+ return kind === "work-mesh-register"
40
+ || kind === "work-mesh-sweep"
41
+ || kind === "work-mesh-ground"
42
+ || kind === "work-mesh-close";
43
+ }
44
+ export function parseWorkMeshShim(kind, args, session) {
45
+ switch (kind) {
46
+ case "work-mesh-register": {
47
+ if (!exactKeys(args, ["binding", "category", "harness", "intent", "project", "session_id", "slug", "uid"]))
48
+ return undefined;
49
+ const { session_id: sessionId, slug, uid, project, binding, category, intent, harness } = args;
50
+ if (!plain(sessionId) || !SAFE_SESSION.test(sessionId) || sessionId !== session)
51
+ return undefined;
52
+ if (!plain(slug) || !SAFE_SLUG.test(slug))
53
+ return undefined;
54
+ if (!plain(uid) || (uid !== "" && !SAFE_UID.test(uid)))
55
+ return undefined;
56
+ if (!bounded(project, 256))
57
+ return undefined;
58
+ if (binding !== "project" && binding !== "adhoc")
59
+ return undefined;
60
+ if (!bounded(category, 128, true))
61
+ return undefined;
62
+ if (!bounded(intent, 1120))
63
+ return undefined;
64
+ if (!bounded(harness, 128, true))
65
+ return undefined;
66
+ return { kind, sessionId, slug, uid, project, binding, category, intent, harness };
67
+ }
68
+ case "work-mesh-sweep": {
69
+ if (Object.keys(args).length !== 0)
70
+ return undefined;
71
+ return { kind };
72
+ }
73
+ case "work-mesh-ground": {
74
+ if (!exactKeys(args, ["company", "event", "project", "session_id"]))
75
+ return undefined;
76
+ const { event, session_id: sessionId, company, project } = args;
77
+ if (!plain(event) || !SAFE_EVENT.test(event))
78
+ return undefined;
79
+ if (!plain(sessionId) || (sessionId !== "" && !SAFE_SESSION.test(sessionId)) || sessionId !== session)
80
+ return undefined;
81
+ if (!plain(company) || (company !== "" && !SAFE_SLUG.test(company)))
82
+ return undefined;
83
+ if (!bounded(project, 256))
84
+ return undefined;
85
+ return { kind, event, sessionId, company, project };
86
+ }
87
+ case "work-mesh-close": {
88
+ if (!exactKeys(args, ["category", "harness", "hint", "intent", "project", "session_id", "summary"]))
89
+ return undefined;
90
+ const { session_id: sessionId, hint, project, category, intent, harness, summary } = args;
91
+ if (!plain(sessionId) || !SAFE_SESSION.test(sessionId) || sessionId !== session)
92
+ return undefined;
93
+ if (!bounded(hint, 3500))
94
+ return undefined;
95
+ if (!bounded(project, 256))
96
+ return undefined;
97
+ if (!bounded(category, 128, true))
98
+ return undefined;
99
+ if (!bounded(intent, 1120))
100
+ return undefined;
101
+ if (!bounded(harness, 128, true))
102
+ return undefined;
103
+ if (!bounded(summary, 1024))
104
+ return undefined;
105
+ return { kind, sessionId, hint, project, category, intent, harness, summary };
106
+ }
107
+ }
108
+ }
109
+ function decodeGroundPrompt(body) {
110
+ if (!body || body.includes(0))
111
+ return undefined;
112
+ try {
113
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body);
114
+ }
115
+ catch {
116
+ return undefined;
117
+ }
118
+ }
119
+ export async function runWorkMeshShim(request, operation, base, options) {
120
+ const script = path.join(request.root, WORK_MESH_SHIM_SCRIPTS[operation.kind]);
121
+ try {
122
+ if (!fs.statSync(script).isFile())
123
+ return { code: 0 };
124
+ }
125
+ catch {
126
+ return { code: 0 };
127
+ }
128
+ let stdinPayload;
129
+ let argv;
130
+ const env = { ...base };
131
+ // Session kill switches were already evaluated by the native hook.
132
+ delete env.HQ_WORK_MESH_DISABLED;
133
+ delete env.HQ_DISABLED_HOOKS;
134
+ Object.assign(env, {
135
+ HQ_ROOT: request.root,
136
+ WM_ROOT: request.root,
137
+ HQ_HOOK_REQUEST_ID: request.id,
138
+ });
139
+ switch (operation.kind) {
140
+ case "work-mesh-register":
141
+ argv = [script, "__bg__"];
142
+ Object.assign(env, {
143
+ WM_SID: operation.sessionId,
144
+ WM_SLUG: operation.slug,
145
+ WM_UID: operation.uid,
146
+ WM_PROJECT: operation.project,
147
+ WM_BINDING: operation.binding,
148
+ WM_CATEGORY: operation.category,
149
+ WM_INTENT: operation.intent,
150
+ WM_HARNESS: operation.harness,
151
+ });
152
+ break;
153
+ case "work-mesh-sweep":
154
+ argv = [script, "__sweep_bg__"];
155
+ break;
156
+ case "work-mesh-close":
157
+ argv = [script, "__close_bg__"];
158
+ Object.assign(env, {
159
+ WM_SID: operation.sessionId,
160
+ WM_HINT: operation.hint,
161
+ WM_HARNESS: operation.harness,
162
+ WM_PROJECT: operation.project,
163
+ WM_CATEGORY: operation.category,
164
+ WM_INTENT: operation.intent,
165
+ WM_SUMMARY: operation.summary,
166
+ });
167
+ break;
168
+ case "work-mesh-ground": {
169
+ const prompt = decodeGroundPrompt(request.body);
170
+ if (prompt === undefined) {
171
+ options.log?.(`Hook request ${request.stem}: invalid work-mesh-ground prompt body; deleted, nothing was run`);
172
+ return { code: 0 };
173
+ }
174
+ argv = [script, operation.event];
175
+ env.CLAUDE_PROJECT_DIR = request.root;
176
+ if (operation.sessionId !== "") {
177
+ env.HQ_SESSION_ID = operation.sessionId;
178
+ }
179
+ else {
180
+ delete env.HQ_SESSION_ID;
181
+ }
182
+ stdinPayload = JSON.stringify({
183
+ prompt,
184
+ hook_event_name: operation.event,
185
+ ...(operation.sessionId !== "" ? { session_id: operation.sessionId } : {}),
186
+ });
187
+ break;
188
+ }
189
+ }
190
+ const logFile = path.join(request.root, WORK_MESH_SHIM_LOG);
191
+ let output;
192
+ try {
193
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
194
+ output = fs.openSync(logFile, "a");
195
+ }
196
+ catch (error) {
197
+ options.log?.(`${operation.kind}: ${WORK_MESH_SHIM_LOG} under ${request.root} could not be opened (${String(error)})`);
198
+ return { code: 1 };
199
+ }
200
+ try {
201
+ if (options.signal?.aborted)
202
+ return { code: 1 };
203
+ const stdio = operation.kind === "work-mesh-ground"
204
+ ? ["pipe", "ignore", output]
205
+ : ["ignore", output, output];
206
+ const { child, settle } = spawnRequestProgram("bash", argv, {
207
+ cwd: request.root,
208
+ env,
209
+ windowsHide: true,
210
+ stdio,
211
+ }, {
212
+ timeoutMs: options.timeoutMs,
213
+ killGraceMs: options.killGraceMs,
214
+ ...(options.signal ? { signal: options.signal } : {}),
215
+ });
216
+ if (stdinPayload !== undefined) {
217
+ child.stdin?.on("error", () => undefined);
218
+ child.stdin?.end(stdinPayload);
219
+ }
220
+ return await new Promise(resolve => {
221
+ let settled = false;
222
+ const done = (exited) => {
223
+ if (settled)
224
+ return;
225
+ settled = true;
226
+ const ended = settle();
227
+ resolve({ code: !ended && exited ? 0 : 1 });
228
+ };
229
+ child.once("error", () => done(false));
230
+ child.once("close", (code, signal) => done(code !== null && signal === null));
231
+ });
232
+ }
233
+ finally {
234
+ fs.closeSync(output);
235
+ }
236
+ }
237
+ //# sourceMappingURL=hook-requests-work-mesh-shims.js.map
@@ -55,6 +55,7 @@ import { type MachineCheckResult, type RunMachineChecksOptions } from "./machine
55
55
  import { type MeshToolWritesOperation } from "./hook-requests-mesh-tool-writes.js";
56
56
  import { type FleetLocalPromptOperation, type FleetSessionStartOperation } from "./hook-requests-fleet-session-start.js";
57
57
  import { type ConductLinkOperation } from "./hook-requests-conduct-link.js";
58
+ import { type WorkMeshShimOperation } from "./hook-requests-work-mesh-shims.js";
58
59
  import { type CodexSettingsOperation } from "./hook-requests-codex-settings.js";
59
60
  import { type FleetMembersRefreshOperation } from "./fleet-members-cache.js";
60
61
  /** What the daemon is asked to do. A closed list, the same as `Kind` in daemon_req.rs. */
@@ -111,7 +112,9 @@ export type HookOperation = {
111
112
  /** One machine check run by the daemon for a SessionStart where the hooks own the checks (the machine-check notes at the end of this file). */
112
113
  | MachineCheckOperation | MeshOperation | MeshToolWritesOperation | CodexSettingsOperation | FleetSessionStartOperation | FleetLocalPromptOperation | FleetMembersRefreshOperation
113
114
  /** The Codex adapter's SubagentStop runs of the root's conduct-link hooks (hook-requests-conduct-link.ts). */
114
- | ConductLinkOperation;
115
+ | ConductLinkOperation
116
+ /** The background runs of the five legacy core Work Mesh shims (hook-requests-work-mesh-shims.ts). */
117
+ | WorkMeshShimOperation;
115
118
  /**
116
119
  * One command of a `fleet-local-settings` note, a record of the adapter's `hqad_iter_settings`. Typed fields only: the
117
120
  * daemon builds the program and its arguments (`fleetLocalSettingsProgram`).
@@ -64,6 +64,7 @@ import { MACHINE_CHECKS, machineCheckCollectOnlySupported, runMachineChecks } fr
64
64
  import { parseMeshToolWrites, runMeshToolWrites } from "./hook-requests-mesh-tool-writes.js";
65
65
  import { parseFleetLocalPrompt, parseFleetSessionStart, runFleetLocalPrompt, runFleetSessionStart } from "./hook-requests-fleet-session-start.js";
66
66
  import { isConductLinkKind, parseConductLink, runConductLink } from "./hook-requests-conduct-link.js";
67
+ import { isWorkMeshShimKind, parseWorkMeshShim, runWorkMeshShim } from "./hook-requests-work-mesh-shims.js";
67
68
  import { parseCodexSettings, runCodexSettings } from "./hook-requests-codex-settings.js";
68
69
  import { hqMembersList, parseFleetMembersRefresh, runFleetMembersRefresh } from "./fleet-members-cache.js";
69
70
  /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
@@ -319,6 +320,12 @@ export function parseHookRequest(text, stem) {
319
320
  return undefined;
320
321
  operation = conduct;
321
322
  }
323
+ else if (isWorkMeshShimKind(value.kind)) {
324
+ const shim = parseWorkMeshShim(value.kind, args, value.session);
325
+ if (!shim)
326
+ return undefined;
327
+ operation = shim;
328
+ }
322
329
  else if (value.kind === "codex-settings") {
323
330
  const codex = parseCodexSettings(value.kind, args);
324
331
  if (!codex)
@@ -403,7 +410,8 @@ export function hookRequestHasBody(operation) {
403
410
  || operation.kind === "fleet-local-settings"
404
411
  || operation.kind === "codex-settings"
405
412
  || operation.kind === "fleet-session-start"
406
- || operation.kind === "fleet-local-prompt";
413
+ || operation.kind === "fleet-local-prompt"
414
+ || operation.kind === "work-mesh-ground";
407
415
  }
408
416
  /** The helper a plan-sync request runs, inside the HQ root. */
409
417
  export const PLAN_SYNC_HELPER = "core/scripts/session-project.sh";
@@ -444,6 +452,11 @@ export function hookRequestArguments(request) {
444
452
  // Not a CLI request: the root's own conduct-link hook script is run (`runConductLink`).
445
453
  case "conduct-lanes-link-deliver":
446
454
  case "conduct-link-inherit": return [];
455
+ // Not a CLI request: the root's own work-mesh-*.sh script is run (`runWorkMeshShim`).
456
+ case "work-mesh-register":
457
+ case "work-mesh-sweep":
458
+ case "work-mesh-ground":
459
+ case "work-mesh-close": return [];
447
460
  }
448
461
  }
449
462
  /**
@@ -1675,6 +1688,15 @@ export function executeHookRequest(request, options) {
1675
1688
  timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS,
1676
1689
  }).catch(() => ({ code: 1 }));
1677
1690
  }
1691
+ if (request.operation.kind === "work-mesh-register"
1692
+ || request.operation.kind === "work-mesh-sweep"
1693
+ || request.operation.kind === "work-mesh-ground"
1694
+ || request.operation.kind === "work-mesh-close") {
1695
+ return runWorkMeshShim(request, request.operation, base, {
1696
+ ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
1697
+ timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, ...(options.log ? { log: options.log } : {}),
1698
+ }).catch(() => ({ code: 1 }));
1699
+ }
1678
1700
  if (request.operation.kind === "startwork-prefetch") {
1679
1701
  return runStartworkPrefetch(request, request.operation, base, {
1680
1702
  ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
@@ -366,6 +366,7 @@ async function run() {
366
366
  // must not inherit them: it would exit when its own launcher exited.
367
367
  HQ_DAEMON_BOOTSTRAP_CHILD: "1",
368
368
  HQ_DAEMON_OWNER_CONTROL_FD: "3",
369
+ HQ_DAEMON_UNIT_PARENT_PID: String(process.pid),
369
370
  },
370
371
  // fd 3 is a pipe this process holds. When we exit, including by SIGKILL,
371
372
  // the command sees EOF and leaves. stdin stays the parent's stdin.
@@ -33,6 +33,18 @@ export function installedCliVersionOnDisk(packageRoot, read = (file) => fs.readF
33
33
  return null;
34
34
  }
35
35
  }
36
+ function writeMarker(markerPath, marker) {
37
+ fs.mkdirSync(path.dirname(markerPath), { recursive: true, mode: 0o700 });
38
+ const tmp = `${markerPath}.${process.pid}.tmp`;
39
+ try {
40
+ fs.writeFileSync(tmp, `${JSON.stringify(marker)}\n`, { mode: 0o600 });
41
+ fs.renameSync(tmp, markerPath);
42
+ }
43
+ catch (error) {
44
+ fs.rmSync(tmp, { force: true });
45
+ throw error;
46
+ }
47
+ }
36
48
  /**
37
49
  * Heal a daemon that is already stuck on an older release, which has no
38
50
  * housekeeping check of its own: a unit it starts runs the CLI on disk and can
@@ -53,8 +65,7 @@ export function requestRestartOfOlderParentDaemon(deps) {
53
65
  catch {
54
66
  // no marker yet, or unreadable: ask
55
67
  }
56
- fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
57
- fs.writeFileSync(deps.markerPath, `${JSON.stringify({ pair })}\n`, { mode: 0o600 });
68
+ writeMarker(deps.markerPath, { pair });
58
69
  deps.requestRestart();
59
70
  return true;
60
71
  }
@@ -94,8 +105,7 @@ export function createInstalledCliRestartCheck(deps) {
94
105
  requestedFor = installed;
95
106
  if (deps.markerPath) {
96
107
  try {
97
- fs.mkdirSync(path.dirname(deps.markerPath), { recursive: true, mode: 0o700 });
98
- fs.writeFileSync(deps.markerPath, `${JSON.stringify({ running, installed })}\n`, { mode: 0o600 });
108
+ writeMarker(deps.markerPath, { running, installed });
99
109
  }
100
110
  catch {
101
111
  // Without the marker this process still asks only once; ask now.
@@ -216,7 +216,7 @@ export declare function unitProcessEnv(base: NodeJS.ProcessEnv, unit: UnitPlan):
216
216
  * leave even if it is killed before it can signal. Node and exec runners do
217
217
  * not get either value.
218
218
  */
219
- export declare function daemonChildOwnershipEnv(base: NodeJS.ProcessEnv, unit: UnitPlan, handoffPath: string | null): NodeJS.ProcessEnv;
219
+ export declare function daemonChildOwnershipEnv(base: NodeJS.ProcessEnv, unit: UnitPlan, handoffPath: string | null, daemonPid?: number): NodeJS.ProcessEnv;
220
220
  type DaemonStdioSlot = "ignore" | "pipe" | "inherit" | number;
221
221
  export declare function daemonChildStdio(stdio: readonly [DaemonStdioSlot, DaemonStdioSlot, DaemonStdioSlot], trackOwner: boolean): DaemonStdioSlot[];
222
222
  /**
@@ -79,6 +79,7 @@ import { daemonStartEnv } from "./hook-env.js";
79
79
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
80
80
  import { takeControlRequests, writeControlRequest } from "./requests.js";
81
81
  import { createInstalledCliRestartCheck, installedCliVersionOnDisk } from "./installed-cli-restart.js";
82
+ import { createDaemonRestart, exitWhenStopped, logServicesStopped, servicesAndJobsStopped, stopServicesAndExit, timeoutCap } from "./daemon-restart.js";
82
83
  import { currentHqCloud, currentHqCloudAfterLeaseRelease, hqCloudRunners, hqCloudVersionOlder } from "./hq-cloud.js";
83
84
  import { stageSyncRunnerBundle } from "./sync-runner-bundle.js";
84
85
  import { stageHqChildBootstrap } from "./hq-child-bootstrap-stage.js";
@@ -780,6 +781,7 @@ export function unitProcessEnv(base, unit) {
780
781
  };
781
782
  for (const key of DAEMON_CHILD_ONE_SHOT_KEYS)
782
783
  delete env[key];
784
+ delete env.HQ_DAEMON_UNIT_PARENT_PID;
783
785
  // Scheduled hq commands stay eligible for Sentry. The resident mark goes only
784
786
  // to a long-running hq command, which clears it before starting another hq
785
787
  // command. A sync runner, sync-core engine, or outpost node runner must not
@@ -797,12 +799,14 @@ export function unitProcessEnv(base, unit) {
797
799
  * leave even if it is killed before it can signal. Node and exec runners do
798
800
  * not get either value.
799
801
  */
800
- export function daemonChildOwnershipEnv(base, unit, handoffPath) {
802
+ export function daemonChildOwnershipEnv(base, unit, handoffPath, daemonPid = process.pid) {
801
803
  const env = unitProcessEnv(base, unit);
802
804
  if (unit.command?.type === "hq") {
803
805
  if (handoffPath)
804
806
  env.HQ_DAEMON_HANDOFF_PATH = handoffPath;
805
807
  env.HQ_DAEMON_OWNER_CONTROL_FD = "3";
808
+ // The unit's own parent. The staged launcher replaces it with its pid.
809
+ env.HQ_DAEMON_UNIT_PARENT_PID = String(daemonPid);
806
810
  }
807
811
  return env;
808
812
  }
@@ -2110,7 +2114,11 @@ export async function runDaemon(opts) {
2110
2114
  };
2111
2115
  return await new Promise((resolve) => {
2112
2116
  let stopping = false;
2113
- let restartPending = false;
2117
+ const exitAfter = (hardExitMs) => (code) => {
2118
+ extendSyncShutdownCap = undefined;
2119
+ resolve(code);
2120
+ setTimeout(() => process.exit(code), hardExitMs).unref();
2121
+ };
2114
2122
  const shutdown = (why, exitCode = 0) => {
2115
2123
  if (stopping)
2116
2124
  return;
@@ -2123,25 +2131,30 @@ export async function runDaemon(opts) {
2123
2131
  const stopJobsClosed = closeRuntimeWatchers();
2124
2132
  // Keep shutdown bounded, but let a stopping sync runner reach its persist deadline.
2125
2133
  const cap = createShutdownCap();
2126
- extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
2127
- if (supervisor.hasStoppingSyncRunner())
2128
- cap.extendForSyncRunnerPersist();
2129
- const servicesStopped = supervisor.stop();
2130
- syncPerfForwarder.stop();
2131
- void Promise.race([Promise.all([servicesStopped, stopJobsClosed]).then(([result]) => result), cap.promise]).then((result) => {
2134
+ let servicesStopped;
2135
+ try {
2136
+ extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
2137
+ if (supervisor.hasStoppingSyncRunner())
2138
+ cap.extendForSyncRunnerPersist();
2139
+ servicesStopped = supervisor.stop();
2140
+ syncPerfForwarder.stop();
2141
+ }
2142
+ catch (err) {
2132
2143
  cap.clear();
2133
2144
  extendSyncShutdownCap = undefined;
2134
- if (result === "timeout")
2135
- log("error", "some services did not exit after SIGKILL; releasing the lock anyway");
2136
- else
2137
- log("info", "all services stopped");
2138
- releaseDaemonLock(paths.lockPath);
2139
- resolve(exitCode);
2140
- // Pipes, sockets and unrelated timers can outlive a clean shutdown.
2141
- // Services and the lock are already stopped; unrelated handles should
2142
- // not hold a restart or signal exit open for another service interval.
2143
- setTimeout(() => process.exit(exitCode), 1_000).unref();
2144
- });
2145
+ throw err;
2146
+ }
2147
+ // Pipes, sockets and unrelated timers can outlive a clean shutdown.
2148
+ // Services and the lock are already stopped; unrelated handles should
2149
+ // not hold a restart or signal exit open for another service interval.
2150
+ void exitWhenStopped({
2151
+ stopped: servicesAndJobsStopped(servicesStopped, stopJobsClosed, log),
2152
+ cap,
2153
+ releaseLock: () => releaseDaemonLock(paths.lockPath),
2154
+ exit: exitAfter(1_000),
2155
+ log,
2156
+ onSettled: (result) => logServicesStopped(log, result),
2157
+ }, exitCode);
2145
2158
  };
2146
2159
  /** Exit for a restart but leave the services running for the next daemon to adopt. */
2147
2160
  const handOver = () => {
@@ -2185,40 +2198,41 @@ export async function runDaemon(opts) {
2185
2198
  child.unref();
2186
2199
  // The aborted Stop job's receipt is written before the lease is released
2187
2200
  // (bounded: the job's child is already signalled).
2188
- let handOverTimer;
2189
- void Promise.race([stopJobsClosed, new Promise((done) => { handOverTimer = setTimeout(done, 3_000); handOverTimer.unref(); })]).then(() => {
2190
- if (handOverTimer)
2191
- clearTimeout(handOverTimer);
2192
- releaseDaemonLock(paths.lockPath);
2193
- resolve(RESTART_EXIT_CODE);
2194
- // Anything else still holding the event loop open must not delay the restart.
2195
- setTimeout(() => process.exit(RESTART_EXIT_CODE), 5_000).unref();
2196
- });
2201
+ // Anything else still holding the event loop open must not delay the restart.
2202
+ void exitWhenStopped({
2203
+ stopped: stopJobsClosed,
2204
+ cap: timeoutCap(3_000),
2205
+ releaseLock: () => releaseDaemonLock(paths.lockPath),
2206
+ exit: exitAfter(5_000),
2207
+ log,
2208
+ }, RESTART_EXIT_CODE);
2197
2209
  };
2198
- restartDaemon = () => {
2199
- if (!restartsForParent(opts)) {
2200
- log("warn", "a restart was requested, but no service manager would start this daemon again; restart it yourself");
2201
- return false;
2202
- }
2203
- if (stopping || restartPending)
2204
- return true;
2205
- restartPending = true;
2206
- return handoffWanted()
2207
- .catch((err) => {
2208
- log("warn", `could not decide on a handoff; restarting every service: ${err.message}`);
2209
- return false;
2210
- })
2211
- .then((handoff) => {
2212
- // A stop that began meanwhile (SIGTERM, `hq daemon stop`) wins: no relaunch.
2213
- if (!stopping)
2214
- relaunchWindowsTaskAfterExit();
2215
- if (handoff && succession)
2216
- handOver();
2217
- else
2218
- shutdown("restarting onto the updated CLI", RESTART_EXIT_CODE);
2219
- return true;
2220
- });
2210
+ const exitForRestartNow = () => {
2211
+ stopping = true;
2212
+ daemonStopping = true;
2213
+ void stopServicesAndExit({
2214
+ stopServices: () => supervisor.stop(),
2215
+ hasStoppingSyncRunner: () => supervisor.hasStoppingSyncRunner(),
2216
+ createCap: () => {
2217
+ const cap = createShutdownCap();
2218
+ extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
2219
+ return cap;
2220
+ },
2221
+ releaseLock: () => releaseDaemonLock(paths.lockPath),
2222
+ exit: exitAfter(1_000),
2223
+ log,
2224
+ }, RESTART_EXIT_CODE);
2221
2225
  };
2226
+ restartDaemon = createDaemonRestart({
2227
+ canRestart: () => restartsForParent(opts),
2228
+ isStopping: () => stopping,
2229
+ handoffWanted,
2230
+ beforeExit: relaunchWindowsTaskAfterExit,
2231
+ handOver: succession ? handOver : null,
2232
+ shutdown: () => shutdown("restarting onto the updated CLI", RESTART_EXIT_CODE),
2233
+ exitNow: exitForRestartNow,
2234
+ log,
2235
+ });
2222
2236
  hqdShutdown = () => shutdown("hqd shutdown request");
2223
2237
  tccEpermExit = (code) => shutdown("macOS refused file access under the HQ root; exiting so launchd starts a fresh daemon", code);
2224
2238
  process.on("SIGTERM", () => shutdown("received SIGTERM"));
@@ -423,8 +423,6 @@ export function createSupervisor(deps) {
423
423
  }
424
424
  deferredCliRestart = true;
425
425
  deps.log("info", "deferring CLI-update restart until sync is idle (maximum 10 minutes)");
426
- if (pendingSyncCommandRestart?.slot === sync)
427
- return;
428
426
  deferredCliRestartTimer = setT(() => runDeferredCliRestart(true), CLI_UPDATE_SYNC_IDLE_MAX_MS);
429
427
  };
430
428
  const deferSyncCommandRestart = (slot, onFinish) => {
@@ -209,6 +209,27 @@ export declare const SESSION_START_PINS: ReadonlyArray<readonly [string, readonl
209
209
  * any revision it does not rebuild. Null when every file matches.
210
210
  */
211
211
  export declare function sessionStartHold(root: string): string | null;
212
+ /**
213
+ * Pinned revisions of the five legacy core Work Mesh shims and their `core/hooks/work-mesh-*.sh`
214
+ * bodies (`crates/hq-hook/src/work_mesh_shims.rs`):
215
+ * - `work-mesh-close.sh`: hq-core v16.0.52 (`8203c5f1`) and v16.0.53-beta.4 (`f8a3b57b`).
216
+ * - `work-mesh-register.sh` and `work-mesh-ground.sh`: upgraded-root and v15.0.120 revisions.
217
+ * Each shim is existence-gated: a fresh install without the shim on disk is never held.
218
+ */
219
+ export interface WorkMeshShimPin {
220
+ readonly shim: PinnedFile;
221
+ readonly body: PinnedFile;
222
+ }
223
+ export declare const WORK_MESH_SESSION_START_PINS: readonly WorkMeshShimPin[];
224
+ export declare const WORK_MESH_USER_PROMPT_SUBMIT_PINS: readonly WorkMeshShimPin[];
225
+ export declare const WORK_MESH_SESSION_END_PINS: readonly WorkMeshShimPin[];
226
+ /**
227
+ * Why `event` (`SessionStart`, `UserPromptSubmit`, or `SessionEnd`) must stay on the shell
228
+ * registration for a present legacy Work Mesh shim in `root`: the shim file exists on disk, is
229
+ * claimed in `covered`, and either the shim or its `core/hooks/work-mesh-*.sh` body is not a
230
+ * pinned revision (`pinnedFilesHold`). Missing shims are not held.
231
+ */
232
+ export declare function workMeshShimsHold(root: string, event: 'SessionStart' | 'UserPromptSubmit' | 'SessionEnd', covered: readonly string[]): string | null;
212
233
  /**
213
234
  * The script revisions the native SessionStart `migrate-policy-triggers` port rebuilds
214
235
  * (`crates/hq-hook/src/session_start_ss1/migrate_triggers.rs`: `SCRIPT_SHA256`,