@indigoai-us/hq-cli 5.345.220 → 5.345.221

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 +118 -0
  2. package/dist/command-catalog.generated.d.ts +144 -2
  3. package/dist/command-catalog.generated.js +175 -2
  4. package/dist/commands/auth.js +4 -1
  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-stop-autosave.d.ts +21 -0
  10. package/dist/commands/core-stop-autosave.js +300 -0
  11. package/dist/commands/core.js +2 -0
  12. package/dist/commands/daemon.d.ts +5 -0
  13. package/dist/commands/daemon.js +31 -7
  14. package/dist/commands/doctor-usage.d.ts +5 -0
  15. package/dist/commands/doctor-usage.js +25 -0
  16. package/dist/commands/env.d.ts +49 -4
  17. package/dist/commands/env.js +355 -5
  18. package/dist/commands/lanes-shared.d.ts +3 -0
  19. package/dist/commands/lanes.d.ts +3 -0
  20. package/dist/commands/lanes.js +87 -3
  21. package/dist/commands/sources.js +3 -3
  22. package/dist/commands/sync-core.d.ts +1 -0
  23. package/dist/commands/sync-core.js +77 -3
  24. package/dist/commands/whoami.js +96 -80
  25. package/dist/lib/bot/config.d.ts +17 -0
  26. package/dist/lib/bot/config.js +13 -0
  27. package/dist/lib/bot/fleet-cron.js +24 -2
  28. package/dist/lib/bot/fleet-local.d.ts +30 -2
  29. package/dist/lib/bot/fleet-local.js +60 -1
  30. package/dist/lib/bot/grok-login-scope.d.ts +36 -0
  31. package/dist/lib/bot/grok-login-scope.js +93 -0
  32. package/dist/lib/bot/legacy-provider-login.d.ts +32 -9
  33. package/dist/lib/bot/legacy-provider-login.js +28 -22
  34. package/dist/lib/bot/runtime-sign-in-check.js +6 -1
  35. package/dist/lib/bot/runtime-sign-in.d.ts +2 -0
  36. package/dist/lib/core-utils/sentry-report.js +2 -0
  37. package/dist/lib/daemon/machine-checks.d.ts +22 -1
  38. package/dist/lib/daemon/machine-checks.js +54 -12
  39. package/dist/lib/daemon/run.js +66 -8
  40. package/dist/lib/daemon/stop-autosave-lock.d.ts +19 -0
  41. package/dist/lib/daemon/stop-autosave-lock.js +166 -0
  42. package/dist/lib/daemon/stop-autosave.d.ts +28 -0
  43. package/dist/lib/daemon/stop-autosave.js +111 -0
  44. package/dist/lib/daemon/stop-diagnostics.d.ts +11 -0
  45. package/dist/lib/daemon/stop-diagnostics.js +136 -0
  46. package/dist/lib/daemon/stop-job-executor.d.ts +19 -0
  47. package/dist/lib/daemon/stop-job-executor.js +126 -0
  48. package/dist/lib/daemon/stop-jobs.d.ts +93 -0
  49. package/dist/lib/daemon/stop-jobs.js +599 -0
  50. package/dist/lib/doctor/checks/fleet-hook-core.js +1 -1
  51. package/dist/lib/doctor/checks/host-core.js +1 -1
  52. package/dist/lib/environment/access-probes.d.ts +234 -0
  53. package/dist/lib/environment/access-probes.js +918 -0
  54. package/dist/lib/environment/profile.d.ts +15 -2
  55. package/dist/lib/environment/profile.js +55 -20
  56. package/dist/lib/environment/rfc3339.d.ts +8 -0
  57. package/dist/lib/environment/rfc3339.js +26 -0
  58. package/dist/lib/environment/work-requirements.d.ts +169 -0
  59. package/dist/lib/environment/work-requirements.js +389 -0
  60. package/dist/lib/hook-engine/coverage.d.ts +137 -7
  61. package/dist/lib/hook-engine/coverage.js +1424 -4
  62. package/dist/lib/hook-engine/fleet-registration.js +2 -2
  63. package/dist/lib/hook-engine/git-stop-config.json +513 -0
  64. package/dist/lib/hook-engine/native-stop-compatibility.json +311 -0
  65. package/dist/lib/hook-engine/reconcile.js +2 -2
  66. package/dist/lib/hot-channels/alert.d.ts +2 -2
  67. package/dist/lib/hot-channels/alert.js +8 -5
  68. package/dist/lib/hot-channels/signals-pass.d.ts +126 -17
  69. package/dist/lib/hot-channels/signals-pass.js +296 -17
  70. package/dist/lib/hot-channels/signals-runtime.d.ts +30 -0
  71. package/dist/lib/hot-channels/signals-runtime.js +82 -0
  72. package/dist/lib/install/hook-target.js +1 -1
  73. package/dist/lib/lanes/host-capacity.d.ts +26 -2
  74. package/dist/lib/lanes/host-capacity.js +17 -2
  75. package/dist/lib/lanes/host-compute.d.ts +90 -0
  76. package/dist/lib/lanes/host-compute.js +185 -0
  77. package/dist/lib/lanes/index.d.ts +2 -0
  78. package/dist/lib/lanes/index.js +1 -0
  79. package/dist/lib/lanes/reconcile.js +22 -1
  80. package/dist/lib/lanes/resource-usage.d.ts +155 -0
  81. package/dist/lib/lanes/resource-usage.js +589 -0
  82. package/dist/lib/lanes/run-size.d.ts +46 -0
  83. package/dist/lib/lanes/run-size.js +197 -0
  84. package/dist/lib/lanes/store.js +27 -0
  85. package/dist/lib/lanes/throttle.d.ts +36 -1
  86. package/dist/lib/lanes/throttle.js +47 -10
  87. package/dist/lib/lanes/types.d.ts +40 -0
  88. package/dist/lib/lanes/types.js +2 -2
  89. package/dist/lib/lanes/watcher.js +13 -4
  90. package/dist/lib/lanes/worker-process.d.ts +25 -2
  91. package/dist/lib/lanes/worker-process.js +71 -19
  92. package/dist/lib/placement/match.d.ts +192 -0
  93. package/dist/lib/placement/match.js +667 -0
  94. package/dist/lib/safe-store.d.ts +14 -0
  95. package/dist/lib/safe-store.js +77 -4
  96. package/dist/lib/search-index/index.d.ts +88 -4
  97. package/dist/lib/search-index/index.js +288 -24
  98. package/dist/lib/search-index/max-doc-bytes.d.ts +17 -6
  99. package/dist/lib/search-index/max-doc-bytes.js +48 -23
  100. package/dist/lib/signals/codex-lockdown.d.ts +79 -0
  101. package/dist/lib/signals/codex-lockdown.js +271 -0
  102. package/dist/lib/signals/codex-login.d.ts +37 -0
  103. package/dist/lib/signals/codex-login.js +83 -0
  104. package/dist/lib/signals/engine.d.ts +27 -0
  105. package/dist/lib/signals/engine.js +70 -0
  106. package/dist/lib/signals/reply.js +22 -1
  107. package/dist/lib/signals/run-record.js +6 -1
  108. package/dist/lib/signals/settings.d.ts +5 -0
  109. package/dist/lib/signals/settings.js +2 -0
  110. package/dist/lib/signals/steps/extract.d.ts +85 -9
  111. package/dist/lib/signals/steps/extract.js +317 -68
  112. package/dist/lib/signals/steps/types.d.ts +2 -0
  113. package/dist/lib/sync-core/engine-home.d.ts +35 -1
  114. package/dist/lib/sync-core/engine-home.js +119 -16
  115. package/dist/lib/sync-core/rollout-state.d.ts +2 -1
  116. package/dist/lib/sync-core/rollout-state.js +5 -2
  117. package/dist/lib/sync-core/vault-uid.d.ts +2 -0
  118. package/dist/lib/sync-core/vault-uid.js +4 -0
  119. package/dist/schemas/hq-work-requirements.v1.schema.json +145 -0
  120. package/dist/utils/auth-session-check.d.ts +16 -0
  121. package/dist/utils/auth-session-check.js +16 -0
  122. package/dist/utils/client-health-contract.d.ts +6 -0
  123. package/dist/utils/client-health-contract.js +13 -0
  124. package/dist/utils/client-health.d.ts +7 -0
  125. package/dist/utils/client-health.js +22 -1
  126. package/dist/utils/command-usage.d.ts +40 -0
  127. package/dist/utils/command-usage.js +61 -0
  128. package/dist/utils/duplicate-command-usage.d.ts +72 -0
  129. package/dist/utils/duplicate-command-usage.js +125 -0
  130. package/dist/utils/host-registration.js +2 -1
  131. package/dist/utils/resident-package-preload.js +4 -0
  132. package/dist/utils/sentry-fingerprint.js +9 -0
  133. package/dist/utils/windows-bash.d.ts +2 -0
  134. package/dist/utils/windows-bash.js +2 -1
  135. package/package.json +9 -8
  136. package/scripts/bench-core-compare.mjs +313 -0
  137. package/scripts/bench-core.mjs +399 -12
  138. package/scripts/check-function-manifest.mjs +116 -3
