@indigoai-us/hq-cli 5.345.231 → 5.345.233

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 (107) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +3 -2
  3. package/assets/lanes-reconcile/hq-lanes-reconcile.service +1 -1
  4. package/assets/scaffold/core/scripts/pipeline-conductor.sh +14 -14
  5. package/assets/scaffold/core/scripts/pipeline-driver.sh +7 -7
  6. package/assets/scaffold/core/scripts/session-project.sh +19 -4
  7. package/dist/command-catalog.generated.d.ts +213 -177
  8. package/dist/command-catalog.generated.js +263 -212
  9. package/dist/command-registration-plan.d.ts +6 -24
  10. package/dist/command-registration-plan.js +4 -8
  11. package/dist/commands/auth.js +3 -2
  12. package/dist/commands/core-handoff.d.ts +1 -0
  13. package/dist/commands/core-handoff.js +2 -28
  14. package/dist/commands/core-pipeline-conductor-command.js +1 -1
  15. package/dist/commands/core-pipeline-conductor-native.js +5 -5
  16. package/dist/commands/core-pipeline-driver-native.js +5 -5
  17. package/dist/commands/daemon.js +7 -36
  18. package/dist/commands/deploy-access.js +6 -13
  19. package/dist/commands/deploy-comments.js +5 -13
  20. package/dist/commands/deploy-domains.js +6 -13
  21. package/dist/commands/deploy-list.js +25 -11
  22. package/dist/commands/deploy-mutations.d.ts +3 -0
  23. package/dist/commands/deploy-mutations.js +147 -0
  24. package/dist/commands/link.js +29 -0
  25. package/dist/commands/mcp-serve-gate.d.ts +22 -0
  26. package/dist/commands/mcp-serve-gate.js +37 -0
  27. package/dist/commands/mcp-serve.js +2 -8
  28. package/dist/commands/mesh.js +3 -1
  29. package/dist/commands/report.js +8 -9
  30. package/dist/data/command-states.json +10 -7
  31. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +257 -214
  32. package/dist/hq-cloud-sync-runner/package.json +1 -1
  33. package/dist/index.js +6 -1
  34. package/dist/lib/bot/fleet-bots-update-pass.d.ts +8 -0
  35. package/dist/lib/bot/fleet-bots-update-pass.js +40 -0
  36. package/dist/lib/bot/fleet-bots-update-task.d.ts +12 -0
  37. package/dist/lib/bot/fleet-bots-update-task.js +52 -0
  38. package/dist/lib/bot/fleet-bots-update-worker-v1.d.ts +2 -0
  39. package/dist/lib/bot/fleet-bots-update-worker-v1.js +5 -0
  40. package/dist/lib/daemon/catalog.d.ts +8 -5
  41. package/dist/lib/daemon/catalog.js +15 -8
  42. package/dist/lib/daemon/flag.d.ts +2 -0
  43. package/dist/lib/daemon/flag.js +6 -4
  44. package/dist/lib/daemon/lock.js +33 -37
  45. package/dist/lib/daemon/ops/skill-command.d.ts +99 -0
  46. package/dist/lib/daemon/ops/skill-command.js +260 -0
  47. package/dist/lib/daemon/protocol.d.ts +1 -1
  48. package/dist/lib/daemon/protocol.js +1 -0
  49. package/dist/lib/daemon/run.js +10 -18
  50. package/dist/lib/daemon/server.js +7 -0
  51. package/dist/lib/daemon/shared-flag-reads.d.ts +70 -0
  52. package/dist/lib/daemon/shared-flag-reads.js +173 -0
  53. package/dist/lib/daemon/supervisor.d.ts +5 -0
  54. package/dist/lib/daemon/supervisor.js +17 -2
  55. package/dist/lib/db/app-ref.js +10 -15
  56. package/dist/lib/deploy-apps.d.ts +29 -0
  57. package/dist/lib/deploy-apps.js +37 -0
  58. package/dist/lib/doctor/checks/search-index.d.ts +16 -0
  59. package/dist/lib/doctor/checks/search-index.js +61 -0
  60. package/dist/lib/doctor/checks/stranded-lanes.js +1 -1
  61. package/dist/lib/doctor/registry.js +4 -0
  62. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  63. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  64. package/dist/lib/lanes/accounts.js +3 -3
  65. package/dist/lib/lanes/admission-host.js +1 -1
  66. package/dist/lib/lanes/admission.js +4 -4
  67. package/dist/lib/lanes/autopilot.js +2 -2
  68. package/dist/lib/lanes/blocker-freshness.js +1 -1
  69. package/dist/lib/lanes/compaction.js +5 -5
  70. package/dist/lib/lanes/delivery.js +1 -1
  71. package/dist/lib/lanes/depth-cap.js +1 -1
  72. package/dist/lib/lanes/disk-guard.js +1 -1
  73. package/dist/lib/lanes/dropbox.js +1 -1
  74. package/dist/lib/lanes/hooks-install.js +1 -1
  75. package/dist/lib/lanes/imported-question.js +1 -1
  76. package/dist/lib/lanes/keep-alive.d.ts +2 -2
  77. package/dist/lib/lanes/keep-alive.js +3 -3
  78. package/dist/lib/lanes/kr-freshness.js +1 -1
  79. package/dist/lib/lanes/links.js +4 -4
  80. package/dist/lib/lanes/loop.js +2 -2
  81. package/dist/lib/lanes/machine-identity.js +3 -3
  82. package/dist/lib/lanes/models.js +6 -6
  83. package/dist/lib/lanes/quota.js +1 -1
  84. package/dist/lib/lanes/reconcile-install.js +3 -3
  85. package/dist/lib/lanes/reconcile.js +16 -16
  86. package/dist/lib/lanes/remote-control-lane.js +6 -6
  87. package/dist/lib/lanes/reviews.js +2 -2
  88. package/dist/lib/lanes/spawn.js +24 -24
  89. package/dist/lib/lanes/status-fields.js +4 -4
  90. package/dist/lib/lanes/wait.js +4 -4
  91. package/dist/lib/lanes/watch.js +2 -2
  92. package/dist/lib/lanes/watcher-main.js +1 -1
  93. package/dist/lib/lanes/watcher.js +38 -38
  94. package/dist/lib/lanes/worker-process.js +5 -5
  95. package/dist/lib/mesh/live/daemon/pid-lock.d.ts +2 -4
  96. package/dist/lib/mesh/live/daemon/pid-lock.js +38 -55
  97. package/dist/utils/cognito-session.d.ts +2 -56
  98. package/dist/utils/cognito-session.js +6 -164
  99. package/dist/utils/exclusive-lock.d.ts +60 -0
  100. package/dist/utils/exclusive-lock.js +65 -0
  101. package/package.json +9 -8
  102. package/dist/commands/staff/listings.d.ts +0 -41
  103. package/dist/commands/staff/listings.js +0 -160
  104. package/dist/commands/staff/reset-test-account.d.ts +0 -121
  105. package/dist/commands/staff/reset-test-account.js +0 -285
  106. package/dist/commands/staff/test-account.d.ts +0 -51
  107. package/dist/commands/staff/test-account.js +0 -196
