@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
@@ -0,0 +1,419 @@
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 * as fs from "node:fs";
35
+ import * as path from "node:path";
36
+ import { openStoreDir } from "../safe-store.js";
37
+ import { resolveProcessFlagCompanyContext } from "../flag-registry.js";
38
+ import { daemonPaths, isUnsafeFolderRefusal, readStoreFile, StoreRefusedError, writeStoreFile } from "./paths.js";
39
+ import { DAEMON_STATE_FILE_FLAG, daemonStateFileOffReason } from "./state-file-switch.js";
40
+ export const DAEMON_STATE_SCHEMA = "hq-state.v1";
41
+ export const DAEMON_STATE_FILE = "hq-state.json";
42
+ /** Written into the file: a reader treats the file, or its flags, as stale past this age. */
43
+ export const DAEMON_STATE_MAX_AGE_SECONDS = 600;
44
+ const WINDOWS_RENAME_RETRY_DELAYS_MS = [10, 20, 40, 80, 160];
45
+ /** The engine reads at most this much of the state file (MAX_FILE_BYTES in crates/hq-hook/src/state.rs). */
46
+ const MAX_STATE_FILE_BYTES = 8 * 1024 * 1024;
47
+ /** The vault access manifest is small; a larger file is not read. */
48
+ const MAX_MANIFEST_BYTES = 8 * 1024 * 1024;
49
+ const PERSON_SCOPE = "person";
50
+ const COMPANY_UID_RE = /^cmp_[A-Za-z0-9]{3,128}$/;
51
+ const COMPANY_SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
52
+ const HOOK_ENGINE_PORT_FLAG_PREFIX = "hook-engine-port-";
53
+ const HOOK_ENGINE_PORT_MODES = new Set(["off", "shadow", "on"]);
54
+ const VAULT_PERMISSIONS = new Set(["read", "write", "admin"]);
55
+ const VAULT_ROLES = new Set(["owner", "admin", "member", "guest", "unknown"]);
56
+ const MACHINE_CHECK_STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
57
+ /** `HQ_STATE_FILE` when set (tests and isolated daemons), else `<daemon folder>/hq-state.json`. */
58
+ export function daemonStateFilePath(home, env = process.env) {
59
+ const explicit = env.HQ_STATE_FILE?.trim();
60
+ if (explicit)
61
+ return explicit;
62
+ return defaultDaemonStateFilePath(home, env);
63
+ }
64
+ /** `<daemon folder>/hq-state.json`: the one state path whose folder the daemon creates and tightens. */
65
+ export function defaultDaemonStateFilePath(home, env = process.env) {
66
+ return path.join(daemonPaths(home, env).root, DAEMON_STATE_FILE);
67
+ }
68
+ /**
69
+ * A grant path as the access list means it: forward slashes, no empty or `.`
70
+ * segments, a trailing slash kept (it marks a create-only folder). Null for a
71
+ * path that is absolute, empty, too long, or has a `..` segment.
72
+ */
73
+ export function normalizeVaultGrantPath(raw) {
74
+ if (typeof raw !== "string" || !raw || raw.length > 1024 || raw.includes("\0"))
75
+ return null;
76
+ const slashed = raw.replace(/\\/g, "/");
77
+ if (slashed.startsWith("/") || /^[A-Za-z]:/.test(slashed))
78
+ return null;
79
+ const segments = slashed.split("/").filter((segment) => segment !== "" && segment !== ".");
80
+ if (segments.length === 0 || segments.includes(".."))
81
+ return null;
82
+ return segments.join("/") + (slashed.endsWith("/") ? "/" : "");
83
+ }
84
+ function isRecord(value) {
85
+ return typeof value === "object" && value !== null && !Array.isArray(value);
86
+ }
87
+ function isIsoTime(value) {
88
+ return typeof value === "string" && Number.isFinite(Date.parse(value));
89
+ }
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 function daemonStateFlagValues(flags) {
92
+ const values = {};
93
+ for (const key of Object.keys(flags).sort()) {
94
+ const value = flags[key];
95
+ if (!key.trim())
96
+ continue;
97
+ if (typeof value === "boolean")
98
+ values[key] = value;
99
+ else if (key.startsWith(HOOK_ENGINE_PORT_FLAG_PREFIX)
100
+ && key.length > HOOK_ENGINE_PORT_FLAG_PREFIX.length
101
+ && HOOK_ENGINE_PORT_MODES.has(value))
102
+ values[key] = value;
103
+ }
104
+ return values;
105
+ }
106
+ /**
107
+ * The vault access section from the manifest refresh-vault-access.sh writes.
108
+ * Only the documented fields are copied, so nothing else in that file can
109
+ * reach the state file. Grant paths are normalized and a path with a `..`
110
+ * segment is dropped. Null when the manifest is missing or not valid, and when
111
+ * it is a symlink, has another link, is not this user's, or group or others can
112
+ * write it, or when its folder is not safe (src/lib/safe-store.ts read rules).
113
+ */
114
+ export function readVaultAccessManifest(hqRoot) {
115
+ if (!hqRoot)
116
+ return null;
117
+ const read = readStoreFile(path.join(hqRoot, ".hq", "vault-access.json"), MAX_MANIFEST_BYTES);
118
+ if (!read)
119
+ return null;
120
+ let parsed;
121
+ try {
122
+ parsed = JSON.parse(read.text);
123
+ }
124
+ catch {
125
+ return null;
126
+ }
127
+ const refreshedAt = new Date(read.mtimeMs).toISOString();
128
+ if (!isRecord(parsed) || parsed.version !== 1 || !isRecord(parsed.companies))
129
+ return null;
130
+ const companies = {};
131
+ for (const slug of Object.keys(parsed.companies).sort()) {
132
+ const entry = parsed.companies[slug];
133
+ if (!COMPANY_SLUG_RE.test(slug) || !isRecord(entry))
134
+ continue;
135
+ const grants = [];
136
+ for (const grant of Array.isArray(entry.grants) ? entry.grants : []) {
137
+ if (!isRecord(grant) || !VAULT_PERMISSIONS.has(grant.permission))
138
+ continue;
139
+ const grantPath = normalizeVaultGrantPath(grant.path);
140
+ if (grantPath === null)
141
+ continue;
142
+ grants.push({ path: grantPath, permission: grant.permission });
143
+ }
144
+ companies[slug] = {
145
+ role: (VAULT_ROLES.has(entry.role) ? entry.role : "unknown"),
146
+ enforced: entry.enforced !== false,
147
+ grants,
148
+ };
149
+ }
150
+ return { refreshed_at: refreshedAt, companies };
151
+ }
152
+ /**
153
+ * The one machine check the daemon has today: the sync-engine self-check. Its
154
+ * latest run's result is written on every run, healthy or not. The unit ids
155
+ * carry vault ids, so only their count reaches the state file.
156
+ */
157
+ export function selfCheckMachineChecks(result) {
158
+ if (!result)
159
+ return [];
160
+ return [{
161
+ id: "sync-core-selfcheck",
162
+ status: result.problems > 0 ? "warn" : "ok",
163
+ checked_at: new Date(result.checkedAt).toISOString(),
164
+ summary: `${result.problems} sync engine unit(s) needed attention`,
165
+ }];
166
+ }
167
+ function machineChecksOf(results) {
168
+ const out = [];
169
+ for (const result of results) {
170
+ if (!isRecord(result) || typeof result.id !== "string" || !result.id.trim())
171
+ continue;
172
+ if (!MACHINE_CHECK_STATUSES.has(result.status) || !isIsoTime(result.checked_at))
173
+ continue;
174
+ out.push({
175
+ id: result.id,
176
+ status: result.status,
177
+ checked_at: result.checked_at,
178
+ ...(typeof result.summary === "string" && result.summary ? { summary: result.summary.slice(0, 240) } : {}),
179
+ });
180
+ }
181
+ return out;
182
+ }
183
+ /** The exact bytes written: one line of JSON with the keys in schema order. */
184
+ export function renderDaemonStateFile(state) {
185
+ const scopes = {};
186
+ for (const scope of Object.keys(state.flags.scopes).sort()) {
187
+ const entry = state.flags.scopes[scope];
188
+ scopes[scope] = { fetched_at: entry.fetched_at, values: daemonStateFlagValues(entry.values) };
189
+ }
190
+ const ordered = {
191
+ schema: DAEMON_STATE_SCHEMA,
192
+ written_at: state.written_at,
193
+ max_age_seconds: state.max_age_seconds,
194
+ flags: { scopes },
195
+ vault_access: state.vault_access
196
+ ? { refreshed_at: state.vault_access.refreshed_at, companies: state.vault_access.companies }
197
+ : null,
198
+ machine_checks: { results: machineChecksOf(state.machine_checks.results) },
199
+ };
200
+ return `${JSON.stringify(ordered)}\n`;
201
+ }
202
+ /**
203
+ * Write the state file so a reader sees the previous file or the new one,
204
+ * never part of one: a temporary file in the same folder, flushed, then
205
+ * renamed over the destination, through src/lib/safe-store.ts (writeAtomic),
206
+ * which holds the checked folder open and refuses the write if the folder
207
+ * path is replaced; its comment names the remaining window.
208
+ *
209
+ * POSIX rename replaces the destination atomically. On Windows the rename
210
+ * (MoveFileEx with replace) fails with EPERM, EACCES or EBUSY while another
211
+ * process holds the destination open without delete sharing, which a virus
212
+ * scanner can do for a moment. Those failures are retried for about 300 ms.
213
+ * If the rename still fails the previous file stays in place and the error is
214
+ * thrown; the file is never written in place.
215
+ *
216
+ * The temporary file has a random name and is created with O_EXCL|O_NOFOLLOW,
217
+ * and a symlink or hardlink at the destination is replaced by the rename,
218
+ * never written through.
219
+ *
220
+ * The folder must be a real folder (not a symlink) that belongs to this user
221
+ * and is not writable by group or others, or the write is refused. Only the
222
+ * daemon's default folder is created and tightened.
223
+ */
224
+ export function writeDaemonStateFile(file, state, deps = {}) {
225
+ const ownFolder = deps.defaultFile === undefined || path.resolve(deps.defaultFile) === path.resolve(file);
226
+ const platform = deps.platform ?? process.platform;
227
+ try {
228
+ writeStoreFile(file, renderDaemonStateFile(state), {
229
+ create: ownFolder,
230
+ platform,
231
+ ...(deps.rename ? { renameFile: deps.rename } : {}),
232
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
233
+ ...(deps.at ? { at: deps.at } : {}),
234
+ renameRetryDelaysMs: platform === "win32" ? WINDOWS_RENAME_RETRY_DELAYS_MS : [],
235
+ });
236
+ }
237
+ catch (error) {
238
+ if (!(error instanceof StoreRefusedError) || !isUnsafeFolderRefusal(error.refusal))
239
+ throw error;
240
+ throw Object.assign(new Error("state file folder is not a private folder of this user"), { code: "EACCES" });
241
+ }
242
+ }
243
+ /**
244
+ * The file as written, or null for anything that is not a complete
245
+ * current-schema file, and for a file the shared store rules refuse (a link,
246
+ * a hardlink, not this user's, group or world writable, larger than the
247
+ * engine reads, or in an unsafe folder). Age is not checked.
248
+ */
249
+ export function readDaemonStateFile(file) {
250
+ const read = readStoreFile(file, MAX_STATE_FILE_BYTES);
251
+ if (!read)
252
+ return null;
253
+ let parsed;
254
+ try {
255
+ parsed = JSON.parse(read.text);
256
+ }
257
+ catch {
258
+ return null;
259
+ }
260
+ if (!isRecord(parsed) || parsed.schema !== DAEMON_STATE_SCHEMA || !isIsoTime(parsed.written_at))
261
+ return null;
262
+ if (typeof parsed.max_age_seconds !== "number" || !(parsed.max_age_seconds > 0))
263
+ return null;
264
+ if (!isRecord(parsed.flags) || !isRecord(parsed.flags.scopes))
265
+ return null;
266
+ const scopes = {};
267
+ for (const [scope, entry] of Object.entries(parsed.flags.scopes)) {
268
+ if (scope !== PERSON_SCOPE && !COMPANY_UID_RE.test(scope))
269
+ return null;
270
+ if (!isRecord(entry) || !isIsoTime(entry.fetched_at) || !isRecord(entry.values))
271
+ return null;
272
+ scopes[scope] = { fetched_at: entry.fetched_at, values: daemonStateFlagValues(entry.values) };
273
+ }
274
+ const vault = parsed.vault_access;
275
+ const checks = isRecord(parsed.machine_checks) && Array.isArray(parsed.machine_checks.results)
276
+ ? machineChecksOf(parsed.machine_checks.results)
277
+ : [];
278
+ return {
279
+ schema: DAEMON_STATE_SCHEMA,
280
+ written_at: parsed.written_at,
281
+ max_age_seconds: parsed.max_age_seconds,
282
+ flags: { scopes },
283
+ vault_access: isRecord(vault) && isIsoTime(vault.refreshed_at) && isRecord(vault.companies)
284
+ ? { refreshed_at: vault.refreshed_at, companies: vault.companies }
285
+ : null,
286
+ machine_checks: { results: checks },
287
+ };
288
+ }
289
+ /** `person`, a company uid, or null for a slug that resolves to no uid (its flags are not written). */
290
+ function daemonFlagScope(env) {
291
+ const company = resolveProcessFlagCompanyContext(env);
292
+ return company.companyUid ?? (company.companySlug ? null : PERSON_SCOPE);
293
+ }
294
+ /**
295
+ * Remove the daemon's own state file when the switch goes off, so a reader
296
+ * that cannot see the off signal (the switch was turned off only by the
297
+ * registry flag, and the hook's flag snapshot does not hold `false` yet) does
298
+ * not keep reading the last file until it expires (600 s, at most 660 s).
299
+ * Only through a checked private folder (src/lib/safe-store.ts: no symlinked,
300
+ * shared or foreign folder) and only a regular single-link file of this user;
301
+ * a link is never followed. Never creates the folder.
302
+ */
303
+ export function removeDaemonStateFile(file) {
304
+ const opened = openStoreDir(path.dirname(file));
305
+ if (!opened.ok)
306
+ return opened.code === "folder-missing" ? "absent" : "refused";
307
+ const store = opened.value;
308
+ try {
309
+ let stat;
310
+ try {
311
+ stat = fs.lstatSync(file);
312
+ }
313
+ catch (error) {
314
+ if (error.code === "ENOENT")
315
+ return "absent";
316
+ throw error;
317
+ }
318
+ const mine = typeof process.getuid !== "function" || stat.uid === process.getuid();
319
+ if (!stat.isFile() || stat.nlink !== 1 || !mine)
320
+ return "refused";
321
+ const removed = store.remove(path.basename(file));
322
+ if (!removed.ok)
323
+ return "refused";
324
+ return removed.value ? "removed" : "absent";
325
+ }
326
+ finally {
327
+ store.close();
328
+ }
329
+ }
330
+ /** The switch for one registry answer: the local signals, then the value the answer carries. */
331
+ function defaultOffReason(read, env) {
332
+ const answered = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
333
+ return daemonStateFileOffReason({ env, registryValue: answered?.flags[DAEMON_STATE_FILE_FLAG] });
334
+ }
335
+ export function createDaemonStateWriter(options) {
336
+ const maxAgeSeconds = options.maxAgeSeconds ?? DAEMON_STATE_MAX_AGE_SECONDS;
337
+ const wallClock = options.wallClock ?? (() => new Date());
338
+ const log = options.log ?? (() => { });
339
+ let closed = false;
340
+ let lastProblem;
341
+ // The file left from before the switch went off is removed once per off period.
342
+ let removedWhileOff = false;
343
+ const ownFile = options.defaultFile === undefined || path.resolve(options.defaultFile) === path.resolve(options.file);
344
+ const report = (problem, level = "warn") => {
345
+ if (problem === lastProblem)
346
+ return;
347
+ lastProblem = problem;
348
+ if (problem)
349
+ log(level, `state file: ${problem}`);
350
+ else
351
+ log("info", "state file: written again");
352
+ };
353
+ const errorName = (error) => (error instanceof Error ? error.name : "UnknownError");
354
+ return {
355
+ onRegistryRead(read, env) {
356
+ if (closed)
357
+ return;
358
+ try {
359
+ const snapshot = !read.signedOut && read.errors.length === 0 ? read.client?.snapshot?.() ?? null : null;
360
+ const off = (options.offReason ?? defaultOffReason)(read, env);
361
+ if (off) {
362
+ let removed = "";
363
+ if (!removedWhileOff && ownFile) {
364
+ removedWhileOff = true;
365
+ const outcome = removeDaemonStateFile(options.file);
366
+ if (outcome === "removed")
367
+ removed = "; the previous file was removed";
368
+ else if (outcome === "refused")
369
+ removed = "; the previous file was left in place (not a private file of this user)";
370
+ }
371
+ report(`switched off (${off}); not written${removed}`, "info");
372
+ return;
373
+ }
374
+ removedWhileOff = false;
375
+ const now = wallClock();
376
+ const scope = daemonFlagScope(env);
377
+ // The file holds only what this request returned, for the daemon's own
378
+ // scope. Nothing is carried from the file on disk or from an earlier
379
+ // request: a file planted or loosened by another process is never
380
+ // rewritten as the daemon's own, and when the daemon is signed out or
381
+ // the request failed the flags are absent, so readers use each flag's
382
+ // default.
383
+ const scopes = {};
384
+ if (snapshot && scope) {
385
+ scopes[scope] = { fetched_at: now.toISOString(), values: daemonStateFlagValues(snapshot.flags) };
386
+ }
387
+ try {
388
+ writeDaemonStateFile(options.file, {
389
+ schema: DAEMON_STATE_SCHEMA,
390
+ written_at: now.toISOString(),
391
+ max_age_seconds: maxAgeSeconds,
392
+ flags: { scopes },
393
+ vault_access: options.readVaultAccess?.() ?? null,
394
+ machine_checks: { results: options.readMachineChecks?.() ?? [] },
395
+ }, { ...options.writeDeps, ...(options.defaultFile ? { defaultFile: options.defaultFile } : {}) });
396
+ }
397
+ catch (error) {
398
+ // Never the contents: the file holds the vault access list.
399
+ const code = error.code;
400
+ report(`could not be written (${typeof code === "string" ? code : errorName(error)}); readers keep the previous file`);
401
+ return;
402
+ }
403
+ if (read.signedOut)
404
+ report("signed out; flags are absent");
405
+ else if (!snapshot)
406
+ report(`flag registry read failed (${errorName(read.errors[0])}); flags are absent`);
407
+ else
408
+ report(undefined);
409
+ }
410
+ catch {
411
+ // a failing section reader or log sink cannot reach the flag read that called this
412
+ }
413
+ },
414
+ close() {
415
+ closed = true;
416
+ },
417
+ };
418
+ }
419
+ //# sourceMappingURL=state-file.js.map
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The daemon's timed flag monitors: the four default-on kill switches read by
3
+ * the supervisor loop, and the HQ Anywhere runtime gate read by the hqd
4
+ * socket server. They are built here, apart from run.ts and server.ts, so the
5
+ * call-budget test (daemon-call-budget.test.ts) drives the same construction
6
+ * the daemon uses.
7
+ *
8
+ * Every monitor refreshes on the shared source's timer and reads the shared
9
+ * source's snapshot, so one 30-second tick costs one registry request however
10
+ * many flags are watched.
11
+ */
12
+ import { type BoundedDaemonFlagMonitor, type BoundedDaemonFlagMonitorOptions } from "./flag-monitor.js";
13
+ import { type DaemonFlagSnapshotSource, type ReadDaemonFlagOptions } from "./flag.js";
14
+ type Log = (level: "info" | "warn" | "error", message: string) => void;
15
+ export interface DaemonKillSwitchMonitors {
16
+ childBootstrapHandoffWatch: BoundedDaemonFlagMonitor;
17
+ lanesReconcileFileWatch: BoundedDaemonFlagMonitor;
18
+ searchIndexRunnerOwnsIndex: BoundedDaemonFlagMonitor;
19
+ syncProcessScanOnMissing: BoundedDaemonFlagMonitor;
20
+ close(): void;
21
+ }
22
+ export interface DaemonKillSwitchMonitorOptions {
23
+ env: NodeJS.ProcessEnv;
24
+ log: Log;
25
+ /** Omit to give each monitor its own timer and its own registry request (the behavior before sharing). */
26
+ snapshots?: DaemonFlagSnapshotSource;
27
+ /** Test seam for the registry request. */
28
+ readOptions?: Pick<ReadDaemonFlagOptions, "createClient" | "getToken">;
29
+ }
30
+ /** One default-on kill switch per daemon behavior that can be turned off from the registry. */
31
+ export declare function createDaemonKillSwitchMonitors(options: DaemonKillSwitchMonitorOptions): DaemonKillSwitchMonitors;
32
+ export interface HqdRuntimeFlagMonitorOptions {
33
+ env: NodeJS.ProcessEnv;
34
+ log: Log;
35
+ /** Omit to keep this monitor on its own timer and its own registry request. */
36
+ snapshots?: DaemonFlagSnapshotSource;
37
+ /** Test seam for the live hq-flags read. */
38
+ runtimeFlagReader?: (options: ReadDaemonFlagOptions) => Promise<boolean>;
39
+ /** Test seam for the human opt-in setting; production reads hq-pro. */
40
+ personSettingReader?: () => Promise<boolean | null>;
41
+ onChange?: BoundedDaemonFlagMonitorOptions["onChange"];
42
+ onReadError?: BoundedDaemonFlagMonitorOptions["onReadError"];
43
+ }
44
+ /** hqd's HQ Anywhere gate: the operator flag, then the person's own setting while the flag is on. */
45
+ export declare function createHqdRuntimeFlagMonitor(options: HqdRuntimeFlagMonitorOptions): BoundedDaemonFlagMonitor;
46
+ export {};
47
+ //# sourceMappingURL=timed-flag-monitors.d.ts.map
@@ -0,0 +1,75 @@
1
+ /**
2
+ * The daemon's timed flag monitors: the four default-on kill switches read by
3
+ * the supervisor loop, and the HQ Anywhere runtime gate read by the hqd
4
+ * socket server. They are built here, apart from run.ts and server.ts, so the
5
+ * call-budget test (daemon-call-budget.test.ts) drives the same construction
6
+ * the daemon uses.
7
+ *
8
+ * Every monitor refreshes on the shared source's timer and reads the shared
9
+ * source's snapshot, so one 30-second tick costs one registry request however
10
+ * many flags are watched.
11
+ */
12
+ import { HQ_ANYWHERE_RUNTIME_FLAG } from "../anywhere-runtime-flag-key.js";
13
+ import { readHqAnywherePersonSetting } from "../anywhere-person-setting.js";
14
+ import { createBoundedDaemonFlagMonitor, } from "./flag-monitor.js";
15
+ import { readDaemonFlag } from "./flag.js";
16
+ 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";
17
+ /** One default-on kill switch per daemon behavior that can be turned off from the registry. */
18
+ export function createDaemonKillSwitchMonitors(options) {
19
+ const { env, log, snapshots } = options;
20
+ const monitor = (flagKey) => createBoundedDaemonFlagMonitor({
21
+ fallback: true,
22
+ read: () => readDaemonFlag(flagKey, {
23
+ env,
24
+ fallback: true,
25
+ localOverrideMode: "ignore",
26
+ throwOnError: true,
27
+ ...options.readOptions,
28
+ ...(snapshots ? { snapshots } : {}),
29
+ }),
30
+ onReadError: (error) => log("warn", `could not read ${flagKey}; keeping its default-on behavior (${error instanceof Error ? error.name : "UnknownError"})`),
31
+ ...(snapshots ? { scheduleRefresh: (tick) => snapshots.schedule(tick) } : {}),
32
+ });
33
+ const monitors = {
34
+ childBootstrapHandoffWatch: monitor(DAEMON_CHILD_BOOTSTRAP_HANDOFF_WATCH_FLAG),
35
+ lanesReconcileFileWatch: monitor(DAEMON_LANES_RECONCILE_FILE_WATCH_FLAG),
36
+ searchIndexRunnerOwnsIndex: monitor(DAEMON_SEARCH_INDEX_RUNNER_OWNS_INDEX_FLAG),
37
+ syncProcessScanOnMissing: monitor(DAEMON_SYNC_PROCESS_SCAN_ON_MISSING_FLAG),
38
+ };
39
+ return {
40
+ ...monitors,
41
+ close() {
42
+ for (const each of Object.values(monitors))
43
+ each.close();
44
+ },
45
+ };
46
+ }
47
+ /** hqd's HQ Anywhere gate: the operator flag, then the person's own setting while the flag is on. */
48
+ export function createHqdRuntimeFlagMonitor(options) {
49
+ const { env, log, snapshots } = options;
50
+ return createBoundedDaemonFlagMonitor({
51
+ read: async () => {
52
+ const readOptions = {
53
+ env,
54
+ throwOnError: true,
55
+ // A local opt-out is honored, while a local opt-in cannot override the operator kill switch.
56
+ localOverrideMode: "off-only",
57
+ ...(snapshots ? { snapshots } : {}),
58
+ };
59
+ const flagEnabled = await (options.runtimeFlagReader
60
+ ? options.runtimeFlagReader(readOptions)
61
+ : readDaemonFlag(HQ_ANYWHERE_RUNTIME_FLAG, readOptions));
62
+ if (!flagEnabled)
63
+ return false;
64
+ const personSetting = await (options.personSettingReader ?? (() => readHqAnywherePersonSetting({
65
+ env,
66
+ onError: (name) => log("warn", `hqd person setting refresh failed (${name}); keeping HQ Anywhere off`),
67
+ })))();
68
+ return personSetting === true;
69
+ },
70
+ ...(options.onChange ? { onChange: options.onChange } : {}),
71
+ ...(options.onReadError ? { onReadError: options.onReadError } : {}),
72
+ ...(snapshots ? { scheduleRefresh: (tick) => snapshots.schedule(tick) } : {}),
73
+ });
74
+ }
75
+ //# sourceMappingURL=timed-flag-monitors.js.map
@@ -0,0 +1,50 @@
1
+ import { type EngineCapabilities } from '../../../utils/host-registration.js';
2
+ import type { CheckContext, CheckResult, FamilyRun } from '../types.js';
3
+ import { type DoctorRegistry } from '../registry.js';
4
+ export declare const HOST_CORE_FAMILY_ID = "host-core";
5
+ export declare const HOST_CORE_FAMILY_TITLE = "Hook core per host";
6
+ export type CoreKind = 'new-core' | 'launcher' | 'old-dispatcher';
7
+ export interface HostRegistrationFile {
8
+ host: 'claude' | 'codex' | 'grok';
9
+ scope: 'project' | 'user';
10
+ file: string;
11
+ }
12
+ export interface HostCoreOptions {
13
+ home?: string;
14
+ env?: NodeJS.ProcessEnv;
15
+ platform?: NodeJS.Platform;
16
+ /** Reads an engine's capabilities; `probeEngine` by default. */
17
+ probe?: (engine: string) => EngineCapabilities;
18
+ }
19
+ /** The registration files `hq reindex` reconciles, per host. */
20
+ export declare function hostRegistrationFiles(root: string, home: string, env: NodeJS.ProcessEnv): HostRegistrationFile[];
21
+ /** Which core one HQ hook entry calls, or null when the entry is not HQ's. */
22
+ export declare function classifyEntry(entry: Record<string, unknown>, host: HostRegistrationFile['host'], root: string): CoreKind | null;
23
+ type Status = 'PASS' | 'WARN' | 'FAIL';
24
+ /** Which core one event of one registration file uses, and why. */
25
+ export interface EventCore {
26
+ event: string;
27
+ core: CoreKind;
28
+ status: Status;
29
+ reason: string;
30
+ }
31
+ /**
32
+ * One result per registration file, with each event's core and the reason
33
+ * for it. An event registered to the new core passes only when its engine
34
+ * runs and has every evaluator the event needs; a missing or dangling engine
35
+ * link, an engine that does not run, or a missing evaluator is FAIL with the
36
+ * fix. With the flag on, an event left on the old dispatcher says why.
37
+ */
38
+ export declare function hostCoreResults(root: string, options?: HostCoreOptions): CheckResult[];
39
+ /** Flag and kill-switch state, shown once. */
40
+ export declare function coreSwitchResult(options?: HostCoreOptions): CheckResult;
41
+ /** The family `hq doctor` prints. */
42
+ export declare function hostCoreFamily(context: CheckContext, options?: HostCoreOptions): Promise<FamilyRun>;
43
+ /**
44
+ * The one call `hq doctor` makes on a run without `--only`: when the hook
45
+ * wiring family ran, add this family right after it. Registries without it
46
+ * (tests that register their own families) are left as they are.
47
+ */
48
+ export declare function addHostCoreFamily(families: FamilyRun[], registry: Pick<DoctorRegistry, 'has'>, context: CheckContext, options?: HostCoreOptions): Promise<void>;
49
+ export {};
50
+ //# sourceMappingURL=host-core.d.ts.map