@indigoai-us/hq-cli 5.345.226 → 5.345.230

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