@indigoai-us/hq-cli 5.345.226 → 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 (132) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/dist/command-catalog.generated.d.ts +137 -0
  3. package/dist/command-catalog.generated.js +164 -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 +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/lazy-commands.js +3 -4
  38. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  39. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  40. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  41. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  42. package/dist/lib/core-utils/session-company.d.ts +13 -1
  43. package/dist/lib/core-utils/session-company.js +75 -4
  44. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  45. package/dist/lib/core-utils/worktree-resume.js +8 -4
  46. package/dist/lib/daemon/background-qos.d.ts +7 -0
  47. package/dist/lib/daemon/background-qos.js +13 -0
  48. package/dist/lib/daemon/catalog.d.ts +9 -0
  49. package/dist/lib/daemon/catalog.js +8 -1
  50. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  51. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  52. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  53. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  54. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  55. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  56. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  57. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  58. package/dist/lib/daemon/hook-requests.d.ts +349 -8
  59. package/dist/lib/daemon/hook-requests.js +1312 -46
  60. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  61. package/dist/lib/daemon/machine-checks.js +27 -10
  62. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  63. package/dist/lib/daemon/merge-sections.js +58 -16
  64. package/dist/lib/daemon/ops/policy.js +4 -2
  65. package/dist/lib/daemon/resolver.js +9 -2
  66. package/dist/lib/daemon/run.d.ts +11 -7
  67. package/dist/lib/daemon/run.js +168 -24
  68. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  69. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  70. package/dist/lib/daemon/session-registry.d.ts +0 -1
  71. package/dist/lib/daemon/session-registry.js +0 -3
  72. package/dist/lib/daemon/supervisor.d.ts +3 -1
  73. package/dist/lib/daemon/supervisor.js +1 -1
  74. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  75. package/dist/lib/daemon/tcc-eperm.js +110 -8
  76. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  77. package/dist/lib/doctor/fix/process-identity.js +48 -5
  78. package/dist/lib/hook-engine/canary-gate.js +1 -0
  79. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  80. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  81. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  82. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  83. package/dist/lib/lanes/company-outposts.js +164 -0
  84. package/dist/lib/lanes/liveness.d.ts +6 -0
  85. package/dist/lib/lanes/liveness.js +49 -8
  86. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  87. package/dist/lib/lanes/orphan-report.js +223 -0
  88. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  89. package/dist/lib/lanes/orphan-sweep.js +152 -0
  90. package/dist/lib/lanes/reaper.d.ts +2 -0
  91. package/dist/lib/lanes/reaper.js +11 -8
  92. package/dist/lib/lanes/reconcile.d.ts +8 -7
  93. package/dist/lib/lanes/reconcile.js +39 -0
  94. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  95. package/dist/lib/mesh/live/backfill-held.js +23 -0
  96. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  97. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  98. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  99. package/dist/lib/mesh/live/daemon/run.js +116 -7
  100. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  101. package/dist/lib/mesh/live/direct-drain.js +315 -0
  102. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  103. package/dist/lib/mesh/live/emit-replay.js +10 -0
  104. package/dist/lib/mesh/live/flush.d.ts +15 -0
  105. package/dist/lib/mesh/live/flush.js +27 -0
  106. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  107. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  108. package/dist/lib/mesh/live/spool.d.ts +19 -0
  109. package/dist/lib/mesh/live/spool.js +80 -0
  110. package/dist/lib/safe-store.d.ts +2 -0
  111. package/dist/lib/safe-store.js +8 -6
  112. package/dist/lib/search-index/index.d.ts +9 -3
  113. package/dist/lib/search-index/index.js +35 -10
  114. package/dist/lib/search-index/worker-process.d.ts +9 -0
  115. package/dist/lib/search-index/worker-process.js +171 -0
  116. package/dist/lib/session-company-lock.d.ts +3 -1
  117. package/dist/lib/session-company-lock.js +3 -2
  118. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  119. package/dist/utils/delegate-command-supervisor.js +44 -0
  120. package/dist/utils/delegate-lock.d.ts +12 -0
  121. package/dist/utils/delegate-lock.js +88 -0
  122. package/dist/utils/frontmatter.d.ts +27 -0
  123. package/dist/utils/frontmatter.js +33 -0
  124. package/dist/utils/hook-trust.d.ts +1 -0
  125. package/dist/utils/hook-trust.js +18 -2
  126. package/dist/utils/host-registration.d.ts +13 -1
  127. package/dist/utils/host-registration.js +98 -5
  128. package/dist/utils/package-use-lease.d.ts +1 -1
  129. package/dist/utils/package-use-lease.js +15 -7
  130. package/docs/anywhere-runtime.md +17 -0
  131. package/package.json +8 -7
  132. package/scripts/check-function-manifest.mjs +17 -3