@@ -20,6 +20,14 @@
20
20
  * it gains no access it did not have; the check keeps a link, a hardlink, a
21
21
  * file of another user or a writable file from being run by mistake.
22
22
  *
23
+ * On Windows (only `hq doctor --only machine-checks` runs there; the daemon
24
+ * schedule skips Windows) each script is run with the trusted Git Bash that
25
+ * src/utils/windows-bash.ts resolves, never System32\bash.exe (WSL) or a
26
+ * WindowsApps alias. With no trusted Git Bash every check is `unknown` and
27
+ * nothing is run. The store read rules there are safe-store's Windows rules:
28
+ * a real folder (not a symlink or junction) and a regular single-link file
29
+ * that is not a symlink; Windows has no POSIX owner or mode bits to check.
30
+ *
23
31
  * Results can name local paths, so they are written only to the daemon's
24
32
  * private folder (machine-checks.json, mode 0600) and the state file, and are
25
33
  * never logged or sent.
@@ -30,6 +38,7 @@ import * as fs from "node:fs";
30
38
  import * as path from "node:path";
31
39
  import { coreNextEnabled } from "../../utils/core-next-flag.js";
32
40
  import { coreNextKillReason } from "../../utils/core-next-kill.js";
41
+ import { isExcludedWindowsBash, resolveWindowsBash } from "../../utils/windows-bash.js";
33
42
  import { anyNativeSessionStartRegistered } from "./machine-check-registration.js";
