@indigoai-us/hq-cli 5.345.225 → 5.345.228

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -28,6 +28,8 @@ export interface ReapDeps {
28
28
  now?: () => Date;
29
29
  hostname?: () => string;
30
30
  processes?: () => ReapProcess[];
31
+ /** In-process ancestry reader, used by daemon reporting without a full ps. */
32
+ processAncestry?: (pid: number) => ReapProcess[];
31
33
  isAlive?: (pid: number) => boolean;
32
34
  readStarttime?: (pid: number) => number | null;
33
35
  sessionState?: (root: string, sessionId: string, now: Date) => string | null;
@@ -1,3 +1,4 @@
1
+ import { clearStalePidMarker } from "./orphan-sweep.js";
1
2
  /** Session-start orphan lane sweep. Every destructive action is opt-in and gated. */
2
3
  import * as fs from "node:fs";
3
4
  import { createHash } from "node:crypto";
@@ -211,7 +212,8 @@ function localRun(lane, hostname) {
211
212
  }
212
213
  export async function classifyLocalLanes(root, now, minAgeMinutes, deps = {}) {
213
214
  const hostname = deps.hostname?.() ?? os.hostname();
214
- const processes = (deps.processes ?? readProcesses)();
215
+ let processes;
216
+ const ancestry = (pid) => deps.processAncestry?.(pid) ?? (processes ??= (deps.processes ?? readProcesses)());
215
217
  const alive = deps.isAlive ?? isProcessRunning;
216
218
  const readStart = deps.readStarttime ?? readProcStarttime;
217
219
  const result = [];
@@ -281,7 +283,7 @@ export async function classifyLocalLanes(root, now, minAgeMinutes, deps = {}) {
281
283
  finding.reason = "worker_process_gone_or_pid_reused";
282
284
  finding.stale_state = staleState;
283
285
  }
284
- else if (ancestryReachesSession(worker.pid, processes))
286
+ else if (ancestryReachesSession(worker.pid, ancestry(worker.pid)))
285
287
  finding.reason = "process_has_live_session_ancestor";
286
288
  else {
287
289
  finding.orphaned = true;
@@ -356,12 +358,13 @@ export async function reapLocalLanes(root, options, deps = {}) {
356
358
  if (!expected)
357
359
  return;
358
360
  const markerPath = path.join(laneRunDir(root, finding.lane_id), marker);
359
- const current = readPidRecord(markerPath);
360
- if (!current || current.pid !== expected.pid || current.starttime !== expected.starttime)
361
- return;
362
- if (isPidRecordAlive(current, isAlive, readStart))
363
- return;
364
- fs.rmSync(markerPath, { force: true });
361
+ try {
362
+ clearStalePidMarker(root, markerPath, expected, (current) => !isPidRecordAlive(current, isAlive, readStart));
363
+ }
364
+ catch (error) {
365
+ if (error.code !== "ENOENT")
366
+ throw error;
367
+ }
365
368
  };
366
369
  let stopEnabled = false;
367
370
  for (const finding of findings) {
@@ -1,10 +1,5 @@
1
- /**
2
- * Periodic reconcile pass (spec §5.7, §6.8, §9).
3
- *
4
- * Owned by the machine, not by any lane. Reads never mutate; every write is a
5
- * compare-and-set. The per-lane watcher owns progress/terminal/silence of a
6
- * live process — this pass owns the transitions no single lane can own.
7
- */
1
+ import { type DaemonOrphanDeps } from "./orphan-report.js";
2
+ import { type OrphanMarkerDeps, type OrphanMarkerFinding } from "./orphan-sweep.js";
8
3
  import { type LivenessDeps } from "./liveness.js";
9
4
  import { type EnvelopeRepairSpawnInput, type SpawnLaneDeps } from "./spawn.js";
10
5
  import { type ThrottleDeps, type CpuBusyObservation } from "./throttle.js";
@@ -67,6 +62,9 @@ export interface ReconcileSummary {
67
62
  heartbeats: string[];
68
63
  skipped: ReconcileSkip[];
69
64
  notes?: string[];
65
+ orphan_markers?: OrphanMarkerFinding[];
66
+ uncertain_markers?: number;
67
+ orphan_count?: number;
70
68
  keep_alive_blocked: Array<{
71
69
  id: string;
72
70
  reason: KeepAliveBlockedReason;
@@ -93,6 +91,9 @@ export interface ReconcileHost {
93
91
  aliases?: readonly string[];
94
92
  }
95
93
  export interface ReconcileDeps {
94
+ /** Child-free process identity probes for stale marker maintenance. */
95
+ orphanMarkerDeps?: OrphanMarkerDeps;
96
+ orphanReportDeps?: DaemonOrphanDeps;
96
97
  now: () => Date;
97
98
  host: ReconcileHost;
98
99
  dryRun: boolean;
@@ -1,3 +1,6 @@
1
+ import { classifyDaemonOrphans, writeOrphanReport } from "./orphan-report.js";
2
+ import { LANE_ORPHAN_SWEEP_WAITING_FLAG } from "./flag-keys.js";
3
+ import { changedOrphanMarkers, snapshotOrphanMarkers, sweepOrphanMarkers } from "./orphan-sweep.js";
1
4
  /**
2
5
  * Periodic reconcile pass (spec §5.7, §6.8, §9).
3
6
  *
@@ -6,6 +9,7 @@
6
9
  * live process — this pass owns the transitions no single lane can own.
7
10
  */
8
11
  import { accountMatchesCompany } from "./account-company.js";
12
+ import { accountHeldByOther } from "./account-ownership.js";
9
13
  import * as fs from "node:fs";
10
14
  import * as path from "node:path";
11
15
  import { parseUserYaml } from "../../utils/user-yaml-error.js";
@@ -756,6 +760,29 @@ function availableBalancedAccount(hqRoot, lane, occupying, config, host, profile
756
760
  }
757
761
  return undefined;
758
762
  }
763
+ /**
764
+ * Move a queued recovering lane off a login that another person holds
765
+ * (PS-006). The write is guarded on the lane still recording that login and
766
+ * the target being one this lane may use, and it records the change in
767
+ * account_history like any other automatic account move.
768
+ */
769
+ function writeRecoveryAccountOffHeldLogin(hqRoot, lane, account, now, dryRun) {
770
+ return casLaneIf(hqRoot, lane.lane_id, (current) => {
771
+ const accounts = loadLanesConfig(hqRoot).providers[current.provider].accounts;
772
+ return current.state === "queued" &&
773
+ current.account === lane.account &&
774
+ current.account !== undefined &&
775
+ accountHeldByOther(accounts[current.account]) &&
776
+ accountMatchesCompany(accounts[account], resolveLaneCompany(hqRoot, current).company, accounts);
777
+ }, (current) => ({
778
+ ...current,
779
+ account,
780
+ account_history: [
781
+ ...(current.account_history ?? []),
782
+ { from: current.account ?? null, to: account, at: now.toISOString(), reason: "account_unavailable" },
783
+ ],
784
+ }), dryRun).record;
785
+ }
759
786
  function writeAdmissionAccount(hqRoot, lane, account, dryRun) {
760
787
  return casLaneIf(hqRoot, lane.lane_id, (current) => current.state === "queued" &&
761
788
  current.account === lane.account &&
@@ -1156,6 +1183,7 @@ export async function runPassBody(hqRoot, deps) {
1156
1183
  if (deps.terminalKeepAliveCandidate) {
1157
1184
  return runTerminalKeepAliveCandidatePass(hqRoot, lanes, summary, deps, now, deps.terminalKeepAliveCandidate);
1158
1185
  }
1186
+ const orphanMarkerSnapshot = snapshotOrphanMarkers(hqRoot, lanes, deps.host);
1159
1187
  await reconcileBlockedEscalations(hqRoot, lanes, summary, deps, now);
1160
1188
  await resumeDueQuotaHeldLanes(hqRoot, lanes, summary, deps, now);
1161
1189
  let presenceConnected;
@@ -1274,6 +1302,29 @@ export async function runPassBody(hqRoot, deps) {
1274
1302
  sessionStateCache.set(sessionId, state);
1275
1303
  return state;
1276
1304
  };
1305
+ try {
1306
+ const orphans = await classifyDaemonOrphans(hqRoot, now, {
1307
+ hostname: () => deps.host.hostname,
1308
+ onProcessReadFailure: (note) => {
1309
+ summary.notes ??= [];
1310
+ summary.notes.push(note);
1311
+ process.stderr.write(`${note}\n`);
1312
+ },
1313
+ isAlive: deps.isAlive,
1314
+ sessionState: (_root, id) => sessionState(id),
1315
+ waitingSeniorEnabled: () => (deps.readRegistryFlag ?? readLanesRegistryFlagFailOpen)(LANE_ORPHAN_SWEEP_WAITING_FLAG, { env: deps.env, defaultValue: true }),
1316
+ ...deps.orphanReportDeps,
1317
+ });
1318
+ summary.orphan_count = orphans.filter((lane) => lane.orphaned).length;
1319
+ if (!deps.dryRun)
1320
+ writeOrphanReport(hqRoot, deps.host.hostname, now, orphans);
1321
+ }
1322
+ catch (error) {
1323
+ const note = `Orphan report unavailable: ${error instanceof Error ? error.message : String(error)}`;
1324
+ summary.notes ??= [];
1325
+ summary.notes.push(note);
1326
+ process.stderr.write(`${note}\n`);
1327
+ }
1277
1328
  const questionAgeWindowMs = (audience) => audience.kind === "session"
1278
1329
  ? config.session_question_timeout_secs * 1000
1279
1330
  : QUESTION_AGE_MS;
@@ -1538,6 +1589,18 @@ export async function runPassBody(hqRoot, deps) {
1538
1589
  writeThrottleState(throttleStatePath(hqRoot), recordCpuBusyObservation(currentThrottleState, cpuObservation), admissionThrottleDeps);
1539
1590
  }
1540
1591
  }
1592
+ const markerFindings = sweepOrphanMarkers(hqRoot, lanes, deps.host, deps.dryRun, {
1593
+ isAlive: deps.isAlive,
1594
+ ...deps.orphanMarkerDeps,
1595
+ }, orphanMarkerSnapshot);
1596
+ summary.uncertain_markers = markerFindings.filter((marker) => marker.status === "uncertain").length;
1597
+ summary.orphan_markers = deps.dryRun ? markerFindings : changedOrphanMarkers(hqRoot, deps.host, markerFindings, orphanMarkerSnapshot);
1598
+ for (const marker of summary.orphan_markers) {
1599
+ const note = `hq runners marker ${marker.lane_id}/${marker.marker}: ${marker.reason}${marker.cleared ? "; cleared" : "; preserved"}`;
1600
+ summary.notes ??= [];
1601
+ summary.notes.push(note);
1602
+ process.stderr.write(`${note}\n`);
1603
+ }
1541
1604
  if (!deps.dryRun && summary.errors.length === 0) {
1542
1605
  try {
1543
1606
  writeHeartbeatFile(hqRoot, summary, nowIso);
@@ -2245,8 +2308,12 @@ async function admitQueued(hqRoot, lanes, summary, deps, now, onlyLaneIds, exclu
2245
2308
  const accounts = config.providers[admittedLane.provider].accounts;
2246
2309
  const company = resolveLaneCompany(hqRoot, admittedLane).company;
2247
2310
  let account;
2311
+ // A recorded login now held by another person is not kept (PS-006):
2312
+ // pick again among the allowed accounts instead.
2313
+ const leavingHeldLogin = admittedLane.account !== undefined && accountHeldByOther(accounts[admittedLane.account]);
2314
+ const recorded = leavingHeldLogin ? undefined : admittedLane.account;
2248
2315
  try {
2249
- account = resolveAccount(admittedLane.provider, admittedLane.account, config, {
2316
+ account = resolveAccount(admittedLane.provider, recorded, config, {
2250
2317
  hqRoot, hostname: deps.host.hostname,
2251
2318
  allowedAccounts: Object.keys(accounts).filter((id) => accountMatchesCompany(accounts[id], company, accounts)),
2252
2319
  }).id;
@@ -2257,12 +2324,25 @@ async function admitQueued(hqRoot, lanes, summary, deps, now, onlyLaneIds, exclu
2257
2324
  writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2258
2325
  continue;
2259
2326
  }
2260
- if (!accountMatchesCompany(accounts[account], company, accounts) && accounts[account]?.company !== undefined) {
2327
+ if (accountHeldByOther(accounts[account]) ||
2328
+ (!accountMatchesCompany(accounts[account], company, accounts) && accounts[account]?.company !== undefined)) {
2261
2329
  writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2262
2330
  continue;
2263
2331
  }
2264
- if (admittedLane.account !== account)
2332
+ if (leavingHeldLogin) {
2333
+ // writeAdmissionAccount only moves within admission_accounts, which a
2334
+ // recovering lane usually lacks. Leaving another person's login is not
2335
+ // an admission choice: write the move directly, and never spawn the
2336
+ // lane while it still records that login (PS-006).
2337
+ admittedLane = writeRecoveryAccountOffHeldLogin(hqRoot, admittedLane, account, now, deps.dryRun);
2338
+ if (admittedLane.account !== account) {
2339
+ writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2340
+ continue;
2341
+ }
2342
+ }
2343
+ else if (admittedLane.account !== account) {
2265
2344
  admittedLane = writeAdmissionAccount(hqRoot, admittedLane, account, deps.dryRun);
2345
+ }
2266
2346
  const status = accountStatus(admittedLane.provider, account, config, {
2267
2347
  hostname: deps.host.hostname,
2268
2348
  existsSync: (file) => fs.existsSync(file),
@@ -410,16 +410,6 @@ export type EnvelopeRepairMode = "resume" | "fresh_turn";
410
410
  * path was built and proven that way, and a repair by resume has not been.
411
411
  */
412
412
  export declare function envelopeRepairMode(provider: LaneProvider): EnvelopeRepairMode;
413
- /**
414
- * Spec §4 repair turn. The lane is still `running` (the watcher has not
415
- * written a terminal state), so this does not claim or transition the
416
- * record. It resumes the recorded provider session with the repair prompt
417
- * (`resume` mode), or for a provider with no session resume runs the repair
418
- * prompt as a fresh single turn on the same account (`fresh_turn` mode). It
419
- * replaces `worker.pid` and rewrites `spawn.json` so the watcher's next tick
420
- * follows the new process. The account is the one already bound on the record.
421
- * Fast-mode evidence is updated after the replacement is proven detached.
422
- */
423
413
  export declare function spawnEnvelopeRepair(hqRoot: string, lane: LaneRecord, input: EnvelopeRepairSpawnInput, deps?: SpawnLaneDeps): number;
424
414
  export { PROVIDER_HOME_ENV, PROVIDER_COMMAND };
425
415
  //# sourceMappingURL=spawn.d.ts.map
@@ -8,6 +8,7 @@
8
8
  * mutable fields are re-read from the lane record (spec §5.4).
9
9
  */
10
10
  import { accountMatchesCompany, accountMayRetainLane, companyMismatchError } from "./account-company.js";
11
+ import { accountHeldByOther } from "./account-ownership.js";
11
12
  import { spawn, spawnSync } from "node:child_process";
12
13
  import { randomUUID } from "node:crypto";
13
14
  import * as fs from "node:fs";
@@ -282,7 +283,13 @@ function selectSpawnAccount(input) {
282
283
  let refusal;
283
284
  const operatorMovePending = lane.pending_resume !== undefined &&
284
285
  lane.account_history?.at(-1)?.reason === "operator_move";
285
- if (current !== undefined && !accountMayRetainLane(current, resolveLaneCompany(hqRoot, lane).company, config.providers[lane.provider].accounts)) {
286
+ if (current !== undefined && accountHeldByOther(current)) {
287
+ reason = "account_unavailable";
288
+ refusal = new LanesError("account_held_by_other", "The lane's recorded login is held by another person and is not used for lanes", {
289
+ provider: lane.provider, account: lane.account,
290
+ });
291
+ }
292
+ else if (current !== undefined && !accountMayRetainLane(current, resolveLaneCompany(hqRoot, lane).company, config.providers[lane.provider].accounts)) {
286
293
  reason = "account_unavailable";
287
294
  refusal = new LanesError("account_company_mismatch", `Account ${lane.account} belongs to another company`, {
288
295
  provider: lane.provider, account: lane.account,
@@ -2565,6 +2572,30 @@ export function spawnLaneWorker(hqRoot, lane, deps = {}, launch = {}) {
2565
2572
  }
2566
2573
  throw err;
2567
2574
  }
2575
+ if (err instanceof LanesError && err.error === "account_held_by_other") {
2576
+ // PS-006: the lane's login is held by another person and no other login
2577
+ // can take it. Record why it waits, once, instead of leaving it queued
2578
+ // with no reason and logging a bind failure on every tick.
2579
+ let recorded = false;
2580
+ retryUpdateLane(hqRoot, lane.lane_id, "spawn", (current) => {
2581
+ if (current.state !== "queued")
2582
+ return current;
2583
+ if (current.queued_reason === "admit_failed" && current.queued_details?.reason === "admit_failed" &&
2584
+ current.queued_details.error === err.error)
2585
+ return current;
2586
+ recorded = true;
2587
+ return {
2588
+ ...current,
2589
+ queued_reason: "admit_failed",
2590
+ queued_details: { reason: "admit_failed", error: err.error, message: err.message },
2591
+ admission_reserved_at: undefined,
2592
+ };
2593
+ });
2594
+ if (recorded) {
2595
+ process.stderr.write(`hq lanes: lane ${lane.lane_id} waits: ${err.message}\n`);
2596
+ }
2597
+ throw err;
2598
+ }
2568
2599
  process.stderr.write(`hq lanes: account bind failed for ${lane.lane_id}: ${err instanceof Error ? err.message : String(err)}\n`);
2569
2600
  throw err;
2570
2601
  }
@@ -3289,6 +3320,20 @@ export function envelopeRepairMode(provider) {
3289
3320
  * follows the new process. The account is the one already bound on the record.
3290
3321
  * Fast-mode evidence is updated after the replacement is proven detached.
3291
3322
  */
3323
+ function assertRepairAccountUsable(hqRoot, lane, config) {
3324
+ if (lane.account === undefined)
3325
+ return;
3326
+ const accounts = config.providers[lane.provider].accounts;
3327
+ const account = accounts[lane.account];
3328
+ if (accountHeldByOther(account)) {
3329
+ throw new LanesError("account_held_by_other", `Envelope repair refused: login ${lane.account} is held by ${account?.holder ?? "another person"}, not the owner, and is not used for lanes`, { provider: lane.provider, account: lane.account, holder: account?.holder ?? null });
3330
+ }
3331
+ if (account !== undefined && !accountMayRetainLane(account, resolveLaneCompany(hqRoot, lane).company, accounts)) {
3332
+ throw new LanesError("account_company_mismatch", `Envelope repair refused: account ${lane.account} belongs to another company`, {
3333
+ provider: lane.provider, account: lane.account,
3334
+ });
3335
+ }
3336
+ }
3292
3337
  export function spawnEnvelopeRepair(hqRoot, lane, input, deps = {}) {
3293
3338
  const env = deps.env ?? process.env;
3294
3339
  const hostname = accountHomeHostname(deps);
@@ -3305,6 +3350,11 @@ export function spawnEnvelopeRepair(hqRoot, lane, input, deps = {}) {
3305
3350
  const logsDir = path.join(runDir, "logs");
3306
3351
  ensureDir(logsDir);
3307
3352
  const config = loadLanesConfig(hqRoot);
3353
+ // PS-006: the repair turn runs in the lane's recorded login, so it gets the
3354
+ // same ownership checks as any spawn. It cannot move the session to another
3355
+ // login (the transcript lives in that home), so it refuses; the failed turn
3356
+ // then ends normally and the next spawn or resume moves the lane off.
3357
+ assertRepairAccountUsable(hqRoot, lane, config);
3308
3358
  const profile = lane.worker_profile
3309
3359
  ? loadWorkerProfileWithRegistry(hqRoot, lane.worker_profile, {
3310
3360
  laneCompany: lane.company?.slug ?? lane.mesh_company?.slug,
@@ -1210,6 +1210,18 @@ export interface LaneEnvelope {
1210
1210
  export interface AccountConfig {
1211
1211
  /** Company slug or UID owning this account. Untagged accounts are personal. */
1212
1212
  company?: string;
1213
+ /**
1214
+ * The business that owns this login: a company slug, `personal` or
1215
+ * `unknown`. Recorded for reporting and ranking only (PS-006, D5); it never
1216
+ * restricts which lanes may use the login. `company` above is the filter.
1217
+ */
1218
+ owning_company?: string;
1219
+ /**
1220
+ * Who holds this login: `owner` (the person this HQ belongs to) or another
1221
+ * named person. Logins held by another person are never picked for lanes and
1222
+ * are listed without their account id in `hq runners capacity`.
1223
+ */
1224
+ holder?: string;
1213
1225
  home: string;
1214
1226
  /** Optional account home overrides keyed by the owning host's hostname. */
1215
1227
  hosts?: Record<string, AccountHostHome>;
@@ -167,6 +167,19 @@ export declare function hasCurrentAcknowledgedRegistration(ref: HeldSessionRef,
167
167
  * their disposition; this backfill never mutates or deletes held lines).
168
168
  */
169
169
  export declare function readHeldSessions(workMeshRoot: string): HeldSessionRef[];
170
+ /** A real held backfill was asked for on a machine in emit mode "direct". */
171
+ export declare class HeldBackfillRefusedError extends Error {
172
+ readonly code: "HELD_BACKFILL_REFUSED_DIRECT_MODE";
173
+ constructor();
174
+ }
175
+ /**
176
+ * backfillHeldSessions behind the emit mode. In direct mode a real run is
177
+ * refused before anything is read, written or delivered (the direct-mode
178
+ * drain trusts session state, so this command must not write a company the
179
+ * session's own state never named). A dry run writes and delivers nothing and
180
+ * is allowed. Legacy mode is unchanged.
181
+ */
182
+ export declare function backfillHeldSessionsForMode(mode: "legacy" | "direct", deps: BackfillHeldDeps): Promise<BackfillHeldResult>;
170
183
  /**
171
184
  * Reconcile ended sessions whose held events lack a company. Idempotent:
172
185
  * re-running skips sessions that already carry a companyUid.
@@ -583,6 +583,29 @@ export function readHeldSessions(workMeshRoot) {
583
583
  }
584
584
  return [...seen.values()];
585
585
  }
586
+ /** A real held backfill was asked for on a machine in emit mode "direct". */
587
+ export class HeldBackfillRefusedError extends Error {
588
+ code = "HELD_BACKFILL_REFUSED_DIRECT_MODE";
589
+ constructor() {
590
+ super("hq mesh context backfill-held does not run in emit mode direct. It gives a held session a company from " +
591
+ "its working folder, the slug on its events or the device default, and the daemon would then send that " +
592
+ "session's events to that company. In direct mode a session is sent only to the company its own state " +
593
+ "names. Nothing was changed. --dry-run still works.");
594
+ this.name = "HeldBackfillRefusedError";
595
+ }
596
+ }
597
+ /**
598
+ * backfillHeldSessions behind the emit mode. In direct mode a real run is
599
+ * refused before anything is read, written or delivered (the direct-mode
600
+ * drain trusts session state, so this command must not write a company the
601
+ * session's own state never named). A dry run writes and delivers nothing and
602
+ * is allowed. Legacy mode is unchanged.
603
+ */
604
+ export async function backfillHeldSessionsForMode(mode, deps) {
605
+ if (mode === "direct" && !deps.dryRun)
606
+ throw new HeldBackfillRefusedError();
607
+ return backfillHeldSessions(deps);
608
+ }
586
609
  /**
587
610
  * Reconcile ended sessions whose held events lack a company. Idempotent:
588
611
  * re-running skips sessions that already carry a companyUid.
@@ -7,10 +7,14 @@
7
7
  * - "legacy" — the daemon runs the EMIT path (spool watch + flush + held +
8
8
  * outbox replay + transcript-watch fallback) AND the receive
9
9
  * subscriber. This is the default until the server route is live.
10
- * - "direct" — sessions POST events directly (see `hq mesh session`/`emit`);
11
- * the daemon runs RECEIVE-ONLY: the presence subscriber on
12
- * hq/{personUid}/mesh keeps the cache the desktop app reads warm.
13
- * No spool/held/outbox/flush/transcript-watch on this box.
10
+ * - "direct" — CLI commands POST their events directly (see `hq mesh
11
+ * session`/`emit`) and the daemon keeps the presence subscriber
12
+ * on hq/{personUid}/mesh, which keeps the cache the desktop app
13
+ * reads warm. The hooks still append session and turn events
14
+ * to the spool, so the daemon also delivers the spool on a
15
+ * timer (../direct-drain.ts; US-038, owner decision 70). No
16
+ * outbox replay, held backfill, directory watcher, shutdown
17
+ * flush or transcript-watch on this box.
14
18
  *
15
19
  * The flag is resolved from (highest first): env HQ_MESH_MODE, the work-mesh
16
20
  * config file (~/.hq/work-mesh/config.json `emitMode`), else "legacy".
@@ -7,10 +7,14 @@
7
7
  * - "legacy" — the daemon runs the EMIT path (spool watch + flush + held +
8
8
  * outbox replay + transcript-watch fallback) AND the receive
9
9
  * subscriber. This is the default until the server route is live.
10
- * - "direct" — sessions POST events directly (see `hq mesh session`/`emit`);
11
- * the daemon runs RECEIVE-ONLY: the presence subscriber on
12
- * hq/{personUid}/mesh keeps the cache the desktop app reads warm.
13
- * No spool/held/outbox/flush/transcript-watch on this box.
10
+ * - "direct" — CLI commands POST their events directly (see `hq mesh
11
+ * session`/`emit`) and the daemon keeps the presence subscriber
12
+ * on hq/{personUid}/mesh, which keeps the cache the desktop app
13
+ * reads warm. The hooks still append session and turn events
14
+ * to the spool, so the daemon also delivers the spool on a
15
+ * timer (../direct-drain.ts; US-038, owner decision 70). No
16
+ * outbox replay, held backfill, directory watcher, shutdown
17
+ * flush or transcript-watch on this box.
14
18
  *
15
19
  * The flag is resolved from (highest first): env HQ_MESH_MODE, the work-mesh
16
20
  * config file (~/.hq/work-mesh/config.json `emitMode`), else "legacy".
@@ -11,6 +11,8 @@ import { type MeshEmitMode } from "./mode.js";
11
11
  import { type CommandRunner, type LegacyListenPlatform } from "./legacy-listen.js";
12
12
  import { type StartCapacitySchedulerOptions } from "../../../capacity/scheduler.js";
13
13
  export declare const SPOOL_DEBOUNCE_MS = 2000;
14
+ /** Direct mode: wait after daemon start before the first spool drain cycle. */
15
+ export declare const DIRECT_DRAIN_START_DELAY_MS = 1000;
14
16
  export declare const FLUSH_INTERVAL_MS = 10000;
15
17
  /** Keep startup recovery bounded: the next daemon start continues the backlog. */
16
18
  export declare const HELD_BACKFILL_STARTUP_BATCH_SIZE = 100;
@@ -24,6 +26,14 @@ export declare const DEVICE_DEFAULT_MEMBERSHIP_TIMEOUT_MS = 2000;
24
26
  /** Skip further membership probes after a transport failure so a network drop
25
27
  * cannot fan out one hanging lookup per held session. */
26
28
  export declare const DEVICE_DEFAULT_MEMBERSHIP_UNAVAILABLE_COOLDOWN_MS = 30000;
29
+ /** Direct mode: longest wait between drain cycles after repeated failures. */
30
+ export declare const DIRECT_DRAIN_MAX_DELAY_MS: number;
31
+ /**
32
+ * Wait before the next direct-mode drain cycle. FLUSH_INTERVAL_MS while cycles
33
+ * succeed; doubled for each cycle in a row that failed or delivered nothing
34
+ * it tried to send, up to DIRECT_DRAIN_MAX_DELAY_MS.
35
+ */
36
+ export declare function directDrainDelayMs(consecutiveFailures: number): number;
27
37
  /** Three sequential async shutdown steps must finish within six seconds. */
28
38
  export declare const SHUTDOWN_STEP_TIMEOUT_MS = 2000;
29
39
  /** Non-zero exit reserved for CLI version drift so legacy Restart=on-failure units restart. */
@@ -74,9 +84,10 @@ export interface DaemonRunDeps {
74
84
  enableTranscriptWatch?: boolean;
75
85
  /**
76
86
  * Emit mode. "legacy" runs the spool/flush/held/outbox/transcript-watch emit
77
- * path; "direct" runs receive-only (subscriber + cache) because sessions POST
78
- * events directly. Default resolves from HQ_MESH_MODE / work-mesh config, else
79
- * "legacy" (contract direct-emit-v1 §6.3).
87
+ * path. "direct" keeps the subscriber and cache, and delivers the spool the
88
+ * hooks still write on a timer (runDirectDrainCycle), with no outbox replay,
89
+ * held backfill or transcript-watch. Default resolves from HQ_MESH_MODE /
90
+ * work-mesh config, else "legacy" (contract direct-emit-v1 §6.3).
80
91
  */
81
92
  mode?: MeshEmitMode;
82
93
  /** Injectable transcript fs (tests). */