@indigoai-us/hq-cli 5.345.225 → 5.345.228

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 (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -26,6 +26,14 @@ export interface HostCapacityAccount {
26
26
  awaiting_input: number;
27
27
  live: number;
28
28
  };
29
+ /**
30
+ * The business that owns this login (slug, `personal` or `unknown`) and who
31
+ * holds it (`owner`, or `unknown` when not recorded). PS-006. Absent on
32
+ * snapshots from older CLIs. Logins held by another person are not in
33
+ * `accounts`; see `HostCapacitySnapshot.other_holder_logins`.
34
+ */
35
+ owning_company?: string;
36
+ holder?: string;
29
37
  /** Provider-reported usage, when a host can read a recent sample. */
30
38
  usage?: {
31
39
  five_hour_percent?: number;
@@ -66,6 +74,17 @@ export interface HostCapacitySnapshot {
66
74
  * snapshot from another host is parsed.
67
75
  */
68
76
  compute_stale?: boolean;
77
+ /**
78
+ * Logins on this host held by another person (PS-006). Engine and holder
79
+ * only: the account id, home and owning business are left out, and these
80
+ * logins are never offered for placement. Absent when there are none and on
81
+ * snapshots from older CLIs.
82
+ */
83
+ other_holder_logins?: OtherHolderLogin[];
84
+ }
85
+ export interface OtherHolderLogin {
86
+ engine: LaneProvider;
87
+ holder: string;
69
88
  }
70
89
  /** The printed form: `hq runners capacity --json` and the remote capacity probe. */
71
90
  export type HostCapacitySnapshotWire = Omit<HostCapacitySnapshot, "host" | "host_aliases"> & {
@@ -1,4 +1,5 @@
1
1
  import { accountStatus } from "./accounts.js";
2
+ import { accountHeldByOther, accountOwnership, holderProblem, owningCompanyProblem } from "./account-ownership.js";
2
3
  import { accountMaxRunning } from "./config.js";
3
4
  import { laneOccupiesRunningSlot, laneRunsOnHost, } from "./admission.js";
4
5
  import { HOST_ALIAS_LIMIT } from "./canonical-host.js";
@@ -34,6 +35,7 @@ export function buildHostCapacitySnapshot(input) {
34
35
  lane.host.kind === "local" &&
35
36
  lane.host.id === localHostname));
36
37
  const providers = {};
38
+ const otherHolderLogins = [];
37
39
  for (const provider of ["claude", "codex", "grok"]) {
38
40
  const providerConfig = input.config.providers[provider];
39
41
  const providerLanes = onHost.filter((lane) => lane.provider === provider);
@@ -41,6 +43,11 @@ export function buildHostCapacitySnapshot(input) {
41
43
  const queued = providerLanes.filter((lane) => lane.state === "queued");
42
44
  const accounts = {};
43
45
  for (const [id, account] of Object.entries(providerConfig.accounts)) {
46
+ if (accountHeldByOther(account)) {
47
+ otherHolderLogins.push({ engine: provider, holder: account.holder });
48
+ continue;
49
+ }
50
+ const ownership = accountOwnership(account);
44
51
  const status = accountStatus(provider, id, input.config, {
45
52
  existsSync: input.existsSync,
46
53
  ...(input.probe !== undefined ? { probe: input.probe } : {}),
@@ -62,6 +69,8 @@ export function buildHostCapacitySnapshot(input) {
62
69
  max_running: accountMaxRunning(providerConfig, id),
63
70
  running: running.filter((lane) => lane.account === id).length,
64
71
  queued: queued.filter((lane) => lane.account === id).length,
72
+ owning_company: ownership.owning_company,
73
+ holder: ownership.holder,
65
74
  ...(quotaBlock !== undefined
66
75
  ? {
67
76
  quota_held: quotaBlock.blocked,
@@ -95,6 +104,7 @@ export function buildHostCapacitySnapshot(input) {
95
104
  ...(input.compute
96
105
  ? { compute: input.compute, compute_stale: computeReadingIsStale(input.compute, input.now) }
97
106
  : {}),
107
+ ...(otherHolderLogins.length > 0 ? { other_holder_logins: otherHolderLogins } : {}),
98
108
  };
99
109
  }
100
110
  function objectValue(value) {
@@ -178,6 +188,11 @@ export function parseHostCapacitySnapshot(raw, now = new Date()) {
178
188
  max_running: requireCount(account.max_running, `${provider}.${id}.max_running`, true),
179
189
  running: requireCount(account.running, `${provider}.${id}.running`),
180
190
  queued: requireCount(account.queued, `${provider}.${id}.queued`),
191
+ // Informational labels: a malformed value is dropped, never fatal.
192
+ ...(owningCompanyProblem(account.owning_company) === null
193
+ ? { owning_company: account.owning_company }
194
+ : {}),
195
+ ...(holderProblem(account.holder) === null ? { holder: account.holder } : {}),
181
196
  ...(account.quota_held !== undefined ? { quota_held: account.quota_held } : {}),
182
197
  ...(account.quota_reset_at !== undefined
183
198
  ? { quota_reset_at: account.quota_reset_at }
@@ -205,6 +220,7 @@ export function parseHostCapacitySnapshot(raw, now = new Date()) {
205
220
  };
206
221
  }
207
222
  const compute = root.compute === undefined ? null : parseHostComputeReading(root.compute);
223
+ const otherHolderLogins = parseOtherHolderLogins(root.other_holder_logins);
208
224
  return {
209
225
  schema_version: "hq-lanes-host-capacity.v1",
210
226
  host: { kind: hostRaw.kind, id: hostRaw.id },
@@ -214,8 +230,29 @@ export function parseHostCapacitySnapshot(raw, now = new Date()) {
214
230
  ...(compute !== null
215
231
  ? { compute, compute_stale: root.compute_stale === true || computeReadingIsStale(compute, now) }
216
232
  : {}),
233
+ ...(otherHolderLogins.length > 0 ? { other_holder_logins: otherHolderLogins } : {}),
217
234
  };
218
235
  }
236
+ /**
237
+ * Keep only engine and holder from each entry, whatever else a producer sent,
238
+ * so an account id never travels further than the host that holds it.
239
+ */
240
+ function parseOtherHolderLogins(value) {
241
+ if (!Array.isArray(value))
242
+ return [];
243
+ const out = [];
244
+ for (const entry of value) {
245
+ const row = objectValue(entry);
246
+ if (row === undefined)
247
+ continue;
248
+ if (row.engine !== "claude" && row.engine !== "codex" && row.engine !== "grok")
249
+ continue;
250
+ if (holderProblem(row.holder) !== null)
251
+ continue;
252
+ out.push({ engine: row.engine, holder: row.holder });
253
+ }
254
+ return out;
255
+ }
219
256
  function parseLaneCounts(value, field) {
220
257
  const counts = objectValue(value);
221
258
  if (counts === undefined) {
@@ -27,6 +27,12 @@ export interface LivenessIndex {
27
27
  spool_path: string;
28
28
  spool_bytes: number;
29
29
  spool_mtime_ms: number;
30
+ /**
31
+ * mtime of the liveness carry file merged into this index; absent when no
32
+ * carry file was read. The mesh daemon writes that file before it removes
33
+ * delivered lines from the spool.
34
+ */
35
+ carry_mtime_ms?: number;
30
36
  sessions: Record<string, SessionIndexEntry>;
31
37
  }
32
38
  export interface LivenessDeps {
@@ -12,6 +12,7 @@ import * as fs from "node:fs";
12
12
  import * as os from "node:os";
13
13
  import * as path from "node:path";
14
14
  import { workMeshSpoolPath, workMeshRoot } from "../mesh/live/paths.js";
15
+ import { LIVENESS_CARRY_BASENAME, parseLivenessCarry, supersedesLivenessEntry, } from "../mesh/live/liveness-carry.js";
15
16
  import { daemonDir, daemonStatePath } from "../mesh/live/daemon/paths.js";
16
17
  import { LanesError } from "./errors.js";
17
18
  import { effectiveAccountHome } from "./account-home.js";
@@ -221,7 +222,40 @@ function atomicWriteJson(target, value, deps) {
221
222
  throw err;
222
223
  }
223
224
  }
225
+ /**
226
+ * The last event per session that the mesh daemon copied out of the spool
227
+ * before delivering and removing those lines. It sits beside the spool. Null
228
+ * when the file is absent or is not a carry file: liveness then comes from the
229
+ * spool alone.
230
+ */
231
+ function readLivenessCarryFor(spoolPath, deps) {
232
+ const carryPath = path.join(path.dirname(spoolPath), LIVENESS_CARRY_BASENAME);
233
+ try {
234
+ const st = deps.statSync(carryPath);
235
+ const parsed = parseLivenessCarry(deps.readFileSync(carryPath, "utf8"));
236
+ if (!parsed)
237
+ return null;
238
+ return { mtimeMs: Math.floor(st.mtimeMs), sessions: parsed.sessions };
239
+ }
240
+ catch {
241
+ return null;
242
+ }
243
+ }
244
+ /** Add carried sessions to an index built from the spool; the newer event wins. */
245
+ function mergeLivenessCarry(index, carry) {
246
+ if (!carry)
247
+ return index;
248
+ for (const [sessionId, carried] of Object.entries(carry.sessions)) {
249
+ const fromSpool = index.sessions[sessionId];
250
+ if (!fromSpool || !supersedesLivenessEntry(carried, fromSpool)) {
251
+ index.sessions[sessionId] = carried;
252
+ }
253
+ }
254
+ index.carry_mtime_ms = carry.mtimeMs;
255
+ return index;
256
+ }
224
257
  export function rebuildLivenessIndex(hqRoot, spoolPath, deps = defaultLivenessDeps()) {
258
+ const carry = readLivenessCarryFor(spoolPath, deps);
225
259
  let contents;
226
260
  let st;
227
261
  try {
@@ -231,25 +265,25 @@ export function rebuildLivenessIndex(hqRoot, spoolPath, deps = defaultLivenessDe
231
265
  catch (err) {
232
266
  const code = err.code;
233
267
  if (code === "ENOENT") {
234
- const empty = {
268
+ const empty = mergeLivenessCarry({
235
269
  schema_version: "hq-lane-liveness-index.v1",
236
270
  built_at: new Date(deps.now()).toISOString(),
237
271
  spool_path: spoolPath,
238
272
  spool_bytes: 0,
239
273
  spool_mtime_ms: 0,
240
274
  sessions: {},
241
- };
275
+ }, carry);
242
276
  atomicWriteJson(livenessIndexPath(hqRoot), empty, deps);
243
277
  return empty;
244
278
  }
245
279
  throw err;
246
280
  }
247
- const index = buildLivenessIndexFromSpool(contents, {
281
+ const index = mergeLivenessCarry(buildLivenessIndexFromSpool(contents, {
248
282
  spool_path: spoolPath,
249
283
  spool_bytes: st.size,
250
284
  spool_mtime_ms: Math.floor(st.mtimeMs),
251
285
  built_at: new Date(deps.now()).toISOString(),
252
- });
286
+ }), carry);
253
287
  atomicWriteJson(livenessIndexPath(hqRoot), index, deps);
254
288
  return index;
255
289
  }
@@ -295,10 +329,17 @@ export function loadLivenessIndex(hqRoot, spoolPath, deps = defaultLivenessDeps(
295
329
  return null;
296
330
  }
297
331
  })();
332
+ const carry = readLivenessCarryFor(spool, deps);
333
+ // The index is also stale when the carry file changed: the daemon may have
334
+ // delivered and removed spool lines since the index was built.
335
+ const carryCurrent = existing
336
+ ? (existing.carry_mtime_ms ?? 0) === (carry?.mtimeMs ?? 0)
337
+ : false;
298
338
  if (existing) {
299
339
  try {
300
340
  const st = deps.statSync(spool);
301
- if (existing.spool_path === spool &&
341
+ if (carryCurrent &&
342
+ existing.spool_path === spool &&
302
343
  existing.spool_bytes === st.size &&
303
344
  existing.spool_mtime_ms === Math.floor(st.mtimeMs)) {
304
345
  return existing;
@@ -308,7 +349,7 @@ export function loadLivenessIndex(hqRoot, spoolPath, deps = defaultLivenessDeps(
308
349
  const code = err.code;
309
350
  if (code !== "ENOENT")
310
351
  throw err;
311
- if (existing.spool_bytes === 0)
352
+ if (carryCurrent && existing.spool_bytes === 0)
312
353
  return existing;
313
354
  }
314
355
  }
@@ -327,12 +368,12 @@ export function loadLivenessIndex(hqRoot, spoolPath, deps = defaultLivenessDeps(
327
368
  if (code !== "ENOENT")
328
369
  throw err;
329
370
  }
330
- return buildLivenessIndexFromSpool(contents, {
371
+ return mergeLivenessCarry(buildLivenessIndexFromSpool(contents, {
331
372
  spool_path: spool,
332
373
  spool_bytes: stSize,
333
374
  spool_mtime_ms: stMtime,
334
375
  built_at: new Date(deps.now()).toISOString(),
335
- });
376
+ }), carry);
336
377
  }
337
378
  return rebuildLivenessIndex(hqRoot, spool, deps);
338
379
  }
@@ -0,0 +1,15 @@
1
+ import { type ReapDeps, type ReapFinding } from "./reaper.js";
2
+ export interface DaemonOrphanDeps extends ReapDeps {
3
+ platform?: NodeJS.Platform;
4
+ readDarwinSnapshot?: () => string;
5
+ onProcessReadFailure?: (message: string) => void;
6
+ }
7
+ /** Five minutes spans the idle daemon's one-minute reconcile fallback. */
8
+ export declare const ORPHAN_REPORT_MAX_AGE_MS: number;
9
+ export declare function orphanReportPath(root: string, hostname?: string): string;
10
+ export declare function writeOrphanReport(root: string, hostname: string, now: Date, lanes: readonly ReapFinding[]): void;
11
+ /** Advisory only: stale, missing, malformed or unreadable reports stay silent. */
12
+ export declare function readOrphanReportCount(root: string, hostname?: string, nowMs?: number): number | null;
13
+ /** Reuse manual eligibility rules, supplying every process seam explicitly. */
14
+ export declare function classifyDaemonOrphans(root: string, now: Date, deps: DaemonOrphanDeps): Promise<ReapFinding[]>;
15
+ //# sourceMappingURL=orphan-report.d.ts.map
@@ -0,0 +1,223 @@
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+ import { randomUUID } from "node:crypto";
5
+ import { spawnSync } from "node:child_process";
6
+ import { classifyLocalLanes, DEFAULT_REAP_MIN_AGE_MINUTES } from "./reaper.js";
7
+ import { orphanProcessAlive, orphanProcessStarttime } from "./orphan-sweep.js";
8
+ import { parseProcStat, parsePsStarttime } from "./spawn.js";
9
+ const darwinSnapshots = new Map();
10
+ // The production reader is one stable function, so this limit spans roots.
11
+ // Injected readers represent independent daemon instances in tests.
12
+ const darwinReadTimes = new WeakMap();
13
+ const DARWIN_SNAPSHOT_MS = 60_000;
14
+ function readDarwinProcesses() {
15
+ // Candidate-only PID lists omit unknown ancestors. One narrow-column snapshot
16
+ // preserves the manual reaper's ancestor/session checks without N ps calls.
17
+ const result = spawnSync("/bin/ps", ["-ww", "-axo", "pid=,ppid=,lstart=,stat=,args="], {
18
+ encoding: "utf8", timeout: 3_000, killSignal: "SIGKILL", maxBuffer: 1024 * 1024, windowsHide: true,
19
+ });
20
+ if (result.error || result.status !== 0)
21
+ throw new Error("Darwin process snapshot failed");
22
+ return result.stdout;
23
+ }
24
+ function parseDarwinProcesses(text) {
25
+ const rows = [];
26
+ const seen = new Set();
27
+ for (const line of text.split("\n").filter((line) => line.trim())) {
28
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+\s+\S+\s+\d+\s+\d\d:\d\d:\d\d\s+\d{4})\s+(\S+)\s+(.*)$/.exec(line);
29
+ if (!match)
30
+ throw new Error("Darwin process snapshot is malformed");
31
+ const pid = Number(match[1]);
32
+ const ppid = Number(match[2]);
33
+ const starttime = parsePsStarttime(match[3]);
34
+ if (!Number.isSafeInteger(pid) || pid < 0 || !Number.isSafeInteger(ppid) || ppid < 0 || starttime === null || seen.has(pid))
35
+ throw new Error("Darwin process identity is malformed");
36
+ seen.add(pid);
37
+ rows.push({ pid, ppid, starttime, zombie: match[4].startsWith("Z"), args: match[5].trim().split(/\s+/).slice(0, 2).join(" ") });
38
+ }
39
+ if (rows.length === 0)
40
+ throw new Error("Darwin process snapshot is empty");
41
+ return rows;
42
+ }
43
+ async function classifyDarwinOrphans(root, now, deps) {
44
+ const isAlive = deps.isAlive ?? orphanProcessAlive;
45
+ const preliminary = await classifyLocalLanes(root, now, DEFAULT_REAP_MIN_AGE_MINUTES, {
46
+ ...deps, processes: () => [], processAncestry: () => [], isAlive, readStarttime: () => null,
47
+ });
48
+ const candidates = preliminary.filter((row) => row.orphaned && row.pid !== undefined);
49
+ if (candidates.length === 0)
50
+ return preliminary;
51
+ const key = JSON.stringify([fs.realpathSync(root), deps.hostname?.() ?? os.hostname()]);
52
+ let snapshot = darwinSnapshots.get(key);
53
+ const reader = deps.readDarwinSnapshot ?? readDarwinProcesses;
54
+ const lastRead = darwinReadTimes.get(reader);
55
+ const canRead = lastRead === undefined || now.getTime() - lastRead >= DARWIN_SNAPSHOT_MS;
56
+ if ((!snapshot || now.getTime() - snapshot.at >= DARWIN_SNAPSHOT_MS) && canRead) {
57
+ darwinReadTimes.set(reader, now.getTime());
58
+ snapshot = { at: now.getTime(), candidates: new Set(candidates.map((row) => row.pid)), rows: null };
59
+ try {
60
+ snapshot.rows = parseDarwinProcesses(reader());
61
+ }
62
+ catch {
63
+ deps.onProcessReadFailure?.("Darwin orphan process snapshot unavailable; candidates remain uncertain");
64
+ }
65
+ darwinSnapshots.delete(key);
66
+ darwinSnapshots.set(key, snapshot);
67
+ while (darwinSnapshots.size > 64)
68
+ darwinSnapshots.delete(darwinSnapshots.keys().next().value);
69
+ }
70
+ // Do not reuse another root's evidence or start a second read in this window.
71
+ if (!snapshot)
72
+ return preliminary.map((row) => row.orphaned && row.pid !== undefined ? { ...row, orphaned: false, reason: "process_snapshot_rate_limited" } : row);
73
+ const uncertain = () => preliminary.map((row) => row.orphaned && row.pid !== undefined ? { ...row, orphaned: false, reason: "process_snapshot_unavailable" } : row);
74
+ if (snapshot.rows === null)
75
+ return uncertain();
76
+ const rows = snapshot.rows;
77
+ const byPid = new Map(rows.map((row) => [row.pid, row]));
78
+ const allowed = snapshot.candidates;
79
+ const findings = await classifyLocalLanes(root, now, DEFAULT_REAP_MIN_AGE_MINUTES, {
80
+ ...deps, processes: () => rows, processAncestry: () => rows,
81
+ isAlive: (pid) => allowed.has(pid) && byPid.has(pid) ? !byPid.get(pid).zombie : isAlive(pid),
82
+ readStarttime: (pid) => allowed.has(pid) ? byPid.get(pid)?.starttime ?? null : null,
83
+ });
84
+ return findings.map((row) => {
85
+ if (row.orphaned && row.pid !== undefined && (!allowed.has(row.pid) || !completeAncestry(row.pid, rows)))
86
+ return { ...row, orphaned: false, reason: "process_snapshot_identity_or_ancestry_unavailable" };
87
+ return row;
88
+ });
89
+ }
90
+ /** Five minutes spans the idle daemon's one-minute reconcile fallback. */
91
+ export const ORPHAN_REPORT_MAX_AGE_MS = 5 * 60_000;
92
+ const SCHEMA = "hq-daemon-orphan-report.v1";
93
+ export function orphanReportPath(root, hostname = os.hostname()) {
94
+ return path.join(root, "workspace", "lanes-runs", `orphan-report-${hostname.replace(/[^A-Za-z0-9._-]/g, "_")}.json`);
95
+ }
96
+ function contained(root, destination) {
97
+ let parent = path.dirname(destination);
98
+ while (!fs.existsSync(parent)) {
99
+ const next = path.dirname(parent);
100
+ if (next === parent)
101
+ return false;
102
+ parent = next;
103
+ }
104
+ const relative = path.relative(fs.realpathSync(root), fs.realpathSync(parent));
105
+ return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`));
106
+ }
107
+ export function writeOrphanReport(root, hostname, now, lanes) {
108
+ const file = orphanReportPath(root, hostname);
109
+ if (!contained(root, file))
110
+ throw new Error("orphan report parent resolves outside HQ root");
111
+ fs.mkdirSync(path.dirname(file), { recursive: true });
112
+ const temporary = `${file}.${randomUUID()}.tmp`;
113
+ fs.writeFileSync(temporary, JSON.stringify({ schema: SCHEMA, hostname, computed_at: now.toISOString(), count: lanes.filter((lane) => lane.orphaned).length }), { flag: "wx", mode: 0o600 });
114
+ try {
115
+ fs.renameSync(temporary, file);
116
+ }
117
+ finally {
118
+ fs.rmSync(temporary, { force: true });
119
+ }
120
+ }
121
+ /** Advisory only: stale, missing, malformed or unreadable reports stay silent. */
122
+ export function readOrphanReportCount(root, hostname = os.hostname(), nowMs = Date.now()) {
123
+ try {
124
+ const file = orphanReportPath(root, hostname);
125
+ if (!contained(root, file))
126
+ return null;
127
+ const stat = fs.lstatSync(file);
128
+ if (!stat.isFile() || stat.size > 4096)
129
+ return null;
130
+ const report = JSON.parse(fs.readFileSync(file, "utf8"));
131
+ const at = typeof report.computed_at === "string" ? Date.parse(report.computed_at) : NaN;
132
+ if (report.schema !== SCHEMA || report.hostname !== hostname || !Number.isFinite(at) || at > nowMs || nowMs - at > ORPHAN_REPORT_MAX_AGE_MS)
133
+ return null;
134
+ return typeof report.count === "number" && Number.isSafeInteger(report.count) && report.count >= 0 ? report.count : null;
135
+ }
136
+ catch {
137
+ return null;
138
+ }
139
+ }
140
+ function processAncestry(pid) {
141
+ if (process.platform !== "linux")
142
+ return [];
143
+ const processes = [];
144
+ const seen = new Set();
145
+ for (let hops = 0; pid > 1 && hops < 64 && !seen.has(pid); hops += 1) {
146
+ seen.add(pid);
147
+ try {
148
+ const stat = parseProcStat(fs.readFileSync(path.join("/proc", String(pid), "stat"), "utf8"));
149
+ // Read a bounded prefix for the executable and first argument only.
150
+ const fd = fs.openSync(path.join("/proc", String(pid), "cmdline"), "r");
151
+ let args;
152
+ try {
153
+ const bytes = Buffer.alloc(8192);
154
+ const length = fs.readSync(fd, bytes, 0, bytes.length, 0);
155
+ const words = bytes.subarray(0, length).toString("utf8").split("\0");
156
+ if (length === bytes.length && words.length < 3)
157
+ break;
158
+ args = words.slice(0, 2).join(" ");
159
+ }
160
+ finally {
161
+ fs.closeSync(fd);
162
+ }
163
+ processes.push({ pid: stat.pid, ppid: stat.ppid, args });
164
+ pid = stat.ppid;
165
+ }
166
+ catch {
167
+ break; /* Missing evidence leaves the ancestry unproven. */
168
+ }
169
+ }
170
+ return processes;
171
+ }
172
+ function completeAncestry(pid, processes) {
173
+ const byPid = new Map(processes.map((row) => [row.pid, row]));
174
+ const seen = new Set();
175
+ for (let hops = 0; hops < 64; hops += 1) {
176
+ if (pid <= 1)
177
+ return true;
178
+ if (seen.has(pid))
179
+ return false;
180
+ seen.add(pid);
181
+ const current = byPid.get(pid);
182
+ if (!current)
183
+ return false;
184
+ pid = current.ppid;
185
+ }
186
+ return false;
187
+ }
188
+ /** Reuse manual eligibility rules, supplying every process seam explicitly. */
189
+ export async function classifyDaemonOrphans(root, now, deps) {
190
+ if ((deps.platform ?? process.platform) === "darwin" && (!deps.processes && !deps.processAncestry || deps.readDarwinSnapshot))
191
+ return classifyDarwinOrphans(root, now, deps);
192
+ const ancestry = new Map();
193
+ let supplied;
194
+ const readAncestry = (pid) => {
195
+ const rows = deps.processAncestry?.(pid) ?? (deps.processes ? (supplied ??= deps.processes()) : processAncestry(pid));
196
+ ancestry.set(pid, rows);
197
+ return rows;
198
+ };
199
+ const findings = await classifyLocalLanes(root, now, DEFAULT_REAP_MIN_AGE_MINUTES, {
200
+ ...deps,
201
+ processes: () => [],
202
+ processAncestry: readAncestry,
203
+ isAlive: deps.isAlive ?? orphanProcessAlive,
204
+ readStarttime: deps.readStarttime ?? orphanProcessStarttime,
205
+ });
206
+ return findings.map((finding) => {
207
+ if (finding.orphaned && finding.pid !== undefined) {
208
+ let identity;
209
+ try {
210
+ identity = (deps.readStarttime ?? orphanProcessStarttime)(finding.pid);
211
+ }
212
+ catch {
213
+ identity = null;
214
+ }
215
+ if (identity === null || identity !== finding.process_starttime)
216
+ return { ...finding, orphaned: false, reason: "process_identity_unavailable" };
217
+ if (!completeAncestry(finding.pid, ancestry.get(finding.pid) ?? []))
218
+ return { ...finding, orphaned: false, reason: "process_ancestry_unavailable" };
219
+ }
220
+ return finding;
221
+ });
222
+ }
223
+ //# sourceMappingURL=orphan-report.js.map
@@ -0,0 +1,26 @@
1
+ import { type AdmissionHost } from "./admission.js";
2
+ import { readPidRecord } from "./spawn.js";
3
+ import { type LaneRecord } from "./types.js";
4
+ type PidRecord = NonNullable<ReturnType<typeof readPidRecord>>;
5
+ export type MarkerState = "live" | "stale" | "uncertain";
6
+ export interface OrphanMarkerFinding {
7
+ lane_id: string;
8
+ marker: "worker.pid" | "watcher.pid";
9
+ status: MarkerState;
10
+ reason: string;
11
+ cleared: boolean;
12
+ }
13
+ export interface OrphanMarkerDeps {
14
+ isAlive?: (pid: number) => boolean;
15
+ readStarttime?: (pid: number) => number | null;
16
+ }
17
+ export declare function orphanProcessAlive(pid: number): boolean;
18
+ export declare function orphanProcessStarttime(pid: number): number | null;
19
+ /** Shared with manual reap: recheck both marker contents and staleness. */
20
+ export declare function clearStalePidMarker(root: string, file: string, expected: PidRecord, isStale: (record: PidRecord) => boolean): boolean;
21
+ /** Keep cleanup from removing markers created or replaced during reconciliation. */
22
+ export declare function snapshotOrphanMarkers(root: string, lanes: readonly LaneRecord[], host: AdmissionHost): Map<string, string | null>;
23
+ export declare function sweepOrphanMarkers(root: string, lanes: readonly LaneRecord[], host: AdmissionHost, dryRun: boolean, deps?: OrphanMarkerDeps, snapshot?: ReadonlyMap<string, string | null>): OrphanMarkerFinding[];
24
+ export declare function changedOrphanMarkers(root: string, host: AdmissionHost, findings: readonly OrphanMarkerFinding[], snapshot: ReadonlyMap<string, string | null>): OrphanMarkerFinding[];
25
+ export {};
26
+ //# sourceMappingURL=orphan-sweep.d.ts.map
@@ -0,0 +1,152 @@
1
+ /** In-process PID marker maintenance. Never starts or stops a process. */
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { laneRunsOnHost } from "./admission.js";
5
+ import { laneRunDir, parsePidRecord, parseProcStat, readPidRecord } from "./spawn.js";
6
+ import { isSubagentLane } from "./types.js";
7
+ export function orphanProcessAlive(pid) {
8
+ process.kill(pid, 0);
9
+ return true;
10
+ }
11
+ export function orphanProcessStarttime(pid) {
12
+ // Darwin's existing starttime reader starts ps. Leave identity uncertain
13
+ // there rather than starting a helper from the daemon sweep.
14
+ if (process.platform !== "linux")
15
+ return null;
16
+ return parseProcStat(fs.readFileSync(path.join("/proc", String(pid), "stat"), "utf8")).starttime ?? null;
17
+ }
18
+ function classify(record, deps) {
19
+ try {
20
+ if (!(deps.isAlive ?? orphanProcessAlive)(record.pid))
21
+ return { status: "stale", reason: "process_gone" };
22
+ }
23
+ catch (error) {
24
+ return error.code === "ESRCH"
25
+ ? { status: "stale", reason: "process_gone" }
26
+ : { status: "uncertain", reason: "process_probe_unavailable" };
27
+ }
28
+ if (record.starttime == null)
29
+ return { status: "uncertain", reason: "recorded_identity_missing" };
30
+ try {
31
+ const current = (deps.readStarttime ?? orphanProcessStarttime)(record.pid);
32
+ if (current === null)
33
+ return { status: "uncertain", reason: "process_identity_unavailable" };
34
+ return current === record.starttime
35
+ ? { status: "live", reason: "process_identity_matches" }
36
+ : { status: "stale", reason: "pid_reused" };
37
+ }
38
+ catch {
39
+ return { status: "uncertain", reason: "process_identity_unavailable" };
40
+ }
41
+ }
42
+ /** Shared with manual reap: recheck both marker contents and staleness. */
43
+ export function clearStalePidMarker(root, file, expected, isStale) {
44
+ if (!withinRoot(root, file))
45
+ return false;
46
+ const before = fs.lstatSync(file);
47
+ if (!before.isFile())
48
+ return false;
49
+ const current = readPidRecord(file);
50
+ if (!current || current.pid !== expected.pid || current.starttime !== expected.starttime || !isStale(current))
51
+ return false;
52
+ const after = fs.lstatSync(file);
53
+ if (!after.isFile() || before.ino !== after.ino || before.dev !== after.dev || before.mtimeMs !== after.mtimeMs || before.size !== after.size)
54
+ return false;
55
+ const latest = readPidRecord(file);
56
+ if (!latest || latest.pid !== expected.pid || latest.starttime !== expected.starttime)
57
+ return false;
58
+ fs.unlinkSync(file);
59
+ return true;
60
+ }
61
+ function withinRoot(root, file) {
62
+ const relative = path.relative(fs.realpathSync(root), fs.realpathSync(path.dirname(file)));
63
+ return relative === "" || (!path.isAbsolute(relative) && relative !== ".." && !relative.startsWith(`..${path.sep}`));
64
+ }
65
+ /** Keep cleanup from removing markers created or replaced during reconciliation. */
66
+ export function snapshotOrphanMarkers(root, lanes, host) {
67
+ const snapshot = new Map();
68
+ for (const lane of lanes) {
69
+ if (isSubagentLane(lane) || !laneRunsOnHost(lane, host))
70
+ continue;
71
+ for (const marker of ["worker.pid", "watcher.pid"]) {
72
+ const file = path.join(laneRunDir(root, lane.lane_id), marker);
73
+ try {
74
+ snapshot.set(file, withinRoot(root, file) && fs.lstatSync(file).isFile() ? fs.readFileSync(file, "utf8") : null);
75
+ }
76
+ catch (error) {
77
+ if (error.code !== "ENOENT")
78
+ snapshot.set(file, null);
79
+ }
80
+ }
81
+ }
82
+ return snapshot;
83
+ }
84
+ export function sweepOrphanMarkers(root, lanes, host, dryRun, deps = {}, snapshot) {
85
+ const findings = [];
86
+ for (const lane of lanes) {
87
+ if (isSubagentLane(lane) || !laneRunsOnHost(lane, host))
88
+ continue;
89
+ for (const marker of ["worker.pid", "watcher.pid"]) {
90
+ const file = path.join(laneRunDir(root, lane.lane_id), marker);
91
+ if (snapshot && !snapshot.has(file))
92
+ continue;
93
+ const finding = { lane_id: lane.lane_id, marker, status: "uncertain", reason: "marker_unreadable", cleared: false };
94
+ try {
95
+ if (!withinRoot(root, file)) {
96
+ finding.reason = "marker_parent_outside_root";
97
+ }
98
+ else if (!fs.lstatSync(file).isFile()) {
99
+ finding.reason = "marker_not_regular_file";
100
+ }
101
+ else {
102
+ const text = fs.readFileSync(file, "utf8");
103
+ const record = parsePidRecord(text);
104
+ if (snapshot && snapshot.get(file) !== text)
105
+ finding.reason = "marker_changed_during_reconcile";
106
+ else if (!record)
107
+ finding.reason = "marker_malformed";
108
+ else {
109
+ Object.assign(finding, classify(record, deps));
110
+ if (finding.status === "stale" && !dryRun) {
111
+ finding.cleared = clearStalePidMarker(root, file, record, (current) => classify(current, deps).status === "stale");
112
+ if (!finding.cleared) {
113
+ finding.status = "uncertain";
114
+ finding.reason = "marker_or_process_changed";
115
+ }
116
+ }
117
+ }
118
+ }
119
+ }
120
+ catch (error) {
121
+ if (error.code === "ENOENT")
122
+ continue;
123
+ finding.status = "uncertain";
124
+ finding.reason = "marker_read_or_clear_failed";
125
+ }
126
+ findings.push(finding);
127
+ }
128
+ }
129
+ return findings;
130
+ }
131
+ // Each root/host keeps only its current markers. Bound root/host entries too.
132
+ const reportedMarkerStates = new Map();
133
+ export function changedOrphanMarkers(root, host, findings, snapshot) {
134
+ const scope = JSON.stringify([fs.realpathSync(root), host.hostname, host.outpostId]);
135
+ const previous = reportedMarkerStates.get(scope);
136
+ const current = new Map();
137
+ const changed = [];
138
+ for (const finding of findings) {
139
+ const key = `${finding.lane_id}/${finding.marker}`;
140
+ const bytes = snapshot.get(path.join(laneRunDir(root, finding.lane_id), finding.marker));
141
+ const state = JSON.stringify([finding.status, finding.reason, finding.cleared, bytes]);
142
+ current.set(key, state);
143
+ if (previous?.get(key) !== state)
144
+ changed.push(finding);
145
+ }
146
+ reportedMarkerStates.delete(scope);
147
+ reportedMarkerStates.set(scope, current);
148
+ while (reportedMarkerStates.size > 64)
149
+ reportedMarkerStates.delete(reportedMarkerStates.keys().next().value);
150
+ return changed;
151
+ }
152
+ //# sourceMappingURL=orphan-sweep.js.map