@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
@@ -4,6 +4,7 @@ import { buildOutpostBalanceMoveCommand, dispatchErrorMessage } from "../lib/lan
4
4
  import { BALANCE_MOVABLE_STATES, accountLoadsForReport, planClaudeBalanceMoves, selectClaudeAccount } from "../lib/lanes/claude-balance.js";
5
5
  import { CompanySelectionError } from "../utils/company-selection-error.js";
6
6
  import { effectiveAccountHome } from "../lib/lanes/account-home.js";
7
+ import { accountHeldByOther, accountOwnership, heldByOwner, holderProblem, normalizeHolder, normalizeOwningCompany, owningCompanyProblem, ownershipWarning, setOwnerCommand } from "../lib/lanes/account-ownership.js";
7
8
  import { AccountResolutionError, DEFAULT_ACCOUNT_HOMES, LANE_PROVIDERS, accountStatus, canonicalizeHome, claudeIdentityDiffers, installDrainHook, isLanesError, listAccountStatuses, loadLanesConfig, parseLaneProvider, probeInteractiveClaudeIdentity, readLane, withProviderHomeEnv, writeLanesConfig } from "../lib/lanes/index.js";
8
9
  import { assertUniqueAccountHomes, providerCompactAfterMs } from "../lib/lanes/config.js";
9
10
  import { resolveLaneEffort } from "../lib/lanes/effort.js";
@@ -14,6 +15,33 @@ import { accountQuotaView, clearAccountQuota, loadQuotaState } from "../lib/lane
14
15
  import { resolveLaneModel } from "../lib/lanes/spawn.js";
15
16
  import { leadLaneIds } from "../lib/lanes/admission.js";
16
17
  import { resolveLaneCompany } from "../lib/lanes/lane-company.js";
18
+ /**
19
+ * PS-006 set-owner warnings. The change is still saved; these only flag the
20
+ * likely mistake of recording the owner's own login under his name instead
21
+ * of `owner`, which takes that login away from every lane.
22
+ */
23
+ export function setOwnerWarnings(env, provider, id, holder, accounts) {
24
+ const warnings = [];
25
+ if (holder === undefined || !accountHeldByOther(accounts[id]))
26
+ return warnings;
27
+ const usable = Object.values(accounts).filter((account) => account.enabled && !accountHeldByOther(account));
28
+ if (usable.length === 0) {
29
+ warnings.push({
30
+ code: "no_usable_login",
31
+ message: "No enabled " + provider + " login is usable by lanes now. If " + id + " is really your own login, record it with: hq lanes accounts set-owner " + provider + " " + id + " --holder owner",
32
+ });
33
+ }
34
+ const localNames = [env.USER, env.LOGNAME, env.USERNAME]
35
+ .filter((name) => typeof name === "string" && name.trim() !== "")
36
+ .map((name) => name.trim().toLowerCase());
37
+ if (localNames.some((name) => name === holder.toLowerCase())) {
38
+ warnings.push({
39
+ code: "holder_matches_local_user",
40
+ message: "Holder " + JSON.stringify(holder) + " matches this machine's user name. If " + id + " is your own login, use --holder owner; a named holder keeps lanes off it.",
41
+ });
42
+ }
43
+ return warnings;
44
+ }
17
45
  export function createLaneAccountsHandlers(deps) {
18
46
  const { admitQueuedFromCtx, automaticBalanceMoveHistoryReason, ensureDir, laneWithRecoveredProviderSession, loadClaudeBalanceHostSnapshots, parseRemoteJson, prepareAccountMove, printJson, reconcileHostFromCtx, resolveCallerPath } = deps;
19
47
  const VENDOR_LOGIN = {
@@ -166,8 +194,20 @@ export function createLaneAccountsHandlers(deps) {
166
194
  effective_effort: effort.effort ?? null,
167
195
  effective_effort_source: effort.source,
168
196
  ...accountQuotaView(quota, provider, status.id),
197
+ // PS-006: who owns and who holds this login. Added fields only.
198
+ ...ownershipView(provider, status.id, accountCfg),
169
199
  };
170
200
  }));
