GitNexus/gitnexus-cursor-integration/hooks/hook-lock.cjs
ming1523 b7d6db29ed
fix(cursor): keep cold npx hooks within host deadlines (#3799)
* fix(cursor-hook): keep npx fallback under the postToolUse host budget

hooks.json grants postToolUse a 10s budget. The npx fallback branch
added a flat +5s on top of the inner 7s spawnSync budget, reaching
12s — past the host deadline. When the local gitnexus package is
absent and npx cold-starts, Cursor kills the hook before the child
finishes, so the augmentation result is always lost on exactly the
machines the fallback exists for.

Cap the fallback at 10000 - 2000 = 8000ms (host budget minus
headroom for node startup and the final stdout write) via
Math.min, and add a source-level regression test asserting the cap
wiring so the fallback can never exceed the host budget again.

* style: collapse Math.min call to satisfy prettier formatting

* fix(cursor-hook): size npx fallback from the real host budget and KILL the npx tree

Review follow-up on #3292 (P1 + 2xP2):

- hooks.json now ships postToolUse timeout 60s: a cold `npx -y gitnexus`
  (download + install) can never fit inside 10s, so shrinking the child
  timer could only convert a late success into a guaranteed failure.
- runGitNexusCli derives the npx budget at call time: hooks.json seconds
  x1000, minus 5s headroom for node startup and the stdout write, minus
  the hook's own elapsed time — and floors at 1s.
- The npx grandchild (npx -> gitnexus) is wrapped in a coreutils
  `timeout -s KILL -k 1` guard resolved from standard locations
  (GITNEXUS_HOOK_TIMEOUT_PATH override / disabled honored), mirroring the
  Claude adapter: a plain SIGTERM killed only the obedient npx parent and
  left the grandchild holding the LadybugDB lock after the hook released
  its slot. Windows stays unwrapped (npx is a .cmd there).
- The regression tests now read the shipped hooks.json, assert the
  budget derivation is actually wired into the spawn (sliced function
  body), and assert the -s KILL wrap instead of detached substring
  checks.

* test(cursor-hook): accept either quote style in the -s KILL assertions

CI runs prettier before vitest, which normalizes the wrapped spawnSync
arguments to single quotes; the double-quoted substring assertions then
fail on all platforms. Match both quote styles instead.

* fix(cursor-hook): self-test the guard, size npx budget from the real host window

Four fixes to the Cursor postToolUse hook's npx fallback.

F1 — Homebrew installs `gtimeout`, not `timeout`. The builtin candidate
list named `/opt/homebrew/bin/timeout` and `/usr/local/bin/timeout`, which
exist on no Homebrew install, so on Apple Silicon the `-s KILL`
orphan-containment wrap silently never engaged. Adopt the canonical list:
`/usr/bin/timeout`, `/bin/timeout`, `/opt/homebrew/bin/gtimeout`,
`/usr/local/bin/gtimeout`.

F2 — candidates were adopted on mere existence. `GITNEXUS_HOOK_TIMEOUT_PATH`
pointing at an always-exit-0 binary passed `existsSync`, and the wrapped
spawn then exited 0 without ever running npx — status 0 and empty stderr
satisfy main()'s success check, so the hook emitted no augmentation at all.
Port `passesGuardSelfTest` from hook-db-lock-probe.cjs: a candidate is
adopted only when `timeout -k 1 1 /bin/sh -c 'exit 42'` exits 42, i.e. it
both runs the wrapped command and propagates its status. This also rejects
busybox <1.34 / toybox, which lack `-k`. The override is resolved with
`path.resolve` because runGitNexusCli spawns it with the tool request's cwd.
Resolution is memoized per hook process.

F3 — `Math.max(1000, ...)` handed the guard 1000ms of an already-expired
host window (3000ms with the spawnSync allowance), so the host killed the
hook before the guard returned or the final stdout write landed. Skip the
npx spawn when no usable budget remains; return the same shape main()
already handles so the hook slot is still released.

F4 — `timeout + 5000` capped every npx fallback at 12s (main passes 7000),
defeating the 60s hooks.json manifest that exists to accommodate the cold
`npx -y gitnexus` install. Size the npx arm from the remaining host budget
instead, clamped by a documented max so one slow install cannot hold a
per-repo hook slot for the whole window.

Tests: pin the Homebrew gtimeout candidates, the always-exit-0 stub
rejection, the exhausted-budget skip, and the uncapped budget. The budget
arithmetic and the guard resolver are now exported so the tests exercise
them directly instead of matching substrings.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix: address reviewer feedback for #3292

---------

Co-authored-by: luyua9 <luyua9@foxmail.com>
Co-authored-by: haimingZZ <haimingz@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
2026-11-02 09:07:27 +00:00

269 lines
11 KiB
JavaScript

const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const HOOK_LOCK_SUBDIR = '.hook-locks';
const HOOK_LOCK_MAX_INFLIGHT = 3;
// How long the PID recorded in a slot file is still trusted to identify the
// process that wrote it. Age is the final arbiter ONLY as a defense against
// PID reuse on long-abandoned slots, so this bound must exceed the LONGEST
// hook lifetime that legitimately holds a slot.
//
// Every adapter copy of this file shares ONE `.hook-locks` directory per
// repo (the key is the repo's storage path), so the bound has to cover the
// longest lifetime of ANY adapter — not just the one reading the slot:
//
// cursor integration : the npx fallback may hold its slot for
// CURSOR_NPX_MAX_BUDGET_MS (45s) + the spawnSync
// teardown allowance (2s) + the guard self-test (3s)
// ≈ 50s — the longest of the four.
// claude CJS / plugin: the DB-owner probe plus the augment child ≈ 18s.
// factory plugin : a 10s host window.
//
// The previous 30s bound was sized for the claude adapter's 7s child and is
// SHORTER than the cursor adapter's npx fallback: a healthy cold-start hook
// therefore lost its slot to a concurrent hook while its child was still
// running, defeating the per-repo concurrency cap exactly during the slow
// installs the npx fallback exists to support.
//
// 60s covers the ≈50s worst case with ~10s of slack for a loaded host, and
// still bounds how long an orphaned slot (one whose owner was killed before
// it could release) blocks a slot.
const HOOK_LOCK_STALE_MS = 60000;
// An evictor's claim marker older than this belongs to a crashed evictor.
// The critical section it guards is a few syscalls (token read, lstat,
// unlink), so any live evictor finishes orders of magnitude sooner; kept well
// under HOOK_LOCK_STALE_MS so an orphan never blocks a slot for long.
const HOOK_LOCK_EVICT_MARKER_STALE_MS = 5000;
// Same file iff inode identity AND content metadata match. dev+ino alone is
// not enough: filesystems reuse a freed inode number immediately (ext4), so a
// file recreated after an unlink can carry the old file's ino. bigint stats
// keep Windows' 64-bit file ids exact.
function sameSlotFile(a, b) {
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs;
}
function readMarkerToken(marker) {
try {
return fs.readFileSync(marker, 'utf-8');
} catch {
return null;
}
}
// Stat and token of a marker, both taken from one open descriptor so they
// describe the same file (a path stat followed by a path read could straddle
// a replacement). O_NOFOLLOW where the platform has it: a marker is always a
// regular file this module created. Returns null when there is no marker.
function readMarkerSnapshot(marker) {
let fd;
try {
fd = fs.openSync(marker, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0));
return { stat: fs.fstatSync(fd, { bigint: true }), token: fs.readFileSync(fd, 'utf-8') };
} catch {
return null;
} finally {
if (fd !== undefined) {
try {
fs.closeSync(fd);
} catch {
/* already closed */
}
}
}
}
// Break an evictor's claim marker only if it is an orphan: older than
// HOOK_LOCK_EVICT_MARKER_STALE_MS, and still the exact file (identity and
// owner token) judged old when it is re-checked just before the unlink. A
// marker released and re-created by a new claimant in between is fresh, so
// it fails the check and stays.
function breakOrphanedMarker(marker) {
const seen = readMarkerSnapshot(marker);
if (!seen || Date.now() - Number(seen.stat.mtimeMs) <= HOOK_LOCK_EVICT_MARKER_STALE_MS) return;
const now = readMarkerSnapshot(marker);
if (!now || !sameSlotFile(now.stat, seen.stat) || now.token !== seen.token) return;
try {
fs.unlinkSync(marker);
} catch {
/* another contender already cleared it */
}
}
// Evict a slot judged stale from the `inspected` stat. A slot file is only
// ever deleted, never moved, and only by the evictor holding the per-slot
// `<slot>.evicting` marker, created O_EXCL with a token unique to this call.
// Every destructive step verifies first:
// - the slot is unlinked only if the marker still carries our token (an
// evictor stalled long enough for its marker to be broken as an orphan has
// lost its claim and backs off) and the slot is still the exact file
// inspected — identical dev/ino/size/mtimeNs means its content and age are
// unchanged, so the stale verdict still holds, while a slot recreated since
// inspection fails the check and its lock stands;
// - our marker is removed only if it still carries our token, so a marker
// that has passed to another claimant is left alone;
// - an orphaned marker is broken only if it is still the old file it was
// judged to be (see breakOrphanedMarker).
//
// Residual windows. POSIX has no conditional unlink, so each check-then-
// unlink pair keeps a gap of two adjacent syscalls:
// (a) Slot: between the lstat identity check and unlinkSync(slot), a live
// owner past HOOK_LOCK_STALE_MS could release and a new hook recreate the
// slot, whose fresh lock would then be deleted. The consequence is at
// most one extra concurrent augment beyond HOOK_LOCK_MAX_INFLIGHT for
// that run — the cap is a load guard, and no data or index state
// depends on it. The victim's release() sees a foreign or missing file
// and leaves it alone.
// (b) Marker: between the token re-read and unlinkSync(marker) (ours or an
// orphan's), the marker could pass to another claimant, whose claim would
// then be removed. That only re-opens the slot to one more evictor, which
// still has to pass the slot identity check before deleting anything.
// Both need a stall of seconds landing on that exact syscall pair, and the
// only thing lost is one run's cap accounting, so they are accepted rather
// than traded for heavier machinery. A crash at any point orphans at most the
// marker, which the next contender breaks after it expires.
function evictStaleSlot(slotPath, inspected) {
const marker = `${slotPath}.evicting`;
breakOrphanedMarker(marker);
const token = `${process.pid}:${crypto.randomBytes(8).toString('hex')}`;
try {
fs.writeFileSync(marker, token, { flag: 'wx' });
} catch {
return; // Another evictor holds this slot — leave it to that evictor.
}
try {
if (
readMarkerToken(marker) === token &&
sameSlotFile(fs.lstatSync(slotPath, { bigint: true }), inspected)
) {
fs.unlinkSync(slotPath);
}
} catch {
/* slot already gone — the retry claims it */
} finally {
if (readMarkerToken(marker) === token) {
try {
fs.unlinkSync(marker);
} catch {
/* already gone */
}
}
}
}
function acquireHookSlot(gitNexusDir) {
const lockDir = path.join(gitNexusDir, HOOK_LOCK_SUBDIR);
try {
fs.mkdirSync(lockDir, { recursive: true });
} catch {
// Cannot create lock dir (read-only fs, cross-user perm denial, out of
// inodes, etc.) — fail closed by returning null. Caller skips augment.
// Fail-open here would let N concurrent hooks all proceed unguarded and
// reintroduce the #1486 fan-out the guard exists to prevent.
return null;
}
const myPidStr = String(process.pid);
for (let slot = 0; slot < HOOK_LOCK_MAX_INFLIGHT; slot++) {
const slotPath = path.join(lockDir, `slot-${slot}.lock`);
for (let attempt = 0; attempt < 2; attempt++) {
try {
fs.writeFileSync(slotPath, myPidStr, { flag: 'wx' });
let released = false;
const release = () => {
if (released) return;
released = true;
process.removeListener('exit', release);
try {
// Only unlink if we still own the slot. If we appeared stale and
// another hook took over, the file now belongs to it — leave alone.
const content = fs.readFileSync(slotPath, 'utf-8').trim();
if (content === myPidStr) fs.unlinkSync(slotPath);
} catch {
/* already removed or unreadable */
}
};
process.on('exit', release);
return release;
} catch {
// Slot exists. Decide whether to take it over.
// Open once and inspect mtime + content via the same fd so there's
// no TOCTOU between the metadata check and the content read
// (codeql js/file-system-race).
let fd;
try {
fd = fs.openSync(slotPath, 'r');
} catch {
continue; // Vanished between EEXIST and open — retry this slot.
}
let isLive = false;
let mtimeMs = Date.now();
let inspected = null;
try {
inspected = fs.fstatSync(fd, { bigint: true });
mtimeMs = Number(inspected.mtimeMs);
const buf = Buffer.alloc(32);
const n = fs.readSync(fd, buf, 0, 32, 0);
const ownerStr = buf.slice(0, n).toString('utf-8').trim();
if (ownerStr === '') {
// Owner created the file but hasn't written its PID yet. The
// wx open+write window is microseconds; give it the benefit
// of the doubt and treat as live.
isLive = true;
} else {
const owner = Number.parseInt(ownerStr, 10);
if (Number.isFinite(owner) && owner > 0) {
try {
process.kill(owner, 0);
isLive = true;
} catch (e) {
// ESRCH = process gone → treat as dead. EPERM = process exists
// but owned by another user (cross-user lock dir) → still alive,
// keep the slot. Anything else: be conservative, assume alive.
if (e && e.code === 'ESRCH') {
isLive = false;
} else {
isLive = true;
}
}
}
}
} catch {
/* unreadable — treat as dead */
} finally {
try {
fs.closeSync(fd);
} catch {
/* already closed */
}
}
// For slots younger than HOOK_LOCK_STALE_MS, PID-liveness wins —
// a slow-but-alive hook is never wrongly evicted. For older slots,
// age is the final arbiter as a defense against PID reuse on long-
// abandoned slots. HOOK_LOCK_STALE_MS exceeds the longest hook
// lifetime that legitimately holds a slot (see its definition), so a
// healthy run never crosses this threshold.
if (isLive && Date.now() - mtimeMs > HOOK_LOCK_STALE_MS) {
isLive = false;
}
if (isLive) break; // Try the next slot.
// No stat means we cannot prove which file we judged stale; leave it
// (the retry re-inspects it) rather than risk deleting a fresh lock.
if (inspected) evictStaleSlot(slotPath, inspected);
// Loop and retry this slot.
}
}
}
return null;
}
module.exports = {
HOOK_LOCK_SUBDIR,
HOOK_LOCK_MAX_INFLIGHT,
HOOK_LOCK_STALE_MS,
acquireHookSlot,
};