@indigoai-us/hq-cli 5.345.220 → 5.345.222

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 (184) hide show
  1. package/CHANGELOG.md +164 -0
  2. package/dist/command-catalog.generated.d.ts +175 -2
  3. package/dist/command-catalog.generated.js +213 -2
  4. package/dist/commands/auth.js +6 -2
  5. package/dist/commands/bot-runtime.d.ts +18 -5
  6. package/dist/commands/bot-runtime.js +29 -12
  7. package/dist/commands/bot.d.ts +39 -2
  8. package/dist/commands/bot.js +140 -11
  9. package/dist/commands/core-delegate-w1b.js +9 -3
  10. package/dist/commands/core-stop-autosave.d.ts +21 -0
  11. package/dist/commands/core-stop-autosave.js +300 -0
  12. package/dist/commands/core.js +2 -0
  13. package/dist/commands/daemon.d.ts +6 -0
  14. package/dist/commands/daemon.js +46 -8
  15. package/dist/commands/doctor-usage.d.ts +5 -0
  16. package/dist/commands/doctor-usage.js +25 -0
  17. package/dist/commands/env.d.ts +49 -4
  18. package/dist/commands/env.js +355 -5
  19. package/dist/commands/lanes-shared.d.ts +3 -0
  20. package/dist/commands/lanes.d.ts +3 -0
  21. package/dist/commands/lanes.js +87 -3
  22. package/dist/commands/link.d.ts +2 -0
  23. package/dist/commands/link.js +14 -2
  24. package/dist/commands/mesh.js +23 -3
  25. package/dist/commands/sources.js +3 -3
  26. package/dist/commands/sync-core.d.ts +7 -0
  27. package/dist/commands/sync-core.js +132 -3
  28. package/dist/commands/whoami.js +96 -80
  29. package/dist/data/command-states.json +3 -0
  30. package/dist/lib/bot/config.d.ts +17 -0
  31. package/dist/lib/bot/config.js +13 -0
  32. package/dist/lib/bot/fleet-cron.js +24 -2
  33. package/dist/lib/bot/fleet-local.d.ts +30 -2
  34. package/dist/lib/bot/fleet-local.js +60 -1
  35. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  36. package/dist/lib/bot/grok-login-scope.js +93 -0
  37. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  38. package/dist/lib/bot/legacy-provider-login.js +28 -22
  39. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  40. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  41. package/dist/lib/core-utils/sentry-report.js +2 -0
  42. package/dist/lib/daemon/catalog.js +2 -0
  43. package/dist/lib/daemon/install.d.ts +2 -1
  44. package/dist/lib/daemon/install.js +9 -0
  45. package/dist/lib/daemon/legacy.d.ts +1 -0
  46. package/dist/lib/daemon/legacy.js +5 -2
  47. package/dist/lib/daemon/machine-check-owner.d.ts +2 -0
  48. package/dist/lib/daemon/machine-check-owner.js +6 -1
  49. package/dist/lib/daemon/machine-checks.d.ts +29 -2
  50. package/dist/lib/daemon/machine-checks.js +64 -13
  51. package/dist/lib/daemon/mesh-owner.d.ts +45 -0
  52. package/dist/lib/daemon/mesh-owner.js +166 -0
  53. package/dist/lib/daemon/native-notice-ledger.d.ts +27 -0
  54. package/dist/lib/daemon/native-notice-ledger.js +113 -0
  55. package/dist/lib/daemon/run.d.ts +15 -0
  56. package/dist/lib/daemon/run.js +137 -11
  57. package/dist/lib/daemon/selfcheck.d.ts +35 -2
  58. package/dist/lib/daemon/selfcheck.js +118 -9
  59. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  60. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  61. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  62. package/dist/lib/daemon/stop-autosave.js +111 -0
  63. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  64. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  65. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  66. package/dist/lib/daemon/stop-job-executor.js +126 -0
  67. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  68. package/dist/lib/daemon/stop-jobs.js +599 -0
  69. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  70. package/dist/lib/doctor/checks/host-core.js +1 -1
  71. package/dist/lib/environment/access-probes.d.ts +234 -0
  72. package/dist/lib/environment/access-probes.js +918 -0
  73. package/dist/lib/environment/profile.d.ts +15 -2
  74. package/dist/lib/environment/profile.js +55 -20
  75. package/dist/lib/environment/rfc3339.d.ts +8 -0
  76. package/dist/lib/environment/rfc3339.js +26 -0
  77. package/dist/lib/environment/work-requirements.d.ts +169 -0
  78. package/dist/lib/environment/work-requirements.js +389 -0
  79. package/dist/lib/hook-engine/coverage.d.ts +146 -7
  80. package/dist/lib/hook-engine/coverage.js +1480 -4
  81. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  82. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  83. package/dist/lib/hook-engine/native-stop-compatibility.json +362 -0
  84. package/dist/lib/hook-engine/reconcile.js +2 -2
  85. package/dist/lib/hot-channels/alert.d.ts +2 -2
  86. package/dist/lib/hot-channels/alert.js +8 -5
  87. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  88. package/dist/lib/hot-channels/signals-pass.js +296 -17
  89. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  90. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  91. package/dist/lib/install/hook-target.js +1 -1
  92. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  93. package/dist/lib/lanes/host-capacity.js +17 -2
  94. package/dist/lib/lanes/host-compute.d.ts +90 -0
  95. package/dist/lib/lanes/host-compute.js +185 -0
  96. package/dist/lib/lanes/index.d.ts +2 -0
  97. package/dist/lib/lanes/index.js +1 -0
  98. package/dist/lib/lanes/reconcile.js +22 -1
  99. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  100. package/dist/lib/lanes/resource-usage.js +589 -0
  101. package/dist/lib/lanes/run-size.d.ts +46 -0
  102. package/dist/lib/lanes/run-size.js +197 -0
  103. package/dist/lib/lanes/store.js +27 -0
  104. package/dist/lib/lanes/throttle.d.ts +36 -1
  105. package/dist/lib/lanes/throttle.js +47 -10
  106. package/dist/lib/lanes/types.d.ts +40 -0
  107. package/dist/lib/lanes/types.js +2 -2
  108. package/dist/lib/lanes/watcher.js +13 -4
  109. package/dist/lib/lanes/worker-process.d.ts +25 -2
  110. package/dist/lib/lanes/worker-process.js +71 -19
  111. package/dist/lib/mesh/live/daemon/config.d.ts +8 -1
  112. package/dist/lib/mesh/live/daemon/config.js +16 -0
  113. package/dist/lib/mesh/live/daemon/install.d.ts +31 -2
  114. package/dist/lib/mesh/live/daemon/install.js +142 -1
  115. package/dist/lib/mesh/live/daemon/login-home.d.ts +5 -0
  116. package/dist/lib/mesh/live/daemon/login-home.js +27 -0
  117. package/dist/lib/mesh/live/daemon/unit-home.d.ts +49 -0
  118. package/dist/lib/mesh/live/daemon/unit-home.js +134 -0
  119. package/dist/lib/placement/match.d.ts +192 -0
  120. package/dist/lib/placement/match.js +667 -0
  121. package/dist/lib/registry/registry.d.ts +35 -7
  122. package/dist/lib/registry/registry.js +88 -13
  123. package/dist/lib/safe-store.d.ts +14 -0
  124. package/dist/lib/safe-store.js +77 -4
  125. package/dist/lib/scan-packages/index.js +24 -2
  126. package/dist/lib/search-index/index.d.ts +88 -4
  127. package/dist/lib/search-index/index.js +288 -24
  128. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  129. package/dist/lib/search-index/max-doc-bytes.js +49 -23
  130. package/dist/lib/service-manager/startup-migration.d.ts +1 -0
  131. package/dist/lib/service-manager/startup-migration.js +3 -0
  132. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  133. package/dist/lib/signals/codex-lockdown.js +271 -0
  134. package/dist/lib/signals/codex-login.d.ts +37 -0
  135. package/dist/lib/signals/codex-login.js +83 -0
  136. package/dist/lib/signals/engine.d.ts +27 -0
  137. package/dist/lib/signals/engine.js +70 -0
  138. package/dist/lib/signals/reply.js +22 -1
  139. package/dist/lib/signals/run-record.js +6 -1
  140. package/dist/lib/signals/settings.d.ts +5 -0
  141. package/dist/lib/signals/settings.js +2 -0
  142. package/dist/lib/signals/steps/extract.d.ts +85 -9
  143. package/dist/lib/signals/steps/extract.js +317 -68
  144. package/dist/lib/signals/steps/types.d.ts +2 -0
  145. package/dist/lib/sync-core/engine-holds.d.ts +14 -0
  146. package/dist/lib/sync-core/engine-holds.js +60 -0
  147. package/dist/lib/sync-core/engine-home.d.ts +37 -1
  148. package/dist/lib/sync-core/engine-home.js +119 -16
  149. package/dist/lib/sync-core/reconcile.js +8 -0
  150. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  151. package/dist/lib/sync-core/rollout-state.js +5 -2
  152. package/dist/lib/sync-core/vault-settings.d.ts +21 -0
  153. package/dist/lib/sync-core/vault-settings.js +131 -0
  154. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  155. package/dist/lib/sync-core/vault-uid.js +4 -0
  156. package/dist/lib/windows/install-followup.d.ts +2 -0
  157. package/dist/lib/windows/install-followup.js +4 -1
  158. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  159. package/dist/utils/auth-session-check.d.ts +16 -0
  160. package/dist/utils/auth-session-check.js +16 -0
  161. package/dist/utils/client-health-contract.d.ts +6 -0
  162. package/dist/utils/client-health-contract.js +13 -0
  163. package/dist/utils/client-health.d.ts +7 -0
  164. package/dist/utils/client-health.js +22 -1
  165. package/dist/utils/command-usage.d.ts +40 -0
  166. package/dist/utils/command-usage.js +61 -0
  167. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  168. package/dist/utils/duplicate-command-usage.js +125 -0
  169. package/dist/utils/host-registration.js +5 -2
  170. package/dist/utils/pack-contributions.d.ts +3 -0
  171. package/dist/utils/pack-contributions.js +110 -23
  172. package/dist/utils/resident-package-preload.js +4 -0
  173. package/dist/utils/self-update.d.ts +3 -1
  174. package/dist/utils/self-update.js +56 -11
  175. package/dist/utils/sentry-fingerprint.js +9 -0
  176. package/dist/utils/update-lock.d.ts +151 -14
  177. package/dist/utils/update-lock.js +782 -46
  178. package/dist/utils/version-gate.js +12 -2
  179. package/dist/utils/windows-bash.d.ts +2 -0
  180. package/dist/utils/windows-bash.js +2 -1
  181. package/package.json +9 -8
  182. package/scripts/bench-core-compare.mjs +313 -0
  183. package/scripts/bench-core.mjs +399 -12
  184. package/scripts/check-function-manifest.mjs +116 -3
