@indigoai-us/hq-cli 5.345.245 → 5.345.246

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 (113) hide show
  1. package/CHANGELOG.md +82 -0
  2. package/dist/command-catalog.generated.d.ts +93 -6
  3. package/dist/command-catalog.generated.js +114 -6
  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/lanes-loop.js +4 -1
  15. package/dist/commands/lanes.js +16 -5
  16. package/dist/commands/mesh.d.ts +2 -0
  17. package/dist/commands/mesh.js +26 -6
  18. package/dist/commands/reindex.js +2 -1
  19. package/dist/commands/rescue.d.ts +22 -1
  20. package/dist/commands/rescue.js +56 -9
  21. package/dist/commands/sources.d.ts +1 -1
  22. package/dist/commands/sources.js +1 -1
  23. package/dist/commands/storage.d.ts +15 -2
  24. package/dist/commands/storage.js +74 -7
  25. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +232 -225
  26. package/dist/hq-cloud-sync-runner/package.json +1 -1
  27. package/dist/lib/agent-kit/mcp/tools.js +22 -0
  28. package/dist/lib/bot/jobs/hot-signal-sync.js +4 -1
  29. package/dist/lib/daemon/fleet-members-cache.d.ts +55 -0
  30. package/dist/lib/daemon/fleet-members-cache.js +266 -0
  31. package/dist/lib/daemon/handoff.d.ts +4 -0
  32. package/dist/lib/daemon/handoff.js +2 -1
  33. package/dist/lib/daemon/hook-requests.d.ts +2 -1
  34. package/dist/lib/daemon/hook-requests.js +19 -2
  35. package/dist/lib/daemon/install.d.ts +9 -1
  36. package/dist/lib/daemon/install.js +11 -2
  37. package/dist/lib/daemon/ops/policy.d.ts +23 -3
  38. package/dist/lib/daemon/ops/policy.js +62 -15
  39. package/dist/lib/daemon/run.js +12 -0
  40. package/dist/lib/daemon/server.d.ts +5 -0
  41. package/dist/lib/daemon/server.js +1 -1
  42. package/dist/lib/daemon/supervisor.d.ts +6 -0
  43. package/dist/lib/daemon/supervisor.js +31 -2
  44. package/dist/lib/doctor/checks/sync-runtime.js +8 -1
  45. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  46. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  47. package/dist/lib/hook-engine/coverage.d.ts +68 -0
  48. package/dist/lib/hook-engine/coverage.js +163 -0
  49. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  50. package/dist/lib/hot-channels/signals-pass.d.ts +52 -2
  51. package/dist/lib/hot-channels/signals-pass.js +65 -3
  52. package/dist/lib/install/claude-targets.d.ts +6 -0
  53. package/dist/lib/install/claude-targets.js +9 -1
  54. package/dist/lib/lanes/reconcile-result.d.ts +1 -1
  55. package/dist/lib/lanes/reconcile.js +19 -4
  56. package/dist/lib/lanes/remote-control-lane.d.ts +6 -0
  57. package/dist/lib/lanes/remote-control-lane.js +10 -1
  58. package/dist/lib/lanes/spawn.d.ts +2 -0
  59. package/dist/lib/lanes/spawn.js +19 -3
  60. package/dist/lib/lanes/worker-env-scrub.d.ts +48 -0
  61. package/dist/lib/lanes/worker-env-scrub.js +146 -0
  62. package/dist/lib/lanes/worker-process.js +4 -1
  63. package/dist/lib/mesh/client.js +5 -1
  64. package/dist/lib/mesh/live/daemon/doctor.d.ts +9 -0
  65. package/dist/lib/mesh/live/daemon/doctor.js +51 -6
  66. package/dist/lib/mesh/live/daemon/install.d.ts +39 -0
  67. package/dist/lib/mesh/live/daemon/install.js +70 -0
  68. package/dist/lib/mesh/live/daemon/outbox-company.d.ts +47 -0
  69. package/dist/lib/mesh/live/daemon/outbox-company.js +77 -0
  70. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  71. package/dist/lib/mesh/live/daemon/run.js +48 -3
  72. package/dist/lib/mesh/live/daemon/state.d.ts +5 -0
  73. package/dist/lib/mesh/live/daemon/system-unit.d.ts +21 -0
  74. package/dist/lib/mesh/live/daemon/system-unit.js +80 -0
  75. package/dist/lib/mesh/live/daemon/transcript-watch.d.ts +4 -1
  76. package/dist/lib/mesh/live/daemon/transcript-watch.js +42 -38
  77. package/dist/lib/mesh/live/direct-drain.js +3 -1
  78. package/dist/lib/mesh/live/emit.js +4 -2
  79. package/dist/lib/mesh/live/flush.d.ts +61 -0
  80. package/dist/lib/mesh/live/flush.js +434 -114
  81. package/dist/lib/mesh/live/paths.d.ts +10 -0
  82. package/dist/lib/mesh/live/paths.js +14 -0
  83. package/dist/lib/mesh/live/reporting-privacy.d.ts +41 -1
  84. package/dist/lib/mesh/live/reporting-privacy.js +81 -7
  85. package/dist/lib/mesh/live/spool.d.ts +171 -17
  86. package/dist/lib/mesh/live/spool.js +777 -62
  87. package/dist/lib/signals/engine.d.ts +82 -2
  88. package/dist/lib/signals/engine.js +389 -53
  89. package/dist/lib/signals/steps/extract.js +5 -0
  90. package/dist/lib/work-context/organize.d.ts +22 -4
  91. package/dist/lib/work-context/organize.js +50 -21
  92. package/dist/lib/work-context/paths.d.ts +6 -0
  93. package/dist/lib/work-context/paths.js +9 -0
  94. package/dist/lib/work-context/reconcile.d.ts +1 -1
  95. package/dist/lib/work-context/reconcile.js +1 -1
  96. package/dist/startup-registration.d.ts +14 -0
  97. package/dist/startup-registration.js +26 -0
  98. package/dist/utils/cli-telemetry.d.ts +6 -0
  99. package/dist/utils/cli-telemetry.js +154 -9
  100. package/dist/utils/github-tag-fallback.d.ts +7 -2
  101. package/dist/utils/github-tag-fallback.js +17 -8
  102. package/dist/utils/hq-core-source.d.ts +31 -0
  103. package/dist/utils/hq-core-source.js +144 -0
  104. package/dist/utils/interactive-caller.d.ts +6 -0
  105. package/dist/utils/interactive-caller.js +8 -0
  106. package/dist/utils/shipped-codex-hooks.d.ts +6 -4
  107. package/dist/utils/shipped-codex-hooks.js +22 -10
  108. package/dist/utils/vault-api.js +1 -0
  109. package/dist/utils/version-report.d.ts +3 -1
  110. package/dist/utils/version-report.js +13 -5
  111. package/docs/anywhere-runtime.md +2 -2
  112. package/package.json +8 -8
  113. package/scripts/check-function-manifest.mjs +99 -18
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The environment a lane worker process starts with.
3
+ *
4
+ * A lane worker runs a model CLI (codex, claude, grok) whose tool output goes
5
+ * to that model's provider. A worker that lists processes with their
6
+ * environments, or runs `env`, sends every inherited variable there. On
7
+ * 2026-11-20 a Codex lane worker did that and the owner's GitHub CLI token
8
+ * (GH_TOKEN) went to the provider. Lane workers therefore start without
9
+ * secret-bearing variables; everything else passes through unchanged.
10
+ *
11
+ * Each runner signs in to its own model provider from files in its account
12
+ * home, not from an API-key variable: claude reads `.credentials.json` in
13
+ * CLAUDE_CONFIG_DIR (or the Keychain item for the default ~/.claude home),
14
+ * codex reads `auth.json` in CODEX_HOME, and grok reads `auth.json` in
15
+ * GROK_HOME (see PROVIDER_CREDENTIAL_FILES in accounts.ts). So no provider
16
+ * API key is kept.
17
+ *
18
+ * gh inside a lane still works: with GH_TOKEN and GITHUB_TOKEN unset, gh uses
19
+ * the credentials stored by `gh auth login` (the system keyring or
20
+ * hosts.yml), as `gh help environment` documents.
21
+ *
22
+ * This module imports nothing from the lanes package, so every spawn path
23
+ * (spawn.ts, worker-process.ts, remote-control-lane.ts) can use it without
24
+ * an import cycle.
25
+ */
26
+ /** Removed by exact name, whatever the patterns below say. */
27
+ export declare const LANE_WORKER_SECRET_ENV_NAMES: readonly string[];
28
+ /** Name patterns of secret-bearing variables. */
29
+ export declare const LANE_WORKER_SECRET_ENV_PATTERNS: readonly RegExp[];
30
+ /**
31
+ * Kept even when a name matches a pattern above. Each one is a path, a socket
32
+ * or an on/off flag, never a secret value, and a runner or a tool inside the
33
+ * lane needs it.
34
+ */
35
+ export declare const LANE_WORKER_ENV_ALLOWLIST: readonly string[];
36
+ /**
37
+ * True when a lane worker must not inherit this variable. `value` is
38
+ * optional; when given, a URL with a password in it is removed whatever the
39
+ * name.
40
+ */
41
+ export declare function isLaneWorkerSecretEnvName(name: string, value?: string): boolean;
42
+ /**
43
+ * A copy of `parentEnv` without secret-bearing variables. The input is not
44
+ * changed. Every lane worker spawn, and every long-lived helper a lane
45
+ * starts (watcher, loop controller), builds its environment through this.
46
+ */
47
+ export declare function laneWorkerEnv(parentEnv: NodeJS.ProcessEnv): NodeJS.ProcessEnv;
48
+ //# sourceMappingURL=worker-env-scrub.d.ts.map
@@ -0,0 +1,146 @@
1
+ /**
2
+ * The environment a lane worker process starts with.
3
+ *
4
+ * A lane worker runs a model CLI (codex, claude, grok) whose tool output goes
5
+ * to that model's provider. A worker that lists processes with their
6
+ * environments, or runs `env`, sends every inherited variable there. On
7
+ * 2026-11-20 a Codex lane worker did that and the owner's GitHub CLI token
8
+ * (GH_TOKEN) went to the provider. Lane workers therefore start without
9
+ * secret-bearing variables; everything else passes through unchanged.
10
+ *
11
+ * Each runner signs in to its own model provider from files in its account
12
+ * home, not from an API-key variable: claude reads `.credentials.json` in
13
+ * CLAUDE_CONFIG_DIR (or the Keychain item for the default ~/.claude home),
14
+ * codex reads `auth.json` in CODEX_HOME, and grok reads `auth.json` in
15
+ * GROK_HOME (see PROVIDER_CREDENTIAL_FILES in accounts.ts). So no provider
16
+ * API key is kept.
17
+ *
18
+ * gh inside a lane still works: with GH_TOKEN and GITHUB_TOKEN unset, gh uses
19
+ * the credentials stored by `gh auth login` (the system keyring or
20
+ * hosts.yml), as `gh help environment` documents.
21
+ *
22
+ * This module imports nothing from the lanes package, so every spawn path
23
+ * (spawn.ts, worker-process.ts, remote-control-lane.ts) can use it without
24
+ * an import cycle.
25
+ */
26
+ /** Removed by exact name, whatever the patterns below say. */
27
+ export const LANE_WORKER_SECRET_ENV_NAMES = [
28
+ "GH_TOKEN",
29
+ "GITHUB_TOKEN",
30
+ "GH_ENTERPRISE_TOKEN",
31
+ "GITHUB_ENTERPRISE_TOKEN",
32
+ "AWS_ACCESS_KEY_ID",
33
+ "AWS_SECRET_ACCESS_KEY",
34
+ "AWS_SESSION_TOKEN",
35
+ "NPM_TOKEN",
36
+ "NODE_AUTH_TOKEN",
37
+ "ANTHROPIC_API_KEY",
38
+ "OPENAI_API_KEY",
39
+ "XAI_API_KEY",
40
+ ];
41
+ /** Name patterns of secret-bearing variables. */
42
+ export const LANE_WORKER_SECRET_ENV_PATTERNS = [
43
+ // Slack bot, user and app tokens, signing secrets and webhook URLs.
44
+ /^SLACK_/i,
45
+ /(TOKEN|SECRET|PASSWORD|PASSWD|PRIVATE_KEY|API_KEY|ACCESS_KEY|CREDENTIALS?)$/i,
46
+ /^(.*_)?(TOKEN|SECRET)(_.*)?$/i,
47
+ // Keys without the API_ prefix (STRIPE_KEY, AZURE_OPENAI_KEY, SST_KEY) and
48
+ // run-together names (SENDGRID_APIKEY).
49
+ /_KEY$/i,
50
+ /APIKEY$/i,
51
+ // Personal access tokens (GITLAB_PAT) and basic-auth values (NPM_CONFIG__AUTH).
52
+ /_PAT$/i,
53
+ /_AUTH$/i,
54
+ // 1Password CLI session tokens (OP_SESSION_<account>).
55
+ /^OP_SESSION_/i,
56
+ // Connection strings and URLs that usually carry a password or a key.
57
+ /^DATABASE_URL$/i,
58
+ /_DSN$/i,
59
+ /_WEBHOOK_URL$/i,
60
+ ];
61
+ /**
62
+ * A URL with a password in it (scheme://user:password@host), whatever the
63
+ * variable is called. REDIS_URL, MONGO_URI and the like are removed by value.
64
+ */
65
+ const URL_WITH_PASSWORD = /^[a-z][a-z0-9+.-]*:\/\/[^/\s:@]*:[^/\s@]+@/i;
66
+ /**
67
+ * A name ending in _FILE holds a file path, not a secret value: for example
68
+ * AWS_WEB_IDENTITY_TOKEN_FILE or HQ_TOKEN_FILE. The lane can read that file
69
+ * anyway, because the worker runs as the same user, so dropping the variable
70
+ * protects nothing and breaks tools that read it. These are kept unless the
71
+ * value itself is a URL with a password.
72
+ */
73
+ const PATH_NAME = /_FILE$/i;
74
+ /**
75
+ * Proxy settings (HTTPS_PROXY, HTTP_PROXY, ALL_PROXY, NO_PROXY and their
76
+ * lowercase forms) are kept even when they hold user:password@. Without them a
77
+ * runner behind a proxy that needs a login cannot reach its model provider, so
78
+ * the lane has no network. (Remote Control lanes still drop them later on
79
+ * purpose; see configureRemoteControlChildEnv.)
80
+ */
81
+ const PROXY_NAME = /_PROXY$/i;
82
+ /**
83
+ * Kept even when a name matches a pattern above. Each one is a path, a socket
84
+ * or an on/off flag, never a secret value, and a runner or a tool inside the
85
+ * lane needs it.
86
+ */
87
+ export const LANE_WORKER_ENV_ALLOWLIST = [
88
+ // Codex account home: holds the account's auth.json, the codex sign-in.
89
+ "CODEX_HOME",
90
+ // Claude account home: holds .credentials.json, the claude sign-in.
91
+ "CLAUDE_CONFIG_DIR",
92
+ // Grok account home: holds auth.json, the grok sign-in.
93
+ "GROK_HOME",
94
+ // Path to the HQ token file that `hq` commands in the lane read; a path, not the token.
95
+ "HQ_TOKEN_FILE",
96
+ // Directory where hq keeps machine token state; a path, not a token.
97
+ "HQ_MACHINE_TOKEN_STATE_DIR",
98
+ // ssh-agent socket path: git over SSH in the lane signs through the agent; no key material.
99
+ "SSH_AUTH_SOCK",
100
+ // On/off flag (src/utils/token-keychain.ts) that tells `hq` whether to read
101
+ // its token from the Keychain. Dropping it sends `hq` in a lane back to the
102
+ // Keychain, which can stall a detached process on a prompt.
103
+ "HQ_TOKEN_KEYCHAIN",
104
+ // Path to a Google service-account key file, not the key itself (see the
105
+ // _FILE note above: the file stays readable to the same user either way).
106
+ "GOOGLE_APPLICATION_CREDENTIALS",
107
+ // Public key hq uses to verify pack signatures; public by design.
108
+ "HQ_PACK_PUBLIC_KEY",
109
+ // Path override for the Codex auth.json that `hq core job probe` checks
110
+ // (src/commands/core-job-probe-native.ts); a path, not the auth file's contents.
111
+ "HQ_JOB_PROBE_CODEX_AUTH",
112
+ ];
113
+ const ALLOWED = new Set(LANE_WORKER_ENV_ALLOWLIST);
114
+ const SECRET_NAMES = new Set(LANE_WORKER_SECRET_ENV_NAMES);
115
+ /**
116
+ * True when a lane worker must not inherit this variable. `value` is
117
+ * optional; when given, a URL with a password in it is removed whatever the
118
+ * name.
119
+ */
120
+ export function isLaneWorkerSecretEnvName(name, value) {
121
+ if (ALLOWED.has(name))
122
+ return false;
123
+ if (PROXY_NAME.test(name))
124
+ return false;
125
+ if (value !== undefined && URL_WITH_PASSWORD.test(value.trim()))
126
+ return true;
127
+ if (SECRET_NAMES.has(name.toUpperCase()))
128
+ return true;
129
+ if (PATH_NAME.test(name))
130
+ return false;
131
+ return LANE_WORKER_SECRET_ENV_PATTERNS.some((pattern) => pattern.test(name));
132
+ }
133
+ /**
134
+ * A copy of `parentEnv` without secret-bearing variables. The input is not
135
+ * changed. Every lane worker spawn, and every long-lived helper a lane
136
+ * starts (watcher, loop controller), builds its environment through this.
137
+ */
138
+ export function laneWorkerEnv(parentEnv) {
139
+ const env = {};
140
+ for (const [name, value] of Object.entries(parentEnv)) {
141
+ if (!isLaneWorkerSecretEnvName(name, value))
142
+ env[name] = value;
143
+ }
144
+ return env;
145
+ }
146
+ //# sourceMappingURL=worker-env-scrub.js.map
@@ -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