@indigoai-us/hq-cli 5.345.225 → 5.345.228

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 (164) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/command-catalog.generated.d.ts +215 -0
  3. package/dist/command-catalog.generated.js +261 -0
  4. package/dist/commands/auth.d.ts +2 -2
  5. package/dist/commands/auth.js +3 -3
  6. package/dist/commands/core-delegate-w1b.js +92 -69
  7. package/dist/commands/core-delegate.d.ts +19 -1
  8. package/dist/commands/core-delegate.js +411 -6
  9. package/dist/commands/core-dm-bind-native.js +2 -1
  10. package/dist/commands/core-handoff.d.ts +5 -0
  11. package/dist/commands/core-handoff.js +1008 -14
  12. package/dist/commands/core-pin-native.d.ts +1 -0
  13. package/dist/commands/core-pin-native.js +3 -15
  14. package/dist/commands/core-register-project-native.d.ts +6 -0
  15. package/dist/commands/core-register-project-native.js +182 -52
  16. package/dist/commands/core-work-mesh-bind-trusted-native.js +4 -9
  17. package/dist/commands/daemon.js +3 -3
  18. package/dist/commands/deploy-domains.js +38 -2
  19. package/dist/commands/index-cmd.d.ts +3 -1
  20. package/dist/commands/index-cmd.js +12 -0
  21. package/dist/commands/lanes-accounts.d.ts +14 -0
  22. package/dist/commands/lanes-accounts.js +119 -0
  23. package/dist/commands/lanes-checks.js +1 -1
  24. package/dist/commands/lanes-move.js +10 -0
  25. package/dist/commands/lanes-session-start.d.ts +1 -2
  26. package/dist/commands/lanes-session-start.js +9 -145
  27. package/dist/commands/lanes-shared.d.ts +3 -0
  28. package/dist/commands/lanes-shared.js +9 -0
  29. package/dist/commands/lanes.d.ts +3 -0
  30. package/dist/commands/lanes.js +231 -39
  31. package/dist/commands/link.d.ts +8 -3
  32. package/dist/commands/link.js +14 -17
  33. package/dist/commands/mcp-registration.d.ts +65 -7
  34. package/dist/commands/mcp-registration.js +289 -51
  35. package/dist/commands/mesh.d.ts +12 -0
  36. package/dist/commands/mesh.js +92 -10
  37. package/dist/commands/reindex.js +6 -0
  38. package/dist/commands/repo.d.ts +13 -0
  39. package/dist/commands/repo.js +39 -1
  40. package/dist/commands/sync-held.d.ts +22 -0
  41. package/dist/commands/sync-held.js +167 -18
  42. package/dist/commands/sync-mode.d.ts +3 -1
  43. package/dist/commands/sync-mode.js +11 -1
  44. package/dist/hq-cloud-sync-runner/bin/sync-runner.js +4845 -2524
  45. package/dist/hq-cloud-sync-runner/package.json +1 -1
  46. package/dist/lazy-commands.js +3 -4
  47. package/dist/lib/capacity/accounts.d.ts +4 -0
  48. package/dist/lib/capacity/accounts.js +4 -0
  49. package/dist/lib/capacity/route.js +14 -0
  50. package/dist/lib/capacity/sign-in.d.ts +18 -0
  51. package/dist/lib/capacity/sign-in.js +34 -1
  52. package/dist/lib/checkpoint-ontology/entity-file.js +4 -4
  53. package/dist/lib/checkpoint-ontology/merge-copies.js +7 -11
  54. package/dist/lib/checkpoint-ontology/plan.js +2 -1
  55. package/dist/lib/core-utils/archive-old-threads.js +5 -2
  56. package/dist/lib/core-utils/session-company.d.ts +13 -1
  57. package/dist/lib/core-utils/session-company.js +75 -4
  58. package/dist/lib/core-utils/worktree-resume.d.ts +6 -0
  59. package/dist/lib/core-utils/worktree-resume.js +8 -4
  60. package/dist/lib/daemon/background-qos.d.ts +7 -0
  61. package/dist/lib/daemon/background-qos.js +13 -0
  62. package/dist/lib/daemon/catalog.d.ts +10 -0
  63. package/dist/lib/daemon/catalog.js +9 -2
  64. package/dist/lib/daemon/hook-requests-acl-suggest.d.ts +18 -0
  65. package/dist/lib/daemon/hook-requests-acl-suggest.js +245 -0
  66. package/dist/lib/daemon/hook-requests-fleet-session-start.d.ts +32 -0
  67. package/dist/lib/daemon/hook-requests-fleet-session-start.js +214 -0
  68. package/dist/lib/daemon/hook-requests-mesh-tool-writes.d.ts +44 -0
  69. package/dist/lib/daemon/hook-requests-mesh-tool-writes.js +292 -0
  70. package/dist/lib/daemon/hook-requests-mesh.d.ts +54 -0
  71. package/dist/lib/daemon/hook-requests-mesh.js +559 -0
  72. package/dist/lib/daemon/hook-requests.d.ts +417 -0
  73. package/dist/lib/daemon/hook-requests.js +1747 -0
  74. package/dist/lib/daemon/lanes-reconcile-status.d.ts +35 -0
  75. package/dist/lib/daemon/lanes-reconcile-status.js +86 -0
  76. package/dist/lib/daemon/machine-checks.d.ts +12 -2
  77. package/dist/lib/daemon/machine-checks.js +27 -10
  78. package/dist/lib/daemon/merge-sections.d.ts +24 -2
  79. package/dist/lib/daemon/merge-sections.js +58 -16
  80. package/dist/lib/daemon/ops/policy.d.ts +1 -1
  81. package/dist/lib/daemon/ops/policy.js +47 -6
  82. package/dist/lib/daemon/resolver.js +9 -2
  83. package/dist/lib/daemon/run.d.ts +11 -7
  84. package/dist/lib/daemon/run.js +195 -18
  85. package/dist/lib/daemon/search-index-worker-v1.d.ts +2 -0
  86. package/dist/lib/daemon/search-index-worker-v1.js +25 -0
  87. package/dist/lib/daemon/server.js +6 -1
  88. package/dist/lib/daemon/session-registry.d.ts +0 -1
  89. package/dist/lib/daemon/session-registry.js +0 -3
  90. package/dist/lib/daemon/supervisor.d.ts +5 -1
  91. package/dist/lib/daemon/supervisor.js +1 -1
  92. package/dist/lib/daemon/tcc-eperm.d.ts +59 -4
  93. package/dist/lib/daemon/tcc-eperm.js +110 -8
  94. package/dist/lib/doctor/fix/process-identity.d.ts +20 -2
  95. package/dist/lib/doctor/fix/process-identity.js +48 -5
  96. package/dist/lib/flag-registry-worker-source.generated.d.ts +1 -1
  97. package/dist/lib/flag-registry-worker-source.generated.js +1 -1
  98. package/dist/lib/hook-engine/canary-gate.js +1 -0
  99. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  100. package/dist/lib/hot-channels/adapters/attio.js +2 -1
  101. package/dist/lib/hot-channels/adapters/meetings.js +2 -1
  102. package/dist/lib/lanes/account-company.d.ts +7 -1
  103. package/dist/lib/lanes/account-company.js +22 -4
  104. package/dist/lib/lanes/account-ownership.d.ts +65 -0
  105. package/dist/lib/lanes/account-ownership.js +134 -0
  106. package/dist/lib/lanes/accounts.js +9 -2
  107. package/dist/lib/lanes/claude-balance.js +9 -3
  108. package/dist/lib/lanes/company-outposts.d.ts +37 -0
  109. package/dist/lib/lanes/company-outposts.js +164 -0
  110. package/dist/lib/lanes/config.js +17 -0
  111. package/dist/lib/lanes/host-capacity.d.ts +19 -0
  112. package/dist/lib/lanes/host-capacity.js +37 -0
  113. package/dist/lib/lanes/liveness.d.ts +6 -0
  114. package/dist/lib/lanes/liveness.js +49 -8
  115. package/dist/lib/lanes/orphan-report.d.ts +15 -0
  116. package/dist/lib/lanes/orphan-report.js +223 -0
  117. package/dist/lib/lanes/orphan-sweep.d.ts +26 -0
  118. package/dist/lib/lanes/orphan-sweep.js +152 -0
  119. package/dist/lib/lanes/reaper.d.ts +2 -0
  120. package/dist/lib/lanes/reaper.js +11 -8
  121. package/dist/lib/lanes/reconcile.d.ts +8 -7
  122. package/dist/lib/lanes/reconcile.js +83 -3
  123. package/dist/lib/lanes/spawn.d.ts +0 -10
  124. package/dist/lib/lanes/spawn.js +51 -1
  125. package/dist/lib/lanes/types.d.ts +12 -0
  126. package/dist/lib/mesh/live/backfill-held.d.ts +13 -0
  127. package/dist/lib/mesh/live/backfill-held.js +23 -0
  128. package/dist/lib/mesh/live/daemon/mode.d.ts +8 -4
  129. package/dist/lib/mesh/live/daemon/mode.js +8 -4
  130. package/dist/lib/mesh/live/daemon/run.d.ts +14 -3
  131. package/dist/lib/mesh/live/daemon/run.js +116 -7
  132. package/dist/lib/mesh/live/direct-drain.d.ts +123 -0
  133. package/dist/lib/mesh/live/direct-drain.js +315 -0
  134. package/dist/lib/mesh/live/emit-replay.d.ts +10 -0
  135. package/dist/lib/mesh/live/emit-replay.js +10 -0
  136. package/dist/lib/mesh/live/flush.d.ts +15 -0
  137. package/dist/lib/mesh/live/flush.js +27 -0
  138. package/dist/lib/mesh/live/liveness-carry.d.ts +45 -0
  139. package/dist/lib/mesh/live/liveness-carry.js +141 -0
  140. package/dist/lib/mesh/live/spool.d.ts +19 -0
  141. package/dist/lib/mesh/live/spool.js +80 -0
  142. package/dist/lib/safe-store.d.ts +2 -0
  143. package/dist/lib/safe-store.js +8 -6
  144. package/dist/lib/search-index/index.d.ts +9 -3
  145. package/dist/lib/search-index/index.js +35 -10
  146. package/dist/lib/search-index/worker-process.d.ts +9 -0
  147. package/dist/lib/search-index/worker-process.js +171 -0
  148. package/dist/lib/session-company-lock.d.ts +3 -1
  149. package/dist/lib/session-company-lock.js +3 -2
  150. package/dist/utils/delegate-command-supervisor.d.ts +3 -0
  151. package/dist/utils/delegate-command-supervisor.js +44 -0
  152. package/dist/utils/delegate-lock.d.ts +12 -0
  153. package/dist/utils/delegate-lock.js +88 -0
  154. package/dist/utils/frontmatter.d.ts +27 -0
  155. package/dist/utils/frontmatter.js +33 -0
  156. package/dist/utils/hook-trust.d.ts +1 -0
  157. package/dist/utils/hook-trust.js +18 -2
  158. package/dist/utils/host-registration.d.ts +13 -1
  159. package/dist/utils/host-registration.js +98 -5
  160. package/dist/utils/package-use-lease.d.ts +1 -1
  161. package/dist/utils/package-use-lease.js +15 -7
  162. package/docs/anywhere-runtime.md +17 -0
  163. package/package.json +9 -8
  164. package/scripts/check-function-manifest.mjs +17 -3
