mirror of
https://github.com/abhigyanpatwari/GitNexus.git
synced 2026-09-22 00:31:17 +00:00
* feat(cursor): upgrade hooks to Cursor 2.4 postToolUse for Read/Grep/Shell coverage
Cursor 2.4 (released 2026-01-22) shipped generic preToolUse/postToolUse hooks
matching `Shell|Read|Write|Grep|Delete|Task|MCP:<tool>`, replacing the
2.3-era beforeShellExecution hook that only fired on shell commands. The
existing integration only intercepted the shell path, so Cursor users got
graph augmentation roughly 10% as often as Claude Code users — only when
the agent dropped to rg/grep instead of using its native Read/Grep tools.
This swaps the integration over to postToolUse and ports the bash+jq
hook script to cross-platform Node:
- gitnexus-cursor-integration/hooks/hooks.json: registers a single
postToolUse hook matching Shell|Read|Grep that invokes the new
gitnexus-hook.cjs.
- gitnexus-cursor-integration/hooks/gitnexus-hook.cjs: new Node hook
mirroring the safety patterns from the Claude hook (absolute-cwd
validation, .gitnexus discovery with linked-worktree fallback,
npx.cmd on Windows, end-of-options `--` marker, debug truncation,
graceful failure). Extracts the search pattern per tool kind:
Grep -> toolInput.query; Read -> file basename stripped to identifier
chars; Shell -> existing rg/grep arg parser. Emits Cursor-shape
`{ "additional_context": "..." }` on stdout — no shell, no jq.
- gitnexus-cursor-integration/hooks/augment-shell.sh: removed (Windows
incompatible, narrower coverage).
- gitnexus/test/unit/cursor-hook.test.ts: 33 regression tests covering
manifest wiring, source-level invariants (no shell:true, npx.cmd,
isAbsolute, additional_context output shape, end-of-options marker),
extractPattern coverage per tool, and behavioral early-exit paths
(empty/invalid stdin, relative cwd, no .gitnexus, unknown tool name,
short patterns, non-search shell commands, case-insensitive matching).
- README.md / gitnexus/README.md: editor-support table now lists Cursor
as Full / hooks=Yes (postToolUse), matching reality.
- gitnexus/src/cli/augment.ts and gitnexus/src/core/augmentation/engine.ts:
doc-strings updated from `Cursor beforeShellExecution` to
`Cursor postToolUse`.
Closes #1466.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(cursor): hook timeout is in seconds, not milliseconds
Cursor's `timeout` field in hooks.json is in seconds (per
https://cursor.com/docs/agent/hooks and the original integration's
`"timeout": 5`). I'd written `10000` after blindly copying the issue
body's example — that resolves to ~2.8 hours, not 10 seconds. If the
script ever hangs before reaching its inner spawnSync timeouts (e.g.
during stdin read), Cursor would have waited that long before killing
it.
Drop to `10` (seconds), matching the Claude plugin's hooks.json and
giving plenty of headroom over the inner 7s augment-CLI timeout.
Add a regression-guard assertion in cursor-hook.test.ts so a future
ms/s mixup fails fast.
Reported by Cursor Bugbot on PR #1467.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
* fix(cursor): address Claude review findings — payload aliases, debug, install docs
Resolves three findings from Claude reviewer on PR #1467:
1. Cursor payload field-name uncertainty (SIGNIFICANT)
Claude flagged that the Grep `query` field is an unverified assumption
per Cursor 2.4 docs (https://cursor.com/docs/agent/hooks). Mitigated:
- Expanded Grep aliases: query | pattern | regex | q | search | searchQuery
- Added pickLongestStringValue() last-resort fallback so the hook
extracts *something* even if Cursor renames every documented field
- Added GITNEXUS_DEBUG=1 stderr logging of the raw stdin payload so
users can capture Cursor's actual contract when diagnosing silent
no-ops, and report it back if aliases drift
- Added Read alias `filePath` (camelCase variant alongside `file_path`)
- Inline comment block citing the docs URL and the uncertainty
2. Hook command path resolution + install docs (SIGNIFICANT)
Claude flagged `node ./hooks/gitnexus-hook.cjs` as relative without
documented install path. Added gitnexus-cursor-integration/README.md
with explicit install steps:
- .cursor/hooks.json + hooks/gitnexus-hook.cjs at project root
- Confirms Cursor's project-root CWD convention with doc link
- Verify steps including GITNEXUS_DEBUG capture
- Pattern-extraction contract table per tool
- Troubleshooting: not-firing, npx fallback, wrong-pattern diagnosis
3. README "Full" overclaim for Cursor (MODERATE)
Both README rows now read `Yes (postToolUse, manual install)` linking
to the new install README, accurately signaling that hooks aren't
automated by `gitnexus setup` like they are for Claude Code.
4. Shell quoted-pattern parser limitation (MINOR, documented)
Added inline comment in gitnexus-hook.cjs documenting the known
`rg "User Service"` -> `User` truncation, plus regression tests in
cursor-hook.test.ts pinning the behavior so a future change is
visible.
Test additions (33 -> 41):
- Wide-alias source coverage for Grep (query / pattern / regex / q /
search / searchQuery) plus pickLongestStringValue fallback
- Read alias coverage including camelCase filePath
- GITNEXUS_DEBUG behavioral test: stderr quiet by default, payload
echoed when env var set, stdout output contract preserved either way
- Shell quoted-pattern documented behavior tests
- Install README presence + content (.cursor/hooks.json, hooks/, debug
diagnostics)
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
259 lines
7.2 KiB
JavaScript
259 lines
7.2 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');
|
|
|
|
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'],
|
|
});
|
|
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'],
|
|
});
|
|
}
|
|
return spawnSync(isWin ? 'npx.cmd' : 'npx', ['-y', 'gitnexus', ...args], {
|
|
encoding: 'utf-8',
|
|
timeout: timeout + 5000,
|
|
cwd,
|
|
stdio: ['pipe', 'pipe', 'pipe'],
|
|
});
|
|
}
|
|
|
|
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;
|
|
if (!findGitNexusDir(cwd)) return;
|
|
|
|
const toolName = input.tool_name || '';
|
|
const toolInput = input.tool_input || {};
|
|
|
|
const pattern = extractPattern(toolName, toolInput);
|
|
if (!pattern || pattern.length < 3) 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 */
|
|
}
|
|
|
|
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();
|