@indigoai-us/hq-cli 5.345.212 → 5.345.214

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 (66) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/bin/hq-auth-refresh.js +2 -1
  3. package/dist/command-catalog.generated.d.ts +308 -43
  4. package/dist/command-catalog.generated.js +373 -43
  5. package/dist/commands/agent-inbox.d.ts +11 -1
  6. package/dist/commands/agent-inbox.js +128 -38
  7. package/dist/commands/agent-kit.js +2 -2
  8. package/dist/commands/core-handoff.js +1 -0
  9. package/dist/commands/core-hq-session-native.js +2 -2
  10. package/dist/commands/core-pin-native.js +1 -1
  11. package/dist/commands/core-policy.js +1 -1
  12. package/dist/commands/core-resolve-company-native.js +1 -1
  13. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  14. package/dist/commands/core-sentry-report-fast.js +3 -1
  15. package/dist/commands/daemon.js +11 -1
  16. package/dist/commands/integrations-connect.d.ts +7 -1
  17. package/dist/commands/integrations-connect.js +137 -13
  18. package/dist/commands/lanes-link.js +10 -5
  19. package/dist/commands/rescue.js +13 -0
  20. package/dist/commands/secrets.d.ts +11 -0
  21. package/dist/commands/secrets.js +41 -7
  22. package/dist/index.js +2 -0
  23. package/dist/lazy-commands.js +2 -0
  24. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  25. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  26. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  27. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  28. package/dist/lib/agent-kit/inbox-state.js +261 -4
  29. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  30. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  31. package/dist/lib/agent-kit/run/inbox.js +4 -2
  32. package/dist/lib/agent-kit/skills.js +4 -1
  33. package/dist/lib/agent-kit/wake.d.ts +9 -1
  34. package/dist/lib/agent-kit/wake.js +10 -3
  35. package/dist/lib/bot/fleet-cron.js +193 -14
  36. package/dist/lib/bot/fleet-download.d.ts +2 -0
  37. package/dist/lib/bot/fleet-download.js +23 -0
  38. package/dist/lib/bot/fleet-local.d.ts +1 -0
  39. package/dist/lib/bot/fleet-local.js +41 -8
  40. package/dist/lib/core-utils/session-id.d.ts +1 -1
  41. package/dist/lib/core-utils/session-id.js +4 -0
  42. package/dist/lib/daemon/run.js +9 -1
  43. package/dist/lib/daemon/updater.d.ts +34 -2
  44. package/dist/lib/daemon/updater.js +51 -2
  45. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  46. package/dist/lib/doctor/checks/release-links.js +260 -24
  47. package/dist/lib/doctor/fix/apply.js +24 -8
  48. package/dist/lib/doctor/fix/remediation.js +15 -5
  49. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  50. package/dist/lib/lanes/autopilot-registry.js +59 -7
  51. package/dist/lib/lanes/links.d.ts +14 -0
  52. package/dist/lib/lanes/links.js +320 -25
  53. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  54. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  55. package/dist/main.js +3 -1
  56. package/dist/sentry-init.d.ts +2 -0
  57. package/dist/sentry-init.js +13 -2
  58. package/dist/sentry.d.ts +2 -0
  59. package/dist/sentry.js +5 -1
  60. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  61. package/dist/utils/cli-network-lifecycle.js +52 -0
  62. package/dist/utils/safe-link.d.ts +63 -0
  63. package/dist/utils/safe-link.js +246 -0
  64. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  65. package/dist/utils/sentry-keepalive-transport.js +70 -0
  66. package/package.json +7 -7
@@ -10,6 +10,21 @@ const OUTPOST_LEAD_REGISTRY_REFRESH_MS = 6 * 60 * 60 * 1000;
10
10
  export const LEAD_REGISTRY_REL = path.join("workspace", "lane-briefs", "juniors.json");
11
11
  export const OUTPOST_LEAD_REGISTRY_STATE_REL = path.join("workspace", "lane-briefs", "autopilot-outpost-registry-state.json");
12
12
  export const LEAD_AUTOPILOT_FLAG = "lanes.lead-autopilot";
13
+ /** First wait after a failed delivery to one Outpost; doubles per failure. */
14
+ export const LEAD_REGISTRY_RETRY_BASE_MS = 30_000;
15
+ /** The wait between delivery attempts never grows past this. */
16
+ export const LEAD_REGISTRY_RETRY_MAX_MS = 30 * 60 * 1000;
17
+ /**
18
+ * Wait before the next delivery after `failures` consecutive failures:
19
+ * 30 s, 60 s, 2 min, ... capped at 30 min, then scaled by a jitter factor in
20
+ * [0.5, 1] so many machines do not retry in step.
21
+ */
22
+ export function leadRegistryRetryDelayMs(failures, random = Math.random) {
23
+ const exponent = Math.max(0, Math.min(failures - 1, 16));
24
+ const ceiling = Math.min(LEAD_REGISTRY_RETRY_MAX_MS, LEAD_REGISTRY_RETRY_BASE_MS * 2 ** exponent);
25
+ const jitter = Math.min(1, Math.max(0, random()));
26
+ return Math.round(ceiling * (0.5 + jitter / 2));
27
+ }
13
28
  function isRecord(value) {
14
29
  return value !== null && typeof value === "object" && !Array.isArray(value);
15
30
  }