@@ -0,0 +1,1747 @@
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
+ * Kinds: `reindex`, `autocommit` (decision 48 for its failure file),
5
+ * `plan-sync`, `pr-footer` (decision 47), `session-close`, `mesh-session-bind`
6
+ * (decision 36), `fleet-local-settings` (US-050 c2, conductor ruling on #3042), and the mesh kinds
7
+ * `mesh-reconcile` and `mesh-register-retry` (hook-requests-mesh.ts).
8
+ * Also `fleet-session-start`, US-050 c2 (hook-requests-fleet-session-start.ts).
9
+ *
10
+ * A hook that used to re-index, commit, copy a plan or edit a pull request
11
+ * now only decides that the work is due and leaves one small file in
12
+ * `~/.hq/daemon/hook-requests/<root key>/<kind>-<key>.json`. This module is
13
+ * the other half: the running daemon takes the notes of its own HQ root,
14
+ * oldest first, and does the work. No process is added: the drainer runs in
15
+ * the daemon, beside the Stop job drainer, under the same lease.
16
+ *
17
+ * A note is data, never a command. Only the kinds listed here are accepted,
18
+ * each with its own typed fields, and the arguments of the program that is
19
+ * started are built here from the validated fields.
20
+ *
21
+ * Life of a note `X.json`:
22
+ * - Invalid (version, kind, fields, size, another HQ root): deleted, one log line, nothing runs.
23
+ * - Older than a day: deleted, one log line, never run (for an autosave the
24
+ * session's failure file is left, as for a note that is given up). The age is counted
25
+ * from the note's own time, and the hook writes a waiting note again on
26
+ * every new request for the same thing, so it is the age of the newest
27
+ * request, not of the first.
28
+ * - A folder, link or FIFO where a note or a claimed note should be is never
29
+ * run. It is deleted; one that cannot be deleted (a folder) is reported
30
+ * once per daemon run and left.
31
+ * - Claimed by renaming it to `X.run` before the work starts, so a request
32
+ * made during the work is a new `X.json` and runs afterwards.
33
+ * - A kind with text (plan-sync, fleet-local-settings) has it in `X.body`, written before the note.
34
+ * A claimed note whose body is missing or too long is deleted with one log
35
+ * line and nothing runs: the same request, made again while its first copy
36
+ * ran, loses its body when that copy finishes, and its text was just filed.
37
+ * When the first copy fails instead, its text was not filed: the body stays
38
+ * for the newer note. A body with no note and no claimed note, a day old,
39
+ * was left by a hook that died between its two writes and is deleted.
40
+ * - Done: `X.run` and its side files are deleted.
41
+ * - Not started because the work's own lock is held (`later`): put back as
42
+ * it was, no try counted, looked at again after 5 s. Only the day limit
43
+ * ends such a note.
44
+ * - Failed, or found as `X.run` at the start of a pass (the daemon stopped
45
+ * mid-work): the count in `X.attempts` goes up and the note is put back,
46
+ * unless a newer `X.json` is already there. It runs again after 5 s, then
47
+ * after 30 s. After the third failure it is deleted with one log line.
48
+ */
49
+ import { spawn } from "node:child_process";
50
+ import { createHash } from "node:crypto";
51
+ import * as fs from "node:fs";
52
+ import * as os from "node:os";
53
+ import * as path from "node:path";
54
+ import { openStoreDir } from "../safe-store.js";
55
+ import { executeAclSuggestion, parseShareCandidates } from "./hook-requests-acl-suggest.js";
56
+ import { parseMeshOperation, runMeshReconcile, runMeshRegisterRetry } from "./hook-requests-mesh.js";
57
+ import { MACHINE_CHECKS, machineCheckCollectOnlySupported, runMachineChecks } from "./machine-checks.js";
58
+ import { parseMeshToolWrites, runMeshToolWrites } from "./hook-requests-mesh-tool-writes.js";
59
+ import { parseFleetSessionStart, runFleetSessionStart } from "./hook-requests-fleet-session-start.js";
60
+ /** The longest note the Rust writer leaves (`NOTE_MAX_BYTES`). */
61
+ export const HOOK_REQUEST_MAX_BYTES = 4096;
62
+ /** The longest `.body` file the Rust writer leaves (`BODY_MAX_BYTES`). */
63
+ export const HOOK_REQUEST_BODY_MAX_BYTES = 256 * 1024;
64
+ /** A note older than this is deleted and never run. */
65
+ export const HOOK_REQUEST_MAX_AGE_MS = 24 * 60 * 60_000;
66
+ /** Tries per note, and the waits before the second and third. */
67
+ export const HOOK_REQUEST_MAX_ATTEMPTS = 3;
68
+ export const HOOK_REQUEST_RETRY_DELAYS_MS = [5_000, 30_000];
69
+ /** The longest a request's program runs before it is told to end (SIGTERM to its process group). */
70
+ export const HOOK_REQUEST_KILL_MS = 60_000;
71
+ /** How long after that the whole process group is killed. */
72
+ export const HOOK_REQUEST_KILL_GRACE_MS = 5_000;
73
+ /** The wait before a note whose work could not start is looked at again. */
74
+ export const HOOK_REQUEST_LATER_MS = 5_000;
75
+ /** The lock folder of `hq-autocommit.sh`, under the script's `${TMPDIR:-/tmp}`. */
76
+ export const AUTOCOMMIT_LOCK = "hq-autocommit.lock";
77
+ /** Failure files and shown marks older than this are removed when a new one is written. */
78
+ export const AUTOCOMMIT_WARNING_MAX_AGE_MS = 7 * 24 * 60 * 60_000;
79
+ /** The longest path an `autocommit` note carries (`PATH_MAX_BYTES` in post_m5/autocommit.rs). */
80
+ export const HOOK_REQUEST_PATH_MAX_BYTES = 3500;
81
+ /** The autosave script of an HQ root, which the daemon runs for an `autocommit` note. */
82
+ export const AUTOCOMMIT_SCRIPT = ".claude/hooks/hq-autocommit.sh";
83
+ /** The script of an HQ root that prints the fingerprint for a `pr-footer` note (its fingerprint-only mode). */
84
+ export const PR_FOOTER_SCRIPT = "core/scripts/hq-pr-create.sh";
85
+ /** The only shape of `args.url` in a `pr-footer` note (`pull_url` in post_m5/pr_footer.rs). */
86
+ export const PR_FOOTER_URL = /^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/[0-9]+$/;
87
+ /** The longest URL a `pr-footer` note carries. */
88
+ export const PR_FOOTER_URL_MAX_BYTES = 512;
89
+ /** The footer is added no sooner than this after the hook left the note (owner decision 47: "a few seconds after the PR opens"). */
90
+ export const PR_FOOTER_DELAY_MS = 3_000;
91
+ /** The longest each program of a `pr-footer` request runs (the script, `gh pr view`, `gh pr edit`). */
92
+ export const PR_FOOTER_PROGRAM_MS = 20_000;
93
+ /** How often the body is read again when it changed between the read and the write, before the try fails. */
94
+ export const PR_FOOTER_ROUNDS = 3;
95
+ /** The most of a program's output that is kept. A pull request body is at most 65,536 characters. */
96
+ const PR_FOOTER_OUTPUT_MAX_BYTES = 1_048_576;
97
+ /** The most commands one `fleet-local-settings` note carries (the note itself is at most 4096 bytes). */
98
+ export const FLEET_LOCAL_SETTINGS_MAX_COMMANDS = 64;
99
+ /** The hook-gate and master-hook of an HQ root, which `gate` and `master` commands start. */
100
+ export const FLEET_LOCAL_HOOK_GATE = ".claude/hooks/hook-gate.sh";
101
+ export const FLEET_LOCAL_MASTER_HOOK = ".claude/hooks/master-hook.sh";
102
+ /** The hook a `mesh-session-bind` note runs, inside the HQ root (`spawn_work_mesh_register` in hq-session.sh). */
103
+ export const MESH_SESSION_BIND_HOOK = "core/hooks/SessionStart/35-work-mesh-session-start.sh";
104
+ /** Where that hook's output goes, inside the HQ root, as when hq-session.sh started it. */
105
+ export const MESH_SESSION_BIND_LOG = "workspace/logs/work-mesh-hook.log";
106
+ /** The longest `cwd` a `mesh-session-bind` note carries (`MESH_SESSION_BIND_CWD_MAX_BYTES` in daemon_req.rs). */
107
+ export const MESH_SESSION_BIND_CWD_MAX_BYTES = 3500;
108
+ /** A company as `mesh_session_bind` in daemon_req.rs leaves it: a plain folder name. */
109
+ const MESH_SESSION_BIND_COMPANY = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
110
+ /**
111
+ * A session id as `mesh_session_bind` in daemon_req.rs leaves it: the session part of a
112
+ * `mesh-reconcile` observation name (`OBSERVATION` in hook-requests-mesh.ts), at most 512
113
+ * characters. The hook builds read and write paths from it and strips spaces, so "a b" would
114
+ * run as "ab"; anything else is refused.
115
+ */
116
+ const MESH_SESSION_BIND_SESSION = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,511}$/;
117
+ /** Session variables the hook reads before the event's `session_id` (its `SID`); the daemon's own are not the session's. */
118
+ const MESH_SESSION_BIND_UNSET = ["HQ_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID", "CODEX_THREAD_ID", "HQ_PARENT_SESSION_ID", "HQ_SPAWN_COMPANY", "PWD", "OLDPWD"];
119
+ /** The script a `startwork-prefetch` note runs, inside the HQ root (`PREFETCH_SCRIPT` in prompt_up6/intent_hint.rs). */
120
+ export const STARTWORK_PREFETCH_SCRIPT = "core/scripts/startwork-prefetch.sh";
121
+ /** The hook leaves a prefetch note only for a prompt shorter than this (`PREFETCH_PROMPT_LIMIT` in prompt_up6/intent_hint.rs). */
122
+ export const STARTWORK_PREFETCH_PROMPT_LIMIT = 65_536;
123
+ /** A session id the prefetch script accepts (`valid_sid` in prompt_up6/intent_hint.rs; the script's own `case`). */
124
+ const STARTWORK_PREFETCH_SESSION = /^[A-Za-z0-9._-]{1,512}$/;
125
+ /** Notes handled per pass; the drainer schedules another pass at once when reached. */
126
+ export const HOOK_REQUEST_PASS_LIMIT = 64;
127
+ /** A writer's temporary file older than this was left by a hook that died mid-write. */
128
+ const TEMPORARY_MAX_AGE_MS = 60 * 60_000;
129
+ const STEM = /^([a-z][a-z-]{0,31})-([0-9a-f]{32})$/;
130
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : undefined;
131
+ const plain = (s) => typeof s === "string" && !s.includes("\0");
132
+ /** The folder name for an HQ root: 32 hex characters of SHA-256 over its real path (`root_key` in daemon_req.rs). */
133
+ export function hookRequestRootKey(root) {
134
+ let real = root;
135
+ try {
136
+ real = fs.realpathSync(root);
137
+ }
138
+ catch { /* A root that cannot be resolved is used as given, as the writer does. */ }
139
+ return createHash("sha256").update(real).digest("hex").slice(0, 32);
140
+ }
141
+ /** The request folder of `root` under `home`. */
142
+ export function hookRequestDir(home, root) {
143
+ return path.join(home, ".hq/daemon/hook-requests", hookRequestRootKey(root));
144
+ }
145
+ /** Where the daemon leaves a session's "autosave failed" file for the native hq-autocommit hook
146
+ * (`WARNING_PARTS` in post_m5/autocommit.rs; owner decision 48). */
147
+ export function autocommitWarningDir(home, root) {
148
+ return path.join(home, ".hq/daemon/hook-warnings", hookRequestRootKey(root));
149
+ }
150
+ /** The name part for a session (`session_key` in post_m5/autocommit.rs). */
151
+ export function autocommitWarningKey(session) {
152
+ return createHash("sha256").update("autocommit\0").update(session).digest("hex").slice(0, 32);
153
+ }
154
+ /**
155
+ * Record that an autosave failed for `session`, so the native hook shows its
156
+ * warning on that session's next Write or Edit. One file per session; nothing
157
+ * is written once the hook has shown it (`.shown`). True when a file was made.
158
+ */
159
+ export function leaveAutocommitFailure(home, root, session, now = Date.now()) {
160
+ const opened = openStoreDir(autocommitWarningDir(home, root), { home, create: true });
161
+ if (!opened.ok)
162
+ return false;
163
+ const store = opened.value;
164
+ try {
165
+ const listed = store.list();
166
+ for (const name of listed.ok ? listed.value : []) {
167
+ if (!/^autocommit-[0-9a-f]{32}\.(failed|shown)$/.test(name))
168
+ continue;
169
+ const facts = store.stat(name);
170
+ if (facts.ok && now - facts.value.mtimeMs > AUTOCOMMIT_WARNING_MAX_AGE_MS)
171
+ store.remove(name);
172
+ }
173
+ const stem = `autocommit-${autocommitWarningKey(session)}`;
174
+ if (store.stat(`${stem}.shown`).ok)
175
+ return false;
176
+ const made = store.createExclusive(`${stem}.failed`, `${new Date(now).toISOString()}\n`);
177
+ return made.ok && made.value;
178
+ }
179
+ finally {
180
+ store.close();
181
+ }
182
+ }
183
+ /** Read one note. `stem` is its file name without `.json`. Undefined for anything the writer does not produce. */
184
+ export function parseHookRequest(text, stem) {
185
+ if (Buffer.byteLength(text) > HOOK_REQUEST_MAX_BYTES)
186
+ return undefined;
187
+ const named = STEM.exec(stem);
188
+ if (!named)
189
+ return undefined;
190
+ let value;
191
+ try {
192
+ value = record(JSON.parse(text));
193
+ }
194
+ catch {
195
+ return undefined;
196
+ }
197
+ if (!value || value.v !== 1 || value.kind !== named[1] || value.key !== named[2]
198
+ || !plain(value.id) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.id)
199
+ || !plain(value.hqRoot) || !path.isAbsolute(value.hqRoot)
200
+ || !plain(value.session) || value.session.length > 512
201
+ || typeof value.at !== "string")
202
+ return undefined;
203
+ const at = Date.parse(value.at);
204
+ const args = record(value.args);
205
+ if (!Number.isFinite(at) || !args)
206
+ return undefined;
207
+ let operation;
208
+ if (value.kind === "reindex") {
209
+ if (Object.keys(args).length !== 0)
210
+ return undefined;
211
+ operation = { kind: "reindex" };
212
+ }
213
+ else if (value.kind === "autocommit") {
214
+ const file = args.path;
215
+ if (Object.keys(args).length !== 1 || !plain(file) || !path.posix.isAbsolute(file)
216
+ || Buffer.byteLength(file) > HOOK_REQUEST_PATH_MAX_BYTES)
217
+ return undefined;
218
+ operation = { kind: "autocommit", path: file };
219
+ }
220
+ else if (value.kind === "startwork-prefetch") {
221
+ const sessionId = args.sessionId;
222
+ if (Object.keys(args).length !== 1 || !plain(sessionId) || !STARTWORK_PREFETCH_SESSION.test(sessionId)
223
+ || sessionId === "." || sessionId === ".." || sessionId !== value.session)
224
+ return undefined;
225
+ operation = { kind: "startwork-prefetch", sessionId };
226
+ }
227
+ else if (value.kind === "plan-sync") {
228
+ const project = args.project;
229
+ if (Object.keys(args).length !== 1 || !hookRequestProject(project))
230
+ return undefined;
231
+ operation = { kind: "plan-sync", project };
232
+ }
233
+ else if (value.kind === "acl-suggest") {
234
+ const candidates = parseShareCandidates(args.candidates);
235
+ if (Object.keys(args).length !== 1 || !candidates)
236
+ return undefined;
237
+ operation = { kind: "acl-suggest", candidates };
238
+ }
239
+ else if (value.kind === "pr-footer") {
240
+ const url = args.url;
241
+ if (Object.keys(args).length !== 1 || !plain(url) || Buffer.byteLength(url) > PR_FOOTER_URL_MAX_BYTES
242
+ || !PR_FOOTER_URL.test(url))
243
+ return undefined;
244
+ operation = { kind: "pr-footer", url };
245
+ }
246
+ else if (value.kind === "fleet-local-settings") {
247
+ const parsed = parseFleetLocalSettings(args);
248
+ if (!parsed)
249
+ return undefined;
250
+ operation = parsed;
251
+ }
252
+ else if (value.kind === "session-close") {
253
+ const keys = Object.keys(args).sort();
254
+ if (keys.length !== 2 || keys[0] !== "runtime" || keys[1] !== "sessionId")
255
+ return undefined;
256
+ if (args.runtime !== "claude" || !plain(args.sessionId) || args.sessionId.length === 0 || args.sessionId.length > 512)
257
+ return undefined;
258
+ operation = { kind: "session-close", runtime: "claude", sessionId: args.sessionId };
259
+ }
260
+ else if (value.kind === "mesh-tool-writes") {
261
+ const parsed = parseMeshToolWrites(args, value.session);
262
+ if (!parsed)
263
+ return undefined;
264
+ operation = parsed;
265
+ }
266
+ else if (value.kind === "mesh-session-bind") {
267
+ const keys = Object.keys(args).filter(key => key !== "disabled").sort();
268
+ if (keys.length !== 3 || keys[0] !== "company_slug" || keys[1] !== "cwd" || keys[2] !== "session_id")
269
+ return undefined;
270
+ const { session_id: sessionId, cwd, company_slug: company, disabled } = args;
271
+ if (disabled !== undefined && disabled !== "HQ_WORK_MESH_DISABLED" && disabled !== "HQ_DISABLED_HOOKS")
272
+ return undefined;
273
+ if (!plain(sessionId) || !MESH_SESSION_BIND_SESSION.test(sessionId) || sessionId !== value.session)
274
+ return undefined;
275
+ if (!plain(cwd) || Buffer.byteLength(cwd) > MESH_SESSION_BIND_CWD_MAX_BYTES || (cwd !== "" && !path.posix.isAbsolute(cwd)))
276
+ return undefined;
277
+ if (!plain(company) || !MESH_SESSION_BIND_COMPANY.test(company) || company === "personal")
278
+ return undefined;
279
+ operation = { kind: "mesh-session-bind", sessionId, cwd, company, ...(disabled !== undefined ? { disabled } : {}) };
280
+ }
281
+ else if (value.kind === "mesh-session-register") {
282
+ // `register_request` in crates/hq-hook/src/session_set/add.rs: exactly session_id and cwd (and the optional switch), checked as for mesh-session-bind.
283
+ const keys = Object.keys(args).filter(key => key !== "disabled").sort();
284
+ if (keys.length !== 2 || keys[0] !== "cwd" || keys[1] !== "session_id")
285
+ return undefined;
286
+ const { session_id: sessionId, cwd, disabled } = args;
287
+ if (disabled !== undefined && disabled !== "HQ_WORK_MESH_DISABLED" && disabled !== "HQ_DISABLED_HOOKS")
288
+ return undefined;
289
+ if (!plain(sessionId) || !MESH_SESSION_BIND_SESSION.test(sessionId) || sessionId !== value.session)
290
+ return undefined;
291
+ if (!plain(cwd) || Buffer.byteLength(cwd) > MESH_SESSION_BIND_CWD_MAX_BYTES || (cwd !== "" && !path.posix.isAbsolute(cwd)))
292
+ return undefined;
293
+ operation = { kind: "mesh-session-register", sessionId, cwd, ...(disabled !== undefined ? { disabled } : {}) };
294
+ }
295
+ else if (value.kind === "fleet-session-start") {
296
+ const fleet = parseFleetSessionStart(value.kind, args, value.session);
297
+ if (!fleet)
298
+ return undefined;
299
+ operation = fleet;
300
+ }
301
+ else if (isMachineCheckRequestKind(value.kind)) {
302
+ const check = parseMachineCheckOperation(value.kind, args);
303
+ if (!check)
304
+ return undefined;
305
+ operation = check;
306
+ }
307
+ else {
308
+ const mesh = parseMeshOperation(value.kind, args, value.session);
309
+ if (!mesh)
310
+ return undefined;
311
+ operation = mesh;
312
+ }
313
+ return { stem, id: value.id, at, root: value.hqRoot, session: value.session, operation };
314
+ }
315
+ /** The args of a `fleet-local-settings` note: exactly `event` (PostToolUse) and 1 to 64 typed commands. */
316
+ function parseFleetLocalSettings(args) {
317
+ const keys = Object.keys(args).sort();
318
+ if (keys.length !== 2 || keys[0] !== "commands" || keys[1] !== "event" || args.event !== "PostToolUse")
319
+ return undefined;
320
+ const list = args.commands;
321
+ if (!Array.isArray(list) || list.length === 0 || list.length > FLEET_LOCAL_SETTINGS_MAX_COMMANDS)
322
+ return undefined;
323
+ const commands = [];
324
+ const word = (s) => plain(s) && s.length > 0 && s.length <= 4096;
325
+ const script = (s) => word(s) && path.isAbsolute(s);
326
+ const exactly = (item, names) => {
327
+ const have = Object.keys(item).sort();
328
+ return have.length === names.length && have.every((name, i) => name === names[i]);
329
+ };
330
+ for (const entry of list) {
331
+ const item = record(entry);
332
+ if (!item)
333
+ return undefined;
334
+ if (item.type === "gate" && exactly(item, ["args", "id", "script", "type"])) {
335
+ // The adapter's hook ids: letters, digits, `.`, `_` and `-`.
336
+ if (!plain(item.id) || !/^[A-Za-z0-9._-]{1,128}$/.test(item.id) || !script(item.script))
337
+ return undefined;
338
+ if (!Array.isArray(item.args) || !item.args.every(arg => plain(arg) && arg.length <= 4096))
339
+ return undefined;
340
+ commands.push({ type: "gate", id: item.id, script: item.script, args: [...item.args] });
341
+ }
342
+ else if (item.type === "master" && exactly(item, ["event", "type"])) {
343
+ if (!plain(item.event) || !/^[A-Za-z]{1,64}$/.test(item.event))
344
+ return undefined;
345
+ commands.push({ type: "master", event: item.event });
346
+ }
347
+ else if (item.type === "script" && exactly(item, ["script", "type"])) {
348
+ if (!script(item.script))
349
+ return undefined;
350
+ commands.push({ type: "script", script: item.script });
351
+ }
352
+ else {
353
+ return undefined;
354
+ }
355
+ }
356
+ return { kind: "fleet-local-settings", event: "PostToolUse", commands };
357
+ }
358
+ /** A project as the plan-sync writer leaves it: a path under the HQ root, relative, with no `..` part. */
359
+ function hookRequestProject(project) {
360
+ return plain(project) && project.length > 0 && project.length <= 1024
361
+ && !path.isAbsolute(project) && !project.startsWith("/") && !project.split("/").includes("..");
362
+ }
363
+ /** Whether a note of this kind has its text in a `.body` file beside it. */
364
+ export function hookRequestHasBody(operation) {
365
+ return operation.kind === "plan-sync"
366
+ || operation.kind === "startwork-prefetch"
367
+ || operation.kind === "fleet-local-settings"
368
+ || operation.kind === "fleet-session-start";
369
+ }
370
+ /** The helper a plan-sync request runs, inside the HQ root. */
371
+ export const PLAN_SYNC_HELPER = "core/scripts/session-project.sh";
372
+ /**
373
+ * The CLI arguments for a validated request (plan-sync: the helper's arguments). Nothing from the note is passed through as an argument except its checked root.
374
+ * Undefined for a request the daemon does in process (`session-close`), which never starts a program.
375
+ */
376
+ export function hookRequestArguments(request) {
377
+ switch (request.operation.kind) {
378
+ case "reindex": return ["reindex", "--from-hook", "--repo-root", request.root];
379
+ // Not a CLI request: the root's own script is run (`autocommitInput`).
380
+ case "autocommit": return [];
381
+ // Run in process by hook-requests-mesh.ts, which builds its own `hq` calls.
382
+ case "mesh-reconcile":
383
+ case "mesh-register-retry": return [];
384
+ // Not a CLI request: the root's own SessionStart Work Mesh hook is run (`runMeshSessionBind`).
385
+ case "mesh-session-bind": return [];
386
+ // The same hook, with the company-less event (`runMeshSessionBind`).
387
+ case "mesh-session-register": return [];
388
+ // Not a CLI request: the root's own prefetch script is run (`runStartworkPrefetch`).
389
+ case "startwork-prefetch": return [];
390
+ case "plan-sync": return ["ingest-plan", "--project", request.operation.project, "--source", "native-plan-tool"];
391
+ // Not a CLI request either: the root's fingerprint script and `gh` are run (`addPrFooter`).
392
+ case "pr-footer": return [];
393
+ // Not a CLI request: the settings commands are started one by one (`runFleetLocalSettings`).
394
+ case "fleet-local-settings": return [];
395
+ // Run in process by runMachineCheckRequest below, through the machine-check runner.
396
+ case "check-hq-update":
397
+ case "check-client-health": return [];
398
+ case "acl-suggest":
399
+ case "session-close": return undefined;
400
+ // Run by hook-requests-fleet-session-start.ts with the pinned engine.
401
+ case "fleet-session-start": return [];
402
+ }
403
+ }
404
+ /**
405
+ * Do a `session-close` request in the running hqd's session registry, as its `session.close` op does (allowed while HQ
406
+ * Anywhere is off). With no hqd running there is no session to close, which is done too: a retry would find the same.
407
+ * The note's root must be this daemon's root, as for every request.
408
+ */
409
+ export function executeSessionClose(request, options) {
410
+ if (request.operation.kind !== "session-close")
411
+ return Promise.resolve({ code: 1 });
412
+ try {
413
+ if (!options.allowedRoot || fs.realpathSync(request.root) !== fs.realpathSync(options.allowedRoot))
414
+ return Promise.resolve({ code: 1 });
415
+ }
416
+ catch {
417
+ return Promise.resolve({ code: 1 });
418
+ }
419
+ options.sessions?.close(request.operation.runtime, request.operation.sessionId);
420
+ return Promise.resolve({ code: 0 });
421
+ }
422
+ const activeFolders = new Set();
423
+ /** Entries a pass could not delete or use, so each is reported once per daemon run. */
424
+ const reported = new Set();
425
+ const REPORTED_MAX = 1024;
426
+ /** When a note whose work could not start is looked at again, by folder and name. */
427
+ const waitUntil = new Map();
428
+ /**
429
+ * One pass over the request folder of this daemon's HQ root. Returns the
430
+ * number of notes settled or tried. Notes of another HQ root are in another
431
+ * folder and are not touched.
432
+ */
433
+ export async function drainHookRequests(options) {
434
+ if (!options.ownsQueue())
435
+ return 0;
436
+ const root = options.root();
437
+ if (!root)
438
+ return 0;
439
+ const dir = hookRequestDir(options.home, root);
440
+ if (activeFolders.has(dir))
441
+ return 0;
442
+ activeFolders.add(dir);
443
+ try {
444
+ const opened = openStoreDir(dir, { home: options.home });
445
+ if (!opened.ok) {
446
+ if (opened.code !== "folder-missing")
447
+ options.log(`Hook request folder unavailable: ${opened.code}`);
448
+ return 0;
449
+ }
450
+ try {
451
+ return await new Pass(opened.value, root, options).run();
452
+ }
453
+ finally {
454
+ opened.value.close();
455
+ }
456
+ }
457
+ finally {
458
+ activeFolders.delete(dir);
459
+ }
460
+ }
461
+ class Pass {
462
+ store;
463
+ root;
464
+ options;
465
+ done = 0;
466
+ constructor(store, root, options) {
467
+ this.store = store;
468
+ this.root = root;
469
+ this.options = options;
470
+ }
471
+ now() { return (this.options.now ?? Date.now)(); }
472
+ log(message) { this.options.log(message); }
473
+ /** Log about an entry that stays in the folder: once per daemon run, not on every pass. */
474
+ once(name, message) {
475
+ const key = `${this.store.path}/${name}`;
476
+ if (reported.has(key))
477
+ return;
478
+ // Bounded: past this many entries the memory starts over, and a line may be said a second time.
479
+ if (reported.size >= REPORTED_MAX)
480
+ reported.clear();
481
+ reported.add(key);
482
+ this.log(message);
483
+ }
484
+ async run() {
485
+ const listed = this.store.list();
486
+ if (!listed.ok) {
487
+ this.log(`Hook request folder could not be read: ${listed.code}`);
488
+ return 0;
489
+ }
490
+ const names = new Set(listed.value);
491
+ for (const name of listed.value) {
492
+ if (name.startsWith(".") && name.endsWith(".tmp"))
493
+ this.removeStaleTemporary(name);
494
+ else if (name.endsWith(".run"))
495
+ this.recover(name.slice(0, -".run".length), names);
496
+ }
497
+ for (const name of listed.value)
498
+ if (name.endsWith(".body"))
499
+ this.removeOrphanBody(name, names);
500
+ const waiting = [];
501
+ for (const name of [...names].sort()) {
502
+ if (!name.endsWith(".json"))
503
+ continue;
504
+ const request = this.load(name.slice(0, -".json".length));
505
+ if (request)
506
+ waiting.push(request);
507
+ }
508
+ waiting.sort((a, b) => a.at - b.at || (a.stem < b.stem ? -1 : a.stem > b.stem ? 1 : 0));
509
+ for (const request of waiting) {
510
+ if (this.done >= HOOK_REQUEST_PASS_LIMIT)
511
+ break;
512
+ if (!this.options.ownsQueue()) {
513
+ this.log("Hook request lease was lost; notes retained");
514
+ break;
515
+ }
516
+ await this.work(request);
517
+ }
518
+ return this.done;
519
+ }
520
+ removeStaleTemporary(name) {
521
+ const facts = this.store.stat(name);
522
+ if (facts.ok && this.now() - facts.value.mtimeMs > TEMPORARY_MAX_AGE_MS)
523
+ this.store.remove(name);
524
+ }
525
+ attempts(stem) {
526
+ const read = this.store.readWithFacts(`${stem}.attempts`, { maxBytes: 16 });
527
+ if (!read.ok)
528
+ return { count: 0, at: 0 };
529
+ const count = Number(read.value.data.toString().trim());
530
+ // An unreadable count cannot say how often the request ran: treat it as one try short of the limit.
531
+ return { count: Number.isSafeInteger(count) && count >= 0 ? count : HOOK_REQUEST_MAX_ATTEMPTS - 1, at: read.value.facts.mtimeMs };
532
+ }
533
+ /** Delete the claimed note and its side files. `keepBody`: a newer note waits under the same name and shares the body file. */
534
+ forget(stem, keepBody = false) {
535
+ for (const suffix of keepBody ? [".run", ".attempts"] : [".run", ".attempts", ".body"])
536
+ this.store.remove(`${stem}${suffix}`);
537
+ }
538
+ /** A `.body` file with no note and no claimed note: the hook writes the body first, so one that is a day old
539
+ * was left by a hook that died before it wrote the note. The hook writes the body again before every note,
540
+ * so a body this old belongs to no request that is still coming. */
541
+ removeOrphanBody(name, names) {
542
+ const stem = name.slice(0, -".body".length);
543
+ if (names.has(`${stem}.json`) || names.has(`${stem}.run`))
544
+ return;
545
+ const facts = this.store.stat(name);
546
+ if (!facts.ok || this.now() - facts.value.mtimeMs <= HOOK_REQUEST_MAX_AGE_MS)
547
+ return;
548
+ if (this.store.stat(`${stem}.json`).ok || this.store.stat(`${stem}.run`).ok)
549
+ return;
550
+ if (this.store.remove(name).ok) {
551
+ this.done += 1;
552
+ this.log(`Hook request text ${name} has had no note for a day; deleted`);
553
+ }
554
+ }
555
+ /** Count one failed try of the claimed note `stem.run` and put it back, or give up. True when the
556
+ * request is now lost: deleted with its work not done and no newer request in its place. */
557
+ failed(stem, why) {
558
+ const count = this.attempts(stem).count + 1;
559
+ // A newer request for the same thing may be waiting. It shares the body file by name, and this try did not
560
+ // file the text, so the body is kept for it wherever the claimed note is dropped below.
561
+ const newer = () => this.store.stat(`${stem}.json`).ok;
562
+ if (count >= HOOK_REQUEST_MAX_ATTEMPTS) {
563
+ this.forget(stem, newer());
564
+ this.log(`Hook request ${stem} gave up after ${count} tries (${why}); deleted`);
565
+ return true;
566
+ }
567
+ if (!this.store.writeAtomic(`${stem}.attempts`, String(count)).ok) {
568
+ // Without a count the note could run for ever: drop it instead.
569
+ this.forget(stem, newer());
570
+ this.log(`Hook request ${stem} failed (${why}) and its try count could not be saved; deleted`);
571
+ return true;
572
+ }
573
+ if (newer()) {
574
+ // It starts with a clean count.
575
+ this.forget(stem, true);
576
+ this.log(`Hook request ${stem} failed (${why}); a newer request replaces it`);
577
+ return false;
578
+ }
579
+ const back = this.store.rename(`${stem}.run`, `${stem}.json`);
580
+ if (!back.ok) {
581
+ this.forget(stem, newer());
582
+ this.log(`Hook request ${stem} failed (${why}) and could not be put back (${back.code}); deleted`);
583
+ return true;
584
+ }
585
+ this.log(`Hook request ${stem} failed (${why}); try ${count + 1} of ${HOOK_REQUEST_MAX_ATTEMPTS} follows`);
586
+ return false;
587
+ }
588
+ /** A request that is deleted with its work not done. For an autosave the session is told on its next edit. */
589
+ lost(request) {
590
+ if (request.operation.kind === "autocommit")
591
+ leaveAutocommitFailure(this.options.home, this.root, request.session);
592
+ }
593
+ /** The work of the claimed note `stem.run` could not start: put the note back as it was. No try is counted. */
594
+ later(request) {
595
+ const { stem } = request;
596
+ waitUntil.set(`${this.store.path}/${stem}`, this.now() + (this.options.laterDelayMs ?? HOOK_REQUEST_LATER_MS));
597
+ if (this.store.stat(`${stem}.json`).ok) {
598
+ // A newer request for the same thing is waiting: it stands for both, and starts with a clean count
599
+ // (the side file `.body` is the newer note's and stays).
600
+ this.store.remove(`${stem}.run`);
601
+ this.store.remove(`${stem}.attempts`);
602
+ }
603
+ else {
604
+ const back = this.store.rename(`${stem}.run`, `${stem}.json`);
605
+ if (!back.ok) {
606
+ this.forget(stem);
607
+ this.log(`Hook request ${stem} could not start and could not be put back (${back.code}); deleted`);
608
+ this.lost(request);
609
+ return;
610
+ }
611
+ }
612
+ this.once(`${stem}.later`, `Hook request ${stem} waits: its work could not start yet (another run holds its lock); it is tried again, and no try is counted`);
613
+ }
614
+ /** A claimed note found at the start of a pass: its work was interrupted. */
615
+ recover(stem, names) {
616
+ const claimed = this.store.stat(`${stem}.run`);
617
+ if (!claimed.ok && (claimed.code === "file-link" || claimed.code === "not-regular-file")) {
618
+ // Not a note this daemon claimed: a folder, a link, a FIFO or a device. The daemon claims by renaming a
619
+ // regular file, so this was never work in progress: no try is counted and nothing is put back. Any other
620
+ // refusal (a read error, a file whose mode or owner changed) is still a claimed note and is counted
621
+ // and retried below, as before.
622
+ names.delete(`${stem}.run`);
623
+ const removed = this.store.remove(`${stem}.run`);
624
+ if (removed.ok) {
625
+ this.done += 1;
626
+ this.log(`Hook request ${stem}.run is not a claimed note (${claimed.code}); deleted, nothing was run`);
627
+ }
628
+ else {
629
+ 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`);
630
+ }
631
+ return;
632
+ }
633
+ this.done += 1;
634
+ // Read before the count: a note that is given up here is deleted, and its session is still told.
635
+ const read = this.store.read(`${stem}.run`, { maxBytes: HOOK_REQUEST_MAX_BYTES });
636
+ const interrupted = read.ok ? parseHookRequest(read.value.toString(), stem) : undefined;
637
+ if (this.failed(stem, "interrupted") && interrupted)
638
+ this.lost(interrupted);
639
+ names.delete(`${stem}.run`);
640
+ if (this.store.stat(`${stem}.json`).ok)
641
+ names.add(`${stem}.json`);
642
+ else
643
+ names.delete(`${stem}.json`);
644
+ }
645
+ /** Read and check a waiting note. An invalid or expired note is deleted here. */
646
+ load(stem) {
647
+ const drop = (why) => {
648
+ const removed = this.store.remove(`${stem}.json`);
649
+ this.forget(stem);
650
+ if (!removed.ok) {
651
+ // An entry that cannot be removed (a link, another user's file) stays; say so once, not on every pass.
652
+ this.once(`${stem}.json`, `Hook request ${stem} ${why}, but it could not be deleted (${removed.code})`);
653
+ return undefined;
654
+ }
655
+ this.done += 1;
656
+ this.log(`Hook request ${stem} ${why}`);
657
+ return undefined;
658
+ };
659
+ const read = this.store.read(`${stem}.json`, { maxBytes: HOOK_REQUEST_MAX_BYTES });
660
+ if (!read.ok) {
661
+ if (read.code === "missing")
662
+ return undefined;
663
+ return drop(`refused (${read.code}); deleted, nothing was run`);
664
+ }
665
+ const request = parseHookRequest(read.value.toString(), stem);
666
+ if (!request)
667
+ return drop("rejected; deleted, nothing was run");
668
+ let same;
669
+ try {
670
+ same = fs.realpathSync(request.root) === fs.realpathSync(this.root);
671
+ }
672
+ catch {
673
+ same = false;
674
+ }
675
+ if (!same)
676
+ return drop("names another HQ root; deleted, nothing was run");
677
+ if (this.now() - request.at > HOOK_REQUEST_MAX_AGE_MS)
678
+ return this.expire(request);
679
+ return request;
680
+ }
681
+ /** Delete a note that was read as older than a day. The hook may write the note again at any moment, and a
682
+ * delete by name would take the new one. So the note is renamed aside first, as for work, and read again:
683
+ * what is deleted is the file that was renamed, and a note written after the rename is a new file. */
684
+ expire(request) {
685
+ const { stem } = request;
686
+ const claimed = this.store.rename(`${stem}.json`, `${stem}.run`);
687
+ if (!claimed.ok) {
688
+ if (claimed.code !== "missing")
689
+ this.once(`${stem}.run`, `Hook request ${stem} is older than a day, but it could not be claimed for deletion: ${claimed.code}`);
690
+ return undefined;
691
+ }
692
+ const read = this.store.read(`${stem}.run`, { maxBytes: HOOK_REQUEST_MAX_BYTES });
693
+ const again = read.ok ? parseHookRequest(read.value.toString(), stem) : undefined;
694
+ if (again && this.now() - again.at <= HOOK_REQUEST_MAX_AGE_MS) {
695
+ // Written again between the read and the rename: it is a fresh request. Put it back for the next pass,
696
+ // unless a still newer note is already waiting.
697
+ if (this.store.stat(`${stem}.json`).ok || !this.store.rename(`${stem}.run`, `${stem}.json`).ok)
698
+ this.store.remove(`${stem}.run`);
699
+ return undefined;
700
+ }
701
+ this.store.remove(`${stem}.run`);
702
+ // The side files belong to a newer note when one arrived after the rename.
703
+ const replaced = this.store.stat(`${stem}.json`).ok;
704
+ if (!replaced)
705
+ for (const suffix of [".attempts", ".body"])
706
+ this.store.remove(`${stem}${suffix}`);
707
+ this.done += 1;
708
+ this.log(`Hook request ${stem} is older than a day; deleted, never run`);
709
+ // Its work was never done. A newer note, when one arrived, does it instead.
710
+ if (!replaced)
711
+ this.lost(again ?? request);
712
+ return undefined;
713
+ }
714
+ async work(request) {
715
+ const { stem } = request;
716
+ const waitKey = `${this.store.path}/${stem}`;
717
+ const until = waitUntil.get(waitKey);
718
+ if (until !== undefined) {
719
+ if (this.now() < until)
720
+ return;
721
+ waitUntil.delete(waitKey);
722
+ }
723
+ const tried = this.attempts(stem);
724
+ if (tried.count >= HOOK_REQUEST_MAX_ATTEMPTS) {
725
+ this.done += 1;
726
+ this.store.remove(`${stem}.json`);
727
+ this.forget(stem);
728
+ this.log(`Hook request ${stem} gave up after ${tried.count} tries; deleted`);
729
+ this.lost(request);
730
+ return;
731
+ }
732
+ if (tried.count > 0) {
733
+ const delays = this.options.retryDelaysMs ?? HOOK_REQUEST_RETRY_DELAYS_MS;
734
+ const wait = delays[Math.min(tried.count, delays.length) - 1] ?? 0;
735
+ if (wait > 0 && this.now() - tried.at < wait)
736
+ return;
737
+ }
738
+ const claimed = this.store.rename(`${stem}.json`, `${stem}.run`);
739
+ if (!claimed.ok) {
740
+ // The note stays and is tried on every pass; the reason is said once (the same key as an entry in the
741
+ // claimed note's place, which is the usual cause and has then been reported already).
742
+ if (claimed.code !== "missing")
743
+ this.once(`${stem}.run`, `Hook request ${stem} could not be claimed: ${claimed.code}`);
744
+ return;
745
+ }
746
+ this.done += 1;
747
+ if (hookRequestHasBody(request.operation)) {
748
+ const body = this.store.read(`${stem}.body`, { maxBytes: HOOK_REQUEST_BODY_MAX_BYTES });
749
+ if (!body.ok) {
750
+ this.forget(stem);
751
+ this.log(`Hook request ${stem} has no usable text (${body.code}); deleted, nothing was run`);
752
+ return;
753
+ }
754
+ request.body = body.value;
755
+ }
756
+ let result;
757
+ try {
758
+ result = await this.options.execute(request);
759
+ }
760
+ catch {
761
+ result = { code: 1 };
762
+ }
763
+ if (result.later) {
764
+ this.later(request);
765
+ return;
766
+ }
767
+ if (result.code === 0) {
768
+ this.forget(stem);
769
+ return;
770
+ }
771
+ if (this.failed(stem, `exit ${result.code}`))
772
+ this.lost(request);
773
+ }
774
+ }
775
+ /** Startup scan plus folder notifications, with a 5 s fallback scan when a
776
+ * watcher is unavailable or an event was missed. Close waits for the request
777
+ * in progress. */
778
+ export function startHookRequestDrainer(options) {
779
+ let watcher;
780
+ let watched;
781
+ let timer;
782
+ let running;
783
+ let closed = false;
784
+ let again = false;
785
+ let failing = false;
786
+ const schedule = (delay = 50) => {
787
+ if (closed)
788
+ return;
789
+ if (timer)
790
+ clearTimeout(timer);
791
+ timer = setTimeout(run, delay);
792
+ timer.unref();
793
+ };
794
+ const watch = () => {
795
+ const root = options.root();
796
+ const dir = root ? hookRequestDir(options.home, root) : undefined;
797
+ if (dir === watched && watcher)
798
+ return;
799
+ watcher?.close();
800
+ watcher = undefined;
801
+ watched = dir;
802
+ if (!dir)
803
+ return;
804
+ try {
805
+ watcher = fs.watch(dir, (_kind, filename) => {
806
+ if (filename === null || filename.toString().endsWith(".json"))
807
+ schedule();
808
+ });
809
+ watcher.on("error", () => { watcher?.close(); watcher = undefined; schedule(1000); });
810
+ watcher.unref();
811
+ }
812
+ catch { /* Before the first note the folder does not exist: the fallback scan retries. */ }
813
+ };
814
+ const run = () => {
815
+ timer = undefined;
816
+ if (closed)
817
+ return;
818
+ if (running) {
819
+ again = true;
820
+ return;
821
+ }
822
+ // `options.root()` reads the daemon config and throws on a malformed one. watch() calls it, so it runs
823
+ // inside the chain: a throw in this timer callback would end the drainer without its next scan.
824
+ running = Promise.resolve().then(() => { watch(); return drainHookRequests(options); })
825
+ .then(count => { failing = false; if (count >= HOOK_REQUEST_PASS_LIMIT)
826
+ again = true; })
827
+ .catch(() => {
828
+ // Said when scans start failing, not on every 5 s scan while they do.
829
+ if (!failing)
830
+ options.log("Hook request scan failed; notes retained");
831
+ failing = true;
832
+ })
833
+ .finally(() => {
834
+ running = undefined;
835
+ schedule(again ? 0 : options.scanIntervalMs ?? 5000);
836
+ again = false;
837
+ });
838
+ };
839
+ schedule(0);
840
+ return { async close() { closed = true; if (timer)
841
+ clearTimeout(timer); watcher?.close(); await running; } };
842
+ }
843
+ /** What `hq-autocommit.sh` reads on stdin for a validated `autocommit` request: the payload fields the script uses, built here. */
844
+ export function autocommitInput(request) {
845
+ if (request.operation.kind !== "autocommit")
846
+ throw new Error("not an autocommit request");
847
+ return JSON.stringify({
848
+ tool_name: "Write",
849
+ ...(request.session ? { session_id: request.session } : {}),
850
+ tool_input: { file_path: request.operation.path },
851
+ });
852
+ }
853
+ /** The script's lock folder in the environment it is run with. */
854
+ function autocommitLock(env) {
855
+ return path.join(env.TMPDIR || "/tmp", AUTOCOMMIT_LOCK);
856
+ }
857
+ /** Whether the script's lock is held and younger than the age at which the script itself takes over a dead
858
+ * owner's lock (`HQ_AUTOCOMMIT_STALE_LOCK_MINUTES`, 5). Starting the script then could only end in its silent exit 0. */
859
+ function autocommitLockIsFresh(lock, env) {
860
+ let age;
861
+ try {
862
+ age = Date.now() - fs.lstatSync(lock).mtimeMs;
863
+ }
864
+ catch {
865
+ return false;
866
+ }
867
+ const minutes = env.HQ_AUTOCOMMIT_STALE_LOCK_MINUTES ?? "5";
868
+ return /^[0-9]{1,6}$/.test(minutes) && age < Number(minutes) * 60_000;
869
+ }
870
+ /** Remove the script's lock when its owner file names `pid`, a script this daemon killed before its exit trap could run. */
871
+ function releaseAutocommitLock(lock, pid) {
872
+ try {
873
+ const owner = fs.readFileSync(path.join(lock, "owner"), "utf8");
874
+ if (!owner.split("\n").includes(`pid=${pid}`))
875
+ return;
876
+ fs.rmSync(path.join(lock, "owner"), { force: true });
877
+ fs.rmdirSync(lock);
878
+ }
879
+ catch { /* No owner file, another owner, or already gone: not this run's lock. */ }
880
+ }
881
+ /** The most of the script's stderr that is kept to look for its warning line. */
882
+ const AUTOCOMMIT_STDERR_MAX_BYTES = 65_536;
883
+ /**
884
+ * The one stop model of every request kind. `program` is started without a
885
+ * shell in its own process group (not on Windows, where the program alone is
886
+ * signalled). At `timeoutMs`, or when `signal` aborts, the group is sent
887
+ * SIGTERM, so a script can run its exit trap and the programs it started end
888
+ * with it, and SIGKILL after `killGraceMs` (default 5 s).
889
+ */
890
+ export function spawnRequestProgram(program, args, spawnOptions, stop) {
891
+ const grouped = process.platform !== "win32";
892
+ const child = spawn(program, args, { ...spawnOptions, shell: false, detached: grouped });
893
+ const signalAll = (signal) => {
894
+ try {
895
+ if (grouped && child.pid !== undefined)
896
+ process.kill(-child.pid, signal);
897
+ else
898
+ child.kill(signal);
899
+ }
900
+ catch { /* The group is already gone. */ }
901
+ };
902
+ let ended = false;
903
+ let killTimer;
904
+ const end = () => {
905
+ if (ended)
906
+ return;
907
+ ended = true;
908
+ signalAll("SIGTERM");
909
+ killTimer = setTimeout(() => signalAll("SIGKILL"), stop.killGraceMs ?? HOOK_REQUEST_KILL_GRACE_MS);
910
+ };
911
+ stop.signal?.addEventListener("abort", end, { once: true });
912
+ const timer = setTimeout(end, stop.timeoutMs);
913
+ const settle = () => {
914
+ clearTimeout(timer);
915
+ if (killTimer)
916
+ clearTimeout(killTimer);
917
+ stop.signal?.removeEventListener("abort", end);
918
+ if (ended)
919
+ signalAll("SIGKILL");
920
+ return ended;
921
+ };
922
+ return { child, signalAll, settle };
923
+ }
924
+ /**
925
+ * Run one program to its end with `spawnRequestProgram`'s stop model (its own
926
+ * process group, SIGTERM to the group at `timeoutMs` or when `signal` stops
927
+ * the daemon, SIGKILL after the grace time; then nothing the program started
928
+ * outlives it), for the kinds that run their programs one after another: the
929
+ * CLI kinds, `autocommit`, `plan-sync`, and `pr-footer`'s script, `gh pr view`
930
+ * and `gh pr edit`. `input` goes to stdin; `stdout` and `stderr` are how many
931
+ * characters of each are kept (none is read when not given). A program that
932
+ * exits by itself is not followed: a child it left in the background keeps
933
+ * running, as it did when the hook ran the script. No shell evaluation.
934
+ */
935
+ function runRequestProgram(program, args, options) {
936
+ return new Promise(resolve => {
937
+ if (options.signal?.aborted) {
938
+ resolve({ code: 1, ended: true, exited: false, pid: undefined, stdout: "", stderr: "" });
939
+ return;
940
+ }
941
+ const { child, settle } = spawnRequestProgram(program, args, {
942
+ cwd: options.cwd, env: options.env, windowsHide: true,
943
+ stdio: [options.input === undefined ? "ignore" : "pipe", options.stdout === undefined ? "ignore" : "pipe", options.stderr === undefined ? "ignore" : "pipe"],
944
+ }, { timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, signal: options.signal });
945
+ if (options.input !== undefined && child.stdin) {
946
+ // A script that exits before it reads leaves a closed pipe; its exit status is the result.
947
+ child.stdin.on("error", () => undefined);
948
+ child.stdin.end(options.input);
949
+ }
950
+ let out = "";
951
+ let said = "";
952
+ child.stdout?.setEncoding("utf8");
953
+ child.stdout?.on("data", (text) => { if (out.length < (options.stdout ?? 0))
954
+ out += text; });
955
+ child.stdout?.on("error", () => undefined);
956
+ child.stderr?.setEncoding("utf8");
957
+ child.stderr?.on("data", (text) => { if (said.length < (options.stderr ?? 0))
958
+ said += text; });
959
+ child.stderr?.on("error", () => undefined);
960
+ let settled = false;
961
+ const finish = (code, exited = false) => {
962
+ if (settled)
963
+ return;
964
+ settled = true;
965
+ // An ended run takes its whole group with it (`settle`).
966
+ const ended = settle();
967
+ resolve({ code: ended && code === 0 ? 1 : code, ended, exited, pid: child.pid, stdout: out, stderr: said });
968
+ };
969
+ child.once("error", () => finish(1));
970
+ child.once("close", code => finish(code ?? 1, code !== null));
971
+ });
972
+ }
973
+ /** `$(...)`: a program's output without its trailing newlines. */
974
+ const captured = (text) => text.replace(/\n+$/, "");
975
+ /** Wait `ms`, or less when the daemon stops. False when it stopped. */
976
+ function pause(ms, signal) {
977
+ return new Promise(resolve => {
978
+ if (signal?.aborted) {
979
+ resolve(false);
980
+ return;
981
+ }
982
+ if (ms <= 0) {
983
+ resolve(true);
984
+ return;
985
+ }
986
+ const stop = () => { clearTimeout(timer); resolve(false); };
987
+ const timer = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve(true); }, ms);
988
+ signal?.addEventListener("abort", stop, { once: true });
989
+ });
990
+ }
991
+ /**
992
+ * The body `pr-fingerprint-footer.sh` wrote for a pull request whose body is
993
+ * `body` (trailing newlines already removed), or undefined when a line of
994
+ * it already starts with `HQ-Fingerprint:`.
995
+ */
996
+ export function prFooterBody(body, fingerprint) {
997
+ // `grep -q '^HQ-Fingerprint:'`: lines end at a newline only.
998
+ if (body.split("\n").some(line => line.startsWith("HQ-Fingerprint:")))
999
+ return undefined;
1000
+ return body === "" ? `\n---\nHQ-Fingerprint: ${fingerprint}\n` : `${body}\n\n---\nHQ-Fingerprint: ${fingerprint}\n`;
1001
+ }
1002
+ /**
1003
+ * Add the `HQ-Fingerprint:` footer to the pull request a `pr-footer` note
1004
+ * names (owner decision 47). The steps are those of
1005
+ * `.claude/hooks/pr-fingerprint-footer.sh` after its trigger, which the
1006
+ * native hook keeps (post_m5/pr_footer.rs):
1007
+ *
1008
+ * 1. Not before `delayMs` after the hook left the note.
1009
+ * 2. The fingerprint: the root's `core/scripts/hq-pr-create.sh` in its
1010
+ * fingerprint-only mode, with the note's session id. No script, or no
1011
+ * fingerprint (the setting is off, or none is known): done, `gh` is not started.
1012
+ * 3. `gh pr view <url> --json body -q .body`. A body with a line that
1013
+ * starts with `HQ-Fingerprint:`: done, nothing is written.
1014
+ * 4. The body is read again just before the write. When it changed, the
1015
+ * new body is taken and step 3's check is made again, `rounds` times at
1016
+ * most; a body that changed every time is a failed try.
1017
+ * 5. `gh pr edit <url> --body-file <temporary file>`.
1018
+ *
1019
+ * Each program has its own limit; one that reaches it is ended with its
1020
+ * process group. A `gh`
1021
+ * that fails or is ended is a failed try, and the note is tried again
1022
+ * (three tries in all), where the shell hook gave up at once.
1023
+ */
1024
+ async function addPrFooter(request, url, base, options) {
1025
+ const script = path.join(request.root, PR_FOOTER_SCRIPT);
1026
+ // A root without the script: the shell hook stopped there too.
1027
+ try {
1028
+ if (!fs.statSync(script).isFile())
1029
+ return { code: 0 };
1030
+ }
1031
+ catch {
1032
+ return { code: 0 };
1033
+ }
1034
+ if (!await pause(request.at + options.delayMs - Date.now(), options.signal))
1035
+ return { code: 1 };
1036
+ const limits = { cwd: request.root, timeoutMs: options.programMs, killGraceMs: options.killGraceMs, ...(options.signal ? { signal: options.signal } : {}) };
1037
+ const env = { ...base, HQ_HOOK_REQUEST_ID: request.id };
1038
+ const printed = await runRequestProgram("bash", [script], {
1039
+ ...limits, stdout: PR_FOOTER_OUTPUT_MAX_BYTES,
1040
+ env: { ...env, HQ_ROOT: request.root, HQ_SESSION_ID: request.session, HQ_PR_CREATE_FINGERPRINT_ONLY: "1" },
1041
+ });
1042
+ if (printed.ended)
1043
+ return { code: printed.code };
1044
+ // As the shell hook: what the script printed decides, whatever its exit status.
1045
+ const fingerprint = captured(printed.stdout);
1046
+ if (fingerprint === "")
1047
+ return { code: 0 };
1048
+ const view = async () => {
1049
+ const read = await runRequestProgram("gh", ["pr", "view", url, "--json", "body", "-q", ".body"], { ...limits, env, stdout: PR_FOOTER_OUTPUT_MAX_BYTES });
1050
+ return read.code === 0 && read.stdout.length < PR_FOOTER_OUTPUT_MAX_BYTES ? captured(read.stdout) : undefined;
1051
+ };
1052
+ let body = await view();
1053
+ for (let round = 0; round < options.rounds; round += 1) {
1054
+ if (body === undefined)
1055
+ return { code: 1 };
1056
+ const next = prFooterBody(body, fingerprint);
1057
+ if (next === undefined)
1058
+ return { code: 0 };
1059
+ let folder;
1060
+ try {
1061
+ folder = fs.mkdtempSync(path.join(os.tmpdir(), "hq-pr-fp-edit."));
1062
+ }
1063
+ catch {
1064
+ return { code: 1 };
1065
+ }
1066
+ try {
1067
+ const file = path.join(folder, "body");
1068
+ fs.writeFileSync(file, next, { mode: 0o600, flag: "wx" });
1069
+ // The body again, just before the write: an edit made since the first read is not overwritten.
1070
+ const now = await view();
1071
+ if (now === undefined)
1072
+ return { code: 1 };
1073
+ if (now !== body) {
1074
+ body = now;
1075
+ continue;
1076
+ }
1077
+ const edit = await runRequestProgram("gh", ["pr", "edit", url, "--body-file", file], { ...limits, env });
1078
+ return { code: edit.code };
1079
+ }
1080
+ catch {
1081
+ return { code: 1 };
1082
+ }
1083
+ finally {
1084
+ fs.rmSync(folder, { recursive: true, force: true });
1085
+ }
1086
+ }
1087
+ // The body changed on every read.
1088
+ return { code: 1 };
1089
+ }
1090
+ /**
1091
+ * The words `eval "toks=( $rest )"` gives with `CLAUDE_PROJECT_DIR` set to `root`, for the shapes hq-hook models
1092
+ * (`shell_words` in `host::fleet_settings`): blanks, single and double quotes, backslash escapes, and
1093
+ * `$CLAUDE_PROJECT_DIR` or `${CLAUDE_PROJECT_DIR}`. Undefined for anything else the shell would expand or treat as syntax.
1094
+ */
1095
+ export function fleetLocalSettingsWords(text, root) {
1096
+ const NAME = "CLAUDE_PROJECT_DIR";
1097
+ const chars = [...text];
1098
+ const words = [];
1099
+ let word = "";
1100
+ let inWord = false;
1101
+ let i = 0;
1102
+ // Expand `$...` at `i` (just after `$`); false for an expansion hq-hook does not model.
1103
+ const expand = (quoted) => {
1104
+ const rest = chars.slice(i).join("");
1105
+ if (rest.startsWith(`{${NAME}}`))
1106
+ i += NAME.length + 2;
1107
+ else if (rest.startsWith(NAME) && !/^[A-Za-z0-9_]/.test(rest.slice(NAME.length)))
1108
+ i += NAME.length;
1109
+ else
1110
+ return false;
1111
+ if (!quoted && /[ \t\n*?[]/.test(root))
1112
+ return false;
1113
+ word += root;
1114
+ return true;
1115
+ };
1116
+ while (i < chars.length) {
1117
+ const c = chars[i];
1118
+ if (c === " " || c === "\t") {
1119
+ if (inWord) {
1120
+ words.push(word);
1121
+ word = "";
1122
+ inWord = false;
1123
+ }
1124
+ i += 1;
1125
+ }
1126
+ else if (c === "'") {
1127
+ inWord = true;
1128
+ i += 1;
1129
+ for (;;) {
1130
+ const next = chars[i];
1131
+ if (next === undefined)
1132
+ return undefined;
1133
+ i += 1;
1134
+ if (next === "'")
1135
+ break;
1136
+ word += next;
1137
+ }
1138
+ }
1139
+ else if (c === "\"") {
1140
+ inWord = true;
1141
+ i += 1;
1142
+ for (;;) {
1143
+ const next = chars[i];
1144
+ if (next === undefined)
1145
+ return undefined;
1146
+ if (next === "\"") {
1147
+ i += 1;
1148
+ break;
1149
+ }
1150
+ if (next === "\\") {
1151
+ const after = chars[i + 1];
1152
+ if (after === "$" || after === "`" || after === "\"" || after === "\\") {
1153
+ word += after;
1154
+ i += 2;
1155
+ }
1156
+ else if (after === "\n")
1157
+ i += 2;
1158
+ else {
1159
+ word += "\\";
1160
+ i += 1;
1161
+ }
1162
+ }
1163
+ else if (next === "$") {
1164
+ i += 1;
1165
+ if (!expand(true))
1166
+ return undefined;
1167
+ }
1168
+ else if (next === "`") {
1169
+ return undefined;
1170
+ }
1171
+ else {
1172
+ word += next;
1173
+ i += 1;
1174
+ }
1175
+ }
1176
+ }
1177
+ else if (c === "\\") {
1178
+ inWord = true;
1179
+ const after = chars[i + 1];
1180
+ if (after === undefined)
1181
+ return undefined;
1182
+ if (after !== "\n")
1183
+ word += after;
1184
+ i += 2;
1185
+ }
1186
+ else if (c === "$") {
1187
+ inWord = true;
1188
+ i += 1;
1189
+ if (!expand(false))
1190
+ return undefined;
1191
+ }
1192
+ else if ("`*?[{;&|<>()\n".includes(c) || (c === "~" && !inWord)) {
1193
+ return undefined;
1194
+ }
1195
+ else {
1196
+ inWord = true;
1197
+ word += c;
1198
+ i += 1;
1199
+ }
1200
+ }
1201
+ if (inWord)
1202
+ words.push(word);
1203
+ return words;
1204
+ }
1205
+ /** A regular file (symlinks followed), as Rust's `Path::is_file`. */
1206
+ function isFile(file) {
1207
+ try {
1208
+ return fs.statSync(file).isFile();
1209
+ }
1210
+ catch {
1211
+ return false;
1212
+ }
1213
+ }
1214
+ /**
1215
+ * `hqad_classify_command` for one settings command, as hq-hook's `fleet_settings::classify` reads it: the record the
1216
+ * hook would put in a note, or undefined for a command that gives none or that hq-hook does not model.
1217
+ */
1218
+ export function fleetLocalSettingsRecord(command, root) {
1219
+ const stripped = command.startsWith("env BASH_ENV=/dev/null bash ") ? command.slice("env BASH_ENV=/dev/null ".length) : command;
1220
+ if (!stripped.startsWith("bash "))
1221
+ return undefined;
1222
+ const words = fleetLocalSettingsWords(stripped.slice("bash ".length), root);
1223
+ const script = words?.[0];
1224
+ if (!words || script === undefined)
1225
+ return undefined;
1226
+ if (script.endsWith("/hook-gate.sh")) {
1227
+ if (words.length < 3 || !isFile(words[2]))
1228
+ return undefined;
1229
+ const args = [];
1230
+ for (const extra of words.slice(3)) {
1231
+ if (/[*?[]/.test(extra))
1232
+ return undefined;
1233
+ args.push(...extra.split(/[ \t\n]/).filter(Boolean));
1234
+ }
1235
+ return { type: "gate", id: words[1], script: words[2], args };
1236
+ }
1237
+ if (script.endsWith("/master-hook.sh"))
1238
+ return { type: "master", event: words[1] ?? "" };
1239
+ return isFile(script) ? { type: "script", script } : undefined;
1240
+ }
1241
+ /**
1242
+ * The records the root's `.claude/settings.json` lists for `event` right now (any matcher), for the drain-time check
1243
+ * that a note's command is still listed there. Exec-form entries give none (the hook puts none in a note). An absent
1244
+ * or unreadable file lists nothing.
1245
+ */
1246
+ export function fleetLocalSettingsListed(root, event) {
1247
+ let settings;
1248
+ try {
1249
+ settings = JSON.parse(fs.readFileSync(path.join(root, ".claude/settings.json"), "utf8"));
1250
+ }
1251
+ catch {
1252
+ return [];
1253
+ }
1254
+ const values = (value) => Array.isArray(value) ? value : (record(value) ? Object.values(value) : []);
1255
+ const out = [];
1256
+ for (const group of values(record(record(settings)?.hooks)?.[event])) {
1257
+ for (const hook of values(record(group)?.hooks)) {
1258
+ const item = record(hook);
1259
+ if (!item || item.type !== "command" || typeof item.command !== "string")
1260
+ continue;
1261
+ if (Array.isArray(item.args) && item.args.length > 0)
1262
+ continue;
1263
+ const listed = fleetLocalSettingsRecord(item.command, root);
1264
+ if (listed)
1265
+ out.push(listed);
1266
+ }
1267
+ }
1268
+ return out;
1269
+ }
1270
+ /** Whether `file`'s real path (every symlink in its whole parent chain resolved) is inside the real HQ root. */
1271
+ export function fleetLocalSettingsUnderRoot(root, file) {
1272
+ let real;
1273
+ let realRoot;
1274
+ try {
1275
+ real = fs.realpathSync(file);
1276
+ realRoot = fs.realpathSync(root);
1277
+ }
1278
+ catch {
1279
+ return false;
1280
+ }
1281
+ const relative = path.relative(realRoot, real);
1282
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1283
+ }
1284
+ /**
1285
+ * Why the daemon refuses one note command at drain, or undefined to run it. A note is only what a hook said a moment
1286
+ * ago, so the daemon re-checks it against the root: the command must still be listed in the root's
1287
+ * `.claude/settings.json` for the note's event, and every file it would start (the gate and its script, master-hook,
1288
+ * the script) must resolve, with its whole parent chain, to a real path under the HQ root.
1289
+ */
1290
+ export function fleetLocalSettingsRefusal(root, command, listed) {
1291
+ const same = (a, b) => {
1292
+ if (a.type === "gate" && b.type === "gate") {
1293
+ return a.id === b.id && a.script === b.script && a.args.length === b.args.length && a.args.every((arg, i) => arg === b.args[i]);
1294
+ }
1295
+ if (a.type === "master" && b.type === "master")
1296
+ return a.event === b.event;
1297
+ if (a.type === "script" && b.type === "script")
1298
+ return a.script === b.script;
1299
+ return false;
1300
+ };
1301
+ if (!listed.some(entry => same(entry, command)))
1302
+ return "it is no longer listed in .claude/settings.json for the event";
1303
+ const files = command.type === "gate" ? [path.join(root, FLEET_LOCAL_HOOK_GATE), command.script]
1304
+ : command.type === "master" ? [path.join(root, FLEET_LOCAL_MASTER_HOOK)] : [command.script];
1305
+ const outside = files.find(file => !fleetLocalSettingsUnderRoot(root, file));
1306
+ return outside === undefined ? undefined : `${outside} does not resolve to a real path under the HQ root`;
1307
+ }
1308
+ /**
1309
+ * The program and arguments for one `fleet-local-settings` command, as the adapter (and `child::Runner` in hq-hook)
1310
+ * starts it: an executable file is started itself, any other with `bash`; master-hook always with `bash`. No shell
1311
+ * reads the words. Undefined for a master command whose master-hook is not a file (the hook skipped it too).
1312
+ */
1313
+ export function fleetLocalSettingsProgram(root, command) {
1314
+ const exec = (file, args) => {
1315
+ let executable = false;
1316
+ try {
1317
+ fs.accessSync(file, fs.constants.X_OK);
1318
+ executable = true;
1319
+ }
1320
+ catch { /* Not executable: run with bash. */ }
1321
+ return executable ? { program: file, args, bashEnv: true } : { program: "bash", args: [file, ...args], bashEnv: false };
1322
+ };
1323
+ switch (command.type) {
1324
+ case "gate": return exec(path.join(root, FLEET_LOCAL_HOOK_GATE), [command.id, command.script, ...command.args]);
1325
+ case "master": {
1326
+ const master = path.join(root, FLEET_LOCAL_MASTER_HOOK);
1327
+ try {
1328
+ if (!fs.statSync(master).isFile())
1329
+ return undefined;
1330
+ }
1331
+ catch {
1332
+ return undefined;
1333
+ }
1334
+ return { program: "bash", args: [master, command.event], bashEnv: false };
1335
+ }
1336
+ case "script": return exec(command.script, []);
1337
+ }
1338
+ }
1339
+ /**
1340
+ * Run the settings commands of a `fleet-local-settings` note in order, as the adapter's `dispatch_settings_hooks` did
1341
+ * in the hook (conductor ruling on #3042: a program the hook starts goes to the daemon on a request note). Each
1342
+ * reads the adapter's payload (the note's body) on stdin, with the variables the adapter exported for its hooks, in
1343
+ * the HQ root. Each is started by `runRequestProgram` under the one per-program limit; a command still running at
1344
+ * it is ended with its process group and the commands after it are skipped, as at the hook's limit. Output is
1345
+ * discarded and a failing command does not stop the rest (the adapter's PostToolUse is advisory). The note is done
1346
+ * once the list has been run: a retry would start the commands that already ran a second time.
1347
+ *
1348
+ * Before any command starts, the root's settings file is read again: a command runs only if it is still listed there
1349
+ * for the note's event and every file it starts resolves to a real path under the HQ root
1350
+ * (`fleetLocalSettingsRefusal`). A refused command is not started, is logged, and does not stop the rest.
1351
+ */
1352
+ async function runFleetLocalSettings(request, operation, base, options) {
1353
+ if (!request.body)
1354
+ return { code: 1 };
1355
+ const listed = fleetLocalSettingsListed(request.root, operation.event);
1356
+ const env = {
1357
+ ...base,
1358
+ // `stop::fleet::overlay(FleetLocal, Registry, root)` in hq-hook: what the adapter exports for its hooks.
1359
+ HQ_CHECKPOINT_RUNTIME: "hq-fleet-local", HQ_ROOT: request.root, CLAUDE_PROJECT_DIR: request.root,
1360
+ HQ_HARNESS: "codex", HQ_WORK_MESH_DISABLED: "1", HQ_HOOK_REQUEST_ID: request.id,
1361
+ };
1362
+ for (const command of operation.commands) {
1363
+ const refusal = fleetLocalSettingsRefusal(request.root, command, listed);
1364
+ if (refusal !== undefined) {
1365
+ options.log?.(`hook request ${request.stem}: refused the ${command.type} settings command: ${refusal}`);
1366
+ continue;
1367
+ }
1368
+ const started = fleetLocalSettingsProgram(request.root, command);
1369
+ if (!started)
1370
+ continue;
1371
+ const ran = await runRequestProgram(started.program, started.args, {
1372
+ cwd: request.root, env: started.bashEnv ? { ...env, BASH_ENV: "/dev/null" } : env, input: request.body,
1373
+ timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, ...(options.signal ? { signal: options.signal } : {}),
1374
+ });
1375
+ if (ran.ended)
1376
+ break;
1377
+ }
1378
+ return { code: 0 };
1379
+ }
1380
+ /**
1381
+ * The Work Mesh register step of a mid-session company bind (owner decision
1382
+ * 36), as `spawn_work_mesh_register` in hq-core v16.0.48-beta.124
1383
+ * `core/scripts/hq-session.sh` (line 600) started it, but in the daemon's
1384
+ * foreground instead of detached from the bind:
1385
+ *
1386
+ * HQ_ROOT=<root> CLAUDE_CODE_SESSION_ID=<sid> \
1387
+ * printf '%s' '{"session_id":…,"cwd":…,"company_slug":…}' \
1388
+ * | bash core/hooks/SessionStart/35-work-mesh-session-start.sh SessionStart \
1389
+ * >>workspace/logs/work-mesh-hook.log 2>&1 </dev/null
1390
+ *
1391
+ * - A note whose session had the hook switched off (`args.disabled`:
1392
+ * `HQ_WORK_MESH_DISABLED` or `HQ_DISABLED_HOOKS`, which the daemon cannot
1393
+ * read from the session): done, nothing is started, one log line. The
1394
+ * hook exited at once there in the shell.
1395
+ * - A root without the hook: done, nothing is started (`[ -f "$hook" ] || return 0`).
1396
+ * - The shell also stopped where `jq` was missing, because it built the event
1397
+ * with jq. The daemon builds it itself and does not look for jq (owner
1398
+ * decision 48: the Work Mesh bind runs on every machine).
1399
+ * - The session variables the hook reads before the event's `session_id`
1400
+ * are removed from the daemon's environment, so the hook's `SID` is the
1401
+ * note's session, as it was in the session that bound.
1402
+ * - The program runs where the bind ran (the note's `cwd`, when it is a
1403
+ * folder; else the root).
1404
+ * - The hook's exit status is ignored when it ended by itself (the shell's
1405
+ * `|| true` on a detached job); a run stopped at the limit or by a daemon
1406
+ * stop is a failed try. A log that cannot be opened is a failed try too
1407
+ * (the shell's redirection failed and the hook did not run).
1408
+ */
1409
+ async function runMeshSessionBind(request, operation, base, options) {
1410
+ if (operation.disabled !== undefined) {
1411
+ options.log?.(`${operation.kind}: ${operation.disabled} switched the Work Mesh hook off in session ${operation.sessionId}; not bound`);
1412
+ return { code: 0 };
1413
+ }
1414
+ const hook = path.join(request.root, MESH_SESSION_BIND_HOOK);
1415
+ try {
1416
+ if (!fs.statSync(hook).isFile())
1417
+ return { code: 0 };
1418
+ }
1419
+ catch {
1420
+ return { code: 0 };
1421
+ }
1422
+ // jq -nc '{session_id:$sid,cwd:$cwd} + (if $company == "" then {} else {company_slug:$company} end)'
1423
+ const event = JSON.stringify(operation.kind === "mesh-session-bind"
1424
+ ? { session_id: operation.sessionId, cwd: operation.cwd, company_slug: operation.company }
1425
+ : { session_id: operation.sessionId, cwd: operation.cwd });
1426
+ const env = { ...base };
1427
+ for (const name of MESH_SESSION_BIND_UNSET)
1428
+ delete env[name];
1429
+ Object.assign(env, { HQ_ROOT: request.root, CLAUDE_CODE_SESSION_ID: operation.sessionId, HQ_HOOK_REQUEST_ID: request.id });
1430
+ let cwd = request.root;
1431
+ try {
1432
+ if (operation.cwd !== "" && fs.statSync(operation.cwd).isDirectory())
1433
+ cwd = operation.cwd;
1434
+ }
1435
+ catch { /* the root */ }
1436
+ const logFile = path.join(request.root, MESH_SESSION_BIND_LOG);
1437
+ let output;
1438
+ try {
1439
+ fs.mkdirSync(path.dirname(logFile), { recursive: true });
1440
+ output = fs.openSync(logFile, "a");
1441
+ }
1442
+ catch (error) {
1443
+ options.log?.(`${operation.kind}: ${MESH_SESSION_BIND_LOG} under ${request.root} could not be opened (${String(error)})`);
1444
+ return { code: 1 };
1445
+ }
1446
+ try {
1447
+ if (options.signal?.aborted)
1448
+ return { code: 1 };
1449
+ // spawnRequestProgram's stop model, as every kind; stdout and stderr go to the log file (`>>log 2>&1`).
1450
+ const { child, settle } = spawnRequestProgram("bash", [hook, "SessionStart"], {
1451
+ cwd, env, windowsHide: true, stdio: ["pipe", output, output],
1452
+ }, { timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs, signal: options.signal });
1453
+ // A hook that exits before it reads leaves a closed pipe; its run is what counts.
1454
+ child.stdin?.on("error", () => undefined);
1455
+ child.stdin?.end(event);
1456
+ return await new Promise(resolve => {
1457
+ let settled = false;
1458
+ const finish = (exited) => {
1459
+ if (settled)
1460
+ return;
1461
+ settled = true;
1462
+ // Stopped at the limit or by a daemon stop (its whole group with it), or never started: a failed try.
1463
+ // A hook that ran to its end is done, whatever its exit status.
1464
+ resolve({ code: settle() || !exited ? 1 : 0 });
1465
+ };
1466
+ child.once("error", () => finish(false));
1467
+ child.once("close", code => finish(code !== null));
1468
+ });
1469
+ }
1470
+ finally {
1471
+ fs.closeSync(output);
1472
+ }
1473
+ }
1474
+ /** The prompt in a `startwork-prefetch` body, or undefined for a body the hook does not leave. */
1475
+ function startworkPrefetchPrompt(body) {
1476
+ if (!body || body.length >= STARTWORK_PREFETCH_PROMPT_LIMIT || body.includes(0))
1477
+ return undefined;
1478
+ try {
1479
+ return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(body);
1480
+ }
1481
+ catch {
1482
+ return undefined;
1483
+ }
1484
+ }
1485
+ /**
1486
+ * The `/startwork <argument>` company prefetch that intent-hint.sh (hq-core
1487
+ * v16.0.48-beta.124) ran in the prompt hook, run by the daemon instead
1488
+ * (standing rule b; the native hook starts no program):
1489
+ *
1490
+ * env HQ_ROOT="$HQ_ROOT" bash "$HQ_ROOT/core/scripts/startwork-prefetch.sh" \
1491
+ * --prompt "$PROMPT" --session-id "$PREFETCH_SID" 2>/dev/null || true
1492
+ *
1493
+ * - The program and its arguments are an argv array, no shell: the prompt is
1494
+ * the note's body, passed as one argument byte for byte; the session id is
1495
+ * the note's checked `args.sessionId`.
1496
+ * - A body that is not UTF-8 text, holds a NUL, or is not shorter than
1497
+ * `STARTWORK_PREFETCH_PROMPT_LIMIT` bytes is not one the hook leaves: done,
1498
+ * nothing is started, one log line (as a rejected note).
1499
+ * - A root without the script: done, nothing is started (bash found no file
1500
+ * there, and `|| true` ended it).
1501
+ * - The session's switches were read by the hook before it left the note
1502
+ * (`HQ_STARTWORK_PREFETCH`, `HQ_DISABLED_HOOKS`); the daemon's own values are
1503
+ * not the session's and are removed, so the script decides only on the prompt.
1504
+ * - Output is not read: the block the script prints went to the model's turn,
1505
+ * and that turn has passed (the recorded one-turn delay in the hook's ledger).
1506
+ * - Exit status ignored when the script ended by itself (`|| true`); a run
1507
+ * stopped at the limit or by a daemon stop is a failed try.
1508
+ */
1509
+ async function runStartworkPrefetch(request, operation, base, options) {
1510
+ const prompt = startworkPrefetchPrompt(request.body);
1511
+ if (prompt === undefined) {
1512
+ options.log?.(`Hook request ${request.stem}: the startwork-prefetch prompt is not one the hook leaves; deleted, nothing was run`);
1513
+ return { code: 0 };
1514
+ }
1515
+ const script = path.join(request.root, STARTWORK_PREFETCH_SCRIPT);
1516
+ try {
1517
+ if (!fs.statSync(script).isFile())
1518
+ return { code: 0 };
1519
+ }
1520
+ catch {
1521
+ return { code: 0 };
1522
+ }
1523
+ const env = { ...base };
1524
+ delete env.HQ_STARTWORK_PREFETCH;
1525
+ delete env.HQ_DISABLED_HOOKS;
1526
+ Object.assign(env, { HQ_ROOT: request.root, HQ_HOOK_REQUEST_ID: request.id });
1527
+ const ran = await runRequestProgram("bash", [script, "--prompt", prompt, "--session-id", operation.sessionId], {
1528
+ cwd: request.root, env, timeoutMs: options.timeoutMs, killGraceMs: options.killGraceMs,
1529
+ ...(options.signal ? { signal: options.signal } : {}),
1530
+ });
1531
+ return { code: !ran.ended && ran.exited ? 0 : ran.code || 1 };
1532
+ }
1533
+ /**
1534
+ * Run a validated request: the daemon's own CLI entry point, for `autocommit` the HQ root's own autosave
1535
+ * script, for `plan-sync` the HQ root's own helper with the plan on stdin, as the shell hook did, for
1536
+ * `pr-footer` the root's fingerprint script and `gh` (`addPrFooter`), for `mesh-session-bind` the root's
1537
+ * SessionStart Work Mesh hook (`runMeshSessionBind`).
1538
+ *
1539
+ * Every program runs in its own process group (`spawnRequestProgram`, through
1540
+ * `runRequestProgram`). At the limit the group is sent SIGTERM, so a script
1541
+ * can run its exit trap and the programs it started end with it, and SIGKILL
1542
+ * after the grace time. Both count as a failed try.
1543
+ *
1544
+ * `autocommit` only. The script exits 0 without a word when another autosave
1545
+ * holds its lock, which is not a commit: a lock that is held is answered with
1546
+ * `later` (the note is kept and no try is counted), without starting the
1547
+ * script while the lock is younger than the script's own takeover age. The
1548
+ * script's warning line on stderr ("WARNING: HQ autosave ...", once per
1549
+ * session and cause) becomes the session's failure file.
1550
+ *
1551
+ * `plan-sync` only. A helper that is not an executable file is done (code 0),
1552
+ * as the shell hook skipped it. The helper's own exit status is ignored when
1553
+ * it ended by itself (the shell hook's `|| true`); a run that had to be
1554
+ * stopped at the limit still counts as a failed try.
1555
+ */
1556
+ export function executeHookRequest(request, options) {
1557
+ try {
1558
+ if (!options.allowedRoot || fs.realpathSync(request.root) !== fs.realpathSync(options.allowedRoot))
1559
+ return Promise.resolve({ code: 1 });
1560
+ if (!fs.statSync(path.join(request.root, "core/core.yaml")).isFile())
1561
+ return Promise.resolve({ code: 1 });
1562
+ }
1563
+ catch {
1564
+ return Promise.resolve({ code: 1 });
1565
+ }
1566
+ const operation = request.operation;
1567
+ if (operation.kind === "acl-suggest") {
1568
+ if (options.signal?.aborted)
1569
+ return Promise.resolve({ code: 1 });
1570
+ const code = executeAclSuggestion(request.root, request.session, operation.candidates, options.env ?? process.env);
1571
+ return Promise.resolve({ code });
1572
+ }
1573
+ if (operation.kind === "mesh-reconcile")
1574
+ return runMeshReconcile(request.root, request.session, operation, options);
1575
+ if (operation.kind === "mesh-register-retry")
1576
+ return runMeshRegisterRetry(request.root, operation, options).then(({ code }) => ({ code }));
1577
+ if (isMachineCheckRequestKind(operation.kind))
1578
+ return runMachineCheckRequest(request.root, { kind: operation.kind }, options.env ? { env: options.env } : {});
1579
+ if (operation.kind === "mesh-tool-writes")
1580
+ return runMeshToolWrites(operation, { ...options, root: request.root });
1581
+ if (operation.kind === "fleet-session-start")
1582
+ return runFleetSessionStart(request, operation, options);
1583
+ const cliArgs = hookRequestArguments(request);
1584
+ if (!cliArgs)
1585
+ return Promise.resolve({ code: 1 });
1586
+ let program = options.nodeBinary;
1587
+ let args = [options.hqBinary, ...cliArgs];
1588
+ let input;
1589
+ let lock;
1590
+ const base = { ...(options.env ?? process.env) };
1591
+ const killGraceMs = options.killGraceMs ?? HOOK_REQUEST_KILL_GRACE_MS;
1592
+ if (request.operation.kind === "mesh-session-bind" || request.operation.kind === "mesh-session-register") {
1593
+ return runMeshSessionBind(request, request.operation, base, {
1594
+ ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
1595
+ timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, ...(options.log ? { log: options.log } : {}),
1596
+ }).catch(() => ({ code: 1 }));
1597
+ }
1598
+ if (request.operation.kind === "startwork-prefetch") {
1599
+ return runStartworkPrefetch(request, request.operation, base, {
1600
+ ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
1601
+ timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, ...(options.log ? { log: options.log } : {}),
1602
+ }).catch(() => ({ code: 1 }));
1603
+ }
1604
+ if (request.operation.kind === "pr-footer") {
1605
+ return addPrFooter(request, request.operation.url, base, {
1606
+ ...(options.signal ? { signal: options.signal } : {}), killGraceMs,
1607
+ programMs: options.prFooterProgramMs ?? PR_FOOTER_PROGRAM_MS, delayMs: options.prFooterDelayMs ?? PR_FOOTER_DELAY_MS,
1608
+ rounds: options.prFooterRounds ?? PR_FOOTER_ROUNDS,
1609
+ }).catch(() => ({ code: 1 }));
1610
+ }
1611
+ if (request.operation.kind === "fleet-local-settings") {
1612
+ return runFleetLocalSettings(request, request.operation, base, {
1613
+ ...(options.signal ? { signal: options.signal } : {}), ...(options.log ? { log: options.log } : {}), killGraceMs,
1614
+ timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS,
1615
+ }).catch(() => ({ code: 0 }));
1616
+ }
1617
+ if (request.operation.kind === "autocommit") {
1618
+ const script = path.join(request.root, AUTOCOMMIT_SCRIPT);
1619
+ // A root without the script never autosaved: done, nothing is started.
1620
+ try {
1621
+ if (!fs.statSync(script).isFile())
1622
+ return Promise.resolve({ code: 0 });
1623
+ }
1624
+ catch {
1625
+ return Promise.resolve({ code: 0 });
1626
+ }
1627
+ program = "bash";
1628
+ args = [script];
1629
+ input = autocommitInput(request);
1630
+ // The hook read the switch in the session; the script's root is the note's root.
1631
+ delete base.HQ_AUTOCOMMIT;
1632
+ delete base.HQ_AUTOCOMMIT_STRICT;
1633
+ // Without this the script does not start node to read the live flag that chose the shape of its warning.
1634
+ // The shape is fixed now (owner decision 48) and the script's stdout is not read.
1635
+ delete base.HQ_FLAGS_API_URL;
1636
+ base.CLAUDE_PROJECT_DIR = request.root;
1637
+ lock = autocommitLock(base);
1638
+ if (autocommitLockIsFresh(lock, base))
1639
+ return Promise.resolve({ code: 0, later: true });
1640
+ }
1641
+ else if (request.operation.kind === "plan-sync") {
1642
+ if (!request.body)
1643
+ return Promise.resolve({ code: 1 });
1644
+ program = path.join(request.root, PLAN_SYNC_HELPER);
1645
+ // The shell hook skipped a helper that is not an executable file; so does the daemon, and the note is done.
1646
+ try {
1647
+ fs.accessSync(program, fs.constants.X_OK);
1648
+ if (!fs.statSync(program).isFile())
1649
+ return Promise.resolve({ code: 0 });
1650
+ }
1651
+ catch {
1652
+ return Promise.resolve({ code: 0 });
1653
+ }
1654
+ args = cliArgs;
1655
+ // `printf '%s\n' "$body" | helper`: the text and one line break.
1656
+ input = Buffer.concat([request.body, Buffer.from("\n")]);
1657
+ }
1658
+ // The shell hook ignored the helper's exit status (`|| true`): a helper that ran to its end is done, whatever it returned.
1659
+ const exitIgnored = request.operation.kind === "plan-sync";
1660
+ // The two variables reindex.sh set: no update check, and no wait for the
1661
+ // per-root operation lock (a busy lock is a failed try, retried later).
1662
+ // The plan-sync helper is started with the environment the shell hook gave it.
1663
+ const env = exitIgnored
1664
+ ? { ...base, HQ_ROOT: request.root, HQ_HOOK_REQUEST_ID: request.id }
1665
+ : { ...base, HQ_ROOT: request.root, HQ_NO_UPDATE_CHECK: "1", HQ_OP_LOCK_TIMEOUT: "0", HQ_HOOK_REQUEST_ID: request.id };
1666
+ const home = options.home ?? base.HOME ?? os.homedir();
1667
+ return runRequestProgram(program, args, {
1668
+ cwd: request.root, env, timeoutMs: options.timeoutMs ?? HOOK_REQUEST_KILL_MS, killGraceMs,
1669
+ ...(input === undefined ? {} : { input }), ...(lock === undefined ? {} : { stderr: AUTOCOMMIT_STDERR_MAX_BYTES }),
1670
+ ...(options.signal ? { signal: options.signal } : {}),
1671
+ }).then(ran => {
1672
+ if (ran.ended) {
1673
+ // A lock the script's exit trap did not release is released here.
1674
+ if (lock !== undefined && ran.pid !== undefined)
1675
+ releaseAutocommitLock(lock, ran.pid);
1676
+ return { code: ran.code };
1677
+ }
1678
+ if (lock !== undefined) {
1679
+ if (/^WARNING: HQ autosave /m.test(ran.stderr))
1680
+ leaveAutocommitFailure(home, request.root, request.session);
1681
+ // Exit 0 with the lock still held: the script may have stopped at the lock without committing.
1682
+ if (ran.code === 0 && fs.existsSync(lock))
1683
+ return { code: 0, later: true };
1684
+ }
1685
+ if (exitIgnored && ran.exited)
1686
+ return { code: 0 };
1687
+ return { code: ran.code };
1688
+ });
1689
+ }
1690
+ /** The `check-hq-update` and `check-client-health` request notes
1691
+ * (crates/hq-hook/src/daemon_req.rs, `Kind::CheckHqUpdate` and
1692
+ * `Kind::CheckClientHealth`; hq-core-rust decision 19 with standing rule (b)).
1693
+ *
1694
+ * The native SessionStart rows for these two machine checks start no program.
1695
+ * When the hooks own the machine checks (master-hook's helper answers legacy)
1696
+ * the row leaves one note instead, and the daemon runs that one check here on
1697
+ * its next pass over the notes.
1698
+ *
1699
+ * The check runs through the machine-check runner (machine-checks.ts): the
1700
+ * same script rules, environment and time limit as the daemon's batch. Like
1701
+ * the batch it runs collect-only when the installed core advertises the mode,
1702
+ * so a show-once message nobody has seen is not marked as shown; the work
1703
+ * itself (the update, the bounded repair, their cooldowns) is done. Its result
1704
+ * is not written to the results file: that file is the batch's, and its age is
1705
+ * what the owner decision reads, so a single check must not refresh it. It runs
1706
+ * as a single run (`single: true`): it never takes the batch's in-flight slot,
1707
+ * so a batch tick during it runs the full batch and writes that file.
1708
+ */
1709
+ /** The request kinds these notes carry: each is the id of one machine check. */
1710
+ export const MACHINE_CHECK_REQUEST_KINDS = ["check-hq-update", "check-client-health"];
1711
+ export function isMachineCheckRequestKind(kind) {
1712
+ return typeof kind === "string" && MACHINE_CHECK_REQUEST_KINDS.includes(kind);
1713
+ }
1714
+ /** A note of one of these kinds carries no fields. Undefined for anything else. */
1715
+ export function parseMachineCheckOperation(kind, args) {
1716
+ if (!isMachineCheckRequestKind(kind) || Object.keys(args).length !== 0)
1717
+ return undefined;
1718
+ return { kind };
1719
+ }
1720
+ /**
1721
+ * Run the note's check once in `root` (already checked to be the daemon's own
1722
+ * root). Done (0) when the check ran to an answer, or when nothing is to run
1723
+ * (inside a machine check); a failed try (1) when its answer is `unknown`
1724
+ * (missing or refused script, timeout, crash, non-zero exit), which the
1725
+ * drainer retries as any failed note.
1726
+ */
1727
+ export async function runMachineCheckRequest(root, operation, options = {}) {
1728
+ const spec = MACHINE_CHECKS.find((check) => check.id === operation.kind);
1729
+ if (!spec)
1730
+ return { code: 1 };
1731
+ const env = options.env ?? process.env;
1732
+ if (env.HQ_MACHINE_CHECKS_RUNNING === "1")
1733
+ return { code: 0 };
1734
+ try {
1735
+ const collectOnly = (options.collectOnlySupported ?? machineCheckCollectOnlySupported)(root);
1736
+ const results = await (options.run ?? runMachineChecks)({ hqRoot: root, env, checks: [spec], collectOnly, single: true });
1737
+ const result = results.find((each) => each.id === spec.id);
1738
+ // A batch already running answers for every check, this one included.
1739
+ if (!result)
1740
+ return { code: 0 };
1741
+ return { code: result.status === "unknown" ? 1 : 0 };
1742
+ }
1743
+ catch {
1744
+ return { code: 1 };
1745
+ }
1746
+ }
1747
+ //# sourceMappingURL=hook-requests.js.map