@indigoai-us/hq-cli 5.345.218 → 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 (62) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/dist/command-catalog.generated.d.ts +69 -0
  3. package/dist/command-catalog.generated.js +83 -0
  4. package/dist/commands/agents.d.ts +22 -0
  5. package/dist/commands/agents.js +92 -1
  6. package/dist/commands/core-hook-registration-plan.d.ts +8 -0
  7. package/dist/commands/core-hook-registration-plan.js +21 -0
  8. package/dist/commands/core.js +9 -0
  9. package/dist/commands/doctor.js +4 -0
  10. package/dist/commands/lanes-shared.d.ts +2 -0
  11. package/dist/commands/lanes-watch.js +28 -1
  12. package/dist/commands/lanes.d.ts +2 -0
  13. package/dist/commands/lanes.js +99 -9
  14. package/dist/commands/reindex.js +6 -0
  15. package/dist/index.js +8 -0
  16. package/dist/lib/anywhere-person-setting.d.ts +2 -2
  17. package/dist/lib/anywhere-person-setting.js +2 -2
  18. package/dist/lib/daemon/anywhere-listener.d.ts +33 -1
  19. package/dist/lib/daemon/anywhere-listener.js +86 -4
  20. package/dist/lib/daemon/machine-check-owner.d.ts +21 -0
  21. package/dist/lib/daemon/machine-check-owner.js +95 -0
  22. package/dist/lib/daemon/machine-check-registration.d.ts +4 -0
  23. package/dist/lib/daemon/machine-check-registration.js +64 -0
  24. package/dist/lib/daemon/machine-checks.d.ts +144 -0
  25. package/dist/lib/daemon/machine-checks.js +412 -0
  26. package/dist/lib/daemon/run.js +30 -4
  27. package/dist/lib/daemon/server.d.ts +2 -0
  28. package/dist/lib/daemon/server.js +6 -0
  29. package/dist/lib/daemon/state-file.d.ts +12 -1
  30. package/dist/lib/daemon/state-file.js +23 -1
  31. package/dist/lib/doctor/checks/fleet-hook-core.d.ts +4 -0
  32. package/dist/lib/doctor/checks/fleet-hook-core.js +103 -0
  33. package/dist/lib/doctor/checks/host-core.js +3 -1
  34. package/dist/lib/doctor/checks/machine-checks.d.ts +16 -0
  35. package/dist/lib/doctor/checks/machine-checks.js +103 -0
  36. package/dist/lib/doctor/registry.js +4 -0
  37. package/dist/lib/doctor/types.d.ts +4 -0
  38. package/dist/lib/hook-engine/canary-gate.d.ts +64 -0
  39. package/dist/lib/hook-engine/canary-gate.js +147 -0
  40. package/dist/lib/hook-engine/coverage.d.ts +3 -1
  41. package/dist/lib/hook-engine/coverage.js +8 -2
  42. package/dist/lib/hook-engine/fleet-registration.d.ts +30 -0
  43. package/dist/lib/hook-engine/fleet-registration.js +132 -0
  44. package/dist/lib/hook-engine/reconcile.js +3 -2
  45. package/dist/lib/hook-engine/registration-identity.d.ts +33 -0
  46. package/dist/lib/hook-engine/registration-identity.js +97 -0
  47. package/dist/lib/hook-engine/registration.d.ts +1 -30
  48. package/dist/lib/hook-engine/registration.js +1 -88
  49. package/dist/lib/hook-engine/resolve.d.ts +2 -0
  50. package/dist/lib/hook-engine/resolve.js +7 -3
  51. package/dist/lib/lanes/canonical-host.d.ts +8 -1
  52. package/dist/lib/lanes/canonical-host.js +9 -3
  53. package/dist/lib/lanes/machine-identity.d.ts +15 -0
  54. package/dist/lib/lanes/machine-identity.js +26 -0
  55. package/dist/lib/lanes/spawn.js +17 -3
  56. package/dist/utils/core-next-flag.d.ts +4 -0
  57. package/dist/utils/core-next-flag.js +22 -0
  58. package/dist/utils/core-next-kill.d.ts +16 -0
  59. package/dist/utils/core-next-kill.js +35 -0
  60. package/dist/utils/host-registration.d.ts +33 -23
  61. package/dist/utils/host-registration.js +86 -66
  62. package/package.json +8 -8
