@indigoai-us/hq-cli 5.345.226 → 5.345.230

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 (138) hide show
  1. package/CHANGELOG.md +156 -0
  2. package/dist/command-catalog.generated.d.ts +376 -11
  3. package/dist/command-catalog.generated.js +451 -11
  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 +2 -2
  18. package/dist/commands/index-cmd.d.ts +3 -1
  19. package/dist/commands/index-cmd.js +12 -0
  20. package/dist/commands/lanes-checks.js +1 -1
  21. package/dist/commands/lanes-session-start.d.ts +1 -2
  22. package/dist/commands/lanes-session-start.js +9 -145
  23. package/dist/commands/lanes-shared.d.ts +3 -0
  24. package/dist/commands/lanes.d.ts +3 -0
  25. package/dist/commands/lanes.js +94 -27
  26. package/dist/commands/link.d.ts +8 -3
  27. package/dist/commands/link.js +14 -17
  28. package/dist/commands/mcp-registration.d.ts +65 -7
  29. package/dist/commands/mcp-registration.js +289 -51
  30. package/dist/commands/mesh.d.ts +12 -0
  31. package/dist/commands/mesh.js +92 -10
  32. package/dist/commands/reindex.js +6 -0
  33. package/dist/commands/repo.d.ts +13 -0
  34. package/dist/commands/repo.js +39 -1
  35. package/dist/commands/sync-mode.d.ts +3 -1
  36. package/dist/commands/sync-mode.js +11 -1
  37. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +1473 -1043
  38. package/dist/hq-cloud-sync-runner/package.json +1 -1
  39. package/dist/lazy-commands.js +3 -4
  40. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  41. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  42. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  43. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  44. package/dist/lib/core-utils/session-company.d.ts +13 -1
  45. package/dist/lib/core-utils/session-company.js +75 -4
  46. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  47. package/dist/lib/core-utils/worktree-resume.js +8 -4
  48. package/dist/lib/daemon/background-qos.d.ts +7 -0
  49. package/dist/lib/daemon/background-qos.js +13 -0
  50. package/dist/lib/daemon/catalog.d.ts +9 -0
  51. package/dist/lib/daemon/catalog.js +8 -1
  52. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  53. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  54. package/dist/lib/daemon/hook-requests-conduct-link.d.ts +20 -0
  55. package/dist/lib/daemon/hook-requests-conduct-link.js +105 -0
  56. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  57. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  58. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  59. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  60. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  61. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  62. package/dist/lib/daemon/hook-requests.d.ts +354 -8
  63. package/dist/lib/daemon/hook-requests.js +1330 -46
  64. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  65. package/dist/lib/daemon/machine-checks.js +27 -10
  66. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  67. package/dist/lib/daemon/merge-sections.js +58 -16
  68. package/dist/lib/daemon/ops/policy.js +4 -2
  69. package/dist/lib/daemon/resolver.js +9 -2
  70. package/dist/lib/daemon/run.d.ts +11 -7
  71. package/dist/lib/daemon/run.js +168 -24
  72. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  73. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  74. package/dist/lib/daemon/session-registry.d.ts +0 -1
  75. package/dist/lib/daemon/session-registry.js +0 -3
  76. package/dist/lib/daemon/supervisor.d.ts +3 -1
  77. package/dist/lib/daemon/supervisor.js +1 -1
  78. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  79. package/dist/lib/daemon/tcc-eperm.js +110 -8
  80. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  81. package/dist/lib/doctor/fix/process-identity.js +48 -5
  82. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  83. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  84. package/dist/lib/hook-engine/canary-gate.js +1 -0
  85. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  86. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  87. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  88. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  89. package/dist/lib/lanes/company-outposts.js +164 -0
  90. package/dist/lib/lanes/liveness.d.ts +6 -0
  91. package/dist/lib/lanes/liveness.js +49 -8
  92. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  93. package/dist/lib/lanes/orphan-report.js +223 -0
  94. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  95. package/dist/lib/lanes/orphan-sweep.js +152 -0
  96. package/dist/lib/lanes/reaper.d.ts +2 -0
  97. package/dist/lib/lanes/reaper.js +11 -8
  98. package/dist/lib/lanes/reconcile.d.ts +8 -7
  99. package/dist/lib/lanes/reconcile.js +39 -0
  100. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  101. package/dist/lib/mesh/live/backfill-held.js +23 -0
  102. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  103. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  104. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  105. package/dist/lib/mesh/live/daemon/run.js +116 -7
  106. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  107. package/dist/lib/mesh/live/direct-drain.js +315 -0
  108. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  109. package/dist/lib/mesh/live/emit-replay.js +10 -0
  110. package/dist/lib/mesh/live/flush.d.ts +15 -0
  111. package/dist/lib/mesh/live/flush.js +27 -0
  112. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  113. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  114. package/dist/lib/mesh/live/spool.d.ts +19 -0
  115. package/dist/lib/mesh/live/spool.js +80 -0
  116. package/dist/lib/safe-store.d.ts +2 -0
  117. package/dist/lib/safe-store.js +8 -6
  118. package/dist/lib/search-index/index.d.ts +9 -3
  119. package/dist/lib/search-index/index.js +35 -10
  120. package/dist/lib/search-index/worker-process.d.ts +9 -0
  121. package/dist/lib/search-index/worker-process.js +171 -0
  122. package/dist/lib/session-company-lock.d.ts +3 -1
  123. package/dist/lib/session-company-lock.js +3 -2
  124. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  125. package/dist/utils/delegate-command-supervisor.js +44 -0
  126. package/dist/utils/delegate-lock.d.ts +12 -0
  127. package/dist/utils/delegate-lock.js +88 -0
  128. package/dist/utils/frontmatter.d.ts +27 -0
  129. package/dist/utils/frontmatter.js +33 -0
  130. package/dist/utils/hook-trust.d.ts +1 -0
  131. package/dist/utils/hook-trust.js +18 -2
  132. package/dist/utils/host-registration.d.ts +13 -1
  133. package/dist/utils/host-registration.js +98 -5
  134. package/dist/utils/package-use-lease.d.ts +1 -1
  135. package/dist/utils/package-use-lease.js +15 -7
  136. package/docs/anywhere-runtime.md +17 -0
  137. package/package.json +9 -8
  138. package/scripts/check-function-manifest.mjs +17 -3
