@indigoai-us/hq-cli 5.345.215 → 5.345.217

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 (135) hide show
  1. package/CHANGELOG.md +141 -0
  2. package/README.md +45 -0
  3. package/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  4. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  5. package/dist/command-catalog.generated.d.ts +59 -4
  6. package/dist/command-catalog.generated.js +74 -4
  7. package/dist/command-help.js +3 -1
  8. package/dist/command-registration-plan.d.ts +6 -0
  9. package/dist/command-registration-plan.js +1 -0
  10. package/dist/commands/auth.d.ts +1 -1
  11. package/dist/commands/auth.js +11 -52
  12. package/dist/commands/bot.js +11 -4
  13. package/dist/commands/cloud-demote.d.ts +19 -4
  14. package/dist/commands/cloud-demote.js +85 -12
  15. package/dist/commands/cloud-provision.d.ts +5 -1
  16. package/dist/commands/cloud-provision.js +6 -2
  17. package/dist/commands/cloud.d.ts +36 -0
  18. package/dist/commands/cloud.js +109 -26
  19. package/dist/commands/core.js +1 -0
  20. package/dist/commands/daemon.js +4 -1
  21. package/dist/commands/dm.js +7 -0
  22. package/dist/commands/doctor-usage.d.ts +8 -0
  23. package/dist/commands/doctor-usage.js +20 -0
  24. package/dist/commands/doctor.js +7 -1
  25. package/dist/commands/env.d.ts +18 -0
  26. package/dist/commands/env.js +82 -0
  27. package/dist/commands/install-global.js +2 -2
  28. package/dist/commands/lanes.js +100 -24
  29. package/dist/commands/logout.d.ts +7 -0
  30. package/dist/commands/logout.js +41 -34
  31. package/dist/commands/sources.d.ts +8 -2
  32. package/dist/commands/sources.js +65 -9
  33. package/dist/commands/whoami.js +26 -1
  34. package/dist/data/command-states.json +15 -0
  35. package/dist/index.js +52 -4
  36. package/dist/lazy-commands.js +2 -1
  37. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  38. package/dist/lib/anywhere-person-setting.js +6 -3
  39. package/dist/lib/billing/usage-card.d.ts +25 -4
  40. package/dist/lib/billing/usage-card.js +76 -9
  41. package/dist/lib/billing/usage-cost.d.ts +3 -3
  42. package/dist/lib/billing/usage-cost.js +35 -13
  43. package/dist/lib/billing/usage-only.js +4 -2
  44. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  45. package/dist/lib/billing/usage-rate-card.js +3 -0
  46. package/dist/lib/bot/fleet-cron.js +93 -6
  47. package/dist/lib/bot/inflight.d.ts +9 -0
  48. package/dist/lib/bot/inflight.js +10 -0
  49. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  50. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  51. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  52. package/dist/lib/bot/runtime/grok.js +1 -1
  53. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  54. package/dist/lib/daemon/flag-monitor.js +17 -6
  55. package/dist/lib/daemon/flag.d.ts +65 -1
  56. package/dist/lib/daemon/flag.js +190 -40
  57. package/dist/lib/daemon/ops/policy.js +62 -5
  58. package/dist/lib/daemon/paths.d.ts +72 -2
  59. package/dist/lib/daemon/paths.js +154 -3
  60. package/dist/lib/daemon/run.js +25 -20
  61. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  62. package/dist/lib/daemon/selfcheck.js +40 -1
  63. package/dist/lib/daemon/server.d.ts +3 -1
  64. package/dist/lib/daemon/server.js +7 -22
  65. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  66. package/dist/lib/daemon/state-file-switch.js +88 -0
  67. package/dist/lib/daemon/state-file.d.ts +198 -0
  68. package/dist/lib/daemon/state-file.js +419 -0
  69. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  70. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  71. package/dist/lib/doctor/checks/host-core.d.ts +50 -0
  72. package/dist/lib/doctor/checks/host-core.js +269 -0
  73. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  74. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  75. package/dist/lib/doctor/registry.js +4 -0
  76. package/dist/lib/environment/profile.d.ts +239 -0
  77. package/dist/lib/environment/profile.js +251 -0
  78. package/dist/lib/hook-engine/reconcile.js +39 -13
  79. package/dist/lib/hook-engine/registration.d.ts +9 -0
  80. package/dist/lib/hook-engine/registration.js +19 -0
  81. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  82. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  83. package/dist/lib/hot-channels/alert.d.ts +2 -0
  84. package/dist/lib/hot-channels/alert.js +8 -1
  85. package/dist/lib/hot-channels/contract.d.ts +12 -0
  86. package/dist/lib/hot-channels/contract.js +7 -0
  87. package/dist/lib/hot-channels/loop.js +1 -0
  88. package/dist/lib/hot-channels/run.d.ts +6 -0
  89. package/dist/lib/hot-channels/run.js +4 -0
  90. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  91. package/dist/lib/hot-channels/signals-pass.js +21 -49
  92. package/dist/lib/install/claude-targets.d.ts +12 -1
  93. package/dist/lib/install/claude-targets.js +57 -5
  94. package/dist/lib/install/codex-targets.d.ts +2 -2
  95. package/dist/lib/install/codex-targets.js +36 -6
  96. package/dist/lib/install/hook-target.d.ts +3 -0
  97. package/dist/lib/install/hook-target.js +11 -0
  98. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  99. package/dist/lib/lanes/canonical-host.js +65 -0
  100. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  101. package/dist/lib/lanes/host-capacity.js +29 -3
  102. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  103. package/dist/lib/mesh/live/daemon/run.js +5 -2
  104. package/dist/lib/mesh/live/flush.d.ts +5 -1
  105. package/dist/lib/mesh/live/flush.js +12 -6
  106. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  107. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  108. package/dist/lib/mesh/live/spool.d.ts +7 -0
  109. package/dist/lib/mesh/live/spool.js +25 -0
  110. package/dist/lib/person-setting-cache.d.ts +38 -0
  111. package/dist/lib/person-setting-cache.js +98 -0
  112. package/dist/lib/safe-store.d.ts +245 -0
  113. package/dist/lib/safe-store.js +777 -0
  114. package/dist/lib/signals/engine.d.ts +29 -2
  115. package/dist/lib/signals/engine.js +103 -4
  116. package/dist/lib/signals/reply.js +73 -18
  117. package/dist/lib/signals/steps/adapters.js +7 -2
  118. package/dist/lib/signals/steps/extract.d.ts +13 -0
  119. package/dist/lib/signals/steps/extract.js +84 -4
  120. package/dist/main.js +46 -3
  121. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  122. package/dist/utils/auth-expiry.d.ts +8 -0
  123. package/dist/utils/auth-expiry.js +53 -0
  124. package/dist/utils/cli-telemetry.d.ts +21 -0
  125. package/dist/utils/cli-telemetry.js +34 -0
  126. package/dist/utils/command-usage.d.ts +275 -0
  127. package/dist/utils/command-usage.js +797 -0
  128. package/dist/utils/hook-trust.d.ts +7 -0
  129. package/dist/utils/hook-trust.js +31 -4
  130. package/dist/utils/host-registration.d.ts +126 -0
  131. package/dist/utils/host-registration.js +378 -0
  132. package/dist/utils/resident-package-preload.js +2 -0
  133. package/package.json +10 -8
  134. package/scripts/bench-core.mjs +1096 -0
  135. package/scripts/check-function-manifest.mjs +702 -0