@@ -135,6 +150,14 @@ export async function syncOutpostLeadRegistries(input) {
135
150
  const stateFile = path.join(input.hqRoot, OUTPOST_LEAD_REGISTRY_STATE_REL);
136
151
  const state = readDeliveryState(stateFile);
137
152
  const results = [];
153
+ const now = Date.parse(input.generatedAt);
154
+ const recordFailure = (outpostId) => {
155
+ const count = (state.failures?.[outpostId]?.count ?? 0) + 1;
156
+ const delay = leadRegistryRetryDelayMs(count, input.random);
157
+ const from = Number.isFinite(now) ? now : Date.now();
158
+ state.failures = { ...state.failures, [outpostId]: { count, next_at: new Date(from + delay).toISOString() } };
159
+ writeDeliveryState(stateFile, state);
160
+ };
138
161
  const targets = [...new Set(input.outpostIds.map((id) => id.trim()))]
139
162
  .filter((id) => id && !isControllerAliasOutpostId(id, input.localHost))
140
163
  .sort();
@@ -149,23 +172,52 @@ export async function syncOutpostLeadRegistries(input) {
149
172
  !Number.isFinite(age) ||
150
173
  age < 0 ||
151
174
  age >= OUTPOST_LEAD_REGISTRY_REFRESH_MS;
152
- if (shouldDispatch) {
153
- const result = await input.dispatch({
154
- outpostId,
155
- command: buildOutpostLeadRegistryInstallCommand(registry),
156
- timeoutSeconds: 120,
157
- waitMs: 120_000,
175
+ const lanesSkipped = skipped.filter(({ lane }) => sourceRows.some((row) => row.lane === lane && row.host === outpostId));
176
+ // A failed delivery used to be retried on every reconcile pass (every
177
+ // 15 s) with no wait. Hold this Outpost until its backoff has passed.
178
+ const failure = state.failures?.[outpostId];
179
+ const retryAt = failure ? Date.parse(failure.next_at) : NaN;
180
+ // A stored time further ahead than the longest backoff (the clock moved
181
+ // back, or the file was edited) is ignored rather than holding for days.
182
+ const held = Number.isFinite(retryAt) && Number.isFinite(now) && now < retryAt &&
183
+ retryAt - now <= LEAD_REGISTRY_RETRY_MAX_MS;
184
+ if (shouldDispatch && held) {
185
+ results.push({
186
+ outpost_id: outpostId,
187
+ row_count: registry.juniors.length,
188
+ skipped: lanesSkipped,
189
+ dispatched: false,
190
+ retry_after: new Date(retryAt).toISOString(),
158
191
  });
192
+ continue;
193
+ }
194
+ if (shouldDispatch) {
195
+ let result;
196
+ try {
197
+ result = await input.dispatch({
198
+ outpostId,
199
+ command: buildOutpostLeadRegistryInstallCommand(registry),
200
+ timeoutSeconds: 120,
201
+ waitMs: 120_000,
202
+ });
203
+ }
204
+ catch (error) {
205
+ recordFailure(outpostId);
206
+ throw error;
207
+ }
159
208
  if (result.done !== true || result.exitCode !== 0) {
209
+ recordFailure(outpostId);
160
210
  throw new LanesError("lead_autopilot_registry_sync_failed", `Could not sync lead registry to Outpost ${outpostId}`, { outpost_id: outpostId, exit_code: result.exitCode, done: result.done === true });
161
211
  }
162
212
  state.delivered[outpostId] = { hash, at: new Date(input.generatedAt).toISOString() };
213
+ if (state.failures)
214
+ delete state.failures[outpostId];
163
215
  writeDeliveryState(stateFile, state);
164
216
  }
165
217
  results.push({
166
218
  outpost_id: outpostId,
167
219
  row_count: registry.juniors.length,
168
- skipped: skipped.filter(({ lane }) => sourceRows.some((row) => row.lane === lane && row.host === outpostId)),
220
+ skipped: lanesSkipped,
169
221
  dispatched: shouldDispatch,
170
222
  });
171
223
  }
@@ -22,6 +22,14 @@ export interface LinkOptions {
22
22
  input?: string;
23
23
  ackMode?: string;
24
24
  claims?: string;
25
+ /** One-time handover token from `hq lanes link handover`, consumed by `adopt`. */
26
+ token?: string;
27
+ /** File holding the handover token; keeps it out of argv. */
28
+ tokenFile?: string;
29
+ /** Reads stdin for `--token -`. Injected in tests. */
30
+ readStdin?: () => string;
31
+ /** Test hook: runs after a conductor drain resolved its pointer and before it takes the queue lock. */
32
+ beforeConductorQueue?: () => Promise<void> | void;
25
33
  now?: () => Date;
26
34
  sleep?: (milliseconds: number) => Promise<void>;
27
35
  /** Injected in tests; defaults to the real package-use lease drop/retake. */
@@ -40,6 +48,12 @@ export declare function resolveSignalConductor(root: string, env: NodeJS.Process
40
48
  /** Cheap hook guard used before remote flag lookup or queue access. */
41
49
  export declare function linkedSessionIdFromHookInput(input: string): string;
42
50
  export declare function isLinkedSession(root: string, sid: string, env?: NodeJS.ProcessEnv): boolean;
51
+ /**
52
+ * Read all of stdin synchronously. `fs.readFileSync(0)` throws EAGAIN on a
53
+ * non-blocking stdin (some hosts hand one over) and EOF on a Windows console,
54
+ * so read in chunks: wait and retry on EAGAIN, and treat EOF as end of input.
55
+ */
56
+ export declare function readStdinSync(read?: (fd: number, buffer: Buffer) => number, sleep?: (milliseconds: number) => void): string;
43
57
  export declare function drainLinkQueue(inbox: string): string;
44
58
  /** Called by the installed lane drain hook before core's pointer-file guard. */
45
59
  export declare function bindSignalLaneHook(root: string, input: string, env: NodeJS.ProcessEnv): void;
@@ -1,4 +1,4 @@
1
- import { randomBytes } from "node:crypto";
1
+ import { createHash, randomBytes, timingSafeEqual } from "node:crypto";
2
2
  import * as fs from "node:fs";
3
3
  import * as path from "node:path";
4
4
  import { appendDropboxMessageAtPath } from "./dropbox.js";
@@ -24,7 +24,7 @@ export function resolveLinkSessionId(root, explicit, env = process.env) {
24
24
  throw new LaneLinkError("invalid_session_id", `Invalid session id: ${explicit}`);
25
25
  return explicit;
26
26
  }
27
- for (const key of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID"]) {
27
+ for (const key of ["HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "GROK_SESSION_ID", "HQ_FLEET_SESSION_ID"]) {
28
28
  const candidate = env[key]?.replace(/\s/g, "");
29
29
  if (safeId(candidate))
30
30
  return candidate;
@@ -143,7 +143,11 @@ function bindSignalLaneSession(root, sid, env) {
143
143
  return;
144
144
  const dir = linkPath(root, lane.signal_link);
145
145
  const meta = readJson(path.join(dir, "meta.json"));
146
- if (lane.senior.kind !== "session" || lane.senior.id !== meta.conductor_session || sid === meta.conductor_session)
146
+ // A lane created by a conductor that later handed the link over still binds:
147
+ // its senior is a previous conductor of record, not an arbitrary session.
148
+ const previous = Array.isArray(meta.previous_conductors) ? meta.previous_conductors : [];
149
+ const seniorIsConductor = lane.senior.id === meta.conductor_session || previous.includes(lane.senior.id);
150
+ if (lane.senior.kind !== "session" || !seniorIsConductor || sid === meta.conductor_session || previous.includes(sid))
147
151
  return;
148
152
  const child = lane.lane_id;
149
153
  const at = new Date().toISOString();
@@ -187,6 +191,11 @@ function resolvePointer(root, sid, role, options) {
187
191
  if (role === "conductor" && link !== pointer.link) {
188
192
  throw new LaneLinkError("link_role_invalid", "A conductor can only consume or wait on its own link");
189
193
  }
194
+ // A conductor pointer is only a hint: after a handover the old session's
195
+ // pointer can survive (an interrupted adopt, or one recreated by hand).
196
+ // The link's meta names the one conductor of record.
197
+ if (role === "conductor")
198
+ assertConductorOfRecord(root, pointer.link, sid);
190
199
  if (role === "child") {
191
200
  if (options.link !== undefined && !safeId(options.link))
192
201
  throw new LaneLinkError("link_invalid", "Invalid --link");
@@ -196,6 +205,127 @@ function resolvePointer(root, sid, role, options) {
196
205
  }
197
206
  return { link, child };
198
207
  }
208
+ /** A handover token is good for a week: long enough for a handoff to be picked up. */
209
+ const HANDOVER_TTL_MS = 7 * 24 * 60 * 60 * 1000;
210
+ function sha256(value) {
211
+ return createHash("sha256").update(value, "utf8").digest("hex");
212
+ }
213
+ function handoverTokenValid(handover, token, at) {
214
+ if (!token || !handover || typeof handover !== "object")
215
+ return false;
216
+ const record = handover;
217
+ if (typeof record.token_sha256 !== "string" || typeof record.expires !== "string")
218
+ return false;
219
+ const expires = Date.parse(record.expires);
220
+ if (!Number.isFinite(expires) || at.getTime() >= expires)
221
+ return false;
222
+ const expected = Buffer.from(record.token_sha256, "hex");
223
+ const actual = Buffer.from(sha256(token), "hex");
224
+ return expected.length === actual.length && timingSafeEqual(expected, actual);
225
+ }
226
+ function isConductorOfRecord(meta, sid) {
227
+ return typeof meta.conductor_session === "string" && meta.conductor_session === sid;
228
+ }
229
+ function assertConductorOfRecord(root, link, sid, meta) {
230
+ const record = meta ?? readJson(path.join(rootDir(root), link, "meta.json"));
231
+ if (!isConductorOfRecord(record, sid)) {
232
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${link}; it was handed over to another session`);
233
+ }
234
+ }
235
+ /**
236
+ * Drop this session's pointer when it is stale: the link was closed (a close
237
+ * that failed mid-sweep leaves pointers behind), or, for a conductor pointer,
238
+ * the link was handed to another session.
239
+ */
240
+ function dropStalePointer(root, sid) {
241
+ const pointer = readPointer(root, sid);
242
+ if (!pointer)
243
+ return pointer;
244
+ let meta;
245
+ try {
246
+ meta = readJson(path.join(rootDir(root), pointer.link, "meta.json"));
247
+ }
248
+ catch {
249
+ return pointer;
250
+ }
251
+ if (!meta.closed && (pointer.role !== "conductor" || isConductorOfRecord(meta, sid)))
252
+ return pointer;
253
+ fs.rmSync(pointerPath(root, sid), { force: true });
254
+ return null;
255
+ }
256
+ /** Keep retrying a non-blocking stdin for this long in total before giving up. */
257
+ const STDIN_EAGAIN_LIMIT_MS = 30_000;
258
+ function sleepSync(milliseconds) {
259
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, milliseconds);
260
+ }
261
+ /**
262
+ * Read all of stdin synchronously. `fs.readFileSync(0)` throws EAGAIN on a
263
+ * non-blocking stdin (some hosts hand one over) and EOF on a Windows console,
264
+ * so read in chunks: wait and retry on EAGAIN, and treat EOF as end of input.
265
+ */
266
+ export function readStdinSync(read = (fd, buffer) => fs.readSync(fd, buffer), sleep = sleepSync) {
267
+ const chunks = [];
268
+ const buffer = Buffer.alloc(64 * 1024);
269
+ let waited = 0;
270
+ for (;;) {
271
+ let count;
272
+ try {
273
+ count = read(0, buffer);
274
+ }
275
+ catch (error) {
276
+ const code = error.code;
277
+ if (code === "EOF")
278
+ break;
279
+ if (code === "EAGAIN" && waited < STDIN_EAGAIN_LIMIT_MS) {
280
+ sleep(10);
281
+ waited += 10;
282
+ continue;
283
+ }
284
+ throw error;
285
+ }
286
+ if (count === 0)
287
+ break;
288
+ chunks.push(Buffer.from(buffer.subarray(0, count)));
289
+ }
290
+ return Buffer.concat(chunks).toString("utf8");
291
+ }
292
+ /** `provided` is true when the caller passed a token at all, even an empty one. */
293
+ function readHandoverToken(options) {
294
+ if (options.tokenFile)
295
+ return { provided: true, token: fs.readFileSync(options.tokenFile, "utf8").trim() || undefined };
296
+ if (options.token === "-") {
297
+ const read = options.readStdin ?? (() => readStdinSync());
298
+ return { provided: true, token: read().trim() || undefined };
299
+ }
300
+ if (options.token === undefined)
301
+ return { provided: false, token: undefined };
302
+ return { provided: true, token: options.token.trim() || undefined };
303
+ }
304
+ /**
305
+ * Run fn on the conductor queue only while `sid` is the conductor of record.
306
+ * The check runs inside the queue lock, and adopt rebinds the conductor while
307
+ * holding the same lock, so a former conductor cannot drain a batch in the
308
+ * window around an adopt. Returns null when `sid` is not the conductor.
309
+ */
310
+ function withConductorQueue(root, link, sid, fn) {
311
+ const inbox = queueDir(root, link);
312
+ return withLinkQueueLock(inbox, () => {
313
+ if (!isConductorOfRecord(readJson(path.join(rootDir(root), link, "meta.json")), sid))
314
+ return null;
315
+ return fn(inbox);
316
+ });
317
+ }
318
+ function withLinkMetaLock(dir, fn) {
319
+ try {
320
+ return withLaneRecordFileLock(path.join(dir, "meta"), fn, { reclaimByAge: false });
321
+ }
322
+ catch (error) {
323
+ if (error instanceof LanesError && error.error === "store_lock_timeout") {
324
+ throw new LaneLinkError("link_busy", "Another session is changing this link; try again");
325
+ }
326
+ throw error;
327
+ }
328
+ }
199
329
  function queueDir(root, link, child) {
200
330
  return path.join(rootDir(root), link, child ? "children" : "up", ...(child ? [child] : []), "inbox");
201
331
  }
@@ -599,11 +729,27 @@ export async function runLaneLink(subcommand, options) {
599
729
  const pointer = readPointer(root, sid);
600
730
  if (!pointer)
601
731
  return {};
732
+ // A former conductor's leftover pointer must not drain the reports that now
733
+ // belong to the conductor of record.
602
734
  const target = hookMessage(root, pointer);
603
735
  if (options.ackMode !== undefined && options.ackMode !== "explicit")
604
736
  throw new LaneLinkError("ack_mode_invalid", "Unsupported acknowledgement mode");
605
- const claim = options.ackMode === "explicit" ? claimLinkQueue(target.inbox) : undefined;
606
- const messages = claim ? claim.messages : drainLinkQueue(target.inbox);
737
+ let claim;
738
+ let messages;
739
+ if (pointer.role === "conductor") {
740
+ await options.beforeConductorQueue?.();
741
+ const drained = withConductorQueue(root, pointer.link, sid, (inbox) => options.ackMode === "explicit"
742
+ ? { claim: claimLinkQueueUnlocked(inbox), messages: "" }
743
+ : { claim: undefined, messages: drainLinkQueueUnlocked(inbox) });
744
+ if (drained === null)
745
+ return {};
746
+ claim = drained.claim;
747
+ messages = claim ? claim.messages : drained.messages;
748
+ }
749
+ else {
750
+ claim = options.ackMode === "explicit" ? claimLinkQueue(target.inbox) : undefined;
751
+ messages = claim ? claim.messages : drainLinkQueue(target.inbox);
752
+ }
607
753
  if (!messages)
608
754
  return {};
609
755
  const receipt = claim ? { _hqLinkDelivery: { version: 1, sessionId: sid, link: pointer.link, child: pointer.name ?? null, claims: claim.claims } } : {};
@@ -627,12 +773,24 @@ export async function runLaneLink(subcommand, options) {
627
773
  throw new LaneLinkError("claim_owner_invalid", "Receipt does not match the current link/child binding");
628
774
  }
629
775
  const claims = options.claims?.split(",");
630
- acknowledgeLinkClaims(hookMessage(root, pointer).inbox, claims);
776
+ const target = hookMessage(root, pointer);
777
+ if (pointer.role === "conductor") {
778
+ // Check the conductor of record inside the queue lock, like read and
779
+ // _deliver: an adopt that commits after a check made outside the lock
780
+ // would let the former conductor consume claims owed to the new one.
781
+ await options.beforeConductorQueue?.();
782
+ const acked = withConductorQueue(root, pointer.link, currentSid, (inbox) => { acknowledgeLinkClaimsUnlocked(inbox, claims); return true; });
783
+ if (acked === null)
784
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${pointer.link}; it was handed over to another session`);
785
+ }
786
+ else {
787
+ acknowledgeLinkClaims(target.inbox, claims);
788
+ }
631
789
  return { output: { acknowledged: true, acceptance: "recipient_instruction_only" } };
632
790
  }
633
791
  if (subcommand === "open") {
634
792
  const sessionId = requireSid();
635
- const p = readPointer(root, sessionId);
793
+ const p = dropStalePointer(root, sessionId);
636
794
  if (p) {
637
795
  if (p.role !== "conductor")
638
796
  throw new LaneLinkError("session_already_child", `This session is already a child of ${p.link}; leave first`);
@@ -652,7 +810,7 @@ export async function runLaneLink(subcommand, options) {
652
810
  if (subcommand === "join") {
653
811
  const sessionId = requireSid();
654
812
  const dir = linkPath(root, options.link);
655
- if (readPointer(root, sessionId))
813
+ if (dropStalePointer(root, sessionId))
656
814
  throw new LaneLinkError("session_already_linked", "This session is already linked; leave first");
657
815
  const name = options.name || `s-${sessionId.replace(/[^A-Za-z0-9]/g, "").slice(0, 8)}`;
658
816
  if (!safeId(name) || name === "all")
@@ -725,9 +883,15 @@ export async function runLaneLink(subcommand, options) {
725
883
  // Preserve explicit-link validation errors before resolving ownership.
726
884
  if (role === "conductor" && options.link !== undefined)
727
885
  linkPath(root, options.link);
728
- const resolved = resolvePointer(root, requireSid(), role, options);
886
+ const sessionId = requireSid();
887
+ const resolved = resolvePointer(root, sessionId, role, options);
729
888
  linkPath(root, resolved.link);
730
- const text = drainLinkQueue(queueDir(root, resolved.link, role === "child" ? resolved.child : undefined));
889
+ if (role === "child")
890
+ return { output: { messages: drainLinkQueue(queueDir(root, resolved.link, resolved.child)) } };
891
+ await options.beforeConductorQueue?.();
892
+ const text = withConductorQueue(root, resolved.link, sessionId, (inbox) => drainLinkQueueUnlocked(inbox));
893
+ if (text === null)
894
+ throw new LaneLinkError("link_role_invalid", `This session no longer conducts ${resolved.link}; it was handed over to another session`);
731
895
  return { output: { messages: text } };
732
896
  }
733
897
  if (subcommand === "wait") {
@@ -746,7 +910,7 @@ export async function runLaneLink(subcommand, options) {
746
910
  if (!link)
747
911
  return { output: { link: null, children: [] } };
748
912
  const dir = linkPath(root, link);
749
- const meta = readJson(path.join(dir, "meta.json"));
913
+ const { handover: _handover, ...meta } = readJson(path.join(dir, "meta.json"));
750
914
  const unread = countPending(path.join(dir, "up", "inbox"));
751
915
  return { output: { ...meta, unread_reports: unread, quarantined_reports: countQuarantined(path.join(dir, "up", "inbox")), children: listChildren(root, dir) } };
752
916
  }
@@ -763,24 +927,155 @@ export async function runLaneLink(subcommand, options) {
763
927
  fs.rmdirSync(path.dirname(pointerPath(root, sessionId)));
764
928
  return { output: { link: pointer.link, left: child } };
765
929
  }
930
+ if (subcommand === "handover") {
931
+ // Only the conductor of record can authorize a successor. The pointer check
932
+ // in resolvePointer runs before the lock, so check meta again inside it: an
933
+ // adopt that finished in between makes this session a former conductor.
934
+ const sessionId = requireSid();
935
+ const pointer = resolvePointer(root, sessionId, "conductor", options);
936
+ const dir = linkPath(root, pointer.link);
937
+ const token = randomBytes(24).toString("hex");
938
+ const issued = now();
939
+ const expires = new Date(issued.getTime() + HANDOVER_TTL_MS).toISOString();
940
+ withLinkMetaLock(dir, () => {
941
+ const meta = readJson(path.join(dir, "meta.json"));
942
+ if (meta.closed)
943
+ throw new LaneLinkError("link_closed", `The link was closed: ${pointer.link}`);
944
+ assertConductorOfRecord(root, pointer.link, sessionId, meta);
945
+ atomicJson(path.join(dir, "meta.json"), { ...meta, handover: { token_sha256: sha256(token), issued: issued.toISOString(), expires } });
946
+ });
947
+ // The token is printed once. The successor should pass it on stdin or in a
948
+ // file, not on argv, where other processes can read it.
949
+ return { output: { link: pointer.link, token, expires, adopt: `hq lanes link adopt --link ${pointer.link} --token -` } };
950
+ }
951
+ if (subcommand === "adopt") {
952
+ const sessionId = requireSid();
953
+ const dir = linkPath(root, options.link);
954
+ const link = options.link;
955
+ const { provided: tokenProvided, token } = readHandoverToken(options);
956
+ const current = dropStalePointer(root, sessionId);
957
+ if (current?.role === "conductor" && current.link === link) {
958
+ return { output: { link, conductor_session: sessionId, adopted: false } };
959
+ }
960
+ if (current)
961
+ throw new LaneLinkError("session_already_linked", `This session is already a ${current.role} on ${current.link}; leave or close it first`);
962
+ return withLinkMetaLock(dir, () => {
963
+ const meta = readJson(path.join(dir, "meta.json"));
964
+ if (meta.closed)
965
+ throw new LaneLinkError("link_closed", `The link was closed: ${link}`);
966
+ const previous = typeof meta.conductor_session === "string" && safeId(meta.conductor_session) ? meta.conductor_session : "";
967
+ const held = previous ? readPointer(root, previous) : null;
968
+ const previousHolds = held?.role === "conductor" && held.link === link;
969
+ // A successor needs the handover token while the conductor of record
970
+ // still holds the link. Without one, it may only adopt a link that the
971
+ // previous conductor no longer holds. A child or any other linked session
972
+ // is refused above, so no session can take over a link it was not given.
973
+ if (previousHolds && !handoverTokenValid(meta.handover, token, now())) {
974
+ throw new LaneLinkError(tokenProvided ? "handover_token_invalid" : "link_owned", tokenProvided
975
+ ? `The handover token for ${link} is wrong, used, or expired; ask the conductor of record to run hq lanes link handover again`
976
+ : `Link ${link} is held by conductor session ${previous}; that session must run hq lanes link handover and pass you the token`);
977
+ }
978
+ const at = now().toISOString();
979
+ fs.mkdirSync(path.join(links, "by-session"), { recursive: true });
980
+ try {
981
+ fs.writeFileSync(pointerPath(root, sessionId), `conductor ${link}\n`, { mode: 0o600, flag: "wx" });
982
+ }
983
+ catch (error) {
984
+ if (error.code === "EEXIST")
985
+ throw new LaneLinkError("session_already_linked", "This session is already linked; leave first");
986
+ throw error;
987
+ }
988
+ const { handover: _used, ...rest } = meta;
989
+ const priorList = Array.isArray(meta.previous_conductors) ? meta.previous_conductors.filter((value) => typeof value === "string") : [];
990
+ // The recorded host session belongs to the previous conductor's host. Keep
991
+ // it only when this same session re-adopts; otherwise clear it so
992
+ // children's reports never wake the old host.
993
+ const sameSession = previous === sessionId;
994
+ const recordedHost = typeof meta.conductor_host_session === "string" ? meta.conductor_host_session : "";
995
+ const hostSession = options.hostSession ?? (sameSession ? recordedHost : "");
996
+ const hostCleared = options.hostSession === undefined && !sameSession && recordedHost !== "";
997
+ // Without --engine the link keeps its recorded engine.
998
+ const engine = options.engine || (typeof meta.engine === "string" && meta.engine) || "claude";
999
+ try {
1000
+ // Rebind while holding the conductor queue lock as well (lock order:
1001
+ // meta, then queue; queue holders never take the meta lock), so a
1002
+ // former conductor's read or delivery either drains before the
1003
+ // rebind or sees the new conductor and drains nothing.
1004
+ withLinkQueueLock(queueDir(root, link), () => {
1005
+ atomicJson(path.join(dir, "meta.json"), {
1006
+ ...rest,
1007
+ conductor_session: sessionId,
1008
+ conductor_host_session: hostSession,
1009
+ engine,
1010
+ previous_conductors: previous && !sameSession && !priorList.includes(previous) ? [...priorList, previous] : priorList,
1011
+ adopted: at,
1012
+ });
1013
+ });
1014
+ }
1015
+ catch (error) {
1016
+ fs.rmSync(pointerPath(root, sessionId), { force: true });
1017
+ throw error;
1018
+ }
1019
+ // Still inside the meta lock. If this step is lost (a crash), the old
1020
+ // pointer is harmless: every conductor command checks conductor_session.
1021
+ if (previousHolds)
1022
+ fs.rmSync(pointerPath(root, previous), { force: true });
1023
+ return {
1024
+ output: {
1025
+ link,
1026
+ conductor_session: sessionId,
1027
+ previous_conductor: previous && !sameSession ? previous : null,
1028
+ conductor_host_session: hostSession,
1029
+ engine,
1030
+ ...(hostCleared ? { host_session_cleared: true, note: "The previous conductor's host session was cleared; pass --host-session so children's reports can wake this session" } : {}),
1031
+ adopted: true,
1032
+ },
1033
+ };
1034
+ });
1035
+ }
766
1036
  if (subcommand === "close") {
767
- const pointer = resolvePointer(root, requireSid(), "conductor", options);
1037
+ const sessionId = requireSid();
1038
+ const pointer = resolvePointer(root, sessionId, "conductor", options);
768
1039
  const resolved = options.link ? { link: options.link } : pointer;
769
1040
  if (resolved.link !== pointer.link)
770
1041
  throw new LaneLinkError("link_role_invalid", "A conductor can only close its own link");
771
- const dir = linkPath(root, resolved.link);
772
- const bySession = path.join(links, "by-session");
773
- if (fs.existsSync(bySession))
774
- for (const file of fs.readdirSync(bySession)) {
775
- const [role, pointerLink] = fs.readFileSync(path.join(bySession, file), "utf8").trim().split(/\s+/);
776
- if ((role === "conductor" || role === "child") && pointerLink === resolved.link)
777
- fs.rmSync(path.join(bySession, file), { force: true });
778
- }
779
- if (fs.existsSync(bySession) && fs.readdirSync(bySession).length === 0)
780
- fs.rmdirSync(bySession);
781
- const meta = readJson(path.join(dir, "meta.json"));
782
- atomicJson(path.join(dir, "meta.json"), { ...meta, closed: now().toISOString() });
783
- return { output: { link: resolved.link, closed: true } };
1042
+ // Not linkPath: a link that is already closed may still need its sweep
1043
+ // finished. resolvePointer above already read this link's meta.
1044
+ const dir = path.join(links, resolved.link);
1045
+ // Under the meta lock, so a concurrent adopt cannot reopen the link under a
1046
+ // new conductor after this sweep removed every pointer.
1047
+ return withLinkMetaLock(dir, () => {
1048
+ const meta = readJson(path.join(dir, "meta.json"));
1049
+ assertConductorOfRecord(root, resolved.link, sessionId, meta);
1050
+ // Mark the link closed before removing pointers. A crash in between then
1051
+ // leaves a closed link with stray pointers, never an open link with no
1052
+ // conductor pointer that anyone could adopt without a token. A link that
1053
+ // is already closed had an earlier close fail mid-sweep: finish it.
1054
+ if (!meta.closed)
1055
+ atomicJson(path.join(dir, "meta.json"), { ...meta, closed: now().toISOString() });
1056
+ const bySession = path.join(links, "by-session");
1057
+ const own = path.basename(pointerPath(root, sessionId));
1058
+ // Remove this conductor's own pointer last, so a sweep that fails part
1059
+ // way still lets this session run close again to finish it.
1060
+ if (fs.existsSync(bySession))
1061
+ for (const file of [...fs.readdirSync(bySession).filter((name) => name !== own), own]) {
1062
+ let text;
1063
+ try {
1064
+ text = fs.readFileSync(path.join(bySession, file), "utf8");
1065
+ }
1066
+ catch (error) {
1067
+ if (error.code === "ENOENT")
1068
+ continue;
1069
+ throw error;
1070
+ }
1071
+ const [role, pointerLink] = text.trim().split(/\s+/);
1072
+ if ((role === "conductor" || role === "child") && pointerLink === resolved.link)
1073
+ fs.rmSync(path.join(bySession, file), { force: true });
1074
+ }
1075
+ if (fs.existsSync(bySession) && fs.readdirSync(bySession).length === 0)
1076
+ fs.rmdirSync(bySession);
1077
+ return { output: { link: resolved.link, closed: true, ...(meta.closed ? { sweep_finished: true } : {}) } };
1078
+ });
784
1079
  }
785
1080
  throw new LaneLinkError("subcommand_unknown", `Unknown lanes link subcommand: ${subcommand}`);
786
1081
  }
@@ -24,6 +24,16 @@ export interface OutpostPrunerInstallResult {
24
24
  enabled?: boolean;
25
25
  removed?: boolean;
26
26
  }
27
+ /** The pruner's systemd service unit; exported so tests can read its command line. */
28
+ export declare function renderOutpostPrunerService(opts: {
29
+ trigger: "pressure" | "daily";
30
+ nodeBinary: string;
31
+ hqBinary: string;
32
+ hqRoot: string;
33
+ home: string;
34
+ pathEnv: string;
35
+ flagEnvironment: string;
36
+ }): string;
27
37
  export declare function renderOutpostPrunerPressureTimer(): string;
28
38
  export declare function renderOutpostPrunerDailyTimer(): string;
29
39
  export declare function defaultOutpostPrunerSystemdDir(home?: string): string;
@@ -91,7 +91,8 @@ function unitPathEnv(hqBinary, nodeBinary) {
91
91
  ];
92
92
  return [...new Set(dirs)].filter(Boolean).join(":");
93
93
  }
94
- function renderService(opts) {
94
+ /** The pruner's systemd service unit; exported so tests can read its command line. */
95
+ export function renderOutpostPrunerService(opts) {
95
96
  const command = [
96
97
  opts.nodeBinary,
97
98
  opts.hqBinary,
@@ -183,9 +184,9 @@ export function installOutpostPrunerTimers(options) {
183
184
  ].join("\n");
184
185
  const pathEnv = unitPathEnv(hqBinary, nodeBinary);
185
186
  const units = [
186
- [OUTPOST_PRUNER_PRESSURE_SERVICE, renderService({ trigger: "pressure", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
187
+ [OUTPOST_PRUNER_PRESSURE_SERVICE, renderOutpostPrunerService({ trigger: "pressure", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
187
188
  [OUTPOST_PRUNER_PRESSURE_TIMER, renderOutpostPrunerPressureTimer()],
188
- [OUTPOST_PRUNER_DAILY_SERVICE, renderService({ trigger: "daily", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
189
+ [OUTPOST_PRUNER_DAILY_SERVICE, renderOutpostPrunerService({ trigger: "daily", nodeBinary, hqBinary, hqRoot: options.hqRoot, home, pathEnv, flagEnvironment })],
189
190
  [OUTPOST_PRUNER_DAILY_TIMER, renderOutpostPrunerDailyTimer()],
190
191
  ];
191
192
  let written = false;
package/dist/main.js CHANGED
@@ -10,7 +10,7 @@ import fs from "node:fs";
10
10
  import path from "node:path";
11
11
  import { fileURLToPath } from "node:url";
12
12
  import { Command } from "commander";
13
- import { finishSentrySession, initSentry, Sentry } from "./sentry.js";
13
+ import { closeSentryTransport, finishSentrySession, initSentry, Sentry } from "./sentry.js";
14
14
  import { addCommandBreadcrumb } from "./utils/command-breadcrumb.js";
15
15
  import { environmentalFsErrorMessage, filesystemErrorCaptureContext, filesystemErrorMessage, } from "./utils/environmental-error.js";
16
16
  import { syncStateLockMessage } from "./utils/sync-state-lock-error.js";
@@ -366,6 +366,8 @@ export async function runCli() {
366
366
  ...limitNoticeExposureFlushes,
367
367
  ...limitNoticeEngagementFlushes,
368
368
  ], releaseHealthTimeoutMs);
369
+ // The flush above is bounded; do not leave its keep-alive socket open.
370
+ closeSentryTransport();
369
371
  });
370
372
  // Last, so it wins over anything the (skipped) command path would have
371
373
  // set: the re-exec'd child's status IS this invocation's result.
@@ -5,6 +5,8 @@ type SentryBreadcrumb = Parameters<SentryModule["addBreadcrumb"]>[0];
5
5
  export declare function createFlaggedBeforeSend(beforeSend: NodeOptions["beforeSend"], skipManualOnlyReportsEnabled?: () => Promise<boolean>): NonNullable<NodeOptions["beforeSend"]>;
6
6
  export declare function initSentryRuntime(beforeSend: NodeOptions["beforeSend"], overrides?: Partial<Pick<NodeOptions, "transport">>, pendingBreadcrumbs?: readonly SentryBreadcrumb[]): SentryModule | undefined;
7
7
  export declare function finishSentryRuntimeSession(): void;
8
+ /** Close the transport's sockets once the final flush is done. */
9
+ export declare function closeSentryRuntimeTransport(): void;
8
10
  export declare function addSentryRuntimeBreadcrumb(breadcrumb: SentryBreadcrumb): void;
9
11
  export declare function flushSentryRuntime(timeoutMs: number): PromiseLike<boolean>;
10
12
  export {};