@@ -1,14 +1,14 @@
1
1
  import fs from "node:fs";
2
+ import { readOrphanReportCount } from "../lib/lanes/orphan-report.js";
2
3
  import { spawn, spawnSync } from "node:child_process";
3
- import os from "node:os";
4
4
  import path from "node:path";
5
- import { createHash, randomUUID } from "node:crypto";
5
+ import { randomUUID } from "node:crypto";
6
+ import { validSessionId } from "../lib/core-utils/session-id.js";
6
7
  import { resolveLanesHqRoot } from "../lib/lanes/hq-root.js";
7
8
  import { readLanesRegistryFlagOffline, readLanesRegistryFlagResult } from "../lib/lanes/registry-flag.js";
8
- import { LANE_CONDUCT_SESSION_START_FLAG, LANE_ORPHAN_SWEEP_CONTEXT_FLAG, LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG } from "../lib/lanes/flag-keys.js";
9
+ import { LANE_CONDUCT_SESSION_START_FLAG, LANE_ORPHAN_SWEEP_CONTEXT_FLAG } from "../lib/lanes/flag-keys.js";
9
10
  const SESSION_START_FLAGS = [
10
11
  LANE_CONDUCT_SESSION_START_FLAG,
11
- LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG,
12
12
  LANE_ORPHAN_SWEEP_CONTEXT_FLAG,
13
13
  ];
14
14
  /** Offline flag values older than this trigger one background registry read. */
@@ -228,7 +228,7 @@ function conductorCorePath(root, runner) {
228
228
  }
229
229
  function validPayloadSessionId(payload) {
230
230
  const sessionId = payload.session_id ?? payload.sessionId;
231
- if (!sessionId || !/^[A-Za-z0-9._-]+$/.test(sessionId) || sessionId === "." || sessionId === "..")
231
+ if (!sessionId || !validSessionId(sessionId))
232
232
  return null;
233
233
  return sessionId;
234
234
  }
@@ -386,139 +386,6 @@ function extractConductorBlock(core) {
386
386
  return null;
387
387
  return core.slice(start + "<!-- inject:start -->".length, end).replace(/^\r?\n/, "").replace(/\r?\n$/, "");
388
388
  }
