@indigoai-us/hq-cli 5.345.215 → 5.345.218

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 (161) hide show
  1. package/CHANGELOG.md +168 -0
  2. package/README.md +46 -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/assets/scaffold/core/scripts/lib/epochrealtime.sh +30 -0
  6. package/assets/scaffold/core/scripts/lib/work-mesh-enqueue.sh +12 -5
  7. package/dist/command-catalog.generated.d.ts +59 -4
  8. package/dist/command-catalog.generated.js +74 -4
  9. package/dist/command-help.js +3 -1
  10. package/dist/command-registration-plan.d.ts +6 -0
  11. package/dist/command-registration-plan.js +1 -0
  12. package/dist/commands/auth.d.ts +1 -1
  13. package/dist/commands/auth.js +11 -52
  14. package/dist/commands/bot.js +11 -4
  15. package/dist/commands/cloud-demote.d.ts +19 -4
  16. package/dist/commands/cloud-demote.js +85 -12
  17. package/dist/commands/cloud-provision.d.ts +5 -1
  18. package/dist/commands/cloud-provision.js +6 -2
  19. package/dist/commands/cloud.d.ts +37 -1
  20. package/dist/commands/cloud.js +110 -27
  21. package/dist/commands/core-hq-session-native.js +3 -0
  22. package/dist/commands/core.js +1 -0
  23. package/dist/commands/daemon.js +4 -1
  24. package/dist/commands/dm.js +7 -0
  25. package/dist/commands/doctor-usage.d.ts +8 -0
  26. package/dist/commands/doctor-usage.js +20 -0
  27. package/dist/commands/doctor.js +7 -1
  28. package/dist/commands/env.d.ts +18 -0
  29. package/dist/commands/env.js +82 -0
  30. package/dist/commands/install-global.js +3 -3
  31. package/dist/commands/lanes.js +100 -24
  32. package/dist/commands/logout.d.ts +7 -0
  33. package/dist/commands/logout.js +41 -34
  34. package/dist/commands/members.js +1 -1
  35. package/dist/commands/pack-start-bot.d.ts +1 -1
  36. package/dist/commands/pack-start-bot.js +2 -2
  37. package/dist/commands/pkg-update.js +1 -1
  38. package/dist/commands/sources.d.ts +8 -2
  39. package/dist/commands/sources.js +65 -9
  40. package/dist/commands/sync-narrow.js +1 -1
  41. package/dist/commands/team-sync.js +1 -1
  42. package/dist/commands/whoami.js +26 -1
  43. package/dist/data/command-states.json +22 -0
  44. package/dist/index.js +52 -4
  45. package/dist/lazy-commands.js +2 -1
  46. package/dist/lib/anywhere-person-setting.d.ts +2 -0
  47. package/dist/lib/anywhere-person-setting.js +6 -3
  48. package/dist/lib/billing/usage-card.d.ts +25 -4
  49. package/dist/lib/billing/usage-card.js +76 -9
  50. package/dist/lib/billing/usage-cost.d.ts +3 -3
  51. package/dist/lib/billing/usage-cost.js +40 -15
  52. package/dist/lib/billing/usage-only.js +4 -2
  53. package/dist/lib/billing/usage-rate-card.d.ts +2 -2
  54. package/dist/lib/billing/usage-rate-card.js +3 -0
  55. package/dist/lib/bot/fleet-cron.js +93 -6
  56. package/dist/lib/bot/inflight.d.ts +9 -0
  57. package/dist/lib/bot/inflight.js +10 -0
  58. package/dist/lib/bot/jobs/hot-signal-sync.js +12 -1
  59. package/dist/lib/bot/pack-link.d.ts +2 -2
  60. package/dist/lib/bot/pack-link.js +2 -2
  61. package/dist/lib/bot/runtime/grok-acp.d.ts +1 -0
  62. package/dist/lib/bot/runtime/grok-acp.js +26 -11
  63. package/dist/lib/bot/runtime/grok.js +1 -1
  64. package/dist/lib/daemon/flag-monitor.d.ts +8 -0
  65. package/dist/lib/daemon/flag-monitor.js +17 -6
  66. package/dist/lib/daemon/flag.d.ts +65 -1
  67. package/dist/lib/daemon/flag.js +190 -40
  68. package/dist/lib/daemon/hook-env.d.ts +32 -0
  69. package/dist/lib/daemon/hook-env.js +51 -0
  70. package/dist/lib/daemon/ops/policy.js +67 -8
  71. package/dist/lib/daemon/paths.d.ts +72 -2
  72. package/dist/lib/daemon/paths.js +154 -3
  73. package/dist/lib/daemon/run.js +32 -21
  74. package/dist/lib/daemon/selfcheck.d.ts +22 -0
  75. package/dist/lib/daemon/selfcheck.js +40 -1
  76. package/dist/lib/daemon/server.d.ts +3 -1
  77. package/dist/lib/daemon/server.js +7 -22
  78. package/dist/lib/daemon/state-file-switch.d.ts +57 -0
  79. package/dist/lib/daemon/state-file-switch.js +88 -0
  80. package/dist/lib/daemon/state-file.d.ts +198 -0
  81. package/dist/lib/daemon/state-file.js +419 -0
  82. package/dist/lib/daemon/timed-flag-monitors.d.ts +47 -0
  83. package/dist/lib/daemon/timed-flag-monitors.js +75 -0
  84. package/dist/lib/doctor/checks/host-core.d.ts +52 -0
  85. package/dist/lib/doctor/checks/host-core.js +337 -0
  86. package/dist/lib/doctor/checks/replay-recorder.d.ts +39 -0
  87. package/dist/lib/doctor/checks/replay-recorder.js +261 -0
  88. package/dist/lib/doctor/checks/sync-runtime.js +3 -3
  89. package/dist/lib/doctor/registry.js +4 -0
  90. package/dist/lib/environment/credential-shapes.d.ts +61 -0
  91. package/dist/lib/environment/credential-shapes.js +333 -0
  92. package/dist/lib/environment/profile.d.ts +239 -0
  93. package/dist/lib/environment/profile.js +239 -0
  94. package/dist/lib/hook-engine/coverage.d.ts +13 -0
  95. package/dist/lib/hook-engine/coverage.js +124 -0
  96. package/dist/lib/hook-engine/reconcile.js +300 -94
  97. package/dist/lib/hook-engine/registration.d.ts +17 -1
  98. package/dist/lib/hook-engine/registration.js +62 -7
  99. package/dist/lib/hot-channels/adapters/slack.d.ts +21 -5
  100. package/dist/lib/hot-channels/adapters/slack.js +64 -21
  101. package/dist/lib/hot-channels/alert.d.ts +2 -0
  102. package/dist/lib/hot-channels/alert.js +8 -1
  103. package/dist/lib/hot-channels/contract.d.ts +12 -0
  104. package/dist/lib/hot-channels/contract.js +7 -0
  105. package/dist/lib/hot-channels/loop.js +1 -0
  106. package/dist/lib/hot-channels/run.d.ts +6 -0
  107. package/dist/lib/hot-channels/run.js +4 -0
  108. package/dist/lib/hot-channels/signals-pass.d.ts +64 -1
  109. package/dist/lib/hot-channels/signals-pass.js +21 -49
  110. package/dist/lib/install/claude-targets.d.ts +12 -1
  111. package/dist/lib/install/claude-targets.js +70 -5
  112. package/dist/lib/install/codex-pack-contributions.js +1 -1
  113. package/dist/lib/install/codex-targets.d.ts +2 -2
  114. package/dist/lib/install/codex-targets.js +48 -5
  115. package/dist/lib/install/hook-target.d.ts +4 -1
  116. package/dist/lib/install/hook-target.js +14 -1
  117. package/dist/lib/lanes/canonical-host.d.ts +35 -0
  118. package/dist/lib/lanes/canonical-host.js +65 -0
  119. package/dist/lib/lanes/host-capacity.d.ts +30 -0
  120. package/dist/lib/lanes/host-capacity.js +29 -3
  121. package/dist/lib/mesh/live/daemon/run.d.ts +2 -0
  122. package/dist/lib/mesh/live/daemon/run.js +5 -2
  123. package/dist/lib/mesh/live/flush.d.ts +5 -1
  124. package/dist/lib/mesh/live/flush.js +12 -6
  125. package/dist/lib/mesh/live/reporting-privacy.d.ts +32 -0
  126. package/dist/lib/mesh/live/reporting-privacy.js +56 -1
  127. package/dist/lib/mesh/live/spool.d.ts +7 -0
  128. package/dist/lib/mesh/live/spool.js +25 -0
  129. package/dist/lib/packages/setup-block.d.ts +2 -2
  130. package/dist/lib/packages/setup-block.js +2 -2
  131. package/dist/lib/packages/start-bot.d.ts +1 -1
  132. package/dist/lib/packages/start-bot.js +1 -1
  133. package/dist/lib/person-setting-cache.d.ts +38 -0
  134. package/dist/lib/person-setting-cache.js +98 -0
  135. package/dist/lib/safe-store.d.ts +245 -0
  136. package/dist/lib/safe-store.js +777 -0
  137. package/dist/lib/signals/engine.d.ts +29 -2
  138. package/dist/lib/signals/engine.js +103 -4
  139. package/dist/lib/signals/reply.js +73 -18
  140. package/dist/lib/signals/steps/adapters.js +7 -2
  141. package/dist/lib/signals/steps/extract.d.ts +13 -0
  142. package/dist/lib/signals/steps/extract.js +84 -4
  143. package/dist/main.js +47 -4
  144. package/dist/schemas/hq-environment-profile.v1.schema.json +438 -0
  145. package/dist/types.d.ts +1 -1
  146. package/dist/utils/auth-expiry.d.ts +8 -0
  147. package/dist/utils/auth-expiry.js +53 -0
  148. package/dist/utils/callback-port-busy.d.ts +1 -1
  149. package/dist/utils/callback-port-busy.js +4 -4
  150. package/dist/utils/cli-telemetry.d.ts +21 -0
  151. package/dist/utils/cli-telemetry.js +34 -0
  152. package/dist/utils/command-usage.d.ts +275 -0
  153. package/dist/utils/command-usage.js +797 -0
  154. package/dist/utils/hook-trust.d.ts +7 -0
  155. package/dist/utils/hook-trust.js +34 -4
  156. package/dist/utils/host-registration.d.ts +179 -0
  157. package/dist/utils/host-registration.js +505 -0
  158. package/dist/utils/resident-package-preload.js +2 -0
  159. package/package.json +10 -8
  160. package/scripts/bench-core.mjs +1096 -0
  161. package/scripts/check-function-manifest.mjs +702 -0
