@indigoai-us/hq-cli 5.345.223 → 5.345.226

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 (130) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/assets/bot-workers/setup/context/quick-reference.md +2 -2
  3. package/assets/mesh-daemon/README.md +11 -12
  4. package/dist/command-catalog.generated.d.ts +156 -4
  5. package/dist/command-catalog.generated.js +191 -4
  6. package/dist/commands/cloud-provision.d.ts +4 -1
  7. package/dist/commands/cloud-provision.js +7 -3
  8. package/dist/commands/cloud-retire.js +1 -1
  9. package/dist/commands/core-delegate-w1b.js +3 -1
  10. package/dist/commands/core-delegate.d.ts +5 -0
  11. package/dist/commands/core-dm-bind-native.d.ts +5 -1
  12. package/dist/commands/core-dm-bind-native.js +4 -0
  13. package/dist/commands/core-job-notify-native.d.ts +5 -1
  14. package/dist/commands/core-job-notify-native.js +8 -2
  15. package/dist/commands/core-jobs-native.d.ts +27 -1
  16. package/dist/commands/core-jobs-native.js +49 -28
  17. package/dist/commands/core-pipeline-conductor-native.js +7 -7
  18. package/dist/commands/core-pipeline-driver-native.js +5 -5
  19. package/dist/commands/core-refresh-vault-access-native.d.ts +5 -0
  20. package/dist/commands/core-refresh-vault-access-native.js +3 -1
  21. package/dist/commands/core-work-mesh-bind-trusted-native.js +1 -1
  22. package/dist/commands/daemon.d.ts +2 -0
  23. package/dist/commands/daemon.js +68 -2
  24. package/dist/commands/deploy-domains.js +38 -2
  25. package/dist/commands/lanes-accounts.d.ts +14 -0
  26. package/dist/commands/lanes-accounts.js +119 -0
  27. package/dist/commands/lanes-hold.d.ts +2 -27
  28. package/dist/commands/lanes-hold.js +3 -75
  29. package/dist/commands/lanes-loop.js +1 -1
  30. package/dist/commands/lanes-move.js +10 -0
  31. package/dist/commands/lanes-session-start.js +2 -2
  32. package/dist/commands/lanes-shared.js +9 -0
  33. package/dist/commands/lanes.js +137 -12
  34. package/dist/commands/mesh.d.ts +12 -0
  35. package/dist/commands/mesh.js +13 -4
  36. package/dist/commands/monitor.js +1 -1
  37. package/dist/commands/packs.js +1 -1
  38. package/dist/commands/sync-held.d.ts +22 -0
  39. package/dist/commands/sync-held.js +167 -18
  40. package/dist/commands/whoami.d.ts +10 -17
  41. package/dist/commands/whoami.js +7 -79
  42. package/dist/data/command-states.json +13 -0
  43. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  44. package/dist/hq-cloud-sync-runner/package.json +1 -1
  45. package/dist/index.js +1 -1
  46. package/dist/lib/capacity/accounts.d.ts +4 -0
  47. package/dist/lib/capacity/accounts.js +4 -0
  48. package/dist/lib/capacity/route.js +14 -0
  49. package/dist/lib/capacity/sign-in.d.ts +18 -0
  50. package/dist/lib/capacity/sign-in.js +34 -1
  51. package/dist/lib/daemon/catalog.d.ts +9 -5
  52. package/dist/lib/daemon/catalog.js +14 -8
  53. package/dist/lib/daemon/config.d.ts +5 -0
  54. package/dist/lib/daemon/config.js +6 -0
  55. package/dist/lib/daemon/hook-requests.d.ts +76 -0
  56. package/dist/lib/daemon/hook-requests.js +481 -0
  57. package/dist/lib/daemon/lanes-monitor-state.d.ts +55 -0
  58. package/dist/lib/daemon/lanes-monitor-state.js +129 -0
  59. package/dist/lib/daemon/lanes-reconcile-loader.d.ts +7 -0
  60. package/dist/lib/daemon/lanes-reconcile-loader.js +13 -0
  61. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  62. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  63. package/dist/lib/daemon/merge-sections.d.ts +165 -0
  64. package/dist/lib/daemon/merge-sections.js +556 -0
  65. package/dist/lib/daemon/ops/policy.d.ts +2 -2
  66. package/dist/lib/daemon/ops/policy.js +44 -5
  67. package/dist/lib/daemon/protocol.d.ts +1 -1
  68. package/dist/lib/daemon/protocol.js +0 -6
  69. package/dist/lib/daemon/run.js +110 -5
  70. package/dist/lib/daemon/selfcheck.js +2 -2
  71. package/dist/lib/daemon/server.d.ts +2 -4
  72. package/dist/lib/daemon/server.js +11 -49
  73. package/dist/lib/daemon/state-file.d.ts +74 -4
  74. package/dist/lib/daemon/state-file.js +159 -19
  75. package/dist/lib/daemon/supervisor.d.ts +3 -1
  76. package/dist/lib/daemon/updater.d.ts +2 -6
  77. package/dist/lib/daemon/updater.js +4 -11
  78. package/dist/lib/daemon/whoami-cache.d.ts +96 -0
  79. package/dist/lib/daemon/whoami-cache.js +244 -0
  80. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  81. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  82. package/dist/lib/hook-engine/coverage.d.ts +2 -0
  83. package/dist/lib/hook-engine/coverage.js +71 -0
  84. package/dist/lib/hook-engine/native-precompact-compatibility.json +449 -0
  85. package/dist/lib/hook-engine/reconcile.js +14 -8
  86. package/dist/lib/install/hook-target.d.ts +13 -3
  87. package/dist/lib/install/hook-target.js +14 -11
  88. package/dist/lib/lanes/account-company.d.ts +7 -1
  89. package/dist/lib/lanes/account-company.js +22 -4
  90. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  91. package/dist/lib/lanes/account-ownership.js +134 -0
  92. package/dist/lib/lanes/accounts.js +9 -2
  93. package/dist/lib/lanes/claude-balance.js +9 -3
  94. package/dist/lib/lanes/config.js +17 -0
  95. package/dist/lib/lanes/envelope-repair-dispatch.js +1 -1
  96. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  97. package/dist/lib/lanes/host-capacity.js +37 -0
  98. package/dist/lib/lanes/monitor.d.ts +2 -0
  99. package/dist/lib/lanes/monitor.js +2 -1
  100. package/dist/lib/lanes/reconcile.js +44 -3
  101. package/dist/lib/lanes/registry-flag.d.ts +6 -0
  102. package/dist/lib/lanes/registry-flag.js +3 -2
  103. package/dist/lib/lanes/repo-merge-hold.d.ts +39 -0
  104. package/dist/lib/lanes/repo-merge-hold.js +90 -0
  105. package/dist/lib/lanes/spawn.d.ts +0 -10
  106. package/dist/lib/lanes/spawn.js +51 -1
  107. package/dist/lib/lanes/types.d.ts +12 -0
  108. package/dist/lib/lanes/watcher-main.js +3 -3
  109. package/dist/lib/mesh/live/daemon/doctor.js +1 -1
  110. package/dist/lib/mesh/live/daemon/install.js +2 -2
  111. package/dist/lib/windows/install-followup.js +1 -1
  112. package/dist/utils/client-health-contract.d.ts +1 -0
  113. package/dist/utils/client-health-contract.js +5 -0
  114. package/dist/utils/client-health.d.ts +2 -0
  115. package/dist/utils/client-health.js +40 -0
  116. package/dist/utils/cognito-session.d.ts +2 -14
  117. package/dist/utils/cognito-session.js +2 -40
  118. package/dist/utils/daemon-cli-version.d.ts +13 -0
  119. package/dist/utils/daemon-cli-version.js +47 -0
  120. package/dist/utils/duplicate-command-usage.js +1 -1
  121. package/dist/utils/machine-token-cache.d.ts +21 -0
  122. package/dist/utils/machine-token-cache.js +49 -0
  123. package/dist/utils/resident-package-preload.js +4 -0
  124. package/dist/utils/whoami-identity.d.ts +54 -0
  125. package/dist/utils/whoami-identity.js +108 -0
  126. package/package.json +8 -8
  127. package/dist/lib/daemon/ops/memory.d.ts +0 -18
  128. package/dist/lib/daemon/ops/memory.js +0 -65
  129. package/dist/lib/daemon/ops/mesh.d.ts +0 -38
  130. package/dist/lib/daemon/ops/mesh.js +0 -70
