@indigoai-us/hq-cli 5.345.260 → 5.345.261
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.
- package/CHANGELOG.md +38 -0
- package/assets/scaffold/core/scripts/handoff-post.sh +30 -0
- package/contracts/host-canary-release.json +7 -7
- package/dist/commands/core-delegate-w1b.js +17 -16
- package/dist/commands/core-delegate.js +5 -4
- package/dist/commands/core-handoff.d.ts +10 -0
- package/dist/commands/core-handoff.js +81 -2
- package/dist/lib/doctor/fix/process-identity.d.ts +13 -0
- package/dist/lib/doctor/fix/process-identity.js +63 -7
- package/dist/lib/hook-engine/coverage.d.ts +1 -1
- package/dist/lib/hook-engine/coverage.js +2 -1
- package/dist/utils/delegate-lock.d.ts +18 -0
- package/dist/utils/delegate-lock.js +149 -37
- package/package.json +7 -7
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,44 @@
|
|
|
2
2
|
|
|
3
3
|
## [Unreleased]
|
|
4
4
|
|
|
5
|
+
## [5.345.261] — 2026-11-26
|
|
6
|
+
- Internal: the hq-hook PR test shards, the Grok comparison and the Windows Clippy cross-check run on the autoscaled AWS arm64 pool (`hq-cli-main-priority`) instead of waiting in the fixed `hq-hook-mac` queue, and no longer wait for the Mac route job. `HQ_HOOK_AWS_OVERFLOW=off` puts them back on `hq-hook-mac`; `HQ_HOOK_AWS_SHARDS` is no longer read. The shards install rustfmt with clippy, so the round12 formatter fixture in `credential_grep_sources` can run `cargo fmt` on a fresh runner. Only pull request and train runs cancel a superseded run; the daily schedule never does.
|
|
7
|
+
- Internal: the Windows hq-hook test step in `hq-hook.yml` now runs under `shell: bash` (Git Bash), matching `hq-hook-windows-baseline.yml`, and all three Windows hq-hook workflows verify `awk` is on `PATH` before running tests (CI-only).
|
|
8
|
+
- On hq-agents-v2 bots running the Rust hook engine, the current hq-agents-v2 main hook adapter and the adapter from hq-agents-v2 #364 (JSON deny on `pre_tool_call`) are now known revisions. A tool call under either goes to the adapter instead of being refused natively, so these bots no longer block every tool call after the adapter update. Under the main adapter, SessionEnd, PostToolUse, SubagentStop and SessionStart stay native as under #347; under the #364 adapter every event goes to the adapter. An edited adapter is still refused.
|
|
9
|
+
- Exclude `gtimeout` alongside `timeout` when `command_guards` builds the `no-timeout` test PATH, so macOS hosts with Homebrew coreutils exercise the missing-timeout refusal path.
|
|
10
|
+
- Accept exit code `255` alongside `128`/`129` as git's invalid-option rejection in `credential_grep_sources::grep_recurse_and_pathspec_file_do_not_leak`, matching older Apple Git on macOS for `git diff --pathspec-from-file=...`.
|
|
11
|
+
- Fixed: native delegate locking on Windows no longer spawns PowerShell to acquire, hold, or reclaim dead-process manifest locks, eliminating false "verification or delivery is active" errors when PowerShell is slow or unavailable; when a process identity probe does time out or cannot run, native delegate commands now report that probe failure separately from a held lock.
|
|
12
|
+
- Fixed: `hq-hook` vault-write locale warnings omit the trailing `: <strerror>` suffix when `newlocale` leaves `errno` at 0, matching GNU Bash across Linux and macOS hosts.
|
|
13
|
+
- Fixed quadratic scans in the Rust hook engine's native transcript and field reader (`trigger_facts::native`) that could cause `inject-policy-on-trigger` to time out on large, number-heavy Codex rollout transcripts during `PreToolUse` and `UserPromptSubmit`. `serde_json::Number` literals are now formatted directly in jq's decNumber form without rewriting inputs with textual placeholders or scanning all numbers per transcript event.
|
|
14
|
+
- Clear inherited `GIT_*` environment variables (such as `GIT_CONFIG_GLOBAL=/dev/null` on macOS native CI runners) in `after_turn_suggestions::native_stop_with` so in-process Stop parity matches the clean bash child environment.
|
|
15
|
+
- Exclude host-installed `agent-browser` from `PATH` in `agents_v2_session_start_parity` so `50-agent-browser-presence-check.sh` exercises the missing-browser nudge consistently on machines where `agent-browser` is installed.
|
|
16
|
+
- Detect macOS BSD `awk` `towc` multibyte `substr` crashes at runtime in `gate_native` so UTF-8 prompt-word tests assert the `LC_ALL=C` bash-verified native receipt instead of expecting native to fail open like BSD `awk`.
|
|
17
|
+
- Strip inherited `GIT_*` variables (such as `GIT_CONFIG_GLOBAL=/dev/null` on macOS native CI runners) in `isolated_command::isolate` and `pretool_paths::numbered_sibling_matches_bash_on_every_path_form_and_tool` so `protect-core` sees the same clean environment as bash parity runs.
|
|
18
|
+
- Exclude host-installed `hq` from the test `PATH` in `reindex_hook` so `no hq` cases behave identically on machines where `hq` is installed in `/opt/homebrew/bin` or another `PATH` directory.
|
|
19
|
+
- Use POSIX `touch -t 202001010000` in `session_start_ss1` stale-lock reclamation test so it passes on macOS BSD `touch` as well as Linux and Windows Git Bash.
|
|
20
|
+
- Measure `recorder_all_events::recording_adds_a_small_share_of_the_event_cost` full-vs-empty store overhead using per-child CPU time via `libc::wait4` instead of wall-clock time so the 10% bound stays stable under host CPU contention without widening the threshold.
|
|
21
|
+
- Use the production default `HQ_HQD_SHIM_TIMEOUT_MS` budget in `session_start_hqd_open` parity tests instead of an artificial 300 ms override that starved the pinned bash+perl shim under Mac container load.
|
|
22
|
+
- Strip Windows verbatim `\\?\` prefixes in `scope_bash` test tempdirs and format Bash command path operands in MSYS POSIX form.
|
|
23
|
+
- Fixed: on Windows, fleet-local and agents-v2 tool calls work again with every home folder shape (drive letter, forward slash, `/c/`, `\\?\` and UNC), with `HOME` read the way the adapters' Git Bash reads it.
|
|
24
|
+
- Changed: the host canary record shipped with the CLI is refreshed for this release build.
|
|
25
|
+
- The Rust hook engine now gives company and other folder hooks the same time limit as master-hook on every event. `HQ_MASTER_CHILD_TIMEOUT` (2 s on fleet bots) applies only to events whose hooks cannot block the tool call, such as PostToolUse and SessionStart. PreToolUse, UserPromptSubmit and the other events that can block use `HQ_MASTER_BLOCKING_CHILD_TIMEOUT` (default 120 s), so a slow guard such as a review gate that calls `gh pr view` is no longer cut off into a block. This applies only when the installed master-hook.sh uses the same rule (hq-core-staging #2152); with an older master-hook the engine keeps the old limits, and with a master-hook it cannot read this way it hands the event to master-hook. On fleet bots, the check that decides whether company hooks fit the native time budget now counts only the hooks one tool can start, so Indigo's two PostToolUse hooks (which take different tools) leave 2 s of the 5 s budget spare instead of none. When a hook's tool list cannot be read plainly, for example one with an empty entry such as `Bash,`, the check counts every hook. `hq-hook dispatch` now hands Stop and SubagentStop to master-hook when master-hook applies its shared Stop budget.
|
|
26
|
+
- Internal: inject a deterministic/manual budget clock (`BudgetSource`, `host::RunClock`, `core_next::main_with_clock`) into `hq-hook` dispatch tests (`host::chain`, `host_run` stdin-budget `#3952`, and the five master parity suites `#3954`) so time-budget tests no longer race against wall-clock time under CI load; production `hq-hook` keeps the real monotonic clock, and one real-time wall-clock budget smoke test runs on the nightly Linux schedule (`budget_realtime_perf`).
|
|
27
|
+
- The Rust hook engine's native PreToolUse now accepts the master-hook.sh from hq-core-staging #2152 (the version that gives folder hooks on events that can block their longer time limit). An HQ on that core keeps answering PreToolUse natively instead of falling back to the shell dispatcher.
|
|
28
|
+
- SessionStart folder hooks now get the longer `HQ_MASTER_BLOCKING_CHILD_TIMEOUT` limit (120 s by default, 8 s on fleet bots) in the Rust hook engine instead of `HQ_MASTER_CHILD_TIMEOUT`, matching master-hook.sh from hq-core-staging #2152 at f9a32c25. Native PreToolUse accepts that master-hook.sh in place of its earlier 0bec9205 revision, which kept SessionStart on the short limit; a root still on 0bec9205 hands its events to master-hook.
|
|
29
|
+
- Internal: in `host_run::jq_only_folder_augmentation_allows_benign_denies_protected_and_refuses_absent_jq` Part 7(c), assert that real-binary dispatch resolves the host's fixed candidate `jq` (such as `/opt/homebrew/bin/jq` on macOS) when one exists, and refuses with exit 2 when none exists (test-only).
|
|
30
|
+
- Internal: fix three macOS-native test assumptions in `policy_frontmatter` — symlink sibling `lib/` when copying dynamically linked Homebrew `node` into the headerless `distro-node` prefix (keeping `include/` absent), and probe whether `MallocStackLogging` emits stderr noise on the host `node` before asserting shell exit 2 while keeping native deny assertions unconditional (test-only).
|
|
31
|
+
- Internal: pass explicit `--new` engine command in `precompact_native::replay_finds_no_precompact_difference_on_any_host` so Grok PreCompact replay runs against the dispatcher snapshot without requiring `.grok/hooks/hq-grok-user-bridge.*` (test-only).
|
|
32
|
+
- Reverted: the fleet-local adapter PreToolUse and fleet merged-write-guard-shadow claims from #4000, which blocked fleet-local and direct agents-v2 tool calls on Windows.
|
|
33
|
+
- test(hq-hook): assert documented Windows fail-closed blocks in `credential_guard` parity suite
|
|
34
|
+
- test(hq-hook): expect Claude SessionStart to succeed natively on Windows in `host_run`
|
|
35
|
+
- test(hq-hook): assert fail-closed Windows refusals for POSIX-rooted fixtures in `run_starts_no_interpreter`
|
|
36
|
+
- Fixed: native `hq core handoff post` and its bundled `handoff-post.sh` fallback now apply the same local-only company check before calling `hq sync push`, honoring `company.yaml` `cloud: true` / `cloud: false` (where an explicit `cloud: false` overrides `companies/manifest.yaml`) and `companies/manifest.yaml` `cloud_uid`, and skipping local-only companies with the same log message and exit code.
|
|
37
|
+
- Internal: On Windows, Claude Code SessionStart dispatcher bookkeeping is now handled by the native hook engine.
|
|
38
|
+
- Internal: On Windows, Claude Code UserPromptSubmit dispatcher bookkeeping is now handled by the native hook engine.
|
|
39
|
+
- Claim `lanes-repo-merge-hold` on `fleet-local` and `agents-v2` with the desktop behaviour (owner decision "Same as desktops"): the native check decides from the hold records, refusing held repositories and allowing the rest, and starts no `hq`. The records are also read under the adapter's own HQ root, as the adapters export it. Differential parity tests against `fleet-local-v0.4.33.sh` and `agents-v2-6490142.sh` running the released shim, with each difference from the bot shell path recorded and tested.
|
|
40
|
+
- Fixed Windows path handling in `hq-hook` so drive-rooted, backslash, and verbatim working directories (`C:\...`, `\\?\C:\...`) normalize cleanly across repository-root lookups, path-normalization helpers, and shadow bridge runs without hanging or dropping ordinary paths.
|
|
41
|
+
- On Windows, the env-file guard refuses a bare option-like file name such as `-x.env ` or `-x.env.` that Windows saves as an env file.
|
|
42
|
+
|
|
5
43
|
## [5.345.260] — 2026-11-26
|
|
6
44
|
- Added: `hq reindex`, `hq rescue`, `hq sync` (every hq-cloud `sync()` leg), the first sync of `hq onboard` and the reindex after `hq sync-core reconcile` pass hq-cloud a `companySessions` option. For a person: the `prs_` person uid, the cloud-backed companies and an `uploadEvidence` lookup. For an agent (`HQ_MACHINE_CREDS_FILE`, or `~/.hq-agent/machine-creds.json` with no person session, or an `agt_` sign-in): `{ identity: "agent" }`, so its transcripts stay in its own vault. A company counts as cloud-backed when its `companies/manifest.yaml` entry has a `cmp_` `cloud_uid`, when the new sync engine runs or is handing back its vault, or when its `company.yaml` says `cloud: true` (an unreadable `company.yaml` counts as cloud-backed), and hq-cloud's personal-vault scope (`isCompanyInPersonalVaultScope`, else `computePersonalCompanySubdirs`) does not hold it. `personal` never counts. Folder names follow hq-cloud's rule (`^[A-Za-z0-9_-]+$`). The lookup reads the new sync engine's confirmed-upload ledger (`~/.hq/sync-core/engines/<cmp>/.hq/sync-core/state/push-only-confirmed/<cmp>.json`) for companies the engine owns in full, and answers nothing for companies on the current sync so hq-cloud uses its own journal. The ledger is read only when it and its folders are not symlinks, is at most 16 MiB and is valid JSON; malformed entries are skipped. The person uid is cached in `~/.hq/company-sessions/person-uid.json` for the signed-in account; a reindex from a hook never looks it up over the network, and other commands wait at most 10 s. When the uid is not known the option is left out, and the message, printed once, says company-bound transcripts are held on this computer. Nobody signed in: no option and no message. `HQ_COMPANY_SESSIONS_HOME` replaces the home folder for this routing (the test setup points it at a temp folder). This needs `@indigoai-us/hq-cloud` 6.18.127 (indigoai-us/hq-cloud#1180), which this release bundles.
|
|
7
45
|
- Added: every engine `config.toml` written by `hq sync-core reconcile` carries `person_uid = "prs_..."` under `[sync]` when the person uid is known (resolved, else cached), so the engine uploads `sessions/<uid>/` in company vaults (indigoai-us/hq-sync-core#242). Engines before that release ignore the key.
|
|
@@ -170,9 +170,39 @@ if [[ -n "$THREAD_PATH" && -f "$THREAD_PATH" ]] && command -v hq >/dev/null 2>&1
|
|
|
170
170
|
log "workspace-sync: mirror hook unavailable for handoff thread"
|
|
171
171
|
fi
|
|
172
172
|
fi
|
|
173
|
+
# handoff_company_is_cloud <slug> — true when the company has a cloud vault.
|
|
174
|
+
# company.yaml `cloud: true` says so directly. Many cloud companies have no
|
|
175
|
+
# company.yaml (or no cloud: line) and are known only by their manifest
|
|
176
|
+
# cloud_uid; they used to be skipped as local-only
|
|
177
|
+
# (feedback_98f2ce49-5065-4670-8544-1a3dccd9985e). An explicit `cloud: false`
|
|
178
|
+
# still wins over the manifest.
|
|
179
|
+
handoff_company_is_cloud() {
|
|
180
|
+
local co="$1" yaml="$HQ_ROOT/companies/$1/company.yaml"
|
|
181
|
+
if [[ -f "$yaml" ]]; then
|
|
182
|
+
grep -Eq '^cloud:[[:space:]]*"?true"?([[:space:]]|#|$)' "$yaml" && return 0
|
|
183
|
+
grep -Eq '^cloud:[[:space:]]*"?false"?([[:space:]]|#|$)' "$yaml" && return 1
|
|
184
|
+
fi
|
|
185
|
+
[[ -f "$HQ_ROOT/companies/manifest.yaml" ]] || return 1
|
|
186
|
+
awk -v co="$co" '
|
|
187
|
+
/^[^[:space:]#]/ { in_companies = ($0 ~ /^companies:[[:space:]]*$/); in_co = 0; next }
|
|
188
|
+
in_companies && /^ [^[:space:]#][^:]*:/ { k = $1; sub(/:$/, "", k); gsub(/["\047]/, "", k); in_co = (k == co); next }
|
|
189
|
+
in_companies && in_co && /^ cloud_uid:/ {
|
|
190
|
+
v = $0; sub(/^ cloud_uid:[[:space:]]*/, "", v); gsub(/["\047\r[:space:]]/, "", v)
|
|
191
|
+
if (v != "" && v != "null" && v != "~") found = 1
|
|
192
|
+
}
|
|
193
|
+
END { exit !found }
|
|
194
|
+
' "$HQ_ROOT/companies/manifest.yaml"
|
|
195
|
+
}
|
|
173
196
|
while IFS= read -r company; do
|
|
174
197
|
[[ "$company" =~ ^[a-z][a-z0-9_-]*$ ]] || continue
|
|
175
198
|
[[ -d "$HQ_ROOT/companies/$company/workspace" ]] || continue
|
|
199
|
+
# Local-only companies have no cloud vault. Pushing them fails with
|
|
200
|
+
# "No entity in caller's namespace matches company/<slug>" and a
|
|
201
|
+
# wrong-identity hint even when the operator is signed in correctly.
|
|
202
|
+
if ! handoff_company_is_cloud "$company"; then
|
|
203
|
+
log "workspace-sync: skipped (company is local-only: no cloud: true and no manifest cloud_uid)"
|
|
204
|
+
continue
|
|
205
|
+
fi
|
|
176
206
|
if [[ "$THREAD_MIRRORABLE" != "true" || \
|
|
177
207
|
! -f "$HQ_ROOT/companies/$company/workspace/sessions/$THREAD_ID.json" ]]; then
|
|
178
208
|
log "workspace-sync: skipped (thread mirror missing for $company)"
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
{
|
|
2
2
|
"schema": "hq.host-canary-release.v1",
|
|
3
|
-
"cliVersion": "5.345.
|
|
3
|
+
"cliVersion": "5.345.261",
|
|
4
4
|
"hosts": {
|
|
5
5
|
"claude": [
|
|
6
6
|
{
|
|
7
7
|
"passed": true,
|
|
8
|
-
"at": "2026-11-
|
|
9
|
-
"engineVersion": "0.3.1+hq.5.345.
|
|
8
|
+
"at": "2026-11-26T12:12:28.930Z",
|
|
9
|
+
"engineVersion": "0.3.1+hq.5.345.261.src.6599dfcb673f514942b5a9bc7aea662654013c5013127224466562049bb8da9c",
|
|
10
10
|
"gateSha256": "a2879dfe692233f5953bac86672947bbd82f3c5247292f3efcb80f16c3d2c6b1"
|
|
11
11
|
},
|
|
12
12
|
{
|
|
13
13
|
"passed": true,
|
|
14
|
-
"at": "2026-11-
|
|
15
|
-
"engineVersion": "0.3.1+hq.5.345.
|
|
14
|
+
"at": "2026-11-26T12:12:55.594Z",
|
|
15
|
+
"engineVersion": "0.3.1+hq.5.345.261.src.6599dfcb673f514942b5a9bc7aea662654013c5013127224466562049bb8da9c",
|
|
16
16
|
"gateSha256": "ca58a94859eae0a345c11c8d9c59303eb76350dc1cf223391037d21979c28718"
|
|
17
17
|
},
|
|
18
18
|
{
|
|
19
19
|
"passed": true,
|
|
20
|
-
"at": "2026-11-
|
|
21
|
-
"engineVersion": "0.3.1+hq.5.345.
|
|
20
|
+
"at": "2026-11-26T12:13:22.264Z",
|
|
21
|
+
"engineVersion": "0.3.1+hq.5.345.261.src.6599dfcb673f514942b5a9bc7aea662654013c5013127224466562049bb8da9c",
|
|
22
22
|
"gateSha256": "ecdbab7c2e0a1d94eb9c98f15e760390f215bc7115a217ded24b4275322722d2"
|
|
23
23
|
}
|
|
24
24
|
]
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/** Native implementations of the second Wave 1 delegate command family. */
|
|
2
2
|
import { daemonWhoamiOutput } from "../lib/daemon/whoami-cache.js";
|
|
3
3
|
import { createHash, randomBytes, randomInt } from "node:crypto";
|
|
4
|
-
import {
|
|
4
|
+
import { acquireDelegateLockDetailed, formatDelegateLockError } from "../utils/delegate-lock.js";
|
|
5
5
|
import * as fs from "node:fs";
|
|
6
6
|
import * as os from "node:os";
|
|
7
7
|
import * as path from "node:path";
|
|
@@ -516,9 +516,6 @@ function writeBundle(context, input) {
|
|
|
516
516
|
function runHq(args, context, stdout = "capture", timeout) {
|
|
517
517
|
return subprocess("hq", args, context.cwd, { stdout, timeout });
|
|
518
518
|
}
|
|
519
|
-
function delegateLockBusy() {
|
|
520
|
-
return "verification or delivery is active; retry after it finishes";
|
|
521
|
-
}
|
|
522
519
|
const runJq = createShellCompatibleJqInvoker((args, input, cwd, options) => subprocess("jq", args, cwd, { input, ...options }), process.platform, process.env, (cwd) => {
|
|
523
520
|
const bash = resolveWindowsBash(process.env).executable;
|
|
524
521
|
if (!bash)
|
|
@@ -741,9 +738,10 @@ function runGrant(args, context) {
|
|
|
741
738
|
if (!fs.existsSync(manifestPath) || !fs.statSync(manifestPath).isFile())
|
|
742
739
|
return fail("grant", `manifest not found: ${delegateDiagnosticPath(manifestPath)}`);
|
|
743
740
|
const lock = `${manifestPath}.send-lock`;
|
|
744
|
-
const
|
|
745
|
-
if (
|
|
746
|
-
return fail("grant",
|
|
741
|
+
const acquired = yes ? acquireDelegateLockDetailed(lock) : null;
|
|
742
|
+
if (acquired && !acquired.ok)
|
|
743
|
+
return fail("grant", formatDelegateLockError(acquired));
|
|
744
|
+
const held = acquired?.ok ? acquired.lock : null;
|
|
747
745
|
const grantHq = (args, ctx, stdout = "capture") => runHq(args, ctx, stdout, 120_000);
|
|
748
746
|
try {
|
|
749
747
|
let manifest;
|
|
@@ -1126,9 +1124,10 @@ function runPublish(args, context, legacyHandoff, nativeLock) {
|
|
|
1126
1124
|
return fail("publish", "verification lock missing");
|
|
1127
1125
|
}
|
|
1128
1126
|
else {
|
|
1129
|
-
|
|
1130
|
-
if (!
|
|
1131
|
-
return fail("publish",
|
|
1127
|
+
const acquired = acquireDelegateLockDetailed(lock);
|
|
1128
|
+
if (!acquired.ok)
|
|
1129
|
+
return fail("publish", formatDelegateLockError(acquired));
|
|
1130
|
+
ownedLock = acquired.lock;
|
|
1132
1131
|
if (args.length !== 2) {
|
|
1133
1132
|
ownedLock.release();
|
|
1134
1133
|
return fail("publish", "usage: --manifest <path>");
|
|
@@ -1339,9 +1338,10 @@ function runSend(args, context) {
|
|
|
1339
1338
|
if (reconcile)
|
|
1340
1339
|
return reconcileSend(manifestPath, reconcile, context);
|
|
1341
1340
|
const lock = `${manifestPath}.send-lock`;
|
|
1342
|
-
const
|
|
1343
|
-
if (
|
|
1344
|
-
return fail("send",
|
|
1341
|
+
const acquired = send ? acquireDelegateLockDetailed(lock) : null;
|
|
1342
|
+
if (acquired && !acquired.ok)
|
|
1343
|
+
return fail("send", formatDelegateLockError(acquired));
|
|
1344
|
+
const held = acquired?.ok ? acquired.lock : null;
|
|
1345
1345
|
let lockRemoved = false;
|
|
1346
1346
|
const removeLock = () => {
|
|
1347
1347
|
if (!send || lockRemoved)
|
|
@@ -1646,9 +1646,10 @@ function runVerify(args, context) {
|
|
|
1646
1646
|
if (!manifest)
|
|
1647
1647
|
return fail("verify", `jq: error: ${delegateDiagnosticPath(manifestPath)}: Invalid JSON`);
|
|
1648
1648
|
const lock = `${manifestPath}.send-lock`;
|
|
1649
|
-
const
|
|
1650
|
-
if (!
|
|
1651
|
-
return fail("verify",
|
|
1649
|
+
const acquired = acquireDelegateLockDetailed(lock);
|
|
1650
|
+
if (!acquired.ok)
|
|
1651
|
+
return fail("verify", formatDelegateLockError(acquired));
|
|
1652
|
+
const held = acquired.lock;
|
|
1652
1653
|
let cache = "";
|
|
1653
1654
|
try {
|
|
1654
1655
|
const company = jqRawPath(manifest, "company");
|
|
@@ -11,7 +11,7 @@ import { resolveWindowsExecutable } from "../lib/bot/runtime/windows.js";
|
|
|
11
11
|
import { buildCmdExeSpawnPlan, isWindowsBatchFile } from "../utils/windows-spawn.js";
|
|
12
12
|
import { describeCoreCommand } from "./core-command-catalog.js";
|
|
13
13
|
import { resolveLiveRoot } from "../utils/hq-roots.js";
|
|
14
|
-
import {
|
|
14
|
+
import { acquireDelegateLockDetailed, formatDelegateLockError } from "../utils/delegate-lock.js";
|
|
15
15
|
import { runBundledScript } from "../utils/run-bundled-script.js";
|
|
16
16
|
import { brainstormFrontmatterSet, brainstormSummary, brainstormTitle } from "./core-delegate-brainstorm.js";
|
|
17
17
|
import { delegateBoardPath, delegateRepoDirectory, secretsSourcePaths } from "../lib/core-utils/delegate-helper-paths.js";
|
|
@@ -1302,11 +1302,12 @@ export function runNative(name, args, context) {
|
|
|
1302
1302
|
writeErr(`hq-delegate-${name}: cannot check the manifest before locking it\n`);
|
|
1303
1303
|
return 1;
|
|
1304
1304
|
}
|
|
1305
|
-
const
|
|
1306
|
-
if (!
|
|
1307
|
-
writeErr(`hq-delegate-${name}:
|
|
1305
|
+
const acquired = acquireDelegateLockDetailed(`${file}.send-lock`);
|
|
1306
|
+
if (!acquired.ok) {
|
|
1307
|
+
writeErr(`hq-delegate-${name}: ${formatDelegateLockError(acquired)}\n`);
|
|
1308
1308
|
return 1;
|
|
1309
1309
|
}
|
|
1310
|
+
const lock = acquired.lock;
|
|
1310
1311
|
try {
|
|
1311
1312
|
return runNativeUnlocked(name, args, context);
|
|
1312
1313
|
}
|
|
@@ -20,6 +20,16 @@ type HandoffContext = {
|
|
|
20
20
|
};
|
|
21
21
|
export declare function boundSessionCompany(root: string): string;
|
|
22
22
|
export declare function runHandoffFinalize(args: string[], context: HandoffContext): RunResult;
|
|
23
|
+
/**
|
|
24
|
+
* Matches `handoff_company_is_cloud` in hq-core's `core/scripts/handoff-post.sh`:
|
|
25
|
+
* 1. `companies/<slug>/company.yaml`: `cloud: true` wins immediately; an
|
|
26
|
+
* explicit `cloud: false` keeps the company local even if manifest.yaml
|
|
27
|
+
* carries a `cloud_uid`.
|
|
28
|
+
* 2. `companies/manifest.yaml`: under `companies:` -> ` <slug>:` ->
|
|
29
|
+
* ` cloud_uid:` with a non-empty value that is neither `null` nor `~`.
|
|
30
|
+
* 3. Otherwise local-only (returns false).
|
|
31
|
+
*/
|
|
32
|
+
export declare function handoffCompanyIsCloud(root: string, company: string): boolean;
|
|
23
33
|
export declare function runHandoffPost(args: string[], context: HandoffContext): RunResult | Promise<RunResult>;
|
|
24
34
|
export declare function runHandoffPostWorker(args: string[], context: HandoffContext): RunResult;
|
|
25
35
|
export declare function runHandoffPointerCompany(args: string[], context: HandoffContext): RunResult;
|
|
@@ -2140,6 +2140,79 @@ function spawnBashDetached(script, args, cwd, root, logFile) {
|
|
|
2140
2140
|
}
|
|
2141
2141
|
}
|
|
2142
2142
|
}
|
|
2143
|
+
const CLOUD_YAML_SPACE = "[\\t\\v\\f\\r ]";
|
|
2144
|
+
const CLOUD_YAML_TRUE_RE = new RegExp(`^cloud:${CLOUD_YAML_SPACE}*"?true"?(?:${CLOUD_YAML_SPACE}|#|$)`);
|
|
2145
|
+
const CLOUD_YAML_FALSE_RE = new RegExp(`^cloud:${CLOUD_YAML_SPACE}*"?false"?(?:${CLOUD_YAML_SPACE}|#|$)`);
|
|
2146
|
+
const MANIFEST_TOP_LEVEL_RE = /^[^\t\v\f\r #]/;
|
|
2147
|
+
const MANIFEST_COMPANIES_HEADER_RE = new RegExp(`^companies:${CLOUD_YAML_SPACE}*$`);
|
|
2148
|
+
const MANIFEST_COMPANY_KEY_RE = /^ {2}[^\t\v\f\r #][^:]*:/;
|
|
2149
|
+
const MANIFEST_CLOUD_UID_PREFIX_RE = new RegExp(`^ {4}cloud_uid:${CLOUD_YAML_SPACE}*`);
|
|
2150
|
+
const MANIFEST_CLOUD_UID_STRIP_RE = /["'\t\v\f\r ]/g;
|
|
2151
|
+
/**
|
|
2152
|
+
* Matches `handoff_company_is_cloud` in hq-core's `core/scripts/handoff-post.sh`:
|
|
2153
|
+
* 1. `companies/<slug>/company.yaml`: `cloud: true` wins immediately; an
|
|
2154
|
+
* explicit `cloud: false` keeps the company local even if manifest.yaml
|
|
2155
|
+
* carries a `cloud_uid`.
|
|
2156
|
+
* 2. `companies/manifest.yaml`: under `companies:` -> ` <slug>:` ->
|
|
2157
|
+
* ` cloud_uid:` with a non-empty value that is neither `null` nor `~`.
|
|
2158
|
+
* 3. Otherwise local-only (returns false).
|
|
2159
|
+
*/
|
|
2160
|
+
export function handoffCompanyIsCloud(root, company) {
|
|
2161
|
+
if (!/^[a-z0-9][a-z0-9_-]*$/.test(company))
|
|
2162
|
+
return false;
|
|
2163
|
+
const companyYaml = path.join(root, "companies", company, "company.yaml");
|
|
2164
|
+
if (isFile(companyYaml)) {
|
|
2165
|
+
let content;
|
|
2166
|
+
try {
|
|
2167
|
+
content = fs.readFileSync(companyYaml, "utf8");
|
|
2168
|
+
}
|
|
2169
|
+
catch {
|
|
2170
|
+
content = undefined;
|
|
2171
|
+
}
|
|
2172
|
+
if (content !== undefined) {
|
|
2173
|
+
const lines = content.split("\n");
|
|
2174
|
+
if (lines.some((line) => CLOUD_YAML_TRUE_RE.test(line)))
|
|
2175
|
+
return true;
|
|
2176
|
+
if (lines.some((line) => CLOUD_YAML_FALSE_RE.test(line)))
|
|
2177
|
+
return false;
|
|
2178
|
+
}
|
|
2179
|
+
}
|
|
2180
|
+
const manifestPath = path.join(root, "companies", "manifest.yaml");
|
|
2181
|
+
if (!isFile(manifestPath))
|
|
2182
|
+
return false;
|
|
2183
|
+
let manifest;
|
|
2184
|
+
try {
|
|
2185
|
+
manifest = fs.readFileSync(manifestPath, "utf8");
|
|
2186
|
+
}
|
|
2187
|
+
catch {
|
|
2188
|
+
return false;
|
|
2189
|
+
}
|
|
2190
|
+
let inCompanies = false;
|
|
2191
|
+
let inCompany = false;
|
|
2192
|
+
let found = false;
|
|
2193
|
+
for (const line of manifest.split("\n")) {
|
|
2194
|
+
if (MANIFEST_TOP_LEVEL_RE.test(line)) {
|
|
2195
|
+
inCompanies = MANIFEST_COMPANIES_HEADER_RE.test(line);
|
|
2196
|
+
inCompany = false;
|
|
2197
|
+
continue;
|
|
2198
|
+
}
|
|
2199
|
+
if (inCompanies && MANIFEST_COMPANY_KEY_RE.test(line)) {
|
|
2200
|
+
const firstField = line.slice(2).split(/[ \t]+/)[0] ?? "";
|
|
2201
|
+
const key = firstField.replace(/:$/, "").replace(/["']/g, "");
|
|
2202
|
+
inCompany = key === company;
|
|
2203
|
+
continue;
|
|
2204
|
+
}
|
|
2205
|
+
if (inCompanies && inCompany && line.startsWith(" cloud_uid:")) {
|
|
2206
|
+
const value = line
|
|
2207
|
+
.replace(MANIFEST_CLOUD_UID_PREFIX_RE, "")
|
|
2208
|
+
.replace(MANIFEST_CLOUD_UID_STRIP_RE, "");
|
|
2209
|
+
if (value !== "" && value !== "null" && value !== "~") {
|
|
2210
|
+
found = true;
|
|
2211
|
+
}
|
|
2212
|
+
}
|
|
2213
|
+
}
|
|
2214
|
+
return found;
|
|
2215
|
+
}
|
|
2143
2216
|
function parseLearningCount(file) {
|
|
2144
2217
|
try {
|
|
2145
2218
|
const value = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
@@ -2314,9 +2387,15 @@ export function runHandoffPostWorker(args, context) {
|
|
|
2314
2387
|
log("workspace-sync: mirror hook unavailable for handoff thread");
|
|
2315
2388
|
}
|
|
2316
2389
|
for (const company of syncCompanies) {
|
|
2317
|
-
if (!
|
|
2390
|
+
if (!POST_COMPANY_SLUG_RE.test(company))
|
|
2318
2391
|
continue;
|
|
2319
|
-
if (!
|
|
2392
|
+
if (!isDirectory(path.join(root, "companies", company, "workspace")))
|
|
2393
|
+
continue;
|
|
2394
|
+
if (!handoffCompanyIsCloud(root, company)) {
|
|
2395
|
+
log("workspace-sync: skipped (company is local-only: no cloud: true and no manifest cloud_uid)");
|
|
2396
|
+
continue;
|
|
2397
|
+
}
|
|
2398
|
+
if (!threadMirrorable || !isFile(path.join(root, "companies", company, "workspace/sessions", `${threadId}.json`))) {
|
|
2320
2399
|
log(`workspace-sync: skipped (thread mirror missing for ${company})`);
|
|
2321
2400
|
continue;
|
|
2322
2401
|
}
|
|
@@ -2,13 +2,26 @@
|
|
|
2
2
|
* Process start times, used to tell the owner of a pid from a later process
|
|
3
3
|
* that reused it (feedback cd56a501).
|
|
4
4
|
*/
|
|
5
|
+
import { spawnSync } from "node:child_process";
|
|
5
6
|
import type { RefreshOwnerIdentity } from "./refresh-sync-handoff.js";
|
|
6
7
|
/** Inputs for locating the system process tool; tests inject them. */
|
|
7
8
|
export interface ProcessToolProbe {
|
|
8
9
|
platform?: NodeJS.Platform;
|
|
9
10
|
env?: NodeJS.ProcessEnv;
|
|
10
11
|
isExecutable?: (file: string) => boolean;
|
|
12
|
+
spawn?: typeof spawnSync;
|
|
11
13
|
}
|
|
14
|
+
export type ProcessStartFailureReason = "invalid-pid" | "tool-missing" | "timeout" | "failed";
|
|
15
|
+
export interface ProcessStartFailure {
|
|
16
|
+
pid: number;
|
|
17
|
+
reason: ProcessStartFailureReason;
|
|
18
|
+
tool?: string;
|
|
19
|
+
detail?: string;
|
|
20
|
+
}
|
|
21
|
+
/** Details of the most recent failed {@link processStartTime} call, or null if the last call succeeded. */
|
|
22
|
+
export declare function lastProcessStartFailure(): ProcessStartFailure | null;
|
|
23
|
+
/** Test seam: clear cached self start time and last failure state. */
|
|
24
|
+
export declare function resetProcessStartTimeCache(): void;
|
|
12
25
|
/** The fixed POSIX locations of `ps`, tried in order. */
|
|
13
26
|
export declare const POSIX_PS_PATHS: readonly string[];
|
|
14
27
|
/**
|
|
@@ -5,6 +5,17 @@
|
|
|
5
5
|
import { spawnSync } from "node:child_process";
|
|
6
6
|
import * as fs from "node:fs";
|
|
7
7
|
import * as path from "node:path";
|
|
8
|
+
let cachedSelfStart = null;
|
|
9
|
+
let lastFailure = null;
|
|
10
|
+
/** Details of the most recent failed {@link processStartTime} call, or null if the last call succeeded. */
|
|
11
|
+
export function lastProcessStartFailure() {
|
|
12
|
+
return lastFailure;
|
|
13
|
+
}
|
|
14
|
+
/** Test seam: clear cached self start time and last failure state. */
|
|
15
|
+
export function resetProcessStartTimeCache() {
|
|
16
|
+
cachedSelfStart = null;
|
|
17
|
+
lastFailure = null;
|
|
18
|
+
}
|
|
8
19
|
/** The fixed POSIX locations of `ps`, tried in order. */
|
|
9
20
|
export const POSIX_PS_PATHS = ["/bin/ps", "/usr/bin/ps"];
|
|
10
21
|
function defaultIsExecutable(platform) {
|
|
@@ -47,25 +58,70 @@ export function processStartTool(probe = {}) {
|
|
|
47
58
|
* null, which lock callers treat as busy.
|
|
48
59
|
*/
|
|
49
60
|
export function processStartTime(pid, probe = {}) {
|
|
50
|
-
|
|
61
|
+
lastFailure = null;
|
|
62
|
+
const useCache = pid === process.pid &&
|
|
63
|
+
probe.platform === undefined &&
|
|
64
|
+
probe.env === undefined &&
|
|
65
|
+
probe.isExecutable === undefined &&
|
|
66
|
+
probe.spawn === undefined;
|
|
67
|
+
if (useCache && cachedSelfStart && cachedSelfStart.pid === process.pid) {
|
|
68
|
+
return cachedSelfStart.start;
|
|
69
|
+
}
|
|
70
|
+
if (!Number.isInteger(pid) || pid <= 0) {
|
|
71
|
+
lastFailure = { pid, reason: "invalid-pid", detail: "invalid process id" };
|
|
51
72
|
return null;
|
|
73
|
+
}
|
|
74
|
+
const platform = probe.platform ?? process.platform;
|
|
52
75
|
const tool = processStartTool(probe);
|
|
53
|
-
if (!tool)
|
|
76
|
+
if (!tool) {
|
|
77
|
+
lastFailure = {
|
|
78
|
+
pid,
|
|
79
|
+
reason: "tool-missing",
|
|
80
|
+
detail: platform === "win32" ? "powershell.exe not found" : "ps not found",
|
|
81
|
+
};
|
|
54
82
|
return null;
|
|
55
|
-
|
|
83
|
+
}
|
|
84
|
+
const runSpawn = probe.spawn ?? spawnSync;
|
|
56
85
|
try {
|
|
57
86
|
const result = platform === "win32"
|
|
58
|
-
?
|
|
87
|
+
? runSpawn(tool, [
|
|
59
88
|
"-NoProfile",
|
|
60
89
|
"-NonInteractive",
|
|
61
90
|
"-Command",
|
|
62
91
|
`(Get-Process -Id ${pid} -ErrorAction Stop).StartTime.ToUniversalTime().ToString('o')`,
|
|
63
92
|
], { encoding: "utf8", timeout: 10_000, windowsHide: true })
|
|
64
|
-
:
|
|
93
|
+
: runSpawn(tool, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000 });
|
|
65
94
|
const text = (result.stdout ?? "").trim();
|
|
66
|
-
|
|
95
|
+
if (result.status === 0 && text) {
|
|
96
|
+
if (useCache)
|
|
97
|
+
cachedSelfStart = { pid: process.pid, start: text };
|
|
98
|
+
return text;
|
|
99
|
+
}
|
|
100
|
+
const errCode = result.error?.code;
|
|
101
|
+
if (errCode === "ETIMEDOUT") {
|
|
102
|
+
lastFailure = { pid, reason: "timeout", tool, detail: `${path.basename(tool)} timed out` };
|
|
103
|
+
}
|
|
104
|
+
else if (result.error) {
|
|
105
|
+
lastFailure = { pid, reason: "failed", tool, detail: errCode || result.error.message };
|
|
106
|
+
}
|
|
107
|
+
else {
|
|
108
|
+
lastFailure = {
|
|
109
|
+
pid,
|
|
110
|
+
reason: "failed",
|
|
111
|
+
tool,
|
|
112
|
+
detail: result.signal ? `signal ${result.signal}` : `exit ${result.status ?? "unknown"}`,
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
67
116
|
}
|
|
68
|
-
catch {
|
|
117
|
+
catch (error) {
|
|
118
|
+
const errCode = error?.code;
|
|
119
|
+
lastFailure = {
|
|
120
|
+
pid,
|
|
121
|
+
reason: "failed",
|
|
122
|
+
tool,
|
|
123
|
+
detail: errCode || (error instanceof Error ? error.message : String(error)),
|
|
124
|
+
};
|
|
69
125
|
return null;
|
|
70
126
|
}
|
|
71
127
|
}
|
|
@@ -312,7 +312,7 @@ export declare function grokPreToolUseHold(root: string, shadow: boolean): strin
|
|
|
312
312
|
/**
|
|
313
313
|
* The dispatcher files the native PreToolUse master model reproduces, in its check order:
|
|
314
314
|
* crates/hq-hook/src/pre_tool_use_master.rs `DISPATCHER_PINS`. master-hook.sh is v16.0.48 (1a2439ae),
|
|
315
|
-
* v16.0.50 (774bca73), v16.0.49 (d5049d5f), v16.0.51 (443272ef) or v16.0.52 (ab46ebdf; v16.0.51 plus a PostToolUse-only
|
|
315
|
+
* v16.0.50 (774bca73), v16.0.49 (d5049d5f), v16.0.51 (443272ef) or v16.0.52 (ab46ebdf, and hq-core-staging #2152's f9a32c25, which only scopes the folder hook limit by event; v16.0.51 plus a PostToolUse-only
|
|
316
316
|
* prefilter text for MCP tools), whose session-id alias record the native bind writes too; hook-adapter-core.sh is held per host below; hqd-hook-shim.sh is the released ab289ac0 or the
|
|
317
317
|
* hq-core-staging fd709b39a ee5e9fe7, and session-id.sh the released 2ebbc508 or the fd709b39a
|
|
318
318
|
* d6a04155; every other file is one revision.
|
|
@@ -2113,7 +2113,7 @@ export function grokPreToolUseHold(root, shadow) {
|
|
|
2113
2113
|
/**
|
|
2114
2114
|
* The dispatcher files the native PreToolUse master model reproduces, in its check order:
|
|
2115
2115
|
* crates/hq-hook/src/pre_tool_use_master.rs `DISPATCHER_PINS`. master-hook.sh is v16.0.48 (1a2439ae),
|
|
2116
|
-
* v16.0.50 (774bca73), v16.0.49 (d5049d5f), v16.0.51 (443272ef) or v16.0.52 (ab46ebdf; v16.0.51 plus a PostToolUse-only
|
|
2116
|
+
* v16.0.50 (774bca73), v16.0.49 (d5049d5f), v16.0.51 (443272ef) or v16.0.52 (ab46ebdf, and hq-core-staging #2152's f9a32c25, which only scopes the folder hook limit by event; v16.0.51 plus a PostToolUse-only
|
|
2117
2117
|
* prefilter text for MCP tools), whose session-id alias record the native bind writes too; hook-adapter-core.sh is held per host below; hqd-hook-shim.sh is the released ab289ac0 or the
|
|
2118
2118
|
* hq-core-staging fd709b39a ee5e9fe7, and session-id.sh the released 2ebbc508 or the fd709b39a
|
|
2119
2119
|
* d6a04155; every other file is one revision.
|
|
@@ -2144,6 +2144,7 @@ export const PRE_TOOL_USE_DISPATCHER_PINS = [
|
|
|
2144
2144
|
'd5049d5fb38d2b33467d493a4a136df8f6d9021c29e722df0d1e6a17d7f452ab',
|
|
2145
2145
|
'443272ef7642d87b6833bc97b71350502491445cd09b26be9f45140804368b00',
|
|
2146
2146
|
'ab46ebdf0cc84a90dd95a54417817f9f9023b109d5b3710c472a8f5e89061592',
|
|
2147
|
+
'f9a32c25f5984856a1bb91a7914495577e505c42a8c02831acf8faf049a9a806',
|
|
2147
2148
|
],
|
|
2148
2149
|
},
|
|
2149
2150
|
{ relative: '.claude/hooks/turn-timing.sh', accepted: ['97c70a3251225ba9e469e41fd3fe2341cfe2936490f54571d2ca16de8e766443'] },
|
|
@@ -2,10 +2,28 @@ export interface DelegateLockOptions {
|
|
|
2
2
|
now?: () => number;
|
|
3
3
|
startOf?: (pid: number) => string | null;
|
|
4
4
|
alive?: (pid: number) => boolean;
|
|
5
|
+
platform?: NodeJS.Platform;
|
|
5
6
|
}
|
|
6
7
|
export interface DelegateLock {
|
|
7
8
|
release(): void;
|
|
8
9
|
}
|
|
10
|
+
export type DelegateLockFailureReason = 'busy' | 'identity-unavailable' | 'error';
|
|
11
|
+
export type DelegateLockResult = {
|
|
12
|
+
ok: true;
|
|
13
|
+
lock: DelegateLock;
|
|
14
|
+
} | {
|
|
15
|
+
ok: false;
|
|
16
|
+
reason: DelegateLockFailureReason;
|
|
17
|
+
timedOut?: boolean;
|
|
18
|
+
detail?: string;
|
|
19
|
+
};
|
|
20
|
+
export declare function formatDelegateLockError(failure: Extract<DelegateLockResult, {
|
|
21
|
+
ok: false;
|
|
22
|
+
}>): string;
|
|
23
|
+
/** A complete owner file is linked into place atomically. Legacy mkdir writers
|
|
24
|
+
* see EEXIST; unknown legacy directories stay held. Returns a structured result
|
|
25
|
+
* so callers can tell a held lock apart from a probe timeout or I/O error. */
|
|
26
|
+
export declare function acquireDelegateLockDetailed(lock: string, options?: DelegateLockOptions): DelegateLockResult;
|
|
9
27
|
/** A complete owner file is linked into place atomically. Legacy mkdir writers
|
|
10
28
|
* see EEXIST; unknown legacy directories stay held. */
|
|
11
29
|
export declare function acquireDelegateLock(lock: string, options?: DelegateLockOptions): DelegateLock | null;
|
|
@@ -1,11 +1,30 @@
|
|
|
1
1
|
import * as fs from 'node:fs';
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { acquireUpdateLock } from './update-lock.js';
|
|
4
|
-
import
|
|
4
|
+
import * as processIdentity from '../lib/doctor/fix/process-identity.js';
|
|
5
|
+
export function formatDelegateLockError(failure) {
|
|
6
|
+
if (failure.reason === 'busy') {
|
|
7
|
+
return 'verification or delivery is active; retry after it finishes';
|
|
8
|
+
}
|
|
9
|
+
if (failure.reason === 'identity-unavailable') {
|
|
10
|
+
if (failure.timedOut) {
|
|
11
|
+
return 'could not acquire delegate lock: process identity check timed out';
|
|
12
|
+
}
|
|
13
|
+
return failure.detail
|
|
14
|
+
? `could not acquire delegate lock: process identity check unavailable (${failure.detail})`
|
|
15
|
+
: 'could not acquire delegate lock: process identity check unavailable';
|
|
16
|
+
}
|
|
17
|
+
return failure.detail
|
|
18
|
+
? `could not acquire delegate lock: ${failure.detail}`
|
|
19
|
+
: 'could not acquire delegate lock';
|
|
20
|
+
}
|
|
5
21
|
/** A complete owner file is linked into place atomically. Legacy mkdir writers
|
|
6
|
-
* see EEXIST; unknown legacy directories stay held.
|
|
7
|
-
|
|
8
|
-
|
|
22
|
+
* see EEXIST; unknown legacy directories stay held. Returns a structured result
|
|
23
|
+
* so callers can tell a held lock apart from a probe timeout or I/O error. */
|
|
24
|
+
export function acquireDelegateLockDetailed(lock, options = {}) {
|
|
25
|
+
const platform = options.platform ?? process.platform;
|
|
26
|
+
const explicitStartOf = options.startOf;
|
|
27
|
+
const startOf = explicitStartOf ?? ((pid) => processIdentity.processStartTime(pid));
|
|
9
28
|
const now = options.now ?? Date.now;
|
|
10
29
|
const alive = options.alive ?? ((pid) => {
|
|
11
30
|
try {
|
|
@@ -16,15 +35,50 @@ export function acquireDelegateLock(lock, options = {}) {
|
|
|
16
35
|
return error.code !== 'ESRCH';
|
|
17
36
|
}
|
|
18
37
|
});
|
|
19
|
-
const
|
|
20
|
-
|
|
21
|
-
|
|
38
|
+
const probeStart = (pid) => {
|
|
39
|
+
const start = startOf(pid);
|
|
40
|
+
if (start)
|
|
41
|
+
return { start, timedOut: false, toolUnavailable: false };
|
|
42
|
+
if (!explicitStartOf && typeof processIdentity.lastProcessStartFailure === 'function') {
|
|
43
|
+
const failure = processIdentity.lastProcessStartFailure();
|
|
44
|
+
if (failure && failure.pid === pid) {
|
|
45
|
+
return {
|
|
46
|
+
start: null,
|
|
47
|
+
timedOut: failure.reason === 'timeout',
|
|
48
|
+
detail: failure.detail,
|
|
49
|
+
toolUnavailable: failure.reason === 'timeout' || failure.reason === 'tool-missing',
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return { start: null, timedOut: false, toolUnavailable: false };
|
|
54
|
+
};
|
|
55
|
+
// On Windows, reading process start times requires spawning PowerShell, which
|
|
56
|
+
// can exceed its timeout under load and fails when blocked by policy. Skip
|
|
57
|
+
// the self start-time probe on win32 unless a caller injected `startOf`, and
|
|
58
|
+
// rely on Node's native OpenProcess liveness check (`process.kill(pid, 0)`)
|
|
59
|
+
// for stale-lock recovery.
|
|
60
|
+
let ownStart;
|
|
61
|
+
if (explicitStartOf !== undefined || platform !== 'win32') {
|
|
62
|
+
const probe = probeStart(process.pid);
|
|
63
|
+
if (!probe.start) {
|
|
64
|
+
return {
|
|
65
|
+
ok: false,
|
|
66
|
+
reason: 'identity-unavailable',
|
|
67
|
+
timedOut: probe.timedOut,
|
|
68
|
+
detail: probe.detail,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
ownStart = probe.start;
|
|
72
|
+
}
|
|
22
73
|
const coordinate = () => acquireUpdateLock({ lockPath: `${lock}.coord`, tool: 'delegate-lock', heartbeatMs: 0, takeoverWaitMs: 0 });
|
|
23
74
|
const mutex = coordinate();
|
|
24
75
|
if (!mutex)
|
|
25
|
-
return
|
|
76
|
+
return { ok: false, reason: 'busy' };
|
|
26
77
|
const token = randomUUID();
|
|
27
|
-
const
|
|
78
|
+
const ownerRecord = ownStart !== undefined
|
|
79
|
+
? { pid: process.pid, start: ownStart, createdAt: now(), token }
|
|
80
|
+
: { pid: process.pid, createdAt: now(), token };
|
|
81
|
+
const body = JSON.stringify(ownerRecord);
|
|
28
82
|
const staged = `${lock}.pending-${token}`;
|
|
29
83
|
let identity;
|
|
30
84
|
try {
|
|
@@ -33,32 +87,81 @@ export function acquireDelegateLock(lock, options = {}) {
|
|
|
33
87
|
fs.linkSync(staged, lock);
|
|
34
88
|
}
|
|
35
89
|
catch (error) {
|
|
36
|
-
|
|
37
|
-
|
|
90
|
+
const code = error.code;
|
|
91
|
+
if (code !== 'EEXIST') {
|
|
92
|
+
return { ok: false, reason: 'error', detail: code || (error instanceof Error ? error.message : String(error)) };
|
|
93
|
+
}
|
|
38
94
|
const before = fs.lstatSync(lock);
|
|
39
95
|
if (before.isSymbolicLink() || !before.isFile())
|
|
40
|
-
return
|
|
96
|
+
return { ok: false, reason: 'busy' };
|
|
41
97
|
const ownerFile = lock;
|
|
42
98
|
const fileStat = fs.lstatSync(ownerFile);
|
|
43
99
|
if (!fileStat.isFile() || fileStat.isSymbolicLink() || fileStat.size > 4096)
|
|
44
|
-
return
|
|
100
|
+
return { ok: false, reason: 'busy' };
|
|
45
101
|
const oldText = fs.readFileSync(ownerFile, 'utf8');
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
return
|
|
102
|
+
let old;
|
|
103
|
+
try {
|
|
104
|
+
old = JSON.parse(oldText);
|
|
105
|
+
}
|
|
106
|
+
catch {
|
|
107
|
+
return { ok: false, reason: 'busy' };
|
|
108
|
+
}
|
|
109
|
+
if (!old ||
|
|
110
|
+
typeof old !== 'object' ||
|
|
111
|
+
!Number.isSafeInteger(old.pid) ||
|
|
112
|
+
old.pid <= 0 ||
|
|
113
|
+
!Number.isFinite(old.createdAt) ||
|
|
114
|
+
(old.start !== undefined &&
|
|
115
|
+
(typeof old.start !== 'string' || !old.start))) {
|
|
116
|
+
return { ok: false, reason: 'busy' };
|
|
117
|
+
}
|
|
118
|
+
const parsed = old;
|
|
119
|
+
const ownerAlive = alive(parsed.pid);
|
|
120
|
+
if (ownerAlive || explicitStartOf !== undefined) {
|
|
121
|
+
if (typeof parsed.start === 'string') {
|
|
122
|
+
const probe = probeStart(parsed.pid);
|
|
123
|
+
if (ownerAlive) {
|
|
124
|
+
if (probe.start === null) {
|
|
125
|
+
if (probe.toolUnavailable) {
|
|
126
|
+
return {
|
|
127
|
+
ok: false,
|
|
128
|
+
reason: 'identity-unavailable',
|
|
129
|
+
timedOut: probe.timedOut,
|
|
130
|
+
detail: probe.detail,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
return { ok: false, reason: 'busy' };
|
|
134
|
+
}
|
|
135
|
+
if (probe.start === parsed.start)
|
|
136
|
+
return { ok: false, reason: 'busy' };
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
else if (ownerAlive) {
|
|
140
|
+
return { ok: false, reason: 'busy' };
|
|
141
|
+
}
|
|
142
|
+
}
|
|
52
143
|
const after = fs.lstatSync(lock);
|
|
53
|
-
if (before.dev !== after.dev || before.ino !== after.ino || fs.readFileSync(ownerFile, 'utf8') !== oldText)
|
|
54
|
-
return
|
|
144
|
+
if (before.dev !== after.dev || before.ino !== after.ino || fs.readFileSync(ownerFile, 'utf8') !== oldText) {
|
|
145
|
+
return { ok: false, reason: 'busy' };
|
|
146
|
+
}
|
|
55
147
|
fs.unlinkSync(lock);
|
|
56
|
-
|
|
148
|
+
try {
|
|
149
|
+
fs.linkSync(staged, lock);
|
|
150
|
+
}
|
|
151
|
+
catch (relinkError) {
|
|
152
|
+
const relinkCode = relinkError.code;
|
|
153
|
+
if (relinkCode === 'EEXIST')
|
|
154
|
+
return { ok: false, reason: 'busy' };
|
|
155
|
+
return { ok: false, reason: 'error', detail: relinkCode || (relinkError instanceof Error ? relinkError.message : String(relinkError)) };
|
|
156
|
+
}
|
|
57
157
|
}
|
|
58
158
|
identity = fs.lstatSync(lock);
|
|
59
159
|
}
|
|
60
|
-
catch {
|
|
61
|
-
|
|
160
|
+
catch (error) {
|
|
161
|
+
const code = error.code;
|
|
162
|
+
if (code === 'ENOENT')
|
|
163
|
+
return { ok: false, reason: 'busy' };
|
|
164
|
+
return { ok: false, reason: 'error', detail: code || (error instanceof Error ? error.message : String(error)) };
|
|
62
165
|
}
|
|
63
166
|
finally {
|
|
64
167
|
try {
|
|
@@ -68,21 +171,30 @@ export function acquireDelegateLock(lock, options = {}) {
|
|
|
68
171
|
mutex.release();
|
|
69
172
|
}
|
|
70
173
|
return {
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
const current = fs.lstatSync(lock);
|
|
77
|
-
if (!current.isFile() || current.isSymbolicLink() || current.dev !== identity.dev || current.ino !== identity.ino || fs.readFileSync(lock, 'utf8') !== body)
|
|
174
|
+
ok: true,
|
|
175
|
+
lock: {
|
|
176
|
+
release() {
|
|
177
|
+
const releaseMutex = coordinate();
|
|
178
|
+
if (!releaseMutex)
|
|
78
179
|
return;
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
180
|
+
try {
|
|
181
|
+
const current = fs.lstatSync(lock);
|
|
182
|
+
if (!current.isFile() || current.isSymbolicLink() || current.dev !== identity.dev || current.ino !== identity.ino || fs.readFileSync(lock, 'utf8') !== body)
|
|
183
|
+
return;
|
|
184
|
+
fs.unlinkSync(lock);
|
|
185
|
+
}
|
|
186
|
+
catch { /* Preserve a replacement or an unknown owner. */ }
|
|
187
|
+
finally {
|
|
188
|
+
releaseMutex.release();
|
|
189
|
+
}
|
|
190
|
+
},
|
|
85
191
|
},
|
|
86
192
|
};
|
|
87
193
|
}
|
|
194
|
+
/** A complete owner file is linked into place atomically. Legacy mkdir writers
|
|
195
|
+
* see EEXIST; unknown legacy directories stay held. */
|
|
196
|
+
export function acquireDelegateLock(lock, options = {}) {
|
|
197
|
+
const result = acquireDelegateLockDetailed(lock, options);
|
|
198
|
+
return result.ok ? result.lock : null;
|
|
199
|
+
}
|
|
88
200
|
//# sourceMappingURL=delegate-lock.js.map
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@indigoai-us/hq-cli",
|
|
3
|
-
"version": "5.345.
|
|
3
|
+
"version": "5.345.261",
|
|
4
4
|
"description": "HQ by Indigo management CLI — modules and cloud sync",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"bin": {
|
|
@@ -128,11 +128,11 @@
|
|
|
128
128
|
"*.{ts,tsx,mts,cts,js,jsx,mjs,cjs}": "eslint --cache --no-error-on-unmatched-pattern"
|
|
129
129
|
},
|
|
130
130
|
"optionalDependencies": {
|
|
131
|
-
"@indigoai-us/hq-hook-win32-x64": "5.345.
|
|
132
|
-
"@indigoai-us/hq-hook-win32-arm64": "5.345.
|
|
133
|
-
"@indigoai-us/hq-hook-darwin-x64": "5.345.
|
|
134
|
-
"@indigoai-us/hq-hook-darwin-arm64": "5.345.
|
|
135
|
-
"@indigoai-us/hq-hook-linux-x64": "5.345.
|
|
136
|
-
"@indigoai-us/hq-hook-linux-arm64": "5.345.
|
|
131
|
+
"@indigoai-us/hq-hook-win32-x64": "5.345.261",
|
|
132
|
+
"@indigoai-us/hq-hook-win32-arm64": "5.345.261",
|
|
133
|
+
"@indigoai-us/hq-hook-darwin-x64": "5.345.261",
|
|
134
|
+
"@indigoai-us/hq-hook-darwin-arm64": "5.345.261",
|
|
135
|
+
"@indigoai-us/hq-hook-linux-x64": "5.345.261",
|
|
136
|
+
"@indigoai-us/hq-hook-linux-arm64": "5.345.261"
|
|
137
137
|
}
|
|
138
138
|
}
|