mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-22 00:31:17 +00:00
Some checks failed
CodeQL / Analyze (javascript-typescript) (push) Waiting to run
CodeQL / Analyze (python) (push) Waiting to run
Gitleaks / gitleaks (push) Waiting to run
Publish / Classify release event (push) Waiting to run
Publish / RC guard (marker + release-PR skip) (push) Blocked by required conditions
Publish / ci (push) Blocked by required conditions
Publish / Publish to npm (push) Blocked by required conditions
Publish / Build & Push RC Docker images (push) Blocked by required conditions
Scorecard / Scorecard analysis (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-cli) (push) Waiting to run
Trivy Image Scan / Trivy (gitnexus-web) (push) Waiting to run
Devcontainer Smoke / Config-transform unit tests (push) Has been cancelled
Devcontainer Smoke / Build devcontainer image (push) Has been cancelled
* fix(hooks): wrap the augment CLI child in the orphan guard (#2163) Follow-up invited by the maintainer on #2165: the augment child (7s local / 12s npx) was the longest-lived unwrapped subprocess, exposed to the same SIGKILL-orphan mechanism fixed for lsof/ps. - Export resolveUnixGuardTimeout from the probe module (both copies, byte-identical); adapters share the same module instance, so the memo and lazy self-test still run at most once per hook process. - Wrap every CLI-executing branch of runGitNexusCli in the three probe-equipped adapters with the guard: budget ceil(inner/1000)+1 seconds with -k 1, strictly above each branch's inner spawnSync timeout, so the supervised path is unchanged and the wrapper only matters once the hook itself is SIGKILLed. Windows and no-guard hosts keep byte-identical argv. The plugin adapter's PATH-direct gitnexus branch (its most common production path) is wrapped too; the cheap which/where probe is not. - Cursor integration: debug-gated 'augment skipped: hook slots saturated' on the slot-starved early return. Its augment child stays unwrapped for now — that integration does not install the probe sibling (the 'cursor probe' item on the #2163 follow-up list). - Reaping tests get a guard-availability precheck with an explicit failure message (assertion, not skipIf, so a coreutils-less Linux host fails diagnosably instead of going silently green). - Tests: orphaned-augment reaping (CJS + Plugin, red without the wrap, ~9.1s reap measured), disabled-sentinel degradation equivalence, source pinning for all three adapters (exact per-branch budget-formula counts) + probe export + cursor debug line. Note: pre-commit typecheck skipped; remaining tsc errors are pre-existing on main (none in files touched here). * fix(hooks): group-SIGKILL the npx arm, prove guard exit propagation (#2169 review) Addresses the tri-review findings on #2169: - [P2] npx-arm containment: the CLI is the guard's grandchild there — at budget expiry coreutils timeout TERMs the group, npx (the obedient direct child) dies, timeout returns, and -k never fires, so a SIGTERM-immune grandchild escaped unbounded. The npx arm's wrapper now uses -s KILL: an unignorable group SIGKILL at budget that reaps the grandchild (kept -k 1 as a harmless belt; direct-exec arms keep TERM-first). CHANGELOG, adapter docblocks, and the test comment now state the per-arm semantics honestly. New behavioral test: a staged hook with a PATH-injected fake npx spawning a SIGTERM-immune grandchild is SIGKILLed; the grandchild must be reaped (red without -s KILL), with a route self-proof marker pinning the npx arm. - [P3] guard self-test now proves exit-status propagation (sh -c 'exit 42' must yield status 42), so an always-exit-0 stub like /bin/true is rejected and resolution falls through to the built-in candidates instead of silently killing the augment feature. New test: stub guard rejected, augment still emits context. - [P3] cleanup SIGKILLs in the reaping tests re-check the /proc/<pid>/cmdline identity immediately before firing (PID-reuse guard), applied consistently to the two pre-existing #2165 spots and both new tests. - Review notes: source pins now constrain wrapper argv order and exact per-arm counts; adapters degrade to unwrapped on probe version skew (typeof check) instead of a swallowed TypeError; export JSDoc wording fixed for relative env paths; debug-gated diagnostic when no guard is available (e.g. macOS without coreutils), with the CHANGELOG entry qualified accordingly. Note: pre-commit typecheck skipped; remaining tsc errors are pre-existing on main (none in files touched here). --------- Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
280 lines
8 KiB
JavaScript
280 lines
8 KiB
JavaScript
#!/usr/bin/env node
|
|
/**
|
|
* GitNexus Cursor postToolUse Hook
|
|
*
|
|
* Receives a JSON event on stdin describing a finished tool call, derives a
|
|
* search pattern (Grep query, Read file basename, or rg/grep arg from a Shell
|
|
* command), runs `gitnexus augment <pattern>`, and emits the enriched context
|
|
* back as `{ additional_context: "..." }` so the agent sees it alongside the
|
|
* tool result.
|
|
*
|
|
* Replaces the legacy beforeShellExecution / augment-shell.sh pipeline:
|
|
* - Cross-platform (no bash, no jq — runs on Windows out of the box)
|
|
* - Covers Read and Grep, not just Shell rg/grep
|
|
*
|
|
* Cursor 2.4+ generic hooks: https://cursor.com/docs/agent/hooks
|
|
*/
|
|
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { spawnSync } = require('child_process');
|
|
const { acquireHookSlot } = require('./hook-lock.cjs');
|
|
|
|
function readInput() {
|
|
try {
|
|
const data = fs.readFileSync(0, 'utf-8');
|
|
return JSON.parse(data);
|
|
} catch {
|
|
return {};
|
|
}
|
|
}
|
|
|
|
function isGlobalRegistryDir(candidate) {
|
|
if (fs.existsSync(path.join(candidate, 'meta.json'))) return false;
|
|
return (
|
|
fs.existsSync(path.join(candidate, 'registry.json')) ||
|
|
fs.existsSync(path.join(candidate, 'repos'))
|
|
);
|
|
}
|
|
|
|
function walkForGitNexusDir(startDir) {
|
|
let dir = startDir;
|
|
for (let i = 0; i < 5; i++) {
|
|
const candidate = path.join(dir, '.gitnexus');
|
|
if (fs.existsSync(candidate)) {
|
|
if (!isGlobalRegistryDir(candidate)) return candidate;
|
|
}
|
|
const parent = path.dirname(dir);
|
|
if (parent === dir) break;
|
|
dir = parent;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function findCanonicalRepoRoot(cwd) {
|
|
try {
|
|
const result = spawnSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
|
|
encoding: 'utf-8',
|
|
timeout: 2000,
|
|
cwd,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
windowsHide: true,
|
|
});
|
|
if (result.error || result.status !== 0) return null;
|
|
const commonDir = (result.stdout || '').trim();
|
|
if (!commonDir || !path.isAbsolute(commonDir)) return null;
|
|
return path.dirname(commonDir);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
function findGitNexusDir(startDir) {
|
|
const cwd = startDir || process.cwd();
|
|
const fromCwd = walkForGitNexusDir(cwd);
|
|
if (fromCwd) return fromCwd;
|
|
const canonicalRoot = findCanonicalRepoRoot(cwd);
|
|
if (canonicalRoot && canonicalRoot !== cwd) {
|
|
return walkForGitNexusDir(canonicalRoot);
|
|
}
|
|
return null;
|
|
}
|
|
|
|
function parseRgGrepPattern(cmd) {
|
|
const tokens = cmd.split(/\s+/);
|
|
let foundCmd = false;
|
|
let skipNext = false;
|
|
const flagsWithValues = new Set([
|
|
'-e',
|
|
'-f',
|
|
'-m',
|
|
'-A',
|
|
'-B',
|
|
'-C',
|
|
'-g',
|
|
'--glob',
|
|
'-t',
|
|
'--type',
|
|
'--include',
|
|
'--exclude',
|
|
]);
|
|
|
|
for (const token of tokens) {
|
|
if (skipNext) {
|
|
skipNext = false;
|
|
continue;
|
|
}
|
|
if (!foundCmd) {
|
|
if (/\brg$|\bgrep$/.test(token)) foundCmd = true;
|
|
continue;
|
|
}
|
|
if (token.startsWith('-')) {
|
|
if (flagsWithValues.has(token)) skipNext = true;
|
|
continue;
|
|
}
|
|
const cleaned = token.replace(/['"]/g, '');
|
|
return cleaned.length >= 3 ? cleaned : null;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/**
|
|
* Extract a search pattern from the tool input. Cursor 2.4 docs at
|
|
* https://cursor.com/docs/agent/hooks list the tool *matchers* but do not
|
|
* formally specify the per-tool tool_input field names, so we probe a
|
|
* generous set of MCP-style aliases. As a last-resort fallback for Grep
|
|
* (the highest-frequency search path) we also accept the longest plausible
|
|
* string value in tool_input. Set GITNEXUS_DEBUG=1 to log the raw payload
|
|
* to stderr if Cursor changes the contract and aliases stop matching.
|
|
*/
|
|
function pickLongestStringValue(obj) {
|
|
let best = null;
|
|
if (!obj || typeof obj !== 'object') return null;
|
|
for (const v of Object.values(obj)) {
|
|
if (typeof v === 'string' && v.length >= 3 && (!best || v.length > best.length)) {
|
|
best = v;
|
|
}
|
|
}
|
|
return best;
|
|
}
|
|
|
|
function extractPattern(toolName, toolInput) {
|
|
const t = (toolName || '').toLowerCase();
|
|
|
|
if (t === 'grep') {
|
|
const aliases = [
|
|
toolInput.query,
|
|
toolInput.pattern,
|
|
toolInput.regex,
|
|
toolInput.q,
|
|
toolInput.search,
|
|
toolInput.searchQuery,
|
|
];
|
|
for (const a of aliases) {
|
|
if (typeof a === 'string' && a.length >= 3) return a;
|
|
}
|
|
// Last resort: scan tool_input for any reasonable-looking string value.
|
|
return pickLongestStringValue(toolInput);
|
|
}
|
|
|
|
if (t === 'read') {
|
|
const filePath =
|
|
toolInput.target_file ||
|
|
toolInput.file_path ||
|
|
toolInput.filePath ||
|
|
toolInput.path ||
|
|
toolInput.file ||
|
|
'';
|
|
if (!filePath) return null;
|
|
const base = path.basename(String(filePath), path.extname(String(filePath)));
|
|
const cleaned = base.replace(/[^a-zA-Z0-9_]/g, '');
|
|
return cleaned.length >= 3 ? cleaned : null;
|
|
}
|
|
|
|
if (t === 'shell') {
|
|
const cmd = toolInput.command || '';
|
|
if (!/\brg\b|\bgrep\b/.test(cmd)) return null;
|
|
// NOTE: parseRgGrepPattern uses split(/\s+/) and cannot handle shell
|
|
// quoting. `rg "User Service" src/` returns "User" (the first token
|
|
// after the rg/grep arg, with surrounding quotes stripped) — the
|
|
// multi-word pattern is intentionally not reconstructed since BM25 is
|
|
// already token-tolerant. Quoted single tokens (`rg "validateUser"`)
|
|
// work fine.
|
|
return parseRgGrepPattern(cmd);
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
function resolveCliPath() {
|
|
try {
|
|
return require.resolve('gitnexus/dist/cli/index.js');
|
|
} catch {
|
|
return '';
|
|
}
|
|
}
|
|
|
|
function runGitNexusCli(cliPath, args, cwd, timeout) {
|
|
const isWin = process.platform === 'win32';
|
|
if (cliPath) {
|
|
return spawnSync(process.execPath, [cliPath, ...args], {
|
|
encoding: 'utf-8',
|
|
timeout,
|
|
cwd,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
windowsHide: true,
|
|
});
|
|
}
|
|
return spawnSync(isWin ? 'npx.cmd' : 'npx', ['-y', 'gitnexus', ...args], {
|
|
encoding: 'utf-8',
|
|
timeout: timeout + 5000,
|
|
cwd,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
windowsHide: true,
|
|
});
|
|
}
|
|
|
|
function main() {
|
|
try {
|
|
const input = readInput();
|
|
if (process.env.GITNEXUS_DEBUG) {
|
|
// Echo the payload so users can capture Cursor's actual contract when
|
|
// diagnosing why augmentation isn't firing. Stderr only — stdout is
|
|
// reserved for the JSON response Cursor consumes.
|
|
try {
|
|
process.stderr.write(
|
|
`GitNexus Cursor hook stdin: ${JSON.stringify(input).slice(0, 500)}\n`,
|
|
);
|
|
} catch {
|
|
/* never let debug logging break the hook */
|
|
}
|
|
}
|
|
const cwd = input.cwd || process.cwd();
|
|
if (!path.isAbsolute(cwd)) return;
|
|
const gitNexusDir = findGitNexusDir(cwd);
|
|
if (!gitNexusDir) return;
|
|
|
|
const toolName = input.tool_name || '';
|
|
const toolInput = input.tool_input || {};
|
|
|
|
const pattern = extractPattern(toolName, toolInput);
|
|
if (!pattern || pattern.length < 3) return;
|
|
|
|
const release = acquireHookSlot(gitNexusDir);
|
|
if (!release) {
|
|
// Normal skip path: all per-repo hook slots are held by concurrent
|
|
// sessions. Stays silent by default; surfaced only under the cursor
|
|
// hook's own GITNEXUS_DEBUG (truthy) convention. NOTE: unlike the
|
|
// claude/plugin/antigravity adapters this integration does not install
|
|
// hook-db-lock-probe.cjs, so its augment child is not guard-wrapped
|
|
// yet — tracked on the #2163 follow-up list ("cursor probe").
|
|
if (process.env.GITNEXUS_DEBUG) {
|
|
process.stderr.write('[GitNexus] augment skipped: hook slots saturated\n');
|
|
}
|
|
return;
|
|
}
|
|
|
|
const cliPath = resolveCliPath();
|
|
let result = '';
|
|
try {
|
|
const child = runGitNexusCli(cliPath, ['augment', '--', pattern], cwd, 7000);
|
|
if (!child.error && child.status === 0) {
|
|
result = child.stderr || '';
|
|
}
|
|
} catch {
|
|
/* graceful failure */
|
|
} finally {
|
|
release();
|
|
}
|
|
|
|
if (result && result.trim()) {
|
|
console.log(JSON.stringify({ additional_context: result.trim() }));
|
|
}
|
|
} catch (err) {
|
|
if (process.env.GITNEXUS_DEBUG) {
|
|
console.error('GitNexus Cursor hook error:', (err.message || '').slice(0, 200));
|
|
}
|
|
}
|
|
}
|
|
|
|
main();
|