@indigoai-us/hq-cli 5.345.217 → 5.345.219

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 (101) hide show
  1. package/CHANGELOG.md +105 -0
  2. package/README.md +1 -1
  3. package/assets/bot-workers/setup/skills/add-a-pack.md +3 -3
  4. package/assets/scaffold/core/scripts/hq-session.sh +4 -0
  5. package/dist/command-catalog.generated.d.ts +69 -0
  6. package/dist/command-catalog.generated.js +83 -0
  7. package/dist/commands/agents.d.ts +22 -0
  8. package/dist/commands/agents.js +92 -1
  9. package/dist/commands/cloud.d.ts +1 -1
  10. package/dist/commands/cloud.js +1 -1
  11. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  12. package/dist/commands/core-hook-registration-plan.js +21 -0
  13. package/dist/commands/core-hq-session-native.js +3 -0
  14. package/dist/commands/core.js +9 -0
  15. package/dist/commands/doctor.js +4 -0
  16. package/dist/commands/install-global.js +1 -1
  17. package/dist/commands/lanes-shared.d.ts +2 -0
  18. package/dist/commands/lanes-watch.js +28 -1
  19. package/dist/commands/lanes.d.ts +2 -0
  20. package/dist/commands/lanes.js +99 -9
  21. package/dist/commands/members.js +1 -1
  22. package/dist/commands/pack-start-bot.d.ts +1 -1
  23. package/dist/commands/pack-start-bot.js +2 -2
  24. package/dist/commands/pkg-update.js +1 -1
  25. package/dist/commands/reindex.js +6 -0
  26. package/dist/commands/sync-narrow.js +1 -1
  27. package/dist/commands/team-sync.js +1 -1
  28. package/dist/data/command-states.json +8 -1
  29. package/dist/index.js +8 -0
  30. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  31. package/dist/lib/anywhere-person-setting.js +2 -2
  32. package/dist/lib/billing/usage-cost.js +5 -2
  33. package/dist/lib/bot/pack-link.d.ts +2 -2
  34. package/dist/lib/bot/pack-link.js +2 -2
  35. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  36. package/dist/lib/daemon/anywhere-listener.js +86 -4
  37. package/dist/lib/daemon/hook-env.d.ts +32 -0
  38. package/dist/lib/daemon/hook-env.js +51 -0
  39. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  40. package/dist/lib/daemon/machine-check-owner.js +95 -0
  41. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  42. package/dist/lib/daemon/machine-check-registration.js +64 -0
  43. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  44. package/dist/lib/daemon/machine-checks.js +412 -0
  45. package/dist/lib/daemon/ops/policy.js +5 -3
  46. package/dist/lib/daemon/run.js +37 -5
  47. package/dist/lib/daemon/server.d.ts +2 -0
  48. package/dist/lib/daemon/server.js +6 -0
  49. package/dist/lib/daemon/state-file.d.ts +12 -1
  50. package/dist/lib/daemon/state-file.js +23 -1
  51. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +4 -0
  52. package/dist/lib/doctor/checks/fleet-hook-core.js +103 -0
  53. package/dist/lib/doctor/checks/host-core.d.ts +2 -0
  54. package/dist/lib/doctor/checks/host-core.js +81 -11
  55. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  56. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  57. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  58. package/dist/lib/doctor/registry.js +4 -0
  59. package/dist/lib/doctor/types.d.ts +4 -0
  60. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  61. package/dist/lib/environment/credential-shapes.js +333 -0
  62. package/dist/lib/environment/profile.js +4 -16
  63. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  64. package/dist/lib/hook-engine/canary-gate.js +147 -0
  65. package/dist/lib/hook-engine/coverage.d.ts +15 -0
  66. package/dist/lib/hook-engine/coverage.js +130 -0
  67. package/dist/lib/hook-engine/fleet-registration.d.ts +30 -0
  68. package/dist/lib/hook-engine/fleet-registration.js +132 -0
  69. package/dist/lib/hook-engine/reconcile.js +297 -116
  70. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  71. package/dist/lib/hook-engine/registration-identity.js +97 -0
  72. package/dist/lib/hook-engine/registration.d.ts +1 -23
  73. package/dist/lib/hook-engine/registration.js +1 -52
  74. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  75. package/dist/lib/hook-engine/resolve.js +7 -3
  76. package/dist/lib/install/claude-targets.js +28 -15
  77. package/dist/lib/install/codex-pack-contributions.js +1 -1
  78. package/dist/lib/install/codex-targets.js +24 -11
  79. package/dist/lib/install/hook-target.d.ts +2 -2
  80. package/dist/lib/install/hook-target.js +7 -5
  81. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  82. package/dist/lib/lanes/canonical-host.js +9 -3
  83. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  84. package/dist/lib/lanes/machine-identity.js +26 -0
  85. package/dist/lib/lanes/spawn.js +17 -3
  86. package/dist/lib/packages/setup-block.d.ts +2 -2
  87. package/dist/lib/packages/setup-block.js +2 -2
  88. package/dist/lib/packages/start-bot.d.ts +1 -1
  89. package/dist/lib/packages/start-bot.js +1 -1
  90. package/dist/main.js +1 -1
  91. package/dist/types.d.ts +1 -1
  92. package/dist/utils/callback-port-busy.d.ts +1 -1
  93. package/dist/utils/callback-port-busy.js +4 -4
  94. package/dist/utils/core-next-flag.d.ts +4 -0
  95. package/dist/utils/core-next-flag.js +22 -0
  96. package/dist/utils/core-next-kill.d.ts +16 -0
  97. package/dist/utils/core-next-kill.js +35 -0
  98. package/dist/utils/hook-trust.js +4 -1
  99. package/dist/utils/host-registration.d.ts +80 -17
  100. package/dist/utils/host-registration.js +194 -47
  101. package/package.json +8 -8