201
+ const ownershipWarnings = providers.flatMap((provider) => Object.entries(config.providers[provider].accounts).flatMap(([id, account]) => {
202
+ const warning = ownershipWarning(provider, id, account);
203
+ return warning === undefined ? [] : [{ provider, account: id, ...warning }];
204
+ }));
205
+ // One summary line, not one per account; the JSON keeps the full list.
206
+ if (ownershipWarnings.length > 0) {
207
+ const names = ownershipWarnings.map((warning) => warning.provider + "/" + warning.account).join(", ");
208
+ process.stderr.write("warning: " + ownershipWarnings.length + " enabled account(s) have no owning_company or holder recorded: " + names +
209
+ ". Record them with: hq lanes accounts set-owner <provider> <account-id> --owning-company <slug|personal|unknown> --holder <owner|name>\n");
210
+ }
171
211
  const providerDefaults = providers.map((provider) => ({
172
212
  provider,
173
213
  model: config.providers[provider].model ?? null,
@@ -180,6 +220,84 @@ export function createLaneAccountsHandlers(deps) {
180
220
  providers: providerDefaults,
181
221
  ...(providers.includes("claude") ? { interactive_identity: interactiveIdentity } : {}),
182
222
  accounts,
223
+ ownership_warnings: ownershipWarnings,
224
+ });
225
+ }
226
+ function ownershipView(provider, id, account) {
227
+ const ownership = accountOwnership(account);
228
+ const warning = ownershipWarning(provider, id, account);
229
+ return {
230
+ owning_company: ownership.owning_company,
231
+ owning_company_source: ownership.owning_company_source,
232
+ holder: ownership.holder,
233
+ holder_source: ownership.holder_source,
234
+ // null when no holder is recorded; never true by default.
235
+ held_by_owner: heldByOwner(account),
236
+ ownership_missing: ownership.ownership_missing,
237
+ ...(warning !== undefined
238
+ ? { ownership_warning: warning.message, ownership_fix_command: warning.fix_command }
239
+ : {}),
240
+ };
241
+ }
242
+ /**
243
+ * Record who owns and who holds a login (PS-006). Only these two labels are
244
+ * written: no credential, home or vault file is read or moved.
245
+ */
246
+ async function runAccountsSetOwner(ctx, providerRaw, accountIdRaw, opts) {
247
+ const provider = parseLaneProvider(providerRaw);
248
+ const id = accountIdRaw.trim();
249
+ const owningCompany = opts.owningCompany === undefined ? undefined : normalizeOwningCompany(opts.owningCompany);
250
+ const holder = opts.holder === undefined ? undefined : normalizeHolder(opts.holder);
251
+ if (owningCompany === undefined && holder === undefined) {
252
+ throw new LanesError("ownership_value_required", "Pass --owning-company, --holder, or both", {
253
+ provider,
254
+ account: id,
255
+ usage: setOwnerCommand(provider, id || "<account-id>"),
256
+ });
257
+ }
258
+ if (owningCompany !== undefined) {
259
+ const problem = owningCompanyProblem(owningCompany);
260
+ if (problem !== null) {
261
+ throw new LanesError("invalid_owning_company", `--owning-company ${problem}`, { provider, account: id, value: opts.owningCompany });
262
+ }
263
+ }
264
+ if (holder !== undefined) {
265
+ const problem = holderProblem(holder);
266
+ if (problem !== null) {
267
+ throw new LanesError("invalid_holder", `--holder ${problem}`, { provider, account: id, value: opts.holder });
268
+ }
269
+ }
270
+ const hqRoot = ctx.hqRoot();
271
+ const config = loadLanesConfig(hqRoot);
272
+ const account = config.providers[provider].accounts[id];
273
+ if (account === undefined) {
274
+ throw new AccountResolutionError("unknown_account", `Unknown account ${JSON.stringify(id)} for ${provider}`, {
275
+ provider,
276
+ account: id,
277
+ enabled: Object.entries(config.providers[provider].accounts)
278
+ .filter(([, a]) => a.enabled)
279
+ .map(([key]) => key),
280
+ });
281
+ }
282
+ const before = { owning_company: account.owning_company ?? null, holder: account.holder ?? null };
283
+ if (owningCompany !== undefined)
284
+ account.owning_company = owningCompany;
285
+ if (holder !== undefined)
286
+ account.holder = holder;
287
+ writeLanesConfig(hqRoot, config);
288
+ const savedConfig = loadLanesConfig(hqRoot);
289
+ const saved = savedConfig.providers[provider].accounts[id];
290
+ const warnings = setOwnerWarnings(ctx.env, provider, id, holder, savedConfig.providers[provider].accounts);
291
+ for (const warning of warnings)
292
+ process.stderr.write("warning: " + warning.message + "\n");
293
+ printJson({
294
+ ok: true,
295
+ action: "accounts.set-owner",
296
+ provider,
297
+ account: id,
298
+ before,
299
+ ...ownershipView(provider, id, saved),
300
+ ...(warnings.length > 0 ? { warnings } : {}),
183
301
  });
184
302
  }
185
303
  async function runAccountsBalance(ctx, opts) {
@@ -637,6 +755,7 @@ export function createLaneAccountsHandlers(deps) {
637
755
  runAccountsBalance,
638
756
  runAccountsLogin,
639
757
  runAccountsSetHome,
758
+ runAccountsSetOwner,
640
759
  runAccountsClearQuota,
641
760
  runAccountsEnable,
642
761
  runAccountsDisable
@@ -931,7 +931,7 @@ async function orphanReport(root, company, now, minAgeMinutes, userIdleHours, de
931
931
  }
932
932
  export function registerLaneChecksCommand(parent, deps, wrap) {
933
933
  parent.command("reap")
934
- // CL-5's SessionStart hook launches this alias detached and does not wait for it.
934
+ // Preserve the historical internal alias for older callers.
935
935
  .alias("_reap")
936
936
  .description("Classify local lanes whose session senior has ended; report only by default")
937
937
  .option("--min-age <minutes>", "Minimum lane age in minutes (default: 120)")
@@ -1,3 +1,4 @@
1
+ import { accountHeldByOther } from "../lib/lanes/account-ownership.js";
1
2
  import * as path from "node:path";
2
3
  import { chooseHostForLane } from "../lib/lanes/host-capacity.js";
3
4
  import { laneRunsHere, loadLanesConfig, loadWorkerProfile, readLane, updateLane, withLaneAdmissionLock, } from "../lib/lanes/index.js";
@@ -167,6 +168,15 @@ export function createLaneMoveHandlers(deps) {
167
168
  assertKnownOutpost(target.id, known);
168
169
  }
169
170
  const accountConfig = loadLanesConfig(hqRoot).providers[before.provider].accounts[account];
171
+ if (accountHeldByOther(accountConfig)) {
172
+ const holder = accountConfig?.holder ?? null;
173
+ throw new LanesError("account_held_by_other", `Account ${account} is held by ${holder}, not the owner, and is not used for lanes`, {
174
+ lane_id: laneId,
175
+ provider: before.provider,
176
+ account,
177
+ holder,
178
+ });
179
+ }
170
180
  if (accountConfig === undefined || !accountConfig.enabled) {
171
181
  throw new LanesError("lane_move_account_invalid", `Account ${account} is unavailable for ${before.provider}`, {
172
182
  lane_id: laneId,
@@ -7,6 +7,7 @@ export interface SessionStartOptions {
7
7
  stdout?: Pick<NodeJS.WriteStream, "write">;
8
8
  stderr?: Pick<NodeJS.WriteStream, "write">;
9
9
  resolveRoot?: (env: NodeJS.ProcessEnv, cwd?: string) => string;
10
+ /** Compatibility option; orphan sweeping is now owned by daemon reconcile. */
10
11
  startSweep?: (root: string, env: NodeJS.ProcessEnv) => void;
11
12
  /** Starts the off-hot-path registry read when an offline flag value is missing or old. */
12
13
  refreshFlags?: (env: NodeJS.ProcessEnv) => void;
@@ -30,8 +31,6 @@ export declare const CONDUCT_RUNNERS_CORE_MISSING_LINE = "hq runners session-sta
30
31
  * that: a stalled resolver costs the pin, and the inject block still prints.
31
32
  */
32
33
  export declare const CONDUCT_RUNNER_RESOLVE_TIMEOUT_MS = 500;
33
- /** Starts the CL-4 read-only orphan report once per host, without holding SessionStart open. */
34
- export declare function startSessionStartOrphanSweep(root: string, env?: NodeJS.ProcessEnv, spawnDetached?: typeof spawn, rootScoped?: boolean): void;
35
34
  /**
36
35
  * Start a detached `hq lanes session-start --refresh-flags` so the registry
37
36
  * read never runs inside the SessionStart hook. A short lease keeps a burst of
@@ -1,14 +1,14 @@
1
1
  import fs from "node:fs";
2
+ import { readOrphanReportCount } from "../lib/lanes/orphan-report.js";
2
3
  import { spawn, spawnSync } from "node:child_process";
3
- import os from "node:os";
4
4
  import path from "node:path";
5
- import { createHash, randomUUID } from "node:crypto";
5
+ import { randomUUID } from "node:crypto";
6
+ import { validSessionId } from "../lib/core-utils/session-id.js";
6
7
  import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
7
8
  import { readLanesRegistryFlagOffline, readLanesRegistryFlagResult } from "../lib/lanes/registry-flag.js";
8
- import { LANE_CONDUCT_SESSION_START_FLAG, LANE_ORPHAN_SWEEP_CONTEXT_FLAG, LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG } from "../lib/lanes/flag-keys.js";
9
+ import { LANE_CONDUCT_SESSION_START_FLAG, LANE_ORPHAN_SWEEP_CONTEXT_FLAG } from "../lib/lanes/flag-keys.js";
9
10
  const SESSION_START_FLAGS = [
10
11
  LANE_CONDUCT_SESSION_START_FLAG,
11
- LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG,
12
12
  LANE_ORPHAN_SWEEP_CONTEXT_FLAG,
13
13
  ];
14
14
  /** Offline flag values older than this trigger one background registry read. */
@@ -228,7 +228,7 @@ function conductorCorePath(root, runner) {
228
228
  }
229
229
  function validPayloadSessionId(payload) {
230
230
  const sessionId = payload.session_id ?? payload.sessionId;
231
- if (!sessionId || !/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === "." || sessionId === "..")
231
+ if (!sessionId || !validSessionId(sessionId))
232
232
  return null;
233
233
  return sessionId;
234
234
  }
@@ -386,139 +386,6 @@ function extractConductorBlock(core) {
386
386
  return null;
387
387
  return core.slice(start + "<!-- inject:start -->".length, end).replace(/^\r?\n/, "").replace(/\r?\n$/, "");
388
388
  }
389
- const ORPHAN_SWEEP_LOCK_TTL_MS = 15 * 60_000;
390
- function rootKeyFor(root) {
391
- let resolved = path.resolve(root);
392
- try {
393
- resolved = fs.realpathSync(root);
394
- }
395
- catch { /* the canonicalized path remains the fallback */ }
396
- return createHash("sha256").update(resolved).digest("hex").slice(0, 12);
397
- }
398
- function readOrphanCount(root, env, rootScoped, onError) {
399
- try {
400
- const stateRoot = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
401
- const host = os.hostname().replace(/[^A-Za-z0-9._-]/g, "_") || "unknown-host";
402
- const rootKey = rootKeyFor(root);
403
- const prefix = rootScoped ? `orphans-${rootKey}-` : "orphans-";
404
- const dir = path.join(stateRoot, "hq-cli", "lanes-orphan-reports", host);
405
- const candidates = fs.readdirSync(dir)
406
- .filter((name) => name.startsWith(prefix) && name.endsWith(".json"))
407
- .map((name) => ({ name, mtime: fs.statSync(path.join(dir, name)).mtimeMs }))
408
- .sort((a, b) => b.mtime - a.mtime);
409
- // Reports accumulate, so read newest first and stop at the first one that
410
- // actually swept; skipped and unreadable reports are passed over.
411
- for (const candidate of candidates) {
412
- let report;
413
- try {
414
- report = JSON.parse(fs.readFileSync(path.join(dir, candidate.name), "utf8"));
415
- }
416
- catch (error) {
417
- onError?.(error);
418
- continue;
419
- }
420
- if (report.skipped)
421
- continue;
422
- return Array.isArray(report.lanes) ? report.lanes.filter((lane) => lane && typeof lane === "object" && lane.orphaned === true).length : 0;
423
- }
424
- return 0;
425
- }
426
- catch (error) {
427
- onError?.(error);
428
- return 0;
429
- }
430
- }
431
- /** Starts the CL-4 read-only orphan report once per host, without holding SessionStart open. */
432
- export function startSessionStartOrphanSweep(root, env = process.env, spawnDetached = spawn, rootScoped = true) {
433
- const stateRoot = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
434
- const host = os.hostname().replace(/[^A-Za-z0-9._-]/g, "_") || "unknown-host";
435
- const rootKey = rootKeyFor(root);
436
- const rootSuffix = rootScoped ? `-${rootKey}` : "";
437
- const stateDir = path.join(stateRoot, "hq-cli", "lanes-session-start", host);
438
- const lockPath = path.join(stateDir, `orphan-sweep${rootSuffix}.lock`);
439
- const reportDir = path.join(stateRoot, "hq-cli", "lanes-orphan-reports", host);
440
- const ownerToken = randomUUID();
441
- try {
442
- fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
443
- fs.mkdirSync(reportDir, { recursive: true, mode: 0o700 });
444
- let fd;
445
- try {
446
- fd = fs.openSync(lockPath, "wx", 0o600);
447
- }
448
- catch (error) {
449
- if (error.code !== "EEXIST")
450
- return;
451
- let previous = {};
452
- try {
453
- previous = JSON.parse(fs.readFileSync(lockPath, "utf8"));
454
- }
455
- catch { /* malformed lease can be reclaimed */ }
456
- const age = Date.now() - Number(previous.started_at || 0);
457
- let running = false;
458
- if (Number.isInteger(previous.pid) && Number(previous.pid) > 0) {
459
- try {
460
- process.kill(Number(previous.pid), 0);
461
- running = true;
462
- }
463
- catch {
464
- running = false;
465
- }
466
- }
467
- if (age < ORPHAN_SWEEP_LOCK_TTL_MS && running)
468
- return;
469
- fs.rmSync(lockPath, { force: true });
470
- try {
471
- fd = fs.openSync(lockPath, "wx", 0o600);
472
- }
473
- catch {
474
- return;
475
- }
476
- }
477
- const startedAt = Date.now();
478
- fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, started_at: startedAt, owner_token: ownerToken }));
479
- fs.closeSync(fd);
480
- const cli = process.argv[1];
481
- if (!cli) {
482
- fs.rmSync(lockPath, { force: true });
483
- return;
484
- }
485
- const wrapper = [
486
- "const cp=require('node:child_process'),fs=require('node:fs'),path=require('node:path');",
487
- "const [cli,lock,root,token,report]=process.argv.slice(1);",
488
- "const cleanup=()=>{try{const lease=JSON.parse(fs.readFileSync(lock,'utf8'));if(lease.owner_token===token)fs.rmSync(lock,{force:true})}catch{}};",
489
- "const start=()=>{let lease;try{lease=JSON.parse(fs.readFileSync(lock,'utf8'))}catch{}if(lease?.owner_token!==token){if(Date.now()<Number(lease?.started_at||0)+1000)return setTimeout(start,10);process.exit(0)}",
490
- "try{fs.writeFileSync(lock,JSON.stringify({...lease,pid:process.pid}))}catch{}",
491
- "const tmp=report+'.tmp';let output;try{output=fs.createWriteStream(tmp,{flags:'wx',mode:0o600})}catch{cleanup();process.exit(0)}",
492
- "const child=cp.spawn(process.execPath,[cli,'runners','_reap','--json','--legacy'],{stdio:['ignore','pipe','ignore'],env:{...process.env,HQ_ROOT:root,HQ_NO_UPDATE_CHECK:'1'}});",
493
- "child.stdout.pipe(output);child.on('error',()=>{output.destroy();try{fs.rmSync(tmp,{force:true})}catch{}cleanup()});",
494
- "child.on('exit',(code)=>output.end(()=>{try{if(code===0)fs.renameSync(tmp,report);else fs.rmSync(tmp,{force:true})}catch{}cleanup()}));};start();",
495
- ].join("");
496
- const reportPath = path.join(reportDir, `orphans-${rootScoped ? `${rootKey}-` : ""}${startedAt}-${ownerToken}.json`);
497
- const launcher = spawnDetached(process.execPath, ["-e", wrapper, cli, lockPath, root, ownerToken, reportPath], {
498
- detached: true,
499
- stdio: "ignore",
500
- env: { ...env, HQ_ROOT: root, HQ_NO_UPDATE_CHECK: "1" },
501
- });
502
- if (launcher.pid) {
503
- try {
504
- fs.writeFileSync(lockPath, JSON.stringify({ pid: launcher.pid, started_at: startedAt, owner_token: ownerToken }));
505
- }
506
- catch { /* TTL lease still bounds an orphaned lock */ }
507
- }
508
- launcher.on("error", () => {
509
- try {
510
- const lease = JSON.parse(fs.readFileSync(lockPath, "utf8"));
511
- if (lease.owner_token === ownerToken)
512
- fs.rmSync(lockPath, { force: true });
513
- }
514
- catch { /* The lease may already have been reclaimed. */ }
515
- });
516
- launcher.unref();
517
- }
518
- catch {
519
- // SessionStart's orphan report is advisory and must never block startup.
520
- }
521
- }
522
389
  function flagRefreshLeaseDir(env) {
523
390
  const stateDir = env.HQ_STATE_DIR?.trim();
524
391
  if (stateDir)
@@ -618,8 +485,6 @@ export async function runLaneSessionStart(options = {}) {
618
485
  return read?.value ?? true;
619
486
  };
620
487
  const flagEnabled = readFlag(LANE_CONDUCT_SESSION_START_FLAG);
621
- const rootScoped = readFlag(LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG);
622
- const contextEnabled = readFlag(LANE_ORPHAN_SWEEP_CONTEXT_FLAG);
623
488
  if (refreshNeeded) {
624
489
  try {
625
490
  (options.refreshFlags ?? ((e) => { startSessionStartFlagRefresh(e); }))(env);
@@ -628,11 +493,10 @@ export async function runLaneSessionStart(options = {}) {
628
493
  }
629
494
  if (!flagEnabled)
630
495
  return;
631
- (options.startSweep ?? ((r, e) => startSessionStartOrphanSweep(r, e, spawn, rootScoped)))(root, env);
632
- if (contextEnabled) {
633
- const count = readOrphanCount(root, env, rootScoped, (error) => debug(`hq lanes session-start: orphan report read failed (${error instanceof Error ? error.name : "Error"})`));
634
- if (count > 0)
635
- stdout.write(`HQ orphaned lanes: ${count}; inspect with hq lanes orphans\n`);
496
+ if (readFlag(LANE_ORPHAN_SWEEP_CONTEXT_FLAG)) {
497
+ const count = readOrphanReportCount(root);
498
+ if (count !== null && count > 0)
499
+ stdout.write(`HQ orphaned lanes: ${count}; inspect with hq runners orphans\n`);
636
500
  }
637
501
  if (sessionWasDisabled(root, env, payload.session_id ?? payload.sessionId))
638
502
  return;
@@ -2,6 +2,7 @@ import type { StatFs } from "../lib/lanes/disk-guard.js";
2
2
  import type { LaneCompanyRef, LanePlacementPolicy, LaneRecord, LanesConfig, QuestionAnswer, QuestionBody, QuestionRecord, SeniorRef, AccountHistoryEntry, LaneAccountSelection, PendingResume, QueuedReason, ResolvedLaneWorker, LivenessDeps, MachineIdentity, MonitorEvidenceReader, ReconcileHost, RunCommand, ThrottleDeps, withLaneAdmissionLock, withLaneHireLocks } from "../lib/lanes/index.js";
3
3
  import type { OutpostIdentity } from "../lib/lanes/admission-host.js";
4
4
  import type { OutpostDispatchResult } from "../lib/lanes/outpost-dispatch.js";
5
+ import type { CompanyOutpostCandidate, CompanyOutpostTargets } from "../lib/lanes/company-outposts.js";
5
6
  import type { CpuBusySource, MemoryHold } from "../lib/lanes/throttle.js";
6
7
  import type { ProbeCommand } from "../lib/lanes/models.js";
7
8
  import type { ClaudeCredentialReader } from "../lib/lanes/claude-credential.js";
@@ -274,6 +275,8 @@ export interface Ctx {
274
275
  resolveActiveCompany: (company: string) => Promise<LaneCompanyRef | null>;
275
276
  listOutpostIds: () => Promise<string[]>;
276
277
  listOutpostRoutes: () => Promise<OutpostRouteIdentity[]>;
278
+ listCompanyOutposts: (company: LaneCompanyRef) => Promise<CompanyOutpostCandidate[]>;
279
+ companyOutposts: CompanyOutpostTargets;
277
280
  readOutpostIdentity: () => OutpostIdentity;
278
281
  spawnLogin: (opts: {
279
282
  command: string;
@@ -3,6 +3,7 @@ import { readLanesRegistryFlag } from "../lib/lanes/registry-flag.js";
3
3
  import { LANE_OUTPOST_LOAD_BALANCING_FLAG } from "../lib/lanes/flag-keys.js";
4
4
  import { resolveLaneEffort } from "../lib/lanes/effort.js";
5
5
  import { LanesError } from "../lib/lanes/errors.js";
6
+ import { accountHeldByOther } from "../lib/lanes/account-ownership.js";
6
7
  import { AccountResolutionError, accountStatus, loadLanesConfig } from "../lib/lanes/index.js";
7
8
  import { resolveLaneModel } from "../lib/lanes/spawn.js";
8
9
  import { sessionIdFromEnv } from "../lib/mesh/live/session-identity.js";
@@ -25,6 +26,14 @@ export function assertCurrentResumeAccountAvailable(ctx, lane) {
25
26
  ? `Lane ${lane.lane_id} records account ${JSON.stringify(lane.account)} which is not configured for ${lane.provider}`
26
27
  : `Account ${JSON.stringify(lane.account)} is disabled${account.disabled_reason ? `: ${account.disabled_reason}` : ""}`, { provider: lane.provider, account: lane.account ?? "", ...(account?.disabled_reason !== undefined ? { reason: account.disabled_reason } : {}) });
27
28
  }
29
+ // PS-006: keeping a lane on a login held by another person is refused
30
+ // before anything probes that login's home.
31
+ if (accountHeldByOther(account)) {
32
+ const holder = account.holder ?? null;
33
+ throw new LanesError("account_held_by_other", `Account ${lane.account} is held by ${holder}, not the owner, and is not used for lanes`, {
34
+ provider: lane.provider, account: lane.account ?? "", holder,
35
+ });
36
+ }
28
37
  const status = accountStatus(lane.provider, lane.account, config, {
29
38
  existsSync: ctx.existsSync,
30
39
  hostname: ctx.hostname(),
@@ -10,6 +10,7 @@ import type { OutpostIdentity } from "../lib/lanes/admission-host.js";
10
10
  export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/admission-host.js";
11
11
  export type { OutpostIdentity } from "../lib/lanes/admission-host.js";
12
12
  import { type OutpostDispatchResult } from "../lib/lanes/outpost-dispatch.js";
13
+ import { type CompanyOutpostCandidate, type CompanyOutpostExecClient } from "../lib/lanes/company-outposts.js";
13
14
  import { emitLaneDecisionEvents } from "../lib/lanes/mesh-events.js";
14
15
  import { MAX_LANE_DEPTH, withLaneAdmissionLock, withLaneHireLocks, type LaneCompanyRef, type QuestionBody, type LaneRecord, type QuestionRecord, type ResolvedLaneWorker, type SeniorRef, type LivenessDeps, type MachineIdentity, type MonitorEvidenceReader, type RunCommand, type ThrottleDeps } from "../lib/lanes/index.js";
15
16
  import { deriveWorkRequirements } from "../lib/environment/work-requirements.js";
@@ -49,6 +50,8 @@ export interface LanesCommandDeps {
49
50
  resolveActiveCompany?: (company: string) => Promise<LaneCompanyRef | null>;
50
51
  listOutpostIds?: () => Promise<string[]>;
51
52
  listOutpostRoutes?: () => Promise<OutpostRouteIdentity[]>;
53
+ listCompanyOutposts?: (company: LaneCompanyRef) => Promise<CompanyOutpostCandidate[]>;
54
+ outpostExecClient?: () => CompanyOutpostExecClient;
52
55
  readOutpostIdentity?: () => OutpostIdentity;
53
56
  spawnLogin?: (opts: {
54
57
  command: string;