@@ -6,6 +6,7 @@
6
6
  * live process — this pass owns the transitions no single lane can own.
7
7
  */
8
8
  import { accountMatchesCompany } from "./account-company.js";
9
+ import { accountHeldByOther } from "./account-ownership.js";
9
10
  import * as fs from "node:fs";
10
11
  import * as path from "node:path";
11
12
  import { parseUserYaml } from "../../utils/user-yaml-error.js";
@@ -756,6 +757,29 @@ function availableBalancedAccount(hqRoot, lane, occupying, config, host, profile
756
757
  }
757
758
  return undefined;
758
759
  }
760
+ /**
761
+ * Move a queued recovering lane off a login that another person holds
762
+ * (PS-006). The write is guarded on the lane still recording that login and
763
+ * the target being one this lane may use, and it records the change in
764
+ * account_history like any other automatic account move.
765
+ */
766
+ function writeRecoveryAccountOffHeldLogin(hqRoot, lane, account, now, dryRun) {
767
+ return casLaneIf(hqRoot, lane.lane_id, (current) => {
768
+ const accounts = loadLanesConfig(hqRoot).providers[current.provider].accounts;
769
+ return current.state === "queued" &&
770
+ current.account === lane.account &&
771
+ current.account !== undefined &&
772
+ accountHeldByOther(accounts[current.account]) &&
773
+ accountMatchesCompany(accounts[account], resolveLaneCompany(hqRoot, current).company, accounts);
774
+ }, (current) => ({
775
+ ...current,
776
+ account,
777
+ account_history: [
778
+ ...(current.account_history ?? []),
779
+ { from: current.account ?? null, to: account, at: now.toISOString(), reason: "account_unavailable" },
780
+ ],
781
+ }), dryRun).record;
782
+ }
759
783
  function writeAdmissionAccount(hqRoot, lane, account, dryRun) {
760
784
  return casLaneIf(hqRoot, lane.lane_id, (current) => current.state === "queued" &&
761
785
  current.account === lane.account &&
@@ -2245,8 +2269,12 @@ async function admitQueued(hqRoot, lanes, summary, deps, now, onlyLaneIds, exclu
2245
2269
  const accounts = config.providers[admittedLane.provider].accounts;
2246
2270
  const company = resolveLaneCompany(hqRoot, admittedLane).company;
2247
2271
  let account;
2272
+ // A recorded login now held by another person is not kept (PS-006):
2273
+ // pick again among the allowed accounts instead.
2274
+ const leavingHeldLogin = admittedLane.account !== undefined && accountHeldByOther(accounts[admittedLane.account]);
2275
+ const recorded = leavingHeldLogin ? undefined : admittedLane.account;
2248
2276
  try {
2249
- account = resolveAccount(admittedLane.provider, admittedLane.account, config, {
2277
+ account = resolveAccount(admittedLane.provider, recorded, config, {
2250
2278
  hqRoot, hostname: deps.host.hostname,
2251
2279
  allowedAccounts: Object.keys(accounts).filter((id) => accountMatchesCompany(accounts[id], company, accounts)),
2252
2280
  }).id;
@@ -2257,12 +2285,25 @@ async function admitQueued(hqRoot, lanes, summary, deps, now, onlyLaneIds, exclu
2257
2285
  writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2258
2286
  continue;
2259
2287
  }
2260
- if (!accountMatchesCompany(accounts[account], company, accounts) && accounts[account]?.company !== undefined) {
2288
+ if (accountHeldByOther(accounts[account]) ||
2289
+ (!accountMatchesCompany(accounts[account], company, accounts) && accounts[account]?.company !== undefined)) {
2261
2290
  writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2262
2291
  continue;
2263
2292
  }
2264
- if (admittedLane.account !== account)
2293
+ if (leavingHeldLogin) {
2294
+ // writeAdmissionAccount only moves within admission_accounts, which a
2295
+ // recovering lane usually lacks. Leaving another person's login is not
2296
+ // an admission choice: write the move directly, and never spawn the
2297
+ // lane while it still records that login (PS-006).
2298
+ admittedLane = writeRecoveryAccountOffHeldLogin(hqRoot, admittedLane, account, now, deps.dryRun);
2299
+ if (admittedLane.account !== account) {
2300
+ writeQueueReason(hqRoot, admittedLane, "account_retry", deps.dryRun);
2301
+ continue;
2302
+ }
2303
+ }
2304
+ else if (admittedLane.account !== account) {
2265
2305
  admittedLane = writeAdmissionAccount(hqRoot, admittedLane, account, deps.dryRun);
2306
+ }
2266
2307
  const status = accountStatus(admittedLane.provider, account, config, {
2267
2308
  hostname: deps.host.hostname,
2268
2309
  existsSync: (file) => fs.existsSync(file),
@@ -28,6 +28,12 @@ export interface ReadLanesFlagOptions {
28
28
  cacheDir?: string | null;
29
29
  retryBackoffMs?: number;
30
30
  sleep?: (ms: number) => Promise<void>;
31
+ /**
32
+ * Share one read per flag and company for the life of this process (the
33
+ * default, right for a CLI command). A long-lived process (the daemon) passes
34
+ * false so every call asks the registry again.
35
+ */
36
+ shareProcessRead?: boolean;
31
37
  }
32
38
  export declare function readLanesFlagLocalOverride(flagKey: string, env?: NodeJS.ProcessEnv): boolean | null;
33
39
  export type LanesRegistryFlagResult = {
@@ -185,9 +185,10 @@ async function readRegistryFlagOutcome(flagKey, options, failOpen) {
185
185
  }
186
186
  const endpoint = resolveFlagRegistryEndpoint(undefined, env);
187
187
  const key = cacheKey(flagKey, options.company, endpoint);
188
- const cached = registryReads.get(key);
188
+ const share = options.shareProcessRead !== false;
189
+ const cached = share ? registryReads.get(key) : undefined;
189
190
  const pending = cached ?? readRegistryValue(flagKey, endpoint, key, options);
190
- if (!cached)
191
+ if (!cached && share)
191
192
  registryReads.set(key, pending);
192
193
  const outcome = await pending;
193
194
  reportRegistryFailure(flagKey, key, outcome, options, failOpen);
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Repository merge hold records (`hq lanes hold`, src/commands/lanes-hold.ts):
3
+ * their location, their format and the parser that accepts or refuses one.
4
+ * Kept apart from the command so the daemon (merge-sections.ts) can read hold
5
+ * records without loading the lanes runtime.
6
+ */
7
+ import type { LaneCompanyRef } from "./types.js";
8
+ export declare const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
9
+ export declare const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
10
+ export declare const REPO_MERGE_HOLDS_REL: string;
11
+ export declare const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
12
+ export declare const HOLD_HISTORY_CAP = 50;
13
+ export interface HoldHistoryEntry {
14
+ set_at: string;
15
+ until: string;
16
+ reason: string;
17
+ set_by_lane: string | null;
18
+ set_by_session: string | null;
19
+ released_at?: string;
20
+ released_reason?: string;
21
+ }
22
+ export interface RepoMergeHold {
23
+ schema_version: typeof HOLD_SCHEMA_VERSION;
24
+ repo: string;
25
+ company: LaneCompanyRef;
26
+ reason: string;
27
+ set_at: string;
28
+ until: string;
29
+ set_by_lane: string | null;
30
+ set_by_session: string | null;
31
+ released_at?: string;
32
+ released_reason?: string;
33
+ history: HoldHistoryEntry[];
34
+ }
35
+ /** `<hqRoot>/workspace/lanes/holds/<owner>__<repo>.json`. */
36
+ export declare function holdFilePath(hqRoot: string, repo: string): string;
37
+ /** A hold record as `hq lanes hold` accepts it; throws LanesError for any other value. */
38
+ export declare function parseHold(raw: unknown, file: string): RepoMergeHold;
39
+ //# sourceMappingURL=repo-merge-hold.d.ts.map
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Repository merge hold records (`hq lanes hold`, src/commands/lanes-hold.ts):
3
+ * their location, their format and the parser that accepts or refuses one.
4
+ * Kept apart from the command so the daemon (merge-sections.ts) can read hold
5
+ * records without loading the lanes runtime.
6
+ */
7
+ import * as path from "node:path";
8
+ import { LanesError } from "./errors.js";
9
+ import { canonicalRepo } from "./merge-command.js";
10
+ import { assertNoSecretText } from "./text-scan.js";
11
+ export const LANES_REPO_MERGE_HOLD_FLAG = "lanes.repo-merge-hold";
12
+ export const LANES_REVIEW_BEFORE_MERGE_FLAG = "lanes.review-before-merge";
13
+ export const REPO_MERGE_HOLDS_REL = path.join("workspace", "lanes", "holds");
14
+ export const HOLD_SCHEMA_VERSION = "hq-lanes-repo-merge-hold.v1";
15
+ export const HOLD_HISTORY_CAP = 50;
16
+ function fail(error, message, details = {}) {
17
+ throw new LanesError(error, message, details);
18
+ }
19
+ /** `<hqRoot>/workspace/lanes/holds/<owner>__<repo>.json`. */
20
+ export function holdFilePath(hqRoot, repo) {
21
+ const [owner, repository] = canonicalRepo(repo).split("/");
22
+ return path.join(hqRoot, REPO_MERGE_HOLDS_REL, `${owner}__${repository}.json`);
23
+ }
24
+ function isObject(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ function isCanonicalTimestamp(value) {
28
+ if (typeof value !== "string")
29
+ return false;
30
+ const timestamp = Date.parse(value);
31
+ return Number.isFinite(timestamp) && new Date(timestamp).toISOString() === value;
32
+ }
33
+ /** A hold record as `hq lanes hold` accepts it; throws LanesError for any other value. */
34
+ export function parseHold(raw, file) {
35
+ if (!isObject(raw))
36
+ return fail("repo_hold_invalid", "Merge hold record must be an object", { path: file });
37
+ const company = raw.company;
38
+ const history = raw.history;
39
+ if (raw.schema_version !== HOLD_SCHEMA_VERSION || typeof raw.repo !== "string" ||
40
+ !isObject(company) || typeof company.slug !== "string" || !company.slug.trim() ||
41
+ typeof company.uid !== "string" || !company.uid.trim() ||
42
+ typeof raw.reason !== "string" || !raw.reason.trim() ||
43
+ !isCanonicalTimestamp(raw.set_at) || !isCanonicalTimestamp(raw.until) ||
44
+ !(raw.set_by_lane === null || typeof raw.set_by_lane === "string") ||
45
+ !(raw.set_by_session === null || typeof raw.set_by_session === "string") ||
46
+ !Array.isArray(history) || history.length > HOLD_HISTORY_CAP ||
47
+ (raw.released_at !== undefined && !isCanonicalTimestamp(raw.released_at)) ||
48
+ (raw.released_reason !== undefined && typeof raw.released_reason !== "string")) {
49
+ return fail("repo_hold_invalid", "Merge hold record has invalid fields", { path: file });
50
+ }
51
+ let repo;
52
+ try {
53
+ repo = canonicalRepo(raw.repo);
54
+ }
55
+ catch {
56
+ return fail("repo_hold_invalid", "Merge hold record has an invalid repository", { path: file });
57
+ }
58
+ if (repo !== raw.repo)
59
+ return fail("repo_hold_invalid", "Merge hold repository is not canonical", { path: file });
60
+ if ((raw.released_at === undefined) !== (raw.released_reason === undefined)) {
61
+ return fail("repo_hold_invalid", "Released merge hold must include both release fields", { path: file });
62
+ }
63
+ if (raw.released_at !== undefined && (!raw.released_reason || !raw.released_reason.trim())) {
64
+ return fail("repo_hold_invalid", "Released merge hold is missing its reason", { path: file });
65
+ }
66
+ assertNoSecretText("hold.reason", raw.reason);
67
+ if (typeof raw.released_reason === "string")
68
+ assertNoSecretText("hold.released_reason", raw.released_reason);
69
+ for (const entry of history) {
70
+ if (!isObject(entry) || !isCanonicalTimestamp(entry.set_at) || !isCanonicalTimestamp(entry.until) ||
71
+ typeof entry.reason !== "string" || !entry.reason.trim() ||
72
+ !(entry.set_by_lane === null || typeof entry.set_by_lane === "string") ||
73
+ !(entry.set_by_session === null || typeof entry.set_by_session === "string") ||
74
+ (entry.released_at !== undefined && !isCanonicalTimestamp(entry.released_at)) ||
75
+ (entry.released_reason !== undefined && typeof entry.released_reason !== "string")) {
76
+ return fail("repo_hold_invalid", "Merge hold history has invalid entries", { path: file });
77
+ }
78
+ if ((entry.released_at === undefined) !== (entry.released_reason === undefined)) {
79
+ return fail("repo_hold_invalid", "Merge hold history release fields are incomplete", { path: file });
80
+ }
81
+ if (entry.released_reason !== undefined && !entry.released_reason.trim()) {
82
+ return fail("repo_hold_invalid", "Merge hold history release reason is empty", { path: file });
83
+ }
84
+ assertNoSecretText("hold.history.reason", entry.reason);
85
+ if (typeof entry.released_reason === "string")
86
+ assertNoSecretText("hold.history.released_reason", entry.released_reason);
87
+ }
88
+ return raw;
89
+ }
90
+ //# sourceMappingURL=repo-merge-hold.js.map
@@ -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>;
@@ -22,7 +22,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
22
22
  spawnRepair: (root, lane, input) => spawnEnvelopeRepairViaCurrentCli(root, lane, input, { ...repairDispatchDeps, env }),
23
23
  deliverLaneSeniorMessage: async (seniorLaneId, text) => deliverLaneSeniorMessage(cliEntry, seniorLaneId, text),
24
24
  recoverQueuedMessages: async () => {
25
- const result = spawnSync(liveNodeBinary(), [cliEntry, "lanes", "_recover-queued-messages", laneId], {
25
+ const result = spawnSync(liveNodeBinary(), [cliEntry, "runners", "_recover-queued-messages", laneId], {
26
26
  env,
27
27
  encoding: "utf8",
28
28
  timeout: 120_000,
@@ -37,7 +37,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
37
37
  await new Promise((resolve, reject) => {
38
38
  const child = spawn(liveNodeBinary(), [
39
39
  cliEntry,
40
- "lanes",
40
+ "runners",
41
41
  "_keep-alive-terminal-trigger",
42
42
  scheduledLaneId,
43
43
  String(version),
@@ -55,7 +55,7 @@ export function watcherMainDeps(hqRoot, laneId, env = process.env, repairDispatc
55
55
  };
56
56
  }
57
57
  function deliverLaneSeniorMessage(cliEntry, laneId, text) {
58
- const result = spawnSync(liveNodeBinary(), [cliEntry, "lanes", "message", laneId, "--text", text], {
58
+ const result = spawnSync(liveNodeBinary(), [cliEntry, "runners", "message", laneId, "--text", text], {
59
59
  env: process.env,
60
60
  encoding: "utf8",
61
61
  timeout: 120_000,
@@ -106,7 +106,7 @@ export function formatCliMismatchLine(input) {
106
106
  const recordedAt = recordedEntry || "(none)";
107
107
  const currentAt = input.currentEntry || "(none)";
108
108
  return (`daemon hq ${recordedLabel} at ${recordedAt} does not match this CLI ` +
109
- `${input.currentVersion} at ${currentAt}. Run hq mesh daemon install to repoint it.`);
109
+ `${input.currentVersion} at ${currentAt}. Run hq daemon install to repoint it.`);
110
110
  }
111
111
  export function formatCliIdentityLines(report) {
112
112
  const lines = [];
@@ -350,7 +350,7 @@ export function repairMeshUnitFromOtherHome(opts = {}) {
350
350
  repaired: true,
351
351
  action: "removed",
352
352
  from: other.from,
353
- message: `${found} Stopped it. Start the real one with: hq mesh daemon install`,
353
+ message: `${found} Stopped it. Start the real one with: hq daemon install`,
354
354
  };
355
355
  }
356
356
  const env = opts.env ?? process.env;
@@ -374,7 +374,7 @@ export function repairMeshUnitFromOtherHome(opts = {}) {
374
374
  repaired: false,
375
375
  action: "removed",
376
376
  from: other.from,
377
- message: `${found} Stopped it, but starting the real one failed: ${error instanceof Error ? error.message : String(error)}. Run: hq mesh daemon install`,
377
+ message: `${found} Stopped it, but starting the real one failed: ${error instanceof Error ? error.message : String(error)}. Run: hq daemon install`,
378
378
  };
379
379
  }
380
380
  }
@@ -20,7 +20,7 @@ export function isInstallFollowupSkipped(argv, env) {
20
20
  const args = argv.slice(2).filter((arg) => arg !== "--verbose");
21
21
  if (args[0] === "mesh" && args[1] === "daemon")
22
22
  return true;
23
- if (args[0] === "daemon" && (args[1] === "run" || args[1] === "install"))
23
+ if (args[0] === "daemon" && (args[1] === "run" || args[1] === "install" || args[1] === "service"))
24
24
  return true;
25
25
  return false;
26
26
  }
@@ -157,6 +157,7 @@ export interface ClientHealthHeartbeat {
157
157
  daemonHqCloudUpdateOutcome?: ClientHealthDaemonHqCloudUpdateOutcome;
158
158
  daemonHqCloudUpdateTarget?: string;
159
159
  daemonHqCloudUpdateErrorClass?: ClientHealthDaemonHqCloudUpdateErrorClass;
160
+ daemonCliVersion?: string;
160
161
  /** Absent on older clients / non-sync-outcome events. See {@link ClientHealthLocalFilesOverview}. */
161
162
  localFilesOverview?: ClientHealthLocalFilesOverview;
162
163
  }
@@ -328,6 +328,11 @@ export function parseClientHealthHeartbeat(input) {
328
328
  heartbeat.daemonHqCloudUpdateTarget = target;
329
329
  }
330
330
  copyKnownOptionalEnum(heartbeat, "daemonHqCloudUpdateErrorClass", raw.daemonHqCloudUpdateErrorClass, CLIENT_HEALTH_DAEMON_HQ_CLOUD_UPDATE_ERROR_CLASSES);
331
+ if (raw.daemonCliVersion !== undefined) {
332
+ const daemonCliVersion = copyValidOptionalDiagnostic("daemonCliVersion", raw.daemonCliVersion, assertVersion);
333
+ if (daemonCliVersion !== undefined)
334
+ heartbeat.daemonCliVersion = daemonCliVersion;
335
+ }
331
336
  if (raw.localFilesOverview !== undefined) {
332
337
  heartbeat.localFilesOverview = parseClientHealthLocalFilesOverview("localFilesOverview", raw.localFilesOverview);
333
338
  }
@@ -179,6 +179,7 @@ export interface BuildCliHeartbeatInput {
179
179
  */
180
180
  localFilesOverview?: ClientHealthLocalFilesOverview | null;
181
181
  syncEngine?: CliSyncEngine | null;
182
+ daemonCliVersion?: string | null;
182
183
  }
183
184
  export interface CliSyncEngine {
184
185
  release: string;
@@ -212,6 +213,7 @@ export interface ClientHealthDeps {
212
213
  /** US-016: overridable for tests; defaults to {@link collectLocalFilesOverview}. */
213
214
  localFilesOverview?: () => ClientHealthLocalFilesOverview;
214
215
  syncEngine?: () => CliSyncEngine | null;
216
+ daemonCliVersion?: () => Promise<string | null>;
215
217
  /** Override for {@link JOURNAL_OBSERVATION_TTL_MS}. */
216
218
  journalObservationTtlMs?: number;
217
219
  /** Override for {@link JOURNAL_OBSERVATION_LOCK_STALE_MS}. */
@@ -40,6 +40,7 @@ import { getStateDir, listJournals } from "@indigoai-us/hq-cloud";
40
40
  import { isExpiring, isMachineIdentity, loadCachedTokens, } from "./cognito-session.js";
41
41
  import { vaultApiFetch } from "./vault-api.js";
42
42
  import { collectVersions } from "./feedback-versions.js";
43
+ import { resolveDaemonCliVersion } from "./daemon-cli-version.js";
43
44
  import { isAuthError } from "./auth-error.js";
44
45
  import { CLIENT_HEALTH_CONTRACT_VERSION, CLIENT_HEALTH_MAX_SYNC_ENGINE_VAULTS, parseClientHealthHeartbeat, } from "./client-health-contract.js";
45
46
  import { collectLocalFilesOverview } from "./local-files-overview.js";
@@ -508,6 +509,9 @@ export function buildCliHeartbeat(input) {
508
509
  if (SEMVER.test(engineVersion))
509
510
  versions.syncEngine = engineVersion;
510
511
  }
512
+ if (input.daemonCliVersion && SEMVER.test(input.daemonCliVersion)) {
513
+ heartbeat.daemonCliVersion = input.daemonCliVersion;
514
+ }
511
515
  return heartbeat;
512
516
  }
513
517
  const defaultPoster = (heartbeat, token, signal) => vaultApiFetch({
@@ -674,6 +678,16 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
674
678
  catch {
675
679
  syncEngine = null;
676
680
  }
681
+ // Bounded on its own budget so a slow parent-process lookup (up to 2 s on
682
+ // Windows) leaves the field off instead of using up the whole
683
+ // contribution bound and dropping the heartbeat.
684
+ let daemonCliVersion = null;
685
+ try {
686
+ daemonCliVersion = await valueWithin((deps.daemonCliVersion ?? processDaemonCliVersion)(), DAEMON_CLI_VERSION_BUDGET_MS);
687
+ }
688
+ catch {
689
+ daemonCliVersion = null;
690
+ }
677
691
  const heartbeat = buildCliHeartbeat({
678
692
  kind,
679
693
  state,
@@ -684,6 +698,7 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
684
698
  localFilesOverview,
685
699
  failureReason,
686
700
  syncEngine,
701
+ daemonCliVersion,
687
702
  });
688
703
  if (!heartbeat)
689
704
  return;
@@ -706,6 +721,31 @@ async function contributeClientHealthUnbounded(kind, deps, failureReason) {
706
721
  // Health contribution is best effort and must never affect a CLI command.
707
722
  }
708
723
  }
724
+ /**
725
+ * How long one heartbeat waits for the daemon CLI version. Well inside
726
+ * {@link CLIENT_HEALTH_TIMEOUT_MS}. The lookup is memoised per process, so a
727
+ * value that misses this budget is still used by later heartbeats.
728
+ */
729
+ const DAEMON_CLI_VERSION_BUDGET_MS = 300;
730
+ /** Resolve with `work`'s value, or null if it rejects or takes longer than `ms`. */
731
+ function valueWithin(work, ms) {
732
+ return new Promise((resolve) => {
733
+ const timer = setTimeout(() => resolve(null), ms);
734
+ timer.unref?.();
735
+ work.then((value) => {
736
+ clearTimeout(timer);
737
+ resolve(value);
738
+ }, () => {
739
+ clearTimeout(timer);
740
+ resolve(null);
741
+ });
742
+ });
743
+ }
744
+ let daemonCliVersionPromise;
745
+ function processDaemonCliVersion() {
746
+ daemonCliVersionPromise ??= resolveDaemonCliVersion().catch(() => null);
747
+ return daemonCliVersionPromise;
748
+ }
709
749
  // ─── Command wiring ──────────────────────────────────────────────────────────
710
750
  let invocationPromise;
711
751
  /**
@@ -20,6 +20,8 @@
20
20
  */
21
21
  import { isExpiring, isMachineIdentity, type CognitoAuthConfig, type CognitoTokens, type ClientInfo, type VaultServiceConfig } from "@indigoai-us/hq-cloud";
22
22
  import { hasPersonCachedSession, isMachineCredsFileEnvSet, wantsMachineCognitoTokens, type CognitoTokenSource } from "./machine-principal-state.js";
23
+ import { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir } from "./machine-token-cache.js";
24
+ export { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir };
23
25
  import { HQ_NO_BROWSER_LOGIN_ENV, type InteractiveCallerInput } from "./interactive-caller.js";
24
26
  import { loadCachedTokens, personTokenCacheFile, readPersonTokenFile } from "./person-token-cache.js";
25
27
  export { loadCachedTokens, personTokenCacheFile, readPersonTokenFile };
@@ -33,7 +35,6 @@ export type CognitoActorKind = "human" | "agent" | "unknown";
33
35
  * Default: the work-mesh daemon state dir (`~/.hq/work-mesh/daemon`), so a
34
36
  * machine mint never overwrites a person's `~/.hq/cognito-tokens.json`.
35
37
  */
36
- export declare const HQ_MACHINE_TOKEN_STATE_DIR_ENV = "HQ_MACHINE_TOKEN_STATE_DIR";
37
38
  export declare const DEFAULT_COGNITO: CognitoAuthConfig;
38
39
  export declare const DEFAULT_VAULT_API_URL: string;
39
40
  /**
@@ -93,14 +94,6 @@ export declare function resolveDefaultHqRoot(opts?: {
93
94
  platform?: NodeJS.Platform;
94
95
  }): string;
95
96
  export declare const DEFAULT_HQ_ROOT: string;
96
- /**
97
- * Directory used as `HQ_STATE_DIR` while minting/caching machine Cognito
98
- * tokens. Never the person's `~/.hq` — agent boxes write under the daemon
99
- * state dir so a mint cannot clobber a human login cache.
100
- */
101
- export declare function machineTokenStateDir(home?: string, env?: NodeJS.ProcessEnv): string;
102
- /** Absolute path of the machine-token cache file (daemon state dir). */
103
- export declare function machineTokenCacheFile(home?: string, env?: NodeJS.ProcessEnv): string;
104
97
  /** Default machine-creds path hq-cloud also checks when the env is unset. */
105
98
  export declare function defaultMachineCredsFile(home?: string): string;
106
99
  export type EnsureCognitoTokenOptions = {
@@ -181,11 +174,6 @@ export declare function refreshActivePersonTokens(cached: CognitoTokens, env?: N
181
174
  export declare function refreshActivePersonTokensForClientHealth(cached: CognitoTokens, signal: AbortSignal): Promise<CognitoTokens>;
182
175
  /** Derive actor kind from an ID token's custom:entity* claims (no verify). */
183
176
  export declare function actorKindFromIdToken(idToken: string | undefined): CognitoActorKind;
184
- /**
185
- * Peek the machine-token cache under the daemon state dir without minting.
186
- * Used by doctor; never logs token material.
187
- */
188
- export declare function loadMachineCachedTokens(home?: string, env?: NodeJS.ProcessEnv): CognitoTokens | null;
189
177
  /**
190
178
  * Report token source + actor kind for `hq mesh daemon doctor`. Does not mint
191
179
  * or hit the network. Machine identity without a readable cache still reports