@@ -0,0 +1,164 @@
1
+ import { OutpostHttpError } from "@indigoai-us/hq-cloud/outposts";
2
+ import { LanesError } from "./errors.js";
3
+ const COMPANY_OUTPOST_ID = /^(?:opc_[0-9A-HJKMNP-TV-Z]{26}|outpost_cmp_[A-Za-z0-9]+)$/;
4
+ const FIRST_COMPANY_OUTPOST_PREFIX = "outpost_";
5
+ const NO_COMPANY_OUTPOSTS_CODES = new Set(["feature_disabled", "forbidden", "admin_required", "not_found"]);
6
+ const LIFECYCLE = /^[a-z_]{1,32}$/;
7
+ export function isCompanyOutpostId(id) {
8
+ return COMPANY_OUTPOST_ID.test(id);
9
+ }
10
+ export function companyUidOfFirstOutpostId(id) {
11
+ if (!isCompanyOutpostId(id) || !id.startsWith(FIRST_COMPANY_OUTPOST_PREFIX))
12
+ return undefined;
13
+ return id.slice(FIRST_COMPANY_OUTPOST_PREFIX.length);
14
+ }
15
+ function companyDetails(outpostId, company) {
16
+ return {
17
+ outpost_id: outpostId,
18
+ company_uid: company.uid,
19
+ ...(company.slug ? { company: company.slug } : {}),
20
+ };
21
+ }
22
+ export function companyOutpostAccessRequired(outpostId, company) {
23
+ const label = company.slug ? `${company.slug}'s Outpost ${outpostId}` : `company Outpost ${outpostId}`;
24
+ const approvers = company.slug ? `An owner or admin of ${company.slug}` : "An owner or admin of the company";
25
+ const slug = company.slug ?? "<slug>";
26
+ const requestAccess = `hq outposts request-access --company ${slug} --outpost ${outpostId}`;
27
+ const requestOutpost = `hq outposts request --company ${slug}`;
28
+ return new LanesError("company_outpost_access_required", `You are not approved to use ${label}. Next: ${requestAccess} (or ${requestOutpost} for an Outpost of your own). ${approvers} approves the request once; access lasts until they revoke it.`, {
29
+ ...companyDetails(outpostId, company),
30
+ request_access_command: requestAccess,
31
+ request_outpost_command: requestOutpost,
32
+ request_access: { method: "POST", path: "/outpost/status", body: { companyUid: company.uid, action: "request-access", outpostId } },
33
+ request_outpost: { method: "POST", path: "/outpost/status", body: { companyUid: company.uid, action: "request-outpost" } },
34
+ });
35
+ }
36
+ export function companyOutpostRefusal(err, outpostId, company) {
37
+ if (!(err instanceof OutpostHttpError))
38
+ return undefined;
39
+ const details = { ...companyDetails(outpostId, company), status: err.status };
40
+ const name = company.slug ?? "the company";
41
+ const slugArg = company.slug ?? "<slug>";
42
+ switch (err.code) {
43
+ case "grant_required":
44
+ return companyOutpostAccessRequired(outpostId, company);
45
+ case "forbidden":
46
+ case "admin_required":
47
+ return new LanesError("company_outpost_not_a_member", `Only current members of ${name} can use its Outpost ${outpostId}.`, details);
48
+ case "not_found":
49
+ return new LanesError("company_outpost_not_found", `${name} has no Outpost ${outpostId}. Run: hq outposts list --company ${slugArg}`, details);
50
+ case "not_ready":
51
+ return new LanesError("company_outpost_not_ready", `Outpost ${outpostId} of ${name} is not running yet. Check it with: hq outposts status --company ${slugArg} --outpost ${outpostId}`, details);
52
+ case "feature_disabled":
53
+ return new LanesError("company_outposts_unavailable", `Company Outposts are not available for ${name} right now. Try again later.`, details);
54
+ default:
55
+ return undefined;
56
+ }
57
+ }
58
+ const COMPANY_OUTPOST_REFUSALS = new Set([
59
+ "company_outpost_access_required",
60
+ "company_outpost_not_a_member",
61
+ "company_outpost_not_found",
62
+ "company_outpost_not_ready",
63
+ "company_outposts_unavailable",
64
+ ]);
65
+ export function isCompanyOutpostRefusal(err) {
66
+ return err instanceof LanesError && COMPANY_OUTPOST_REFUSALS.has(err.error);
67
+ }
68
+ export function assertCompanyOutpostBelongsTo(outpostId, company) {
69
+ const owner = companyUidOfFirstOutpostId(outpostId);
70
+ if (owner !== undefined && owner !== company.uid) {
71
+ throw new LanesError("company_outpost_wrong_company", `Outpost ${outpostId} does not belong to ${company.slug}. A lane can only run on an Outpost of its own company.`, { outpost_id: outpostId, company: company.slug });
72
+ }
73
+ }
74
+ export function companyOutpostNeedsCompany(outpostId) {
75
+ return new LanesError("company_outpost_requires_company", `Outpost ${outpostId} is a company Outpost. Pass --company <slug> for the company that owns it.`, { outpost_id: outpostId });
76
+ }
77
+ export function isNoCompanyOutposts(err) {
78
+ return (err instanceof OutpostHttpError &&
79
+ err.code !== undefined &&
80
+ NO_COMPANY_OUTPOSTS_CODES.has(err.code));
81
+ }
82
+ export class CompanyOutpostTargets {
83
+ lookupRecordedCompany;
84
+ companies = new Map();
85
+ constructor(lookupRecordedCompany = () => undefined) {
86
+ this.lookupRecordedCompany = lookupRecordedCompany;
87
+ }
88
+ remember(company, outpostIds) {
89
+ for (const id of outpostIds) {
90
+ if (isCompanyOutpostId(id))
91
+ this.companies.set(id, { uid: company.uid, slug: company.slug });
92
+ }
93
+ }
94
+ companyOf(outpostId) {
95
+ if (!isCompanyOutpostId(outpostId))
96
+ return undefined;
97
+ const remembered = this.companies.get(outpostId);
98
+ if (remembered)
99
+ return remembered;
100
+ const recorded = this.lookupRecordedCompany(outpostId);
101
+ const firstOutpostCompany = companyUidOfFirstOutpostId(outpostId);
102
+ if (recorded && (firstOutpostCompany === undefined || firstOutpostCompany === recorded.uid)) {
103
+ return { uid: recorded.uid, slug: recorded.slug };
104
+ }
105
+ if (firstOutpostCompany !== undefined)
106
+ return { uid: firstOutpostCompany };
107
+ throw companyOutpostNeedsCompany(outpostId);
108
+ }
109
+ }
110
+ export async function listCompanyOutpostCandidates(port, company) {
111
+ const body = await port.request({
112
+ path: "/outpost/status",
113
+ query: { companyUid: company.uid, list: "true" },
114
+ });
115
+ const rows = Array.isArray(body?.outposts) ? body.outposts : [];
116
+ const candidates = [];
117
+ for (const raw of rows) {
118
+ if (!raw || typeof raw !== "object")
119
+ continue;
120
+ const row = raw;
121
+ if (typeof row.outpostId !== "string" || !isCompanyOutpostId(row.outpostId))
122
+ continue;
123
+ const owner = companyUidOfFirstOutpostId(row.outpostId);
124
+ if (owner !== undefined && owner !== company.uid)
125
+ continue;
126
+ candidates.push({
127
+ outpostId: row.outpostId,
128
+ ...(typeof row.lifecycle === "string" && LIFECYCLE.test(row.lifecycle) ? { lifecycle: row.lifecycle } : {}),
129
+ ...(typeof row.canUse === "boolean" ? { canUse: row.canUse } : {}),
130
+ ...(typeof row.lanesReady === "boolean" ? { lanesReady: row.lanesReady } : {}),
131
+ });
132
+ }
133
+ return candidates;
134
+ }
135
+ export function readyCompanyOutpostIds(candidates) {
136
+ return candidates
137
+ .filter((row) => (row.lifecycle === undefined || row.lifecycle === "ready") && row.canUse !== false && row.lanesReady === true)
138
+ .map((row) => row.outpostId);
139
+ }
140
+ export function companyOutpostNotLaneReady(outpostId, company) {
141
+ const label = company.slug ? `${company.slug}'s Outpost ${outpostId}` : `Company Outpost ${outpostId}`;
142
+ return new LanesError("company_outpost_not_lane_ready", `${label} is not set up for lanes yet. Nothing was dispatched. Next: run the lane on a personal Outpost or this host for now.`, companyDetails(outpostId, company));
143
+ }
144
+ export function companyAwareExecPort(client, targets) {
145
+ const guarded = async (outpostId, call) => {
146
+ if (outpostId === undefined)
147
+ return call(undefined);
148
+ const company = targets.companyOf(outpostId);
149
+ if (!company)
150
+ return call(outpostId);
151
+ try {
152
+ return await call({ companyUid: company.uid, outpostId });
153
+ }
154
+ catch (err) {
155
+ throw companyOutpostRefusal(err, outpostId, company) ?? err;
156
+ }
157
+ };
158
+ return {
159
+ stageExecInput: (outpostId) => guarded(outpostId, (target) => client.stageExecInput(target)),
160
+ submitExec: (command, outpostId, timeoutSeconds) => guarded(outpostId, (target) => client.submitExec(command, target, timeoutSeconds)),
161
+ waitForExecResult: (commandId, outpostId, options) => guarded(outpostId, (target) => client.waitForExecResult(commandId, target, options)),
162
+ };
163
+ }
164
+ //# sourceMappingURL=company-outposts.js.map
@@ -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