@indigoai-us/hq-cli 5.345.245 → 5.345.247

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 (127) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/dist/command-catalog.generated.d.ts +96 -9
  3. package/dist/command-catalog.generated.js +117 -9
  4. package/dist/commands/bot.js +1 -1
  5. package/dist/commands/core-checkpoint-native.d.ts +5 -1
  6. package/dist/commands/core-checkpoint-native.js +13 -5
  7. package/dist/commands/deploy-comments.js +139 -0
  8. package/dist/commands/deploy-list.d.ts +5 -0
  9. package/dist/commands/deploy-list.js +8 -0
  10. package/dist/commands/dm.d.ts +4 -1
  11. package/dist/commands/dm.js +11 -2
  12. package/dist/commands/files.d.ts +11 -2
  13. package/dist/commands/files.js +48 -3
  14. package/dist/commands/install-global.d.ts +15 -0
  15. package/dist/commands/install-global.js +98 -4
  16. package/dist/commands/lanes-loop.js +4 -1
  17. package/dist/commands/lanes.js +16 -5
  18. package/dist/commands/mcp-registration.d.ts +17 -0
  19. package/dist/commands/mcp-registration.js +119 -0
  20. package/dist/commands/mesh.d.ts +2 -0
  21. package/dist/commands/mesh.js +26 -6
  22. package/dist/commands/pkg-install.js +1 -1
  23. package/dist/commands/reindex.js +3 -2
  24. package/dist/commands/rescue.d.ts +22 -1
  25. package/dist/commands/rescue.js +56 -9
  26. package/dist/commands/sources.d.ts +1 -1
  27. package/dist/commands/sources.js +1 -1
  28. package/dist/commands/storage.d.ts +15 -2
  29. package/dist/commands/storage.js +74 -7
  30. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
  31. package/dist/hq-cloud-sync-runner/package.json +1 -1
  32. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  33. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  34. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  35. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  36. package/dist/lib/daemon/handoff.d.ts +4 -0
  37. package/dist/lib/daemon/handoff.js +2 -1
  38. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  39. package/dist/lib/daemon/hook-requests.js +19 -2
  40. package/dist/lib/daemon/install.d.ts +9 -1
  41. package/dist/lib/daemon/install.js +11 -2
  42. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  43. package/dist/lib/daemon/ops/policy.js +62 -15
  44. package/dist/lib/daemon/run.js +12 -0
  45. package/dist/lib/daemon/server.d.ts +5 -0
  46. package/dist/lib/daemon/server.js +1 -1
  47. package/dist/lib/daemon/supervisor.d.ts +6 -0
  48. package/dist/lib/daemon/supervisor.js +31 -2
  49. package/dist/lib/doctor/checks/antigravity-wiring.d.ts +21 -0
  50. package/dist/lib/doctor/checks/antigravity-wiring.js +75 -0
  51. package/dist/lib/doctor/checks/anywhere.js +30 -0
  52. package/dist/lib/doctor/checks/runtime-probe.js +13 -0
  53. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  54. package/dist/lib/doctor/platform.d.ts +1 -1
  55. package/dist/lib/doctor/platform.js +5 -0
  56. package/dist/lib/doctor/registry.js +3 -0
  57. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  58. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  59. package/dist/lib/hook-engine/coverage.d.ts +159 -0
  60. package/dist/lib/hook-engine/coverage.js +347 -0
  61. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  62. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  63. package/dist/lib/hot-channels/signals-pass.js +65 -3
  64. package/dist/lib/install/antigravity-targets.d.ts +39 -0
  65. package/dist/lib/install/antigravity-targets.js +122 -0
  66. package/dist/lib/install/claude-targets.d.ts +6 -0
  67. package/dist/lib/install/claude-targets.js +9 -1
  68. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  69. package/dist/lib/lanes/reconcile.js +19 -4
  70. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  71. package/dist/lib/lanes/remote-control-lane.js +10 -1
  72. package/dist/lib/lanes/spawn.d.ts +2 -0
  73. package/dist/lib/lanes/spawn.js +19 -3
  74. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  75. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  76. package/dist/lib/lanes/worker-process.js +4 -1
  77. package/dist/lib/mesh/client.js +5 -1
  78. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  79. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  80. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  81. package/dist/lib/mesh/live/daemon/install.js +70 -0
  82. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  83. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  84. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  85. package/dist/lib/mesh/live/daemon/run.js +48 -3
  86. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  87. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  88. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  89. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  90. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  91. package/dist/lib/mesh/live/direct-drain.js +3 -1
  92. package/dist/lib/mesh/live/emit.js +4 -2
  93. package/dist/lib/mesh/live/flush.d.ts +61 -0
  94. package/dist/lib/mesh/live/flush.js +434 -114
  95. package/dist/lib/mesh/live/paths.d.ts +10 -0
  96. package/dist/lib/mesh/live/paths.js +14 -0
  97. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  98. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  99. package/dist/lib/mesh/live/spool.d.ts +171 -17
  100. package/dist/lib/mesh/live/spool.js +777 -62
  101. package/dist/lib/signals/engine.d.ts +82 -2
  102. package/dist/lib/signals/engine.js +389 -53
  103. package/dist/lib/signals/steps/extract.js +5 -0
  104. package/dist/lib/work-context/organize.d.ts +22 -4
  105. package/dist/lib/work-context/organize.js +50 -21
  106. package/dist/lib/work-context/paths.d.ts +6 -0
  107. package/dist/lib/work-context/paths.js +9 -0
  108. package/dist/lib/work-context/reconcile.d.ts +1 -1
  109. package/dist/lib/work-context/reconcile.js +1 -1
  110. package/dist/startup-registration.d.ts +14 -0
  111. package/dist/startup-registration.js +26 -0
  112. package/dist/utils/cli-telemetry.d.ts +6 -0
  113. package/dist/utils/cli-telemetry.js +154 -9
  114. package/dist/utils/github-tag-fallback.d.ts +7 -2
  115. package/dist/utils/github-tag-fallback.js +17 -8
  116. package/dist/utils/hq-core-source.d.ts +31 -0
  117. package/dist/utils/hq-core-source.js +144 -0
  118. package/dist/utils/interactive-caller.d.ts +6 -0
  119. package/dist/utils/interactive-caller.js +8 -0
  120. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  121. package/dist/utils/shipped-codex-hooks.js +22 -10
  122. package/dist/utils/vault-api.js +1 -0
  123. package/dist/utils/version-report.d.ts +3 -1
  124. package/dist/utils/version-report.js +13 -5
  125. package/docs/anywhere-runtime.md +2 -2
  126. package/package.json +8 -8
  127. package/scripts/check-function-manifest.mjs +99 -18
