@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
@@ -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
@@ -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