@@ -35,7 +35,7 @@ async function boundedUsage(sampler, endedAt, waitMs) {
35
35
  sampler.stop(endedAt),
36
36
  new Promise((resolve) => {
37
37
  timer = setTimeout(() => {
38
- process.stderr.write("hq lanes: worker resource use was not ready in time; the exit record has none\n");
38
+ process.stderr.write("hq runners: worker resource use was not ready in time; the exit record has none\n");
39
39
  resolve(null);
40
40
  }, waitMs);
41
41
  // Not unref'd: this timer is what keeps the wrapper alive until the
@@ -44,7 +44,7 @@ async function boundedUsage(sampler, endedAt, waitMs) {
44
44
  ]);
45
45
  }
46
46
  catch (error) {
47
- process.stderr.write(`hq lanes: could not measure worker resource use: ${error instanceof Error ? error.message : String(error)}\n`);
47
+ process.stderr.write(`hq runners: could not measure worker resource use: ${error instanceof Error ? error.message : String(error)}\n`);
48
48
  return null;
49
49
  }
50
50
  finally {
@@ -79,7 +79,7 @@ export function runLaneWorkerProcess(command, args, env = process.env, cwd = pro
79
79
  recordExit(exitPath, code, signal, endedAt, usage);
80
80
  }
81
81
  catch (error) {
82
- process.stderr.write(`hq lanes: could not persist worker exit status: ${error instanceof Error ? error.message : String(error)}\n`);
82
+ process.stderr.write(`hq runners: could not persist worker exit status: ${error instanceof Error ? error.message : String(error)}\n`);
83
83
  }
84
84
  }
85
85
  return exitCodeFor(code, signal);
@@ -110,7 +110,7 @@ export function runLaneWorkerProcess(command, args, env = process.env, cwd = pro
110
110
  });
111
111
  };
112
112
  child.once("error", (error) => {
113
- process.stderr.write(`hq lanes: worker process could not start: ${error.message}\n`);
113
+ process.stderr.write(`hq runners: worker process could not start: ${error.message}\n`);
114
114
  end(127, null);
115
115
  });
116
116
  child.once("exit", (code, signal) => end(code, signal));
