@indigoai-us/hq-cli 5.345.270 → 5.345.273

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 (54) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/contracts/host-canary-release.json +7 -7
  3. package/dist/command-catalog.generated.d.ts +2 -2
  4. package/dist/command-catalog.generated.js +2 -2
  5. package/dist/commands/core-checkpoint-stop-gate-native.js +2 -13
  6. package/dist/commands/core-session-journal-native.js +20 -4
  7. package/dist/commands/signals-run.d.ts +4 -1
  8. package/dist/commands/signals-run.js +6 -8
  9. package/dist/commands/sync-core.js +2 -1
  10. package/dist/lib/daemon/daemon-restart.d.ts +70 -0
  11. package/dist/lib/daemon/daemon-restart.js +114 -0
  12. package/dist/lib/daemon/hook-requests-work-mesh-shims.d.ts +41 -0
  13. package/dist/lib/daemon/hook-requests-work-mesh-shims.js +237 -0
  14. package/dist/lib/daemon/hook-requests.d.ts +4 -1
  15. package/dist/lib/daemon/hook-requests.js +23 -1
  16. package/dist/lib/daemon/hq-child-bootstrap.mjs +1 -0
  17. package/dist/lib/daemon/installed-cli-restart.js +14 -4
  18. package/dist/lib/daemon/merge-sections.d.ts +24 -1
  19. package/dist/lib/daemon/merge-sections.js +59 -11
  20. package/dist/lib/daemon/run.d.ts +1 -1
  21. package/dist/lib/daemon/run.js +67 -53
  22. package/dist/lib/daemon/supervisor.js +0 -2
  23. package/dist/lib/hook-engine/coverage.d.ts +21 -0
  24. package/dist/lib/hook-engine/coverage.js +98 -5
  25. package/dist/lib/hook-engine/native-precompact-compatibility.json +1 -0
  26. package/dist/lib/hook-engine/native-stop-compatibility.json +2 -1
  27. package/dist/lib/hot-channels/signals-pass.d.ts +10 -2
  28. package/dist/lib/hot-channels/signals-pass.js +13 -3
  29. package/dist/lib/signals/engine.d.ts +0 -2
  30. package/dist/lib/signals/engine.js +12 -7
  31. package/dist/lib/signals/reply.js +35 -82
  32. package/dist/lib/signals/run-lock.d.ts +8 -0
  33. package/dist/lib/signals/run-lock.js +42 -7
  34. package/dist/lib/signals/run-record.js +2 -1
  35. package/dist/lib/signals/settings.d.ts +9 -4
  36. package/dist/lib/signals/settings.js +7 -5
  37. package/dist/lib/signals/steps/extract.d.ts +37 -10
  38. package/dist/lib/signals/steps/extract.js +88 -111
  39. package/dist/lib/signals/steps/types.d.ts +3 -2
  40. package/dist/lib/sync-core/reconcile.d.ts +7 -1
  41. package/dist/lib/sync-core/reconcile.js +105 -18
  42. package/dist/lib/sync-core/release.d.ts +52 -2
  43. package/dist/lib/sync-core/release.js +172 -11
  44. package/dist/lib/sync-core/rollout-state.d.ts +11 -0
  45. package/dist/lib/sync-core/rollout-state.js +16 -0
  46. package/dist/utils/client-health-contract.d.ts +32 -0
  47. package/dist/utils/client-health-contract.js +35 -0
  48. package/dist/utils/client-health.d.ts +43 -0
  49. package/dist/utils/client-health.js +106 -3
  50. package/dist/utils/login-browser.d.ts +1 -0
  51. package/dist/utils/login-browser.js +31 -6
  52. package/dist/utils/spawn-detached-hidden.d.ts +66 -0
  53. package/dist/utils/spawn-detached-hidden.js +222 -0
  54. package/package.json +7 -7
package/CHANGELOG.md CHANGED
@@ -2,6 +2,70 @@
2
2
 
3
3
  ## [Unreleased]
4
4
 