@@ -642,6 +642,9 @@ export function executeHqSession(argv, context, overrides = {}) {
642
642
  return { code: 1, stdout: "", stderr: `hq-session: invalid company_slug: '${slug}' (allowed characters: A-Z a-z 0-9 - _)\n` };
643
643
  }
644
644
  const dir = path.join(root, "companies", slug);
645
+ if (subcommand === "add" && slug !== "personal" && !deps.exists(dir) && !deps.isSymlink(dir) && !hasCompanyCaseAlias(root, slug, deps)) {
646
+ return { code: 1, stdout: "", stderr: `hq-session: no company directory at companies/${slug}/ (looked for ${dir}/). Run ls companies/ and pass the exact directory name, or create the company first with /newcompany.\n` };
647
+ }
645
648
  if (subcommand === "add" && (slug === "personal" || !isRegisteredCompany(root, slug, deps) || deps.isSymlink(dir) || hasCompanyCaseAlias(root, slug, deps) || !exactCompanyDir(root, slug, deps))) {
646
649
  return { code: 1, stdout: "", stderr: `hq-session: company_slug must use the exact real directory name: '${slug}'\n` };
647
650
  }
@@ -29,6 +29,7 @@
29
29
  * `ScaffoldRoot`.
30
30
  */
31
31
  import { Option } from "commander";
32
+ import { registerCoreHookRegistrationPlan } from "./core-hook-registration-plan.js";
32
33
  import { registerCoreCheckpointCommand } from "./core-checkpoint.js";
33
34
  import { runHookEnginePath } from '../hook-engine-path.js';
34
35
  import { registerCoreDelegateCommand } from "./core-delegate.js";