@@ -119,7 +119,7 @@ export function runLaneWorkerProcess(command, args, env = process.env, cwd = pro
119
119
  if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
120
120
  const [command, ...args] = process.argv.slice(2);
121
121
  if (!command) {
122
- process.stderr.write("hq lanes: worker process command is missing\n");
122
+ process.stderr.write("hq runners: worker process command is missing\n");
123
123
  process.exitCode = 2;
124
124
  }
125
125
  else {
@@ -9,10 +9,8 @@
9
9
  * directory with a temp file inside (rmdir can never clear that class).
10
10
  */
11
11
  import * as fs from "node:fs";
12
- export interface PidLockRecord {
13
- pid: number;
14
- ts: number;
15
- }
12
+ import { type PidLockRecord } from "../../../../utils/exclusive-lock.js";
13
+ export type { PidLockRecord };
16
14
  export type PidLockResult = {
17
15
  ok: true;
18
16
  path: string;
@@ -9,6 +9,7 @@
9
9
  * directory with a temp file inside (rmdir can never clear that class).
10
10
  */
11
11
  import * as fs from "node:fs";
12
+ import { createLockFile, lockIsStale, parsePidLockRecord, readLockFile, releaseLockFile, } from "../../../../utils/exclusive-lock.js";
12
13
  import { daemonDir, daemonPidPath } from "./paths.js";
13
14
  function defaultAlive(pid) {
14
15
  try {
@@ -20,29 +21,10 @@ function defaultAlive(pid) {
20
21
  }
21
22
  }
22
23
  export function parsePidLock(content) {
23
- const fields = {};
24
- for (const line of content.split("\n")) {
25
- const i = line.indexOf("=");
26
- if (i === -1)
27
- continue;
28
- fields[line.slice(0, i)] = line.slice(i + 1);
29
- }
30
- if (!/^\d+$/.test(fields.pid ?? "") || !/^\d+$/.test(fields.ts ?? "")) {
31
- return null;
32
- }
33
- return { pid: Number(fields.pid), ts: Number(fields.ts) };
24
+ return parsePidLockRecord(content);
34
25
  }
35
26
  export function readPidLock(lockPath, deps = {}) {
36
- const existsSync = deps.existsSync ?? fs.existsSync;
37
- const readFileSync = deps.readFileSync ?? fs.readFileSync;
38
- if (!existsSync(lockPath))
39
- return null;
40
- try {
41
- return parsePidLock(readFileSync(lockPath, "utf8"));
42
- }
43
- catch {
44
- return null;
45
- }
27
+ return readLockFile(lockPath, parsePidLockRecord, deps);
46
28
  }
47
29
  export function pidLockStatus(lockPath, deps) {
48
30
  const record = readPidLock(lockPath, deps);
@@ -50,7 +32,11 @@ export function pidLockStatus(lockPath, deps) {
50
32
  return "free";
51
33
  return deps.isProcessAlive(record.pid) ? "held" : "stale";
52
34
  }
53
- /** Bounded stale-takeover retries (exclusive create after unlink). */
35
+ /**
36
+ * Bounded stale-takeover retries (exclusive create after unlink).
37
+ * Stale policy: pid only. A lock whose owner is unreadable or not alive is
38
+ * reclaimed at once; a live owner keeps it at any age.
39
+ */
54
40
  const STALE_TAKEOVER_ATTEMPTS = 3;
55
41
  /**
56
42
  * Acquire the single-file pid lock via exclusive create (`wx`).
@@ -67,9 +53,9 @@ export function acquirePidLock(dir, deps) {
67
53
  mkdirSync(dir, { recursive: true, mode: 0o700 });
68
54
  const lockPath = daemonPidPath(dir);
69
55
  const body = `pid=${deps.pid}\nts=${deps.now()}\n`;
56
+ const stale = { kind: "pid", alive: (pid) => deps.isProcessAlive(pid) };
70
57
  for (let attempt = 0; attempt < STALE_TAKEOVER_ATTEMPTS; attempt += 1) {
71
- try {
72
- writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
58
+ if (createLockFile(lockPath, body, writeFileSync)) {
73
59
  try {
74
60
  chmodSync(lockPath, 0o600);
75
61
  }
@@ -78,47 +64,44 @@ export function acquirePidLock(dir, deps) {
78
64
  }
79
65
  return { ok: true, path: lockPath };
80
66
  }
81
- catch (err) {
82
- const code = err?.code;
83
- if (code !== "EEXIST")
84
- throw err;
85
- const owner = readPidLock(lockPath, { readFileSync, existsSync });
86
- if (owner && deps.isProcessAlive(owner.pid)) {
87
- return { ok: false, reason: "held", owner, path: lockPath };
88
- }
89
- // Stale or unreadable: unlink and retry exclusive create.
90
- try {
91
- unlinkSync(lockPath);
92
- }
93
- catch (unlinkErr) {
94
- const ucode = unlinkErr?.code;
95
- if (ucode !== "ENOENT") {
96
- const raced = readPidLock(lockPath, { readFileSync, existsSync });
97
- if (raced && deps.isProcessAlive(raced.pid)) {
98
- return { ok: false, reason: "held", owner: raced, path: lockPath };
99
- }
100
- throw unlinkErr;
67
+ const owner = readPidLock(lockPath, { readFileSync, existsSync });
68
+ if (owner && !lockIsStale(stale, { owner })) {
69
+ return { ok: false, reason: "held", owner, path: lockPath };
70
+ }
71
+ // Stale or unreadable: unlink and retry exclusive create.
72
+ try {
73
+ unlinkSync(lockPath);
74
+ }
75
+ catch (unlinkErr) {
76
+ const ucode = unlinkErr?.code;
77
+ if (ucode !== "ENOENT") {
78
+ const raced = readPidLock(lockPath, { readFileSync, existsSync });
79
+ if (raced && !lockIsStale(stale, { owner: raced })) {
80
+ return { ok: false, reason: "held", owner: raced, path: lockPath };
101
81
  }
82
+ throw unlinkErr;
102
83
  }
103
84
  }
104
85
  }
105
86
  const finalOwner = readPidLock(lockPath, { readFileSync, existsSync });
106
- if (finalOwner && deps.isProcessAlive(finalOwner.pid)) {
87
+ if (finalOwner && !lockIsStale(stale, { owner: finalOwner })) {
107
88
  return { ok: false, reason: "held", owner: finalOwner, path: lockPath };
108
89
  }
109
90
  throw new Error(`pid lock acquire failed after ${STALE_TAKEOVER_ATTEMPTS} attempts`);
110
91
  }
111
92
  export function releasePidLock(dir, deps) {
112
- const lockPath = daemonPidPath(dir);
113
- const record = readPidLock(lockPath, deps);
114
- if (!record || record.pid !== deps.pid)
115
- return;
116
- try {
117
- (deps.unlinkSync ?? fs.unlinkSync)(lockPath);
118
- }
119
- catch {
120
- /* ignore */
121
- }
93
+ releaseLockFile(daemonPidPath(dir), {
94
+ read: (lockPath) => readPidLock(lockPath, deps),
95
+ owns: (record) => record.pid === deps.pid,
96
+ remove: (lockPath) => {
97
+ try {
98
+ (deps.unlinkSync ?? fs.unlinkSync)(lockPath);
99
+ }
100
+ catch {
101
+ /* ignore */
102
+ }
103
+ },
104
+ });
122
105
  }
123
106
  export function defaultPidLockDeps(overrides = {}) {
124
107
  return {
@@ -22,6 +22,7 @@ import { isExpiring, isMachineIdentity, type CognitoAuthConfig, type CognitoToke
22
22
  import { hasPersonCachedSession, isMachineCredsFileEnvSet, wantsMachineCognitoTokens, type CognitoTokenSource } from "./machine-principal-state.js";
23
23
  import { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir } from "./machine-token-cache.js";
24
24
  export { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir };
25
+ import { resolveDefaultHqRoot } from "./hq-root-resolver.js";
25
26
  import { HQ_NO_BROWSER_LOGIN_ENV, type InteractiveCallerInput } from "./interactive-caller.js";
26
27
  import { loadCachedTokens, personTokenCacheFile, readPersonTokenFile } from "./person-token-cache.js";
27
28
  export { loadCachedTokens, personTokenCacheFile, readPersonTokenFile };
@@ -37,62 +38,7 @@ export type CognitoActorKind = "human" | "agent" | "unknown";
37
38
  */
38
39
  export declare const DEFAULT_COGNITO: CognitoAuthConfig;
39
40
  export declare const DEFAULT_VAULT_API_URL: string;
40
- /**
41
- * Resolve the HQ tree root for cloud-aware subcommands (`hq sync`, `hq onboard`,
42
- * `hq cloud …`, etc.).
43
- *
44
- * Resolution order — mirrors the menubar/installer resolver
45
- * (`hq-sync` `util/paths.rs::resolve_hq_folder`) so the CLI targets the SAME
46
- * root the AppBar syncs, regardless of cwd:
47
- * 1. `$HQ_ROOT` env var — explicit assertion by the caller; short-circuits all.
48
- * 2. Walk up from `process.cwd()` to the nearest HQ root (working-tree wins:
49
- * if you're inside an HQ tree, operate on THAT tree). See {@link isHqRoot}.
50
- * 3. `~/.hq/menubar.json` → `hqPath` — the canonical record written by the
51
- * installer (≥0.1.28) and the menubar's Settings re-tether. Same field HQ
52
- * Sync reads first.
53
- * 4. `~/.hq/config.json` → `hqFolderPath` — legacy installer record.
54
- * 5. Discovery: scan well-known locations (`~/HQ`, `~/hq`, `~/Documents/HQ`,
55
- * …) for a folder carrying a valid `core.yaml` signature. Safety net for
56
- * installs that never wrote the path back to menubar.json.
57
- * 6. Fall back to `~/hq` (`C:\hq` on Windows) — or throw, per
58
- * `opts.onMissing`.
59
- *
60
- * Why tiers 3–5 exist:
61
- * Before this, the CLI only knew `$HQ_ROOT` and the cwd walk-up. Run from any
62
- * cwd OUTSIDE the HQ tree with `$HQ_ROOT` unset, it fell straight to `~/hq` —
63
- * so a user whose HQ lives anywhere else (e.g. `~/Desktop/HQ`, as the AppBar
64
- * syncs it) silently got a brand-new `~/hq` stub and a full re-sync into it
65
- * (split-brain). Reading the installer/menubar records the way HQ Sync does
66
- * closes that gap (feedback_3967e294).
67
- *
68
- * Why both markers in the walk-up (tier 2)?
69
- * An HQ root has a `core.yaml` (canonical `core/core.yaml` since hq-core v14,
70
- * legacy `<root>/core.yaml` before) AND a sibling `companies/` directory. The
71
- * synced `core/` subtree ALSO contains a `core.yaml` (the template version
72
- * source-of-truth) but NO `companies/`. Requiring `companies/` as well stops
73
- * the walk from latching onto `<hqRoot>/core/` (Codex P2 on hq#146).
74
- *
75
- * `opts.onMissing` controls the final arm:
76
- * - `'fallback'` (default) — return `~/hq` (`C:\hq` on Windows) if nothing resolves. Preserves the
77
- * module-load contract of `DEFAULT_HQ_ROOT`, pinned by commander.js
78
- * `.option()` callers at registration time.
79
- * - `'throw'` — throw a user-actionable error. Used by module-management
80
- * commands (pkg-*, team-sync) where a silent default-path miss would
81
- * target the wrong directory.
82
- *
83
- * Evaluated once at module load for `DEFAULT_HQ_ROOT`; the installer/menubar
84
- * records and cwd are both fixed at process start, so a one-shot read is sound.
85
- * Re-importable as a function for command-time resolution and tests.
86
- */
87
- export declare function resolveDefaultHqRoot(opts?: {
88
- onMissing?: "throw" | "fallback";
89
- /** Defaults to process.env, process.cwd() and os.homedir(). */
90
- env?: NodeJS.ProcessEnv;
91
- cwd?: string;
92
- home?: string;
93
- /** Defaults to process.platform; injectable so tests can exercise win32. */
94
- platform?: NodeJS.Platform;
95
- }): string;
41
+ export { resolveDefaultHqRoot };
96
42
  export declare const DEFAULT_HQ_ROOT: string;
97
43
  /** Default machine-creds path hq-cloud also checks when the env is unset. */
98
44
  export declare function defaultMachineCredsFile(home?: string): string;
@@ -23,14 +23,13 @@ import { randomBytes } from "node:crypto";
23
23
  import * as fs from "fs";
24
24
  import * as os from "os";
25
25
  import * as path from "path";
26
- import * as yaml from "js-yaml";
27
26
  import chalk from "chalk";
28
27
  import { isExpiring, refreshTokens, saveCachedTokens, browserLogin, detectHqCoreVersion, isMachineIdentity, getValidMachineTokens, CognitoRefreshError, accessTokenFingerprint, invalidateCachedTokensByFingerprint, } from "@indigoai-us/hq-cloud";
29
28
  import { hasPersonCachedSession, isMachineCredsFileEnvSet, probeMachineIdentity, wantsMachineCognitoTokens, } from "./machine-principal-state.js";
30
29
  import { CLI_NAME, CLI_VERSION } from "../cli-version.js";
31
30
  import { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir, } from "./machine-token-cache.js";
32
31
  export { HQ_MACHINE_TOKEN_STATE_DIR_ENV, loadMachineCachedTokens, machineTokenCacheFile, machineTokenStateDir };
33
- import { defaultHqRootFallback, hqDiscoveryCandidates, pathForPlatform, } from "./hq-root-resolver.js";
32
+ import { resolveDefaultHqRoot } from "./hq-root-resolver.js";
34
33
  import { acquireLockFileExclusively } from "./exclusive-lock.js";
35
34
  import { interactiveLoginConfig, resolveCognitoCallbackPort } from "./cognito-callback-port.js";
36
35
  import { HQ_NO_BROWSER_LOGIN_ENV, NON_INTERACTIVE_LOGIN_MESSAGE, isInteractiveCaller, } from "./interactive-caller.js";
@@ -66,168 +65,11 @@ export const DEFAULT_COGNITO = {
66
65
  : "Google",
67
66
  };
68
67
  export const DEFAULT_VAULT_API_URL = process.env.HQ_VAULT_API_URL ?? "https://hqapi.hq.computer";
69
- /**
70
- * Resolve the HQ tree root for cloud-aware subcommands (`hq sync`, `hq onboard`,
71
- * `hq cloud …`, etc.).
72
- *
73
- * Resolution order — mirrors the menubar/installer resolver
74
- * (`hq-sync` `util/paths.rs::resolve_hq_folder`) so the CLI targets the SAME
75
- * root the AppBar syncs, regardless of cwd:
76
- * 1. `$HQ_ROOT` env var — explicit assertion by the caller; short-circuits all.
77
- * 2. Walk up from `process.cwd()` to the nearest HQ root (working-tree wins:
78
- * if you're inside an HQ tree, operate on THAT tree). See {@link isHqRoot}.
79
- * 3. `~/.hq/menubar.json` → `hqPath` — the canonical record written by the
80
- * installer (≥0.1.28) and the menubar's Settings re-tether. Same field HQ
81
- * Sync reads first.
82
- * 4. `~/.hq/config.json` → `hqFolderPath` — legacy installer record.
83
- * 5. Discovery: scan well-known locations (`~/HQ`, `~/hq`, `~/Documents/HQ`,
84
- * …) for a folder carrying a valid `core.yaml` signature. Safety net for
85
- * installs that never wrote the path back to menubar.json.
86
- * 6. Fall back to `~/hq` (`C:\hq` on Windows) — or throw, per
87
- * `opts.onMissing`.
88
- *
89
- * Why tiers 3–5 exist:
90
- * Before this, the CLI only knew `$HQ_ROOT` and the cwd walk-up. Run from any
91
- * cwd OUTSIDE the HQ tree with `$HQ_ROOT` unset, it fell straight to `~/hq` —
92
- * so a user whose HQ lives anywhere else (e.g. `~/Desktop/HQ`, as the AppBar
93
- * syncs it) silently got a brand-new `~/hq` stub and a full re-sync into it
94
- * (split-brain). Reading the installer/menubar records the way HQ Sync does
95
- * closes that gap (feedback_3967e294).
96
- *
97
- * Why both markers in the walk-up (tier 2)?
98
- * An HQ root has a `core.yaml` (canonical `core/core.yaml` since hq-core v14,
99
- * legacy `<root>/core.yaml` before) AND a sibling `companies/` directory. The
100
- * synced `core/` subtree ALSO contains a `core.yaml` (the template version
101
- * source-of-truth) but NO `companies/`. Requiring `companies/` as well stops
102
- * the walk from latching onto `<hqRoot>/core/` (Codex P2 on hq#146).
103
- *
104
- * `opts.onMissing` controls the final arm:
105
- * - `'fallback'` (default) — return `~/hq` (`C:\hq` on Windows) if nothing resolves. Preserves the
106
- * module-load contract of `DEFAULT_HQ_ROOT`, pinned by commander.js
107
- * `.option()` callers at registration time.
108
- * - `'throw'` — throw a user-actionable error. Used by module-management
109
- * commands (pkg-*, team-sync) where a silent default-path miss would
110
- * target the wrong directory.
111
- *
112
- * Evaluated once at module load for `DEFAULT_HQ_ROOT`; the installer/menubar
113
- * records and cwd are both fixed at process start, so a one-shot read is sound.
114
- * Re-importable as a function for command-time resolution and tests.
115
- */
116
- export function resolveDefaultHqRoot(opts = {}) {
117
- const env = opts.env ?? process.env;
118
- const home = opts.home ?? os.homedir();
119
- const platform = opts.platform ?? process.platform;
120
- const p = pathForPlatform(platform);
121
- // Tier 1: explicit override.
122
- if (env.HQ_ROOT)
123
- return p.resolve(env.HQ_ROOT);
124
- // Tier 2: working-tree walk-up — operate on the HQ tree you're inside.
125
- let cur = p.resolve(opts.cwd ?? process.cwd());
126
- while (cur !== p.dirname(cur)) {
127
- if (isHqRoot(cur, p))
128
- return cur;
129
- cur = p.dirname(cur);
130
- }
131
- // Tiers 3–4: the installer/menubar's canonical "where is HQ" records.
132
- const fromConfig = readHqRootFromHqConfig(p.join(home, ".hq"), p);
133
- if (fromConfig)
134
- return p.resolve(fromConfig);
135
- // Tier 5: discover a valid HQ root in the well-known locations (on Windows
136
- // the home-relative ones first, then %SystemDrive%\hq and %LOCALAPPDATA%\hq).
137
- const discovered = hqDiscoveryCandidates({ platform, env, home }).find((dir) => isValidHqRootSignature(dir, p));
138
- if (discovered)
139
- return discovered;
140
- // Tier 6: nothing resolved. Fallback is ~/hq, or %SystemDrive%\hq on Windows.
141
- if (opts.onMissing === "throw") {
142
- throw new Error("Could not find HQ root. Run this command from within your HQ directory " +
143
- "(must contain core.yaml AND a companies/ subdirectory), set $HQ_ROOT, " +
144
- "or install HQ via the installer/menubar so ~/.hq/menubar.json records " +
145
- "its location.");
146
- }
147
- return defaultHqRootFallback({ platform, env, home });
148
- }
149
- /**
150
- * Read the configured HQ root from the installer/menubar records under
151
- * `hqConfigDir` (`~/.hq`). Mirrors HQ Sync's precedence:
152
- * 1. `menubar.json` → `hqPath` (canonical; written by installer ≥0.1.28 and
153
- * the menubar Settings re-tether)
154
- * 2. `config.json` → `hqFolderPath` (legacy installer flows)
155
- * Returns the first non-empty string, or undefined. Best-effort: a missing or
156
- * malformed file is treated as "not configured" (never throws).
157
- */
158
- function readHqRootFromHqConfig(hqConfigDir, p = path) {
159
- const fromMenubar = readJsonStringField(p.join(hqConfigDir, "menubar.json"), "hqPath");
160
- if (fromMenubar)
161
- return fromMenubar;
162
- return readJsonStringField(p.join(hqConfigDir, "config.json"), "hqFolderPath");
163
- }
164
- /** Read a top-level string field from a JSON file, or undefined on any miss. */
165
- function readJsonStringField(file, field) {
166
- try {
167
- const parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
168
- const value = parsed[field];
169
- return typeof value === "string" && value.length > 0 ? value : undefined;
170
- }
171
- catch {
172
- return undefined;
173
- }
174
- }
175
- /**
176
- * True iff `dir` carries a valid hq-core `core.yaml` — canonical
177
- * (`<dir>/core/core.yaml`, hq-core ≥v14) or legacy (`<dir>/core.yaml`) — that
178
- * parses as YAML and has BOTH the `version` and `hqVersion` fields. The dual
179
- * field check (matching hq-sync's `is_valid_hq_root`) stops a stray `core.yaml`
180
- * from another tool from false-matching.
181
- */
182
- function isValidHqRootSignature(dir, p = path) {
183
- const canonical = p.join(dir, "core", "core.yaml");
184
- const legacy = p.join(dir, "core.yaml");
185
- let file;
186
- if (fileExists(canonical))
187
- file = canonical;
188
- else if (fileExists(legacy))
189
- file = legacy;
190
- else
191
- return false;
192
- try {
193
- const parsed = yaml.load(fs.readFileSync(file, "utf-8"));
194
- return (!!parsed &&
195
- typeof parsed === "object" &&
196
- "version" in parsed &&
197
- "hqVersion" in parsed);
198
- }
199
- catch {
200
- return false;
201
- }
202
- }
203
- /** True iff `p` exists and is a regular file. */
204
- function fileExists(p) {
205
- try {
206
- return fs.statSync(p).isFile();
207
- }
208
- catch {
209
- return false;
210
- }
211
- }
212
- /**
213
- * True iff `dir` is an HQ root for the cwd walk-up: it has a `core.yaml`
214
- * (canonical `core/core.yaml` since hq-core v14, or legacy `<dir>/core.yaml`)
215
- * AND a sibling `companies/` directory. The `companies/` discriminator keeps
216
- * the walk from latching onto the inner `core/` subtree, which carries its own
217
- * `core.yaml` but no `companies/`.
218
- */
219
- function isHqRoot(dir, p = path) {
220
- const hasCoreYaml = fileExists(p.join(dir, "core", "core.yaml")) ||
221
- fileExists(p.join(dir, "core.yaml"));
222
- if (!hasCoreYaml)
223
- return false;
224
- try {
225
- return fs.statSync(p.join(dir, "companies")).isDirectory();
226
- }
227
- catch {
228
- return false;
229
- }
230
- }
68
+ // HQ-root resolution (HQ_ROOT, cwd walk with the core.yaml + companies/
69
+ // check, installer records, known locations, then ~/hq or a throw) has one
70
+ // implementation, in hq-root-resolver.ts (US-030 c2). Re-exported here for
71
+ // the callers that import it from this module.
72
+ export { resolveDefaultHqRoot };
231
73
  export const DEFAULT_HQ_ROOT = resolveDefaultHqRoot();
232
74
  /** Default machine-creds path hq-cloud also checks when the env is unset. */
233
75
  export function defaultMachineCredsFile(home = os.homedir()) {
@@ -19,6 +19,7 @@
19
19
  * Both paths fail with EEXIST when the lock is held, so contention, stale-
20
20
  * owner reclamation and release are unchanged for every caller.
21
21
  */
22
+ import * as fs from "fs";
22
23
  /** Test seam: forget what we learned about which filesystems do links. */
23
24
  export declare function resetLinkSupportCache(): void;
24
25
  /**
@@ -29,4 +30,63 @@ export declare function resetLinkSupportCache(): void;
29
30
  * are written directly. Either way the lock ends up holding the same bytes.
30
31
  */
31
32
  export declare function acquireLockFileExclusively(candidate: string, lockFile: string, dirKey: string): void;
33
+ /** A `pid=<n>\nts=<unix seconds>` lock file (the daemon and mesh daemon pid locks). */
34
+ export interface PidLockRecord {
35
+ pid: number;
36
+ ts: number;
37
+ }
38
+ /** Parse a `pid=<n>\nts=<n>` body; null unless both fields are plain digits. */
39
+ export declare function parsePidLockRecord(content: string): PidLockRecord | null;
40
+ export interface LockFileReadDeps {
41
+ existsSync?: typeof fs.existsSync;
42
+ readFileSync?: typeof fs.readFileSync;
43
+ }
44
+ /** Read and parse a lock file. A missing file, a read error or a parse error is null. */
45
+ export declare function readLockFile<T>(lockPath: string, parse: (content: string) => T | null, deps?: LockFileReadDeps): T | null;
46
+ /**
47
+ * Create `lockPath` with `body` exclusively (`wx`, mode 0600). True when this
48
+ * call created it, false when it already exists (EEXIST); any other error is
49
+ * thrown.
50
+ */
51
+ export declare function createLockFile(lockPath: string, body: string, writeFileSync?: typeof fs.writeFileSync): boolean;
52
+ /**
53
+ * When a held lock may be reclaimed. Each caller passes the rule it has
54
+ * always used; the module does not choose one.
55
+ *
56
+ * - `pid`: stale unless the recorded owner is readable, is not `self` (when
57
+ * given) and `alive(owner.pid)` is true. No age limit: a live owner keeps
58
+ * the lock however old it is. `alive` is not called for `self`.
59
+ * - `age`: stale unless the lock's age is at most `maxAgeMs` (an age that
60
+ * is not a number is stale).
61
+ * - `none`: never stale.
62
+ */
63
+ export type StalePolicy = {
64
+ kind: "pid";
65
+ alive: (pid: number) => boolean;
66
+ self?: number;
67
+ } | {
68
+ kind: "age";
69
+ maxAgeMs: number;
70
+ } | {
71
+ kind: "none";
72
+ };
73
+ /** What the caller observed about the held lock: its owner (pid policy) or its age (age policy). */
74
+ export type LockObservation = {
75
+ owner: {
76
+ pid: number;
77
+ } | null;
78
+ } | {
79
+ ageMs: number;
80
+ };
81
+ export declare function lockIsStale(policy: StalePolicy, observed: LockObservation): boolean;
82
+ export interface LockFileRelease<T> {
83
+ /** Read the current owner; null when there is none or it is unreadable. */
84
+ read: (lockPath: string) => T | null;
85
+ /** The owner is this holder. */
86
+ owns: (owner: T) => boolean;
87
+ /** Remove the lock file (the caller's own error handling). */
88
+ remove: (lockPath: string) => void;
89
+ }
90
+ /** Remove the lock only when this holder owns it. True when `remove` ran. */
91
+ export declare function releaseLockFile<T>(lockPath: string, release: LockFileRelease<T>): boolean;
32
92
  //# sourceMappingURL=exclusive-lock.d.ts.map
@@ -72,4 +72,69 @@ export function acquireLockFileExclusively(candidate, lockFile, dirKey) {
72
72
  mode: 0o600,
73
73
  });
74
74
  }
75
+ /** Parse a `pid=<n>\nts=<n>` body; null unless both fields are plain digits. */
76
+ export function parsePidLockRecord(content) {
77
+ const fields = {};
78
+ for (const line of content.split("\n")) {
79
+ const i = line.indexOf("=");
80
+ if (i === -1)
81
+ continue;
82
+ fields[line.slice(0, i)] = line.slice(i + 1);
83
+ }
84
+ if (!/^\d+$/.test(fields.pid ?? "") || !/^\d+$/.test(fields.ts ?? "")) {
85
+ return null;
86
+ }
87
+ return { pid: Number(fields.pid), ts: Number(fields.ts) };
88
+ }
89
+ /** Read and parse a lock file. A missing file, a read error or a parse error is null. */
90
+ export function readLockFile(lockPath, parse, deps = {}) {
91
+ const existsSync = deps.existsSync ?? fs.existsSync;
92
+ const readFileSync = deps.readFileSync ?? fs.readFileSync;
93
+ if (!existsSync(lockPath))
94
+ return null;
95
+ try {
96
+ return parse(readFileSync(lockPath, "utf8"));
97
+ }
98
+ catch {
99
+ return null;
100
+ }
101
+ }
102
+ /**
103
+ * Create `lockPath` with `body` exclusively (`wx`, mode 0600). True when this
104
+ * call created it, false when it already exists (EEXIST); any other error is
105
+ * thrown.
106
+ */
107
+ export function createLockFile(lockPath, body, writeFileSync = fs.writeFileSync) {
108
+ try {
109
+ writeFileSync(lockPath, body, { flag: "wx", mode: 0o600 });
110
+ return true;
111
+ }
112
+ catch (error) {
113
+ if (error?.code === "EEXIST")
114
+ return false;
115
+ throw error;
116
+ }
117
+ }
118
+ export function lockIsStale(policy, observed) {
119
+ switch (policy.kind) {
120
+ case "none":
121
+ return false;
122
+ case "pid": {
123
+ const owner = "owner" in observed ? observed.owner : null;
124
+ return !(owner && owner.pid !== policy.self && policy.alive(owner.pid));
125
+ }
126
+ case "age": {
127
+ const ageMs = "ageMs" in observed ? observed.ageMs : Number.NaN;
128
+ return !(ageMs <= policy.maxAgeMs);
129
+ }
130
+ }
131
+ }
132
+ /** Remove the lock only when this holder owns it. True when `remove` ran. */
133
+ export function releaseLockFile(lockPath, release) {
134
+ const owner = release.read(lockPath);
135
+ if (owner === null || !release.owns(owner))
136
+ return false;
137
+ release.remove(lockPath);
138
+ return true;
139
+ }
75
140
  //# sourceMappingURL=exclusive-lock.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indigoai-us/hq-cli",
3
- "version": "5.345.231",
3
+ "version": "5.345.233",
4
4
  "description": "HQ by Indigo management CLI — modules and cloud sync",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -14,6 +14,7 @@
14
14
  "!dist/**/__testing__",
15
15
  "!dist/**/*.test-d.*",
16
16
  "!dist/lib/test-utils",
17
+ "!dist/staff",
17
18
  "!dist/lib/decisions/fixtures",
18
19
  "!dist/lib/fingerprint/fixtures.*",
19
20
  "assets/scaffold",
@@ -62,7 +63,7 @@
62
63
  "@aws-sdk/client-iot-data-plane": "^3.1096.0",
63
64
  "@aws-sdk/client-s3": "^3.1049.0",
64
65
  "@aws-sdk/dsql-signer": "^3.1146.0",
65
- "@indigoai-us/hq-cloud": "6.18.112",
66
+ "@indigoai-us/hq-cloud": "6.18.114",
66
67
  "@indigoai-us/hq-flags-client": "^0.2.0",
67
68
  "@modelcontextprotocol/sdk": "1.32.2",
68
69
  "@sentry/node": "^10.49.0",
@@ -125,11 +126,11 @@
125
126
  "*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}": "eslint --cache --no-error-on-unmatched-pattern"
126
127
  },
127
128
  "optionalDependencies": {
128
- "@indigoai-us/hq-hook-win32-x64": "5.345.231",
129
- "@indigoai-us/hq-hook-win32-arm64": "5.345.231",
130
- "@indigoai-us/hq-hook-darwin-x64": "5.345.231",
131
- "@indigoai-us/hq-hook-darwin-arm64": "5.345.231",
132
- "@indigoai-us/hq-hook-linux-x64": "5.345.231",
133
- "@indigoai-us/hq-hook-linux-arm64": "5.345.231"
129
+ "@indigoai-us/hq-hook-win32-x64": "5.345.233",
130
+ "@indigoai-us/hq-hook-win32-arm64": "5.345.233",
131
+ "@indigoai-us/hq-hook-darwin-x64": "5.345.233",
132
+ "@indigoai-us/hq-hook-darwin-arm64": "5.345.233",
133
+ "@indigoai-us/hq-hook-linux-x64": "5.345.233",
134
+ "@indigoai-us/hq-hook-linux-arm64": "5.345.233"
134
135
  }
135
136
  }