@indigoai-us/hq-cli 5.345.214 → 5.345.215

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 (200) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/assets/scaffold/core/scripts/hq-delegate-verify.sh +5 -2
  3. package/dist/command-catalog.generated.d.ts +180 -13
  4. package/dist/command-catalog.generated.js +221 -13
  5. package/dist/commands/agents.d.ts +51 -1
  6. package/dist/commands/agents.js +154 -2
  7. package/dist/commands/bot-jobs.d.ts +2 -15
  8. package/dist/commands/bot-jobs.js +2 -94
  9. package/dist/commands/bot-runtime.d.ts +46 -5
  10. package/dist/commands/bot-runtime.js +228 -18
  11. package/dist/commands/bot.d.ts +16 -9
  12. package/dist/commands/bot.js +231 -55
  13. package/dist/commands/capacity.d.ts +4 -1
  14. package/dist/commands/capacity.js +46 -10
  15. package/dist/commands/cloud.d.ts +66 -13
  16. package/dist/commands/cloud.js +121 -40
  17. package/dist/commands/company-restore.d.ts +23 -0
  18. package/dist/commands/company-restore.js +128 -0
  19. package/dist/commands/company.js +2 -0
  20. package/dist/commands/core-delegate-w1b.js +15 -1
  21. package/dist/commands/core-policy.js +67 -8
  22. package/dist/commands/daemon.js +5 -0
  23. package/dist/commands/files-browse.d.ts +11 -4
  24. package/dist/commands/files-browse.js +21 -4
  25. package/dist/commands/files.d.ts +1 -1
  26. package/dist/commands/files.js +25 -11
  27. package/dist/commands/integrations-auth-rules.d.ts +27 -0
  28. package/dist/commands/integrations-auth-rules.js +79 -0
  29. package/dist/commands/integrations-connect.d.ts +10 -3
  30. package/dist/commands/integrations-connect.js +87 -13
  31. package/dist/commands/integrations-import.js +124 -12
  32. package/dist/commands/lanes.js +28 -11
  33. package/dist/commands/mesh.d.ts +2 -0
  34. package/dist/commands/mesh.js +60 -35
  35. package/dist/commands/sources.js +6 -0
  36. package/dist/commands/storage-offload.d.ts +12 -0
  37. package/dist/commands/storage-offload.js +41 -3
  38. package/dist/commands/sync-held.js +5 -2
  39. package/dist/commands/sync-mode.js +5 -0
  40. package/dist/commands/whoami.js +4 -0
  41. package/dist/lazy-commands.js +3 -5
  42. package/dist/lib/bot/config.d.ts +1 -0
  43. package/dist/lib/bot/config.js +10 -0
  44. package/dist/lib/bot/eventbridge-cron.d.ts +22 -0
  45. package/dist/lib/bot/eventbridge-cron.js +104 -0
  46. package/dist/lib/bot/fleet-cron.d.ts +8 -0
  47. package/dist/lib/bot/fleet-cron.js +35 -3
  48. package/dist/lib/bot/fleet-daemon.d.ts +46 -0
  49. package/dist/lib/bot/fleet-daemon.js +99 -1
  50. package/dist/lib/bot/fleet-local.d.ts +33 -1
  51. package/dist/lib/bot/fleet-local.js +215 -31
  52. package/dist/lib/bot/fleet-python.d.ts +3 -0
  53. package/dist/lib/bot/fleet-python.js +34 -4
  54. package/dist/lib/bot/fleet-runtime-sources.d.ts +15 -0
  55. package/dist/lib/bot/fleet-runtime-sources.js +30 -0
  56. package/dist/lib/bot/legacy-provider-login.d.ts +8 -0
  57. package/dist/lib/bot/legacy-provider-login.js +19 -2
  58. package/dist/lib/bot/probe.js +7 -1
  59. package/dist/lib/bot/prompt.js +1 -1
  60. package/dist/lib/bot/readiness.d.ts +8 -0
  61. package/dist/lib/bot/readiness.js +17 -3
  62. package/dist/lib/bot/run.js +20 -1
  63. package/dist/lib/bot/runtime/codex.js +1 -1
  64. package/dist/lib/bot/runtime/grok-acp.d.ts +5 -1
  65. package/dist/lib/bot/runtime/grok-acp.js +6 -3
  66. package/dist/lib/bot/runtime/index.js +19 -9
  67. package/dist/lib/bot/runtime/messages-stream.js +2 -2
  68. package/dist/lib/bot/runtime/types.d.ts +15 -0
  69. package/dist/lib/bot/runtime/types.js +9 -0
  70. package/dist/lib/bot/runtime-auth.d.ts +30 -0
  71. package/dist/lib/bot/runtime-auth.js +94 -3
  72. package/dist/lib/bot/runtime-failure.d.ts +23 -0
  73. package/dist/lib/bot/runtime-failure.js +43 -1
  74. package/dist/lib/bot/status.d.ts +2 -0
  75. package/dist/lib/capacity/accounts.d.ts +8 -0
  76. package/dist/lib/capacity/accounts.js +19 -0
  77. package/dist/lib/capacity/available.d.ts +154 -0
  78. package/dist/lib/capacity/available.js +905 -0
  79. package/dist/lib/capacity/codex-availability.d.ts +14 -1
  80. package/dist/lib/capacity/codex-availability.js +26 -1
  81. package/dist/lib/capacity/collectors/claude-oauth.d.ts +29 -2
  82. package/dist/lib/capacity/collectors/claude-oauth.js +104 -7
  83. package/dist/lib/capacity/collectors/codex.js +10 -7
  84. package/dist/lib/capacity/collectors/grok-refresh.d.ts +80 -0
  85. package/dist/lib/capacity/collectors/grok-refresh.js +189 -0
  86. package/dist/lib/capacity/collectors/grok.d.ts +5 -0
  87. package/dist/lib/capacity/collectors/grok.js +56 -5
  88. package/dist/lib/capacity/ledger.d.ts +37 -1
  89. package/dist/lib/capacity/ledger.js +207 -30
  90. package/dist/lib/capacity/project.d.ts +26 -0
  91. package/dist/lib/capacity/project.js +137 -8
  92. package/dist/lib/capacity/refusal-rows.d.ts +31 -0
  93. package/dist/lib/capacity/refusal-rows.js +61 -0
  94. package/dist/lib/capacity/refusal.d.ts +53 -2
  95. package/dist/lib/capacity/refusal.js +284 -65
  96. package/dist/lib/capacity/route.js +46 -11
  97. package/dist/lib/capacity/widget.d.ts +12 -1
  98. package/dist/lib/capacity/widget.js +91 -3
  99. package/dist/lib/daemon/catalog.js +11 -1
  100. package/dist/lib/daemon/resolver.d.ts +2 -0
  101. package/dist/lib/daemon/resolver.js +3 -0
  102. package/dist/lib/daemon/run.d.ts +9 -0
  103. package/dist/lib/daemon/run.js +54 -1
  104. package/dist/lib/daemon/server.d.ts +2 -0
  105. package/dist/lib/daemon/server.js +10 -1
  106. package/dist/lib/daemon/tcc-eperm.d.ts +153 -0
  107. package/dist/lib/daemon/tcc-eperm.js +310 -0
  108. package/dist/lib/db/sqlite-binding.d.ts +1 -0
  109. package/dist/lib/db/sqlite-binding.js +1 -1
  110. package/dist/lib/delivery/admission.d.ts +86 -0
  111. package/dist/lib/delivery/admission.js +148 -0
  112. package/dist/lib/delivery/artifacts.d.ts +105 -0
  113. package/dist/lib/delivery/artifacts.js +567 -0
  114. package/dist/lib/delivery/attempt-id.d.ts +13 -0
  115. package/dist/lib/delivery/attempt-id.js +16 -0
  116. package/dist/lib/delivery/backup.d.ts +78 -0
  117. package/dist/lib/delivery/backup.js +343 -0
  118. package/dist/lib/delivery/cache.d.ts +29 -0
  119. package/dist/lib/delivery/cache.js +33 -0
  120. package/dist/lib/delivery/contracts.d.ts +142 -0
  121. package/dist/lib/delivery/contracts.js +289 -0
  122. package/dist/lib/delivery/credentials.d.ts +54 -0
  123. package/dist/lib/delivery/credentials.js +119 -0
  124. package/dist/lib/delivery/disposable-target.d.ts +42 -0
  125. package/dist/lib/delivery/disposable-target.js +111 -0
  126. package/dist/lib/delivery/effects.d.ts +136 -0
  127. package/dist/lib/delivery/effects.js +541 -0
  128. package/dist/lib/delivery/enrollment.d.ts +146 -0
  129. package/dist/lib/delivery/enrollment.js +460 -0
  130. package/dist/lib/delivery/escalations.d.ts +51 -0
  131. package/dist/lib/delivery/escalations.js +60 -0
  132. package/dist/lib/delivery/identity.d.ts +25 -0
  133. package/dist/lib/delivery/identity.js +82 -0
  134. package/dist/lib/delivery/inbox.d.ts +116 -0
  135. package/dist/lib/delivery/inbox.js +260 -0
  136. package/dist/lib/delivery/lease.d.ts +80 -0
  137. package/dist/lib/delivery/lease.js +134 -0
  138. package/dist/lib/delivery/migrations.d.ts +255 -0
  139. package/dist/lib/delivery/migrations.js +823 -0
  140. package/dist/lib/delivery/mqtt-adapter.d.ts +50 -0
  141. package/dist/lib/delivery/mqtt-adapter.js +242 -0
  142. package/dist/lib/delivery/mqtt.d.ts +63 -0
  143. package/dist/lib/delivery/mqtt.js +119 -0
  144. package/dist/lib/delivery/outbox.d.ts +95 -0
  145. package/dist/lib/delivery/outbox.js +187 -0
  146. package/dist/lib/delivery/provenance.d.ts +129 -0
  147. package/dist/lib/delivery/provenance.js +93 -0
  148. package/dist/lib/delivery/reconciler.d.ts +215 -0
  149. package/dist/lib/delivery/reconciler.js +703 -0
  150. package/dist/lib/delivery/restore.d.ts +35 -0
  151. package/dist/lib/delivery/restore.js +134 -0
  152. package/dist/lib/delivery/rpc/client.d.ts +22 -0
  153. package/dist/lib/delivery/rpc/client.js +159 -0
  154. package/dist/lib/delivery/rpc/port.d.ts +40 -0
  155. package/dist/lib/delivery/rpc/port.js +16 -0
  156. package/dist/lib/delivery/rpc/server.d.ts +30 -0
  157. package/dist/lib/delivery/rpc/server.js +205 -0
  158. package/dist/lib/delivery/rpc/wire.d.ts +85 -0
  159. package/dist/lib/delivery/rpc/wire.js +143 -0
  160. package/dist/lib/delivery/store.d.ts +163 -0
  161. package/dist/lib/delivery/store.js +944 -0
  162. package/dist/lib/delivery/windows-service-install.d.ts +262 -0
  163. package/dist/lib/delivery/windows-service-install.js +892 -0
  164. package/dist/lib/delivery/workers/macos-job-helper.d.ts +103 -0
  165. package/dist/lib/delivery/workers/macos-job-helper.js +927 -0
  166. package/dist/lib/delivery/workers/macos.d.ts +191 -0
  167. package/dist/lib/delivery/workers/macos.js +943 -0
  168. package/dist/lib/delivery/workers/windows-job-helper.d.ts +35 -0
  169. package/dist/lib/delivery/workers/windows-job-helper.js +264 -0
  170. package/dist/lib/delivery/workers/windows-service-live.d.ts +121 -0
  171. package/dist/lib/delivery/workers/windows-service-live.js +711 -0
  172. package/dist/lib/delivery/workers/windows-service-runner.d.ts +33 -0
  173. package/dist/lib/delivery/workers/windows-service-runner.js +82 -0
  174. package/dist/lib/delivery/workers/windows-service.d.ts +140 -0
  175. package/dist/lib/delivery/workers/windows-service.js +584 -0
  176. package/dist/lib/delivery/workers/windows.d.ts +251 -0
  177. package/dist/lib/delivery/workers/windows.js +594 -0
  178. package/dist/lib/hot-channels/adapters/meetings.d.ts +15 -0
  179. package/dist/lib/hot-channels/adapters/meetings.js +36 -3
  180. package/dist/lib/hot-channels/signals-pass.d.ts +10 -0
  181. package/dist/lib/hot-channels/signals-pass.js +71 -2
  182. package/dist/lib/hot-channels/signals-redo.js +10 -2
  183. package/dist/lib/install/provider-wrappers.d.ts +2 -0
  184. package/dist/lib/install/provider-wrappers.js +68 -3
  185. package/dist/lib/lanes/watcher.js +35 -0
  186. package/dist/lib/signals/steps/extract.js +40 -4
  187. package/dist/schemas/hq-available-ai.v1.schema.json +76 -0
  188. package/dist/utils/catalog-runtime-paths.d.ts +34 -0
  189. package/dist/utils/catalog-runtime-paths.js +53 -0
  190. package/dist/utils/cognito-callback-port.d.ts +14 -0
  191. package/dist/utils/cognito-callback-port.js +24 -0
  192. package/dist/utils/cognito-session.js +3 -3
  193. package/dist/utils/deleted-company-notice.d.ts +59 -0
  194. package/dist/utils/deleted-company-notice.js +156 -0
  195. package/dist/utils/files-browse-acl.js +1 -1
  196. package/dist/utils/login-browser.d.ts +1 -1
  197. package/dist/utils/login-browser.js +7 -5
  198. package/dist/utils/resident-package-preload.js +30 -15
  199. package/dist/utils/vault-api.js +7 -0
  200. package/package.json +7 -7
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Self-recovery for a daemon that macOS privacy (TCC) has cut off from the
3
+ * HQ folder.
4
+ *
5
+ * After HQ.app updates itself, a daemon that was started from the old app
6
+ * bundle keeps running from the deleted bundle. macOS then refuses its file
7
+ * reads and writes under the HQ root with EPERM ("operation not permitted"),
8
+ * and every hqd op that touches companies/ fails until someone runs
9
+ * `launchctl kickstart -k`. A fresh process started by launchd is checked
10
+ * again and gets access.
11
+ *
12
+ * So: when hqd sees EPERM on reads (open, stat, readdir and the like) of paths
13
+ * under the HQ root, repeated across more than one path within a short window,
14
+ * it logs one structured event, reports
15
+ * it once to Sentry under a fixed fingerprint, and exits with
16
+ * TCC_EPERM_EXIT_CODE. The daemon's LaunchAgent has KeepAlive=true, so launchd
17
+ * starts it again (after its ThrottleInterval) whatever the exit code.
18
+ *
19
+ * It never exits for EPERM outside the HQ root, for EACCES, off macOS, while
20
+ * the daemon is already stopping, or when no service manager would start it
21
+ * again. A permission that stays revoked would otherwise restart the daemon
22
+ * forever, so after TCC_EPERM_MAX_EXITS exits within TCC_EPERM_EXIT_WINDOW_MS
23
+ * it stays up and writes FILES_ACCESS_NEEDED_MARKER, which `hq daemon status`
24
+ * reports as a warning while the daemon runs. It also stays up when it cannot
25
+ * write that exit record, since the backoff could never engage. A daemon that
26
+ * stayed up lists the HQ root every TCC_EPERM_PROBE_INTERVAL_MS; once that
27
+ * works it clears the marker and watches again.
28
+ */
29
+ import * as fs from "node:fs";
30
+ import * as path from "node:path";
31
+ /** sysexits EX_IOERR. Not 75 (RESTART_EXIT_CODE) and not one exit-cause.ts treats as permanent (77, 78, 126, 127). */
32
+ export const TCC_EPERM_EXIT_CODE = 74;
33
+ /** EPERM hits under the HQ root count toward a trip only inside this window. */
34
+ export const TCC_EPERM_WINDOW_MS = 60_000;
35
+ /** Hits needed inside the window. */
36
+ export const TCC_EPERM_MIN_EVENTS = 3;
37
+ /** Distinct paths needed inside the window, so one odd file cannot trip it. */
38
+ export const TCC_EPERM_MIN_PATHS = 2;
39
+ /** Exits allowed inside TCC_EPERM_EXIT_WINDOW_MS before the daemon stays up instead. */
40
+ export const TCC_EPERM_MAX_EXITS = 3;
41
+ export const TCC_EPERM_EXIT_WINDOW_MS = 30 * 60_000;
42
+ /** Under the daemon dir: timestamps of recent EPERM exits (the backoff record). */
43
+ export const TCC_EPERM_EXITS_FILE = "tcc-eperm-exits.json";
44
+ /** Under the daemon dir: present while hqd is up but cannot read the HQ folder. */
45
+ export const FILES_ACCESS_NEEDED_MARKER = "files-access-needed.json";
46
+ export const FILES_ACCESS_NEEDED_MESSAGE = "HQ needs Full Disk Access (or Files and Folders access) to your HQ folder. macOS is refusing the daemon's file reads and writes there. " +
47
+ "Open System Settings > Privacy & Security > Full Disk Access, allow HQ, then run: hq daemon restart";
48
+ export const TCC_EPERM_SENTRY_FINGERPRINT = ["hqd", "tcc-eperm-under-hq-root"];
49
+ /**
50
+ * Syscalls that read. macOS privacy refuses these with EPERM when it cuts a
51
+ * process off from a folder. chmod, chown, utime, unlink, rmdir and rename
52
+ * also fail with EPERM for ordinary reasons (file flags, the sticky bit,
53
+ * ownership), so they never count.
54
+ */
55
+ const READ_SYSCALLS = new Set([
56
+ "open",
57
+ "read",
58
+ "readdir",
59
+ "scandir",
60
+ "opendir",
61
+ "stat",
62
+ "lstat",
63
+ "access",
64
+ "realpath",
65
+ ]);
66
+ /** Last realpath lookup of the HQ root; looked up again only while it keeps failing. */
67
+ let rootCache = null;
68
+ function rootCandidates(hqRoot) {
69
+ if (rootCache && rootCache.hqRoot === hqRoot && rootCache.resolved)
70
+ return rootCache.roots;
71
+ const resolved = path.resolve(hqRoot);
72
+ const roots = [resolved];
73
+ let ok = false;
74
+ try {
75
+ const real = fs.realpathSync(resolved);
76
+ if (real !== resolved)
77
+ roots.push(real);
78
+ ok = true;
79
+ }
80
+ catch {
81
+ // The root itself may be unreadable right now; the lexical path still counts.
82
+ }
83
+ rootCache = { hqRoot, roots, resolved: ok };
84
+ return roots;
85
+ }
86
+ /**
87
+ * Lexical containment. A symlink inside the root that points at a protected
88
+ * folder outside it still counts; the exit backoff caps what that can cost.
89
+ */
90
+ function within(root, candidate) {
91
+ const rel = path.relative(root, path.resolve(candidate));
92
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
93
+ }
94
+ /**
95
+ * The EPERM hit `err` carries for a read under `hqRoot`, or null. Follows
96
+ * `cause` a few levels, since some ops wrap the fs error. EACCES is a plain
97
+ * permission bit, not TCC, and never counts; neither does an EPERM with no
98
+ * path (kill(2), for one) or from a syscall that does not read. The root's
99
+ * realpath is looked up only after an EPERM read is found, and is cached.
100
+ */
101
+ export function epermUnderRoot(err, hqRoot) {
102
+ let current = err;
103
+ for (let depth = 0; depth < 4 && current && typeof current === "object"; depth += 1) {
104
+ const e = current;
105
+ const { code, syscall, path: candidate } = e;
106
+ if (code === "EPERM" && typeof syscall === "string" && READ_SYSCALLS.has(syscall) && typeof candidate === "string" && candidate !== "") {
107
+ if (rootCandidates(hqRoot).some((root) => within(root, candidate)))
108
+ return { path: candidate, syscall };
109
+ }
110
+ current = e.cause;
111
+ }
112
+ return null;
113
+ }
114
+ /** Sliding window of EPERM hits; `record` returns true once the window holds enough of them. */
115
+ export function createEpermWindow(options = {}) {
116
+ const windowMs = options.windowMs ?? TCC_EPERM_WINDOW_MS;
117
+ const minEvents = options.minEvents ?? TCC_EPERM_MIN_EVENTS;
118
+ const minPaths = options.minPaths ?? TCC_EPERM_MIN_PATHS;
119
+ let hits = [];
120
+ return {
121
+ record(hit, at) {
122
+ hits = hits.filter((h) => at - h.at < windowMs);
123
+ hits.push({ ...hit, at });
124
+ return hits.length >= minEvents && new Set(hits.map((h) => h.path)).size >= minPaths;
125
+ },
126
+ summary() {
127
+ return {
128
+ hits: hits.length,
129
+ distinctPaths: new Set(hits.map((h) => h.path)).size,
130
+ syscalls: [...new Set(hits.flatMap((h) => (h.syscall ? [h.syscall] : [])))].sort(),
131
+ };
132
+ },
133
+ };
134
+ }
135
+ /** What a tripped window should do. */
136
+ export function decideEpermExit(input) {
137
+ if (input.platform !== "darwin")
138
+ return { action: "ignore", reason: "not-macos" };
139
+ if (input.stopping)
140
+ return { action: "ignore", reason: "stopping" };
141
+ if (!input.restartable)
142
+ return { action: "stay", reason: "not-restartable" };
143
+ const windowMs = input.exitWindowMs ?? TCC_EPERM_EXIT_WINDOW_MS;
144
+ const recent = input.recentExits.filter((t) => input.now - t < windowMs && t <= input.now);
145
+ if (recent.length >= (input.maxExits ?? TCC_EPERM_MAX_EXITS))
146
+ return { action: "stay", reason: "backoff" };
147
+ return { action: "exit", code: TCC_EPERM_EXIT_CODE };
148
+ }
149
+ export function readEpermExits(daemonDir) {
150
+ try {
151
+ const parsed = JSON.parse(fs.readFileSync(path.join(daemonDir, TCC_EPERM_EXITS_FILE), "utf8"));
152
+ return Array.isArray(parsed.exits) ? parsed.exits.filter((t) => typeof t === "number" && Number.isFinite(t)) : [];
153
+ }
154
+ catch {
155
+ return [];
156
+ }
157
+ }
158
+ function writePrivateJson(file, value) {
159
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
160
+ const tmp = `${file}.${process.pid}.tmp`;
161
+ fs.writeFileSync(tmp, `${JSON.stringify(value)}\n`, { mode: 0o600 });
162
+ fs.renameSync(tmp, file);
163
+ }
164
+ /** Add an exit at `now`, dropping ones older than the backoff window. */
165
+ export function recordEpermExit(daemonDir, now, exitWindowMs = TCC_EPERM_EXIT_WINDOW_MS) {
166
+ const exits = [...readEpermExits(daemonDir).filter((t) => now - t < exitWindowMs && t <= now), now];
167
+ writePrivateJson(path.join(daemonDir, TCC_EPERM_EXITS_FILE), { exits });
168
+ return exits;
169
+ }
170
+ export function writeFilesAccessNeeded(daemonDir, now, reason) {
171
+ writePrivateJson(path.join(daemonDir, FILES_ACCESS_NEEDED_MARKER), {
172
+ since: new Date(now).toISOString(),
173
+ reason,
174
+ message: FILES_ACCESS_NEEDED_MESSAGE,
175
+ });
176
+ }
177
+ export function clearFilesAccessNeeded(daemonDir) {
178
+ fs.rmSync(path.join(daemonDir, FILES_ACCESS_NEEDED_MARKER), { force: true });
179
+ }
180
+ export function filesAccessNeeded(daemonDir) {
181
+ return fs.existsSync(path.join(daemonDir, FILES_ACCESS_NEEDED_MARKER));
182
+ }
183
+ /** A daemon that stayed up checks this often whether macOS gave the HQ folder back. */
184
+ export const TCC_EPERM_PROBE_INTERVAL_MS = 60_000;
185
+ const defaultSchedule = (fn, ms) => {
186
+ const timer = setInterval(fn, ms);
187
+ timer.unref?.();
188
+ return () => clearInterval(timer);
189
+ };
190
+ export function createTccEpermGuard(deps) {
191
+ const now = deps.now ?? Date.now;
192
+ const probe = deps.probe ?? ((root) => void fs.readdirSync(root));
193
+ const schedule = deps.schedule ?? defaultSchedule;
194
+ let window = createEpermWindow(deps.window);
195
+ const windowMs = deps.window?.windowMs ?? TCC_EPERM_WINDOW_MS;
196
+ let state = "watching";
197
+ let cancelProbe = null;
198
+ if (deps.platform === "darwin") {
199
+ // A new daemon starts unflagged; it writes the marker again if access is still refused.
200
+ try {
201
+ clearFilesAccessNeeded(deps.daemonDir);
202
+ }
203
+ catch (err) {
204
+ deps.log("warn", `could not clear ${FILES_ACCESS_NEEDED_MARKER}: ${err.message}`);
205
+ }
206
+ }
207
+ const report = (event) => deps.report(event).catch((err) => deps.log("warn", `could not report the hqd file access failure: ${String(err)}`));
208
+ const checkAccess = () => {
209
+ if (state !== "access-needed" || deps.isStopping())
210
+ return false;
211
+ const hqRoot = deps.hqRoot();
212
+ if (!hqRoot)
213
+ return false;
214
+ try {
215
+ probe(hqRoot);
216
+ }
217
+ catch {
218
+ return false;
219
+ }
220
+ cancelProbe?.();
221
+ cancelProbe = null;
222
+ window = createEpermWindow(deps.window);
223
+ state = "watching";
224
+ try {
225
+ clearFilesAccessNeeded(deps.daemonDir);
226
+ }
227
+ catch (err) {
228
+ deps.log("warn", `could not clear ${FILES_ACCESS_NEEDED_MARKER}: ${err.message}`);
229
+ }
230
+ deps.log("info", "hqd: the HQ folder can be read again; watching for macOS file access errors again");
231
+ return true;
232
+ };
233
+ const stayUp = (at, reason) => {
234
+ state = "access-needed";
235
+ try {
236
+ writeFilesAccessNeeded(deps.daemonDir, at, reason);
237
+ }
238
+ catch (writeErr) {
239
+ deps.log("warn", `could not write ${FILES_ACCESS_NEEDED_MARKER}: ${writeErr.message}`);
240
+ }
241
+ cancelProbe ??= schedule(() => void checkAccess(), deps.probeIntervalMs ?? TCC_EPERM_PROBE_INTERVAL_MS);
242
+ };
243
+ return {
244
+ state: () => state,
245
+ checkAccess,
246
+ dispose() {
247
+ cancelProbe?.();
248
+ cancelProbe = null;
249
+ },
250
+ observe(err) {
251
+ if (state !== "watching" || deps.platform !== "darwin" || deps.isStopping())
252
+ return;
253
+ const hqRoot = deps.hqRoot();
254
+ if (!hqRoot)
255
+ return;
256
+ const hit = epermUnderRoot(err, hqRoot);
257
+ if (!hit)
258
+ return;
259
+ const at = now();
260
+ if (!window.record(hit, at))
261
+ return;
262
+ const recentExits = readEpermExits(deps.daemonDir);
263
+ let decision = decideEpermExit({
264
+ platform: deps.platform,
265
+ stopping: deps.isStopping(),
266
+ restartable: deps.restartable,
267
+ recentExits,
268
+ now: at,
269
+ maxExits: deps.maxExits,
270
+ exitWindowMs: deps.exitWindowMs,
271
+ });
272
+ if (decision.action === "ignore")
273
+ return;
274
+ let exitsInWindow = recentExits.filter((t) => at - t < (deps.exitWindowMs ?? TCC_EPERM_EXIT_WINDOW_MS) && t <= at).length;
275
+ if (decision.action === "exit") {
276
+ try {
277
+ exitsInWindow = recordEpermExit(deps.daemonDir, at, deps.exitWindowMs).length;
278
+ state = "exiting";
279
+ }
280
+ catch (writeErr) {
281
+ // Without the record the backoff never engages and launchd would restart the daemon forever.
282
+ deps.log("warn", `could not record the restart in ${TCC_EPERM_EXITS_FILE}, so staying up: ${writeErr.message}`);
283
+ decision = { action: "stay", reason: "exit-not-recorded" };
284
+ }
285
+ }
286
+ if (decision.action === "stay")
287
+ stayUp(at, decision.reason);
288
+ const event = {
289
+ event: "hqd.tcc_eperm",
290
+ platform: deps.platform,
291
+ ...window.summary(),
292
+ windowMs,
293
+ decision: decision.action,
294
+ ...(decision.action === "stay" ? { reason: decision.reason } : { exitCode: decision.code }),
295
+ exitsInWindow,
296
+ };
297
+ deps.log("error", `hqd: macOS refused file access under the HQ root ${JSON.stringify(event)}`);
298
+ if (decision.action === "exit") {
299
+ deps.log("error", "hqd: exiting so launchd starts a fresh daemon that macOS checks again");
300
+ const code = decision.code;
301
+ void report(event).finally(() => deps.exit(code));
302
+ }
303
+ else {
304
+ deps.log("error", `hqd: staying up; ${FILES_ACCESS_NEEDED_MESSAGE}`);
305
+ void report(event);
306
+ }
307
+ },
308
+ };
309
+ }
310
+ //# sourceMappingURL=tcc-eperm.js.map
@@ -10,6 +10,7 @@ export interface LoadBetterSqlite3Options {
10
10
  repair?: () => boolean;
11
11
  }
