@indigoai-us/hq-cli 5.345.225 → 5.345.226

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 (46) hide show
  1. package/CHANGELOG.md +32 -0
  2. package/dist/command-catalog.generated.d.ts +78 -0
  3. package/dist/command-catalog.generated.js +97 -0
  4. package/dist/commands/daemon.js +1 -1
  5. package/dist/commands/deploy-domains.js +38 -2
  6. package/dist/commands/lanes-accounts.d.ts +14 -0
  7. package/dist/commands/lanes-accounts.js +119 -0
  8. package/dist/commands/lanes-move.js +10 -0
  9. package/dist/commands/lanes-shared.js +9 -0
  10. package/dist/commands/lanes.js +137 -12
  11. package/dist/commands/sync-held.d.ts +22 -0
  12. package/dist/commands/sync-held.js +167 -18
  13. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  14. package/dist/hq-cloud-sync-runner/package.json +1 -1
  15. package/dist/lib/capacity/accounts.d.ts +4 -0
  16. package/dist/lib/capacity/accounts.js +4 -0
  17. package/dist/lib/capacity/route.js +14 -0
  18. package/dist/lib/capacity/sign-in.d.ts +18 -0
  19. package/dist/lib/capacity/sign-in.js +34 -1
  20. package/dist/lib/daemon/catalog.d.ts +1 -0
  21. package/dist/lib/daemon/catalog.js +1 -1
  22. package/dist/lib/daemon/hook-requests.d.ts +76 -0
  23. package/dist/lib/daemon/hook-requests.js +481 -0
  24. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  25. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  26. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  27. package/dist/lib/daemon/ops/policy.js +43 -4
  28. package/dist/lib/daemon/run.js +37 -4
  29. package/dist/lib/daemon/server.js +6 -1
  30. package/dist/lib/daemon/supervisor.d.ts +2 -0
  31. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  32. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  33. package/dist/lib/lanes/account-company.d.ts +7 -1
  34. package/dist/lib/lanes/account-company.js +22 -4
  35. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  36. package/dist/lib/lanes/account-ownership.js +134 -0
  37. package/dist/lib/lanes/accounts.js +9 -2
  38. package/dist/lib/lanes/claude-balance.js +9 -3
  39. package/dist/lib/lanes/config.js +17 -0
  40. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  41. package/dist/lib/lanes/host-capacity.js +37 -0
  42. package/dist/lib/lanes/reconcile.js +44 -3
  43. package/dist/lib/lanes/spawn.d.ts +0 -10
  44. package/dist/lib/lanes/spawn.js +51 -1
  45. package/dist/lib/lanes/types.d.ts +12 -0
  46. package/package.json +8 -8