@@ -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,
@@ -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.
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
  */
@@ -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
@@ -1,6 +1,16 @@
1
+ import { readLocalOverride } from "@indigoai-us/hq-flags-client";
2
+ import { HQ_ANYWHERE_RUNTIME_FLAG } from "../anywhere-runtime-flag-key.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 const HQD_LISTENER_FALLBACK_MS = 10 * 60_000;
1
11
  /** Keep the local hqd listener aligned with the live flag and person setting. */
2
12
  export async function startHqdRuntimeListener(options) {
3
- const intervalMs = options.intervalMs ?? 60_000;
13
+ const fallbackMs = options.fallbackMs ?? HQD_LISTENER_FALLBACK_MS;
4
14
  const log = options.log ?? (() => { });
5
15
  const schedule = options.schedule ?? ((callback, delayMs) => {
6
16
  const timer = setInterval(callback, delayMs);
@@ -10,11 +20,15 @@ export async function startHqdRuntimeListener(options) {
10
20
  let server = null;
11
21
  let closed = false;
12
22
  let inFlight = null;
23
+ // An event arrived while a check was in progress: that check may have read
24
+ // the state from before the change, so one more check follows it.
25
+ let again = false;
13
26
  const refresh = () => {
14
27
  if (closed)
15
28
  return Promise.resolve();
16
29
  if (inFlight)
17
30
  return inFlight;
31
+ again = false;
18
32
  inFlight = (async () => {
19
33
  let enabled = false;
20
34
  try {
@@ -53,19 +67,35 @@ export async function startHqdRuntimeListener(options) {
53
67
  }
54
68
  })().finally(() => {
55
69
  inFlight = null;
70
+ if (again && !closed)
71
+ void refresh();
56
72
  });
57
73
  return inFlight;
58
74
  };
75
+ const notify = () => {
76
+ if (closed)
77
+ return;
78
+ if (inFlight) {
79
+ again = true;
80
+ return;
81
+ }
82
+ void refresh();
83
+ };
84
+ const unsubscribe = options.subscribe?.(notify) ?? (() => { });
59
85
  await refresh();
60
- if (closed)
61
- return { refresh, close: async () => { } };
62
- const cancel = schedule(() => { void refresh(); }, intervalMs);
86
+ if (closed) {
87
+ unsubscribe();
88
+ return { refresh, notify, close: async () => { } };
89
+ }
90
+ const cancel = schedule(() => { void refresh(); }, fallbackMs);
63
91
  return {
64
92
  refresh,
93
+ notify,
65
94
  async close() {
66
95
  if (closed)
67
96
  return;
68
97
  closed = true;
98
+ unsubscribe();
69
99
  cancel();
70
100
  await inFlight;
71
101
  const current = server;
@@ -76,4 +106,56 @@ export async function startHqdRuntimeListener(options) {
76
106
  },
77
107
  };
78
108
  }
109
+ export function createHqdRuntimeEvents() {
110
+ const listeners = new Set();
111
+ return {
112
+ emit() {
113
+ for (const notify of [...listeners]) {
114
+ try {
115
+ notify();
116
+ }
117
+ catch {
118
+ // one listener cannot stop the others
119
+ }
120
+ }
121
+ },
122
+ subscribe(notify) {
123
+ const entry = () => notify();
124
+ listeners.add(entry);
125
+ return () => { listeners.delete(entry); };
126
+ },
127
+ };
128
+ }
129
+ /**
130
+ * An observer for the daemon's shared registry reads (flag.ts `onRead`) that
131
+ * calls `onChange` when the HQ Anywhere runtime answer differs from the last
132
+ * read's: the registry value, a sign-in or sign-out, or the local override
133
+ * file. A failed read says nothing and is skipped. The first answer counts as
134
+ * a change, so a decision the listener made before the first read is checked.
135
+ */
136
+ export function observeHqdRuntimeFlag(onChange) {
137
+ let last;
138
+ return (read, env) => {
139
+ let answer;
140
+ try {
141
+ const override = readLocalOverride(HQ_ANYWHERE_RUNTIME_FLAG, env);
142
+ if (read.signedOut) {
143
+ answer = `signed-out|${String(override)}`;
144
+ }
145
+ else {
146
+ if (read.errors.length > 0 || !read.client)
147
+ return;
148
+ const resolution = read.client.explain(HQ_ANYWHERE_RUNTIME_FLAG, { fallback: true });
149
+ answer = `${resolution.source}:${String(resolution.value)}|${String(override)}`;
150
+ }
151
+ }
152
+ catch {
153
+ return;
154
+ }
155
+ if (answer === last)
156
+ return;
157
+ last = answer;
158
+ onChange();
159
+ };
160
+ }
79
161
  //# sourceMappingURL=anywhere-listener.js.map
@@ -0,0 +1,21 @@
1
+ /**
2
+ * How old the daemon's machine-check results file may be and still count as
3
+ * proof the schedule is running: two hourly intervals plus the first delay,
4
+ * so one late or skipped batch does not flip the owner.
5
+ */
6
+ export declare const MACHINE_CHECK_RESULTS_FRESH_MS: number;
7
+ /** Internal, offline protocol shared with the legacy dispatcher. */
8
+ export declare function machineCheckOwner(env?: NodeJS.ProcessEnv, home?: string, options?: {
9
+ now?: Date;
10
+ platform?: NodeJS.Platform;
11
+ }): {
12
+ schema: "hq-machine-check-owner.v1";
13
+ owner: "daemon" | "legacy";
14
+ reason: string;
15
+ checks: {
16
+ id: string;
17
+ path: string;
18
+ event: import("./machine-checks.js").MachineCheckEvent;
19
+ }[];
20
+ };
21
+ //# sourceMappingURL=machine-check-owner.d.ts.map
@@ -0,0 +1,95 @@
1
+ import * as os from "node:os";
2
+ import * as path from "node:path";
3
+ import { daemonPresenceLabel, readHeartbeat, heartbeatFile } from "./heartbeat.js";
4
+ import { MACHINE_CHECKS, MACHINE_CHECKS_FIRST_DELAY_MS, MACHINE_CHECKS_INTERVAL_MS, MACHINE_CHECKS_RESULT_FILE, machineChecksScheduleOn, } from "./machine-checks.js";
5
+ import { daemonPaths, readStoreFile } from "./paths.js";
6
+ import { readDaemonConfig } from "./config.js";
7
+ import { sameHqRoot } from "../hook-engine/registration-identity.js";
8
+ import { nativeSessionStartRegistered } from "./machine-check-registration.js";
9
+ import { codexEnvEvidence, grokEnvEvidence } from "../doctor/platform.js";
10
+ /**
11
+ * How old the daemon's machine-check results file may be and still count as
12
+ * proof the schedule is running: two hourly intervals plus the first delay,
13
+ * so one late or skipped batch does not flip the owner.
14
+ */
15
+ export const MACHINE_CHECK_RESULTS_FRESH_MS = 2 * MACHINE_CHECKS_INTERVAL_MS + MACHINE_CHECKS_FIRST_DELAY_MS;
16
+ function errorName(error) {
17
+ return error instanceof Error ? error.code ?? error.name : "UnknownError";
18
+ }
19
+ /**
20
+ * The session's harness: `HQ_HARNESS` when set, else the Codex or Grok runtime
21
+ * variables (the same markers `lanes` uses for the orchestrator engine), else
22
+ * Claude. Claude stays the default because `CLAUDECODE=1` is not always set.
23
+ */
24
+ function sessionHarness(env) {
25
+ const named = env.HQ_HARNESS?.trim().toLowerCase();
26
+ if (named)
27
+ return named;
28
+ if (codexEnvEvidence(env).length > 0)
29
+ return "codex";
30
+ if (grokEnvEvidence(env).length > 0)
31
+ return "grok";
32
+ return "claude";
33
+ }
34
+ /**
35
+ * Decide who runs the machine checks, offline and fail-safe. "daemon" only
36
+ * when every host-local signal shows the schedule is really running here:
37
+ * not Windows (checks start with /bin/bash), the rollout flag is on with no
38
+ * kill switch, the daemon heartbeat file is fresh, and the schedule wrote its
39
+ * results file (which needs a resolved HQ root) within the freshness window.
40
+ * Anything that cannot be observed answers "legacy" with the reason.
41
+ */
42
+ function decideOwner(env, home, now, platform) {
43
+ if (platform === "win32")
44
+ return { owner: "legacy", reason: "windows: machine checks need /bin/bash" };
45
+ if (!machineChecksScheduleOn(env, home))
46
+ return { owner: "legacy", reason: "core.next is off or a kill switch is set" };
47
+ const sessionRoot = env.HQ_ROOT?.trim();
48
+ let daemonRoot;
49
+ try {
50
+ daemonRoot = readDaemonConfig(daemonPaths(home, env).configPath).hqRoot;
51
+ }
52
+ catch { /* fail safe */ }
53
+ if (!sessionRoot || !daemonRoot || !sameHqRoot(sessionRoot, daemonRoot))
54
+ return { owner: "legacy", reason: "session HQ root differs from daemon HQ root" };
55
+ const host = sessionHarness(env);
56
+ if ((host !== "claude" && host !== "codex") || !nativeSessionStartRegistered(sessionRoot, home, host, env)) {
57
+ return { owner: "legacy", reason: "no native SessionStart for this host and HQ root" };
58
+ }
59
+ let beat;
60
+ try {
61
+ beat = readHeartbeat(heartbeatFile(home, env));
62
+ }
63
+ catch (error) {
64
+ return { owner: "legacy", reason: `daemon heartbeat unreadable (${errorName(error)})` };
65
+ }
66
+ if (!beat)
67
+ return { owner: "legacy", reason: "daemon heartbeat missing: daemon not running" };
68
+ if (daemonPresenceLabel(beat, now) !== "daemon live")
69
+ return { owner: "legacy", reason: "daemon heartbeat stale" };
70
+ let results;
71
+ try {
72
+ results = readStoreFile(path.join(daemonPaths(home, env).root, MACHINE_CHECKS_RESULT_FILE), 256 * 1024);
73
+ }
74
+ catch (error) {
75
+ return { owner: "legacy", reason: `machine-check results unreadable (${errorName(error)})` };
76
+ }
77
+ if (!results)
78
+ return { owner: "legacy", reason: "no machine-check results: schedule has not run with an HQ root" };
79
+ const age = now.getTime() - results.mtimeMs;
80
+ if (!Number.isFinite(age) || age > MACHINE_CHECK_RESULTS_FRESH_MS) {
81
+ return { owner: "legacy", reason: "machine-check results stale" };
82
+ }
83
+ return { owner: "daemon", reason: "daemon live and schedule results fresh" };
84
+ }
85
+ /** Internal, offline protocol shared with the legacy dispatcher. */
86
+ export function machineCheckOwner(env = process.env, home = env.HOME || env.USERPROFILE || os.homedir(), options = {}) {
87
+ const decided = decideOwner(env, home, options.now ?? new Date(), options.platform ?? process.platform);
88
+ return {
89
+ schema: "hq-machine-check-owner.v1",
90
+ owner: decided.owner,
91
+ reason: decided.reason,
92
+ checks: MACHINE_CHECKS.map(({ id, path: file, event }) => ({ id, path: file, event })),
93
+ };
94
+ }
95
+ //# sourceMappingURL=machine-check-owner.js.map
@@ -0,0 +1,4 @@
1
+ export type MachineCheckHost = "claude" | "codex" | "grok";
2
+ export declare function nativeSessionStartRegistered(root: string, home: string, host: MachineCheckHost, env: NodeJS.ProcessEnv): boolean;
3
+ export declare function anyNativeSessionStartRegistered(root: string, home: string, env: NodeJS.ProcessEnv): boolean;
4
+ //# sourceMappingURL=machine-check-registration.d.ts.map
@@ -0,0 +1,64 @@
1
+ /** Read-only proof that a session can receive the daemon's findings. */
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { parse } from "smol-toml";
5
+ import { isCoreNextEntry, userHookSettingsFile } from "../hook-engine/registration-identity.js";
6
+ function readSettings(file) {
7
+ let fd;
8
+ try {
9
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NONBLOCK ?? 0));
10
+ const stat = fs.fstatSync(fd);
11
+ if (!stat.isFile() || stat.size > 1024 * 1024)
12
+ return undefined;
13
+ const bytes = Buffer.alloc(1024 * 1024 + 1);
14
+ const length = fs.readSync(fd, bytes, 0, bytes.length, 0);
15
+ return length <= 1024 * 1024 ? bytes.toString("utf8", 0, length) : undefined;
16
+ }
17
+ catch {
18
+ return undefined;
19
+ }
20
+ finally {
21
+ if (fd !== undefined)
22
+ fs.closeSync(fd);
23
+ }
24
+ }
25
+ function entries(value) {
26
+ if (!Array.isArray(value))
27
+ return [];
28
+ return value.flatMap((group) => {
29
+ if (!group || typeof group !== "object")
30
+ return [];
31
+ const hooks = group.hooks;
32
+ return Array.isArray(hooks) ? hooks.filter((entry) => !!entry && typeof entry === "object") : [];
33
+ });
34
+ }
35
+ export function nativeSessionStartRegistered(root, home, host, env) {
36
+ const files = host === "claude"
37
+ ? [userHookSettingsFile("claude", home, env), path.join(root, ".claude/settings.json"), path.join(root, ".claude/settings.local.json")]
38
+ : host === "codex"
39
+ ? [userHookSettingsFile("codex", home, env), path.join(root, ".codex/hooks.json"), path.join(root, ".codex/config.toml")]
40
+ : [path.join(home, ".grok/hooks/hq-hq-bridge.json"), path.join(root, ".grok/hooks/hq-grok-user-bridge.json")];
41
+ return files.some((file) => {
42
+ try {
43
+ const text = readSettings(file);
44
+ if (text === undefined)
45
+ return false;
46
+ const doc = (file.endsWith(".toml") ? parse(text) : JSON.parse(text));
47
+ return entries(doc.hooks?.SessionStart ?? doc.hooks?.session_start).some((entry) => {
48
+ if (!isCoreNextEntry(entry, root))
49
+ return false;
50
+ if (Array.isArray(entry.args))
51
+ return entry.args[2] === host && entry.args[3] === "SessionStart";
52
+ return typeof entry.command === "string" && entry.command.includes(`'--host' '${host}' 'SessionStart'`);
53
+ });
54
+ }
55
+ catch {
56
+ return false;
57
+ }
58
+ });
59
+ }
60
+ export function anyNativeSessionStartRegistered(root, home, env) {
61
+ // Grok currently has no SessionStart notice; do not transfer its checks.
62
+ return ["claude", "codex"].some((host) => nativeSessionStartRegistered(root, home, host, env));
63
+ }
64
+ //# sourceMappingURL=machine-check-registration.js.map