@indigoai-us/hq-cli 5.345.212-beta.0 → 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 (119) hide show
  1. package/CHANGELOG.md +40 -1
  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/command-registration-plan.d.ts +15 -0
  6. package/dist/command-registration-plan.js +20 -1
  7. package/dist/commands/agent-inbox.d.ts +11 -1
  8. package/dist/commands/agent-inbox.js +128 -38
  9. package/dist/commands/agent-kit.js +2 -2
  10. package/dist/commands/agents.js +6 -1
  11. package/dist/commands/billing.js +17 -4
  12. package/dist/commands/core-handoff.js +1 -0
  13. package/dist/commands/core-hq-session-native.js +2 -2
  14. package/dist/commands/core-pin-native.js +1 -1
  15. package/dist/commands/core-policy.js +1 -1
  16. package/dist/commands/core-resolve-company-native.js +1 -1
  17. package/dist/commands/core-sentry-report-fast.d.ts +2 -0
  18. package/dist/commands/core-sentry-report-fast.js +3 -1
  19. package/dist/commands/daemon.js +68 -6
  20. package/dist/commands/files.js +2 -2
  21. package/dist/commands/integrations-api.d.ts +11 -0
  22. package/dist/commands/integrations-connect.d.ts +9 -1
  23. package/dist/commands/integrations-connect.js +154 -18
  24. package/dist/commands/integrations-core.d.ts +1 -1
  25. package/dist/commands/integrations-core.js +18 -10
  26. package/dist/commands/integrations.js +1 -1
  27. package/dist/commands/lanes-link.js +10 -5
  28. package/dist/commands/lanes.js +34 -16
  29. package/dist/commands/rescue.js +13 -0
  30. package/dist/commands/secrets.d.ts +11 -0
  31. package/dist/commands/secrets.js +41 -7
  32. package/dist/index.js +2 -0
  33. package/dist/lazy-commands.js +6 -1
  34. package/dist/lib/agent-kit/inbox-fetch.d.ts +122 -1
  35. package/dist/lib/agent-kit/inbox-fetch.js +215 -3
  36. package/dist/lib/agent-kit/inbox-redact.js +1 -1
  37. package/dist/lib/agent-kit/inbox-state.d.ts +98 -1
  38. package/dist/lib/agent-kit/inbox-state.js +261 -4
  39. package/dist/lib/agent-kit/mcp/tools.d.ts +3 -3
  40. package/dist/lib/agent-kit/mcp/tools.js +68 -25
  41. package/dist/lib/agent-kit/run/inbox.js +4 -2
  42. package/dist/lib/agent-kit/skills.js +4 -1
  43. package/dist/lib/agent-kit/wake.d.ts +9 -1
  44. package/dist/lib/agent-kit/wake.js +10 -3
  45. package/dist/lib/billing/usage-only.d.ts +4 -1
  46. package/dist/lib/billing/usage-only.js +7 -2
  47. package/dist/lib/bot/fleet-cron.js +193 -14
  48. package/dist/lib/bot/fleet-download.d.ts +2 -0
  49. package/dist/lib/bot/fleet-download.js +23 -0
  50. package/dist/lib/bot/fleet-local.d.ts +1 -0
  51. package/dist/lib/bot/fleet-local.js +41 -8
  52. package/dist/lib/capacity/ledger.d.ts +7 -0
  53. package/dist/lib/capacity/ledger.js +31 -1
  54. package/dist/lib/capacity/project.d.ts +1 -1
  55. package/dist/lib/capacity/project.js +13 -4
  56. package/dist/lib/capacity/route.d.ts +10 -0
  57. package/dist/lib/capacity/route.js +16 -0
  58. package/dist/lib/core-utils/session-id.d.ts +1 -1
  59. package/dist/lib/core-utils/session-id.js +4 -0
  60. package/dist/lib/daemon/install.d.ts +15 -0
  61. package/dist/lib/daemon/install.js +31 -0
  62. package/dist/lib/daemon/migrate.js +29 -4
  63. package/dist/lib/daemon/run.js +9 -1
  64. package/dist/lib/daemon/updater.d.ts +34 -2
  65. package/dist/lib/daemon/updater.js +51 -2
  66. package/dist/lib/doctor/__testing__/run-doctor.js +4 -0
  67. package/dist/lib/doctor/checks/jq.d.ts +27 -0
  68. package/dist/lib/doctor/checks/jq.js +82 -0
  69. package/dist/lib/doctor/checks/release-links.d.ts +50 -8
  70. package/dist/lib/doctor/checks/release-links.js +260 -24
  71. package/dist/lib/doctor/fix/apply.js +24 -8
  72. package/dist/lib/doctor/fix/remediation.js +15 -5
  73. package/dist/lib/doctor/registry.js +4 -0
  74. package/dist/lib/flag-snapshot-file.js +36 -8
  75. package/dist/lib/install/codex-targets.d.ts +52 -1
  76. package/dist/lib/install/codex-targets.js +77 -2
  77. package/dist/lib/lanes/autopilot-registry.d.ts +14 -0
  78. package/dist/lib/lanes/autopilot-registry.js +59 -7
  79. package/dist/lib/lanes/links.d.ts +14 -0
  80. package/dist/lib/lanes/links.js +320 -25
  81. package/dist/lib/lanes/monitor.d.ts +4 -1
  82. package/dist/lib/lanes/monitor.js +47 -10
  83. package/dist/lib/lanes/outpost-pruner-install.d.ts +10 -0
  84. package/dist/lib/lanes/outpost-pruner-install.js +4 -3
  85. package/dist/lib/lanes/spawn.js +8 -1
  86. package/dist/lib/lanes/watch.js +31 -0
  87. package/dist/lib/onboarding/checkpoint.d.ts +6 -0
  88. package/dist/lib/onboarding/checkpoint.js +6 -0
  89. package/dist/lib/onboarding/orchestrator.d.ts +3 -1
  90. package/dist/lib/onboarding/orchestrator.js +62 -9
  91. package/dist/lib/onboarding/types.d.ts +8 -0
  92. package/dist/lib/work-context/organize.d.ts +23 -1
  93. package/dist/lib/work-context/organize.js +25 -3
  94. package/dist/lib/work-context/reconcile.js +3 -2
  95. package/dist/main.js +3 -1
  96. package/dist/secrets-env-action.js +7 -5
  97. package/dist/sentry-init.d.ts +2 -0
  98. package/dist/sentry-init.js +13 -2
  99. package/dist/sentry.d.ts +2 -0
  100. package/dist/sentry.js +5 -1
  101. package/dist/startup-registration.js +7 -2
  102. package/dist/utils/billing-gate.d.ts +12 -16
  103. package/dist/utils/billing-gate.js +17 -18
  104. package/dist/utils/cli-network-lifecycle.d.ts +9 -0
  105. package/dist/utils/cli-network-lifecycle.js +52 -0
  106. package/dist/utils/install-tree-torn.d.ts +22 -4
  107. package/dist/utils/install-tree-torn.js +24 -0
  108. package/dist/utils/registration-plan-error.d.ts +22 -0
  109. package/dist/utils/registration-plan-error.js +27 -0
  110. package/dist/utils/safe-link.d.ts +63 -0
  111. package/dist/utils/safe-link.js +246 -0
  112. package/dist/utils/sentry-fingerprint.js +3 -0
  113. package/dist/utils/sentry-keepalive-transport.d.ts +28 -0
  114. package/dist/utils/sentry-keepalive-transport.js +70 -0
  115. package/dist/utils/unauthorized-error.d.ts +36 -0
  116. package/dist/utils/unauthorized-error.js +105 -0
  117. package/dist/utils/vault-api.js +7 -5
  118. package/package.json +7 -7
  119. package/scripts/install-hook-engine.mjs +17 -0