389
- const ORPHAN_SWEEP_LOCK_TTL_MS = 15 * 60_000;
390
- function rootKeyFor(root) {
391
- let resolved = path.resolve(root);
392
- try {
393
- resolved = fs.realpathSync(root);
394
- }
395
- catch { /* the canonicalized path remains the fallback */ }
396
- return createHash("sha256").update(resolved).digest("hex").slice(0, 12);
397
- }
398
- function readOrphanCount(root, env, rootScoped, onError) {
399
- try {
400
- const stateRoot = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
401
- const host = os.hostname().replace(/[^A-Za-z0-9._-]/g, "_") || "unknown-host";
402
- const rootKey = rootKeyFor(root);
403
- const prefix = rootScoped ? `orphans-${rootKey}-` : "orphans-";
404
- const dir = path.join(stateRoot, "hq-cli", "lanes-orphan-reports", host);
405
- const candidates = fs.readdirSync(dir)
406
- .filter((name) => name.startsWith(prefix) && name.endsWith(".json"))
407
- .map((name) => ({ name, mtime: fs.statSync(path.join(dir, name)).mtimeMs }))
408
- .sort((a, b) => b.mtime - a.mtime);
409
- // Reports accumulate, so read newest first and stop at the first one that
410
- // actually swept; skipped and unreadable reports are passed over.
411
- for (const candidate of candidates) {
412
- let report;
413
- try {
414
- report = JSON.parse(fs.readFileSync(path.join(dir, candidate.name), "utf8"));
415
- }
416
- catch (error) {
417
- onError?.(error);
418
- continue;
419
- }
420
- if (report.skipped)
421
- continue;
422
- return Array.isArray(report.lanes) ? report.lanes.filter((lane) => lane && typeof lane === "object" && lane.orphaned === true).length : 0;
423
- }
424
- return 0;
425
- }
426
- catch (error) {
427
- onError?.(error);
428
- return 0;
429
- }
430
- }
431
- /** Starts the CL-4 read-only orphan report once per host, without holding SessionStart open. */
432
- export function startSessionStartOrphanSweep(root, env = process.env, spawnDetached = spawn, rootScoped = true) {
433
- const stateRoot = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state");
434
- const host = os.hostname().replace(/[^A-Za-z0-9._-]/g, "_") || "unknown-host";
435
- const rootKey = rootKeyFor(root);
436
- const rootSuffix = rootScoped ? `-${rootKey}` : "";
437
- const stateDir = path.join(stateRoot, "hq-cli", "lanes-session-start", host);
438
- const lockPath = path.join(stateDir, `orphan-sweep${rootSuffix}.lock`);
439
- const reportDir = path.join(stateRoot, "hq-cli", "lanes-orphan-reports", host);
440
- const ownerToken = randomUUID();
441
- try {
442
- fs.mkdirSync(stateDir, { recursive: true, mode: 0o700 });
443
- fs.mkdirSync(reportDir, { recursive: true, mode: 0o700 });
444
- let fd;
445
- try {
446
- fd = fs.openSync(lockPath, "wx", 0o600);
447
- }
448
- catch (error) {
449
- if (error.code !== "EEXIST")
450
- return;
451
- let previous = {};
452
- try {
453
- previous = JSON.parse(fs.readFileSync(lockPath, "utf8"));
454
- }
455
- catch { /* malformed lease can be reclaimed */ }
456
- const age = Date.now() - Number(previous.started_at || 0);
457
- let running = false;
458
- if (Number.isInteger(previous.pid) && Number(previous.pid) > 0) {
459
- try {
460
- process.kill(Number(previous.pid), 0);
461
- running = true;
462
- }
463
- catch {
464
- running = false;
465
- }
466
- }
467
- if (age < ORPHAN_SWEEP_LOCK_TTL_MS && running)
468
- return;
469
- fs.rmSync(lockPath, { force: true });
470
- try {
471
- fd = fs.openSync(lockPath, "wx", 0o600);
472
- }
473
- catch {
474
- return;
475
- }
476
- }
477
- const startedAt = Date.now();
478
- fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, started_at: startedAt, owner_token: ownerToken }));
479
- fs.closeSync(fd);
480
- const cli = process.argv[1];
481
- if (!cli) {
482
- fs.rmSync(lockPath, { force: true });
483
- return;
484
- }
485
- const wrapper = [
486
- "const cp=require('node:child_process'),fs=require('node:fs'),path=require('node:path');",
487
- "const [cli,lock,root,token,report]=process.argv.slice(1);",
488
- "const cleanup=()=>{try{const lease=JSON.parse(fs.readFileSync(lock,'utf8'));if(lease.owner_token===token)fs.rmSync(lock,{force:true})}catch{}};",
489
- "const start=()=>{let lease;try{lease=JSON.parse(fs.readFileSync(lock,'utf8'))}catch{}if(lease?.owner_token!==token){if(Date.now()<Number(lease?.started_at||0)+1000)return setTimeout(start,10);process.exit(0)}",
490
- "try{fs.writeFileSync(lock,JSON.stringify({...lease,pid:process.pid}))}catch{}",
491
- "const tmp=report+'.tmp';let output;try{output=fs.createWriteStream(tmp,{flags:'wx',mode:0o600})}catch{cleanup();process.exit(0)}",
492
- "const child=cp.spawn(process.execPath,[cli,'runners','_reap','--json','--legacy'],{stdio:['ignore','pipe','ignore'],env:{...process.env,HQ_ROOT:root,HQ_NO_UPDATE_CHECK:'1'}});",
493
- "child.stdout.pipe(output);child.on('error',()=>{output.destroy();try{fs.rmSync(tmp,{force:true})}catch{}cleanup()});",
494
- "child.on('exit',(code)=>output.end(()=>{try{if(code===0)fs.renameSync(tmp,report);else fs.rmSync(tmp,{force:true})}catch{}cleanup()}));};start();",
495
- ].join("");
496
- const reportPath = path.join(reportDir, `orphans-${rootScoped ? `${rootKey}-` : ""}${startedAt}-${ownerToken}.json`);
497
- const launcher = spawnDetached(process.execPath, ["-e", wrapper, cli, lockPath, root, ownerToken, reportPath], {
498
- detached: true,
499
- stdio: "ignore",
500
- env: { ...env, HQ_ROOT: root, HQ_NO_UPDATE_CHECK: "1" },
501
- });
502
- if (launcher.pid) {
503
- try {
504
- fs.writeFileSync(lockPath, JSON.stringify({ pid: launcher.pid, started_at: startedAt, owner_token: ownerToken }));
505
- }
506
- catch { /* TTL lease still bounds an orphaned lock */ }
507
- }
508
- launcher.on("error", () => {
509
- try {
510
- const lease = JSON.parse(fs.readFileSync(lockPath, "utf8"));
511
- if (lease.owner_token === ownerToken)
512
- fs.rmSync(lockPath, { force: true });
513
- }
514
- catch { /* The lease may already have been reclaimed. */ }
515
- });
516
- launcher.unref();
517
- }
518
- catch {
519
- // SessionStart's orphan report is advisory and must never block startup.
520
- }
521
- }
522
389
  function flagRefreshLeaseDir(env) {
523
390
  const stateDir = env.HQ_STATE_DIR?.trim();
524
391
  if (stateDir)
@@ -618,8 +485,6 @@ export async function runLaneSessionStart(options = {}) {
618
485
  return read?.value ?? true;
619
486
  };
620
487
  const flagEnabled = readFlag(LANE_CONDUCT_SESSION_START_FLAG);
621
- const rootScoped = readFlag(LANE_ORPHAN_SWEEP_ROOT_KEYING_FLAG);
622
- const contextEnabled = readFlag(LANE_ORPHAN_SWEEP_CONTEXT_FLAG);
623
488
  if (refreshNeeded) {
624
489
  try {
625
490
  (options.refreshFlags ?? ((e) => { startSessionStartFlagRefresh(e); }))(env);
@@ -628,11 +493,10 @@ export async function runLaneSessionStart(options = {}) {
628
493
  }
629
494
  if (!flagEnabled)
630
495
  return;
631
- (options.startSweep ?? ((r, e) => startSessionStartOrphanSweep(r, e, spawn, rootScoped)))(root, env);
632
- if (contextEnabled) {
633
- const count = readOrphanCount(root, env, rootScoped, (error) => debug(`hq lanes session-start: orphan report read failed (${error instanceof Error ? error.name : "Error"})`));
634
- if (count > 0)
635
- stdout.write(`HQ orphaned lanes: ${count}; inspect with hq lanes orphans\n`);
496
+ if (readFlag(LANE_ORPHAN_SWEEP_CONTEXT_FLAG)) {
497
+ const count = readOrphanReportCount(root);
498
+ if (count !== null && count > 0)
499
+ stdout.write(`HQ orphaned lanes: ${count}; inspect with hq runners orphans\n`);
636
500
  }
637
501
  if (sessionWasDisabled(root, env, payload.session_id ?? payload.sessionId))
638
502
  return;
@@ -2,6 +2,7 @@ import type { StatFs } from "../lib/lanes/disk-guard.js";
2
2
  import type { LaneCompanyRef, LanePlacementPolicy, LaneRecord, LanesConfig, QuestionAnswer, QuestionBody, QuestionRecord, SeniorRef, AccountHistoryEntry, LaneAccountSelection, PendingResume, QueuedReason, ResolvedLaneWorker, LivenessDeps, MachineIdentity, MonitorEvidenceReader, ReconcileHost, RunCommand, ThrottleDeps, withLaneAdmissionLock, withLaneHireLocks } from "../lib/lanes/index.js";
3
3
  import type { OutpostIdentity } from "../lib/lanes/admission-host.js";
4
4
  import type { OutpostDispatchResult } from "../lib/lanes/outpost-dispatch.js";
5
+ import type { CompanyOutpostCandidate, CompanyOutpostTargets } from "../lib/lanes/company-outposts.js";
5
6
  import type { CpuBusySource, MemoryHold } from "../lib/lanes/throttle.js";
6
7
  import type { ProbeCommand } from "../lib/lanes/models.js";
7
8
  import type { ClaudeCredentialReader } from "../lib/lanes/claude-credential.js";
@@ -274,6 +275,8 @@ export interface Ctx {
274
275
  resolveActiveCompany: (company: string) => Promise<LaneCompanyRef | null>;
275
276
  listOutpostIds: () => Promise<string[]>;
276
277
  listOutpostRoutes: () => Promise<OutpostRouteIdentity[]>;
278
+ listCompanyOutposts: (company: LaneCompanyRef) => Promise<CompanyOutpostCandidate[]>;
279
+ companyOutposts: CompanyOutpostTargets;
277
280
  readOutpostIdentity: () => OutpostIdentity;
278
281
  spawnLogin: (opts: {
279
282
  command: string;
@@ -10,6 +10,7 @@ import type { OutpostIdentity } from "../lib/lanes/admission-host.js";
10
10
  export { OUTPOST_DIR, OUTPOST_ID_PATH, readOutpostIdentity } from "../lib/lanes/admission-host.js";
11
11
  export type { OutpostIdentity } from "../lib/lanes/admission-host.js";
12
12
  import { type OutpostDispatchResult } from "../lib/lanes/outpost-dispatch.js";
13
+ import { type CompanyOutpostCandidate, type CompanyOutpostExecClient } from "../lib/lanes/company-outposts.js";
13
14
  import { emitLaneDecisionEvents } from "../lib/lanes/mesh-events.js";
14
15
  import { MAX_LANE_DEPTH, withLaneAdmissionLock, withLaneHireLocks, type LaneCompanyRef, type QuestionBody, type LaneRecord, type QuestionRecord, type ResolvedLaneWorker, type SeniorRef, type LivenessDeps, type MachineIdentity, type MonitorEvidenceReader, type RunCommand, type ThrottleDeps } from "../lib/lanes/index.js";
15
16
  import { deriveWorkRequirements } from "../lib/environment/work-requirements.js";
@@ -49,6 +50,8 @@ export interface LanesCommandDeps {
49
50
  resolveActiveCompany?: (company: string) => Promise<LaneCompanyRef | null>;
50
51
  listOutpostIds?: () => Promise<string[]>;
51
52
  listOutpostRoutes?: () => Promise<OutpostRouteIdentity[]>;
53
+ listCompanyOutposts?: (company: LaneCompanyRef) => Promise<CompanyOutpostCandidate[]>;
54
+ outpostExecClient?: () => CompanyOutpostExecClient;
52
55
  readOutpostIdentity?: () => OutpostIdentity;
53
56
  spawnLogin?: (opts: {
54
57
  command: string;
@@ -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";
@@ -355,12 +356,21 @@ async function defaultListOutpostRoutes() {
355
356
  const rows = await defaultOutpostsClient().list();
356
357
  return rows.map(({ outpostId, instanceName }) => ({ outpostId, instanceName }));
357
358
  }
358
- async function defaultStageOutpostPayload(outpostId, bytes) {
359
- return stageOutpostPayload(defaultOutpostsClient(), outpostId, bytes);
359
+ async function defaultListCompanyOutposts(company) {
360
+ return listCompanyOutpostCandidates(defaultOutpostsClient(), company);
360
361
  }
361
- 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) {
362
372
  try {
363
- return await dispatchOutpostPickup(defaultOutpostsClient(), input);
373
+ return await dispatchOutpostPickup(port, input);
364
374
  }
365
375
  catch (err) {
366
376
  if (err instanceof LanesError)
@@ -491,6 +501,8 @@ function resolveDeps(deps = {}) {
491
501
  }
492
502
  return root;
493
503
  };
504
+ const companyOutposts = new CompanyOutpostTargets((outpostId) => recordedOutpostCompany(hqRoot(), outpostId));
505
+ const outpostExecPort = () => companyAwareExecPort((deps.outpostExecClient ?? defaultOutpostsClient)(), companyOutposts);
494
506
  return {
495
507
  cwd,
496
508
  callerCwd,
@@ -503,6 +515,8 @@ function resolveDeps(deps = {}) {
503
515
  resolveActiveCompany: deps.resolveActiveCompany ?? defaultResolveActiveCompany,
504
516
  listOutpostIds: deps.listOutpostIds ?? defaultListOutpostIds,
505
517
  listOutpostRoutes,
518
+ listCompanyOutposts: deps.listCompanyOutposts ?? defaultListCompanyOutposts,
519
+ companyOutposts,
506
520
  readOutpostIdentity: deps.readOutpostIdentity ?? (() => readOutpostIdentity()),
507
521
  spawnLogin: deps.spawnLogin ?? defaultSpawnLogin,
508
522
  throttleDeps: deps.throttleDeps ?? defaultThrottleDeps(env),
@@ -547,8 +561,10 @@ function resolveDeps(deps = {}) {
547
561
  env,
548
562
  now: deps.now ?? (() => new Date()),
549
563
  })),
550
- stageOutpostPayload: deps.stageOutpostPayload ?? defaultStageOutpostPayload,
551
- dispatchOutpostExec: deps.dispatchOutpostExec ?? defaultDispatchOutpostExec,
564
+ stageOutpostPayload: deps.stageOutpostPayload ??
565
+ ((outpostId, bytes) => stageOutpostPayload(outpostExecPort(), outpostId, bytes)),
566
+ dispatchOutpostExec: deps.dispatchOutpostExec ??
567
+ ((input) => defaultDispatchOutpostExec(outpostExecPort(), input)),
552
568
  backfillOutpostIdentity: deps.backfillOutpostIdentity ?? ((expectedId) => backfillOutpostIdentityMarkerImpl(expectedId, {
553
569
  read: () => deps.readOutpostIdentity?.() ?? readOutpostIdentity(),
554
570
  createIfMissing: createOutpostIdentityMarkerIfMissing,
@@ -1654,7 +1670,21 @@ async function readOutpostCapacityUncached(ctx, outpostId, waitMs = CAPACITY_PRO
1654
1670
  }
1655
1671
  return snapshot;
1656
1672
  }
1657
- 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) {
1658
1688
  const localHost = laneHostFromCtx(ctx);
1659
1689
  let outpostIds;
1660
1690
  try {
@@ -1671,6 +1701,8 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1671
1701
  maximum: MAX_PLACEMENT_OUTPOSTS,
1672
1702
  });
1673
1703
  }
1704
+ const companyCandidates = company ? await companyPlacementOutpostIds(ctx, company) : { ids: [], skipped: [] };
1705
+ const companySkipped = [...companyCandidates.skipped];
1674
1706
  const remoteIds = outpostIds
1675
1707
  .map((id) => id.trim())
1676
1708
  // `primary` aliases the controller when running on the primary box. From
@@ -1678,6 +1710,15 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1678
1710
  .filter((id) => !isControllerAliasOutpostId(id, localHost))
1679
1711
  .filter((id) => localHost.kind !== "outpost" || id !== localHost.id)
1680
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
+ }
1681
1722
  const local = buildHostCapacitySnapshot({
1682
1723
  host: localHost,
1683
1724
  localMatch: localAdmissionMatch(ctx),
@@ -1719,7 +1760,7 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1719
1760
  ? result.snapshot
1720
1761
  : { host: result.unavailable.host, error: result.unavailable.error }),
1721
1762
  ],
1722
- skippedHosts: unavailable.map(({ outpost_id, error }) => ({ outpost_id, error })),
1763
+ skippedHosts: [...unavailable.map(({ outpost_id, error }) => ({ outpost_id, error })), ...companySkipped],
1723
1764
  };
1724
1765
  }
1725
1766
  const outpostLaneListMemo = new WeakMap();
@@ -3070,6 +3111,36 @@ function assertLaneRunsHereForAdmission(ctx, lane) {
3070
3111
  return;
3071
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 });
3072
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
+ }
3073
3144
  function assertKnownOutpost(requested, known) {
3074
3145
  if (!known.includes(requested)) {
3075
3146
  throw new LanesError("unknown_outpost", `Unknown Outpost ${JSON.stringify(requested)}. Accepted: ${known.join(", ") || "(none)"}`, { accepted: known, value: requested });
@@ -3945,16 +4016,8 @@ async function runCreate(ctx, opts) {
3945
4016
  explicitProvider = autoChosenProvider;
3946
4017
  }
3947
4018
  }
3948
- if (opts.outpost !== undefined && opts.outpost !== "") {
3949
- const requested = opts.outpost.trim();
3950
- let known;
3951
- try {
3952
- known = await ctx.listOutpostIds();
3953
- }
3954
- catch (err) {
3955
- throw new LanesError("outpost_list_unavailable", `Failed to list Outpost ids: ${err instanceof Error ? err.message : String(err)}`, {});
3956
- }
3957
- assertKnownOutpost(requested, known);
4019
+ if (opts.outpost !== undefined && opts.outpost !== "" && !isCompanyOutpostId(opts.outpost.trim())) {
4020
+ await assertKnownLaneOutpost(ctx, opts.outpost.trim(), null);
3958
4021
  }
3959
4022
  let company = companyFlag
3960
4023
  ? await ctx.resolveCompany(companyFlag)
@@ -3980,6 +4043,9 @@ async function runCreate(ctx, opts) {
3980
4043
  if (seniorCompanyIdentifier)
3981
4044
  company = await ctx.resolveCompany(seniorCompanyIdentifier);
3982
4045
  }
4046
+ if (opts.outpost !== undefined && opts.outpost !== "" && isCompanyOutpostId(opts.outpost.trim())) {
4047
+ await assertKnownLaneOutpost(ctx, opts.outpost.trim(), company);
4048
+ }
3983
4049
  const callerAuthorization = requestedHireGrant !== undefined || ctx.env.HQ_LANE_ID?.trim()
3984
4050
  ? callerSeniorAuthorization(ctx, senior)
3985
4051
  : { authorized: true };
@@ -4188,14 +4254,7 @@ async function runCreate(ctx, opts) {
4188
4254
  for (const target of outpostTargets) {
4189
4255
  if (target === opts.outpost?.trim())
4190
4256
  continue;
4191
- let known;
4192
- try {
4193
- known = await ctx.listOutpostIds();
4194
- }
4195
- catch (err) {
4196
- throw new LanesError("outpost_list_unavailable", `Failed to list Outpost ids: ${dispatchErrorMessage(err)}`, {});
4197
- }
4198
- assertKnownOutpost(target, known);
4257
+ await assertKnownLaneOutpost(ctx, target, company);
4199
4258
  }
4200
4259
  if (placementToApply !== undefined) {
4201
4260
  const currentHost = laneHostFromCtx(ctx);
@@ -4223,7 +4282,7 @@ async function runCreate(ctx, opts) {
4223
4282
  }
4224
4283
  }
4225
4284
  else {
4226
- const capacity = await loadHostCapacitySnapshots(ctx, hqRoot, config);
4285
+ const capacity = await loadHostCapacitySnapshots(ctx, hqRoot, config, undefined, company);
4227
4286
  autoPlacementSkippedHosts = capacity.skippedHosts;
4228
4287
  const requestedAccount = opts.account !== undefined
4229
4288
  ? opts.account.trim()
@@ -5266,6 +5325,14 @@ async function dispatchCreatedOutpostLane(ctx, input) {
5266
5325
  message,
5267
5326
  });
5268
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
+ }
5269
5336
  throw new LanesError(DISPATCH_TERMINAL_REASON, `Failed to dispatch lane to Outpost ${outpostId}: ${message}`, {
5270
5337
  outpost_id: outpostId,
5271
5338
  lane_id: failed.lane_id,
@@ -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 = {}) {
@@ -52,6 +52,7 @@
52
52
  * first-class skip), and {@link registerMcpServers} is the pack-install routing
53
53
  * seam over it.
54
54
  */
55
+ import * as path from 'path';
55
56
  /** Base for every MCP-registration error; carries a stable machine-checkable `code`. */
56
57
  export declare abstract class McpRegistrationError extends Error {
57
58
  abstract readonly code: string;
@@ -282,15 +283,58 @@ export declare function readConfigDoc<T>(target: string, format: ConfigFormat<T>
282
283
  * separate snippet block) cannot leak. The result never contains raw file content.
283
284
  */
284
285
  export declare function sanitizeParserMessage(message: string): string;
286
+ /**
287
+ * Default maximum hold time. A lock older than this is reclaimed even when its
288
+ * recorded PID still reports alive: the PID may have been reused by an unrelated
289
+ * process (routine on Windows), or the holder may be hung. A normal hold is one
290
+ * read, merge and write of a small config file, well under a second, and every
291
+ * waiter gives up after {@link DEFAULT_LOCK_WAIT_MS}; ten minutes is far above
292
+ * both. Sentry HQ-CLI-HQ: without this limit a `.claude.json.hqlock` naming a
293
+ * live PID blocked `hq install --global` for 20 hours.
294
+ */
295
+ export declare const DEFAULT_LOCK_MAX_HOLD_MS: number;
296
+ /** Env var that overrides {@link DEFAULT_LOCK_MAX_HOLD_MS} (whole milliseconds, > 0). */
297
+ export declare const CONFIG_LOCK_MAX_HOLD_ENV = "HQ_CONFIG_LOCK_MAX_HOLD_MS";
298
+ /**
299
+ * The smallest maximum hold time in force, one full wait of a waiting command
300
+ * ({@link DEFAULT_LOCK_WAIT_MS}). A smaller limit makes a live holder's lock
301
+ * reclaimable while it is still writing, which turns the lock off.
302
+ */
303
+ export declare const MIN_LOCK_MAX_HOLD_MS = 10000;
304
+ /**
305
+ * The largest maximum hold time in force, 7 days. A real hold lasts well under
306
+ * a second; a larger value would only keep a wedged lock longer, and a value
307
+ * past what a Date can hold would make the refusal's clear time unprintable.
308
+ */
309
+ export declare const MAX_LOCK_MAX_HOLD_MS: number;
285
310
  /** A held advisory lock; release with {@link releaseLock} (idempotent). */
286
311
  export interface ConfigLock {
287
312
  /** The lockfile path (`~/.<basename>.hqlock`). */
288
313
  lockPath: string;
314
+ /**
315
+ * The exact bytes this acquisition wrote. {@link releaseLock} removes the file
316
+ * only while it still holds these bytes, so a holder whose lock was reclaimed
317
+ * never deletes the next holder's lock.
318
+ */
319
+ body?: string;
289
320
  }
321
+ /**
322
+ * The maximum hold time in force: a valid explicit option, else a valid
323
+ * `HQ_CONFIG_LOCK_MAX_HOLD_MS`, else the default. An option that is not a
324
+ * finite number above zero, or an env value that is not a whole number of
325
+ * milliseconds above zero, is ignored. A valid value is kept between
326
+ * {@link MIN_LOCK_MAX_HOLD_MS} and {@link MAX_LOCK_MAX_HOLD_MS}.
327
+ */
328
+ export declare function resolveLockMaxHoldMs(explicit: number | undefined, env?: NodeJS.ProcessEnv): number;
290
329
  /** Options for {@link acquireLock} — overridable so tests can use tiny timeouts. */
291
330
  export interface AcquireLockOptions {
292
331
  /** Age beyond which a dead-PID lock is considered stale + breakable. */
293
332
  staleMs?: number;
333
+ /**
334
+ * Age beyond which a lock is reclaimed even if its PID reports alive. Defaults
335
+ * to `HQ_CONFIG_LOCK_MAX_HOLD_MS`, then {@link DEFAULT_LOCK_MAX_HOLD_MS}.
336
+ */
337
+ maxHoldMs?: number;
294
338
  /** Total time to spin waiting for a live lock before throwing. */
295
339
  waitMs?: number;
296
340
  /** Poll interval while waiting. */
@@ -299,9 +343,17 @@ export interface AcquireLockOptions {
299
343
  isPidAlive?: (pid: number) => boolean;
300
344
  /** Injectable clock (tests). */
301
345
  now?: () => number;
346
+ /**
347
+ * Injectable delete of a stale lock file (tests simulate a Windows handle
348
+ * that denies delete access). Defaults to `fs.unlinkSync`.
349
+ */
350
+ removeLockFile?: (lockPath: string) => void;
302
351
  }
303
- /** The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden). */
304
- export declare function lockPathFor(target: string): string;
352
+ /**
353
+ * The lockfile path for a target: `~/.<basename>.hqlock` (a sibling, hidden).
354
+ * `pathImpl` exists so the Windows form can be checked on any platform.
355
+ */
356
+ export declare function lockPathFor(target: string, pathImpl?: path.PlatformPath): string;
305
357
  /**
306
358
  * Acquire an advisory O_EXCL lock for `target`, held across the whole
307
359
  * read->merge->write cycle so a concurrent register cannot interleave and lose a
@@ -310,14 +362,20 @@ export declare function lockPathFor(target: string): string;
310
362
  * - `O_EXCL | O_CREAT` create-or-fail; on EEXIST another holder exists.
311
363
  * - A held lock whose PID is DEAD and whose mtime is older than `staleMs` is
312
364
  * broken (unlinked) and re-acquired.
313
- * - A held lock whose PID is ALIVE (or fresh) is waited on up to `waitMs`; if
314
- * it never frees, this throws (the concurrent register ABORTS rather than
315
- * racing — the first writer's work is preserved).
365
+ * - A held lock older than `maxHoldMs` is broken and re-acquired even when its
366
+ * PID reports alive (reused PID or hung holder).
367
+ * - A held lock whose PID is ALIVE inside `maxHoldMs` (or dead but fresh) is
368
+ * waited on up to `waitMs`; if it never frees, this throws (the concurrent
369
+ * register ABORTS rather than racing — the first writer's work is preserved).
316
370
  *
317
- * The lockfile body is the holder's PID + an ISO timestamp (diagnostic).
371
+ * The lockfile body is the holder's PID, an ISO timestamp, and a random token.
318
372
  */
319
373
  export declare function acquireLock(target: string, opts?: AcquireLockOptions): ConfigLock;
320
- /** Release a held lock. Idempotent — a missing lockfile is not an error. */
374
+ /**
375
+ * Release a held lock. Idempotent — a missing lockfile is not an error. The file
376
+ * is removed only while it still holds the bytes this acquisition wrote: after a
377
+ * reclaim the file at this path belongs to the next holder and is left alone.
378
+ */
321
379
  export declare function releaseLock(lock: ConfigLock): void;
322
380
  /** UTC `YYYY-MM-DDTHH-MM-SSZ` (dash-separated) — the hq rescue timestamp format. */
323
381
  export declare function rescueStamp(d?: Date): string;