34
43
  import { openStoreDir } from "../safe-store.js";
35
44
  import { readStoreFile, writeStoreFile } from "./paths.js";
@@ -61,6 +70,33 @@ export const MACHINE_CHECK_DRAIN_MS = 50;
61
70
  const SESSION_ID = "hq-machine-checks";
62
71
  const FINGERPRINT = /^[0-9a-f]{64}$/;
63
72
  const STATUSES = new Set(["ok", "warn", "fail", "unknown"]);
73
+ /** The summary of every check on Windows when no trusted Git Bash is found. */
74
+ export const MACHINE_CHECK_NO_GIT_BASH = "not run: Git Bash was not found (set CLAUDE_CODE_GIT_BASH_PATH or install Git for Windows)";
75
+ function defaultResolveBash(env) {
76
+ return resolveWindowsBash(env).executable;
77
+ }
78
+ /**
79
+ * The shell that runs every script: /bin/bash off Windows; on Windows the
80
+ * trusted Git Bash, or undefined when none is found. A resolver answer that
81
+ * windows-bash.ts excludes (System32\bash.exe, a WindowsApps alias) or that
82
+ * is not an absolute path counts as none.
83
+ */
84
+ export function machineCheckShell(platform, env, resolveBash = defaultResolveBash) {
85
+ if (platform !== "win32")
86
+ return "/bin/bash";
87
+ let bash;
88
+ try {
89
+ bash = resolveBash(env);
90
+ }
91
+ catch {
92
+ return undefined;
93
+ }
94
+ if (!bash || isExcludedWindowsBash(bash, env))
95
+ return undefined;
96
+ if (!path.win32.isAbsolute(bash) && !path.posix.isAbsolute(bash))
97
+ return undefined;
98
+ return bash;
99
+ }
64
100
  /** The finding text a script's stdout carries: empty means nothing to report. */