5
+ ## [5.345.273] — 2026-12-01
6
+ - Fixed: hosted agents (`agents-v2`) on the v2.71 release-line hook adapter that carries the `hq-agents-v2` #364 PreToolUse payload fix (`b6db50be`) keep native hook registration. `hq-hook` now answers `PreToolUse`, `PostToolUse`, `UserPromptSubmit`, `SessionStart`, `SessionEnd` and `SubagentStop` natively for that adapter, as it already does for the main-line #364 adapter (`15fa77e8`), and still hands `Stop` to the adapter. An adapter revision `hq-hook` does not know still runs every event through the adapter, and the reason it gives no longer names only #332.
7
+ - Updated `contracts/host-canary-release.json` with the Claude Code host canary records for hq-cli 5.345.273.
8
+ - CI: the hq-hook macOS native tests on a pull request now start after the Linux hq-hook tests pass on the same commit, and do not run again on a commit they already passed on.
9
+ - Fixed: `gh pr merge` no longer stops with "merge state unreadable" only because the daemon's merge state is a little over a minute old. In that case the merge gate asks `hq runners hold check` directly and follows its answer. The daemon now keeps flag values fresh in the background, so building that state no longer waits on slow flag reads.
10
+ - Speed up npm releases by building native `hq-hook` packages in parallel with the tag parity check (while still gating all npm publication on parity) and inheriting verified green `hq-hook` CI across commits that only update `contracts/host-canary-release.json`.
11
+ - Use Windows PowerShell (`shell: powershell`) for the self-hosted Windows `verify-published` signature check in `.github/workflows/hq-hook-packages.yml`, matching the shell shipped on `hq-windows` runners.
12
+
13
+ ## [5.345.272] — 2026-11-30
14
+ - Set explicit file timestamps in auto-checkpoint tests to remove fixture sleeps.
15
+ - Fix a flaky `hq core checkpoint` test that failed when a real process held the PID its spawn mock reported.
16
+ - CI: cancel leftover workflow runs on merged or bisected `train/` branches in `scripts/ci/batch-train.py`, carry passing Windows results across non-Windows bisect sub-batches, and unblock the start gate for runs just cancelled.
17
+ - Changed: the self-hosted Windows hq-hook job and the native macOS hq-hook PR job now record hook p50 and p95 per event against the hq-core v16.0.52 hooks and upload the report. A new compare command prints the Windows-to-macOS p95 ratio next to the 1.2x target. It is report-only and never fails a job, because the limits are not signed off.
18
+ - Fixed: the macOS native hook test shards no longer fail at random while setting up pnpm or installing cargo-nextest when two shards run on the Mac Studio at once. Each job now keeps those setup files in its own temp folder.
19
+ - The release workflow now waits for the hq-hook jobs on the release tag (four Linux shards, the Beaker Windows x64 job, the Windows build archive and its six Windows test shards) and publishes only when each one succeeds. A missing, cancelled, timed-out or failed job stops the release.
20
+ - Every release tag that publishes the native hook packages now re-downloads all six platform packages from npm and checks their integrity, identity and macOS or Windows signatures once publication finishes. It polls npm's per-version document for up to 15 minutes and fails the release when a package or a signature check is missing. The checks and their summary run on self-hosted runners only. The manual published_version run is unchanged.
21
+ - Fixed: the Windows hook baseline shards now run from source with an error note when the one-time archive build fails, instead of all being skipped, and the archive restore fails with a clear error when the build published no archive hash.
22
+ - Fixed: added a build-once nextest archive job (`build-archive` with `sccache` sharing the `hq-cli/hq-hook/windows-x64` prefix), archive restore/download in baseline shards, and 6-way sharding (`HQ_WINDOWS_SHARDS=6`) to `hq-hook-windows-baseline.yml` so main Windows baseline shards match train shard durations.
23
+ - Fixed: the Windows hook test shards are balanced again. The per-test timing file now holds times measured on the AWS Windows runners, including the full injector corpus test turned on in #4269 and three targets the old file lacked, so no shard runs past 1.5x the median.
24
+ - The CLI health heartbeat now reports when the running daemon started, whether the desktop app hosts it, and, from a daemon unit, the CLI version on disk. It also reports the new sync engine release the pin asks for, where the pin came from, and the outcome, time and warning count of the last engine reconcile, including when the pin came from the last one read on the computer or could not be read at all. Warning text stays on the machine.
25
+ - The CLI health report no longer counts a bot or session started below a daemon unit as a unit when the daemon runs this release, so such a process no longer makes the daemon look older than its units. Units started by an older daemon are still recognised as before. The daemon start time is read only from the daemon's own lock and state files, with no extra process started by ordinary commands, and is sent only when the state was written by the daemon that holds the lock and was rewritten within the last two minutes; otherwise the report says no daemon runs.
26
+ - Document Codex hook registration, worktree requirements, and doctor checks.
27
+ - Cover Windows path spelling and CRLF headers in Codex patch decoding.
28
+ - A daemon asked to restart onto a newer installed hq-cli now restarts within 10 minutes even when a sync runner restart was waiting and that runner was stopped before it went idle. Before, the restart waited until a sync pass finished, with no time limit. Once the daemon starts stopping (for a restart, a signal or `hq daemon stop`), it now releases its lock and exits after the usual shutdown limit, even when a service or background job fails to stop cleanly. If a step of the restart fails before that, the daemon stops its services with the same limit and exits with the restart code. Before, either failure left the daemon running and ignoring every later restart request.
29
+ - Document Google Antigravity hook registration, guarded/denied tools, turning hooks off, and `hq doctor` checks in `docs/hooks/antigravity.md` and link it from `docs/hook-registration.md`.
30
+ - Enabled native `agents-v2` handling behind the `hq-agents-v2` #364 adapter (`15fa77e8`) for `PostToolUse`, `SessionEnd`, `SubagentStop`, `SessionStart`, and `UserPromptSubmit`, including payload-aware registry prefilter evaluation and fleet runtime record writes (US-040).
31
+ - Added: native `work-mesh-shims` member and daemon request note handlers for the five core work-mesh shims (`SessionStart/35-work-mesh-register.sh`, `SessionStart/36-work-mesh-sweep.sh`, `UserPromptSubmit/35-work-mesh-register.sh`, `UserPromptSubmit/70-work-mesh-ground.sh`, `SessionEnd/35-work-mesh-close.sh`) with pinned coverage holds for `hq-core` v16.0.52 and v16.0.53-beta.4.
32
+ - Windows checkpoint stop-gate jobs no longer flash cmd/node consoles. Detached background `hq` work now starts through hidden `wscript` plus WMI `Win32_Process.Create` (CreateProcess, so `%VAR%` arguments stay literal) instead of `windowsHide`, which Windows ignores on a detached process. The launcher is UTF-16LE with a BOM so non-ASCII profile paths still start.
33
+ - A first `hq auth login`, and `hq login --provider picker`, now open HQ's own sign-in page with a Google button and a Microsoft button. Before, they opened a page with a long list of provider buttons that most people could not tell apart. Setting `HQ_COGNITO_IDENTITY_PROVIDER=""` still opens the previous page.
34
+ - Recognize reindexed `core.next` `PostToolUse` entries in `post_mesh_tool_writes` when `hook-adapter-core.sh` is a pinned classifying revision, restoring Grok Build and Codex `PostToolUse` parity.
35
+ - Parse shell command words with the engine's existing shell lexer in `lanes-repo-merge-hold` so quoted mentions of "merge" in arguments to non-merge commands (such as `bash script.sh "..."`, `echo`, `printf`, `git commit -m`, `git merge-base`, or non-shell heredoc bodies) allow without spawning `hq runners hold check`, while real merge commands (`git merge`, `gh pr merge`, `gh api .../merge`, `gh api graphql ... mergePullRequest`, and forms hidden behind `;`, `&&`, `$(...)`, `eval`, variables, wrappers, or shell pipes) still run the hold lookup.
36
+ - Fix `src/node-network-compat-closure.test.ts` CI shard timeout flake by setting `noLib: true` and `types: []` in `ts.createProgram` so synthetic tests do not re-parse TypeScript stdlib and `node_modules/@types/*` (no timeouts widened).
37
+ - Fix `session_start_hqd_open` test server flake on macOS under parallel load by clearing inherited `O_NONBLOCK` (`set_nonblocking(false)`) and retrying `EINTR` on accepted `UnixStream`s before `read_until` (no timeouts widened).
38
+ - Fixed: replace a non-subset subagent scope-capability file with the parent session's lock set on SubagentStart.
39
+ - Open the native `folder-hooks` member in `hq-hook` to Codex and Grok Build for `PreToolUse` and `PostToolUse`, running personal, package, and company folder hooks once per adapter-fanned-out payload in each adapter's blocking or advisory mode.
40
+ - Record the daemon restart owner in the reviewed function manifest so the manifest check passes on main again.
41
+ - Document Grok Build hook registration, guard behavior, and doctor checks.
42
+ - Ledger Grok round-2 Stop, UserPromptSubmit, and SessionEnd native-stricter-by-design behaviors in US-013 `intended-differences.yaml` with backing test coverage.
43
+ - Updated `contracts/host-canary-release.json` with the Claude Code host canary records for hq-cli 5.345.272.
44
+ - Fixed: `hq-hook` no longer refuses every tool call when one read of a pinned hook script fails or comes back partial (an interrupted open, a file being replaced or rewritten). The native policy-enforcement gate's version check and the bridge's script pin check read the script up to four times, 25 ms apart, before treating it as unpinned. A script that really changed is still refused, at once when it was not modified in the last two seconds.
45
+ - Fixed: `hq-hook`'s native `journal-due` port no longer picks one bash version's reading of an edit counter that bash versions read differently. A counter with a leading zero, octal digits that are not all zero, then an 8 or 9 (such as `0129`) reads as 0 under bash 3.2 (macOS `/bin/bash`) and as the octal prefix under bash 5 (5.1, 5.2 and 5.3), so the shell hook's reminder depended on which bash was first on PATH. The port now refuses that input and writes nothing, as it does for other inputs it does not model. The parity test runs under the first bash on PATH, `/bin/bash`, and `HQ_HOOK_REFERENCE_BASH`.
46
+ - The native hook engine now recognizes the current Indigo review-gate hook, which allows a call at once when its payload has no "gh" followed by "pr". Bots with that hook run the PreToolUse check natively again instead of handing it to the bash hook.
47
+ - CI: the macOS hook latency report runs in its own job beside the native test shards, so the first shard no longer runs about 2 minutes longer than the rest.
48
+ - Document native hook entry formats and the mixed-canary registration hold.
49
+ - Native tar command handling now matches the shell guard.
50
+ - Performance: evaluate `lanes-repo-merge-hold` in-process from `workspace/lanes/holds` and daemon state without spawning Node on the common path, keeping the CLI fallback only when an active hold or senior lane requires a live flag-registry read.
51
+ - Fix a flaky secret-scan test whose random fake secret sometimes fell under the generic rule's entropy floor and went unflagged.
52
+ - Fix native `session-journal` write lock on Windows to treat delete-pending `EPERM`/`EACCES`/`EBUSY` errors as contention and retry lock removal with `maxRetries`, preventing dropped concurrent journal writes.
53
+ - Signals: the default spend cap for the extract step is now $10.00 per run, up from $2.00, so a morning with many new meetings no longer stops partway. Set `maxBudgetUsd` in core/settings/signals.yaml or pass `--max-budget-usd` to change it.
54
+ - Signals: runs no longer have a spend cap, and no run stops partway on a dollar amount. This replaces the earlier note about a $10.00 default. The `--max-budget-usd` option of `hq signals run` is removed: passing it now ends with a message saying so. `maxBudgetUsd` and `incremental.max_budget_usd` in core/settings/signals.yaml are ignored, so an existing settings file keeps working. The run reply still shows what the run spent, as a plain figure.
55
+ - Signals: what bounds a run now. The step that finds signals in landed source files reads up to 20 new sources per channel in one run, with up to 40 model turns and 10 minutes per source. It stops the run when the coding tool is signed out. On Claude it now also stops when Claude reports that the plan is out of usage or that the call was rate limited (status 429); the sources it did not reach wait for the next run. The hot-channel signals pass keeps its own limits: 40 documents per run, 12 signals per document, a stop after repeated unusable replies, and a stop at a usage limit.
56
+ - Signals: a run that keeps reading sources keeps its run lock, so a second run can no longer start on the same company while the first is still working. The lock is renewed each time a step or a source starts or finishes. A run that makes no progress for 3 hours gives up its lock, as before.
57
+ - Fixed: typing a /skill command in a session bound to a company, such as /handoff-and-archive, was refused with "the native check cannot tell what the released hook would do". The skill-command hook now reads the session's company list itself, so a bound session runs its company skill scripts as before. When the hook still cannot run a script (no daemon, an unreadable file, an unknown library revision), your prompt now goes through and you see one note that the script did not run, instead of the prompt being blocked.
58
+ - The new sync engine pin is checked more strictly. A pin with keys other than `release`, `revoked` and note-style keys (such as `note`, `comment`, `updatedAt` or keys starting with `_`, but never a key containing "revok"), for example a misspelled `revoke`, is used with a warning, and the revoked list stored on the computer is kept, except that the release the pin names is never kept revoked; a pin that lists its own release under another revoked-like key counts as unreadable. A missing `pin.json` on the production download base counts as unreadable: a computer that has read a pin before keeps using it, and a computer that has never read one installs no engine, so its vaults stay on the current sync until the pin can be read (before, it installed the built-in release). A release the pin revokes is not installed, with a warning that says so. Each download base keeps its own stored pin, a mirror whose pin returns 403 or 404 keeps its stored revoked list, the production base is matched only over https, and no temporary file is left when the pin cannot be saved. The scheduled reconcile logs a repeated set of warnings once; a reconcile run by hand prints them all, and the rollout state keeps them all. The CLI health report now says when reconcile refused a revoked release, and counts every warning of a reconcile.
59
+ - The new sync engine pin (`pin.json`) can now list withdrawn engine releases under `revoked` (`"v0.1.42"` or `"0.1.42"`). A machine running a withdrawn release replaces it with the pinned release on its next reconcile, even when the pinned release is older; before, an older pin never replaced a newer installed engine. Each computer keeps the last pin it read. When `pin.json` cannot be read, that pin and its revoked list still apply, and a computer that has never read a pin installs and upgrades no engine until it can. Revoked entries that are not releases are ignored with a warning, and a `revoked` that is not a list makes the pin count as unreadable. A revoked engine whose replacement cannot be downloaded keeps running, with a warning that names it as revoked. Rolling back is only supported to a release that reads the same on-disk index format; releases v0.1.40 to v0.1.46 all use index schema 7.
60
+ - Fixed: the Beaker Rust toolchain step tests no longer fail on CI runners that set their own RUSTUP_HOME. The tests now run the step with a minimal environment instead of the runner's.
61
+ - Split each pinned `block-credential-file-read` corpus into contiguous parts that stop at the end of their range. The main build still compares every payload with the bash guard. The other pinned builds have the port answer every payload against the corpus's own checks and send a recorded sample through bash, which reaches every (section, decision) class. On every build, named payloads run every line of the guard hunks that differ between pinned revisions, and every line no payload runs is listed with its reason. On the pinned revisions other than the main build, compare the parity TABLE through bash on one row per (check, exit code, message) class instead of every row.
62
+ - Tests: the `block-hq-glob` parity suites run the bash reference hook again, at most twice, when bash reports that one of its own writes was interrupted ("Interrupted system call"). Each retry is logged. The native hook is run once, and every comparison is unchanged.
63
+ - Speed up the hq-hook gate parity binaries' lock and gate-fact tests: the lock loop's 100 attempts run with no real pause on both sides (a test-only pause setting in `gate::lock`, and a `sleep` that returns at once on the bash gate's PATH), the hook-state file check rides the same bash run as the byte comparison, and each released gate version sends a fixed sample (5 of 8 lock cases, 20 of 64 fact cases, at least one per decision class) through its bash gate while the `gate_native` binary keeps sending every case. Every binary still checks every case's native answer, and fails when the sample misses a class the full list reaches on that version. A slow-list test in the `gate_native` binary (`bash_samples_run_every_command_the_case_lists_run`, on the batch train and the daily main run, and on a pull request that changes the gate suite, `src/gate` or a pinned gate) runs every case through every pinned bash gate under `bash -x` and fails when a command of the gate or its libraries is run by the full case list but by no sampled case.
64
+ - Fixed: the SessionStart parity tests no longer fail at random when the shell hook's background timeout watchdog writes its storage-class side file before the test compares workspaces. The native side is now checked to never write that file.
65
+ - Run each `us012_root_git_codex_grok` HQ-root git form through the released Codex or Grok adapter in bash once per host and once per root instead of on every host in every root, with the native answer still checked on every row and an invariant that bash reaches every decision class on each host in each root, cutting the binary's bash spawns by half; each part now runs on two threads with its own roots. A slow-list test traces all 632 rows in bash and fails when the sample misses a command of the pinned chain scripts that the full matrix runs on a host or in a root; its one named exemption is master-hook.sh line 334 (`master_debug_phase_buffer_record`), which runs only when master-hook's startup took a second or more, and it is excused only when it does not run again on recheck.
66
+ - Added cross-platform unit tests for `hq-hook` `session_start_master` Windows cwd classification (regression coverage for `#3940`) and a clearer CRLF working-copy error message in `merged_write_guard` pin checks.
67
+ - Added parity tests for the `hq-hook` Task-agent SubagentStart scope pin (US-024). They compare master-hook.sh, the native engine and `hq-hook run` on malformed, other-company and stale parent scope files. Test-only; no behavior change.
68
+
5
69
  ## [5.345.270] — 2026-11-30
6
70
  - Fixed: wired `crates/hq-hook/tests/win_store.rs` into the `hq-hook.yml` Windows "Unit and pipe tests" list (and release archive shards), the PR test list, and the Windows PR scope selector for `src/spool`.
7
71
  - Change `hq-hook Windows baseline` schedule from hourly (`47 * * * *`) to once nightly at 07:47 UTC (`47 7 * * *`, outside the 13:00–03:00 UTC train window) and skip scheduled runs when the `main` commit or its git tree already has a green `hq-hook Windows tests (Beaker)` result from a `train/**` run (`covered by train <run id>`, fail-closed on ambiguity or API errors).
@@ -1,24 +1,24 @@
1
1
  {
2
2
  "schema": "hq.host-canary-release.v1",
3
- "cliVersion": "5.345.270",
3
+ "cliVersion": "5.345.273",
4
4
  "hosts": {
5
5
  "claude": [
6
6
  {
7
7
  "passed": true,
8
- "at": "2026-11-30T02:02:55.216Z",
9
- "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
8
+ "at": "2026-12-01T00:04:49.430Z",
9
+ "engineVersion": "0.3.1+hq.5.345.273.src.90e7e4db1b4b524b040871dd904084a635a22579d519d48cdb7b4b8b2ef5dc04",
10
10
  "gateSha256": "a2879dfe692233f5953bac86672947bbd82f3c5247292f3efcb80f16c3d2c6b1"
11
11
  },
12
12
  {
13
13
  "passed": true,
14
- "at": "2026-11-30T02:03:13.811Z",
15
- "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
14
+ "at": "2026-12-01T00:05:09.860Z",
15
+ "engineVersion": "0.3.1+hq.5.345.273.src.90e7e4db1b4b524b040871dd904084a635a22579d519d48cdb7b4b8b2ef5dc04",
16
16
  "gateSha256": "ca58a94859eae0a345c11c8d9c59303eb76350dc1cf223391037d21979c28718"
17
17
  },
18
18
  {
19
19
  "passed": true,
20
- "at": "2026-11-30T02:03:49.977Z",
21
- "engineVersion": "0.3.1+hq.5.345.270.src.fb37f49ebae3604d89308abc7685e866c6c4e37fa36961d5511730cf3627ca96",
20
+ "at": "2026-12-01T00:05:44.343Z",
21
+ "engineVersion": "0.3.1+hq.5.345.273.src.90e7e4db1b4b524b040871dd904084a635a22579d519d48cdb7b4b8b2ef5dc04",
22
22
  "gateSha256": "ecdbab7c2e0a1d94eb9c98f15e760390f215bc7115a217ded24b4275322722d2"
23
23
  }
24
24
  ]
@@ -5729,8 +5729,8 @@ export declare const COMMAND_CATALOG: readonly [{
5729
5729
  readonly hidden: false;
5730
5730
  }, {
5731
5731
  readonly flags: "--max-budget-usd <x>";
5732
- readonly description: "Spend cap in USD for the extract step (default from core/settings/signals.yaml, else 2.00)";
5733
- readonly hidden: false;
5732
+ readonly description: "Removed: signals runs have no spend cap";
5733
+ readonly hidden: true;
5734
5734
  }, {
5735
5735
  readonly flags: "--json";
5736
5736
  readonly description: "Print the run record as JSON";
@@ -6962,8 +6962,8 @@ export const COMMAND_CATALOG = [
6962
6962
  },
6963
6963
  {
6964
6964
  "flags": "--max-budget-usd <x>",
6965
- "description": "Spend cap in USD for the extract step (default from core/settings/signals.yaml, else 2.00)",
6966
- "hidden": false
6965
+ "description": "Removed: signals runs have no spend cap",
6966
+ "hidden": true
6967
6967
  },
6968
6968
  {
6969
6969
  "flags": "--json",
@@ -1,6 +1,6 @@
1
1
  /** Native fast-route implementation of checkpoint-stop-gate.sh. */
2
- import * as childProcess from "node:child_process";
3
2
  import { planHqSpawn } from "../utils/hq-spawn.js";
3
+ import { spawnDetachedHidden } from "../utils/spawn-detached-hidden.js";
4
4
  import * as fs from "node:fs";
5
5
  import * as os from "node:os";
6
6
  import * as path from "node:path";
@@ -99,18 +99,7 @@ const defaults = () => ({
99
99
  },
100
100
  spawnHqDetached: (args, env) => {
101
101
  const childEnv = env ?? process.env;
102
- const spawnPlan = planHqSpawn(args, childEnv, process.cwd());
103
- const child = childProcess.spawn(spawnPlan.cmd, spawnPlan.args, {
104
- detached: true,
105
- stdio: "ignore",
106
- env: childEnv,
107
- shell: spawnPlan.shell,
108
- ...(spawnPlan.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}),
109
- });
110
- child.once("error", (error) => {
111
- process.stderr.write(`${error.message}\n`);
112
- });
113
- child.unref();
102
+ spawnDetachedHidden(planHqSpawn(args, childEnv, process.cwd()), childEnv);
114
103
  },
115
104
  });
116
105
  function toShellString(value) {
@@ -102,6 +102,14 @@ function counterLockOwnerIsAlive(lock, pid) {
102
102
  catch { /* older shell locks did not record the Win32 PID */ }
103
103
  return windowsPid > 1 && processIsAlive(windowsPid);
104
104
  }
105
+ // Windows keeps a just-released lock directory or pid file in a delete-pending
106
+ // state while another waiter still holds a handle on it. Creating the same
107
+ // name in that window fails with EPERM, EACCES or EBUSY instead of EEXIST, so
108
+ // it is lock contention and the waiter keeps polling until its deadline.
109
+ function isTransientWindowsLockError(error) {
110
+ const code = error?.code;
111
+ return process.platform === "win32" && (code === "EPERM" || code === "EACCES" || code === "EBUSY");
112
+ }
105
113
  function acquireJournalWriteLock(dir) {
106
114
  const lock = path.join(dir, ".session-journal-write.lock");
107
115
  const ownerFile = path.join(lock, "pid");
@@ -112,13 +120,20 @@ function acquireJournalWriteLock(dir) {
112
120
  try {
113
121
  fs.writeFileSync(ownerFile, `${process.pid}\n`, { flag: "wx" });
114
122
  }
115
- catch {
116
- fs.rmSync(lock, { recursive: true, force: true });
117
- return undefined;
123
+ catch (error) {
124
+ fs.rmSync(lock, { recursive: true, force: true, maxRetries: 10, retryDelay: 10 });
125
+ if (!isTransientWindowsLockError(error))
126
+ return undefined;
127
+ sleepSync(20);
128
+ continue;
118
129
  }
119
130
  return lock;
120
131
  }
121
132
  catch (error) {
133
+ if (isTransientWindowsLockError(error)) {
134
+ sleepSync(20);
135
+ continue;
136
+ }
122
137
  if (error.code !== "EEXIST")
123
138
  return undefined;
124
139
  let owner = 0;
@@ -150,8 +165,9 @@ function acquireJournalWriteLock(dir) {
150
165
  function releaseJournalWriteLock(lock) {
151
166
  try {
152
167
  const owner = Number.parseInt(fs.readFileSync(path.join(lock, "pid"), "utf8"), 10);
168
+ // Retry so a waiter's open handle on the pid file cannot leave an ownerless lock directory behind.
153
169
  if (owner === process.pid)
154
- fs.rmSync(lock, { recursive: true, force: true });
170
+ fs.rmSync(lock, { recursive: true, force: true, maxRetries: 10, retryDelay: 10 });
155
171
  }
156
172
  catch { /* shell lock cleanup is best-effort */ }
157
173
  }
@@ -21,12 +21,15 @@ interface RunCliOptions {
21
21
  force?: boolean;
22
22
  catchUp?: boolean;
23
23
  maxTurns?: number;
24
- maxBudgetUsd?: number;
24
+ /** Set only when the removed --max-budget-usd flag is passed. */
25
+ maxBudgetUsd?: string;
25
26
  json?: boolean;
26
27
  reportFound?: boolean;
27
28
  redo?: string[];
28
29
  hqRoot: string;
29
30
  }
31
+ /** What `hq signals run --max-budget-usd` answers now that the flag is gone. Exit code 2, like any usage error. */
32
+ export declare const MAX_BUDGET_FLAG_REMOVED = "--max-budget-usd was removed: signals runs have no spend cap. Drop --max-budget-usd.";
30
33
  export declare function formatRunResult(result: RunSignalsResult, dryRun: boolean): string;
31
34
  /**
32
35
  * The owner's reply for `--report-found`, or null when there is nothing to
@@ -25,12 +25,8 @@ function parsePositiveInt(v) {
25
25
  function collectRedo(v, prev = []) {
26
26
  return [...prev, v];
27
27
  }
28
- function parseNonNegative(v) {
29
- const n = Number(v);
30
- if (!Number.isFinite(n) || n < 0)
31
- throw new InvalidArgumentError("must be a non-negative number");
32
- return n;
33
- }
28
+ /** What `hq signals run --max-budget-usd` answers now that the flag is gone. Exit code 2, like any usage error. */
29
+ export const MAX_BUDGET_FLAG_REMOVED = "--max-budget-usd was removed: signals runs have no spend cap. Drop --max-budget-usd.";
34
30
  function envCatchUp() {
35
31
  const v = process.env.HQ_SIGNALS_CATCH_UP;
36
32
  return v === "1" || v === "true";
@@ -178,6 +174,8 @@ export function terminalSignalsAlert(write = (text) => void process.stderr.write
178
174
  * holds a company's lock (stdout then carries {"status":"running",...}).
179
175
  */
180
176
  export async function runSignalsCli(options, overrides = {}) {
177
+ if (options.maxBudgetUsd !== undefined)
178
+ throw new SignalsUsageError(MAX_BUDGET_FLAG_REMOVED);
181
179
  const result = await runSignals({
182
180
  hqRoot: options.hqRoot,
183
181
  company: options.company,
@@ -189,7 +187,6 @@ export async function runSignalsCli(options, overrides = {}) {
189
187
  force: options.force === true,
190
188
  catchUp: options.catchUp === true || envCatchUp(),
191
189
  maxTurns: options.maxTurns,
192
- maxBudgetUsd: options.maxBudgetUsd,
193
190
  ...(options.redo?.length ? { redo: options.redo } : {}),
194
191
  signalsAlert: overrides.signalsAlert ?? terminalSignalsAlert(),
195
192
  });
@@ -239,7 +236,8 @@ export function registerSignalsRunSubcommand(signals) {
239
236
  .option("--force", "Rerun a job trigger that already ran today")
240
237
  .option("--catch-up", "Mark the run as a catch-up run (also HQ_SIGNALS_CATCH_UP=1)")
241
238
  .option("--max-turns <n>", "Model turn cap for the extract step (default from core/settings/signals.yaml, else 40)", parsePositiveInt)
242
- .option("--max-budget-usd <x>", "Spend cap in USD for the extract step (default from core/settings/signals.yaml, else 2.00)", parseNonNegative)
239
+ // Removed flag. Still parsed, hidden from help, so an old command gets MAX_BUDGET_FLAG_REMOVED instead of "unknown option".
240
+ .addOption(new Option("--max-budget-usd <x>", "Removed: signals runs have no spend cap").hideHelp())
243
241
  .option("--json", "Print the run record as JSON")
244
242
  .option("--report-found", "Print the owner's run reply only when the run found new signals or its hot-channel signals pass did not finish; print nothing otherwise")
245
243
  .option("--redo <file>", "Process a source item again (sources/<channel>/<file>.md; repeatable; needs --company): the extract step re-queues it in the ontology worklist before listing", collectRedo)
@@ -130,10 +130,11 @@ export async function runSyncCoreReconcile(opts, d = defaultDeps()) {
130
130
  ...(journal.reader ? { readLegacyJournal: journal.reader } : { legacyJournalUnavailable: journal.reason }),
131
131
  machineType: await machineTypeHere(d),
132
132
  readDownloadStreams: (companyUid) => readCompanyDownloadStreams(companyUid, token, { env: d.env }),
133
- ensureBinary: (release) => ensureSyncCoreBinary({ home: d.home, platform: d.platform, arch: d.arch, release, env: d.env }),
133
+ ensureBinary: (release, revoked) => ensureSyncCoreBinary({ home: d.home, platform: d.platform, arch: d.arch, release, env: d.env, ...(revoked ? { revoked } : {}) }),
134
134
  platform: d.platform,
135
135
  env: d.env,
136
136
  readPin: () => readSyncCorePin({ env: d.env }),
137
+ quietRepeatedWarnings: Boolean(d.env.HQ_DAEMON_CLI_VERSION?.trim()),
137
138
  log: opts.json ? () => { } : d.out,
138
139
  });
139
140
  await runPostApplyReindex(hqRoot, result.state.vaults, d, opts.json ? () => { } : d.out);
@@ -0,0 +1,70 @@
1
+ /**
2
+ * The daemon's restart: exit with RESTART_EXIT_CODE for its parent (launchd,
3
+ * systemd, the desktop app) to start it again on the CLI on disk, either
4
+ * handing the running services to the next daemon or stopping them first.
5
+ *
6
+ * The first request latches; later ones return true without starting a
7
+ * second exit. If the exit step throws, the daemon exits anyway through
8
+ * `exitNow`. Once a stop has begun, `exitWhenStopped` releases the lock and
9
+ * exits even when the wait for services or jobs rejects.
10
+ */
11
+ type Log = (level: "info" | "warn" | "error", line: string) => void;
12
+ export interface DaemonRestartDeps {
13
+ /** Whether a parent starts this daemon again after it exits. */
14
+ canRestart: () => boolean;
15
+ /** A stop (signal, `hq daemon stop`) or restart is already under way. */
16
+ isStopping: () => boolean;
17
+ handoffWanted: () => Promise<boolean>;
18
+ /** Runs before the exit step unless a stop began meanwhile (schedules the Windows relaunch). */
19
+ beforeExit: () => void;
20
+ /** Exit leaving the services running for the next daemon, or null when there is no handoff. */
21
+ handOver: (() => void) | null;
22
+ /** Stop the services, then exit with the restart code. */
23
+ shutdown: () => void;
24
+ /** Exit with the restart code without the normal stop; used when handOver or shutdown threw. Must not throw. */
25
+ exitNow: (error: unknown) => void;
26
+ log: Log;
27
+ }
28
+ export declare function createDaemonRestart(deps: DaemonRestartDeps): () => boolean | Promise<boolean>;
29
+ /** How long a stop may take: `promise` resolves "timeout" when it runs out. */
30
+ export interface StopCap {
31
+ promise: Promise<"timeout">;
32
+ extendForSyncRunnerPersist?: () => void;
33
+ clear: () => void;
34
+ }
35
+ /** A fixed cap on real timers that does not keep the process alive. */
36
+ export declare function timeoutCap(ms: number): StopCap;
37
+ export interface ExitWhenStoppedDeps {
38
+ /** Services stopped and jobs closed; its value is passed to `onSettled`. */
39
+ stopped: Promise<unknown>;
40
+ cap: StopCap;
41
+ releaseLock: () => void;
42
+ /** End the process with this code (resolve runDaemon, then a hard exit). */
43
+ exit: (code: number) => void;
44
+ log: Log;
45
+ /** Logs the outcome: "timeout" when the cap ran out first. Not called when the stop rejected. */
46
+ onSettled?: (result: unknown) => void;
47
+ }
48
+ /** Wait for the stop, at most until the cap, then release the lock and exit, also when the stop rejects. */
49
+ export declare function exitWhenStopped(deps: ExitWhenStoppedDeps, exitCode: number): Promise<void>;
50
+ /**
51
+ * Services stopped and jobs closed, with the services' result. A rejected jobs
52
+ * promise is logged and counts as closed, so the wait for the services (and
53
+ * a sync runner's persist grace) still runs to its cap.
54
+ */
55
+ export declare function servicesAndJobsStopped(services: Promise<unknown>, jobs: Promise<unknown>, log: Log): Promise<unknown>;
56
+ export declare function logServicesStopped(log: Log, result: unknown): void;
57
+ export interface StopServicesAndExitDeps {
58
+ /** The supervisor's stop: SIGTERM, then SIGKILL, with the sync runner's persist grace. */
59
+ stopServices: () => Promise<unknown>;
60
+ hasStoppingSyncRunner: () => boolean;
61
+ /** The same cap as a normal shutdown. */
62
+ createCap: () => StopCap;
63
+ releaseLock: () => void;
64
+ exit: (code: number) => void;
65
+ log: Log;
66
+ }
67
+ /** The restart fallback after handOver or shutdown threw: stop the services with the normal bounded wait, then exit. */
68
+ export declare function stopServicesAndExit(deps: StopServicesAndExitDeps, exitCode: number): Promise<void>;
69
+ export {};
70
+ //# sourceMappingURL=daemon-restart.d.ts.map
@@ -0,0 +1,114 @@
1
+ /**
2
+ * The daemon's restart: exit with RESTART_EXIT_CODE for its parent (launchd,
3
+ * systemd, the desktop app) to start it again on the CLI on disk, either
4
+ * handing the running services to the next daemon or stopping them first.
5
+ *
6
+ * The first request latches; later ones return true without starting a
7
+ * second exit. If the exit step throws, the daemon exits anyway through
8
+ * `exitNow`. Once a stop has begun, `exitWhenStopped` releases the lock and
9
+ * exits even when the wait for services or jobs rejects.
10
+ */
11
+ function message(error) {
12
+ return error instanceof Error ? error.message : String(error);
13
+ }
14
+ export function createDaemonRestart(deps) {
15
+ let pending = false;
16
+ return () => {
17
+ if (!deps.canRestart()) {
18
+ deps.log("warn", "a restart was requested, but no service manager would start this daemon again; restart it yourself");
19
+ return false;
20
+ }
21
+ if (deps.isStopping() || pending)
22
+ return true;
23
+ pending = true;
24
+ return deps.handoffWanted()
25
+ .catch((err) => {
26
+ deps.log("warn", `could not decide on a handoff; restarting every service: ${message(err)}`);
27
+ return false;
28
+ })
29
+ .then((handoff) => {
30
+ // A stop that began meanwhile (SIGTERM, `hq daemon stop`) wins: no relaunch.
31
+ if (!deps.isStopping()) {
32
+ try {
33
+ deps.beforeExit();
34
+ }
35
+ catch (err) {
36
+ deps.log("error", `could not schedule the relaunch (${message(err)}); exiting for the restart anyway`);
37
+ }
38
+ }
39
+ try {
40
+ if (handoff && deps.handOver)
41
+ deps.handOver();
42
+ else
43
+ deps.shutdown();
44
+ }
45
+ catch (err) {
46
+ deps.log("error", `the restart did not finish stopping (${message(err)}); exiting so the daemon starts again`);
47
+ deps.exitNow(err);
48
+ }
49
+ return true;
50
+ });
51
+ };
52
+ }
53
+ /** A fixed cap on real timers that does not keep the process alive. */
54
+ export function timeoutCap(ms) {
55
+ let timer;
56
+ const promise = new Promise((resolve) => {
57
+ timer = setTimeout(() => resolve("timeout"), ms);
58
+ timer.unref();
59
+ });
60
+ return { promise, clear: () => clearTimeout(timer) };
61
+ }
62
+ /** Wait for the stop, at most until the cap, then release the lock and exit, also when the stop rejects. */
63
+ export function exitWhenStopped(deps, exitCode) {
64
+ return Promise.race([deps.stopped, deps.cap.promise])
65
+ .then((result) => { deps.onSettled?.(result); }, (err) => { deps.log("error", `services or jobs did not stop cleanly (${message(err)}); releasing the lock anyway`); })
66
+ .catch((err) => { deps.log("error", `could not log the stop: ${message(err)}`); })
67
+ .then(() => {
68
+ deps.cap.clear();
69
+ try {
70
+ deps.releaseLock();
71
+ }
72
+ catch (err) {
73
+ deps.log("error", `could not release the daemon lock: ${message(err)}`);
74
+ }
75
+ deps.exit(exitCode);
76
+ });
77
+ }
78
+ /**
79
+ * Services stopped and jobs closed, with the services' result. A rejected jobs
80
+ * promise is logged and counts as closed, so the wait for the services (and
81
+ * a sync runner's persist grace) still runs to its cap.
82
+ */
83
+ export function servicesAndJobsStopped(services, jobs, log) {
84
+ const jobsClosed = jobs.then(() => undefined, (err) => { log("error", `a job did not close cleanly (${message(err)}); still waiting for services`); });
85
+ return Promise.all([services, jobsClosed]).then(([result]) => result);
86
+ }
87
+ export function logServicesStopped(log, result) {
88
+ if (result === "timeout")
89
+ log("error", "some services did not exit after SIGKILL; releasing the lock anyway");
90
+ else
91
+ log("info", "all services stopped");
92
+ }
93
+ /** The restart fallback after handOver or shutdown threw: stop the services with the normal bounded wait, then exit. */
94
+ export function stopServicesAndExit(deps, exitCode) {
95
+ const cap = deps.createCap();
96
+ let stopped = Promise.resolve();
97
+ try {
98
+ if (deps.hasStoppingSyncRunner())
99
+ cap.extendForSyncRunnerPersist?.();
100
+ stopped = deps.stopServices();
101
+ }
102
+ catch (err) {
103
+ deps.log("error", `could not stop services: ${message(err)}`);
104
+ }
105
+ return exitWhenStopped({
106
+ stopped,
107
+ cap,
108
+ releaseLock: deps.releaseLock,
109
+ exit: deps.exit,
110
+ log: deps.log,
111
+ onSettled: (result) => logServicesStopped(deps.log, result),
112
+ }, exitCode);
113
+ }
114
+ //# sourceMappingURL=daemon-restart.js.map
@@ -0,0 +1,41 @@
1
+ import { type HookRequest, type HookRequestResult } from "./hook-requests.js";
2
+ export type WorkMeshShimKind = "work-mesh-register" | "work-mesh-sweep" | "work-mesh-ground" | "work-mesh-close";
3
+ export type WorkMeshShimOperation = {
4
+ kind: "work-mesh-register";
5
+ sessionId: string;
6
+ slug: string;
7
+ uid: string;
8
+ project: string;
9
+ binding: "project" | "adhoc";
10
+ category: string;
11
+ intent: string;
12
+ harness: string;
13
+ } | {
14
+ kind: "work-mesh-sweep";
15
+ } | {
16
+ kind: "work-mesh-ground";
17
+ event: string;
18
+ sessionId: string;
19
+ company: string;
20
+ project: string;
21
+ } | {
22
+ kind: "work-mesh-close";
23
+ sessionId: string;
24
+ hint: string;
25
+ project: string;
26
+ category: string;
27
+ intent: string;
28
+ harness: string;
29
+ summary: string;
30
+ };
31
+ export declare const WORK_MESH_SHIM_SCRIPTS: Readonly<Record<WorkMeshShimKind, string>>;
32
+ export declare const WORK_MESH_SHIM_LOG = "workspace/logs/work-mesh-hook.log";
33
+ export declare function isWorkMeshShimKind(kind: unknown): kind is WorkMeshShimKind;
34
+ export declare function parseWorkMeshShim(kind: WorkMeshShimKind, args: Record<string, unknown>, session: unknown): WorkMeshShimOperation | undefined;
35
+ export declare function runWorkMeshShim(request: HookRequest, operation: WorkMeshShimOperation, base: NodeJS.ProcessEnv, options: {
36
+ signal?: AbortSignal;
37
+ timeoutMs: number;
38
+ killGraceMs: number;
39
+ log?: (message: string) => void;
40
+ }): Promise<HookRequestResult>;
41
+ //# sourceMappingURL=hook-requests-work-mesh-shims.d.ts.map