12
12
  export declare function resetSqliteBindingForTests(): void;
13
+ export declare function isNativeBindingError(error: unknown): boolean;
13
14
  export declare function clearBetterSqlite3RequireCache(): void;
14
15
  /**
15
16
  * A `.js` bin runs under this Node. A `.cmd` shim goes through the escaped
@@ -29,7 +29,7 @@ export function resetSqliteBindingForTests() {
29
29
  failed = undefined;
30
30
  defaultRepairAttempted = false;
31
31
  }
32
- function isNativeBindingError(error) {
32
+ export function isNativeBindingError(error) {
33
33
  const record = error;
34
34
  const text = error instanceof Error ? `${record?.code ?? ""} ${error.message}` : String(error);
35
35
  return /better_sqlite3\.node|could not locate the bindings file|NODE_MODULE_VERSION|was compiled against a different node|not a valid win32 application|dlopen|ERR_DLOPEN_FAILED|MODULE_NOT_FOUND/i.test(text);
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Deployment admission (US-009).
3
+ *
4
+ * A deployment needs both an exact artifact and an explicit policy:
5
+ * - the request names the artifact id and the sha256 digest it expects;
6
+ * - the artifact bytes come from ArtifactStore.read(), which re-checks the
7
+ * provenance signature, the promotion signature and the blob digest;
8
+ * - the artifact was built by a release-trust worker into the release
9
+ * partition and promoted;
10
+ * - the requester's company policy, loaded from the store (never from the
11
+ * request) and set there only by an authenticated company admin, carries a
12
+ * valid admin signature, lists the environment, approves it, names this
13
+ * target and allows the artifact's source repository;
14
+ * - the deploy attempt is open, claimed by the requesting worker, in the
15
+ * current controller epoch.
16
+ *
17
+ * Any failure is an exception: admit() returns a decision scoped to the
18
+ * requester's company and environment, which effects.ts records as a blocked
19
+ * deployment and escalates to that company's admin. There is no override
20
+ * field and no bypass; a request with unknown fields, including a policy, is
21
+ * refused outright.
22
+ *
23
+ * Every admission produces a snapshot of the policy, artifact identity and
24
+ * request context. effects.ts stores it with its sha256 (snapshotDigest) and
25
+ * an HMAC (snapshotSignature) and never changes it.
26
+ */
27
+ import type { ArtifactStore } from "./artifacts.js";
28
+ import type { WorkerIdentity } from "./identity.js";
29
+ import { type DecisionCode, type DeploymentSnapshot, type StoredDeployPolicy, type StoredWorker } from "./migrations.js";
30
+ import { type ArtifactProvenance } from "./provenance.js";
31
+ import type { AttemptView } from "./reconciler.js";
32
+ export interface EnvironmentPolicy {
33
+ /** Explicit approval. A listed but unapproved environment is blocked. */
34
+ approved: boolean;
35
+ /** The deployment target this environment deploys to. */
36
+ targetId: string;
37
+ /** Source repositories whose artifacts may deploy here. */
38
+ allowedRepositories: string[];
39
+ }
40
+ export interface DeployPolicy {
41
+ policyId: string;
42
+ /** The company the policy belongs to. Must be the requester's company. */
43
+ tenantId: string;
44
+ version: number;
45
+ environments: Record<string, EnvironmentPolicy>;
46
+ }
47
+ export interface DeployRequest {
48
+ /** Open deploy attempt claimed by the requesting worker. */
49
+ attemptId: string;
50
+ artifactId: string;
51
+ /** sha256 hex the requester expects the artifact to have. */
52
+ digest: string;
53
+ environment: string;
54
+ }
55
+ export interface AdmissionInput {
56
+ identity: WorkerIdentity;
57
+ worker: StoredWorker;
58
+ attempt: AttemptView | undefined;
59
+ controllerEpoch: number;
60
+ now: string;
61
+ targetId: string;
62
+ artifacts: ArtifactStore;
63
+ request: DeployRequest;
64
+ /** The requester's company policy from the store, or null when none was set. */
65
+ storedPolicy: StoredDeployPolicy | null;
66
+ /** True when the stored policy's admin signature verified with the signing key. */
67
+ policyVerified: boolean;
68
+ }
69
+ /** Shape check of a policy an admin is about to store. Returns the problem, or null. */
70
+ export declare function deployPolicyProblem(p: unknown): string | null;
71
+ export type Admission = {
72
+ ok: true;
73
+ snapshot: DeploymentSnapshot;
74
+ bytes: Buffer;
75
+ provenance: ArtifactProvenance;
76
+ } | {
77
+ ok: false;
78
+ snapshot: DeploymentSnapshot;
79
+ code: DecisionCode;
80
+ found: string;
81
+ };
82
+ /** Refuse a malformed request before anything is recorded. */
83
+ export declare function checkRequest(input: unknown): DeployRequest;
84
+ /** Decide one request. Pure apart from the verified artifact read. */
85
+ export declare function admit(input: AdmissionInput): Admission;
86
+ //# sourceMappingURL=admission.d.ts.map
@@ -0,0 +1,148 @@
1
+ import { DeliveryStoreError } from "./migrations.js";
2
+ import { canonicalJson, sha256Hex } from "./provenance.js";
3
+ /** A request carries no policy: the policy is loaded from the store, where only an authenticated company admin writes it. */
4
+ const REQUEST_KEYS = ["artifactId", "attemptId", "digest", "environment"];
5
+ const HEX64 = /^[0-9a-f]{64}$/;
6
+ const isText = (v) => typeof v === "string" && v.trim() !== "";
7
+ /** Shape check of a policy an admin is about to store. Returns the problem, or null. */
8
+ export function deployPolicyProblem(p) {
9
+ return policyProblem(p);
10
+ }
11
+ /** Refuse a malformed request before anything is recorded. */
12
+ export function checkRequest(input) {
13
+ const r = input;
14
+ const keys = typeof input === "object" && input !== null ? Object.keys(input).sort().join(",") : "";
15
+ if (keys !== REQUEST_KEYS.join(",")) {
16
+ throw new DeliveryStoreError("INVALID_RECORD", {
17
+ found: `a deploy request with fields [${keys}]`,
18
+ expected: `exactly [${REQUEST_KEYS.join(",")}]; there is no override or bypass field`,
19
+ action: "Send the exact artifact, environment and policy. Nothing was recorded or deployed.",
20
+ });
21
+ }
22
+ for (const k of ["attemptId", "artifactId", "environment"]) {
23
+ if (!isText(r[k])) {
24
+ throw new DeliveryStoreError("INVALID_RECORD", { found: `${k} ${JSON.stringify(r[k])}`, expected: `a non-empty ${k}`, action: "Fix the request. Nothing was recorded or deployed." });
25
+ }
26
+ }
27
+ if (typeof r.digest !== "string" || !HEX64.test(r.digest)) {
28
+ throw new DeliveryStoreError("INVALID_RECORD", {
29
+ found: `digest ${JSON.stringify(r.digest)}`,
30
+ expected: "the sha256 hex digest of the exact artifact",
31
+ action: "Name the exact artifact digest. Nothing was recorded or deployed.",
32
+ });
33
+ }
34
+ return r;
35
+ }
36
+ function policyProblem(p) {
37
+ if (typeof p !== "object" || p === null)
38
+ return "no policy object";
39
+ const policy = p;
40
+ if (!isText(policy.policyId) || !isText(policy.tenantId))
41
+ return "policy without policyId or tenantId";
42
+ if (!Number.isInteger(policy.version) || policy.version < 1)
43
+ return "policy without a positive integer version";
44
+ if (typeof policy.environments !== "object" || policy.environments === null)
45
+ return "policy without environments";
46
+ for (const [name, env] of Object.entries(policy.environments)) {
47
+ const e = env;
48
+ if (typeof e !== "object" || e === null || typeof e.approved !== "boolean" || !isText(e.targetId) || !Array.isArray(e.allowedRepositories) || !e.allowedRepositories.every(isText)) {
49
+ return `environment ${name} is not { approved, targetId, allowedRepositories }`;
50
+ }
51
+ }
52
+ return null;
53
+ }
54
+ function digestOf(v) {
55
+ try {
56
+ return sha256Hex(canonicalJson(v));
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ /** Decide one request. Pure apart from the verified artifact read. */
63
+ export function admit(input) {
64
+ const { request: r, worker } = input;
65
+ const tenantId = worker.tenantId;
66
+ const stored = input.storedPolicy;
67
+ const problem = stored ? policyProblem(stored.policy) : null;
68
+ const usable = stored !== null && problem === null && input.policyVerified && stored.policy.tenantId === tenantId;
69
+ const pol = stored?.policy;
70
+ const snapshot = {
71
+ policy: usable ? structuredClone(pol) : null,
72
+ policyDigest: stored ? digestOf(stored.policy) : null,
73
+ policyTenantId: stored ? stored.tenantId : null,
74
+ policySetBy: stored ? stored.setBy : null,
75
+ policySignature: stored ? stored.signature.value : null,
76
+ artifact: { artifactId: r.artifactId, digest: null, partition: null, promoted: false, promotedAt: null, repository: null, commitSha: null, builder: null, provenanceSignature: null },
77
+ context: {
78
+ tenantId,
79
+ environment: r.environment,
80
+ workerId: worker.workerId,
81
+ attemptId: r.attemptId,
82
+ targetId: null,
83
+ requestedDigest: r.digest,
84
+ controllerEpoch: input.controllerEpoch,
85
+ requestedAt: input.now,
86
+ },
87
+ };
88
+ const block = (code, found) => ({ ok: false, snapshot, code, found });
89
+ if (stored === null)
90
+ return block("POLICY_MISSING", `no deploy policy has been set for ${tenantId} by its admin`);
91
+ if (!input.policyVerified || stored.tenantId !== tenantId)
92
+ return block("POLICY_TAMPERED", `the stored deploy policy of ${tenantId} does not match its admin signature`);
93
+ if (problem !== null)
94
+ return block("POLICY_INVALID", problem);
95
+ if (!usable)
96
+ return block("POLICY_TAMPERED", `the stored deploy policy of ${tenantId} names another company`);
97
+ const env = Object.prototype.hasOwnProperty.call(pol.environments, r.environment) ? pol.environments[r.environment] : undefined;
98
+ if (!env)
99
+ return block("ENVIRONMENT_UNLISTED", `policy ${pol.policyId} v${pol.version} does not list environment ${r.environment}`);
100
+ snapshot.context.targetId = env.targetId;
101
+ if (env.approved !== true)
102
+ return block("ENVIRONMENT_UNAPPROVED", `policy ${pol.policyId} v${pol.version} does not approve environment ${r.environment}`);
103
+ if (env.targetId !== input.targetId)
104
+ return block("TARGET_MISMATCH", `environment ${r.environment} deploys to ${env.targetId}, this deployer targets ${input.targetId}`);
105
+ const a = input.attempt;
106
+ if (!a || a.attempt.tenantId !== tenantId || a.resolution !== "open" || a.claimedBy !== worker.workerId || a.claimedEpoch !== input.controllerEpoch) {
107
+ const state = a ? `${a.resolution}, claimed by ${String(a.claimedBy)} at epoch ${a.claimedEpoch}` : "missing";
108
+ return block("ATTEMPT_NOT_CURRENT", `deploy attempt ${r.attemptId} is ${state}; current epoch ${input.controllerEpoch}`);
109
+ }
110
+ let read;
111
+ try {
112
+ read = input.artifacts.read(input.identity, r.artifactId);
113
+ }
114
+ catch (err) {
115
+ if (!(err instanceof DeliveryStoreError))
116
+ throw err;
117
+ if (err.code === "ACCESS_DENIED")
118
+ return block("ARTIFACT_OTHER_TENANT", `artifact ${r.artifactId} is not an artifact of ${tenantId}`);
119
+ if (err.code === "ARTIFACT_UNKNOWN")
120
+ return block("ARTIFACT_UNKNOWN", `no artifact ${r.artifactId}`);
121
+ if (err.code === "ARTIFACT_TAMPERED")
122
+ return block("ARTIFACT_UNTRUSTED", `verified read failed: ${err.message}`);
123
+ throw err;
124
+ }
125
+ const p = read.provenance;
126
+ Object.assign(snapshot.artifact, {
127
+ digest: p.digest.value,
128
+ partition: p.partition,
129
+ promoted: read.promotedAt !== null,
130
+ promotedAt: read.promotedAt,
131
+ repository: p.source.repository,
132
+ commitSha: p.source.commitSha,
133
+ builder: `${p.builder.workerId}:${p.builder.trust}`,
134
+ provenanceSignature: read.provenanceSignature,
135
+ });
136
+ if (p.digest.value !== r.digest)
137
+ return block("ARTIFACT_CHANGED", `artifact ${r.artifactId} has sha256 ${p.digest.value}, the request names ${r.digest}`);
138
+ if (p.partition !== "release" || p.builder.trust !== "release") {
139
+ return block("ARTIFACT_UNTRUSTED", `artifact ${r.artifactId} was built by ${p.builder.trust} worker ${p.builder.workerId} into the ${p.partition} partition`);
140
+ }
141
+ if (read.promotedAt === null)
142
+ return block("ARTIFACT_UNPROMOTED", `artifact ${r.artifactId} is not promoted`);
143
+ if (!env.allowedRepositories.includes(p.source.repository)) {
144
+ return block("SOURCE_NOT_ALLOWED", `environment ${r.environment} does not allow source ${p.source.repository}`);
145
+ }
146
+ return { ok: true, snapshot, bytes: read.bytes, provenance: p };
147
+ }
148
+ //# sourceMappingURL=admission.js.map
@@ -0,0 +1,105 @@
1
+ import type { CredentialSource } from "./credentials.js";
2
+ import type { AdminScope, DeliveryAccess } from "./enrollment.js";
3
+ import { type WorkerIdentity } from "./identity.js";
4
+ import { type ArtifactProvenance, type BuildInputs, type TrustPartition } from "./provenance.js";
5
+ export type { BuildInputs, ArtifactProvenance, TrustPartition } from "./provenance.js";
6
+ export declare const ARTIFACTS_DIR = "artifacts";
7
+ /** Config path of the production provenance signing-key credential ref. */
8
+ export declare const PROVENANCE_SIGNING_KEY_REF_PATH = "delivery.artifacts.signingKeyRef";
9
+ /**
10
+ * The provenance signing-key credential ref from HQ config at
11
+ * PROVENANCE_SIGNING_KEY_REF_PATH. There is no default: an unset or blank ref
12
+ * refuses, so artifacts are never signed with a built-in key.
13
+ */
14
+ export declare function signingKeyRefFromConfig(config: unknown): string;
15
+ /** Blob path relative to the store directory. Used by backup and restore (US-010). */
16
+ export declare function blobRelativePath(tenantId: string, partition: TrustPartition, digest: string): string;
17
+ export interface ArtifactStoreOptions {
18
+ access: DeliveryAccess;
19
+ /** The control-plane data directory (the delivery store directory). */
20
+ dir: string;
21
+ /** HMAC key for provenance. Only `ref` is stored; the value is looked up on each use. */
22
+ signing: {
23
+ ref: string;
24
+ source: CredentialSource;
25
+ };
26
+ }
27
+ export interface PutInput {
28
+ attemptId: string;
29
+ name: string;
30
+ bytes: Uint8Array;
31
+ inputs: BuildInputs;
32
+ }
33
+ export interface ArtifactView {
34
+ artifactId: string;
35
+ tenantId: string;
36
+ partition: TrustPartition;
37
+ digest: string;
38
+ size: number;
39
+ /**
40
+ * Absolute blob path, for diagnostics. Not verified at use: consume
41
+ * artifact bytes through read(), which re-checks signature and digest.
42
+ */
43
+ path: string;
44
+ cacheKey: string;
45
+ promoted: boolean;
46
+ provenance: ArtifactProvenance;
47
+ /** Cache keys this write invalidated. Empty except on put. */
48
+ invalidatedCacheKeys: string[];
49
+ }
50
+ /** Open the artifact store and remove blobs left unreferenced by a failed commit. */
51
+ export declare function openArtifactStore(opts: ArtifactStoreOptions): ArtifactStore;
52
+ export declare class ArtifactStore {
53
+ private readonly access;
54
+ private readonly dir;
55
+ private readonly signing;
56
+ constructor(opts: ArtifactStoreOptions);
57
+ /**
58
+ * Store bytes built by `identity` during an open attempt of its own company. Needs "report".
59
+ * Expired claim leases are swept first, and the commit checks the lease again, so a holder
60
+ * whose lease has run out is refused with ATTEMPT_ABANDONED and the cache is not touched.
61
+ */
62
+ put(identity: WorkerIdentity, input: PutInput): ArtifactView;
63
+ /** Verified bytes of an artifact of the worker's own company. Needs "read". */
64
+ read(identity: WorkerIdentity, artifactId: string): {
65
+ bytes: Buffer;
66
+ provenance: ArtifactProvenance;
67
+ promotedAt: string | null;
68
+ provenanceSignature: string;
69
+ };
70
+ /** Re-check the signature and blob of an artifact in scope. Throws ARTIFACT_TAMPERED. */
71
+ verify(scope: AdminScope, artifactId: string): ArtifactView;
72
+ /** The stored record, unverified. */
73
+ describe(scope: AdminScope, artifactId: string): ArtifactView;
74
+ /**
75
+ * Mark a release artifact promoted. Verifies first; refuses untrusted
76
+ * artifacts and artifacts whose attempt has not passed. Idempotent.
77
+ */
78
+ promote(scope: AdminScope, artifactId: string): ArtifactView;
79
+ /**
80
+ * Cache lookup for the worker's own company and trust partition. Returns a
81
+ * verified artifact or null. A hit that fails verification is evicted.
82
+ * Needs "read".
83
+ */
84
+ lookup(identity: WorkerIdentity, inputs: BuildInputs): ArtifactView | null;
85
+ /**
86
+ * Remove blob files no artifact record references, and leftover temp
87
+ * files. Only regular files under the artifacts directory are touched;
88
+ * symlinks and unknown entries are left alone. Returns the removed paths.
89
+ */
90
+ gc(): {
91
+ removed: string[];
92
+ };
93
+ private key;
94
+ private worker;
95
+ private find;
96
+ private unknown;
97
+ private scoped;
98
+ private sameTenant;
99
+ /** Check the signature, then the blob. Returns the verified bytes. */
100
+ private verifyStored;
101
+ private blobPath;
102
+ private writeBlob;
103
+ private view;
104
+ }
105
+ //# sourceMappingURL=artifacts.d.ts.map