@@ -4,6 +4,7 @@ import * as os from "node:os";
4
4
  import * as path from "node:path";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { RESOURCE_STOP_WAIT_MS, WorkerResourceSampler, resourceSampleIntervalMs, } from "./resource-usage.js";
7
+ import { laneWorkerEnv } from "./worker-env-scrub.js";
7
8
  export const LANE_WORKER_EXIT_PATH_ENV = "HQ_LANE_WORKER_EXIT_PATH";
8
9
  /**
9
10
  * The longest the wrapper waits for resource figures after the worker exits.
@@ -56,7 +57,9 @@ async function boundedUsage(sampler, endedAt, waitMs) {
56
57
  export function runLaneWorkerProcess(command, args, env = process.env, cwd = process.cwd(), options = {}) {
57
58
  const now = options.now ?? (() => new Date());
58
59
  const exitPath = env[LANE_WORKER_EXIT_PATH_ENV];
59
- const childEnv = { ...env };
60
+ // The provider binary never sees secret-bearing variables, even when this
61
+ // wrapper is started with them (worker-env-scrub.ts).
62
+ const childEnv = laneWorkerEnv(env);
60
63
  delete childEnv[LANE_WORKER_EXIT_PATH_ENV];
61
64
  const intervalMs = options.sampleIntervalMs ?? resourceSampleIntervalMs(env);
62
65
  const sampler = exitPath
@@ -19,7 +19,11 @@ export function createWorkSessionDeliverer(opts) {
19
19
  return async (op) => {
20
20
  const companyUid = op.companyUid;
21
21
  if (!companyUid) {
22
- return { ok: false, retryable: false, code: "COMPANY_UID_REQUIRED" };
22
+ // Queued with a company slug only (the company came from local
23
+ // evidence). Kept in the queue: the daemon's replay looks the uid up
24
+ // through the membership check before it sends. Quarantining here made
25
+ // the registration terminal (1,602 on one machine, 2026-11-21).
26
+ return { ok: false, retryable: true, code: "COMPANY_UID_PENDING" };
23
27
  }
24
28
  const body = {
25
29
  contractVersion: 1,
@@ -17,7 +17,12 @@ export interface DaemonDoctorReport {
17
17
  emitMode: "legacy" | "direct";
18
18
  /** True when the receive subscriber is connected (mqtt connected). */
19
19
  subscribed: boolean;
20
+ /** Lines waiting to send: spool.jsonl plus spool claim files left by an earlier flush. */
20
21
  spoolDepth: number;
22
+ /** The part of spoolDepth in spool.*.claimed files. */
23
+ spoolClaimedDepth?: number;
24
+ /** Lines parked for sessions with no company yet (spool.parked.jsonl). */
25
+ parkedDepth?: number;
21
26
  heldCount: number;
22
27
  /** Distinct held sessions with neither bound state nor local company evidence. */
23
28
  heldWithNoLocalEvidence: number;