@@ -0,0 +1,599 @@
1
+ /** Consumer for the bounded append-only queue written by hq-hook Stop.
2
+ * Queue data is never an executable command: only the five producer shapes
3
+ * are accepted, and the caller dispatches the resulting typed operation.
4
+ */
5
+ import * as path from "node:path";
6
+ import { createHash } from "node:crypto";
7
+ import * as fs from "node:fs";
8
+ import { openStoreDir } from "../safe-store.js";
9
+ const ENV_NAMES = new Set([
10
+ "PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "TMP", "TEMP", "CLAUDE_PROJECT_DIR",
11
+ "HQ_ROOT", "HQ_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CLAUDE_SESSION_ID", "CODEX_SESSION_ID",
12
+ "CODEX_THREAD_ID", "HQ_HARNESS", "HQ_WORK_MESH_HARNESS", "HQ_CHECKPOINT_RUNTIME",
13
+ "HQ_ADAPTER_CONTRACT_VERSION", "WORK_MESH_SEQ_DIR", "HQ_DISABLED_HOOKS", "HQ_WORK_MESH_DISABLED",
14
+ "HQ_CLI_BIN", "HQ_OFFLOAD_MIN_BYTES", "HQ_AUTOCOMMIT", "HQ_AUTOCOMMIT_STRICT",
15
+ "HQ_AUTOCOMMIT_LOG_MAX_BYTES", "HQ_AUTOCOMMIT_LOCK_PROBE", "HQ_AUTOCOMMIT_PRESTAGED_STALE_MINUTES",
16
+ "HQ_AUTOCOMMIT_STALE_LOCK_MINUTES", "HQ_COMPANY_UID", "HQ_COMPANY_SLUG", "HQ_FLAGS_API_URL",
17
+ "WORK_MESH_SPOOL", "LANG", "LC_ALL", "LC_CTYPE", "SHELL", "XDG_CONFIG_HOME", "XDG_CACHE_HOME",
18
+ "SYSTEMROOT", "SystemRoot", "WINDIR", "COMSPEC", "PATHEXT", "APPDATA", "LOCALAPPDATA",
19
+ "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "PROGRAMDATA", "PROGRAMFILES", "MSYSTEM", "MSYS",
20
+ "HQ_HOOK_ASYNC_DRAIN",
21
+ ]);
22
+ const record = (v) => v !== null && typeof v === "object" && !Array.isArray(v) ? v : undefined;
23
+ const plain = (s) => typeof s === "string" && !s.includes("\0");
24
+ export function parseStopJob(text, home) {
25
+ if (Buffer.byteLength(text) > 65_536)
26
+ return undefined;
27
+ let value;
28
+ try {
29
+ value = record(JSON.parse(text));
30
+ }
31
+ catch {
32
+ return undefined;
33
+ }
34
+ if (!value || value.v !== 1 || !plain(value.id) || !/^[A-Za-z0-9_-]{1,128}$/.test(value.id)
35
+ || !plain(value.hqRoot) || !path.isAbsolute(value.hqRoot))
36
+ return undefined;
37
+ const inputs = record(value.inputs);
38
+ if (!inputs || !plain(inputs.cwd) || !path.isAbsolute(inputs.cwd))
39
+ return undefined;
40
+ const rawEnv = record(inputs.env);
41
+ if (!rawEnv || Object.entries(rawEnv).some(([key, val]) => !ENV_NAMES.has(key) || !plain(val)))
42
+ return undefined;
43
+ // A queued environment cannot select a different user's home for a daemon.
44
+ if (rawEnv.HOME !== undefined && rawEnv.HOME !== home)
45
+ return undefined;
46
+ const argv = inputs.argv;
47
+ if (!Array.isArray(argv) || !argv.every(plain))
48
+ return undefined;
49
+ const env = Object.fromEntries(Object.entries(rawEnv));
50
+ let operation;
51
+ if (value.job === "checkpoint-after-reply" || value.job === "checkpoint-heartbeat") {
52
+ const summary = value.job === "checkpoint-after-reply"
53
+ ? "turn ended with its user-facing reply already delivered"
54
+ : "automation heartbeat turn ended without a user-facing reply";
55
+ if (argv.length !== 11 || argv[0] !== "hq" || argv[1] !== "core" || argv[2] !== "checkpoint"
56
+ || argv[3] !== "--session-id" || argv[4] !== value.sessionId || argv[5] !== "--trigger"
57
+ || argv[6] !== "stop-gate-auto" || argv[7] !== "--transcript" || argv[9] !== "--summary"
58
+ || argv[10] !== summary || inputs.stdin !== undefined)
59
+ return undefined;
60
+ operation = { kind: "checkpoint", session: argv[4], transcript: argv[8], summary };
61
+ }
62
+ else if (value.job === "checkpoint-gate-probe") {
63
+ if (JSON.stringify(argv) !== JSON.stringify(["hq", "core", "checkpoint", "--gate-probe"])
64
+ || inputs.stdin !== undefined || !plain(env.HQ_CHECKPOINT_RUNTIME))
65
+ return undefined;
66
+ operation = { kind: "probe", runtime: env.HQ_CHECKPOINT_RUNTIME };
67
+ }
68
+ else if (value.job === "checkpoint-gate-setting-refresh") {
69
+ if (argv.length !== 6 || argv.slice(0, 5).join(" ") !== "hq core checkpoint-gate-setting --refresh --company"
70
+ || !/^[a-z0-9][a-z0-9-]*$/.test(argv[5]) || inputs.stdin !== undefined)
71
+ return undefined;
72
+ operation = { kind: "refresh", company: argv[5] };
73
+ }
74
+ else if (value.job === "autosave-bash-sweep") {
75
+ if (argv.length !== 2 || argv[0] !== "bash" || argv[1] !== path.join(value.hqRoot, ".claude/hooks/hq-autocommit-bash-sweep.sh")
76
+ || !plain(inputs.stdin))
77
+ return undefined;
78
+ let payload;
79
+ try {
80
+ payload = record(JSON.parse(inputs.stdin));
81
+ }
82
+ catch {
83
+ return undefined;
84
+ }
85
+ if (!payload || Object.keys(payload).some(key => key !== "session_id")
86
+ || (payload.session_id !== undefined && !plain(payload.session_id)))
87
+ return undefined;
88
+ operation = { kind: "autosave", session: payload.session_id ?? "" };
89
+ }
90
+ else
91
+ return undefined;
92
+ return { id: value.id, digest: createHash("sha256").update(text).digest("hex"), root: value.hqRoot, cwd: inputs.cwd, operation, env };
93
+ }
94
+ /** The longest a job runs before the executor kills it. */
95
+ export const STOP_JOB_KILL_MS = 60_000;
96
+ /** A `started` receipt older than this has no running job behind it: the kill timer plus a margin. */
97
+ export const STOP_JOB_STALE_MS = STOP_JOB_KILL_MS + 60_000;
98
+ /** Receipts and completion proofs are kept this long; a record older than this is never run. */
99
+ export const STOP_JOB_RETENTION_MS = 7 * 24 * 60 * 60_000;
100
+ /** An interrupted job runs again once; interrupted twice, it is skipped. */
101
+ const MAX_ATTEMPTS = 2;
102
+ const LIVE = "stop-jobs.jsonl";
103
+ const ROTATED = "stop-jobs.1.jsonl";
104
+ const CURSOR = "stop-jobs.cursor";
105
+ const WINDOW = 65_536;
106
+ /** Lines consumed per pass (run, skipped or already receipted); the drainer schedules another pass at once when reached. */
107
+ export const STOP_JOB_PASS_LIMIT = 64;
108
+ const ROTATE_BYTES = 1_048_576;
109
+ /** The Rust writer opens, checks and writes in one call; a minute covers any writer that opened the old name. */
110
+ const ROTATE_GRACE_MS = 60_000;
111
+ const PRUNE_INTERVAL_MS = 60 * 60_000;
112
+ const PRUNE_SCAN_LIMIT = 4096;
113
+ const RECEIPT_NAME = /^stop-job-[0-9a-f]{64}\.json$/;
114
+ /** Builds only known CLI arguments from the validated operation. */
115
+ export function stopJobArguments(job) {
116
+ const op = job.operation;
117
+ switch (op.kind) {
118
+ case "checkpoint": return ["core", "checkpoint", "--session-id", op.session, "--trigger", "stop-gate-auto", "--transcript", op.transcript, "--summary", op.summary];
119
+ case "probe": return ["core", "checkpoint", "--gate-probe"];
120
+ case "refresh": return ["core", "checkpoint-gate-setting", "--refresh", "--company", op.company];
121
+ case "autosave": return ["core", "stop-autosave", "--session-id", op.session];
122
+ }
123
+ }
124
+ /** Startup scan plus file notifications, with a bounded fallback scan when
125
+ * a watcher is unavailable or an event was missed. The singleton daemon owns
126
+ * this consumer and close waits for its current operation to finish. */
127
+ export function startStopJobDrainer(options) {
128
+ const dir = path.join(options.home, ".hq/daemon/jobs");
129
+ let watcher;
130
+ let timer;
131
+ let running;
132
+ let closed = false;
133
+ let again = false;
134
+ const schedule = (delay = 50) => {
135
+ if (closed)
136
+ return;
137
+ if (timer)
138
+ clearTimeout(timer);
139
+ timer = setTimeout(run, delay);
140
+ timer.unref();
141
+ };
142
+ const run = () => {
143
+ timer = undefined;
144
+ if (closed)
145
+ return;
146
+ if (running) {
147
+ again = true;
148
+ return;
149
+ }
150
+ if (!watcher) {
151
+ try {
152
+ watcher = fs.watch(dir, (_kind, filename) => {
153
+ if (filename === null || filename.toString() === "stop-jobs.jsonl")
154
+ schedule();
155
+ });
156
+ watcher.on("error", () => { watcher?.close(); watcher = undefined; schedule(1000); });
157
+ watcher.unref();
158
+ }
159
+ catch { /* Startup before the first producer: retry on fallback. */ }
160
+ }
161
+ running = drainStopJobs(options).then(count => { if (count >= STOP_JOB_PASS_LIMIT)
162
+ again = true; })
163
+ .catch(() => options.log("Stop queue scan failed; pending records retained"))
164
+ .finally(() => {
165
+ running = undefined;
166
+ schedule(again ? 0 : 5000);
167
+ again = false;
168
+ });
169
+ };
170
+ schedule(0);
171
+ return { async close() { closed = true; if (timer)
172
+ clearTimeout(timer); watcher?.close(); await running; } };
173
+ }
174
+ // All production consumers are behind the canonical per-user daemon lease.
175
+ // Notification overlap within that owner is excluded separately in memory;
176
+ // no additional persistent lock can survive a crash and strand the queue.
177
+ const activeQueues = new Set();
178
+ const lastPrune = new Map();
179
+ /**
180
+ * Drain the queue. It always makes progress: no input stops it for good.
181
+ *
182
+ * - The cursor names the queue file by identity. A replaced, truncated or
183
+ * rewritten queue (or an unreadable cursor) restarts at the start of the
184
+ * file now there. That is safe because every consumed line has a receipt
185
+ * keyed by its digest, so a line seen again is not run again, and a line
186
+ * older than the receipt retention is never run (`expired`).
187
+ * - A line that is not UTF-8, or a record longer than the producer's line
188
+ * limit, is skipped (logged) and the cursor moves past it.
189
+ * - A `started` receipt with no completion proof is a job that was
190
+ * interrupted (daemon killed, crash, power loss). Once no job can still be
191
+ * running behind it (its daemon is gone, or it is older than the kill timer
192
+ * plus a margin) it runs once more: checkpoint, gate probe, setting refresh
193
+ * and autosave each recompute their result from current state, so a second
194
+ * run repeats work rather than duplicating it, and losing the job would
195
+ * lose the checkpoint or autosave the shell always made. A job interrupted
196
+ * twice is skipped with a warning, so a job that itself kills the daemon
197
+ * cannot stall the queue.
198
+ * - Pruning: when the whole queue is consumed and has grown past a bound, it
199
+ * is renamed to `stop-jobs.1.jsonl` (the Rust writer opens the name with
200
+ * O_APPEND and writes each line in one call, with no lock, so a writer that
201
+ * opened the old name before the rename appends to the renamed file). The
202
+ * renamed file is drained first and removed only after a grace period with
203
+ * no write. Receipts and completion proofs older than the retention are
204
+ * removed only when the queue is fully consumed, so only for jobs behind
205
+ * the cursor.
206
+ */
207
+ export async function drainStopJobs(options) {
208
+ if (!options.ownsQueue()) {
209
+ options.log("Stop queue lease is not held; queue retained");
210
+ return 0;
211
+ }
212
+ const key = path.resolve(options.home);
213
+ if (activeQueues.has(key))
214
+ return 0;
215
+ activeQueues.add(key);
216
+ try {
217
+ const opened = openStoreDir(path.join(options.home, ".hq/daemon/jobs"), { home: options.home });
218
+ if (!opened.ok) {
219
+ if (opened.code !== "folder-missing")
220
+ options.log(`Stop queue unavailable: ${opened.code}`);
221
+ return 0;
222
+ }
223
+ try {
224
+ const pass = new Pass(opened.value, options);
225
+ const idle = await pass.drain();
226
+ const now = pass.now();
227
+ if (idle && now - (lastPrune.get(key) ?? -Infinity) >= PRUNE_INTERVAL_MS && options.ownsQueue()) {
228
+ lastPrune.set(key, now);
229
+ pruneReceipts(opened.value, now - STOP_JOB_RETENTION_MS);
230
+ try {
231
+ options.pruneResults?.(now - STOP_JOB_RETENTION_MS);
232
+ }
233
+ catch { /* Proofs are retried next interval. */ }
234
+ }
235
+ return pass.done;
236
+ }
237
+ finally {
238
+ opened.value.close();
239
+ }
240
+ }
241
+ finally {
242
+ activeQueues.delete(key);
243
+ }
244
+ }
245
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
246
+ class Pass {
247
+ store;
248
+ options;
249
+ done = 0;
250
+ cursor = { offset: 0 };
251
+ constructor(store, options) {
252
+ this.store = store;
253
+ this.options = options;
254
+ }
255
+ now() { return (this.options.now ?? Date.now)(); }
256
+ log(message) { this.options.log(message); }
257
+ /** True when every complete line has been consumed (the queue is idle). */
258
+ async drain() {
259
+ const loaded = this.loadCursor();
260
+ if (!loaded)
261
+ return false;
262
+ this.cursor = loaded;
263
+ const rotated = this.identity(ROTATED);
264
+ if (rotated === null)
265
+ return false;
266
+ if (rotated !== undefined) {
267
+ if (this.cursor.rotatedAt === undefined) {
268
+ // Rotated without a recorded time (an interrupted rotation): its grace starts now.
269
+ this.cursor = { ...this.cursor, rotatedAt: this.now() };
270
+ if (!this.store.writeAtomic(CURSOR, JSON.stringify(this.cursor)).ok)
271
+ return false;
272
+ }
273
+ const end = await this.drainFile(ROTATED, this.start(ROTATED, rotated));
274
+ if (end === "stopped")
275
+ return false;
276
+ const facts = this.store.stat(ROTATED);
277
+ if (!facts.ok)
278
+ return false;
279
+ if (this.now() - Math.max(facts.value.mtimeMs, this.cursor.rotatedAt ?? 0) < (this.options.rotateGraceMs ?? ROTATE_GRACE_MS))
280
+ return false;
281
+ // No writer can still append to it: every producer line ends with a newline in one write.
282
+ if (end === "partial")
283
+ this.log("Stop queue rotated file ended without a newline; its last bytes were dropped");
284
+ const removed = this.store.remove(ROTATED);
285
+ if (!removed.ok) {
286
+ this.log(`Stop queue rotated file could not be removed: ${removed.code}`);
287
+ return false;
288
+ }
289
+ this.cursor = { offset: 0 };
290
+ if (!this.store.writeAtomic(CURSOR, "0").ok)
291
+ return false;
292
+ }
293
+ const live = this.identity(LIVE);
294
+ if (live === null)
295
+ return false;
296
+ if (live === undefined)
297
+ return true;
298
+ const end = await this.drainFile(LIVE, this.start(LIVE, live));
299
+ if (end !== "eof")
300
+ return false;
301
+ const facts = this.store.stat(LIVE);
302
+ if (facts.ok && facts.value.size >= (this.options.rotateBytes ?? ROTATE_BYTES) && this.options.ownsQueue()) {
303
+ // The cursor keeps the file's identity, which the rename does not change.
304
+ const rotating = { ...this.cursor, rotatedAt: this.now() };
305
+ if (this.store.writeAtomic(CURSOR, JSON.stringify(rotating)).ok) {
306
+ this.cursor = rotating;
307
+ const renamed = this.store.rename(LIVE, ROTATED);
308
+ if (!renamed.ok)
309
+ this.log(`Stop queue rotation failed: ${renamed.code}`);
310
+ }
311
+ }
312
+ return true;
313
+ }
314
+ /** The saved cursor; an unreadable one restarts at the start. Undefined when the cursor cannot be read safely. */
315
+ loadCursor() {
316
+ const file = this.store.read(CURSOR, { maxBytes: 512 });
317
+ if (!file.ok) {
318
+ if (file.code === "missing")
319
+ return { offset: 0 };
320
+ this.log(`Stop queue cursor refused: ${file.code}; queue retained`);
321
+ return undefined;
322
+ }
323
+ let saved;
324
+ try {
325
+ saved = JSON.parse(file.value.toString());
326
+ }
327
+ catch {
328
+ saved = undefined;
329
+ }
330
+ if (saved === 0)
331
+ return { offset: 0 };
332
+ const fields = record(saved);
333
+ if (fields && Number.isSafeInteger(fields.offset) && fields.offset >= 0
334
+ && typeof fields.identity === "string" && typeof fields.boundary === "string") {
335
+ return { offset: fields.offset, identity: fields.identity, boundary: fields.boundary,
336
+ ...(typeof fields.rotatedAt === "number" && Number.isFinite(fields.rotatedAt) ? { rotatedAt: fields.rotatedAt } : {}) };
337
+ }
338
+ this.log("Stop queue cursor is unreadable; restarting at the start of the queue");
339
+ return { offset: 0 };
340
+ }
341
+ /** The file's identity; undefined when missing, null when it cannot be read safely. */
342
+ identity(name) {
343
+ const read = this.store.readWithFacts(name, { offset: 0, maxBytes: 0, identity: true });
344
+ if (read.ok)
345
+ return read.value.facts.fileIdentity;
346
+ if (read.code === "missing")
347
+ return undefined;
348
+ this.log(`Stop queue read refused: ${read.code}`);
349
+ return null;
350
+ }
351
+ /** Where to start in `name`: the cursor when it still describes this file, else its start. */
352
+ start(name, identity) {
353
+ const { offset, identity: saved, boundary } = this.cursor;
354
+ if (saved === undefined)
355
+ return 0;
356
+ if (saved !== identity) {
357
+ this.log("Stop queue was replaced after its cursor; restarting at its start");
358
+ return 0;
359
+ }
360
+ const facts = this.store.stat(name);
361
+ if (facts.ok && facts.value.size < offset) {
362
+ this.log("Stop queue was truncated before its cursor; restarting at its start");
363
+ return 0;
364
+ }
365
+ const prior = this.store.readWithFacts(name, { offset: Math.max(0, offset - 64), maxBytes: Math.min(64, offset), identity: true });
366
+ if (!prior.ok || prior.value.facts.fileIdentity !== identity || sha256(prior.value.data) !== boundary) {
367
+ this.log("Stop queue changed before its cursor; restarting at its start");
368
+ return 0;
369
+ }
370
+ return offset;
371
+ }
372
+ /** Record that everything before `offset` in the file `identity` is consumed. */
373
+ advance(name, offset, identity) {
374
+ const tail = this.store.readWithFacts(name, { offset: Math.max(0, offset - 64), maxBytes: Math.min(64, offset), identity: true });
375
+ if (!tail.ok || tail.value.facts.fileIdentity !== identity)
376
+ return false;
377
+ const next = { offset, identity, boundary: sha256(tail.value.data),
378
+ ...(this.cursor.rotatedAt !== undefined ? { rotatedAt: this.cursor.rotatedAt } : {}) };
379
+ if (!this.store.writeAtomic(CURSOR, JSON.stringify(next)).ok)
380
+ return false;
381
+ this.cursor = next;
382
+ this.done += 1;
383
+ return true;
384
+ }
385
+ async drainFile(name, offset) {
386
+ for (;;) {
387
+ if (this.done >= STOP_JOB_PASS_LIMIT)
388
+ return "stopped";
389
+ const read = this.store.readWithFacts(name, { maxBytes: WINDOW, offset, identity: true });
390
+ if (!read.ok) {
391
+ if (read.code !== "missing")
392
+ this.log(`Stop queue read refused: ${read.code}`);
393
+ return "stopped";
394
+ }
395
+ const identity = read.value.facts.fileIdentity;
396
+ const data = read.value.data;
397
+ if (data.length === 0)
398
+ return "eof";
399
+ let end = data.indexOf(10);
400
+ if (end < 0) {
401
+ // Shorter than a window: an in-flight append, wait for its line.
402
+ if (data.length < WINDOW)
403
+ return "partial";
404
+ // No producer line is this long: skip to the end of this record.
405
+ const next = this.newlineFrom(name, offset + WINDOW, identity);
406
+ if (next === undefined)
407
+ return "partial";
408
+ this.log("Stop queue record exceeds its line limit; skipped");
409
+ if (!this.advance(name, next + 1, identity))
410
+ return "stopped";
411
+ offset = next + 1;
412
+ continue;
413
+ }
414
+ let position = 0;
415
+ while (end >= 0) {
416
+ if (this.done >= STOP_JOB_PASS_LIMIT)
417
+ return "stopped";
418
+ if (!this.options.ownsQueue()) {
419
+ this.log("Stop queue lease was lost; queue retained");
420
+ return "stopped";
421
+ }
422
+ if (!await this.consume(data.subarray(position, end)))
423
+ return "stopped";
424
+ position = end + 1;
425
+ if (!this.advance(name, offset + position, identity))
426
+ return "stopped";
427
+ end = data.indexOf(10, position);
428
+ }
429
+ offset += position;
430
+ }
431
+ }
432
+ /** The offset of the next newline at or after `from`, or undefined before the end of the file. */
433
+ newlineFrom(name, from, identity) {
434
+ for (let offset = from;;) {
435
+ const read = this.store.readWithFacts(name, { maxBytes: WINDOW, offset, identity: true });
436
+ if (!read.ok || read.value.facts.fileIdentity !== identity || read.value.data.length === 0)
437
+ return undefined;
438
+ const at = read.value.data.indexOf(10);
439
+ if (at >= 0)
440
+ return offset + at;
441
+ offset += read.value.data.length;
442
+ }
443
+ }
444
+ /** Handle one line. False stops the pass with the cursor before the line. */
445
+ async consume(bytes) {
446
+ let line;
447
+ try {
448
+ line = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
449
+ }
450
+ catch {
451
+ this.log("Stop queue record is not UTF-8; skipped");
452
+ return true;
453
+ }
454
+ const job = parseStopJob(line, this.options.home);
455
+ const digest = sha256(line);
456
+ const receipt = `stop-job-${digest}.json`;
457
+ const write = (value) => this.store.writeAtomic(receipt, JSON.stringify({ ...value, digest })).ok;
458
+ const previous = this.store.readWithFacts(receipt, { maxBytes: 4096 });
459
+ let attempt = 1;
460
+ if (previous.ok) {
461
+ let state;
462
+ try {
463
+ state = record(JSON.parse(previous.value.data.toString()));
464
+ }
465
+ catch {
466
+ state = undefined;
467
+ }
468
+ const status = state?.status;
469
+ if (status === "finished" || status === "rejected" || status === "expired" || status === "abandoned")
470
+ return true;
471
+ if (status === "started") {
472
+ if (job && this.options.completed?.(job))
473
+ return write({ status: "finished", id: job.id, code: 0, recovered: true });
474
+ if (!this.startedIsStale(state, previous.value.facts.mtimeMs)) {
475
+ this.log(`Stop job ${job?.id ?? "invalid"} may still be running; waiting`);
476
+ return false;
477
+ }
478
+ attempt = (Number.isSafeInteger(state.attempt) ? state.attempt : 1) + 1;
479
+ }
480
+ else {
481
+ // An unreadable receipt cannot say whether the job ran: count it as one interrupted run.
482
+ this.log(`Stop job ${job?.id ?? "invalid"} receipt is unreadable; treating it as interrupted`);
483
+ attempt = 2;
484
+ }
485
+ if (job && attempt > MAX_ATTEMPTS) {
486
+ if (!write({ status: "abandoned", id: job.id, attempts: attempt - 1 }))
487
+ return false;
488
+ this.log(`Stop job ${job.id} was interrupted ${attempt - 1} times; skipped`);
489
+ return true;
490
+ }
491
+ if (job)
492
+ this.log(`Stop job ${job.id} was interrupted; running it again (attempt ${attempt})`);
493
+ }
494
+ else if (previous.code !== "missing") {
495
+ // A receipt that cannot be read safely cannot be written either: never run without a receipt.
496
+ this.log(`Stop job receipt refused (${previous.code}); record skipped without running`);
497
+ return true;
498
+ }
499
+ if (!job) {
500
+ if (!write({ status: "rejected" }))
501
+ return false;
502
+ this.log("Stop queue record rejected; no operation executed");
503
+ return true;
504
+ }
505
+ const queuedAt = this.queuedAt(line);
506
+ if (queuedAt !== undefined && this.now() - queuedAt > STOP_JOB_RETENTION_MS) {
507
+ if (!write({ status: "expired", id: job.id }))
508
+ return false;
509
+ this.log(`Stop job ${job.id} is older than the receipt retention; skipped`);
510
+ return true;
511
+ }
512
+ if (!write({ status: "started", id: job.id, pid: process.pid, startedAt: this.now(), attempt }))
513
+ return false;
514
+ let result;
515
+ try {
516
+ result = await this.options.execute(job);
517
+ }
518
+ catch {
519
+ result = { code: 1, detail: "operation failed" };
520
+ }
521
+ if (!write({ status: "finished", id: job.id, code: result.code }))
522
+ return false;
523
+ if (result.code !== 0)
524
+ this.log(`Stop job ${job.id} failed (${result.code})`);
525
+ return true;
526
+ }
527
+ /** Whether no job can still be running behind a `started` receipt. */
528
+ startedIsStale(state, mtimeMs) {
529
+ const pid = state.pid;
530
+ // This daemon runs one job at a time and holds the queue while it does:
531
+ // its own receipt is from a pass that stopped before writing the result.
532
+ if (pid === process.pid)
533
+ return true;
534
+ const startedAt = typeof state.startedAt === "number" && Number.isFinite(state.startedAt) ? state.startedAt : mtimeMs;
535
+ if (this.now() - startedAt >= STOP_JOB_STALE_MS)
536
+ return true;
537
+ if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid <= 0)
538
+ return false;
539
+ const alive = this.options.alive ?? ((value) => {
540
+ try {
541
+ process.kill(value, 0);
542
+ return true;
543
+ }
544
+ catch (error) {
545
+ return error.code === "ESRCH" ? false : undefined;
546
+ }
547
+ });
548
+ return alive(pid) === false;
549
+ }
550
+ /** The producer's `at` time, when the line has one. */
551
+ queuedAt(line) {
552
+ try {
553
+ const at = record(JSON.parse(line))?.at;
554
+ const time = typeof at === "string" ? Date.parse(at) : NaN;
555
+ return Number.isFinite(time) ? time : undefined;
556
+ }
557
+ catch {
558
+ return undefined;
559
+ }
560
+ }
561
+ }
562
+ /** Remove settled receipts older than `olderThan`. Bounded per call; a `started` receipt is never removed. */
563
+ function pruneReceipts(store, olderThan) {
564
+ const names = store.nameCursor();
565
+ if (!names.ok)
566
+ return;
567
+ try {
568
+ let scanned = 0;
569
+ while (scanned < PRUNE_SCAN_LIMIT) {
570
+ const batch = names.value.read(256);
571
+ if (!batch.ok)
572
+ return;
573
+ for (const name of batch.value.names) {
574
+ scanned += 1;
575
+ if (!RECEIPT_NAME.test(name))
576
+ continue;
577
+ const read = store.readWithFacts(name, { maxBytes: 4096 });
578
+ if (!read.ok || read.value.facts.mtimeMs >= olderThan)
579
+ continue;
580
+ let status;
581
+ try {
582
+ status = record(JSON.parse(read.value.data.toString()))?.status;
583
+ }
584
+ catch {
585
+ status = undefined;
586
+ }
587
+ if (status === "started")
588
+ continue;
589
+ store.remove(name);
590
+ }
591
+ if (batch.value.done)
592
+ return;
593
+ }
594
+ }
595
+ finally {
596
+ names.value.close();
597
+ }
598
+ }
599
+ //# sourceMappingURL=stop-jobs.js.map
@@ -109,7 +109,7 @@ export function fleetHookCoreResults(home, env, inspect = (engine, host) => insp
109
109
  if (missing === null || missing.length)
110
110
  problems.push(`${event}: required evaluators are missing`);
111
111
  if (canonical) {
112
- const left = uncoveredHooks(value('--hq-root'), host, canonical, caps.covers);
112
+ const left = uncoveredHooks(value('--hq-root'), host, canonical, caps.covers, env);
113
113
  if (left.length)
114
114
  problems.push(`${event}: uncovered hooks: ${left.join(', ')}`);
115
115
  }
@@ -139,7 +139,7 @@ export function hostCoreResults(root, options = {}) {
139
139
  return { status: 'PASS', reason: `the new core has ${REQUIRED_EVALUATORS[event].join(', ')}` };
140
140
  };
141
141
  /** Old-dispatcher hooks for `event` on `host` that the engine's report does not cover. */
142
- const uncovered = (caps, host, event) => uncoveredHooks(root, host, event, caps.covers);
142
+ const uncovered = (caps, host, event) => uncoveredHooks(root, host, event, caps.covers, env);
143
143
  const listed = (hooks) => (hooks.length > 6 ? `${hooks.slice(0, 6).join(', ')} and ${hooks.length - 6} more` : hooks.join(', '));
144
144
  const oldCore = (event, host) => {
145
145
  if (!flagOn)