@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
@@ -65,6 +65,7 @@ import { createOutpostRegistryWorkerApprovalContext, parseOutpostRegistryWorkerA
65
65
  import { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity, resolveAdmissionHost, } from "../lib/lanes/admission-host.js";
66
66
  export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/admission-host.js";
67
67
  import { buildOutpostCapacityCommand, buildOutpostIdentityBackfillCommand, buildOutpostLaneCommand, buildOutpostQuestionListCommand, buildOutpostPickupCommand, createOutpostsClient, dispatchErrorMessage, dispatchOutpostPickup, buildOutpostLaneListCommand, buildOutpostLegacyLaneUlidListCommand, REMOTE_LANE_READ_ENV, outpostRejectedEffortOption, parseOutpostPickupPayload, PICKUP_WAIT_MS, stageOutpostPayload, } from "../lib/lanes/outpost-dispatch.js";
68
+ import { assertCompanyOutpostBelongsTo, companyAwareExecPort, companyOutpostAccessRequired, companyOutpostNeedsCompany, companyOutpostNotLaneReady, companyOutpostRefusal, CompanyOutpostTargets, isCompanyOutpostId, isCompanyOutpostRefusal, isNoCompanyOutposts, listCompanyOutpostCandidates, readyCompanyOutpostIds, } from "../lib/lanes/company-outposts.js";
68
69
  import { outpostHireSummaryCacheKey, OUTPOST_HIRE_SUMMARY_CACHE_TTL_MS, readOutpostHireSummaryCache, readOutpostHireSummaryCacheIncludingStale, writeOutpostHireSummaryCache, } from "../lib/lanes/outpost-hire-cache.js";
69
70
  import { buildHostCapacitySnapshot, chooseHostForLane, hostCapacitySnapshotToWire, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
70
71
  import { readHostCompute } from "../lib/lanes/host-compute.js";
@@ -85,6 +86,7 @@ import { sessionIdFromEnv } from "../lib/mesh/live/session-identity.js";
85
86
  import { applyLoopDisposition, loopDispositionSnapshot } from "../lib/lanes/loop-disposition.js";
86
87
  import { listLaneReviews } from "../lib/lanes/reviews.js";
87
88
  import { effectiveAccountHome } from "../lib/lanes/account-home.js";
89
+ import { accountHeldByOther } from "../lib/lanes/account-ownership.js";
88
90
  import { remoteControlSelectionConfig, remoteControlSessionHome } from "../lib/lanes/remote-control-lane.js";
89
91
  import { AccountResolutionError, compareLaneQueueOrder, LANE_PROVIDERS, LANE_STATES, QUESTION_STATUSES, SENIOR_KINDS, accountStatus, appendCappedHistory, canonicalizeHome, createLane, mintLaneId, decideAdmission, defaultLivenessDeps, defaultSystemdUserDir, defaultThrottleDeps, installReconcileTimer, providerPathEnv, probeDrainHookRegistration, isLanesError, isLaneVersionConflict, isTerminalLaneState, isFinishedResumableHireChild, childrenHoldingHireGrantCarve, laneHoldsHireGrantCarve, assignedChildHireGrants, hireGrantCapacityError, planHireGrantBackfill, terminalChildResumeHireGrantError, withHireGrantAdmission, laneStoryLedgerEnabled, syncLaneToProjectStoryLedger, removeLaneFromProjectStoryLedger, validateProjectStories, buildLaneStatusSnapshot, formatLaneStatusHuman, expandLocalLaneIdPrefix, listLaneIds, listQuestionIds, loadLanesConfig, laneRunsHere, MAX_LANE_DEPTH, MONITOR_ERROR_EXIT_CODE, readLiveMonitorEvidence, resolveMachineIdentity as lookupMachineIdentity, loadLivenessIndex, parseLaneProvider, isLaneProvider, parseLaneRecord, parseLaneState, parseQuestionRecord, parseSeniorKind, readAllLanes, readLane, sanitizeHostComponent, retryUpdateLane, syncLaneRecordFromOwner, readQuestion, resolveAccount, resolveLaneWorker, ignoredWorkerProfileFields, loadWorkerProfile, loadWorkerProfileWithRegistry, registryWorkerRecord, runReconcilePass, DEAD_HOST_MS, sessionLiveness, tryReadLane, uninstallReconcileTimer, updateLane, updateQuestion, dropboxDir, laneDeliveryMechanism, hasActiveAdmissionReservation, hasActivePendingResume, hasRecordedSessionId, hasEarlierEligibleQueuedLane, laneAdmissionCapReason, providerSupportsSessionResume, providerSessionPortable, isFailedQuotaKeepAliveLane, sessionNotPortableMessage, withLaneAdmissionLock, withAllLaneAdmissionLocks, readWorkerRunResult, resumeCommandRefusal, withLaneHireLocks, raiseLaneQuestion, sha256Text, } from "../lib/lanes/index.js";
90
92
  import { admitQueuedNow } from "../lib/lanes/reconcile.js";
@@ -354,12 +356,21 @@ async function defaultListOutpostRoutes() {
354
356
  const rows = await defaultOutpostsClient().list();
355
357
  return rows.map(({ outpostId, instanceName }) => ({ outpostId, instanceName }));
356
358
  }
357
- async function defaultStageOutpostPayload(outpostId, bytes) {
358
- return stageOutpostPayload(defaultOutpostsClient(), outpostId, bytes);
359
+ async function defaultListCompanyOutposts(company) {
360
+ return listCompanyOutpostCandidates(defaultOutpostsClient(), company);
359
361
  }
360
- async function defaultDispatchOutpostExec(input) {
362
+ function recordedOutpostCompany(hqRoot, outpostId) {
363
+ const companies = new Map();
364
+ for (const lane of loadAllLanes(hqRoot)) {
365
+ if (lane.host.kind === "outpost" && lane.host.id === outpostId && lane.company) {
366
+ companies.set(lane.company.uid, lane.company);
367
+ }
368
+ }
369
+ return companies.size === 1 ? [...companies.values()][0] : undefined;
370
+ }
371
+ async function defaultDispatchOutpostExec(port, input) {
361
372
  try {
362
- return await dispatchOutpostPickup(defaultOutpostsClient(), input);
373
+ return await dispatchOutpostPickup(port, input);
363
374
  }
364
375
  catch (err) {
365
376
  if (err instanceof LanesError)
@@ -490,6 +501,8 @@ function resolveDeps(deps = {}) {
490
501
  }
491
502
  return root;
492
503
  };
504
+ const companyOutposts = new CompanyOutpostTargets((outpostId) => recordedOutpostCompany(hqRoot(), outpostId));
505
+ const outpostExecPort = () => companyAwareExecPort((deps.outpostExecClient ?? defaultOutpostsClient)(), companyOutposts);
493
506
  return {
494
507
  cwd,
495
508
  callerCwd,
@@ -502,6 +515,8 @@ function resolveDeps(deps = {}) {
502
515
  resolveActiveCompany: deps.resolveActiveCompany ?? defaultResolveActiveCompany,
503
516
  listOutpostIds: deps.listOutpostIds ?? defaultListOutpostIds,
504
517
  listOutpostRoutes,
518
+ listCompanyOutposts: deps.listCompanyOutposts ?? defaultListCompanyOutposts,
519
+ companyOutposts,
505
520
  readOutpostIdentity: deps.readOutpostIdentity ?? (() => readOutpostIdentity()),
506
521
  spawnLogin: deps.spawnLogin ?? defaultSpawnLogin,
507
522
  throttleDeps: deps.throttleDeps ?? defaultThrottleDeps(env),
@@ -546,8 +561,10 @@ function resolveDeps(deps = {}) {
546
561
  env,
547
562
  now: deps.now ?? (() => new Date()),
548
563
  })),
549
- stageOutpostPayload: deps.stageOutpostPayload ?? defaultStageOutpostPayload,
550
- dispatchOutpostExec: deps.dispatchOutpostExec ?? defaultDispatchOutpostExec,
564
+ stageOutpostPayload: deps.stageOutpostPayload ??
565
+ ((outpostId, bytes) => stageOutpostPayload(outpostExecPort(), outpostId, bytes)),
566
+ dispatchOutpostExec: deps.dispatchOutpostExec ??
567
+ ((input) => defaultDispatchOutpostExec(outpostExecPort(), input)),
551
568
  backfillOutpostIdentity: deps.backfillOutpostIdentity ?? ((expectedId) => backfillOutpostIdentityMarkerImpl(expectedId, {
552
569
  read: () => deps.readOutpostIdentity?.() ?? readOutpostIdentity(),
553
570
  createIfMissing: createOutpostIdentityMarkerIfMissing,
@@ -1653,7 +1670,21 @@ async function readOutpostCapacityUncached(ctx, outpostId, waitMs = CAPACITY_PRO
1653
1670
  }
1654
1671
  return snapshot;
1655
1672
  }
1656
- async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(hqRoot), localLanes = loadAllLanes(hqRoot)) {
1673
+ async function companyPlacementOutpostIds(ctx, company) {
1674
+ let candidates;
1675
+ try {
1676
+ candidates = await ctx.listCompanyOutposts(company);
1677
+ }
1678
+ catch (err) {
1679
+ if (isNoCompanyOutposts(err))
1680
+ return { ids: [], skipped: [] };
1681
+ return { ids: [], skipped: [{ outpost_id: `company:${company.slug}`, error: "company_outpost_list_unavailable" }] };
1682
+ }
1683
+ const ids = readyCompanyOutpostIds(candidates);
1684
+ ctx.companyOutposts.remember(company, ids);
1685
+ return { ids, skipped: [] };
1686
+ }
1687
+ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(hqRoot), localLanes = loadAllLanes(hqRoot), company = null) {
1657
1688
  const localHost = laneHostFromCtx(ctx);
1658
1689
  let outpostIds;
1659
1690
  try {
@@ -1670,6 +1701,8 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1670
1701
  maximum: MAX_PLACEMENT_OUTPOSTS,
1671
1702
  });
1672
1703
  }
1704
+ const companyCandidates = company ? await companyPlacementOutpostIds(ctx, company) : { ids: [], skipped: [] };
1705
+ const companySkipped = [...companyCandidates.skipped];
1673
1706
  const remoteIds = outpostIds
1674
1707
  .map((id) => id.trim())
1675
1708
  // `primary` aliases the controller when running on the primary box. From
@@ -1677,6 +1710,15 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1677
1710
  .filter((id) => !isControllerAliasOutpostId(id, localHost))
1678
1711
  .filter((id) => localHost.kind !== "outpost" || id !== localHost.id)
1679
1712
  .sort();
1713
+ for (const id of companyCandidates.ids) {
1714
+ if (remoteIds.includes(id) || (localHost.kind === "outpost" && id === localHost.id))
1715
+ continue;
1716
+ if (remoteIds.length >= MAX_PLACEMENT_OUTPOSTS) {
1717
+ companySkipped.push({ outpost_id: id, error: "placement_limit" });
1718
+ continue;
1719
+ }
1720
+ remoteIds.push(id);
1721
+ }
1680
1722
  const local = buildHostCapacitySnapshot({
1681
1723
  host: localHost,
1682
1724
  localMatch: localAdmissionMatch(ctx),
@@ -1718,7 +1760,7 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1718
1760
  ? result.snapshot
1719
1761
  : { host: result.unavailable.host, error: result.unavailable.error }),
1720
1762
  ],
1721
- skippedHosts: unavailable.map(({ outpost_id, error }) => ({ outpost_id, error })),
1763
+ skippedHosts: [...unavailable.map(({ outpost_id, error }) => ({ outpost_id, error })), ...companySkipped],
1722
1764
  };
1723
1765
  }
1724
1766
  const outpostLaneListMemo = new WeakMap();
@@ -3069,6 +3111,36 @@ function assertLaneRunsHereForAdmission(ctx, lane) {
3069
3111
  return;
3070
3112
  throw new LanesError("lane_remote", `Lane ${lane.lane_id} is hosted remotely; run the admission command on its Outpost`, { lane_id: lane.lane_id, host: lane.host });
3071
3113
  }
3114
+ async function assertKnownLaneOutpost(ctx, requested, company) {
3115
+ if (!isCompanyOutpostId(requested)) {
3116
+ let known;
3117
+ try {
3118
+ known = await ctx.listOutpostIds();
3119
+ }
3120
+ catch (err) {
3121
+ throw new LanesError("outpost_list_unavailable", `Failed to list Outpost ids: ${dispatchErrorMessage(err)}`, {});
3122
+ }
3123
+ assertKnownOutpost(requested, known);
3124
+ return;
3125
+ }
3126
+ if (!company)
3127
+ throw companyOutpostNeedsCompany(requested);
3128
+ assertCompanyOutpostBelongsTo(requested, company);
3129
+ let candidates;
3130
+ try {
3131
+ candidates = await ctx.listCompanyOutposts(company);
3132
+ }
3133
+ catch (err) {
3134
+ throw companyOutpostRefusal(err, requested, company) ?? new LanesError("outpost_list_unavailable", `Failed to list ${company.slug}'s Outposts: ${dispatchErrorMessage(err)}`, { company: company.slug });
3135
+ }
3136
+ assertKnownOutpost(requested, candidates.map((row) => row.outpostId));
3137
+ const candidate = candidates.find((row) => row.outpostId === requested);
3138
+ if (candidate?.canUse === false)
3139
+ throw companyOutpostAccessRequired(requested, company);
3140
+ if (candidate?.lanesReady !== true)
3141
+ throw companyOutpostNotLaneReady(requested, company);
3142
+ ctx.companyOutposts.remember(company, [requested]);
3143
+ }
3072
3144
  function assertKnownOutpost(requested, known) {
3073
3145
  if (!known.includes(requested)) {
3074
3146
  throw new LanesError("unknown_outpost", `Unknown Outpost ${JSON.stringify(requested)}. Accepted: ${known.join(", ") || "(none)"}`, { accepted: known, value: requested });
@@ -3559,14 +3631,58 @@ function markPickupFailure(hqRoot, laneId, reasonRaw, details) {
3559
3631
  export function applyOutpostAccountPickup(hqRoot, laneId, modelDeps = {}) {
3560
3632
  const lane = readLane(hqRoot, laneId);
3561
3633
  const config = loadLanesConfig(hqRoot);
3634
+ // PS-006: a recorded login held by another person is never resolved or
3635
+ // probed here. When balancing or the router chose it (account_source
3636
+ // "balanced" or "auto"), pick again among the usable logins; the balanced
3637
+ // pick never returns a held login. When it was pinned (--account, a worker
3638
+ // profile, or a record from before account_source), fail the pickup. The
3639
+ // pickup terminal reasons are a fixed schema list, so that reuses
3640
+ // account_disabled and names the cause in the details.
3641
+ const recordedConfig = lane.account === undefined ? undefined : config.providers[lane.provider].accounts[lane.account];
3642
+ const recordedHeld = lane.account !== undefined && accountHeldByOther(recordedConfig);
3643
+ const recordedPinned = lane.account_source !== "balanced" && lane.account_source !== "auto";
3644
+ if (recordedHeld && recordedPinned) {
3645
+ return markPickupFailure(hqRoot, laneId, "account_disabled", {
3646
+ error: "account_held_by_other",
3647
+ provider: lane.provider,
3648
+ account: lane.account,
3649
+ holder: recordedConfig?.holder ?? null,
3650
+ });
3651
+ }
3652
+ // A pick at pickup (no recorded account, or a balanced login now held by
3653
+ // another person) stays inside the lane's company and its admission list,
3654
+ // the same scope a local first assignment uses. Nothing left in scope fails
3655
+ // the pickup instead of borrowing another company's or a personal login.
3656
+ const repick = lane.account === undefined || recordedHeld;
3657
+ let allowedAccounts;
3658
+ if (repick) {
3659
+ const providerAccounts = config.providers[lane.provider].accounts;
3660
+ const company = resolveLaneCompany(hqRoot, lane).company;
3661
+ allowedAccounts = Object.keys(providerAccounts).filter((id) => accountMatchesCompany(providerAccounts[id], company, providerAccounts) &&
3662
+ (lane.admission_accounts === undefined || lane.admission_accounts.includes(id)));
3663
+ if (!allowedAccounts.some((id) => providerAccounts[id]?.enabled === true && !accountHeldByOther(providerAccounts[id]))) {
3664
+ return markPickupFailure(hqRoot, laneId, "account_disabled", {
3665
+ error: recordedHeld ? "account_held_by_other" : "no_account_in_lane_scope",
3666
+ provider: lane.provider,
3667
+ account: lane.account ?? null,
3668
+ ...(recordedHeld ? { holder: recordedConfig?.holder ?? null } : {}),
3669
+ company: company?.slug ?? null,
3670
+ admission_accounts: lane.admission_accounts ?? null,
3671
+ message: "No enabled login in the lane's company" +
3672
+ (lane.admission_accounts !== undefined ? " and admission accounts" : "") +
3673
+ " is usable by lanes on this host",
3674
+ });
3675
+ }
3676
+ }
3562
3677
  try {
3563
- const resolved = resolveAccount(lane.provider, lane.account, config, {
3678
+ const resolved = resolveAccount(lane.provider, repick ? undefined : lane.account, config, {
3564
3679
  hqRoot,
3565
3680
  hostname: os.hostname(),
3566
3681
  accountDeps: {
3567
3682
  probe: modelDeps.probe,
3568
3683
  env: modelDeps.env,
3569
3684
  },
3685
+ ...(allowedAccounts !== undefined ? { allowedAccounts } : {}),
3570
3686
  });
3571
3687
  const status = accountStatus(lane.provider, resolved.id, config, {
3572
3688
  existsSync: (p) => fs.existsSync(p),
@@ -3622,19 +3738,42 @@ export function applyOutpostAccountPickup(hqRoot, laneId, modelDeps = {}) {
3622
3738
  // writer. `account` stays closed to `command`: an operator command never
3623
3739
  // re-pins the account of a lane it does not execute. The bind also
3624
3740
  // clears the pickup marker: from here the reconcile pass may admit it.
3625
- return retryUpdateLane(hqRoot, laneId, "spawn", (current) => {
3741
+ const bound = retryUpdateLane(hqRoot, laneId, "spawn", (current) => {
3626
3742
  if (isTerminalLaneState(current.state) || current.state === "running")
3627
3743
  return current;
3628
3744
  if (current.account === resolved.id && current.pickup_validation_pending === undefined) {
3629
3745
  return current;
3630
3746
  }
3747
+ const leavingHeld = recordedHeld && current.account === lane.account && current.account !== resolved.id;
3631
3748
  return {
3632
3749
  ...current,
3633
3750
  account: resolved.id,
3634
3751
  pickup_validation_pending: undefined,
3635
3752
  pickup_validation_pending_since: undefined,
3753
+ ...(leavingHeld
3754
+ ? {
3755
+ account_history: appendCappedHistory(current.account_history ?? [], {
3756
+ from: current.account ?? null,
3757
+ to: resolved.id,
3758
+ at: new Date().toISOString(),
3759
+ reason: "account_unavailable",
3760
+ }),
3761
+ }
3762
+ : {}),
3636
3763
  };
3637
3764
  });
3765
+ // PS-006: after leaving a held login, the source and any Claude balance
3766
+ // selection that pointed at it describe an account the lane no longer
3767
+ // uses. Those fields are command-written, so this is a second write.
3768
+ if (recordedHeld && bound.account === resolved.id && bound.account !== lane.account &&
3769
+ (bound.account_source !== "balanced" || bound.account_selection !== undefined)) {
3770
+ return retryUpdateLane(hqRoot, laneId, "command", (current) => {
3771
+ if (isTerminalLaneState(current.state) || current.account !== resolved.id)
3772
+ return current;
3773
+ return { ...current, account_source: "balanced", account_selection: undefined };
3774
+ });
3775
+ }
3776
+ return bound;
3638
3777
  }
3639
3778
  catch (err) {
3640
3779
  if (err instanceof AccountResolutionError) {
@@ -3692,6 +3831,14 @@ export async function createLaneFromSignal(input, deps = {}) {
3692
3831
  }
3693
3832
  /** Project label for lanes created with --no-story and no --project. */
3694
3833
  export const NO_STORY_DEFAULT_PROJECT = "standing";
3834
+ /** PS-006: a pinned login held by another person is refused before anything touches its home. */
3835
+ function refuseHeldPinnedAccount(provider, account, config) {
3836
+ const accountConfig = config.providers[provider].accounts[account];
3837
+ if (!accountHeldByOther(accountConfig))
3838
+ return;
3839
+ const holder = accountConfig?.holder ?? null;
3840
+ throw new LanesError("account_held_by_other", `Account ${account} is held by ${holder}, not the owner, and is not used for lanes`, { provider, account, holder });
3841
+ }
3695
3842
  async function runCreate(ctx, opts) {
3696
3843
  if (opts.signal !== undefined) {
3697
3844
  if (!opts.company?.trim())
@@ -3869,16 +4016,8 @@ async function runCreate(ctx, opts) {
3869
4016
  explicitProvider = autoChosenProvider;
3870
4017
  }
3871
4018
  }
3872
- if (opts.outpost !== undefined && opts.outpost !== "") {
3873
- const requested = opts.outpost.trim();
3874
- let known;
3875
- try {
3876
- known = await ctx.listOutpostIds();
3877
- }
3878
- catch (err) {
3879
- throw new LanesError("outpost_list_unavailable", `Failed to list Outpost ids: ${err instanceof Error ? err.message : String(err)}`, {});
3880
- }
3881
- assertKnownOutpost(requested, known);
4019
+ if (opts.outpost !== undefined && opts.outpost !== "" && !isCompanyOutpostId(opts.outpost.trim())) {
4020
+ await assertKnownLaneOutpost(ctx, opts.outpost.trim(), null);
3882
4021
  }
3883
4022
  let company = companyFlag
3884
4023
  ? await ctx.resolveCompany(companyFlag)
@@ -3904,6 +4043,9 @@ async function runCreate(ctx, opts) {
3904
4043
  if (seniorCompanyIdentifier)
3905
4044
  company = await ctx.resolveCompany(seniorCompanyIdentifier);
3906
4045
  }
4046
+ if (opts.outpost !== undefined && opts.outpost !== "" && isCompanyOutpostId(opts.outpost.trim())) {
4047
+ await assertKnownLaneOutpost(ctx, opts.outpost.trim(), company);
4048
+ }
3907
4049
  const callerAuthorization = requestedHireGrant !== undefined || ctx.env.HQ_LANE_ID?.trim()
3908
4050
  ? callerSeniorAuthorization(ctx, senior)
3909
4051
  : { authorized: true };
@@ -4112,14 +4254,7 @@ async function runCreate(ctx, opts) {
4112
4254
  for (const target of outpostTargets) {
4113
4255
  if (target === opts.outpost?.trim())
4114
4256
  continue;
4115
- let known;
4116
- try {
4117
- known = await ctx.listOutpostIds();
4118
- }
4119
- catch (err) {
4120
- throw new LanesError("outpost_list_unavailable", `Failed to list Outpost ids: ${dispatchErrorMessage(err)}`, {});
4121
- }
4122
- assertKnownOutpost(target, known);
4257
+ await assertKnownLaneOutpost(ctx, target, company);
4123
4258
  }
4124
4259
  if (placementToApply !== undefined) {
4125
4260
  const currentHost = laneHostFromCtx(ctx);
@@ -4147,7 +4282,7 @@ async function runCreate(ctx, opts) {
4147
4282
  }
4148
4283
  }
4149
4284
  else {
4150
- const capacity = await loadHostCapacitySnapshots(ctx, hqRoot, config);
4285
+ const capacity = await loadHostCapacitySnapshots(ctx, hqRoot, config, undefined, company);
4151
4286
  autoPlacementSkippedHosts = capacity.skippedHosts;
4152
4287
  const requestedAccount = opts.account !== undefined
4153
4288
  ? opts.account.trim()
@@ -4234,6 +4369,7 @@ async function runCreate(ctx, opts) {
4234
4369
  if (!requested) {
4235
4370
  throw new AccountResolutionError("unknown_account", `Unknown account ${JSON.stringify(opts.account)} for ${provider}`, { provider, account: opts.account, enabled: [] });
4236
4371
  }
4372
+ refuseHeldPinnedAccount(provider, requested, config);
4237
4373
  const resolved = resolveAccount(provider, requested, config, {
4238
4374
  hqRoot,
4239
4375
  hostname: ctx.hostname(),
@@ -4243,6 +4379,7 @@ async function runCreate(ctx, opts) {
4243
4379
  pinnedAccount = resolved.id;
4244
4380
  }
4245
4381
  else if (profileAccount !== undefined && profileAccounts === undefined) {
4382
+ refuseHeldPinnedAccount(provider, profileAccount, config);
4246
4383
  const resolved = resolveAccount(provider, profileAccount, config, {
4247
4384
  hqRoot,
4248
4385
  hostname: ctx.hostname(),
@@ -4251,6 +4388,10 @@ async function runCreate(ctx, opts) {
4251
4388
  });
4252
4389
  pinnedAccount = resolved.id;
4253
4390
  }
4391
+ // PS-006: refuse a pinned login held by another person before any model
4392
+ // check reads its home.
4393
+ if (pinnedAccount !== undefined)
4394
+ refuseHeldPinnedAccount(provider, pinnedAccount, config);
4254
4395
  if (outpostId !== undefined &&
4255
4396
  profile !== undefined &&
4256
4397
  !(await placementEnabled())) {
@@ -4316,6 +4457,9 @@ async function runCreate(ctx, opts) {
4316
4457
  ...Object.keys(accounts)
4317
4458
  .filter((id) => id !== candidate &&
4318
4459
  accounts[id]?.enabled &&
4460
+ // PS-006: never probe, list models or read the catalog in
4461
+ // another person's login home.
4462
+ !accountHeldByOther(accounts[id]) &&
4319
4463
  (profileAccounts === undefined || profileAccounts.includes(id)) &&
4320
4464
  accountStatus(provider, id, config, {
4321
4465
  existsSync: ctx.existsSync,
@@ -4397,6 +4541,8 @@ async function runCreate(ctx, opts) {
4397
4541
  const accountCompany = resolveLaneCompany(hqRoot, { lane_id: "pending-create", company, mesh_company: meshCompany ?? undefined, project_id: project }).company;
4398
4542
  const allowedAccounts = Object.keys(config.providers[provider].accounts).filter((id) => (candidateAccounts === undefined || candidateAccounts.includes(id)) &&
4399
4543
  accountMatchesCompany(config.providers[provider].accounts[id], accountCompany, config.providers[provider].accounts));
4544
+ if (pinnedAccount !== undefined)
4545
+ refuseHeldPinnedAccount(provider, pinnedAccount, config);
4400
4546
  if (pinnedAccount !== undefined && !accountMatchesCompany(config.providers[provider].accounts[pinnedAccount], accountCompany, config.providers[provider].accounts)) {
4401
4547
  throw new LanesError("account_company_mismatch", `Account ${pinnedAccount} does not belong to the lane company`, { provider, account: pinnedAccount });
4402
4548
  }
@@ -5179,6 +5325,14 @@ async function dispatchCreatedOutpostLane(ctx, input) {
5179
5325
  message,
5180
5326
  });
5181
5327
  await emitLaneTerminalStateSoft(ctx, failed);
5328
+ if (isCompanyOutpostRefusal(err)) {
5329
+ throw new LanesError(err.error, err.message, {
5330
+ ...err.details,
5331
+ lane_id: failed.lane_id,
5332
+ state: failed.state,
5333
+ terminal_reason: DISPATCH_TERMINAL_REASON,
5334
+ });
5335
+ }
5182
5336
  throw new LanesError(DISPATCH_TERMINAL_REASON, `Failed to dispatch lane to Outpost ${outpostId}: ${message}`, {
5183
5337
  outpost_id: outpostId,
5184
5338
  lane_id: failed.lane_id,
@@ -7302,11 +7456,16 @@ function applyLaneSettings(ctx, laneId, request, options) {
7302
7456
  if (account === undefined) {
7303
7457
  throw new AccountResolutionError("unknown_account", `Lane ${laneId} records account ${JSON.stringify(lane.account)} which is not configured for ${lane.provider}`, { provider: lane.provider, account: lane.account ?? "", enabled: [] });
7304
7458
  }
7305
- validateLaneModel(lane.provider, model, effectiveAccountHome(account, ctx.hostname()).home, {
7306
- readFileSync: ctx.readFileSync,
7307
- probe: ctx.probeProvider,
7308
- env: ctx.env,
7309
- });
7459
+ // PS-006: never list models or read the catalog in another person's
7460
+ // login. The next spawn moves the lane off it (or refuses) and checks the
7461
+ // model against the account it really runs on.
7462
+ if (!accountHeldByOther(account)) {
7463
+ validateLaneModel(lane.provider, model, effectiveAccountHome(account, ctx.hostname()).home, {
7464
+ readFileSync: ctx.readFileSync,
7465
+ probe: ctx.probeProvider,
7466
+ env: ctx.env,
7467
+ });
7468
+ }
7310
7469
  }
7311
7470
  const effort = parseCliEffort(lane.provider, request.effort);
7312
7471
  const at = ctx.now().toISOString();
@@ -7858,6 +8017,10 @@ function validateResumeProfileModel(ctx, lane, profile) {
7858
8017
  }
7859
8018
  const hqRoot = ctx.hqRoot();
7860
8019
  const config = loadLanesConfig(hqRoot);
8020
+ // PS-006: never read models in another person's login. The resume moves the
8021
+ // lane off that login at spawn, where the new account's models are checked.
8022
+ if (lane.account !== undefined && accountHeldByOther(config.providers[lane.provider].accounts[lane.account]))
8023
+ return;
7861
8024
  const account = resolveAccount(lane.provider, lane.account, config, {
7862
8025
  hqRoot,
7863
8026
  existsSync: ctx.existsSync,
@@ -7927,6 +8090,15 @@ export function applyResumeProfileAndEffort(hqRoot, current, next, input) {
7927
8090
  next.provider = targetProvider;
7928
8091
  next.provider_source = providerPinned ? current.provider_source : "profile";
7929
8092
  if (!accountPinned && profileMatchesProvider) {
8093
+ const profileAccountConfig = profileAccount === undefined
8094
+ ? undefined
8095
+ : loadLanesConfig(hqRoot).providers[targetProvider].accounts[profileAccount];
8096
+ if (profileAccount !== undefined && accountHeldByOther(profileAccountConfig)) {
8097
+ const holder = profileAccountConfig?.holder ?? null;
8098
+ throw new LanesError("account_held_by_other", `Worker profile account ${profileAccount} is held by ${holder}, not the owner, and is not used for lanes`, {
8099
+ lane_id: current.lane_id, account: profileAccount, holder,
8100
+ });
8101
+ }
7930
8102
  if (profileAccount !== undefined && profileAccount !== current.account &&
7931
8103
  !accountMatchesCompany(loadLanesConfig(hqRoot).providers[targetProvider].accounts[profileAccount], resolveLaneCompany(hqRoot, current).company, loadLanesConfig(hqRoot).providers[targetProvider].accounts)) {
7932
8104
  throw new LanesError("account_company_mismatch", "Worker profile account does not belong to the lane company", {
@@ -8001,11 +8173,15 @@ function recordResumeSetup(ctx, lane, input) {
8001
8173
  if (account === undefined) {
8002
8174
  throw new AccountResolutionError("unknown_account", `Lane ${lane.lane_id} records account ${JSON.stringify(lane.account)} which is not configured for ${lane.provider}`, { provider: lane.provider, account: lane.account ?? "", enabled: [] });
8003
8175
  }
8004
- validateLaneModel(lane.provider, model, effectiveAccountHome(account, ctx.hostname()).home, {
8005
- readFileSync: ctx.readFileSync,
8006
- probe: ctx.probeProvider,
8007
- env: ctx.env,
8008
- });
8176
+ // PS-006: as in applyLaneSettings, a held recorded login is not probed;
8177
+ // spawn moves the lane off it or refuses.
8178
+ if (!accountHeldByOther(account)) {
8179
+ validateLaneModel(lane.provider, model, effectiveAccountHome(account, ctx.hostname()).home, {
8180
+ readFileSync: ctx.readFileSync,
8181
+ probe: ctx.probeProvider,
8182
+ env: ctx.env,
8183
+ });
8184
+ }
8009
8185
  }
8010
8186
  if (input.profile === undefined &&
8011
8187
  input.effort === undefined &&
@@ -8122,6 +8298,11 @@ async function prepareAccountMove(ctx, lane, input) {
8122
8298
  if (targetCfg === undefined) {
8123
8299
  throw new AccountResolutionError("unknown_account", `Unknown account ${JSON.stringify(target)} for ${lane.provider}. Configured: ${Object.keys(providerCfg.accounts).join(", ") || "(none)"}`, { provider: lane.provider, account: target, enabled: Object.keys(providerCfg.accounts).filter((id) => providerCfg.accounts[id]?.enabled) });
8124
8300
  }
8301
+ if (accountHeldByOther(targetCfg)) {
8302
+ throw new LanesError("account_held_by_other", `Account ${target} is held by ${targetCfg.holder}, not the owner, and is not used for lanes`, {
8303
+ provider: lane.provider, account: target, holder: targetCfg.holder ?? null,
8304
+ });
8305
+ }
8125
8306
  if (!accountMatchesCompany(targetCfg, resolveLaneCompany(hqRoot, lane).company, providerCfg.accounts)) {
8126
8307
  throw new LanesError("account_company_mismatch", "Lane moves require an account assigned to the lane's company", {
8127
8308
  provider: lane.provider, account: target, company: lane.company,
@@ -11599,6 +11780,17 @@ export function registerRunnersCommand(parent, deps = {}) {
11599
11780
  .action(wrap(async (provider, accountId, home, opts) => {
11600
11781
  await accountHandlers.runAccountsSetHome(ctx, provider, accountId, home, opts);
11601
11782
  }));
11783
+ accounts
11784
+ .command("set-owner")
11785
+ .description("Record which business owns a login and who holds it (labels only; no credential moves)")
11786
+ .argument("<provider>", "claude | codex | grok")
11787
+ .argument("<account-id>", "Existing account id")
11788
+ .option("--owning-company <slug>", "Company slug, personal, or unknown")
11789
+ .option("--holder <name>", "owner, or the name of the person who holds the login")
11790
+ .option("--json", "JSON on stdout (always)")
11791
+ .action(wrap(async (provider, accountId, opts) => {
11792
+ await accountHandlers.runAccountsSetOwner(ctx, provider, accountId, opts);
11793
+ }));
11602
11794
  accounts
11603
11795
  .command("login")
11604
11796
  .description("Create a home, run the vendor login, and register the account")
@@ -4,6 +4,7 @@
4
4
  * see src/lib/registry/registry.ts for the key and precedence rules.
5
5
  */
6
6
  import { Command } from "commander";
7
+ import { type ResolveResult } from "../lib/registry/registry.js";
7
8
  export interface MembershipCompany {
8
9
  companyUid: string;
9
10
  companySlug: string;
@@ -14,8 +15,12 @@ export interface LinkDeps {
14
15
  /** Active memberships for the signed-in user (reuses GET /membership/me). */
15
16
  listMemberships?: () => Promise<MembershipCompany[]>;
16
17
  now?: () => Date;
17
- /** HQ root for the companies/<slug> layout fallback (default: $HQ_ROOT). */
18
- hqRoot?: string;
18
+ /**
19
+ * HQ root whose companies/manifest.yaml the shared resolver checks, and the
20
+ * only tree whose companies/<slug> layout may bind a company.
21
+ * Undefined looks the root up the way `hq mcp serve` does. Null means there is no root.
22
+ */
23
+ hqRoot?: string | null;
19
24
  }
20
25
  export interface LinkCommandDeps {
21
26
  /** Test seam for the combined hq-flags and person-setting gate. */
@@ -27,7 +32,7 @@ export declare function linkFolder(company: string, dir: string | undefined, dep
27
32
  company: string;
28
33
  }>;
29
34
  export declare function unlinkFolder(dir: string | undefined, deps?: LinkDeps): string[];
30
- export declare function resolveCompany(dir: string | undefined, deps?: LinkDeps): import("../lib/registry/registry.js").ResolveResult;
35
+ export declare function resolveCompany(dir: string | undefined, deps?: LinkDeps): ResolveResult;
31
36
  /** Seed manifest-sourced entries; called by `hq install --global` (US-005). */
32
37
  export declare function seedRegistryFromHqRoot(hqRoot: string, deps?: LinkDeps): import("../lib/registry/registry.js").SeedResult;
33
38
  export declare function registerLinkCommand(program: Command, deps?: LinkCommandDeps): void;
@@ -4,14 +4,17 @@
4
4
  * see src/lib/registry/registry.ts for the key and precedence rules.
5
5
  */
6
6
  import * as fs from "node:fs";
7
+ import * as os from "node:os";
7
8
  import * as path from "node:path";
8
9
  import { Option } from "commander";
9
10
  import chalk from "chalk";
10
11
  import { ensureCognitoToken } from "../utils/cognito-session.js";
11
12
  import { listActiveMembershipCompanies } from "../lib/mesh/api.js";
12
13
  import { anywhereRuntimeAllowed } from "../lib/anywhere-person-setting.js";
14
+ import { createResolver } from "../lib/daemon/resolver.js";
13
15
  import { readCompaniesManifestMap } from "../lib/work-context/repo-remote.js";
14
- import { canonicalDir, keyForDir, readRegistry, registryDir, registryFile, removeEntriesForDir, resolveCompanyForDir, seedFromManifest, setEntry, wouldBindEnclosingRemote, writeRegistry, } from "../lib/registry/registry.js";
16
+ import { canonicalDir, keyForDir, readRegistry, registryDir, registryFile, removeEntriesForDir, seedFromManifest, setEntry, wouldBindEnclosingRemote, writeRegistry, } from "../lib/registry/registry.js";
17
+ import { readHqRoot } from "./mcp-serve.js";
15
18
  async function requireAnywhereRuntime(deps) {
16
19
  if (!(await (deps.runtimeAllowed ?? (() => anywhereRuntimeAllowed()))())) {
17
20
  throw new Error("HQ Anywhere is disabled until both the runtime flag and your person setting are on.");
@@ -59,23 +62,17 @@ export function unlinkFolder(dir, deps = {}) {
59
62
  }
60
63
  export function resolveCompany(dir, deps = {}) {
61
64
  const folder = path.resolve(dir?.trim() || process.cwd());
62
- let registry;
63
- try {
64
- registry = readRegistry(deps.file ?? registryFile());
65
- }
66
- catch (err) {
67
- return { company: null, reason: err.message };
65
+ let root = deps.hqRoot;
66
+ if (root === undefined) {
67
+ try {
68
+ root = readHqRoot(process.env, os.homedir());
69
+ }
70
+ catch {
71
+ root = undefined;
72
+ }
68
73
  }
69
- return resolveCompanyForDir(registry, folder, { hqRoot: layoutHqRoot(deps) });
70
- }
71
- /**
72
- * The HQ root the companies/<slug> layout fallback may trust: an explicit
73
- * dependency or $HQ_ROOT only. Never a cwd walk or CLAUDE_PROJECT_DIR, which
74
- * in a session started outside HQ is that foreign folder.
75
- */
76
- function layoutHqRoot(deps) {
77
- const raw = deps.hqRoot ?? process.env.HQ_ROOT ?? "";
78
- return raw.trim() ? path.resolve(raw.trim()) : null;
74
+ const resolve = createResolver(deps.file ?? registryFile(), { hqRoot: root ?? undefined });
75
+ return resolve(folder);
79
76
  }
80
77
  /** Seed manifest-sourced entries; called by `hq install --global` (US-005). */
81
78
  export function seedRegistryFromHqRoot(hqRoot, deps = {}) {