@@ -32,6 +37,10 @@ export interface DaemonDoctorReport {
32
37
  outboxLastQuarantineServerCode?: string;
33
38
  lastFlushAt?: string;
34
39
  lastFlushResult?: DaemonStateFile["lastFlushResult"];
40
+ /** Set while a flush is running in a live daemon. */
41
+ flushInProgressSince?: string;
42
+ lastFlushError?: string;
43
+ lastFlushErrorAt?: string;
35
44
  unhealthy: boolean;
36
45
  unhealthyReasons: string[];
37
46
  oldestSpoolAgeMs?: number;
@@ -13,7 +13,7 @@ import { outboxQuarantineStatusEnabled } from "../../../work-context/outbox-quar
13
13
  import { formatDroppedPresenceCompany } from "./credentials.js";
14
14
  import { formatOwnerPushStatus, ownerPushStatusForAccount, readOwnerInboxPushState, } from "./owner-inbox-push.js";
15
15
  import { countDistinctHeldEvents, countJsonlLines, countUnattributedEvents, forEachJsonlLine, } from "../spool.js";
16
- import { workMeshDeadLetterPath, workMeshHeldPath, workMeshRoot, workMeshSpoolPath, } from "../paths.js";
16
+ import { workMeshDeadLetterPath, workMeshHeldPath, workMeshParkedPath, workMeshRoot, workMeshSpoolPath, } from "../paths.js";
17
17
  import { daemonDir, daemonPidPath } from "./paths.js";
18
18
  import { readEmitState } from "../emit.js";
19
19
  import { emitRetryDepth } from "../emit-retry.js";
@@ -27,6 +27,31 @@ import { readInstalledCliVersion } from "./version-drift.js";
27
27
  import { workSessionDenialReason } from "../../denial-codes.js";
28
28
  import { LEGACY_LISTENER_DOCTOR_LINE, legacyListenInstalled, } from "./legacy-listen.js";
29
29
  export const UNHEALTHY_SPOOL_AGE_MS = 60_000;
30
+ const SPOOL_CLAIM_FILE_RE = /^spool\..+\.claimed$/;
31
+ /**
32
+ * Lines in spool claim files (spool.<ts>.claimed). A flush renames spool.jsonl
33
+ * to one of these; one that outlives its flush (a crash, or a flush still
34
+ * running) still holds unsent lines, so doctor counts them in spool depth.
35
+ */
36
+ function countSpoolClaimLines(meshRoot) {
37
+ let names;
38
+ try {
39
+ names = fs.readdirSync(meshRoot);
40
+ }
41
+ catch (err) {
42
+ // No mesh folder yet means no claims; any other error is real.
43
+ if (err.code === "ENOENT")
44
+ return 0;
45
+ throw err;
46
+ }
47
+ let total = 0;
48
+ for (const name of names) {
49
+ if (!SPOOL_CLAIM_FILE_RE.test(name))
50
+ continue;
51
+ total += countJsonlLines(path.join(meshRoot, name));
52
+ }
53
+ return total;
54
+ }
30
55
  function oldestJsonlAgeMs(filePath, nowMs) {
31
56
  if (!fs.existsSync(filePath))
32
57
  return undefined;
@@ -178,7 +203,9 @@ export function collectDaemonDoctor(deps = {}) {
178
203
  const spoolPath = workMeshSpoolPath(meshRoot);
179
204
  const heldPath = workMeshHeldPath(meshRoot);
180
205
  const deadPath = workMeshDeadLetterPath(meshRoot);
181
- const spoolDepth = countJsonlLines(spoolPath);
206
+ const spoolClaimedDepth = countSpoolClaimLines(meshRoot);
207
+ const spoolDepth = countJsonlLines(spoolPath) + spoolClaimedDepth;
208
+ const parkedDepth = countJsonlLines(workMeshParkedPath(meshRoot));
182
209
  const heldCount = countDistinctHeldEvents(heldPath);
183
210
  const trustedRoots = readDaemonConfig(dir).trustedHqRoots;
184
211
  const outboxOperations = listOutboxOperations(ctxRoot);
@@ -222,8 +249,12 @@ export function collectDaemonDoctor(deps = {}) {
222
249
  }
223
250
  const presenceRefusal = state?.presenceRefusal ?? null;
224
251
  const presenceDroppedCompanies = state?.presenceDroppedCompanies ?? [];
225
- if (presenceDroppedCompanies.length > 0) {
226
- unhealthyReasons.push(`presence unavailable for ${presenceDroppedCompanies.length} companies`);
252
+ // A company left out only because one credential cannot hold every company
253
+ // (policy_budget) is expected for large memberships; doctor lists it but it
254
+ // does not make the daemon unhealthy.
255
+ const presenceUnavailable = presenceDroppedCompanies.filter((company) => company.reason !== "policy_budget");
256
+ if (presenceUnavailable.length > 0) {
257
+ unhealthyReasons.push(`presence unavailable for ${presenceUnavailable.length} companies`);
227
258
  }
228
259
  if (presenceRefusal) {
229
260
  unhealthyReasons.push(`presence credential refused (${presenceRefusal.code}); next retry ${presenceRefusal.nextRetryAt}`);
@@ -284,6 +315,17 @@ export function collectDaemonDoctor(deps = {}) {
284
315
  : {}),
285
316
  lastFlushAt: state?.lastFlushAt,
286
317
  lastFlushResult: state?.lastFlushResult,
318
+ ...(running && state?.flushStartedAt
319
+ ? { flushInProgressSince: state.flushStartedAt }
320
+ : {}),
321
+ ...(state?.lastFlushError
322
+ ? {
323
+ lastFlushError: state.lastFlushError,
324
+ lastFlushErrorAt: state.lastFlushErrorAt ?? undefined,
325
+ }
326
+ : {}),
327
+ spoolClaimedDepth,
328
+ parkedDepth,
287
329
  unhealthy: unhealthyReasons.length > 0,
288
330
  unhealthyReasons,
289
331
  oldestSpoolAgeMs,
@@ -325,7 +367,7 @@ export function formatDaemonDoctor(report) {
325
367
  if (report.emitMode === "legacy") {
326
368
  // Legacy emit path only: the spool/held/outbox queues do not exist in
327
369
  // receive-only (direct) mode.
328
- lines.push(`spool depth: ${report.spoolDepth}`, `held: ${report.heldCount}${report.heldCount > 0 ? " (needs_company; not sent as NONE)" : ""}`, `held with no local evidence: ${report.heldWithNoLocalEvidence}`, `outbox depth: ${report.outboxDepth}`);
370
+ lines.push(`spool depth: ${report.spoolDepth}${report.spoolClaimedDepth ? ` (${report.spoolClaimedDepth} in claim files)` : ""}`, `parked (no company yet): ${report.parkedDepth ?? 0}`, `held: ${report.heldCount}${report.heldCount > 0 ? " (needs_company; not sent as NONE)" : ""}`, `held with no local evidence: ${report.heldWithNoLocalEvidence}`, `outbox depth: ${report.outboxDepth}`);
329
371
  }
330
372
  if (report.outboxQuarantined !== undefined) {
331
373
  const quarantineDetails = [
@@ -349,7 +391,10 @@ export function formatDaemonDoctor(report) {
349
391
  if (report.emitMode === "legacy") {
350
392
  lines.push(`last flush: ${report.lastFlushAt ?? "(never)"}${report.lastFlushResult
351
393
  ? ` ok=${report.lastFlushResult.ok} posted=${report.lastFlushResult.posted}`
352
- : ""}`);
394
+ : ""}${report.flushInProgressSince ? `; in progress since ${report.flushInProgressSince}` : ""}`);
395
+ if (report.lastFlushError) {
396
+ lines.push(`last flush error: ${report.lastFlushError}${report.lastFlushErrorAt ? ` (at ${report.lastFlushErrorAt})` : ""}`);
397
+ }
353
398
  }
354
399
  lines.push(`emit last post: ${report.lastPostAt ?? "(never)"}${report.lastEmit
355
400
  ? ` accepted=${report.lastEmit.accepted ?? 0}` +
@@ -13,6 +13,7 @@
13
13
  */
14
14
  import * as fs from "node:fs";
15
15
  import { type RunCommand, type SleepFn } from "../../../service-manager/launchd.js";
16
+ import { type SystemUnitState } from "./system-unit.js";
16
17
  export type DaemonInstallPlatform = "darwin" | "linux" | "win32" | "other";
17
18
  /** Result of one schtasks.exe invocation (tests inject; never the real binary). */
18
19
  export interface SchtasksResult {
@@ -93,7 +94,37 @@ export interface InstallResult {
93
94
  recordedHqRoot?: string | null;
94
95
  /** Windows status: whether recordedHqRoot still passes isInstallableHqRoot. */
95
96
  rootValid?: boolean;
97
+ /** Linux status: state of /etc/systemd/system/hq-mesh-daemon.service when that unit exists. */
98
+ systemUnit?: {
99
+ path: string;
100
+ state: SystemUnitState | null;
101
+ };
96
102
  }
103
+ /** Exit code for `hq mesh daemon install` when the box's system unit already runs Work Mesh. */
104
+ export declare const MESH_DAEMON_SYSTEM_UNIT_EXIT = 3;
105
+ /**
106
+ * `hq mesh daemon install` (no --system-user) on a Linux box whose Work Mesh
107
+ * daemon runs from /etc/systemd/system/hq-mesh-daemon.service. A user unit
108
+ * there would start a second daemon that cannot take the pid lock and
109
+ * restarts every few seconds, so install refuses instead.
110
+ */
111
+ export declare class MeshSystemUnitInChargeError extends Error {
112
+ readonly systemUnitPath: string;
113
+ readonly exitCode = 3;
114
+ constructor(systemUnitPath: string);
115
+ }
116
+ export declare function meshSystemUnitInChargeMessage(systemUnitPath: string): string;
117
+ /**
118
+ * The system unit that would make a per-user Linux install a duplicate, or
119
+ * null when a user unit may be installed. `--system-user` writes the system
120
+ * template itself, so it is never refused.
121
+ */
122
+ export declare function meshSystemUnitBlockingInstall(opts: {
123
+ platform: DaemonInstallPlatform;
124
+ systemUser?: string;
125
+ systemUnitDir?: string;
126
+ existsSync?: (file: string) => boolean;
127
+ }): string | null;
97
128
  export declare function installedUnitHqRoot(home: string, platform?: DaemonInstallPlatform, env?: NodeJS.ProcessEnv): string | null;
98
129
  /** Best-effort restart result used after an in-place CLI upgrade. */
99
130
  export interface RestartDaemonResult {
@@ -214,6 +245,8 @@ export declare function installDaemonIfStale(opts: {
214
245
  /** Checks the installed unit's node path (tests); defaults to the real filesystem. */
215
246
  nodeProblem?: (nodePath: string) => "missing" | "versioned" | null;
216
247
  loginHome?: string;
248
+ /** Directory holding the box's system units (tests pass a fake root). */
249
+ systemUnitDir?: string;
217
250
  }): InstallIfStaleResult;
218
251
  /**
219
252
  * The node binary baked into the installed daemon unit (darwin plist or linux
@@ -365,6 +398,8 @@ export declare function installDaemonService(opts: {
365
398
  uid?: number;
366
399
  sleep?: SleepFn;
367
400
  loginHome?: string;
401
+ /** Directory holding the box's system units (tests pass a fake root). */
402
+ systemUnitDir?: string;
368
403
  }): InstallResult;
369
404
  export declare function uninstallDaemonService(opts: {
370
405
  platform?: DaemonInstallPlatform;
@@ -401,6 +436,10 @@ export declare function daemonServiceStatus(opts: {
401
436
  daemonPid: number;
402
437
  pid?: number;
403
438
  } | null;
439
+ /** Linux: directory holding the box's system units (tests pass a fake root). */
440
+ systemUnitDir?: string;
441
+ /** Linux: reads the system unit's state (tests inject; default runs `systemctl show`). */
442
+ systemUnitState?: () => SystemUnitState | null;
404
443
  }): InstallResult;
405
444
  /** Read baked template files from assets/ (optional; renderers are primary). */
406
445
  export declare function readAssetTemplate(name: "launchd.plist.template" | "systemd.user.service.template" | "systemd.system.service.template"): string | null;
@@ -26,6 +26,7 @@ import { readDaemonState } from "./state.js";
26
26
  import { HQ_DAEMON_LAUNCHD_LABEL, assertLoginHome, isLoginHome, meshPlistPath, meshUnitFromOtherHome, removeMeshUnitFromOtherHome, } from "./unit-home.js";
27
27
  import { activateLaunchd, defaultRunCommand, discoverLaunchdIdentity, installLaunchdPlist, launchdProgramArguments, launchdIsLoaded, launchdServiceTarget, launchdPlistProgramArguments, parseLaunchdCommand, launchdProgramArgumentsDiffer, parseLaunchctlPrintArguments, } from "../../../service-manager/launchd.js";
28
28
  import { activateSystemd, systemdIsActive } from "../../../service-manager/systemd.js";
29
+ import { SYSTEMD_SYSTEM_UNIT_DIR, describeSystemUnitState, meshSystemUnitPath, meshSystemUnitPresent, readMeshSystemUnitState, } from "./system-unit.js";
29
30
  import { nodeBinaryProblem, preferStableNodeBinary } from "../../../node-binary.js";
30
31
  /**
31
32
  * `schtasks /End` terminates the task's root process only. The daemon is
@@ -57,6 +58,38 @@ export const defaultSchtasks = (args) => {
57
58
  stderr: r.error ? r.error.message : (r.stderr ?? ""),
58
59
  };
59
60
  };
61
+ /** Exit code for `hq mesh daemon install` when the box's system unit already runs Work Mesh. */
62
+ export const MESH_DAEMON_SYSTEM_UNIT_EXIT = 3;
63
+ /**
64
+ * `hq mesh daemon install` (no --system-user) on a Linux box whose Work Mesh
65
+ * daemon runs from /etc/systemd/system/hq-mesh-daemon.service. A user unit
66
+ * there would start a second daemon that cannot take the pid lock and
67
+ * restarts every few seconds, so install refuses instead.
68
+ */
69
+ export class MeshSystemUnitInChargeError extends Error {
70
+ systemUnitPath;
71
+ exitCode = MESH_DAEMON_SYSTEM_UNIT_EXIT;
72
+ constructor(systemUnitPath) {
73
+ super(meshSystemUnitInChargeMessage(systemUnitPath));
74
+ this.systemUnitPath = systemUnitPath;
75
+ this.name = "MeshSystemUnitInChargeError";
76
+ }
77
+ }
78
+ export function meshSystemUnitInChargeMessage(systemUnitPath) {
79
+ return (`Work Mesh on this machine runs from the system unit ${systemUnitPath}, ` +
80
+ `so no user unit was installed. Check it with: systemctl status ${SYSTEMD_UNIT_NAME}`);
81
+ }
82
+ /**
83
+ * The system unit that would make a per-user Linux install a duplicate, or
84
+ * null when a user unit may be installed. `--system-user` writes the system
85
+ * template itself, so it is never refused.
86
+ */
87
+ export function meshSystemUnitBlockingInstall(opts) {
88
+ if (opts.platform !== "linux" || opts.systemUser)
89
+ return null;
90
+ const dir = opts.systemUnitDir ?? SYSTEMD_SYSTEM_UNIT_DIR;
91
+ return meshSystemUnitPresent(dir, opts.existsSync) ? meshSystemUnitPath(dir) : null;
92
+ }
60
93
  function readServiceText(file, existsSync, readFileSync) {
61
94
  if (!existsSync(file))
62
95
  return "";
@@ -528,6 +561,14 @@ export function isNewerCliVersion(current, recorded) {
528
561
  */
529
562
  export function installDaemonIfStale(opts) {
530
563
  const platformForUnit = opts.platform ?? detectPlatform();
564
+ const blockingSystemUnit = meshSystemUnitBlockingInstall({
565
+ platform: platformForUnit,
566
+ systemUser: opts.systemUser ?? opts.paths.systemUser,
567
+ systemUnitDir: opts.systemUnitDir,
568
+ });
569
+ if (blockingSystemUnit) {
570
+ return { reinstalled: false, message: meshSystemUnitInChargeMessage(blockingSystemUnit) };
571
+ }
531
572
  if (platformForUnit === "darwin" && !isLoginHome(opts.paths.home, opts.loginHome)) {
532
573
  return {
533
574
  reinstalled: false,
@@ -1116,6 +1157,13 @@ export function installDaemonService(opts) {
1116
1157
  buildInstallPaths({ systemUser: opts.systemUser });
1117
1158
  if (platform === "darwin")
1118
1159
  assertLoginHome("install", paths.home, opts.loginHome);
1160
+ const blockingSystemUnit = meshSystemUnitBlockingInstall({
1161
+ platform,
1162
+ systemUser: opts.systemUser ?? paths.systemUser,
1163
+ systemUnitDir: opts.systemUnitDir,
1164
+ });
1165
+ if (blockingSystemUnit)
1166
+ throw new MeshSystemUnitInChargeError(blockingSystemUnit);
1119
1167
  const mkdirSync = opts.mkdirSync ?? fs.mkdirSync;
1120
1168
  mkdirSync(paths.daemonDir, { recursive: true, mode: 0o700 });
1121
1169
  registerTrustedHqRoot(paths.daemonDir, paths.hqRoot);
@@ -1465,6 +1513,28 @@ export function daemonServiceStatus(opts) {
1465
1513
  }
1466
1514
  if (platform === "linux") {
1467
1515
  const installed = existsSync(paths.systemdUnitPath);
1516
+ const systemUnitDir = opts.systemUnitDir ?? SYSTEMD_SYSTEM_UNIT_DIR;
1517
+ if (meshSystemUnitPresent(systemUnitDir, existsSync)) {
1518
+ // The box's system unit runs Work Mesh: report its real state, and name
1519
+ // a user unit next to it as a duplicate rather than as the daemon.
1520
+ const systemUnitPath = meshSystemUnitPath(systemUnitDir);
1521
+ const state = opts.systemUnitState
1522
+ ? opts.systemUnitState()
1523
+ : readMeshSystemUnitState(defaultRunCommand);
1524
+ const running = state?.activeState === "active";
1525
+ const duplicate = installed
1526
+ ? ` A user unit also exists at ${paths.systemdUnitPath}; it duplicates the system unit and should be removed.`
1527
+ : "";
1528
+ return {
1529
+ platform,
1530
+ action: "status",
1531
+ paths,
1532
+ dest: systemUnitPath,
1533
+ running,
1534
+ systemUnit: { path: systemUnitPath, state },
1535
+ message: `systemd system unit ${SYSTEMD_UNIT_NAME} (${systemUnitPath}): ${describeSystemUnitState(state)}.${duplicate}`,
1536
+ };
1537
+ }
1468
1538
  const running = installed
1469
1539
  ? (opts.isLoaded?.(platform, paths.systemdUnitPath) ?? false)
1470
1540
  : false;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Outbox registrations queued with a company slug but no company uid.
3
+ *
4
+ * A session whose company was found from local evidence (a folder, a repo, the
5
+ * session's meta) knows the slug only. Such a registration used to be sent
6
+ * as is, refused locally with COMPANY_UID_REQUIRED, and quarantined for good
7
+ * (1,602 of them on one machine, 2026-11-21). The daemon now looks the uid up
8
+ * at send time, and only through the membership-checked lookup: the person
9
+ * must be a member of that company. A registration whose membership is not
10
+ * confirmed stays quarantined with a logged reason; nothing is dropped.
11
+ */
12
+ import { type OutboxOperation } from "../../../work-context/outbox.js";
13
+ export declare const COMPANY_UID_REQUIRED = "COMPANY_UID_REQUIRED";
14
+ /** Sent without a uid outside the daemon (CLI reconcile): kept queued for the daemon's replay. */
15
+ export declare const COMPANY_UID_PENDING = "COMPANY_UID_PENDING";
16
+ /** The membership lookup could not answer (offline, timeout): retried with the outbox backoff. */
17
+ export declare const COMPANY_UID_LOOKUP_UNAVAILABLE = "COMPANY_UID_LOOKUP_UNAVAILABLE";
18
+ /** The membership-checked slug lookup (the daemon's tenant gate). */
19
+ export type CompanyMembershipLookup = (companySlug: string) => Promise<{
20
+ status: "authorized";
21
+ uid: string;
22
+ } | {
23
+ status: "denied";
24
+ } | {
25
+ status: "unavailable";
26
+ error?: string;
27
+ }>;
28
+ export interface CompanyUidRefusal {
29
+ ok: false;
30
+ retryable: boolean;
31
+ code: string;
32
+ }
33
+ /**
34
+ * One filler per replay: each slug is looked up at most once, and a refusal
35
+ * is logged once per slug.
36
+ */
37
+ export declare function createOutboxCompanyUidFiller(lookup: CompanyMembershipLookup, log?: (message: string) => void,
38
+ /** Work-context root: when given, the confirmed uid is also stored on the operation's file. */
39
+ root?: string): (op: OutboxOperation) => Promise<CompanyUidRefusal | null>;
40
+ /**
41
+ * Once per daemon start: put registrations quarantined for a missing company
42
+ * uid (and ones whose lookup ran out of attempts) back in the queue. The
43
+ * replay sends at most its per-call cap and backs off on failure. Returns the
44
+ * number re-queued.
45
+ */
46
+ export declare function requeueCompanyUidQuarantines(root: string, now?: () => Date): number;
47
+ //# sourceMappingURL=outbox-company.d.ts.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Outbox registrations queued with a company slug but no company uid.
3
+ *
4
+ * A session whose company was found from local evidence (a folder, a repo, the
5
+ * session's meta) knows the slug only. Such a registration used to be sent
6
+ * as is, refused locally with COMPANY_UID_REQUIRED, and quarantined for good
7
+ * (1,602 of them on one machine, 2026-11-21). The daemon now looks the uid up
8
+ * at send time, and only through the membership-checked lookup: the person
9
+ * must be a member of that company. A registration whose membership is not
10
+ * confirmed stays quarantined with a logged reason; nothing is dropped.
11
+ */
12
+ import { readOutboxOperation, requeueQuarantinedOutbox, updateOutboxOperation, } from "../../../work-context/outbox.js";
13
+ export const COMPANY_UID_REQUIRED = "COMPANY_UID_REQUIRED";
14
+ /** Sent without a uid outside the daemon (CLI reconcile): kept queued for the daemon's replay. */
15
+ export const COMPANY_UID_PENDING = "COMPANY_UID_PENDING";
16
+ /** The membership lookup could not answer (offline, timeout): retried with the outbox backoff. */
17
+ export const COMPANY_UID_LOOKUP_UNAVAILABLE = "COMPANY_UID_LOOKUP_UNAVAILABLE";
18
+ /**
19
+ * One filler per replay: each slug is looked up at most once, and a refusal
20
+ * is logged once per slug.
21
+ */
22
+ export function createOutboxCompanyUidFiller(lookup, log,
23
+ /** Work-context root: when given, the confirmed uid is also stored on the operation's file. */
24
+ root) {
25
+ const answers = new Map();
26
+ const logged = new Set();
27
+ const logOnce = (key, message) => {
28
+ if (logged.has(key))
29
+ return;
30
+ logged.add(key);
31
+ log?.(message);
32
+ };
33
+ return async (op) => {
34
+ if (op.companyUid)
35
+ return null;
36
+ const slug = op.companySlug?.trim();
37
+ if (!slug) {
38
+ logOnce("", "work-context: a registration with no company stays quarantined (COMPANY_UID_REQUIRED): no company slug to look up");
39
+ return { ok: false, retryable: false, code: COMPANY_UID_REQUIRED };
40
+ }
41
+ let answer = answers.get(slug);
42
+ if (!answer) {
43
+ answer = lookup(slug);
44
+ answers.set(slug, answer);
45
+ }
46
+ const result = await answer;
47
+ if (result.status === "authorized") {
48
+ // Filled on the operation being sent, so the ack writes the same uid
49
+ // into the session state.
50
+ op.companyUid = result.uid;
51
+ // Stored too, so the ack and a later state repair see the same company.
52
+ if (root) {
53
+ const stored = readOutboxOperation(op.operationId, root);
54
+ if (stored && !stored.companyUid)
55
+ updateOutboxOperation({ ...stored, companyUid: result.uid }, root);
56
+ }
57
+ return null;
58
+ }
59
+ if (result.status === "unavailable") {
60
+ logOnce(`unavailable:${slug}`, `work-context: registrations for company ${slug} wait for the membership lookup (${(result.error ?? "unavailable").slice(0, 120)}); retried with backoff`);
61
+ return { ok: false, retryable: true, code: COMPANY_UID_LOOKUP_UNAVAILABLE };
62
+ }
63
+ logOnce(`denied:${slug}`, `work-context: registrations for company ${slug} stay quarantined (COMPANY_UID_REQUIRED): membership in that company was not confirmed`);
64
+ return { ok: false, retryable: false, code: COMPANY_UID_REQUIRED };
65
+ };
66
+ }
67
+ /**
68
+ * Once per daemon start: put registrations quarantined for a missing company
69
+ * uid (and ones whose lookup ran out of attempts) back in the queue. The
70
+ * replay sends at most its per-call cap and backs off on failure. Returns the
71
+ * number re-queued.
72
+ */
73
+ export function requeueCompanyUidQuarantines(root, now = () => new Date()) {
74
+ return [COMPANY_UID_REQUIRED, `${COMPANY_UID_LOOKUP_UNAVAILABLE}_MAX_ATTEMPTS`, `${COMPANY_UID_PENDING}_MAX_ATTEMPTS`]
75
+ .reduce((total, errorCode) => total + requeueQuarantinedOutbox(root, { errorCode, now }).length, 0);
76
+ }
77
+ //# sourceMappingURL=outbox-company.js.map
@@ -70,6 +70,8 @@ export interface DaemonRunDeps {
70
70
  backfillHeld?: () => Promise<BackfillHeldResult>;
71
71
  /** Maximum distinct held sessions reconciled during one daemon startup. */
72
72
  heldBackfillBatchSize?: number;
73
+ /** Dead-letter size that triggers compaction at start. Default DEAD_LETTER_COMPACT_MIN_BYTES (tests pass 0). */
74
+ deadLetterCompactMinBytes?: number;
73
75
  /** Minimum gap between periodic held backfills. Default HELD_BACKFILL_INTERVAL_MS. */
74
76
  heldBackfillIntervalMs?: number;
75
77
  /** Injected board refresh (tests). */
@@ -34,7 +34,8 @@ import { daemonDir } from "./paths.js";
34
34
  import { PresenceClient, defaultMqttConnect, } from "./presence.js";
35
35
  import { defaultDaemonState, patchDaemonState, readDaemonState, writeDaemonState, } from "./state.js";
36
36
  import { workMeshHeldPath } from "../paths.js";
37
- import { countJsonlLines } from "../spool.js";
37
+ import { compactDeadLetter, countJsonlLines } from "../spool.js";
38
+ import { createOutboxCompanyUidFiller, requeueCompanyUidQuarantines } from "./outbox-company.js";
38
39
  import { defaultTranscriptFs, noteHookSessionsFromSpoolFile, TRANSCRIPT_WATCH_INTERVAL_MS, TranscriptWatcher, } from "./transcript-watch.js";
39
40
  import { resolveMeshEmitMode, runsEmitPath, } from "./mode.js";
40
41
  import { hasCliVersionDrift, readInstalledCliVersion } from "./version-drift.js";
@@ -462,7 +463,14 @@ export async function runMeshDaemon(deps = {}) {
462
463
  (async () => {
463
464
  const t = await getToken();
464
465
  const deliver = deps.deliver ?? createWorkSessionDeliverer({ token: t });
466
+ // A registration queued with a company slug and no uid gets its uid
467
+ // here, from the membership-checked lookup only (never from local
468
+ // evidence). Not confirmed: it stays quarantined, with a logged reason.
469
+ const fillCompanyUid = createOutboxCompanyUidFiller((companySlug) => tenantGate.authorize({ companySlug, deviceDefault: false }), (message) => log(dir, message), ctxRoot);
465
470
  return replayOutbox(ctxRoot, async (op) => {
471
+ const refusal = await fillCompanyUid(op);
472
+ if (refusal)
473
+ return refusal;
466
474
  const state = readSessionState(op.sessionId, ctxRoot);
467
475
  // Provenance must survive session-state loss. For pre-upgrade outbox
468
476
  // entries without provenance, absent state is unknown and therefore
@@ -775,6 +783,8 @@ export async function runMeshDaemon(deps = {}) {
775
783
  return;
776
784
  }
777
785
  flushInFlight = (async () => {
786
+ // Doctor shows a flush that has started and not ended, instead of "never".
787
+ patchDaemonState(dir, { flushStartedAt: now().toISOString() }, now);
778
788
  try {
779
789
  // A held session has already ended, so no later hook will naturally
780
790
  // revisit its context. Repair a bounded batch before the first flush;
@@ -819,12 +829,21 @@ export async function runMeshDaemon(deps = {}) {
819
829
  patchDaemonState(dir, {
820
830
  lastFlushAt: now().toISOString(),
821
831
  lastFlushResult: { ...summary, ok: true },
832
+ flushStartedAt: null,
833
+ lastFlushError: null,
834
+ lastFlushErrorAt: null,
822
835
  }, now);
836
+ const duplicates = summary.duplicates ?? 0;
837
+ const parked = summary.parked ?? 0;
823
838
  if (summary.claimed > 0 ||
824
839
  summary.posted > 0 ||
825
840
  summary.held > 0 ||
826
- (summary.heldOverflow ?? 0) > 0) {
827
- log(dir, `flush(${reason}): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held}`);
841
+ (summary.heldOverflow ?? 0) > 0 ||
842
+ duplicates > 0 ||
843
+ parked > 0) {
844
+ log(dir, `flush(${reason}): claimed=${summary.claimed} posted=${summary.posted} held=${summary.held}` +
845
+ (duplicates > 0 ? ` duplicates=${duplicates}` : "") +
846
+ (parked > 0 ? ` parked=${parked}` : ""));
828
847
  }
829
848
  }
830
849
  catch (err) {
@@ -842,6 +861,9 @@ export async function runMeshDaemon(deps = {}) {
842
861
  batches: 0,
843
862
  },
844
863
  lastErrorCode: msg.slice(0, 120),
864
+ flushStartedAt: null,
865
+ lastFlushError: `flush(${reason}): ${msg.slice(0, 200)}`,
866
+ lastFlushErrorAt: now().toISOString(),
845
867
  }, now);
846
868
  log(dir, `flush(${reason}) error: ${msg.slice(0, 200)}`);
847
869
  }
@@ -1042,6 +1064,29 @@ export async function runMeshDaemon(deps = {}) {
1042
1064
  });
1043
1065
  }, TRANSCRIPT_WATCH_INTERVAL_MS);
1044
1066
  }
1067
+ // Once per start: heal queues an older version left behind. Registrations
1068
+ // quarantined for a missing company uid go back in the queue (the replay
1069
+ // looks the uid up through the membership check), and a large dead-letter
1070
+ // file is compacted to one line per event, with the event loop yielding.
1071
+ if (emitPath) {
1072
+ try {
1073
+ const requeued = requeueCompanyUidQuarantines(ctxRoot, now);
1074
+ if (requeued > 0)
1075
+ log(dir, `outbox: re-queued ${requeued} registrations quarantined for a missing company uid`);
1076
+ }
1077
+ catch (err) {
1078
+ log(dir, `outbox re-queue failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
1079
+ }
1080
+ void compactDeadLetter(meshRoot, { minBytes: deps.deadLetterCompactMinBytes })
1081
+ .then((result) => {
1082
+ if (result.compacted) {
1083
+ log(dir, `dead-letter compacted: lines ${result.linesBefore} -> ${result.linesAfter}, bytes ${result.bytesBefore} -> ${result.bytesAfter}`);
1084
+ }
1085
+ })
1086
+ .catch((err) => {
1087
+ log(dir, `dead-letter compaction failed: ${(err instanceof Error ? err.message : String(err)).slice(0, 160)}`);
1088
+ });
1089
+ }
1045
1090
  // Initial pass. Board refresh runs in both modes; the flush + transcript
1046
1091
  // scan are legacy emit-path only.
1047
1092
  if (!requestRestartForVersionDrift() && emitPath) {
@@ -23,6 +23,11 @@ export interface DaemonStateFile {
23
23
  lastFlushResult?: FlushSummary & {
24
24
  ok: boolean;
25
25
  };
26
+ /** Set when a flush starts and cleared when it ends, so doctor can tell "running" from "never". */
27
+ flushStartedAt?: string | null;
28
+ /** The last flush's error message (bounded) and when it happened; cleared by a flush that succeeds. */
29
+ lastFlushError?: string | null;
30
+ lastFlushErrorAt?: string | null;
26
31
  lastErrorCode?: string;
27
32
  /** Set while credential vend is refused (FEATURE_DISABLED / unsupported / 403). */
28
33
  presenceRefusal?: PresenceRefusalState | null;
@@ -0,0 +1,21 @@
1
+ import type { RunCommand } from "../../../service-manager/launchd.js";
2
+ export declare const SYSTEMD_SYSTEM_UNIT_DIR = "/etc/systemd/system";
3
+ export declare function meshSystemUnitPath(systemUnitDir?: string): string;
4
+ export declare function meshSystemUnitPresent(systemUnitDir?: string, existsSync?: (file: string) => boolean): boolean;
5
+ /** The properties `systemctl show` reports for the system unit. Empty strings when unknown. */
6
+ export interface SystemUnitState {
7
+ loadState: string;
8
+ activeState: string;
9
+ subState: string;
10
+ unitFileState: string;
11
+ }
12
+ /** Parse `systemctl show -p LoadState -p ActiveState -p SubState -p UnitFileState` output. */
13
+ export declare function parseSystemctlShow(stdout: string): SystemUnitState;
14
+ /**
15
+ * Read the system unit's state from the system manager. Reading needs no root.
16
+ * Returns null when systemctl cannot answer (no systemd, no bus).
17
+ */
18
+ export declare function readMeshSystemUnitState(run: RunCommand): SystemUnitState | null;
19
+ /** One plain phrase for the state, for example "active (running), enabled". */
20
+ export declare function describeSystemUnitState(state: SystemUnitState | null): string;
21
+ //# sourceMappingURL=system-unit.d.ts.map