@@ -30,9 +30,8 @@ import { assertPersonalServiceSessionCapability, readRemoteControlPoolsConfig, r
30
30
  import { loadLanesConfig } from "../lanes/config.js";
31
31
  import { daemonLanesReconcileHandler } from "../lanes/daemon-reconcile.js";
32
32
  import { ensureDaemonLanesReconcileHandler } from "./lanes-reconcile-loader.js";
33
- import { SUPERVISOR_HANDOFF_FLAG, readDaemonFlag } from "./flag.js";
34
- import { createBoundedDaemonFlagMonitor } from "./flag-monitor.js";
35
- import { DAEMON_CHILD_BOOTSTRAP_HANDOFF_WATCH_FLAG, DAEMON_LANES_RECONCILE_FILE_WATCH_FLAG, DAEMON_SEARCH_INDEX_RUNNER_OWNS_INDEX_FLAG, DAEMON_SYNC_PROCESS_SCAN_ON_MISSING_FLAG, } from "./kill-switch-flags.js";
33
+ import { SUPERVISOR_HANDOFF_FLAG, createDaemonFlagSnapshotSource, readDaemonFlag } from "./flag.js";
34
+ import { createDaemonKillSwitchMonitors } from "./timed-flag-monitors.js";
36
35
  import { createLanesReconcileWatcher } from "./lanes-reconcile-watcher.js";
37
36
  import { findLegacyUnits, legacyMeshUnitsToRetire, legacyOwnerLookup, } from "./legacy.js";
38
37
  import { readLegacySyncEnv } from "./legacy-sync-env.js";
@@ -47,6 +46,8 @@ import { updateAnywhereRuntimeRevocationMarker } from "../anywhere-runtime-revoc
47
46
  import { classifyWindowsTask, currentWindowsIdentity, daemonRootRefusal } from "./install.js";
48
47
  import { detectMachineType } from "./machine-type.js";
49
48
  import { appendPrivate, daemonPaths, ensurePrivateDir, openPrivateAppend } from "./paths.js";
49
+ import { SELF_CHECK_RESULT_FILE, readSelfCheckResult } from "./selfcheck.js";
50
+ import { createDaemonStateWriter, daemonStateFilePath, defaultDaemonStateFilePath, readVaultAccessManifest, selfCheckMachineChecks, } from "./state-file.js";
50
51
  import { hqdSocketPath } from "./protocol.js";
51
52
  import { startHqdServer, syncHqdEnabledMarker } from "./server.js";
52
53
  import { startHqdRuntimeListener } from "./anywhere-listener.js";
@@ -905,20 +906,24 @@ export async function runDaemon(opts) {
905
906
  };
906
907
  const daemonSyncRunnerPids = new Set();
907
908
  let supervisor = null;
908
- const killSwitchMonitor = (flagKey) => createBoundedDaemonFlagMonitor({
909
- fallback: true,
910
- read: () => readDaemonFlag(flagKey, {
911
- env,
912
- fallback: true,
913
- localOverrideMode: "ignore",
914
- throwOnError: true,
915
- }),
916
- onReadError: (error) => log("warn", `could not read ${flagKey}; keeping its default-on behavior (${error instanceof Error ? error.name : "UnknownError"})`),
909
+ // One registry request per 30-second tick decides every timed daemon flag.
910
+ // The same request also refreshes the state file hooks read (state-file.ts).
911
+ const stateWriter = createDaemonStateWriter({
912
+ file: daemonStateFilePath(home, env),
913
+ defaultFile: defaultDaemonStateFilePath(home, env),
914
+ log,
915
+ readVaultAccess: () => {
916
+ const configured = readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
917
+ return readVaultAccessManifest(configured && fs.existsSync(configured) ? configured : undefined);
918
+ },
919
+ readMachineChecks: () => selfCheckMachineChecks(readSelfCheckResult(path.join(paths.root, SELF_CHECK_RESULT_FILE))),
917
920
  });
918
- const childBootstrapHandoffWatchFlag = killSwitchMonitor(DAEMON_CHILD_BOOTSTRAP_HANDOFF_WATCH_FLAG);
919
- const lanesReconcileFileWatchFlag = killSwitchMonitor(DAEMON_LANES_RECONCILE_FILE_WATCH_FLAG);
920
- const searchIndexRunnerOwnsIndexFlag = killSwitchMonitor(DAEMON_SEARCH_INDEX_RUNNER_OWNS_INDEX_FLAG);
921
- const syncProcessScanOnMissingFlag = killSwitchMonitor(DAEMON_SYNC_PROCESS_SCAN_ON_MISSING_FLAG);
921
+ const flagSnapshots = createDaemonFlagSnapshotSource({ onRead: stateWriter.onRegistryRead });
922
+ const killSwitches = createDaemonKillSwitchMonitors({ env, log, snapshots: flagSnapshots });
923
+ const childBootstrapHandoffWatchFlag = killSwitches.childBootstrapHandoffWatch;
924
+ const lanesReconcileFileWatchFlag = killSwitches.lanesReconcileFileWatch;
925
+ const searchIndexRunnerOwnsIndexFlag = killSwitches.searchIndexRunnerOwnsIndex;
926
+ const syncProcessScanOnMissingFlag = killSwitches.syncProcessScanOnMissing;
922
927
  let laneReconcileWatcher = null;
923
928
  let laneReconcileWatcherRoot = null;
924
929
  let laneReconcileWatchFailedRoot = null;
@@ -945,10 +950,9 @@ export async function runDaemon(opts) {
945
950
  laneReconcileWatcher?.close();
946
951
  laneReconcileWatcher = null;
947
952
  laneReconcileWatcherRoot = null;
948
- childBootstrapHandoffWatchFlag.close();
949
- lanesReconcileFileWatchFlag.close();
950
- searchIndexRunnerOwnsIndexFlag.close();
951
- syncProcessScanOnMissingFlag.close();
953
+ killSwitches.close();
954
+ flagSnapshots.close();
955
+ stateWriter.close();
952
956
  };
953
957
  const plan = () => {
954
958
  const config = readDaemonConfig(paths.configPath);
@@ -1477,6 +1481,7 @@ export async function runDaemon(opts) {
1477
1481
  registryPath: registryFile(registryDir(home, env)),
1478
1482
  hqRoot,
1479
1483
  log,
1484
+ flagSnapshots,
1480
1485
  onShutdown: () => hqdShutdown?.(),
1481
1486
  reportError: reportHqdCrash,
1482
1487
  observeError: (err) => tccEpermGuard.observe(err),
@@ -8,6 +8,7 @@
8
8
  * units are affected, naming every affected vault in that one DM. The 16-hour outage of 2026-11-03 was
9
9
  * found by hand; this makes the next one reach the owner.
10
10
  */
11
+ import { type StoreFileWriteOptions } from "./paths.js";
11
12
  import type { DaemonState, PersistedHolds } from "./supervisor.js";
12
13
  /** An engine unit that has been held or failing this long needs a person. */
13
14
  export declare const ATTENTION_AFTER_MS: number;
@@ -31,6 +32,25 @@ export interface SelfCheckRecord {
31
32
  }
32
33
  export declare function readSelfCheckRecord(file: string): SelfCheckRecord | null;
33
34
  export declare function writeSelfCheckRecord(file: string, record: SelfCheckRecord): void;
35
+ /**
36
+ * What the latest self-check run found, written on every run whether or not a
37
+ * DM was sent. The DM record above only changes when a DM goes out, so it
38
+ * cannot say that a machine is healthy or has recovered; this can.
39
+ */
40
+ export declare const SELF_CHECK_RESULT_FILE = "selfcheck-result.json";
41
+ export interface SelfCheckResult {
42
+ checkedAt: number;
43
+ /** Engine units needing attention at that time. */
44
+ problems: number;
45
+ }
46
+ /**
47
+ * The latest result, or null. A file that is a symlink, has another link, is
48
+ * not this user's, or that group or others can write is not read: its value
49
+ * reaches the state file hooks trust.
50
+ */
51
+ export declare function readSelfCheckResult(file: string): SelfCheckResult | null;
52
+ /** Written atomically through src/lib/safe-store.ts in the daemon's private folder; a link at the path is replaced, never written through. */
53
+ export declare function writeSelfCheckResult(file: string, result: SelfCheckResult, options?: StoreFileWriteOptions): void;
34
54
  /**
35
55
  * Send now: something is wrong and this machine has not sent a self-check DM
36
56
  * in the last day. Which units are affected does not matter, so units that
@@ -48,6 +68,8 @@ export interface SelfCheckDeps {
48
68
  statePath: string;
49
69
  holdsPath: string;
50
70
  recordPath: string;
71
+ /** Where the latest run's result is written, for the daemon's state file. Not written when omitted. */
72
+ resultPath?: string;
51
73
  now: () => number;
52
74
  machine: string;
53
75
  readState: () => DaemonState | null;
@@ -11,7 +11,7 @@
11
11
  import * as fs from "node:fs";
12
12
  import * as path from "node:path";
13
13
  import { syncCoreUnitId } from "../sync-core/engine-home.js";
14
- import { ensurePrivateDir } from "./paths.js";
14
+ import { ensurePrivateDir, readStoreFile, writeStoreFile } from "./paths.js";
15
15
  /** An engine unit that has been held or failing this long needs a person. */
16
16
  export const ATTENTION_AFTER_MS = 30 * 60_000;
17
17
  /** This machine sends at most one self-check DM per this long. */
@@ -96,6 +96,37 @@ export function writeSelfCheckRecord(file, record) {
96
96
  fs.writeFileSync(tmp, `${JSON.stringify(record, null, 2)}\n`, { mode: 0o600 });
97
97
  fs.renameSync(tmp, file);
98
98
  }
99
+ /**
100
+ * What the latest self-check run found, written on every run whether or not a
101
+ * DM was sent. The DM record above only changes when a DM goes out, so it
102
+ * cannot say that a machine is healthy or has recovered; this can.
103
+ */
104
+ export const SELF_CHECK_RESULT_FILE = "selfcheck-result.json";
105
+ /**
106
+ * The latest result, or null. A file that is a symlink, has another link, is
107
+ * not this user's, or that group or others can write is not read: its value
108
+ * reaches the state file hooks trust.
109
+ */
110
+ export function readSelfCheckResult(file) {
111
+ const read = readStoreFile(file, 4096);
112
+ if (!read)
113
+ return null;
114
+ try {
115
+ const parsed = JSON.parse(read.text);
116
+ if (typeof parsed.checkedAt !== "number" || !Number.isFinite(parsed.checkedAt))
117
+ return null;
118
+ if (typeof parsed.problems !== "number" || !Number.isInteger(parsed.problems) || parsed.problems < 0)
119
+ return null;
120
+ return { checkedAt: parsed.checkedAt, problems: parsed.problems };
121
+ }
122
+ catch {
123
+ return null;
124
+ }
125
+ }
126
+ /** Written atomically through src/lib/safe-store.ts in the daemon's private folder; a link at the path is replaced, never written through. */
127
+ export function writeSelfCheckResult(file, result, options = {}) {
128
+ writeStoreFile(file, `${JSON.stringify(result)}\n`, { create: true, ...options });
129
+ }
99
130
  /**
100
131
  * Send now: something is wrong and this machine has not sent a self-check DM
101
132
  * in the last day. Which units are affected does not matter, so units that
@@ -127,6 +158,14 @@ vaultName = () => undefined) {
127
158
  export async function runSelfCheck(deps) {
128
159
  const now = deps.now();
129
160
  const problems = engineUnitsNeedingAttention(deps.readState(), deps.readHolds(), now, deps.wanted);
161
+ if (deps.resultPath) {
162
+ try {
163
+ writeSelfCheckResult(deps.resultPath, { checkedAt: now, problems: problems.length });
164
+ }
165
+ catch (error) {
166
+ deps.log(`sync engine self-check: could not record this run's result (${error.code ?? "error"})`);
167
+ }
168
+ }
130
169
  if (problems.length === 0) {
131
170
  deps.log("sync engine self-check: every engine unit is healthy");
132
171
  return "healthy";
@@ -12,7 +12,7 @@ export { createResolver };
12
12
  import { SessionRegistry } from "./session-registry.js";
13
13
  import { HqMcpBridge, type RunWorkerRequest } from "./ops/mcp.js";
14
14
  import { type StdinMachineCredentials } from "./machine-login.js";
15
- import { type ReadDaemonFlagOptions } from "./flag.js";
15
+ import type { DaemonFlagSnapshotSource, ReadDaemonFlagOptions } from "./flag.js";
16
16
  import { type WindowsPipeAclReport, type WindowsPipeHost } from "./windows-pipe-host.js";
17
17
  export interface HqdServerOptions {
18
18
  socketPath: string;
@@ -45,6 +45,8 @@ export interface HqdServerOptions {
45
45
  runtimeFlagReader?: (options: ReadDaemonFlagOptions) => Promise<boolean>;
46
46
  /** Test seam for the human opt-in setting; production reads hq-pro. */
47
47
  personSettingReader?: () => Promise<boolean | null>;
48
+ /** The daemon's shared flag read, so this server's runtime gate adds no registry request of its own. */
49
+ flagSnapshots?: DaemonFlagSnapshotSource;
48
50
  /** Test seam for the hosted Streamable HTTP MCP transport. */
49
51
  mcpBridge?: HqMcpBridge;
50
52
  /** Test seam for machine login while keeping production credentials off disk. */
@@ -26,9 +26,7 @@ import { authenticateMachineCredentials, machineTokenExpiresAt, MachineLoginErro
26
26
  import { HQ_MCP_TOOL_NAMES, HQD_NATIVE_TOOL_NAMES } from "../mcp/tools.js";
27
27
  import { HQ_ANYWHERE_RUNTIME_FLAG } from "../../commands/anywhere-runtime-flag.js";
28
28
  import { updateAnywhereRuntimeRevocationMarker } from "../anywhere-runtime-revocation-marker.js";
29
- import { readHqAnywherePersonSetting } from "../anywhere-person-setting.js";
30
- import { createBoundedDaemonFlagMonitor } from "./flag-monitor.js";
31
- import { readDaemonFlag } from "./flag.js";
29
+ import { createHqdRuntimeFlagMonitor } from "./timed-flag-monitors.js";
32
30
  import { startWindowsPipeHost, validateWindowsPipeAcl, WINDOWS_PIPE_STARTUP_REFUSAL } from "./windows-pipe-host.js";
33
31
  // The allowlist is deliberately read-only. A newly added hosted MCP tool must
34
32
  // pass hq.policy_check until it is explicitly reviewed as read-only here.
@@ -395,25 +393,12 @@ export async function startHqdServer(opts) {
395
393
  }
396
394
  }
397
395
  }
398
- const runtimeFlagMonitor = opts.mcpEnabled ? undefined : createBoundedDaemonFlagMonitor({
399
- read: async () => {
400
- const options = {
401
- env,
402
- throwOnError: true,
403
- // A local opt-out is honored, while a local opt-in cannot override the operator kill switch.
404
- localOverrideMode: "off-only",
405
- };
406
- const flagEnabled = await (opts.runtimeFlagReader
407
- ? opts.runtimeFlagReader(options)
408
- : readDaemonFlag(HQ_ANYWHERE_RUNTIME_FLAG, options));
409
- if (!flagEnabled)
410
- return false;
411
- const personSetting = await (opts.personSettingReader ?? (() => readHqAnywherePersonSetting({
412
- env,
413
- onError: (name) => log("warn", `hqd person setting refresh failed (${name}); keeping HQ Anywhere off`),
414
- })))();
415
- return personSetting === true;
416
- },
396
+ const runtimeFlagMonitor = opts.mcpEnabled ? undefined : createHqdRuntimeFlagMonitor({
397
+ env,
398
+ log,
399
+ ...(opts.flagSnapshots ? { snapshots: opts.flagSnapshots } : {}),
400
+ ...(opts.runtimeFlagReader ? { runtimeFlagReader: opts.runtimeFlagReader } : {}),
401
+ ...(opts.personSettingReader ? { personSettingReader: opts.personSettingReader } : {}),
417
402
  onChange: (enabled) => {
418
403
  try {
419
404
  updateAnywhereRuntimeRevocationMarker(enabled, env.HOME?.trim() || undefined, env);
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The switch for the daemon's state file (state-file.ts, hq-core-rust US-009).
3
+ * Default ON: with nothing configured the daemon writes the state file and
4
+ * the hook engine reads it, exactly as #2624 shipped.
5
+ *
6
+ * Off when any of these says off (the first one found wins):
7
+ * - env `HQ_FLAG_DAEMON_STATE_FILE=false` (also `0`, `off`, `no`), the
8
+ * CLI's local flag override (`HQ_FLAG_<KEY>`); `true` keeps it on and
9
+ * skips the remaining checks except the off file;
10
+ * - the file `~/.hq/daemon-state-file.off` (any file or link at that path);
11
+ * - flag `daemon-state-file` is `false` in the offline flag snapshot
12
+ * (readDefaultOnFlagSnapshot: a default-on kill switch) or in the flag
13
+ * registry answer the daemon just received.
14
+ *
15
+ * Off means: the daemon writes no hq-state.json and no self-check result for
16
+ * it, the daemon folder is not refused for being a link or another user's
17
+ * (ensurePrivateDir falls back to its behavior before #2624), and the engine
18
+ * (crates/hq-hook/src/state.rs, which reads the same env var, file and
19
+ * snapshot flag) does not read the state file.
20
+ *
21
+ * Where the two sides differ (each difference only ever leads to "no fresh
22
+ * state file, use the flag snapshot", so neither can turn the file on):
23
+ * - Scope: with no company uid, the daemon's snapshot read scans every
24
+ * company's snapshot and the person snapshot, so a `false` in any of them
25
+ * stops the writer. The engine reads only the snapshot of its own
26
+ * HQ_COMPANY_UID (or the person snapshot).
27
+ * - Age: the daemon keeps a snapshot `false` however old it is; the engine
28
+ * uses snapshots up to 24 h old.
29
+ * - Registry only: when the switch is turned off only by the registry flag
30
+ * (no env var, no off file, and the hook's snapshot does not hold `false`
31
+ * yet), the engine cannot see it. The daemon removes its own state file
32
+ * when it first sees the switch off (state-file.ts
33
+ * removeDaemonStateFile); if that removal is refused, the engine keeps
34
+ * reading the last file until it expires (600 s, at most 660 s).
35
+ *
36
+ * Read only: nothing here writes a flag.
37
+ */
38
+ export declare const DAEMON_STATE_FILE_FLAG = "daemon-state-file";
39
+ /** The local override, named as the CLI names every `HQ_FLAG_<KEY>` override. */
40
+ export declare const DAEMON_STATE_FILE_ENV = "HQ_FLAG_DAEMON_STATE_FILE";
41
+ /** Under the home folder; any file or link here turns the state file off on this machine. */
42
+ export declare const DAEMON_STATE_FILE_OFF_FILE: string;
43
+ export type DaemonStateFileOffReason = "env" | "file" | "flag";
44
+ export interface DaemonStateFileSwitchOptions {
45
+ env?: NodeJS.ProcessEnv;
46
+ /** Home folder for the off file. Default: HOME (USERPROFILE on Windows), else os.homedir(). */
47
+ home?: string;
48
+ /** The flag value from a registry answer the caller already has (the daemon's poll). */
49
+ registryValue?: unknown;
50
+ /** Replaces the offline snapshot read (tests). */
51
+ readSnapshot?: (env: NodeJS.ProcessEnv) => boolean;
52
+ }
53
+ /** Why the state file is off, or null while it is on (the default). */
54
+ export declare function daemonStateFileOffReason(options?: DaemonStateFileSwitchOptions): DaemonStateFileOffReason | null;
55
+ /** True unless something turns the state file off (see the module comment). */
56
+ export declare function daemonStateFileEnabled(options?: DaemonStateFileSwitchOptions): boolean;
57
+ //# sourceMappingURL=state-file-switch.d.ts.map
@@ -0,0 +1,88 @@
1
+ /**
2
+ * The switch for the daemon's state file (state-file.ts, hq-core-rust US-009).
3
+ * Default ON: with nothing configured the daemon writes the state file and
4
+ * the hook engine reads it, exactly as #2624 shipped.
5
+ *
6
+ * Off when any of these says off (the first one found wins):
7
+ * - env `HQ_FLAG_DAEMON_STATE_FILE=false` (also `0`, `off`, `no`), the
8
+ * CLI's local flag override (`HQ_FLAG_<KEY>`); `true` keeps it on and
9
+ * skips the remaining checks except the off file;
10
+ * - the file `~/.hq/daemon-state-file.off` (any file or link at that path);
11
+ * - flag `daemon-state-file` is `false` in the offline flag snapshot
12
+ * (readDefaultOnFlagSnapshot: a default-on kill switch) or in the flag
13
+ * registry answer the daemon just received.
14
+ *
15
+ * Off means: the daemon writes no hq-state.json and no self-check result for
16
+ * it, the daemon folder is not refused for being a link or another user's
17
+ * (ensurePrivateDir falls back to its behavior before #2624), and the engine
18
+ * (crates/hq-hook/src/state.rs, which reads the same env var, file and
19
+ * snapshot flag) does not read the state file.
20
+ *
21
+ * Where the two sides differ (each difference only ever leads to "no fresh
22
+ * state file, use the flag snapshot", so neither can turn the file on):
23
+ * - Scope: with no company uid, the daemon's snapshot read scans every
24
+ * company's snapshot and the person snapshot, so a `false` in any of them
25
+ * stops the writer. The engine reads only the snapshot of its own
26
+ * HQ_COMPANY_UID (or the person snapshot).
27
+ * - Age: the daemon keeps a snapshot `false` however old it is; the engine
28
+ * uses snapshots up to 24 h old.
29
+ * - Registry only: when the switch is turned off only by the registry flag
30
+ * (no env var, no off file, and the hook's snapshot does not hold `false`
31
+ * yet), the engine cannot see it. The daemon removes its own state file
32
+ * when it first sees the switch off (state-file.ts
33
+ * removeDaemonStateFile); if that removal is refused, the engine keeps
34
+ * reading the last file until it expires (600 s, at most 660 s).
35
+ *
36
+ * Read only: nothing here writes a flag.
37
+ */
38
+ import * as fs from "node:fs";
39
+ import * as os from "node:os";
40
+ import * as path from "node:path";
41
+ import { readDefaultOnFlagSnapshot } from "../flag-snapshot-file.js";
42
+ import { resolveProcessFlagCompanyContext } from "../process-flag-company-context.js";
43
+ export const DAEMON_STATE_FILE_FLAG = "daemon-state-file";
44
+ /** The local override, named as the CLI names every `HQ_FLAG_<KEY>` override. */
45
+ export const DAEMON_STATE_FILE_ENV = "HQ_FLAG_DAEMON_STATE_FILE";
46
+ /** Under the home folder; any file or link here turns the state file off on this machine. */
47
+ export const DAEMON_STATE_FILE_OFF_FILE = path.join(".hq", "daemon-state-file.off");
48
+ const OFF_WORDS = new Set(["false", "0", "off", "no"]);
49
+ const ON_WORDS = new Set(["true", "1", "on", "yes"]);
50
+ function homeOf(env) {
51
+ const fromEnv = (process.platform === "win32" ? env.USERPROFILE : env.HOME)?.trim();
52
+ return fromEnv || os.homedir();
53
+ }
54
+ function offFilePresent(home) {
55
+ try {
56
+ fs.lstatSync(path.join(home, DAEMON_STATE_FILE_OFF_FILE));
57
+ return true;
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ /** False only when a snapshot holds `daemon-state-file: false`; a missing or unreadable snapshot is on. */
64
+ function snapshotAllows(env) {
65
+ const { companyUid } = resolveProcessFlagCompanyContext(env);
66
+ return readDefaultOnFlagSnapshot(DAEMON_STATE_FILE_FLAG, companyUid, env);
67
+ }
68
+ /** Why the state file is off, or null while it is on (the default). */
69
+ export function daemonStateFileOffReason(options = {}) {
70
+ const env = options.env ?? process.env;
71
+ const override = env[DAEMON_STATE_FILE_ENV]?.trim().toLowerCase();
72
+ if (override && OFF_WORDS.has(override))
73
+ return "env";
74
+ if (offFilePresent(options.home ?? homeOf(env)))
75
+ return "file";
76
+ if (override && ON_WORDS.has(override))
77
+ return null;
78
+ if (options.registryValue === false)
79
+ return "flag";
80
+ if (!(options.readSnapshot ?? snapshotAllows)(env))
81
+ return "flag";
82
+ return null;
83
+ }
84
+ /** True unless something turns the state file off (see the module comment). */
85
+ export function daemonStateFileEnabled(options = {}) {
86
+ return daemonStateFileOffReason(options) === null;
87
+ }
88
+ //# sourceMappingURL=state-file-switch.js.map
@@ -0,0 +1,198 @@
1
+ /**
2
+ * The daemon's state file: one JSON file, rewritten atomically after each
3
+ * flag registry request the daemon's timed flag monitors share, that hooks
4
+ * read instead of starting Node or calling the network.
5
+ *
6
+ * It holds three sections and nothing else:
7
+ * - flags: every flag value the registry returned for the daemon's scope
8
+ * (person, or one company uid), with the time the registry answered;
9
+ * - vault_access: per company slug, the caller's role, whether the access
10
+ * list is enforced, and the granted paths with their permission. It is
11
+ * copied from <hqRoot>/.hq/vault-access.json, field by field;
12
+ * - machine_checks: the latest results of the machine checks the daemon has
13
+ * today (id, status, time, optional one-line summary).
14
+ *
15
+ * No token, key or other secret is written. The vault access list tells which
16
+ * companies and paths a person can reach, so the file lives in the per-host
17
+ * daemon folder (~/.hq/daemon, 0700) with mode 0600, never in a repo or a
18
+ * synced folder, and its contents are never logged.
19
+ *
20
+ * The file states its own maximum age. A reader treats a missing, unreadable,
21
+ * truncated, other-schema, expired or future-dated file as stale: guards keep
22
+ * working without it and flag-gated extras use their defaults. The reader is
23
+ * crates/hq-hook/src/state.rs.
24
+ *
25
+ * The writer makes no registry request. It observes the daemon's shared flag
26
+ * snapshot source (flag.ts), so the file holds the same registry answer the
27
+ * kill-switch monitors are decided from, and a kill switch is no later than
28
+ * it is without this file.
29
+ *
30
+ * The file is behind a switch, default on (state-file-switch.ts): flag
31
+ * `daemon-state-file`, env `HQ_FLAG_DAEMON_STATE_FILE=false`, or the file
32
+ * `~/.hq/daemon-state-file.off`. While it is off nothing is written.
33
+ */
34
+ import { type StoreWriteHook } from "./paths.js";
35
+ import type { DaemonFlagRegistryRead } from "./flag.js";
36
+ import type { SelfCheckResult } from "./selfcheck.js";
37
+ import { type DaemonStateFileOffReason } from "./state-file-switch.js";
38
+ export declare const DAEMON_STATE_SCHEMA = "hq-state.v1";
39
+ export declare const DAEMON_STATE_FILE = "hq-state.json";
40
+ /** Written into the file: a reader treats the file, or its flags, as stale past this age. */
41
+ export declare const DAEMON_STATE_MAX_AGE_SECONDS = 600;
42
+ export type DaemonStateFlagValue = boolean | "off" | "shadow" | "on";
43
+ export interface DaemonStateFlagScope {
44
+ /** When the registry answered with these values. */
45
+ fetched_at: string;
46
+ values: Record<string, DaemonStateFlagValue>;
47
+ }
48
+ export interface DaemonStateVaultGrant {
49
+ path: string;
50
+ permission: "read" | "write" | "admin";
51
+ }
52
+ export interface DaemonStateVaultCompany {
53
+ role: "owner" | "admin" | "member" | "guest" | "unknown";
54
+ enforced: boolean;
55
+ grants: DaemonStateVaultGrant[];
56
+ }
57
+ export interface DaemonStateVaultAccess {
58
+ /** When the access list was last refreshed from the server (the manifest's modification time). */
59
+ refreshed_at: string;
60
+ companies: Record<string, DaemonStateVaultCompany>;
61
+ }
62
+ export interface DaemonStateMachineCheck {
63
+ id: string;
64
+ status: "ok" | "warn" | "fail" | "unknown";
65
+ checked_at: string;
66
+ summary?: string;
67
+ }
68
+ export interface DaemonStateFile {
69
+ schema: typeof DAEMON_STATE_SCHEMA;
70
+ written_at: string;
71
+ max_age_seconds: number;
72
+ flags: {
73
+ scopes: Record<string, DaemonStateFlagScope>;
74
+ };
75
+ vault_access: DaemonStateVaultAccess | null;
76
+ machine_checks: {
77
+ results: DaemonStateMachineCheck[];
78
+ };
79
+ }
80
+ /** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
81
+ export declare function daemonStateFilePath(home?: string, env?: NodeJS.ProcessEnv): string;
82
+ /** `<daemon folder>/hq-state.json`: the one state path whose folder the daemon creates and tightens. */
83
+ export declare function defaultDaemonStateFilePath(home?: string, env?: NodeJS.ProcessEnv): string;
84
+ /**
85
+ * A grant path as the access list means it: forward slashes, no empty or `.`
86
+ * segments, a trailing slash kept (it marks a create-only folder). Null for a
87
+ * path that is absolute, empty, too long, or has a `..` segment.
88
+ */
89
+ export declare function normalizeVaultGrantPath(raw: unknown): string | null;
90
+ /** Booleans for every key; a mode string only for a `hook-engine-port-<id>` key (as flag-snapshot-file.ts stores them). */
91
+ export declare function daemonStateFlagValues(flags: Readonly<Record<string, unknown>>): Record<string, DaemonStateFlagValue>;
92
+ /**
93
+ * The vault access section from the manifest refresh-vault-access.sh writes.
94
+ * Only the documented fields are copied, so nothing else in that file can
95
+ * reach the state file. Grant paths are normalized and a path with a `..`
96
+ * segment is dropped. Null when the manifest is missing or not valid, and when
97
+ * it is a symlink, has another link, is not this user's, or group or others can
98
+ * write it, or when its folder is not safe (src/lib/safe-store.ts read rules).
99
+ */
100
+ export declare function readVaultAccessManifest(hqRoot: string | undefined): DaemonStateVaultAccess | null;
101
+ /**
102
+ * The one machine check the daemon has today: the sync-engine self-check. Its
103
+ * latest run's result is written on every run, healthy or not. The unit ids
104
+ * carry vault ids, so only their count reaches the state file.
105
+ */
106
+ export declare function selfCheckMachineChecks(result: SelfCheckResult | null): DaemonStateMachineCheck[];
107
+ /** The exact bytes written: one line of JSON with the keys in schema order. */
108
+ export declare function renderDaemonStateFile(state: DaemonStateFile): string;
109
+ export interface WriteDaemonStateFileDeps {
110
+ platform?: NodeJS.Platform;
111
+ rename?: (from: string, to: string) => void;
112
+ /** Synchronous wait between Windows rename attempts. */
113
+ sleep?: (ms: number) => void;
114
+ /**
115
+ * The daemon's default state file. The writer creates and tightens the
116
+ * folder of that path only; any other folder (HQ_STATE_FILE) is left as it
117
+ * is. Omitted: `file` is treated as the default.
118
+ */
119
+ defaultFile?: string;
120
+ /** Test seam: called at each named point of the write (see src/lib/safe-store.ts). */
121
+ at?: StoreWriteHook;
122
+ }
123
+ /**
124
+ * Write the state file so a reader sees the previous file or the new one,
125
+ * never part of one: a temporary file in the same folder, flushed, then
126
+ * renamed over the destination, through src/lib/safe-store.ts (writeAtomic),
127
+ * which holds the checked folder open and refuses the write if the folder
128
+ * path is replaced; its comment names the remaining window.
129
+ *
130
+ * POSIX rename replaces the destination atomically. On Windows the rename
131
+ * (MoveFileEx with replace) fails with EPERM, EACCES or EBUSY while another
132
+ * process holds the destination open without delete sharing, which a virus
133
+ * scanner can do for a moment. Those failures are retried for about 300 ms.
134
+ * If the rename still fails the previous file stays in place and the error is
135
+ * thrown; the file is never written in place.
136
+ *
137
+ * The temporary file has a random name and is created with O_EXCL|O_NOFOLLOW,
138
+ * and a symlink or hardlink at the destination is replaced by the rename,
139
+ * never written through.
140
+ *
141
+ * The folder must be a real folder (not a symlink) that belongs to this user
142
+ * and is not writable by group or others, or the write is refused. Only the
143
+ * daemon's default folder is created and tightened.
144
+ */
145
+ export declare function writeDaemonStateFile(file: string, state: DaemonStateFile, deps?: WriteDaemonStateFileDeps): void;
146
+ /**
147
+ * The file as written, or null for anything that is not a complete
148
+ * current-schema file, and for a file the shared store rules refuse (a link,
149
+ * a hardlink, not this user's, group or world writable, larger than the
150
+ * engine reads, or in an unsafe folder). Age is not checked.
151
+ */
152
+ export declare function readDaemonStateFile(file: string): DaemonStateFile | null;
153
+ type Log = (level: "info" | "warn" | "error", message: string) => void;
154
+ export interface DaemonStateWriterOptions {
155
+ /** Where the state file is written. */
156
+ file: string;
157
+ /** The daemon's default state file, whose folder this writer may create and tighten. */
158
+ defaultFile?: string;
159
+ log?: Log;
160
+ maxAgeSeconds?: number;
161
+ /** Wall clock for the timestamps written into the file. */
162
+ wallClock?: () => Date;
163
+ /** The vault access section; null when there is none to write. */
164
+ readVaultAccess?: () => DaemonStateVaultAccess | null;
165
+ readMachineChecks?: () => DaemonStateMachineCheck[];
166
+ /** Test seam for the write (Windows rename behavior). */
167
+ writeDeps?: WriteDaemonStateFileDeps;
168
+ /**
169
+ * Why the state file is switched off for this registry answer, or null while
170
+ * it is on. Default: daemonStateFileOffReason (state-file-switch.ts) with the
171
+ * daemon's env and the `daemon-state-file` value the answer carries. While
172
+ * off nothing is written and the daemon folder is not created or checked.
173
+ */
174
+ offReason?: (read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv) => DaemonStateFileOffReason | null;
175
+ }
176
+ export interface DaemonStateWriter {
177
+ /**
178
+ * Pass as `onRead` to createDaemonFlagSnapshotSource. Every registry request
179
+ * the daemon's timed flag monitors share is written to the state file, so the
180
+ * file comes from the same answer the kill switches are decided from and the
181
+ * writer makes no request of its own.
182
+ */
183
+ onRegistryRead(read: DaemonFlagRegistryRead, env: NodeJS.ProcessEnv): void;
184
+ close(): void;
185
+ }
186
+ /**
187
+ * Remove the daemon's own state file when the switch goes off, so a reader
188
+ * that cannot see the off signal (the switch was turned off only by the
189
+ * registry flag, and the hook's flag snapshot does not hold `false` yet) does
190
+ * not keep reading the last file until it expires (600 s, at most 660 s).
191
+ * Only through a checked private folder (src/lib/safe-store.ts: no symlinked,
192
+ * shared or foreign folder) and only a regular single-link file of this user;
193
+ * a link is never followed. Never creates the folder.
194
+ */
195
+ export declare function removeDaemonStateFile(file: string): "removed" | "absent" | "refused";
196
+ export declare function createDaemonStateWriter(options: DaemonStateWriterOptions): DaemonStateWriter;
197
+ export {};
198
+ //# sourceMappingURL=state-file.d.ts.map