@@ -0,0 +1,481 @@
1
+ /** Consumer for the request notes hq-hook leaves on PostToolUse
2
+ * (crates/hq-hook/src/daemon_req.rs; hq-core-rust owner decision 26).
3
+ *
4
+ * A hook that used to re-index, commit, copy a plan or edit a pull request
5
+ * now only decides that the work is due and leaves one small file in
6
+ * `~/.hq/daemon/hook-requests/<root key>/<kind>-<key>.json`. This module is
7
+ * the other half: the running daemon takes the notes of its own HQ root,
8
+ * oldest first, and does the work. No process is added: the drainer runs in
9
+ * the daemon, beside the Stop job drainer, under the same lease.
10
+ *
11
+ * A note is data, never a command. Only the kinds listed here are accepted,
12
+ * each with its own typed fields, and the arguments of the program that is
13
+ * started are built here from the validated fields.
14
+ *
15
+ * Life of a note `X.json`:
16
+ * - Invalid (version, kind, fields, size, another HQ root): deleted, one log line, nothing runs.
17
+ * - Older than a day: deleted, one log line, never run. The age is counted
18
+ * from the note's own time, and the hook writes a waiting note again on
19
+ * every new request for the same thing, so it is the age of the newest
20
+ * request, not of the first.
21
+ * - A folder, link or FIFO where a note or a claimed note should be is never
22
+ * run. It is deleted; one that cannot be deleted (a folder) is reported
23
+ * once per daemon run and left.
24
+ * - Claimed by renaming it to `X.run` before the work starts, so a request
25
+ * made during the work is a new `X.json` and runs afterwards.
26
+ * - Done: `X.run` and its side files are deleted.
27
+ * - Failed, or found as `X.run` at the start of a pass (the daemon stopped
28
+ * mid-work): the count in `X.attempts` goes up and the note is put back,
29
+ * unless a newer `X.json` is already there. It runs again after 5 s, then
30
+ * after 30 s. After the third failure it is deleted with one log line.
31
+ */
32
+ import { spawn } from "node:child_process";
33
+ import { createHash } from "node:crypto";
34
+ import * as fs from "node:fs";
35
+ import * as path from "node:path";
36
+ import { openStoreDir } from "../safe-store.js";
37
+ /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
38
+ export const HOOK_REQUEST_MAX_BYTES = 4096;
39
+ /** A note older than this is deleted and never run. */
40
+ export const HOOK_REQUEST_MAX_AGE_MS = 24 * 60 * 60_000;
41
+ /** Tries per note, and the waits before the second and third. */
42
+ export const HOOK_REQUEST_MAX_ATTEMPTS = 3;
43
+ export const HOOK_REQUEST_RETRY_DELAYS_MS = [5_000, 30_000];
44
+ /** The longest a request's program runs before it is killed. */
45
+ export const HOOK_REQUEST_KILL_MS = 60_000;
46
+ /** Notes handled per pass; the drainer schedules another pass at once when reached. */
47
+ export const HOOK_REQUEST_PASS_LIMIT = 64;
48
+ /** A writer's temporary file older than this was left by a hook that died mid-write. */
49
+ const TEMPORARY_MAX_AGE_MS = 60 * 60_000;
50
+ const STEM = /^([a-z][a-z-]{0,31})-([0-9a-f]{32})$/;
51
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : undefined;
52
+ const plain = (s) => typeof s === "string" && !s.includes("\0");
53
+ /** The folder name for an HQ root: 32 hex characters of SHA-256 over its real path (`root_key` in daemon_req.rs). */
54
+ export function hookRequestRootKey(root) {
55
+ let real = root;
56
+ try {
57
+ real = fs.realpathSync(root);
58
+ }
59
+ catch { /* A root that cannot be resolved is used as given, as the writer does. */ }
60
+ return createHash("sha256").update(real).digest("hex").slice(0, 32);
61
+ }
62
+ /** The request folder of `root` under `home`. */
63
+ export function hookRequestDir(home, root) {
64
+ return path.join(home, ".hq/daemon/hook-requests", hookRequestRootKey(root));
65
+ }
66
+ /** Read one note. `stem` is its file name without `.json`. Undefined for anything the writer does not produce. */
67
+ export function parseHookRequest(text, stem) {
68
+ if (Buffer.byteLength(text) > HOOK_REQUEST_MAX_BYTES)
69
+ return undefined;
70
+ const named = STEM.exec(stem);
71
+ if (!named)
72
+ return undefined;
73
+ let value;
74
+ try {
75
+ value = record(JSON.parse(text));
76
+ }
77
+ catch {
78
+ return undefined;
79
+ }
80
+ if (!value || value.v !== 1 || value.kind !== named[1] || value.key !== named[2]
81
+ || !plain(value.id) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.id)
82
+ || !plain(value.hqRoot) || !path.isAbsolute(value.hqRoot)
83
+ || !plain(value.session) || value.session.length > 512
84
+ || typeof value.at !== "string")
85
+ return undefined;
86
+ const at = Date.parse(value.at);
87
+ const args = record(value.args);
88
+ if (!Number.isFinite(at) || !args)
89
+ return undefined;
90
+ let operation;
91
+ if (value.kind === "reindex") {
92
+ if (Object.keys(args).length !== 0)
93
+ return undefined;
94
+ operation = { kind: "reindex" };
95
+ }
96
+ else
97
+ return undefined;
98
+ return { stem, id: value.id, at, root: value.hqRoot, session: value.session, operation };
99
+ }
100
+ /** The CLI arguments for a validated request. Nothing from the note is passed through as an argument except its checked root. */
101
+ export function hookRequestArguments(request) {
102
+ switch (request.operation.kind) {
103
+ case "reindex": return ["reindex", "--from-hook", "--repo-root", request.root];
104
+ }
105
+ }
106
+ const activeFolders = new Set();
107
+ /** Entries a pass could not delete or use, so each is reported once per daemon run. */
108
+ const reported = new Set();
109
+ const REPORTED_MAX = 1024;
110
+ /**
111
+ * One pass over the request folder of this daemon's HQ root. Returns the
112
+ * number of notes settled or tried. Notes of another HQ root are in another
113
+ * folder and are not touched.
114
+ */
115
+ export async function drainHookRequests(options) {
116
+ if (!options.ownsQueue())
117
+ return 0;
118
+ const root = options.root();
119
+ if (!root)
120
+ return 0;
121
+ const dir = hookRequestDir(options.home, root);
122
+ if (activeFolders.has(dir))
123
+ return 0;
124
+ activeFolders.add(dir);
125
+ try {
126
+ const opened = openStoreDir(dir, { home: options.home });
127
+ if (!opened.ok) {
128
+ if (opened.code !== "folder-missing")
129
+ options.log(`Hook request folder unavailable: ${opened.code}`);
130
+ return 0;
131
+ }
132
+ try {
133
+ return await new Pass(opened.value, root, options).run();
134
+ }
135
+ finally {
136
+ opened.value.close();
137
+ }
138
+ }
139
+ finally {
140
+ activeFolders.delete(dir);
141
+ }
142
+ }
143
+ class Pass {
144
+ store;
145
+ root;
146
+ options;
147
+ done = 0;
148
+ constructor(store, root, options) {
149
+ this.store = store;
150
+ this.root = root;
151
+ this.options = options;
152
+ }
153
+ now() { return (this.options.now ?? Date.now)(); }
154
+ log(message) { this.options.log(message); }
155
+ /** Log about an entry that stays in the folder: once per daemon run, not on every pass. */
156
+ once(name, message) {
157
+ const key = `${this.store.path}/${name}`;
158
+ if (reported.has(key))
159
+ return;
160
+ // Bounded: past this many entries the memory starts over, and a line may be said a second time.
161
+ if (reported.size >= REPORTED_MAX)
162
+ reported.clear();
163
+ reported.add(key);
164
+ this.log(message);
165
+ }
166
+ async run() {
167
+ const listed = this.store.list();
168
+ if (!listed.ok) {
169
+ this.log(`Hook request folder could not be read: ${listed.code}`);
170
+ return 0;
171
+ }
172
+ const names = new Set(listed.value);
173
+ for (const name of listed.value) {
174
+ if (name.startsWith(".") && name.endsWith(".tmp"))
175
+ this.removeStaleTemporary(name);
176
+ else if (name.endsWith(".run"))
177
+ this.recover(name.slice(0, -".run".length), names);
178
+ }
179
+ const waiting = [];
180
+ for (const name of [...names].sort()) {
181
+ if (!name.endsWith(".json"))
182
+ continue;
183
+ const request = this.load(name.slice(0, -".json".length));
184
+ if (request)
185
+ waiting.push(request);
186
+ }
187
+ waiting.sort((a, b) => a.at - b.at || (a.stem < b.stem ? -1 : a.stem > b.stem ? 1 : 0));
188
+ for (const request of waiting) {
189
+ if (this.done >= HOOK_REQUEST_PASS_LIMIT)
190
+ break;
191
+ if (!this.options.ownsQueue()) {
192
+ this.log("Hook request lease was lost; notes retained");
193
+ break;
194
+ }
195
+ await this.work(request);
196
+ }
197
+ return this.done;
198
+ }
199
+ removeStaleTemporary(name) {
200
+ const facts = this.store.stat(name);
201
+ if (facts.ok && this.now() - facts.value.mtimeMs > TEMPORARY_MAX_AGE_MS)
202
+ this.store.remove(name);
203
+ }
204
+ attempts(stem) {
205
+ const read = this.store.readWithFacts(`${stem}.attempts`, { maxBytes: 16 });
206
+ if (!read.ok)
207
+ return { count: 0, at: 0 };
208
+ const count = Number(read.value.data.toString().trim());
209
+ // An unreadable count cannot say how often the request ran: treat it as one try short of the limit.
210
+ return { count: Number.isSafeInteger(count) && count >= 0 ? count : HOOK_REQUEST_MAX_ATTEMPTS - 1, at: read.value.facts.mtimeMs };
211
+ }
212
+ forget(stem) {
213
+ for (const suffix of [".run", ".attempts", ".body"])
214
+ this.store.remove(`${stem}${suffix}`);
215
+ }
216
+ /** Count one failed try of the claimed note `stem.run` and put it back, or give up. */
217
+ failed(stem, why) {
218
+ const count = this.attempts(stem).count + 1;
219
+ if (count >= HOOK_REQUEST_MAX_ATTEMPTS) {
220
+ this.forget(stem);
221
+ this.log(`Hook request ${stem} gave up after ${count} tries (${why}); deleted`);
222
+ return;
223
+ }
224
+ if (!this.store.writeAtomic(`${stem}.attempts`, String(count)).ok) {
225
+ // Without a count the note could run for ever: drop it instead.
226
+ this.forget(stem);
227
+ this.log(`Hook request ${stem} failed (${why}) and its try count could not be saved; deleted`);
228
+ return;
229
+ }
230
+ if (this.store.stat(`${stem}.json`).ok) {
231
+ // A newer request for the same thing is waiting and starts with a clean count.
232
+ this.forget(stem);
233
+ this.log(`Hook request ${stem} failed (${why}); a newer request replaces it`);
234
+ return;
235
+ }
236
+ const back = this.store.rename(`${stem}.run`, `${stem}.json`);
237
+ if (!back.ok) {
238
+ this.forget(stem);
239
+ this.log(`Hook request ${stem} failed (${why}) and could not be put back (${back.code}); deleted`);
240
+ return;
241
+ }
242
+ this.log(`Hook request ${stem} failed (${why}); try ${count + 1} of ${HOOK_REQUEST_MAX_ATTEMPTS} follows`);
243
+ }
244
+ /** A claimed note found at the start of a pass: its work was interrupted. */
245
+ recover(stem, names) {
246
+ const claimed = this.store.stat(`${stem}.run`);
247
+ if (!claimed.ok && (claimed.code === "file-link" || claimed.code === "not-regular-file")) {
248
+ // Not a note this daemon claimed: a folder, a link, a FIFO or a device. The daemon claims by renaming a
249
+ // regular file, so this was never work in progress: no try is counted and nothing is put back. Any other
250
+ // refusal (a read error, a file whose mode or owner changed) is still a claimed note and is counted
251
+ // and retried below, as before.
252
+ names.delete(`${stem}.run`);
253
+ const removed = this.store.remove(`${stem}.run`);
254
+ if (removed.ok) {
255
+ this.done += 1;
256
+ this.log(`Hook request ${stem}.run is not a claimed note (${claimed.code}); deleted, nothing was run`);
257
+ }
258
+ else {
259
+ this.once(`${stem}.run`, `Hook request ${stem}.run is not a claimed note (${claimed.code}) and could not be deleted (${removed.code}); requests under this name cannot run until it is removed`);
260
+ }
261
+ return;
262
+ }
263
+ this.done += 1;
264
+ this.failed(stem, "interrupted");
265
+ names.delete(`${stem}.run`);
266
+ if (this.store.stat(`${stem}.json`).ok)
267
+ names.add(`${stem}.json`);
268
+ else
269
+ names.delete(`${stem}.json`);
270
+ }
271
+ /** Read and check a waiting note. An invalid or expired note is deleted here. */
272
+ load(stem) {
273
+ const drop = (why) => {
274
+ const removed = this.store.remove(`${stem}.json`);
275
+ this.forget(stem);
276
+ if (!removed.ok) {
277
+ // An entry that cannot be removed (a link, another user's file) stays; say so once, not on every pass.
278
+ this.once(`${stem}.json`, `Hook request ${stem} ${why}, but it could not be deleted (${removed.code})`);
279
+ return undefined;
280
+ }
281
+ this.done += 1;
282
+ this.log(`Hook request ${stem} ${why}`);
283
+ return undefined;
284
+ };
285
+ const read = this.store.read(`${stem}.json`, { maxBytes: HOOK_REQUEST_MAX_BYTES });
286
+ if (!read.ok) {
287
+ if (read.code === "missing")
288
+ return undefined;
289
+ return drop(`refused (${read.code}); deleted, nothing was run`);
290
+ }
291
+ const request = parseHookRequest(read.value.toString(), stem);
292
+ if (!request)
293
+ return drop("rejected; deleted, nothing was run");
294
+ let same;
295
+ try {
296
+ same = fs.realpathSync(request.root) === fs.realpathSync(this.root);
297
+ }
298
+ catch {
299
+ same = false;
300
+ }
301
+ if (!same)
302
+ return drop("names another HQ root; deleted, nothing was run");
303
+ if (this.now() - request.at > HOOK_REQUEST_MAX_AGE_MS)
304
+ return this.expire(stem);
305
+ return request;
306
+ }
307
+ /** Delete a note that was read as older than a day. The hook may write the note again at any moment, and a
308
+ * delete by name would take the new one. So the note is renamed aside first, as for work, and read again:
309
+ * what is deleted is the file that was renamed, and a note written after the rename is a new file. */
310
+ expire(stem) {
311
+ const claimed = this.store.rename(`${stem}.json`, `${stem}.run`);
312
+ if (!claimed.ok) {
313
+ if (claimed.code !== "missing")
314
+ this.once(`${stem}.run`, `Hook request ${stem} is older than a day, but it could not be claimed for deletion: ${claimed.code}`);
315
+ return undefined;
316
+ }
317
+ const read = this.store.read(`${stem}.run`, { maxBytes: HOOK_REQUEST_MAX_BYTES });
318
+ const again = read.ok ? parseHookRequest(read.value.toString(), stem) : undefined;
319
+ if (again && this.now() - again.at <= HOOK_REQUEST_MAX_AGE_MS) {
320
+ // Written again between the read and the rename: it is a fresh request. Put it back for the next pass,
321
+ // unless a still newer note is already waiting.
322
+ if (this.store.stat(`${stem}.json`).ok || !this.store.rename(`${stem}.run`, `${stem}.json`).ok)
323
+ this.store.remove(`${stem}.run`);
324
+ return undefined;
325
+ }
326
+ this.store.remove(`${stem}.run`);
327
+ // The side files belong to a newer note when one arrived after the rename.
328
+ if (!this.store.stat(`${stem}.json`).ok)
329
+ for (const suffix of [".attempts", ".body"])
330
+ this.store.remove(`${stem}${suffix}`);
331
+ this.done += 1;
332
+ this.log(`Hook request ${stem} is older than a day; deleted, never run`);
333
+ return undefined;
334
+ }
335
+ async work(request) {
336
+ const { stem } = request;
337
+ const tried = this.attempts(stem);
338
+ if (tried.count >= HOOK_REQUEST_MAX_ATTEMPTS) {
339
+ this.done += 1;
340
+ this.store.remove(`${stem}.json`);
341
+ this.forget(stem);
342
+ this.log(`Hook request ${stem} gave up after ${tried.count} tries; deleted`);
343
+ return;
344
+ }
345
+ if (tried.count > 0) {
346
+ const delays = this.options.retryDelaysMs ?? HOOK_REQUEST_RETRY_DELAYS_MS;
347
+ const wait = delays[Math.min(tried.count, delays.length) - 1] ?? 0;
348
+ if (wait > 0 && this.now() - tried.at < wait)
349
+ return;
350
+ }
351
+ const claimed = this.store.rename(`${stem}.json`, `${stem}.run`);
352
+ if (!claimed.ok) {
353
+ // The note stays and is tried on every pass; the reason is said once (the same key as an entry in the
354
+ // claimed note's place, which is the usual cause and has then been reported already).
355
+ if (claimed.code !== "missing")
356
+ this.once(`${stem}.run`, `Hook request ${stem} could not be claimed: ${claimed.code}`);
357
+ return;
358
+ }
359
+ this.done += 1;
360
+ let result;
361
+ try {
362
+ result = await this.options.execute(request);
363
+ }
364
+ catch {
365
+ result = { code: 1 };
366
+ }
367
+ if (result.code === 0) {
368
+ this.forget(stem);
369
+ return;
370
+ }
371
+ this.failed(stem, `exit ${result.code}`);
372
+ }
373
+ }
374
+ /** Startup scan plus folder notifications, with a 5 s fallback scan when a
375
+ * watcher is unavailable or an event was missed. Close waits for the request
376
+ * in progress. */
377
+ export function startHookRequestDrainer(options) {
378
+ let watcher;
379
+ let watched;
380
+ let timer;
381
+ let running;
382
+ let closed = false;
383
+ let again = false;
384
+ let failing = false;
385
+ const schedule = (delay = 50) => {
386
+ if (closed)
387
+ return;
388
+ if (timer)
389
+ clearTimeout(timer);
390
+ timer = setTimeout(run, delay);
391
+ timer.unref();
392
+ };
393
+ const watch = () => {
394
+ const root = options.root();
395
+ const dir = root ? hookRequestDir(options.home, root) : undefined;
396
+ if (dir === watched && watcher)
397
+ return;
398
+ watcher?.close();
399
+ watcher = undefined;
400
+ watched = dir;
401
+ if (!dir)
402
+ return;
403
+ try {
404
+ watcher = fs.watch(dir, (_kind, filename) => {
405
+ if (filename === null || filename.toString().endsWith(".json"))
406
+ schedule();
407
+ });
408
+ watcher.on("error", () => { watcher?.close(); watcher = undefined; schedule(1000); });
409
+ watcher.unref();
410
+ }
411
+ catch { /* Before the first note the folder does not exist: the fallback scan retries. */ }
412
+ };
413
+ const run = () => {
414
+ timer = undefined;
415
+ if (closed)
416
+ return;
417
+ if (running) {
418
+ again = true;
419
+ return;
420
+ }
421
+ // `options.root()` reads the daemon config and throws on a malformed one. watch() calls it, so it runs
422
+ // inside the chain: a throw in this timer callback would end the drainer without its next scan.
423
+ running = Promise.resolve().then(() => { watch(); return drainHookRequests(options); })
424
+ .then(count => { failing = false; if (count >= HOOK_REQUEST_PASS_LIMIT)
425
+ again = true; })
426
+ .catch(() => {
427
+ // Said when scans start failing, not on every 5 s scan while they do.
428
+ if (!failing)
429
+ options.log("Hook request scan failed; notes retained");
430
+ failing = true;
431
+ })
432
+ .finally(() => {
433
+ running = undefined;
434
+ schedule(again ? 0 : options.scanIntervalMs ?? 5000);
435
+ again = false;
436
+ });
437
+ };
438
+ schedule(0);
439
+ return { async close() { closed = true; if (timer)
440
+ clearTimeout(timer); watcher?.close(); await running; } };
441
+ }
442
+ /** Run a validated request through the daemon's own CLI entry point. */
443
+ export function executeHookRequest(request, options) {
444
+ try {
445
+ if (!options.allowedRoot || fs.realpathSync(request.root) !== fs.realpathSync(options.allowedRoot))
446
+ return Promise.resolve({ code: 1 });
447
+ if (!fs.statSync(path.join(request.root, "core/core.yaml")).isFile())
448
+ return Promise.resolve({ code: 1 });
449
+ }
450
+ catch {
451
+ return Promise.resolve({ code: 1 });
452
+ }
453
+ const args = hookRequestArguments(request);
454
+ // The two variables reindex.sh set: no update check, and no wait for the
455
+ // per-root operation lock (a busy lock is a failed try, retried later).
456
+ const env = { ...(options.env ?? process.env), HQ_ROOT: request.root, HQ_NO_UPDATE_CHECK: "1", HQ_OP_LOCK_TIMEOUT: "0", HQ_HOOK_REQUEST_ID: request.id };
457
+ return new Promise(resolve => {
458
+ if (options.signal?.aborted) {
459
+ resolve({ code: 1 });
460
+ return;
461
+ }
462
+ const child = spawn(options.nodeBinary, [options.hqBinary, ...args], {
463
+ cwd: request.root, env, shell: false, windowsHide: true, stdio: "ignore",
464
+ });
465
+ const stop = () => { child.kill("SIGTERM"); };
466
+ options.signal?.addEventListener("abort", stop, { once: true });
467
+ const timer = setTimeout(() => child.kill("SIGKILL"), options.timeoutMs ?? HOOK_REQUEST_KILL_MS);
468
+ let settled = false;
469
+ const finish = (code) => {
470
+ if (settled)
471
+ return;
472
+ settled = true;
473
+ clearTimeout(timer);
474
+ options.signal?.removeEventListener("abort", stop);
475
+ resolve({ code });
476
+ };
477
+ child.once("error", () => finish(1));
478
+ child.once("close", code => finish(code ?? 1));
479
+ });
480
+ }
481
+ //# sourceMappingURL=hook-requests.js.map
@@ -0,0 +1,35 @@
1
+ /**
2
+ * The status line of the in-process lanes reconcile.
3
+ *
4
+ * While the lane-store watcher owns reconcile the catalog plans no
5
+ * `lanes-reconcile` unit, so the supervisor has no state for it. This records
6
+ * the outcome of each watcher run and adds one unit entry to the state file
7
+ * `hq daemon status` reads.
8
+ */
9
+ import type { DaemonState } from "./supervisor.js";
10
+ type Unit = DaemonState["units"][number];
11
+ /** The longest `lastError` written to the state file, in UTF-8 bytes. */
12
+ export declare const LANES_RECONCILE_ERROR_BYTES = 300;
13
+ /** One line, no secrets, no control characters (it is printed to a terminal), at most LANES_RECONCILE_ERROR_BYTES. */
14
+ export declare function lanesReconcileErrorText(error: unknown): string;
15
+ export interface LanesReconcileStatus {
16
+ /** The same reconcile, with its outcome recorded. A failure is rethrown. */
17
+ track(reconcile: () => Promise<void>): () => Promise<void>;
18
+ /** Forget the recorded outcome (the watcher was closed or replaced). */
19
+ reset(): void;
20
+ /** The unit entry for the state file. */
21
+ unit(signedIn: boolean): Unit;
22
+ }
23
+ export declare function createLanesReconcileStatus(options?: {
24
+ now?: () => number;
25
+ /** Called after each run has been recorded. */
26
+ onChange?: () => void;
27
+ }): LanesReconcileStatus;
28
+ /**
29
+ * `state` with the in-process reconcile's unit, placed where the timed unit
30
+ * would be in `services` order. A planned `lanes-reconcile` unit (the timed
31
+ * fallback) is left alone.
32
+ */
33
+ export declare function withLanesReconcileUnit(state: DaemonState, unit: Unit | null, services: readonly string[]): DaemonState;
34
+ export {};
35
+ //# sourceMappingURL=lanes-reconcile-status.d.ts.map
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The status line of the in-process lanes reconcile.
3
+ *
4
+ * While the lane-store watcher owns reconcile the catalog plans no
5
+ * `lanes-reconcile` unit, so the supervisor has no state for it. This records
6
+ * the outcome of each watcher run and adds one unit entry to the state file
7
+ * `hq daemon status` reads.
8
+ */
9
+ import { redactForLog } from "../bot/log.js";
10
+ import { redactSecrets } from "../db/redact.js";
11
+ import { NOT_SIGNED_IN, SERVICE_DESCRIPTIONS } from "./catalog.js";
12
+ import { cutUtf8 } from "./state-file.js";
13
+ /** The longest `lastError` written to the state file, in UTF-8 bytes. */
14
+ export const LANES_RECONCILE_ERROR_BYTES = 300;
15
+ const UNIT_ID = "lanes-reconcile";
16
+ /** One line, no secrets, no control characters (it is printed to a terminal), at most LANES_RECONCILE_ERROR_BYTES. */
17
+ export function lanesReconcileErrorText(error) {
18
+ const raw = error instanceof Error ? error.message : String(error);
19
+ const oneLine = redactSecrets(redactForLog(raw)).replace(/\p{Cc}+/gu, " ").replace(/\s+/g, " ").trim();
20
+ return cutUtf8(oneLine, LANES_RECONCILE_ERROR_BYTES);
21
+ }
22
+ export function createLanesReconcileStatus(options = {}) {
23
+ const now = options.now ?? Date.now;
24
+ let lastRunAt;
25
+ let lastResult;
26
+ let lastError;
27
+ return {
28
+ track: (reconcile) => async () => {
29
+ lastRunAt = now();
30
+ try {
31
+ await reconcile();
32
+ lastResult = "ok";
33
+ lastError = undefined;
34
+ }
35
+ catch (error) {
36
+ lastResult = "failed";
37
+ lastError = lanesReconcileErrorText(error);
38
+ throw error;
39
+ }
40
+ finally {
41
+ try {
42
+ options.onChange?.();
43
+ }
44
+ catch {
45
+ // Reporting never changes the reconcile outcome.
46
+ }
47
+ }
48
+ },
49
+ reset: () => {
50
+ lastRunAt = undefined;
51
+ lastResult = undefined;
52
+ lastError = undefined;
53
+ },
54
+ unit: (signedIn) => {
55
+ const failed = lastResult === "failed";
56
+ const waiting = failed && !signedIn;
57
+ return {
58
+ id: UNIT_ID,
59
+ service: UNIT_ID,
60
+ kind: "scheduled",
61
+ description: SERVICE_DESCRIPTIONS[UNIT_ID],
62
+ status: waiting ? "waiting" : "idle",
63
+ ...(waiting ? { reason: NOT_SIGNED_IN } : {}),
64
+ restarts: 0,
65
+ ...(lastRunAt !== undefined ? { lastRunAt } : {}),
66
+ ...(lastResult ? { lastResult } : {}),
67
+ ...(failed && lastError !== undefined ? { lastError } : {}),
68
+ };
69
+ },
70
+ };
71
+ }
72
+ /**
73
+ * `state` with the in-process reconcile's unit, placed where the timed unit
74
+ * would be in `services` order. A planned `lanes-reconcile` unit (the timed
75
+ * fallback) is left alone.
76
+ */
77
+ export function withLanesReconcileUnit(state, unit, services) {
78
+ if (!unit || state.units.some((u) => u.id === unit.id))
79
+ return state;
80
+ const position = services.indexOf(unit.service);
81
+ const at = position < 0 ? -1 : state.units.findIndex((u) => services.indexOf(u.service) > position);
82
+ const units = [...state.units];
83
+ units.splice(at < 0 ? units.length : at, 0, unit);
84
+ return { ...state, units };
85
+ }
86
+ //# sourceMappingURL=lanes-reconcile-status.js.map
@@ -21,7 +21,7 @@ export declare const SCOPE_AUTHORIZER = ".claude/hooks/mandatory-scope-authorize
21
21
  export declare const POLICY_TRIGGER = ".claude/hooks/inject-policy-on-trigger.sh";