65
101
  export function findingText(stdout) {
66
102
  const trimmed = stdout.trim();
@@ -116,12 +152,12 @@ function disabledIds(env) {
116
152
  return new Set((env.HQ_DISABLED_HOOKS ?? "").split(",").map((id) => id.trim()).filter(Boolean));
117
153
  }
118
154
  /** The script's absolute path when it may be run; else why not. */
119
- export function checkMachineCheckScript(hqRoot, relative) {
155
+ export function checkMachineCheckScript(hqRoot, relative, platform = process.platform) {
120
156
  const root = path.resolve(hqRoot);
121
157
  const file = path.resolve(root, ...relative.split("/"));
122
158
  if (!file.startsWith(root + path.sep))
123
159
  return { ok: false, summary: "refused: outside-root" };
124
- const opened = openStoreDir(path.dirname(file));
160
+ const opened = openStoreDir(path.dirname(file), platform === process.platform ? {} : { platform });
125
161
  if (!opened.ok) {
126
162
  return { ok: false, summary: opened.code === "folder-missing" ? "not installed" : `refused: ${opened.code}` };
127
163
  }
@@ -154,18 +190,21 @@ function payload(event, hqRoot) {
154
190
  : JSON.stringify({ hook_event_name: "UserPromptSubmit", prompt: "", session_id: SESSION_ID, cwd: hqRoot });
155
191
  }
156
192
  /**
157
- * `/bin/bash <file>` with the payload on stdin. Waits for the direct child's
158
- * exit, not for stdout to close, so a detached grandchild holding stdout open
159
- * does not delay the result. A timeout sends SIGTERM and then SIGKILL to the
160
- * direct child only, never to its process group.
193
+ * `<shell> <file>` with the payload on stdin (shell: /bin/bash, or Git Bash
194
+ * on Windows). Waits for the direct child's exit, not for stdout to close, so
195
+ * a detached grandchild holding stdout open does not delay the result. A
196
+ * timeout sends SIGTERM and then SIGKILL to the direct child only, never to
197
+ * its process group. On Windows Node ends the direct child with
198
+ * TerminateProcess for either signal (there are no POSIX process groups), so
199
+ * the first kill already ends it and the second is a no-op.
161
200
  */
162
- function runScript(file, spec, hqRoot, env, killGraceMs, drainMs) {
201
+ function runScript(shell, file, spec, hqRoot, env, killGraceMs, drainMs) {
163
202
  return new Promise((resolve) => {
164
203
  const chunks = [];
165
204
  let kept = 0;
166
205
  let child;
167
206
  try {
168
- child = spawn("/bin/bash", [file], {
207
+ child = spawn(shell, [file], {
169
208
  cwd: hqRoot,
170
209
  env: {
171
210
  ...env,
@@ -219,15 +258,17 @@ function runScript(file, spec, hqRoot, env, killGraceMs, drainMs) {
219
258
  child.stdin?.end(payload(spec.event, hqRoot));
220
259
  });
221
260
  }
222
- async function runOne(spec, options, env, disabled) {
261
+ async function runOne(spec, options, env, disabled, shell) {
223
262
  const now = options.now ?? (() => new Date());
224
263
  const at = () => now().toISOString();
225
264
  if (disabled.has(spec.id))
226
265
  return { id: spec.id, status: "ok", checked_at: at(), summary: "disabled by HQ_DISABLED_HOOKS" };
227
- const checked = checkMachineCheckScript(options.hqRoot, spec.path);
266
+ if (shell === undefined)
267
+ return { id: spec.id, status: "unknown", checked_at: at(), summary: MACHINE_CHECK_NO_GIT_BASH };
268
+ const checked = checkMachineCheckScript(options.hqRoot, spec.path, options.platform ?? process.platform);
228
269
  if (!checked.ok)
229
270
  return { id: spec.id, status: "unknown", checked_at: at(), summary: checked.summary };
230
- const run = await runScript(checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS);
271
+ const run = await runScript(shell, checked.file, spec, path.resolve(options.hqRoot), env, options.killGraceMs ?? MACHINE_CHECK_KILL_GRACE_MS, options.drainMs ?? MACHINE_CHECK_DRAIN_MS);
231
272
  if (run.outcome === "timed-out") {
232
273
  return { id: spec.id, status: "unknown", checked_at: at(), summary: `timed out after ${Math.round(spec.timeoutMs / 1000)}s` };
233
274
  }
@@ -253,9 +294,10 @@ export function runMachineChecks(options) {
253
294
  return inFlight;
254
295
  const batch = (async () => {
255
296
  const disabled = disabledIds(env);
297
+ const shell = machineCheckShell(options.platform ?? process.platform, env, options.resolveBash);
256
298
  const results = [];
257
299
  for (const spec of options.checks ?? MACHINE_CHECKS) {
258
- results.push(await runOne(spec, options, env, disabled));
300
+ results.push(await runOne(spec, options, env, disabled, shell));
259
301
  }
260
302
  if (options.resultsFile)
261
303
  writeMachineCheckResults(options.resultsFile, results, options.resultsWrite);
@@ -68,6 +68,9 @@ import { userToolDirs } from "./tools.js";
68
68
  import { logOffset, readLogSince, readUnitHolds, writeUnitHolds } from "./unit-holds.js";
69
69
  import { createTccEpermGuard, TCC_EPERM_SENTRY_FINGERPRINT } from "./tcc-eperm.js";
70
70
  import { daemonRunGuard } from "./lanes-reconcile-guard.js";
71
+ import { startStopJobDrainer } from "./stop-jobs.js";
72
+ import { executeStopJob, pruneStopJobResults, stopJobCompleted } from "./stop-job-executor.js";
73
+ import { closeStopDiagnosticCursor, drainStopDiagnostics } from "./stop-diagnostics.js";
71
74
  export const LOG_ROTATE_BYTES = 5 * 1024 * 1024;
72
75
  /** Exit code for "restart me": non-zero so every service manager relaunches (Windows tasks only restart on failure). */
73
76
  export const RESTART_EXIT_CODE = 75;
@@ -977,7 +980,53 @@ export async function runDaemon(opts) {
977
980
  laneReconcileHandlerLoadInFlight = false;
978
981
  });
979
982
  };
983
+ const stopJobAbort = new AbortController();
984
+ const ownsStopQueue = () => path.resolve(paths.root) === path.resolve(home, ".hq/daemon")
985
+ && readPidLock(paths.lockPath)?.pid === process.pid;
986
+ let stopDiagnosticsRunning = false;
987
+ let stopDiagnosticRoot;
988
+ const stopDiagnosticTimer = setInterval(() => {
989
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
990
+ if (stopDiagnosticRoot && (root !== stopDiagnosticRoot || !ownsStopQueue())) {
991
+ closeStopDiagnosticCursor(stopDiagnosticRoot);
992
+ stopDiagnosticRoot = undefined;
993
+ }
994
+ if (!root || stopDiagnosticsRunning || !ownsStopQueue())
995
+ return;
996
+ stopDiagnosticRoot = root;
997
+ stopDiagnosticsRunning = true;
998
+ void drainStopDiagnostics({ root, ownsQueue: ownsStopQueue, log: message => log("warn", message) })
999
+ .catch(error => log("warn", `Stop diagnostic drain failed: ${String(error)}`))
1000
+ .finally(() => { stopDiagnosticsRunning = false; });
1001
+ }, 5000);
1002
+ stopDiagnosticTimer.unref();
1003
+ const stopJobDrainer = startStopJobDrainer({
1004
+ home,
1005
+ ownsQueue: ownsStopQueue,
1006
+ completed: job => {
1007
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
1008
+ return root !== undefined && stopJobCompleted(job, root);
1009
+ },
1010
+ pruneResults: olderThan => {
1011
+ const root = readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT;
1012
+ if (root)
1013
+ pruneStopJobResults(root, olderThan);
1014
+ },
1015
+ execute: job => executeStopJob(job, {
1016
+ nodeBinary: opts.nodeBinary,
1017
+ hqBinary: opts.hqBinary,
1018
+ allowedRoot: readDaemonConfig(paths.configPath).hqRoot ?? env.HQ_ROOT,
1019
+ signal: stopJobAbort.signal,
1020
+ }),
1021
+ log: message => log("warn", message),
1022
+ });
1023
+ /** Closes the watchers; the promise settles once the Stop job in progress (if any) has written its receipt. */
980
1024
  const closeRuntimeWatchers = () => {
1025
+ if (stopDiagnosticRoot)
1026
+ closeStopDiagnosticCursor(stopDiagnosticRoot);
1027
+ clearInterval(stopDiagnosticTimer);
1028
+ stopJobAbort.abort();
1029
+ const stopJobsClosed = stopJobDrainer.close().catch((err) => log("warn", `Stop job drainer did not close cleanly: ${String(err)}`));
981
1030
  laneReconcileWatcher?.close();
982
1031
  laneReconcileWatcher = null;
983
1032
  laneReconcileWatcherRoot = null;
@@ -985,6 +1034,7 @@ export async function runDaemon(opts) {
985
1034
  machineChecks.close();
986
1035
  flagSnapshots.close();
987
1036
  stateWriter.close();
1037
+ return stopJobsClosed;
988
1038
  };
989
1039
  const plan = () => {
990
1040
  const config = readDaemonConfig(paths.configPath);
@@ -1554,14 +1604,15 @@ export async function runDaemon(opts) {
1554
1604
  tccEpermGuard.dispose();
1555
1605
  log("info", `${why}; stopping services`);
1556
1606
  closeHqd();
1557
- closeRuntimeWatchers();
1607
+ // The aborted Stop job's receipt is written before the lease is released.
1608
+ const stopJobsClosed = closeRuntimeWatchers();
1558
1609
  // Keep shutdown bounded, but let a stopping sync runner reach its persist deadline.
1559
1610
  const cap = createShutdownCap();
1560
1611
  extendSyncShutdownCap = cap.extendForSyncRunnerPersist;
1561
1612
  if (supervisor.hasStoppingSyncRunner())
1562
1613
  cap.extendForSyncRunnerPersist();
1563
1614
  const servicesStopped = supervisor.stop();
1564
- void Promise.race([servicesStopped, cap.promise]).then((result) => {
1615
+ void Promise.race([Promise.all([servicesStopped, stopJobsClosed]).then(([result]) => result), cap.promise]).then((result) => {
1565
1616
  cap.clear();
1566
1617
  extendSyncShutdownCap = undefined;
1567
1618
  if (result === "timeout")
@@ -1584,7 +1635,7 @@ export async function runDaemon(opts) {
1584
1635
  daemonStopping = true;
1585
1636
  tccEpermGuard.dispose();
1586
1637
  closeHqd();
1587
- closeRuntimeWatchers();
1638
+ const stopJobsClosed = closeRuntimeWatchers();
1588
1639
  const released = supervisor.release();
1589
1640
  // What these readers have not read stays in the FIFO for the next daemon.
1590
1641
  for (const tail of protocolTails)
@@ -1616,10 +1667,17 @@ export async function runDaemon(opts) {
1616
1667
  // The released processes must not keep this one alive.
1617
1668
  for (const child of spawned)
1618
1669
  child.unref();
1619
- releaseDaemonLock(paths.lockPath);
1620
- resolve(RESTART_EXIT_CODE);
1621
- // Anything else still holding the event loop open must not delay the restart.
1622
- setTimeout(() => process.exit(RESTART_EXIT_CODE), 5_000).unref();
1670
+ // The aborted Stop job's receipt is written before the lease is released
1671
+ // (bounded: the job's child is already signalled).
1672
+ let handOverTimer;
1673
+ void Promise.race([stopJobsClosed, new Promise((done) => { handOverTimer = setTimeout(done, 3_000); handOverTimer.unref(); })]).then(() => {
1674
+ if (handOverTimer)
1675
+ clearTimeout(handOverTimer);
1676
+ releaseDaemonLock(paths.lockPath);
1677
+ resolve(RESTART_EXIT_CODE);
1678
+ // Anything else still holding the event loop open must not delay the restart.
1679
+ setTimeout(() => process.exit(RESTART_EXIT_CODE), 5_000).unref();
1680
+ });
1623
1681
  };
1624
1682
  restartDaemon = () => {
1625
1683
  if (!restartsForParent(opts)) {
@@ -1654,7 +1712,7 @@ export async function runDaemon(opts) {
1654
1712
  catch (err) {
1655
1713
  log("error", `supervisor failed to start: ${err.message}`);
1656
1714
  closeHqd();
1657
- closeRuntimeWatchers();
1715
+ void closeRuntimeWatchers();
1658
1716
  releaseDaemonLock(paths.lockPath);
1659
1717
  resolve(1);
1660
1718
  }
@@ -0,0 +1,19 @@
1
+ /** Why the folder that holds lock `directory` cannot hold it, or undefined.
2
+ * The folder is resolved first (macOS /tmp is a link to /private/tmp) and must
3
+ * be owned by this user or root and closed to group and other writes, unless
4
+ * it is a root-owned sticky folder such as /tmp: there another user cannot
5
+ * remove or rename this user's lock, and the lock folder itself is checked as
6
+ * a private store before it is used. A store check of the parent itself would
7
+ * refuse /tmp (owned by root, world-writable), which made autosave skip every
8
+ * file on Linux without TMPDIR.
9
+ */
10
+ export declare function lockParentRefusal(directory: string): string | undefined;
11
+ /** Recover only an old, private autosave lock whose owner is definitely gone.
12
+ * Live or unreadable process identity stays held. The renamed directory is
13
+ * checked against the original inode before anything inside it is removed.
14
+ */
15
+ export declare function acquireAutosaveLock(directory: string, now: number, staleMinutes: number, alive?: (pid: number) => boolean | undefined, birth?: (pid: number) => string | undefined): {
16
+ recovered: boolean;
17
+ release(): void;
18
+ } | undefined;
19
+ //# sourceMappingURL=stop-autosave-lock.d.ts.map
@@ -0,0 +1,166 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { randomUUID } from "node:crypto";
4
+ import { spawnSync } from "node:child_process";
5
+ import { openStoreDir, parentStatRefusal } from "../safe-store.js";
6
+ function birthToken(pid) {
7
+ if (!Number.isSafeInteger(pid) || pid <= 0 || !fs.existsSync("/bin/ps"))
8
+ return undefined;
9
+ const result = spawnSync("/bin/ps", ["-p", String(pid), "-o", "lstart="], {
10
+ env: { PATH: "/usr/bin:/bin", LC_ALL: "C" }, encoding: "utf8", timeout: 1000, maxBuffer: 4096,
11
+ });
12
+ if (result.error || result.status !== 0)
13
+ return undefined;
14
+ return result.stdout.replace(/\s/g, "") || undefined;
15
+ }
16
+ /** Why the folder that holds lock `directory` cannot hold it, or undefined.
17
+ * The folder is resolved first (macOS /tmp is a link to /private/tmp) and must
18
+ * be owned by this user or root and closed to group and other writes, unless
19
+ * it is a root-owned sticky folder such as /tmp: there another user cannot
20
+ * remove or rename this user's lock, and the lock folder itself is checked as
21
+ * a private store before it is used. A store check of the parent itself would
22
+ * refuse /tmp (owned by root, world-writable), which made autosave skip every
23
+ * file on Linux without TMPDIR.
24
+ */
25
+ export function lockParentRefusal(directory) {
26
+ let real;
27
+ try {
28
+ real = fs.realpathSync(path.dirname(directory));
29
+ }
30
+ catch (error) {
31
+ return `lock folder unavailable (${error.code ?? "error"})`;
32
+ }
33
+ let stat;
34
+ try {
35
+ stat = fs.lstatSync(real);
36
+ }
37
+ catch {
38
+ return "lock folder unavailable";
39
+ }
40
+ if (!stat.isDirectory())
41
+ return "lock folder is not a folder";
42
+ if (process.platform === "win32" || typeof process.getuid !== "function")
43
+ return undefined;
44
+ const refused = parentStatRefusal(stat, process.getuid());
45
+ return refused ? `lock folder refused (${refused.message})` : undefined;
46
+ }
47
+ /** Recover only an old, private autosave lock whose owner is definitely gone.
48
+ * Live or unreadable process identity stays held. The renamed directory is
49
+ * checked against the original inode before anything inside it is removed.
50
+ */
51
+ export function acquireAutosaveLock(directory, now, staleMinutes, alive = pid => {
52
+ try {
53
+ process.kill(pid, 0);
54
+ return true;
55
+ }
56
+ catch (error) {
57
+ return error.code === "ESRCH" ? false : undefined;
58
+ }
59
+ }, birth = birthToken) {
60
+ let recovered = false;
61
+ if (lockParentRefusal(directory) !== undefined)
62
+ return undefined;
63
+ try {
64
+ fs.mkdirSync(directory, { mode: 0o700 });
65
+ }
66
+ catch (error) {
67
+ if (error.code !== "EEXIST")
68
+ return undefined;
69
+ let before;
70
+ try {
71
+ before = fs.lstatSync(directory);
72
+ }
73
+ catch {
74
+ return undefined;
75
+ }
76
+ if (!before.isDirectory() || before.isSymbolicLink() || now - before.mtimeMs <= staleMinutes * 60_000)
77
+ return undefined;
78
+ const store = openStoreDir(directory);
79
+ if (!store.ok)
80
+ return undefined;
81
+ try {
82
+ const entries = store.value.list();
83
+ if (!entries.ok || entries.value.some(name => name !== "owner"))
84
+ return undefined;
85
+ const owner = store.value.read("owner", { maxBytes: 512 });
86
+ if (owner.ok) {
87
+ const match = /^pid=(\d+)$/m.exec(owner.value.toString());
88
+ if (!match)
89
+ return undefined;
90
+ const pid = Number(match[1]);
91
+ const state = alive(pid);
92
+ if (state === undefined)
93
+ return undefined;
94
+ if (state) {
95
+ const recorded = /^birth=(.*)$/m.exec(owner.value.toString())?.[1];
96
+ const current = birth(pid);
97
+ if (!recorded || !current || recorded === current)
98
+ return undefined;
99
+ }
100
+ }
101
+ else if (owner.code !== "missing")
102
+ return undefined;
103
+ }
104
+ finally {
105
+ store.value.close();
106
+ }
107
+ const retired = `${directory}.stale-${randomUUID()}`;
108
+ try {
109
+ fs.renameSync(directory, retired);
110
+ const captured = fs.lstatSync(retired);
111
+ if (captured.dev !== before.dev || captured.ino !== before.ino) {
112
+ if (!fs.existsSync(directory))
113
+ fs.renameSync(retired, directory);
114
+ return undefined;
115
+ }
116
+ const held = openStoreDir(retired);
117
+ if (!held.ok)
118
+ return undefined;
119
+ try {
120
+ held.value.remove("owner");
121
+ }
122
+ finally {
123
+ held.value.close();
124
+ }
125
+ fs.rmdirSync(retired);
126
+ fs.mkdirSync(directory, { mode: 0o700 });
127
+ recovered = true;
128
+ }
129
+ catch {
130
+ return undefined;
131
+ }
132
+ }
133
+ const held = openStoreDir(directory);
134
+ if (!held.ok)
135
+ return undefined;
136
+ let identity;
137
+ try {
138
+ identity = fs.lstatSync(directory);
139
+ }
140
+ catch {
141
+ held.value.close();
142
+ return undefined;
143
+ }
144
+ const owner = `pid=${process.pid}\nbirth=${birth(process.pid) ?? ""}\n`;
145
+ if (!held.value.writeAtomic("owner", owner).ok) {
146
+ held.value.close();
147
+ return undefined;
148
+ }
149
+ return { recovered, release() {
150
+ try {
151
+ const current = held.value.read("owner", { maxBytes: 512 });
152
+ if (current.ok && current.value.toString() === owner)
153
+ held.value.remove("owner");
154
+ }
155
+ finally {
156
+ held.value.close();
157
+ }
158
+ try {
159
+ const current = fs.lstatSync(directory);
160
+ if (current.dev === identity.dev && current.ino === identity.ino)
161
+ fs.rmdirSync(directory);
162
+ }
163
+ catch { /* Changed or nonempty lock remains held. */ }
164
+ } };
165
+ }
166
+ //# sourceMappingURL=stop-autosave-lock.js.map
@@ -0,0 +1,28 @@
1
+ export interface SweepDependencies {
2
+ git: (args: string[]) => {
3
+ code: number;
4
+ stdout: string;
5
+ stderr: string;
6
+ };
7
+ enabled: () => Promise<boolean>;
8
+ /** `top` is git's own `--show-toplevel` for the HQ root, to compare with git's top for the file. */
9
+ save: (relative: string, top: string) => Promise<number>;
10
+ log: (message: string) => void;
11
+ exists: (file: string) => boolean;
12
+ size: (file: string) => number | undefined;
13
+ }
14
+ /** Parse porcelain v1 -z without splitting filenames on whitespace. */
15
+ export declare function sweepCandidates(output: string): {
16
+ count: number;
17
+ paths: string[];
18
+ };
19
+ export declare function autosavePathAllowed(relative: string): boolean;
20
+ /**
21
+ * Whether git's `--show-toplevel` output names the checkout at `root` (a real
22
+ * path). Git for Windows prints `C:/Users/...` while Node's real path is
23
+ * `C:\Users\...`, and drive letters and names compare without case there.
24
+ */
25
+ export declare function sameCheckout(gitTop: string, root: string, platform?: NodeJS.Platform): boolean;
26
+ export declare function runStopSweep(root: string, minimum: number, deps: SweepDependencies): Promise<number>;
27
+ export declare function sweepFileSize(file: string): number | undefined;
28
+ //# sourceMappingURL=stop-autosave.d.ts.map
@@ -0,0 +1,111 @@
1
+ /** Stop sweep selection, separated from Git mutation and flag I/O.
2
+ * Only the local HQ checkout is eligible. Its nested repositories and company
3
+ * knowledge remain owned by their existing workflows.
4
+ */
5
+ import * as fs from "node:fs";
6
+ import * as path from "node:path";
7
+ /** Parse porcelain v1 -z without splitting filenames on whitespace. */
8
+ export function sweepCandidates(output) {
9
+ const entries = output.split("\0");
10
+ let count = 0;
11
+ const paths = [];
12
+ for (let index = 0; index < entries.length; index++) {
13
+ const entry = entries[index];
14
+ if (!entry)
15
+ continue;
16
+ count++;
17
+ const xy = entry.slice(0, 2);
18
+ if (/[RC]/.test(xy)) {
19
+ index++;
20
+ continue;
21
+ }
22
+ if (xy === "??" || (xy[0] === " " && xy[1] !== " " && xy[1] !== "D"))
23
+ paths.push(entry.slice(3));
24
+ }
25
+ return { count, paths };
26
+ }
27
+ export function autosavePathAllowed(relative) {
28
+ if (!relative || path.isAbsolute(relative)
29
+ || Array.from(relative).some(character => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127))
30
+ return false;
31
+ if (relative.split(/[\\/]/).some(part => part === ".." || part === ".git"))
32
+ return false;
33
+ if (/^(?:repos|node_modules|\.next|\.vercel)\//.test(relative))
34
+ return false;
35
+ if (/^(?:workspace\/worktrees|\.claude\/worktrees)\//.test(relative))
36
+ return false;
37
+ if (/^companies\/[^/]+\/knowledge(?:\/|$)/.test(relative))
38
+ return false;
39
+ return !/\.(?:tmp|log)$/.test(relative);
40
+ }
41
+ /**
42
+ * Whether git's `--show-toplevel` output names the checkout at `root` (a real
43
+ * path). Git for Windows prints `C:/Users/...` while Node's real path is
44
+ * `C:\Users\...`, and drive letters and names compare without case there.
45
+ */
46
+ export function sameCheckout(gitTop, root, platform = process.platform) {
47
+ if (platform !== "win32")
48
+ return gitTop === root;
49
+ const plain = (value) => path.win32.normalize(value).replace(/[\\]+$/, "").toLowerCase();
50
+ return gitTop !== "" && plain(gitTop) === plain(root);
51
+ }
52
+ export async function runStopSweep(root, minimum, deps) {
53
+ if (!deps.exists(path.join(root, "core/core.yaml")) || !deps.exists(path.join(root, ".git")))
54
+ return 0;
55
+ const top = deps.git(["rev-parse", "--show-toplevel"]);
56
+ const hqTop = top.stdout.trim();
57
+ if (top.code !== 0 || !sameCheckout(hqTop, root) || !await deps.enabled())
58
+ return 0;
59
+ const status = deps.git(["status", "--porcelain=v1", "-z", "--untracked-files=all"]);
60
+ if (status.code !== 0) {
61
+ deps.log(`FAIL stage=bash-status exit=${status.code}`);
62
+ return 0;
63
+ }
64
+ const candidates = sweepCandidates(status.stdout);
65
+ if (candidates.count > 20) {
66
+ deps.log(`SKIP stage=bash-sweep reason=path-cap changed=${candidates.count} cap=20`);
67
+ return 0;
68
+ }
69
+ for (const relative of candidates.paths) {
70
+ if (relative.split("/").includes("..") || path.isAbsolute(relative)) {
71
+ deps.log("SKIP stage=bash-sweep reason=unsafe-path");
72
+ continue;
73
+ }
74
+ const ignored = deps.git(["check-ignore", "-q", "--no-index", "--", relative]);
75
+ if (ignored.code === 0) {
76
+ deps.log("SKIP stage=bash-sweep reason=ignored-path");
77
+ continue;
78
+ }
79
+ if (ignored.code !== 1) {
80
+ deps.log(`SKIP stage=bash-sweep reason=ignore-check-failed exit=${ignored.code}`);
81
+ continue;
82
+ }
83
+ if (!deps.exists(path.join(root, relative)))
84
+ continue;
85
+ const size = deps.size(path.join(root, relative));
86
+ if (size === undefined) {
87
+ deps.log("SKIP stage=bash-sweep reason=not-regular-file");
88
+ continue;
89
+ }
90
+ if (!relative.endsWith(".hqcloud") && size !== undefined && size > minimum) {
91
+ deps.log(`SKIP stage=bash-sweep reason=oversize bytes=${size} min=${minimum}`);
92
+ continue;
93
+ }
94
+ if (!autosavePathAllowed(relative))
95
+ continue;
96
+ // The shell uses `set -u`, so a strict per-file failure does not prevent
97
+ // the remaining candidates from being processed.
98
+ await deps.save(relative, hqTop);
99
+ }
100
+ return 0;
101
+ }
102
+ export function sweepFileSize(file) {
103
+ try {
104
+ const stat = fs.lstatSync(file);
105
+ return stat.isFile() && !stat.isSymbolicLink() ? stat.size : undefined;
106
+ }
107
+ catch {
108
+ return undefined;
109
+ }
110
+ }
111
+ //# sourceMappingURL=stop-autosave.js.map
@@ -0,0 +1,11 @@
1
+ export interface StopDiagnosticOptions {
2
+ root: string;
3
+ ownsQueue: () => boolean;
4
+ report?: (body: string) => Promise<{
5
+ code: number;
6
+ }>;
7
+ log: (message: string) => void;
8
+ }
9
+ export declare function closeStopDiagnosticCursor(root: string): void;
10
+ export declare function drainStopDiagnostics(options: StopDiagnosticOptions): Promise<number>;
11
+ //# sourceMappingURL=stop-diagnostics.d.ts.map