@@ -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
  }
@@ -38,7 +38,10 @@ export interface LiveMonitorEvidenceOptions {
38
38
  * torn final write cannot turn into positive liveness evidence.
39
39
  */
40
40
  export declare function parseMonitorTranscript(text: string): MonitorTaskEvidence[];
41
- /** Return argv only for the exact command form the gate arms. */
41
+ /**
42
+ * Return argv only for the exact command form the gate arms:
43
+ * `[HQ_ROOT=<path>] hq {lanes|runners} watch <lane-id>...`.
44
+ */
42
45
  export declare function parseCanonicalWatchCommand(command: string): string[] | null;
43
46
  /**
44
47
  * A Monitor covers its lanes only inside the 30-minute cap. `persistent` is
@@ -187,19 +187,55 @@ export function parseMonitorTranscript(text) {
187
187
  outputPath: item.outputPath,
188
188
  }));
189
189
  }
190
- /** Return argv only for the exact command form the gate arms. */
191
- export function parseCanonicalWatchCommand(command) {
192
- const tokens = command.trim().split(/\s+/u);
190
+ // One optional leading `HQ_ROOT=<path>` assignment. `hq lanes watch` reads
191
+ // $HQ_ROOT first, and a senior whose cwd is a repo outside the HQ tree has no
192
+ // other way to point the watch at the HQ root (feedback_b6b59676). The value
193
+ // is a bare word or a single- or double-quoted string; nothing else is
194
+ // accepted before the hq executable.
195
+ //
196
+ // The value may hold only path characters: letters, digits, `/ . _ - ~`, and
197
+ // spaces inside quotes. Anything the shell would act on (`$(...)`, `$VAR`,
198
+ // backticks, `\`, `;`, `|`, `&`, `<`, `>`, `#`) is rejected in every form, so
199
+ // a prefix can never redirect the watch's output, end the command before the
200
+ // watch, or run something else instead (review of hq-cli #2544).
201
+ // The hyphen is escaped so appending a space to the class can never form a range.
202
+ const HQ_ROOT_PATH_CHARS = "A-Za-z0-9/._~\\-";
203
+ const HQ_ROOT_ASSIGNMENT_PREFIX = new RegExp(`^HQ_ROOT=(?:'[${HQ_ROOT_PATH_CHARS} ]+'|"[${HQ_ROOT_PATH_CHARS} ]+"|[${HQ_ROOT_PATH_CHARS}]+)[ \\t]+`, "u");
204
+ /** The hq executable: a bare `hq` or a path to it, in path characters only. */
205
+ const HQ_EXECUTABLE_TOKEN = new RegExp(`^[${HQ_ROOT_PATH_CHARS}]+$`, "u");
206
+ function parseWatchCommand(command) {
207
+ // A shell splits words only on space, tab and newline. Unicode and control
208
+ // whitespace (NBSP, VT, FF, CR, ...) stays inside a word there, and a newline
209
+ // ends the command. So the gate accepts only printable ASCII and tab between
210
+ // the leading and trailing blanks, and splits on spaces and tabs alone
211
+ // (review of hq-cli #2544).
212
+ const trimmed = command.replace(/^[ \t\n]+|[ \t\n]+$/gu, "");
213
+ if (!/^[\x20-\x7e\t]*$/u.test(trimmed))
214
+ return null;
215
+ const body = trimmed.replace(HQ_ROOT_ASSIGNMENT_PREFIX, "");
216
+ const tokens = body.split(/[ \t]+/u);
193
217
  if (tokens.length < 4)
194
218
  return null;
219
+ // A prefix the assignment pattern refused stays in front of the executable;
220
+ // this keeps a token such as `HQ_ROOT=/x>/tmp/hq` from passing as `hq`.
221
+ if (!HQ_EXECUTABLE_TOKEN.test(tokens[0]))
222
+ return null;
195
223
  const executable = path.basename(tokens[0]);
196
- if (executable !== "hq" || (tokens[1] !== "runners" && tokens[1] !== "lanes") || tokens[2] !== "watch") {
224
+ const group = tokens[1];
225
+ if (executable !== "hq" || (group !== "runners" && group !== "lanes") || tokens[2] !== "watch") {
197
226
  return null;
198
227
  }
199
228
  const laneIds = tokens.slice(3);
200
229
  if (laneIds.some((laneId) => !LANE_ID_PATTERN.test(laneId)))
201
230
  return null;
202
- return laneIds;
231
+ return { group, laneIds };
232
+ }
233
+ /**
234
+ * Return argv only for the exact command form the gate arms:
235
+ * `[HQ_ROOT=<path>] hq {lanes|runners} watch <lane-id>...`.
236
+ */
237
+ export function parseCanonicalWatchCommand(command) {
238
+ return parseWatchCommand(command)?.laneIds ?? null;
203
239
  }
204
240
  function taskOutputIsTerminal(outputText) {
205
241
  return outputText ? TERMINAL_TASK_OUTPUT.test(outputText) : false;
@@ -423,13 +459,13 @@ function isHqInvocationPrefix(prefix) {
423
459
  isHqExecutablePath(prefix.slice(runtimeEnd + 1)));
424
460
  }
425
461
  function processHasExactCommand(processCommands, command) {
426
- const laneIds = parseCanonicalWatchCommand(command);
427
- if (!laneIds)
462
+ const parsed = parseWatchCommand(command);
463
+ if (!parsed)
428
464
  return false;
429
465
  // Match the group name the Monitor used: `hq runners watch` or the
430
- // `hq lanes watch` alias produce different process lines.
431
- const groupToken = command.trim().split(/\s+/u)[1];
432
- const expectedSuffix = ` ${groupToken} watch ${laneIds.join(" ")}`;
466
+ // `hq lanes watch` alias produce different process lines. A leading
467
+ // HQ_ROOT= assignment is environment, not argv, so it never shows in ps.
468
+ const expectedSuffix = ` ${parsed.group} watch ${parsed.laneIds.join(" ")}`;
433
469
  return processCommands.some((rawLine) => {
434
470
  const line = rawLine.trim().replace(/\s+/gu, " ");
435
471
  if (!line.endsWith(expectedSuffix))
@@ -489,6 +525,7 @@ export function monitorReminderText() {
489
525
  return [
490
526
  "For active Claude senior lanes, arm one live Claude Code Monitor task per uncovered lane:",
491
527
  'Monitor(command="hq lanes watch <lane-id>...", timeout_ms=1800000)',
528
+ "When the session's cwd is outside the HQ tree, prefix the command with HQ_ROOT=<hq root> (for example HQ_ROOT=/path/to/hq hq lanes watch <lane-id>...); the gate counts that form too.",
492
529
  "Claude Code stops every Monitor after 30 minutes, so a lane stays covered only while a Monitor armed in the last 30 minutes watches it. Re-arm the same call when `hq lanes monitor-check --session <id>` reports the lane as expired.",
493
530
  "The caller must pass `--engine codex` or `--engine grok` (or set HQ_LANE_ENGINE; deprecated alias HQ_CONDUCT_ENGINE) for sessions whose engine has no Claude Monitor tool; those engines are never required to provide one.",
494
531
  ].join("\n");
@@ -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;
@@ -1358,7 +1358,14 @@ export const STANDING_AUTHORIZATION = "STANDING AUTHORIZATION. This brief author
1358
1358
  export const FOREGROUND_ONLY_RULE = "FOREGROUND ONLY. Run every command, test suite and check in the foreground and wait for it to finish. " +
1359
1359
  "Never background a process and end the turn while it is still running. " +
1360
1360
  "A turn that ends before the envelope is written is classified interrupted, " +
1361
- "and whatever the background process produces afterwards is not read.";
1361
+ "and whatever the background process produces afterwards is not read. " +
1362
+ // feedback_86552798: an /execute-task lane ended its turn while the
1363
+ // builder subagent it had started kept editing; the run left no envelope.
1364
+ "The same holds for a subagent or nested run you start (for example the builder an /execute-task phase spawns): " +
1365
+ "wait for it to finish before you write the envelope. " +
1366
+ "A Monitor or other wait tool stops after at most 30 minutes, so wait in windows shorter than that, " +
1367
+ "start the next wait when one ends, and print one line per window saying what is still running and for how long. " +
1368
+ "If a nested run cannot finish in this turn, stop it and write a blocked envelope that names it.";
1362
1369
  /**
1363
1370
  * Temp-home rule carried in every composed brief, for every provider. Lanes
1364
1371
  * that ran tests under a raw mktemp HOME re-downloaded the Rust toolchain and
@@ -110,6 +110,35 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
110
110
  suppressed = true;
111
111
  }
112
112
  };
113
+ // feedback_86552798: a running lane whose worker waits on a long nested run
114
+ // printed nothing here between its start and its end, so a senior's Monitor
115
+ // on this watch saw silence for as long as the run took (and a Monitor ends
116
+ // after 30 minutes). Report the watcher's stall flag when it is set or
117
+ // cleared, and each progress event the watcher records, so a long run reads
118
+ // as progress or as a plain stall.
119
+ const previousStall = new Map();
120
+ const previousProgress = new Map();
121
+ const emitRunningActivity = (record) => {
122
+ const stallKey = record.stalled === true ? `stalled:${record.stalled_at ?? ""}` : "ok";
123
+ const priorStall = previousStall.get(record.lane_id);
124
+ if (priorStall !== stallKey) {
125
+ if (stallKey !== "ok") {
126
+ const since = record.stalled_at ? ` since ${record.stalled_at}` : "";
127
+ const reason = record.stalled_reason ? ` (${record.stalled_reason})` : "";
128
+ emit(`lane ${record.lane_id}: stalled${since}${reason}; still running, no envelope yet`);
129
+ }
130
+ else if (priorStall !== undefined) {
131
+ emit(`lane ${record.lane_id}: progressing again`);
132
+ }
133
+ previousStall.set(record.lane_id, stallKey);
134
+ }
135
+ const progressAt = record.last_progress_event_at ?? "";
136
+ const priorProgress = previousProgress.get(record.lane_id);
137
+ if (priorProgress !== undefined && progressAt !== "" && progressAt !== priorProgress) {
138
+ emit(`lane ${record.lane_id}: progress at ${progressAt}`);
139
+ }
140
+ previousProgress.set(record.lane_id, progressAt);
141
+ };
113
142
  const unreadable = (kind, id, err) => {
114
143
  const message = `${kind} ${id}: unreadable record (${readableError(err)})`;
115
144
  writeError(`lane watch: ${message}`);
@@ -158,6 +187,8 @@ export async function runLaneWatch(hqRoot, laneIds, deps = {}) {
158
187
  emit(`lane ${record.lane_id}: state=${record.state}${terminal ? " (terminal)" : ""}`);
159
188
  previousStates.set(laneId, stateKey);
160
189
  }
190
+ if (!terminal)
191
+ emitRunningActivity(record);
161
192
  }
162
193
  const keepAliveWaiting = new Set();
163
194
  if (deps.keepAliveEnabled !== undefined) {
@@ -5,6 +5,12 @@
5
5
  * If a flow fails partway, re-running picks up from the last checkpoint.
6
6
  */
7
7
  import type { OnboardingCheckpoint, OnboardingStep } from "./types.js";
8
+ /**
9
+ * Checkpoint format version. 2: a join's invite token is saved only together
10
+ * with `inviteTokenPersonUid`, so an unbound token in a version-2 checkpoint is
11
+ * never the caller's. A checkpoint with no `version` predates that rule.
12
+ */
13
+ export declare const CHECKPOINT_VERSION = 2;
8
14
  export declare function getCheckpointPath(hqRoot: string): string;
9
15
  export declare function readCheckpoint(hqRoot: string): Promise<OnboardingCheckpoint | null>;
10
16
  export declare function writeCheckpoint(hqRoot: string, checkpoint: OnboardingCheckpoint): Promise<void>;