22
22
  export declare class PolicyOpError extends Error {
23
23
  readonly code: string;
24
- constructor(code: string, message: string);
24
+ constructor(code: string, message: string, options?: ErrorOptions);
25
25
  }
26
26
  export interface PolicyEntry {
27
27
  slug: string;
@@ -28,8 +28,8 @@ const SLUG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
28
28
  const SESSION_RE = /^[A-Za-z0-9._-]+$/;
29
29
  export class PolicyOpError extends Error {
30
30
  code;
31
- constructor(code, message) {
32
- super(message);
31
+ constructor(code, message, options) {
32
+ super(message, options);
33
33
  this.code = code;
34
34
  this.name = "PolicyOpError";
35
35
  }
@@ -308,7 +308,46 @@ function blockFromJson(stdout) {
308
308
  }
309
309
  return null;
310
310
  }
311
+ /**
312
+ * EPERM from the HQ root: on macOS, hqd runs under launchd and has no privacy
313
+ * consent for ~/Documents, ~/Desktop or iCloud Drive, so it cannot open the
314
+ * session files there although the user's own session can. Report it under its
315
+ * own code so the hook shim runs the scope check in the hook process (which has
316
+ * the host app's consent) instead of failing closed on a raw "internal" error.
317
+ */
318
+ function hqRootUnreadable(err, hqRoot) {
319
+ if (err?.code !== "EPERM")
320
+ return null;
321
+ return new PolicyOpError("hq_root_unreadable", `hqd cannot read the HQ folder at ${hqRoot} (operation not permitted). On macOS, grant Full Disk Access to the node binary hqd runs, or keep HQ outside Documents, Desktop and iCloud Drive.`,
322
+ // Keep the fs error as the cause: hqd's TCC EPERM guard (tcc-eperm.ts)
323
+ // follows `cause` to count EPERM reads under the HQ root. Only code and
324
+ // message go over the socket, so the cause is never sent to the caller.
325
+ { cause: err });
326
+ }
327
+ /** True when `file` exists. ENOENT/ENOTDIR are "no"; any other error (EPERM) is thrown. */
328
+ function fileExists(file) {
329
+ try {
330
+ fs.statSync(file);
331
+ return true;
332
+ }
333
+ catch (err) {
334
+ const code = err.code;
335
+ if (code === "ENOENT" || code === "ENOTDIR")
336
+ return false;
337
+ throw err;
338
+ }
339
+ }
311
340
  export async function policyCheck(args, deps) {
341
+ // Every step reads the HQ root (session files, hook scripts, the policy
342
+ // index, the scripts' cwd), so EPERM from any of them means the same thing.
343
+ try {
344
+ return await policyCheckUnmapped(args, deps);
345
+ }
346
+ catch (err) {
347
+ throw hqRootUnreadable(err, deps.hqRoot) ?? err;
348
+ }
349
+ }
350
+ async function policyCheckUnmapped(args, deps) {
312
351
  const { hqRoot } = deps;
313
352
  if (args.company !== undefined && !SLUG_RE.test(args.company))
314
353
  throw new PolicyOpError("bad_args", "company must be a company slug");
@@ -317,7 +356,7 @@ export async function policyCheck(args, deps) {
317
356
  }
318
357
  const authorizer = path.join(hqRoot, SCOPE_AUTHORIZER);
319
358
  const trigger = path.join(hqRoot, POLICY_TRIGGER);
320
- if (!fs.existsSync(authorizer)) {
359
+ if (!fileExists(authorizer)) {
321
360
  throw new PolicyOpError("policy_engine_unavailable", `scope authorizer not found at ${authorizer}`);
322
361
  }
323
362
  const event = args.event ?? "PreToolUse";
@@ -362,7 +401,7 @@ export async function policyCheck(args, deps) {
362
401
  }
363
402
  }
364
403
  let additionalContext = "";
365
- if (fs.existsSync(trigger)) {
404
+ if (fileExists(trigger)) {
366
405
  const r = await runScript(trigger, payload, env, hqRoot, timeoutMs);
367
406
  if (r.code === 0 && !r.timedOut)
368
407
  additionalContext = extractContext(r.stdout);