@@ -442,7 +443,15 @@ export function registerCoreCommands(program) {
442
443
  .addOption(new Option("--hq-root <path>", "HQ installation to operate on (live-root commands)").hideHelp());
443
444
  // This group primarily hosts manifest-driven bundled assets, but it also
444
445
  // hosts native TypeScript plumbing when a scaffold contract needs it.
446
+ const machineCheckOwnerCommand = core.command("machine-check-owner")
447
+ .description("Report the offline owner of the twelve scheduled machine checks")
448
+ .action(async () => {
449
+ const { machineCheckOwner } = await import("../lib/daemon/machine-check-owner.js");
450
+ process.stdout.write(`${JSON.stringify(machineCheckOwner())}\n`);
451
+ });
452
+ describeCoreCommand(machineCheckOwnerCommand, { execution: "native", root: "cwd" });
445
453
  registerCoreCheckpointCommand(core);
454
+ registerCoreHookRegistrationPlan(core);
446
455
  const hookEnginePath = core.command('hook-engine-path')
447
456
  .description('Print the offline, version-pinned native hook engine path')
448
457
  .option('--repair', 'Repair the pinned copy after closing running hook processes')
@@ -134,7 +134,11 @@ export async function runDoctor(options = {}) {
134
134
  liveRuntimes: options.liveRuntimes === true,
135
135
  company: options.company,
136
136
  integrations: options.integrations !== false,
137
+ verbose: options.verbose === true,
138
+ runMachineChecks: requested?.includes("machine-checks") === true,
137
139
  };
140
+ if (context.runMachineChecks)
141
+ writeErr("hq doctor: machine checks run repair actions on this machine.\n");
138
142
  const families = await registry.run(context);
139
143
  if (!requested)
140
144
  await addHostCoreFamily(families, registry, context);
@@ -850,7 +850,7 @@ export function installGlobalCodex(opts) {
850
850
  const companySkillLinksToRemove = [...new Set(cleanupRoots.flatMap((root) => hqCompanySkillLinksForRoot(t.skillsDir, root)))];
851
851
  const hooksOld = readOrNull(t.hooksJson);
852
852
  const hooksDoc = readConfigDoc(t.hooksJson, jsonFormat).doc;
853
- const hookTarget = hookTargetFor(hqRoot, home, opts.daemonInstalled, env);
853
+ const hookTarget = hookTargetFor(hqRoot, home, opts.daemonInstalled, env, 'codex');
854
854
  const hooksNext = addCodexHooks(hooksDoc, hqRoot, hookTarget);
855
855
  const tomlOld = readOrNull(t.configToml);
856
856
  const tomlDoc = readConfigDoc(t.configToml, codexConfigFormat).doc;
@@ -309,6 +309,8 @@ export interface Ctx {
309
309
  /** Claude access-token expiry check for account status. Absent in tests that fake the probe. */
310
310
  readClaudeCredential?: ClaudeCredentialReader;
311
311
  resolveMachineIdentity: () => MachineIdentity;
312
+ /** This machine's EC2 instance id from a local file, or null. No network call. */
313
+ readInstanceIdFromDisk: () => string | null;
312
314
  runCompaction?: RunCompactionFn;
313
315
  locateTranscript?: (home: string, sessionId: string) => string | null;
314
316
  monitorEvidence: MonitorEvidenceReader;
@@ -1,5 +1,7 @@
1
1
  import { accountStatus, coveredLaneIds, expiredLaneIds, loadLanesConfig, MAX_WATCHED_LANES, MONITOR_ENGINES, MONITOR_MAX_TIMEOUT_MS, MONITOR_UNCOVERED_EXIT_CODE, monitorReminderText, runLaneWatch, } from "../lib/lanes/index.js";
2
+ import { resolveAdmissionHost } from "../lib/lanes/admission-host.js";
2
3
  import { LEAD_LANE_KEEP_ALIVE_FLAG } from "../lib/lanes/keep-alive.js";
4
+ import { localHostIdsReferToSameMachine } from "../lib/lanes/local-host-identity.js";
3
5
  import { resolveLaneCompany } from "../lib/lanes/lane-company.js";
4
6
  import { readLanesRegistryFlag } from "../lib/lanes/registry-flag.js";
5
7
  import { isLanesError, LanesError } from "../lib/lanes/errors.js";
@@ -44,6 +46,7 @@ export function createLaneWatchHandlers(deps) {
44
46
  async function runWatch(ctx, laneIds, opts) {
45
47
  const rawInterval = opts.intervalMs === undefined ? undefined : Number(opts.intervalMs);
46
48
  const hqRoot = ctx.hqRoot();
49
+ let localMatch;
47
50
  await runLaneWatch(hqRoot, laneIds, {
48
51
  intervalMs: rawInterval,
49
52
  sleep: ctx.sleep,
@@ -57,8 +60,32 @@ export function createLaneWatchHandlers(deps) {
57
60
  const config = loadLanesConfig(hqRoot);
58
61
  const currentHost = laneHostFromCtx(ctx);
59
62
  const currentHostname = ctx.hostname().trim();
63
+ // A local lane is on this machine under any id admission accepts for it:
64
+ // the stable id, the hostname, or an earlier hostname in lane-host.json.
65
+ // The identity file is read once per watch, not once per poll. If it
66
+ // cannot be read, the watch matches by hostname as it did before.
67
+ if (localMatch === undefined) {
68
+ try {
69
+ const admissionHost = resolveAdmissionHost({
70
+ hostname: ctx.hostname,
71
+ homedir: ctx.homedir,
72
+ readOutpostIdentity: () => ({ kind: "not_outpost" }),
73
+ });
74
+ localMatch = {
75
+ hostname: admissionHost.hostname,
76
+ ...(admissionHost.machineId !== undefined ? { machineId: admissionHost.machineId } : {}),
77
+ ...(admissionHost.aliases !== undefined ? { aliases: admissionHost.aliases } : {}),
78
+ };
79
+ }
80
+ catch (err) {
81
+ process.stderr.write(`lane watch: could not read the lane host identity, matching local lanes by hostname: ${err instanceof Error ? err.message : String(err)}\n`);
82
+ localMatch = { hostname: currentHostname };
83
+ }
84
+ }
85
+ const match = localMatch;
60
86
  const isCurrentHost = (host) => (host.kind === currentHost.kind && host.id === currentHost.id) ||
61
- (host.kind === "local" && host.id === currentHostname);
87
+ (host.kind === "local" && host.id === currentHostname) ||
88
+ (host.kind === "local" && localHostIdsReferToSameMachine(host.id, match));
62
89
  const remoteOutpostIds = [...new Set(lanes
63
90
  .filter((lane) => lane.host.kind === "outpost" && !isCurrentHost(lane.host))
64
91
  .map((lane) => lane.host.id))];
@@ -90,6 +90,8 @@ export interface LanesCommandDeps {
90
90
  */
91
91
  readClaudeCredential?: ClaudeCredentialReader;
92
92
  resolveMachineIdentity?: () => MachineIdentity;
93
+ /** Injected in tests; the default reads the board asset tag on Linux and makes no network call. */
94
+ readInstanceIdFromDisk?: () => string | null;
93
95
  stageOutpostPayload?: (outpostId: string, bytes: Uint8Array) => Promise<{
94
96
  getUrl: string;
95
97
  }>;
@@ -49,7 +49,7 @@ import { appendProjectFocusOverride, readProjectStoryFocusData, removeProjectFoc
49
49
  import { appendLaneFocusOverride, assertFocusGuardAllows, makeFocusOverride } from "../lib/lanes/focus-guard.js";
50
50
  import { LANE_FOCUS_GUARD_FLAG, LANE_FOCUS_DASHBOARD_FLAG, LANE_HIRE_GRANT_FINISHED_LANES_FLAG, LANE_LIST_SKIP_REMOTE_REFRESH_FLAG, LANE_MESSAGE_ROUTE_OWNER_HOST_FLAG, LANE_ORPHANED_BARE_ID_DROPBOX_REPAIR_FLAG, LANE_PROFILE_PIN_EXHAUSTED_FALLBACK_FLAG, LANE_STATUS_ROW_FIELDS_FLAG, LANE_REAP_STOP_FLAG, LANE_REUSE_REFRESHES_PROFILE_FLAG, LANE_WORKER_CONTINUITY_FLAG, LANE_CONDUCT_LOOP_FLAG, LANE_ENVELOPE_REPAIR_GUIDANCE_FLAG, } from "../lib/lanes/flag-keys.js";
51
51
  import { applyContinuitySettings, findWorkerContinuityLane, sameLaneHost, workerContinuityPrompt } from "../lib/lanes/worker-continuity.js";
52
- import { localHostIdsReferToSameMachine, observeLocalHostIdentity, resolveLocalHostIdentity } from "../lib/lanes/local-host-identity.js";
52
+ import { laneHostIdentityPath, localHostIdsReferToSameMachine, observeLocalHostIdentity, resolveLocalHostIdentity } from "../lib/lanes/local-host-identity.js";
53
53
  import { commitIdleLoopStop, enqueueLoopEnvelope, interruptLoopQueue, interruptLoopQueueForStory, loopControllerIsAlive, loopLaneIsIdle, loopStatus, validateLoopEnvelope } from "../lib/lanes/loop.js";
54
54
  import { LOOP_CONTROLLER_RECOVERY_REASON, LOOP_STALL_RESTART_REASON, runLaneLoopController, startLaneLoopController, startLaneLoopControllerWithAdmissionLockHeld } from "./lanes-loop.js";
55
55
  import { configuredCodexRolloutHomes, retainCodexRollouts } from "../lib/lanes/disk-guard.js";
@@ -68,6 +68,7 @@ import { buildOutpostCapacityCommand, buildOutpostIdentityBackfillCommand, build
68
68
  import { outpostHireSummaryCacheKey, OUTPOST_HIRE_SUMMARY_CACHE_TTL_MS, readOutpostHireSummaryCache, readOutpostHireSummaryCacheIncludingStale, writeOutpostHireSummaryCache, } from "../lib/lanes/outpost-hire-cache.js";
69
69
  import { buildHostCapacitySnapshot, chooseHostForLane, hostCapacitySnapshotToWire, parseHostCapacitySnapshot, } from "../lib/lanes/host-capacity.js";
70
70
  import { resolveCanonicalHost } from "../lib/lanes/canonical-host.js";
71
+ import { readInstanceIdFromDisk } from "../lib/lanes/machine-identity.js";
71
72
  import { BALANCE_MOVABLE_STATES, selectClaudeAccount, } from "../lib/lanes/claude-balance.js";
72
73
  import { parseUserYaml } from "../utils/user-yaml-error.js";
73
74
  import { backfillOutpostIdentityMarker as backfillOutpostIdentityMarkerImpl, createOutpostIdentityMarkerIfMissing, validateOutpostIdentityId, } from "../lib/lanes/outpost-identity.js";
@@ -487,6 +488,7 @@ function resolveDeps(deps = {}) {
487
488
  };
488
489
  }),
489
490
  resolveMachineIdentity: deps.resolveMachineIdentity ?? lookupMachineIdentity,
491
+ readInstanceIdFromDisk: deps.readInstanceIdFromDisk ?? (() => readInstanceIdFromDisk()),
490
492
  probeProvider: deps.probeProvider ?? defaultProbe,
491
493
  readClaudeCredential: deps.readClaudeCredential ??
492
494
  (deps.probeProvider === undefined ? readLaneClaudeCredential : undefined),
@@ -657,6 +659,21 @@ function reconcileHostFromCtx(ctx) {
657
659
  readOutpostIdentity: ctx.readOutpostIdentity,
658
660
  });
659
661
  }
662
+ /**
663
+ * What lane admission matches a local lane against on this machine: the
664
+ * hostname, the stable id and the hostnames in `~/.hq/lane-host.json`. Every
665
+ * local capacity snapshot counts with it, so placement, account balance and
666
+ * `runners capacity` count the lanes admission would run here and no others.
667
+ * Read only. `buildHostCapacitySnapshot` ignores it for an Outpost host.
668
+ */
669
+ function localAdmissionMatch(ctx) {
670
+ const host = reconcileHostFromCtx(ctx);
671
+ return {
672
+ hostname: host.hostname,
673
+ ...(host.machineId !== undefined ? { machineId: host.machineId } : {}),
674
+ ...(host.aliases !== undefined ? { aliases: host.aliases } : {}),
675
+ };
676
+ }
660
677
  export function parseSeniorRef(raw) {
661
678
  const trimmed = raw.trim();
662
679
  if (trimmed.length === 0) {
@@ -1463,6 +1480,50 @@ function localStableHost(ctx) {
1463
1480
  const identity = resolveLocalHostIdentity({ homedir: ctx.homedir(), hostname });
1464
1481
  return { kind: "local", id: identity.id };
1465
1482
  }
1483
+ /**
1484
+ * The host a subagent-run lane records: the same stable id a worker lane on
1485
+ * this machine records. A subagent lane is a board record written from inside
1486
+ * its senior session, which may not be allowed to write the home directory,
1487
+ * and before this id was used it never read the identity file at all. So this
1488
+ * never fails on the file. When the file cannot be created or updated, the
1489
+ * lane records the stable id already on disk, or the hostname when there is
1490
+ * none. When the file is present but invalid, the lane records the hostname.
1491
+ * The lane host matcher resolves each of these to this machine.
1492
+ */
1493
+ function subagentLaneHost(ctx) {
1494
+ const hostname = ctx.hostname().trim();
1495
+ if (!hostname) {
1496
+ throw new LanesError("host_identity_unknown", "Cannot resolve this host for lane placement", {});
1497
+ }
1498
+ const unusable = (err) => {
1499
+ if (isLanesError(err))
1500
+ return err.error === "host_identity_corrupt" ? err.error : null;
1501
+ const code = err?.code;
1502
+ return typeof code === "string" && /^E[A-Z0-9]+$/.test(code) ? code : null;
1503
+ };
1504
+ const file = laneHostIdentityPath(ctx.homedir());
1505
+ try {
1506
+ return localStableHost(ctx);
1507
+ }
1508
+ catch (err) {
1509
+ const reason = unusable(err);
1510
+ if (reason === null)
1511
+ throw err;
1512
+ process.stderr.write(`hq lanes: could not use ${file} (${reason}); recording a host id that can be read\n`);
1513
+ if (reason === "host_identity_corrupt")
1514
+ return { kind: "local", id: hostname };
1515
+ }
1516
+ try {
1517
+ return recordedLocalHost(ctx);
1518
+ }
1519
+ catch (err) {
1520
+ const reason = unusable(err);
1521
+ if (reason === null)
1522
+ throw err;
1523
+ process.stderr.write(`hq lanes: could not read ${file} (${reason}); recording the hostname\n`);
1524
+ return { kind: "local", id: hostname };
1525
+ }
1526
+ }
1466
1527
  /** Read the stable id when one exists. Does not create or update `~/.hq/lane-host.json`. */
1467
1528
  function recordedLocalHost(ctx) {
1468
1529
  const hostname = ctx.hostname().trim();
@@ -1571,6 +1632,7 @@ async function loadHostCapacitySnapshots(ctx, hqRoot, config = loadLanesConfig(h
1571
1632
  .sort();
1572
1633
  const local = buildHostCapacitySnapshot({
1573
1634
  host: localHost,
1635
+ localMatch: localAdmissionMatch(ctx),
1574
1636
  lanes: localLanes,
1575
1637
  config,
1576
1638
  existsSync: ctx.existsSync,
@@ -2208,6 +2270,7 @@ async function loadClaudeBalanceHostSnapshots(ctx, hqRoot, config, options = {})
2208
2270
  const localLanes = loadAllLanes(hqRoot);
2209
2271
  const local = buildHostCapacitySnapshot({
2210
2272
  host: localHost,
2273
+ localMatch: localAdmissionMatch(ctx),
2211
2274
  lanes: localLanes,
2212
2275
  config,
2213
2276
  existsSync: ctx.existsSync,
@@ -2232,6 +2295,7 @@ async function loadClaudeBalanceHostSnapshots(ctx, hqRoot, config, options = {})
2232
2295
  snapshots.push({
2233
2296
  capacity: buildHostCapacitySnapshot({
2234
2297
  host: actualLocalHost,
2298
+ localMatch: localAdmissionMatch(ctx),
2235
2299
  lanes: actualLocalLanes,
2236
2300
  config,
2237
2301
  existsSync: ctx.existsSync,
@@ -4373,6 +4437,7 @@ async function runCreate(ctx, opts) {
4373
4437
  const refreshedLocal = {
4374
4438
  capacity: buildHostCapacitySnapshot({
4375
4439
  host: localHost,
4440
+ localMatch: localAdmissionMatch(ctx),
4376
4441
  lanes: localLanes,
4377
4442
  config,
4378
4443
  existsSync: ctx.existsSync,
@@ -6479,12 +6544,16 @@ async function runCapacity(ctx) {
6479
6544
  const hostname = ctx.hostname();
6480
6545
  // Read only: this command also runs as the remote capacity probe.
6481
6546
  const localIdentity = observeLocalHostIdentity({ homedir: ctx.homedir(), hostname: hostname.trim() });
6547
+ // A file read, and only on an Outpost: lane records created there carry the
6548
+ // instance id as their origin. Other machines never read it.
6549
+ const instanceId = host.kind === "outpost" ? ctx.readInstanceIdFromDisk() : null;
6482
6550
  const canonical = resolveCanonicalHost({
6483
6551
  host,
6484
6552
  hostname,
6485
6553
  ...(localIdentity
6486
6554
  ? { identityAliases: localIdentity.aliases, localIdentityId: localIdentity.id }
6487
6555
  : {}),
6556
+ ...(instanceId ? { instanceId } : {}),
6488
6557
  lanes,
6489
6558
  now,
6490
6559
  });
@@ -6492,11 +6561,7 @@ async function runCapacity(ctx) {
6492
6561
  host,
6493
6562
  aliases: canonical.aliases,
6494
6563
  // Count what lane admission and `queued_lanes` below accept, no wider.
6495
- localMatch: {
6496
- hostname: admissionHost.hostname,
6497
- ...(admissionHost.machineId !== undefined ? { machineId: admissionHost.machineId } : {}),
6498
- ...(admissionHost.aliases !== undefined ? { aliases: admissionHost.aliases } : {}),
6499
- },
6564
+ localMatch: localAdmissionMatch(ctx),
6500
6565
  lanes,
6501
6566
  config: loadLanesConfig(hqRoot),
6502
6567
  existsSync: ctx.existsSync,
@@ -8147,6 +8212,25 @@ async function prepareAccountMove(ctx, lane, input) {
8147
8212
  ? writeMove()
8148
8213
  : withLaneAdmissionLock(hqRoot, lane.provider, writeMove, ctx.sleep);
8149
8214
  }
8215
+ /**
8216
+ * The host a lane's Claude account is balanced on. A local lane whose
8217
+ * recorded id is another id of this machine, and which has no snapshot under
8218
+ * that id, balances on this machine's local snapshot. Every other lane
8219
+ * balances on the host it records.
8220
+ */
8221
+ function canonicalBalanceHostForLane(ctx, lane, snapshots) {
8222
+ if (lane.host.kind !== "local")
8223
+ return lane.host;
8224
+ if (snapshots.some((host) => sameLaneHost(host.capacity.host, lane.host)))
8225
+ return lane.host;
8226
+ const match = localAdmissionMatch(ctx);
8227
+ if (!localHostIdsReferToSameMachine(lane.host.id, match))
8228
+ return lane.host;
8229
+ // This machine's own snapshots come first in the list. Its local one is
8230
+ // keyed by the stable id, or by the hostname when this machine is an Outpost.
8231
+ const here = snapshots.find((host) => host.capacity.host.kind === "local" && localHostIdsReferToSameMachine(host.capacity.host.id, match));
8232
+ return here?.capacity.host ?? lane.host;
8233
+ }
8150
8234
  async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile, options = {}) {
8151
8235
  if (lane.provider !== "claude")
8152
8236
  return undefined;
@@ -8227,7 +8311,13 @@ async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile, opti
8227
8311
  const balanceHosts = await loadClaudeBalanceHostSnapshots(ctx, hqRoot, config, {
8228
8312
  tolerateInvalidLaneLists: options.tolerateInvalidHostLaneLists === true,
8229
8313
  });
8230
- const targetHost = balanceHosts.snapshots.find((host) => host.capacity.host.kind === lane.host.kind && host.capacity.host.id === lane.host.id);
8314
+ // A lane written under another id of this machine (its hostname before the
8315
+ // stable id existed) balances against this machine's local snapshot. The
8316
+ // lane's `host` keeps the id it has. The stored `account_selection.target_host`
8317
+ // is the host balanced on, the one its `considered` rows are keyed by, as
8318
+ // it is for a lane created on an Outpost.
8319
+ const balanceLaneHost = canonicalBalanceHostForLane(ctx, lane, balanceHosts.snapshots);
8320
+ const targetHost = balanceHosts.snapshots.find((host) => host.capacity.host.kind === balanceLaneHost.kind && host.capacity.host.id === balanceLaneHost.id);
8231
8321
  const currentTargetAccount = lane.account === undefined
8232
8322
  ? undefined
8233
8323
  : targetHost?.capacity.providers.claude.accounts[lane.account];
@@ -8243,7 +8333,7 @@ async function selectAutomaticClaudeResumeAccount(ctx, lane, workerProfile, opti
8243
8333
  company: resolveLaneCompany(hqRoot, lane).company,
8244
8334
  retainedAccount: lane.account,
8245
8335
  hosts: balanceHosts.snapshots,
8246
- targetHost: lane.host,
8336
+ targetHost: balanceLaneHost,
8247
8337
  actualTargetHost: lane.host,
8248
8338
  requestedPlacement: null,
8249
8339
  config,
@@ -9483,7 +9573,7 @@ async function runCreateSubagent(ctx, opts) {
9483
9573
  model_source: cliModel !== undefined ? "cli" : "none",
9484
9574
  ...(cliEffort !== undefined ? { effort: cliEffort } : {}),
9485
9575
  effort_source: cliEffort !== undefined ? "cli" : "none",
9486
- host: { kind: "local", id: ctx.hostname() },
9576
+ host: subagentLaneHost(ctx),
9487
9577
  attribution_history: [],
9488
9578
  created_at: createdAt,
9489
9579
  updated_at: createdAt,
@@ -579,7 +579,7 @@ export function registerMembersCommand(program) {
579
579
  // grant to give them. What they SEE locally is governed by their sync
580
580
  // mode, not by access.
581
581
  console.log(chalk.dim(`${role === "owner" ? "Owners" : "Admins"} automatically have full read and write access to all of this company's context — no separate context grant is needed.\n` +
582
- `What they actually see synced to their machine is governed by their sync mode (\`hq sync mode\`), not by access.`));
582
+ `What they actually see synced to their machine is governed by their sync mode (\`hq daemon sync mode get <company>\`), not by access.`));
583
583
  }
584
584
  else if (role === "guest") {
585
585
  console.log(chalk.dim(GUEST_COMPANY_WIDE_NOTE));
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Production wiring for `hq packages install --start-bot`: the bot lifecycle
2
+ * Production wiring for `hq install --start-bot`: the bot lifecycle
3
3
  * seams of lib/packages/start-bot.ts bound to the real `hq bot` internals
4
4
  * (create, restart, intro) and the bot DM API. Loaded on demand by
5
5
  * pkg-install.ts so an ordinary install never imports the bot machinery.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Production wiring for `hq packages install --start-bot`: the bot lifecycle
2
+ * Production wiring for `hq install --start-bot`: the bot lifecycle
3
3
  * seams of lib/packages/start-bot.ts bound to the real `hq bot` internals
4
4
  * (create, restart, intro) and the bot DM API. Loaded on demand by
5
5
  * pkg-install.ts so an ordinary install never imports the bot machinery.
@@ -26,7 +26,7 @@ async function dmOwner(name, body) {
26
26
  return;
27
27
  }
28
28
  const token = await ensureCognitoToken({ tokenSource: "person", interactive: false });
29
- const owner = await resolveCallerPersonUid(token, undefined, { command: "hq packages install --start-bot" });
29
+ const owner = await resolveCallerPersonUid(token, undefined, { command: "hq install --start-bot" });
30
30
  if (!owner)
31
31
  throw new Error("your HQ login has no person entity yet");
32
32
  await new BotApi({ token: async () => token }).sendDm({ toPersonUid: owner, body });
@@ -37,7 +37,7 @@ async function updatePackages(slug) {
37
37
  const hqRoot = resolveDefaultHqRoot({ onMissing: 'throw' });
38
38
  const entries = readRegistry(hqRoot);
39
39
  if (entries.length === 0) {
40
- console.log('No packages installed. Use "hq packages install <slug>" to install one.');
40
+ console.log('No packages installed. Use "hq install <slug>" to install one.');
41
41
  return;
42
42
  }
43
43
  const accessToken = await ensureCognitoToken();
@@ -1,4 +1,5 @@
1
1
  import { reconcileHookRegistrations } from '../lib/hook-engine/reconcile.js';
2
+ import { SKIP_CANARY_GATE_ENV } from '../lib/hook-engine/canary-gate.js';
2
3
  import { trustCodexUserHooks } from '../utils/hook-trust.js';
3
4
  /**
4
5
  * hq reindex — surface namespaced skills and commands, clean up retired
@@ -742,7 +743,12 @@ export function registerReindexCommand(program) {
742
743
  .option('--repo-root <path>', 'HQ root to operate on (defaults to the current directory)')
743
744
  .option('--from-hook', 'Invoked from a Claude/Codex lifecycle hook: never wait on the per-root operation lock — if a sync/rescue holds it, skip this reindex instead of blocking the session (equivalent to --lock-timeout 0)')
744
745
  .option('--lock-timeout <seconds>', 'Bound the wait for the per-root operation lock (seconds). 0 = refuse immediately; omitted = wait indefinitely (the interactive default). --from-hook implies 0; an explicit --lock-timeout wins.')
746
+ .option('--skip-host-canary-gate', 'Bypass the host canary gate (hq-core-rust US-019): with core.next on, switch Claude Code, Codex and Grok Build hook events to the new core even when no current passing host canary exists for this hq-hook version and HQ root. Prints a warning. Same as HQ_SKIP_HOST_CANARY_GATE=1.')
745
747
  .action(async (opts) => {
748
+ // The registration switch reads the override from the environment, so
749
+ // install, reindex and the Grok trust step all honor it the same way.
750
+ if (opts.skipHostCanaryGate)
751
+ process.env[SKIP_CANARY_GATE_ENV] = '1';
746
752
  // Resolve the lock-wait bound. An explicit --lock-timeout wins; otherwise
747
753
  // --from-hook forces 0 (refuse-fast) so a hook fired while a sync/rescue
748
754
  // holds the shared per-root operation lock can never stall the agent.
@@ -94,7 +94,7 @@ export async function resolveNarrowTarget(input) {
94
94
  throw new Error(`Refusing to narrow: membership for '${companySlug}' is currently ` +
95
95
  `syncMode='${syncConfig.syncMode}'. The narrow ritual only runs on ` +
96
96
  `syncMode='all' memberships (shared → shared is a no-op; ` +
97
- `custom requires \`hq sync mode shared\` directly).`);
97
+ `custom requires \`hq daemon sync mode set ${companySlug} shared\` directly).`);
98
98
  }
99
99
  return {
100
100
  membership,
@@ -361,7 +361,7 @@ export function registerTeamSyncCommand(program) {
361
361
  .join(', ');
362
362
  console.log(chalk.yellow(`Companies ${companyNames} are cloud-synced and do not have team.json. ` +
363
363
  'hq team-sync only handles git team repositories with team.json.'));
364
- console.log(chalk.dim('Use `hq sync pull --all` to sync company vault files and `hq sync status` to check their local sync state.'));
364
+ console.log(chalk.dim('Use `hq sync pull --all` to sync company vault files and `hq daemon sync status` to check the sync runner state.'));
365
365
  }
366
366
  if (discovery.nonCloudBackedCompanyNames.length > 0) {
367
367
  const companyNames = discovery.nonCloudBackedCompanyNames
@@ -10,6 +10,13 @@
10
10
  "report access": { "state": "retiring" },
11
11
  "report discard-draft": { "state": "retiring" },
12
12
  "report promote": { "state": "retiring" },
13
- "report templates": { "state": "retiring" }
13
+ "report templates": { "state": "retiring" },
14
+ "staff listings approve": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
15
+ "staff listings queue": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
16
+ "staff listings reject": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
17
+ "staff reset-test-account": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
18
+ "staff test-account add": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
19
+ "staff test-account list": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" },
20
+ "staff test-account remove": { "state": "retiring", "replacedBy": "the staff-only hq-staff script outside the public CLI" }
14
21
  }
15
22
  }
package/dist/index.js CHANGED
@@ -226,6 +226,14 @@ function dispatchCliEntry() {
226
226
  // Before anything spawns: a background hq on Windows (no terminal) hides the
227
227
  // console window of every child it starts (feedback_351a40d5).
228
228
  installWindowsHideDefault();
229
+ // Offline hook query: bypass full CLI startup, install followup, telemetry
230
+ // and update checks. It reads only the existing flag snapshot/kill switches.
231
+ if (process.argv.length === 4 && process.argv[2] === "core" && process.argv[3] === "machine-check-owner") {
232
+ void import("./lib/daemon/machine-check-owner.js").then(({ machineCheckOwner }) => {
233
+ process.stdout.write(`${JSON.stringify(machineCheckOwner())}\n`);
234
+ }).catch(() => { process.exitCode = 1; });
235
+ return;
236
+ }
229
237
  // A run that mentions --i-still-use-this takes the full command graph, which
230
238
  // knows the command names and reads the flag only where it is hq's (before
231
239
  // the command's own arguments). The fast routes pass their arguments on
@@ -15,8 +15,8 @@ export declare function personTokenCachePath(env: NodeJS.ProcessEnv, home: strin
15
15
  export declare function readHqAnywherePersonSetting(options?: ReadHqAnywherePersonSettingOptions): Promise<boolean | null>;
16
16
  /**
17
17
  * Wrap a setting reader so a failed read (null) returns the last successfully
18
- * read value for `graceMs`. A long-running caller such as hqd re-reads every
19
- * minute, and one slow request would otherwise switch HQ Anywhere off for
18
+ * read value for `graceMs`. A long-running caller such as hqd re-reads it
19
+ * whenever its runtime gate is checked, and one slow request would otherwise switch HQ Anywhere off for
20
20
  * every session. A newly read value, including off, always applies at once;
21
21
  * with no successful read inside the window the result stays null (closed).
22
22
  */
@@ -59,8 +59,8 @@ export async function readHqAnywherePersonSetting(options = {}) {
59
59
  }
60
60
  /**
61
61
  * Wrap a setting reader so a failed read (null) returns the last successfully
62
- * read value for `graceMs`. A long-running caller such as hqd re-reads every
63
- * minute, and one slow request would otherwise switch HQ Anywhere off for
62
+ * read value for `graceMs`. A long-running caller such as hqd re-reads it
63
+ * whenever its runtime gate is checked, and one slow request would otherwise switch HQ Anywhere off for
64
64
  * every session. A newly read value, including off, always applies at once;
65
65
  * with no successful read inside the window the result stays null (closed).
66
66
  */
@@ -353,8 +353,11 @@ export function excludeFoldersFix(scope) {
353
353
  id: "exclude-folders",
354
354
  title: "Stop syncing folders you do not need in the cloud",
355
355
  detail: "Add the folders to .hqignore in your HQ folder so sync skips them, or limit what this company downloads with " +
356
- "`hq sync mode shared`. Files already in the cloud stay until you remove them; nothing is deleted.",
357
- preview: ["hq sync mode --show", ...(scope.kind === "company" ? [`hq storage status${companyFlag(scope)} --json`] : [])],
356
+ (scope.kind === "company" ? `\`hq daemon sync mode set ${scope.companySlug} shared\`.` : "the company's sync settings.") +
357
+ " Files already in the cloud stay until you remove them; nothing is deleted.",
358
+ preview: scope.kind === "company"
359
+ ? [`hq daemon sync mode get ${scope.companySlug}`, `hq storage status${companyFlag(scope)} --json`]
360
+ : ["hq daemon sync status"],
358
361
  apply: ["(edit <HQ folder>/.hqignore: add one line per folder, for example `bigfolder/`)"],
359
362
  savesUsdPerMonth: null,
360
363
  };
@@ -10,7 +10,7 @@
10
10
  * "add the {Display Name}" a display name from the catalog
11
11
  * ./packs/hq-pack-{slug}, ~/Downloads/hq-pack-{slug} a local pack folder
12
12
  *
13
- * The catalog is the curated list `hq packages list` prints (core.yaml
13
+ * The catalog is the curated list `hq packs list` prints (core.yaml
14
14
  * `recommended_packages`, see readRecommendedPackages). A slug or display name
15
15
  * that matches none of its entries is `unknown`, with the three closest
16
16
  * catalog names to offer. Nothing here knows any particular pack.
@@ -34,7 +34,7 @@ export type PackReference = {
34
34
  kind: PackReferenceKind;
35
35
  slug: string;
36
36
  displayName: string;
37
- /** What to hand `hq packages install`: the slug, or the local path when the message carried one. */
37
+ /** What to hand `hq install`: the slug, or the local path when the message carried one. */
38
38
  installSource: string;
39
39
  entry?: PackCatalogEntry;
40
40
  } | {
@@ -10,7 +10,7 @@
10
10
  * "add the {Display Name}" a display name from the catalog
11
11
  * ./packs/hq-pack-{slug}, ~/Downloads/hq-pack-{slug} a local pack folder
12
12
  *
13
- * The catalog is the curated list `hq packages list` prints (core.yaml
13
+ * The catalog is the curated list `hq packs list` prints (core.yaml
14
14
  * `recommended_packages`, see readRecommendedPackages). A slug or display name
15
15
  * that matches none of its entries is `unknown`, with the three closest
16
16
  * catalog names to offer. Nothing here knows any particular pack.
@@ -148,6 +148,6 @@ export function packConfirmSuggestions(displayName) {
148
148
  /** The exact command the setup bot runs after "Add the ...". */
149
149
  export function packInstallCommand(installSource) {
150
150
  const arg = /[\s"']/.test(installSource) ? JSON.stringify(installSource) : installSource;
151
- return `hq packages install ${arg} --start-bot`;
151
+ return `hq install ${arg} --start-bot`;
152
152
  }
153
153
  //# sourceMappingURL=pack-link.js.map
@@ -1,16 +1,48 @@
1
+ import type { DaemonFlagRegistryRead } from "./flag.js";
1
2
  import type { HqdServer } from "./server.js";
3
+ /**
4
+ * How often the listener checks again when no event has arrived. It is a
5
+ * correctness fallback only, for an event that was missed or a change no event
6
+ * reports (a person opting in while hqd is closed). Changes are normally
7
+ * picked up from the daemon's events: a shared registry read whose HQ
8
+ * Anywhere answer changed, or the running hqd server's runtime gate changing.
9
+ */
10
+ export declare const HQD_LISTENER_FALLBACK_MS: number;
2
11
  export interface HqdRuntimeListenerOptions {
3
12
  isEnabled: () => Promise<boolean>;
4
13
  startServer: () => Promise<HqdServer>;
5
14
  onServerChange?: (server: HqdServer | null) => void;
6
- intervalMs?: number;
15
+ /** Delay of the fallback check. Default HQD_LISTENER_FALLBACK_MS. */
16
+ fallbackMs?: number;
7
17
  schedule?: (callback: () => void, delayMs: number) => () => void;
18
+ /**
19
+ * Subscribe to the events that may change the decision. Called once, before
20
+ * the first check, so no event is lost while the listener starts. Returns
21
+ * the unsubscribe.
22
+ */
23
+ subscribe?: (notify: () => void) => () => void;
8
24
  log?: (error: unknown) => void;
9
25
  }
10
26
  export interface HqdRuntimeListener {
11
27
  refresh(): Promise<void>;
28
+ /** An event says the decision may have changed: check now, or again right after a check in progress. */
29
+ notify(): void;
12
30
  close(): Promise<void>;
13
31
  }
14
32
  /** Keep the local hqd listener aligned with the live flag and person setting. */
15
33
  export declare function startHqdRuntimeListener(options: HqdRuntimeListenerOptions): Promise<HqdRuntimeListener>;
34
+ /** A small fan-out from the daemon's event sources to the hqd listener. */
35
+ export interface HqdRuntimeEvents {
36
+ emit(): void;
37
+ subscribe(notify: () => void): () => void;
38
+ }
39
+ export declare function createHqdRuntimeEvents(): HqdRuntimeEvents;
40
+ /**
41
+ * An observer for the daemon's shared registry reads (flag.ts `onRead`) that
42
+ * calls `onChange` when the HQ Anywhere runtime answer differs from the last
43
+ * read's: the registry value, a sign-in or sign-out, or the local override
44
+ * file. A failed read says nothing and is skipped. The first answer counts as
45
+ * a change, so a decision the listener made before the first read is checked.
46
+ */
47
+ export declare function observeHqdRuntimeFlag(onChange: () => void): (read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => void;
16
48
  //# sourceMappingURL=anywhere-listener.d.ts.map