@@ -6,6 +6,8 @@
6
6
  import * as fs from "node:fs";
7
7
  import * as os from "node:os";
8
8
  import * as path from "node:path";
9
+ import { openStoreDir, } from "../safe-store.js";
10
+ import { daemonStateFileEnabled } from "./state-file-switch.js";
9
11
  export function daemonPaths(home = os.homedir(), env = process.env) {
10
12
  const root = env.HQ_DAEMON_DIR?.trim() || path.join(home, ".hq", "daemon");
11
13
  const logsDir = path.join(root, "logs");
@@ -24,10 +26,159 @@ export function daemonPaths(home = os.homedir(), env = process.env) {
24
26
  unitProtocolPath: (unitId) => path.join(root, "protocol", `${unitId.replace(/[^A-Za-z0-9_.-]/g, "-")}.fifo`),
25
27
  };
26
28
  }
27
- /** Create `dir` (and any missing parents) readable only by its owner, and tighten it if it already exists. */
28
- export function ensurePrivateDir(dir) {
29
+ /**
30
+ * Create `dir` (and any missing parents) readable only by its owner, and
31
+ * tighten it if it already exists. The folder is checked before any chmod: it
32
+ * must be a real folder (not a symlink or junction) owned by this user, or
33
+ * EACCES is thrown and nothing is changed. The tightening runs through a
34
+ * descriptor opened with O_DIRECTORY|O_NOFOLLOW (fchmod), so a folder swapped
35
+ * for a link after the check is not followed. Windows, which cannot open a
36
+ * folder, checks by lstat and tightens by path (modes are no-ops there).
37
+ *
38
+ * The check came with the daemon state file (#2624) and sits behind its
39
+ * switch (state-file-switch.ts, default on). With the switch off, a folder the
40
+ * check refuses is handled as before #2624: it is tightened by path with
41
+ * chmod (following a link), and a chmod failure (EPERM on a folder another
42
+ * user owns) is thrown. One exception, which is new and not pre-#2624
43
+ * behavior: for the daemon root itself (`daemonPaths().root`, ~/.hq/daemon or
44
+ * HQ_DAEMON_DIR) a chmod failure is reported on stderr and the folder is used
45
+ * as it is, so a symlinked or foreign-owned daemon root does not stop the
46
+ * daemon. Every other folder (requests, bundle stages, config, logs, ...)
47
+ * still throws. The switch is read only when the check refuses, so the usual
48
+ * call reads no flag.
49
+ */
50
+ export function ensurePrivateDir(dir, options = {}) {
29
51
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
30
- fs.chmodSync(dir, 0o700);
52
+ try {
53
+ tightenCheckedDir(dir);
54
+ }
55
+ catch (error) {
56
+ if (!(error instanceof PrivateDirRefusedError))
57
+ throw error;
58
+ if ((options.stateFileEnabled ?? (() => daemonStateFileEnabled()))())
59
+ throw error;
60
+ const root = options.daemonRoot ?? daemonPaths().root;
61
+ tightenLegacyDir(dir, options.chmod ?? fs.chmodSync, path.resolve(dir) === path.resolve(root));
62
+ }
63
+ }
64
+ /** ensurePrivateDir's refusal of a folder that is a link, not a folder, or another user's. */
65
+ class PrivateDirRefusedError extends Error {
66
+ code = "EACCES";
67
+ }
68
+ /**
69
+ * Before #2624: tighten by path, which follows a link, and throw when that
70
+ * fails. Only the daemon root (`isDaemonRoot`) is used as it is after a failed
71
+ * chmod, with a warning; that part is new with the switch.
72
+ */
73
+ function tightenLegacyDir(dir, chmod, isDaemonRoot) {
74
+ try {
75
+ chmod(dir, 0o700);
76
+ }
77
+ catch (error) {
78
+ if (!isDaemonRoot)
79
+ throw error;
80
+ process.stderr.write(`hq daemon: ${path.basename(dir)} could not be made private (${error.code ?? "error"}); using it as it is\n`);
81
+ }
82
+ }
83
+ function tightenCheckedDir(dir) {
84
+ const refuse = () => {
85
+ throw new PrivateDirRefusedError(`${path.basename(dir)} is not a private folder of this user`);
86
+ };
87
+ const ownedFolder = (stat) => stat.isDirectory() && (typeof process.getuid !== "function" || stat.uid === process.getuid());
88
+ if (!ownedFolder(fs.lstatSync(dir)))
89
+ refuse();
90
+ const { O_RDONLY, O_DIRECTORY, O_NOFOLLOW } = fs.constants;
91
+ if (O_DIRECTORY === undefined || O_NOFOLLOW === undefined) {
92
+ fs.chmodSync(dir, 0o700);
93
+ return;
94
+ }
95
+ let fd;
96
+ try {
97
+ fd = fs.openSync(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
98
+ }
99
+ catch (error) {
100
+ const code = error.code;
101
+ if (code === "ELOOP" || code === "ENOTDIR")
102
+ refuse();
103
+ throw error;
104
+ }
105
+ try {
106
+ const held = fs.fstatSync(fd);
107
+ if (!ownedFolder(held))
108
+ refuse();
109
+ if ((held.mode & 0o777) !== 0o700)
110
+ fs.fchmodSync(fd, 0o700);
111
+ }
112
+ finally {
113
+ fs.closeSync(fd);
114
+ }
115
+ }
116
+ /** A refused store operation as an error: `code` is the safe-store refusal code, or the errno of an io-error. */
117
+ export class StoreRefusedError extends Error {
118
+ code;
119
+ refusal;
120
+ constructor(refused) {
121
+ super(refused.message);
122
+ this.name = "StoreRefusedError";
123
+ this.refusal = refused.code;
124
+ this.code = refused.code === "io-error" && refused.errno ? refused.errno : refused.code;
125
+ }
126
+ }
127
+ /** The store folder itself is unusable: a link, not a folder, foreign, shared, or under an unsafe parent. */
128
+ export function isUnsafeFolderRefusal(code) {
129
+ return code === "folder-link" || code === "not-a-folder" || code === "folder-foreign-owner"
130
+ || code === "folder-writable" || code === "parent-unsafe";
131
+ }
132
+ /**
133
+ * Replace `file` with `text` through src/lib/safe-store.ts: the folder is held
134
+ * open and checked, the temporary file has a random name and O_EXCL, and the
135
+ * write is refused if the folder path is replaced (the helper's comment names
136
+ * the remaining window). A refusal is thrown as StoreRefusedError.
137
+ */
138
+ export function writeStoreFile(file, text, options = {}) {
139
+ const opened = openStoreDir(path.dirname(file), {
140
+ ...(options.create ? { create: true } : {}),
141
+ ...(options.at ? { at: options.at } : {}),
142
+ ...(options.platform ? { platform: options.platform } : {}),
143
+ });
144
+ if (!opened.ok)
145
+ throw new StoreRefusedError(opened);
146
+ const store = opened.value;
147
+ try {
148
+ const written = store.writeAtomic(path.basename(file), text, {
149
+ retryDelaysMs: options.renameRetryDelaysMs ?? [],
150
+ ...(options.sleep ? { sleep: options.sleep } : {}),
151
+ ...(options.renameFile ? { renameFile: options.renameFile } : {}),
152
+ });
153
+ if (!written.ok)
154
+ throw new StoreRefusedError(written);
155
+ }
156
+ finally {
157
+ store.close();
158
+ }
159
+ }
160
+ /**
161
+ * A small file's contents and modification time, read through
162
+ * src/lib/safe-store.ts (a regular single-link file of this user in a checked
163
+ * folder, opened without following a link), or null when it is missing,
164
+ * refused or larger than `maxBytes`.
165
+ */
166
+ export function readStoreFile(file, maxBytes) {
167
+ // mtimeMs is whole milliseconds, floored from the exact nanoseconds.
168
+ const opened = openStoreDir(path.dirname(file));
169
+ if (!opened.ok)
170
+ return null;
171
+ const store = opened.value;
172
+ try {
173
+ // The bytes and the modification time come from the same opened file.
174
+ const read = store.readWithFacts(path.basename(file), { maxBytes });
175
+ if (!read.ok)
176
+ return null;
177
+ return { text: read.value.data.toString("utf8"), mtimeMs: Number(read.value.facts.mtimeNs / 1000000n) };
178
+ }
179
+ finally {
180
+ store.close();
181
+ }
31
182
  }
32
183
  /** Open a log file for appending, creating it (and its folder) owner-only. */
33
184
  export function openPrivateAppend(file) {
@@ -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,10 +46,13 @@ 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";
53
54
  import { heartbeatFile, startHeartbeat } from "./heartbeat.js";
55
+ import { daemonStartEnv } from "./hook-env.js";
54
56
  import { createProtocolTail, ensureProtocolFifo, openProtocolWriter } from "./protocol-tail.js";
55
57
  import { takeControlRequests } from "./requests.js";
56
58
  import { currentHqCloud, currentHqCloudAfterLeaseRelease, hqCloudRunners, hqCloudVersionOlder } from "./hq-cloud.js";
@@ -651,7 +653,9 @@ export function withUserRuntimeDir(env, host) {
651
653
  return host.exists(dir) ? { ...env, XDG_RUNTIME_DIR: dir } : env;
652
654
  }
653
655
  export async function runDaemon(opts) {
654
- const env = withUserRuntimeDir(opts.env ?? process.env, {
656
+ // Before anything reads the environment: hqd and every service inherit it.
657
+ const started = daemonStartEnv(opts.env);
658
+ const env = withUserRuntimeDir(started.env, {
655
659
  platform: process.platform,
656
660
  uid: process.getuid?.() ?? -1,
657
661
  exists: fs.existsSync,
@@ -746,6 +750,9 @@ export async function runDaemon(opts) {
746
750
  }
747
751
  const hostNote = opts.host ? `, hosted by the ${opts.host} app` : "";
748
752
  log("info", `starting hq daemon (pid ${process.pid}) as ${machineType} (${detected.detail})${hostNote}`);
753
+ if (started.removed.length > 0) {
754
+ log("warn", `started with hook fields in the environment; dropped them so policy checks use their own payload: ${started.removed.join(", ")}`);
755
+ }
749
756
  try {
750
757
  scheduleDaemonPlistRefresh({
751
758
  platform,
@@ -905,20 +912,24 @@ export async function runDaemon(opts) {
905
912
  };
906
913
  const daemonSyncRunnerPids = new Set();
907
914
  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"})`),
915
+ // One registry request per 30-second tick decides every timed daemon flag.
916
+ // The same request also refreshes the state file hooks read (state-file.ts).
917
+ const stateWriter = createDaemonStateWriter({
918
+ file: daemonStateFilePath(home, env),
919
+ defaultFile: defaultDaemonStateFilePath(home, env),
920
+ log,
921
+ readVaultAccess: () => {
922
+ const configured = readDaemonConfig(paths.configPath).hqRoot ?? (env.HQ_ROOT?.trim() || undefined);
923
+ return readVaultAccessManifest(configured && fs.existsSync(configured) ? configured : undefined);
924
+ },
925
+ readMachineChecks: () => selfCheckMachineChecks(readSelfCheckResult(path.join(paths.root, SELF_CHECK_RESULT_FILE))),
917
926
  });
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);
927
+ const flagSnapshots = createDaemonFlagSnapshotSource({ onRead: stateWriter.onRegistryRead });
928
+ const killSwitches = createDaemonKillSwitchMonitors({ env, log, snapshots: flagSnapshots });
929
+ const childBootstrapHandoffWatchFlag = killSwitches.childBootstrapHandoffWatch;
930
+ const lanesReconcileFileWatchFlag = killSwitches.lanesReconcileFileWatch;
931
+ const searchIndexRunnerOwnsIndexFlag = killSwitches.searchIndexRunnerOwnsIndex;
932
+ const syncProcessScanOnMissingFlag = killSwitches.syncProcessScanOnMissing;
922
933
  let laneReconcileWatcher = null;
923
934
  let laneReconcileWatcherRoot = null;
924
935
  let laneReconcileWatchFailedRoot = null;
@@ -945,10 +956,9 @@ export async function runDaemon(opts) {
945
956
  laneReconcileWatcher?.close();
946
957
  laneReconcileWatcher = null;
947
958
  laneReconcileWatcherRoot = null;
948
- childBootstrapHandoffWatchFlag.close();
949
- lanesReconcileFileWatchFlag.close();
950
- searchIndexRunnerOwnsIndexFlag.close();
951
- syncProcessScanOnMissingFlag.close();
959
+ killSwitches.close();
960
+ flagSnapshots.close();
961
+ stateWriter.close();
952
962
  };
953
963
  const plan = () => {
954
964
  const config = readDaemonConfig(paths.configPath);
@@ -1477,6 +1487,7 @@ export async function runDaemon(opts) {
1477
1487
  registryPath: registryFile(registryDir(home, env)),
1478
1488
  hqRoot,
1479
1489
  log,
1490
+ flagSnapshots,
1480
1491
  onShutdown: () => hqdShutdown?.(),
1481
1492
  reportError: reportHqdCrash,
1482
1493
  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