GitNexus/gitnexus/test/integration/search-command-real-shells.test.ts
samuel mbabhazi 820ef1c338
fix(hooks): scope graph context to leading rg and grep searches (#4002)
* fix(hooks): read a shell search only when rg or grep starts the line

A grep after `&&`, `;` or `|` counts matches in a file the command names or
filters the output of the command before it. The Antigravity, Cursor and
Factory adapters still took its first word as a code query and searched the
graph for it (#3899). They now read a search only when it is the first
command, as the Claude-schema runtime and the OpenCode plugin already do.

The Claude runtime's parser moves to hooks/claude/search-command-pattern.cjs,
which setup copies next to the Antigravity adapter, so both read options
the same way. It now knows the shell that reads the line: PowerShell keeps a
backslash, reads a doubled quote as one quote, and computes a bare comma,
parenthesis or brace. Antigravity passes `powershell` on Windows; the Claude
runtime passes `either` there, where only a reading both shells agree on is
used.

Fixes #3899

* fix(hooks): read a bash search past variable assignments before it

`NO_COLOR=1 rg UserService src` runs rg as the first command, with
NO_COLOR in its environment, so in bash the query is read past the
assignments. A quoted word or a word after a newline is not an assignment.
PowerShell has no such prefix, so `powershell` and `either` still give no
query.

The comments that said a search after an operator never reads the
repository are reworded: it may read a file, a pipe, or another directory
after `cd`, and the line alone does not say which.

* fix(hooks): address review feedback on the first-command search rule (#4002)

- search-command-pattern: keep a substituted or array assignment value
  ($(...), ${...}, a backtick, (...)) out of the bash assignment strip, so
  `COUNT=$( grep -c TODO notes.md ) echo done` no longer yields `TODO`.
  `$NAME` values still strip.
- search-command-pattern: under `either`, require both readings to give
  the same query instead of the same argv, so `rg UserService .\src`
  keeps its query on Windows.
- Cursor and Factory: stop at the first operator after the search, so a
  later command's `-e` is no longer read when the first search uses `-f`
  or a short `-e`. Read past leading NAME=value assignments, also before
  a wrapper (`NO_COLOR=1 npx rg ...`), and decline computed values.
- Docs: the per-editor prefix differences and the Windows two-shell rule
  in editor-setup.md, the Cursor README Shell row, the Antigravity
  extractPattern docstring, and the helper header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): end a Cursor/Factory search at a newline (#4002)

`tokenizeShellWords` read an unquoted newline as a blank, so in
`git --version` + newline + `grep UserService src` the second command
became the query. A newline now ends the command like `;`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(hooks): correct why Cursor and Factory keep their own search parser (#4002)

They do not ship as single files; they load sibling helpers such as
hook-lock and registry-query. What they lack is the Claude helpers, so
the search parser stays in their hook file. Comment-only change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no query from a brace expansion or a quoted command name (#4002)

- search-command-pattern: bash expands an unquoted `{a,b}` or `{1..3}`
  into several words, so `rg {foo,bar} src` searches for `foo`, not
  `{foo,bar}`. The tokenizer records which words brace-expand, and the
  query is declined only when it comes from such a word, so
  `--include=*.{ts,tsx}` and `src/{a,b}` keep their query.
- Cursor and Factory: read leading NAME=value assignments on the raw
  line, as the shared helper does, so a quoted `'A=foo'` stays a command
  name. After a wrapper such as `env`, NAME=value is still read past.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no query from a leading tilde in bash or PowerShell (#4002)

A leading unquoted `~` is the home folder. bash (Linux, macOS and Git
Bash on Windows) expands `~`, `~/x` and `~user`, so `rg ~/UserService
src` searches for a path, not `~/UserService`. PowerShell expands `~`,
`~/x` and `~\x` for native commands on Windows from 7.6 on
(PSNativeWindowsTildeExpansion) and passes them literally before that,
so the PowerShell reading cannot know either. Both readings now give no
query for such a word; `either` follows from them. A quoted tilde, a
tilde elsewhere in a word, and a tilde in a path keep their query, and
`~user` stays literal in PowerShell.

The editor docs now say the hooks are best effort when the shell would
rewrite the search term first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no Cursor/Factory search past an assignment on Windows (#4002)

On Windows the Cursor and Factory shell may be PowerShell, which runs
`NAME=value` as a command, so `NO_COLOR=1 rg UserService src` runs no
search there while the parser returned `UserService`. Leading
assignments are now read past only off Windows. The assignment rows move
into tests that pin process.platform to linux and win32, so the Windows
CI shards check the same expectations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no query past a brace-expanded option value (#4002)

`rg --glob {foo,bar} UserService src` runs as `rg --glob foo bar
UserService src`: --glob takes `foo` and `bar` becomes the query, while
the helper returned `UserService`. An expanded word consumed as an
option value now declines the line; `--include=*.{ts,tsx}` keeps its
query because each expanded word carries its own `=value`.

The PowerShell backtick-escape test moves out of the "computed" list:
`` rg partial`$ src `` passes a literal `partial$`, and the helper
declines it because it does not read escapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no Cursor/Factory search past a `$` value after a wrapper (#4002)

After a wrapper such as `env`, `A=$ARGS` is an ordinary argument, so the
shell splits `$ARGS` on blanks and `env` may run something other than
rg. A wrapper assignment with `$`, a backtick or parentheses now leaves
no query. A leading `P=$HOME rg x` is a shell assignment, which is not
split, and keeps its query.

The helper header now states the glob rule: an unquoted glob is read as
written, since bash leaves it unchanged unless a file matches, and the
reading is best effort.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read no query that Git Bash converts to a Windows path (#4002)

On Windows, Git Bash converts an argument that looks like a Unix path
(`/api/users`, `--x=/y`, `/a:/b`), quoted or not, before it starts a
native program. A real run on windows-latest showed `rg /api/users src`
reaching rg.exe as `C:/Program Files/Git/api/users`, while the hook read
`/api/users`. The `either` reading, which the Claude runtime uses on
Windows, now declines a query with `/` at the start or after `=` or
`:`. The bash and PowerShell readings are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(hooks): check the search-term reading against real shells (#4002)

Runs each search command through the real shells on the machine (Git
Bash, Windows PowerShell and pwsh on Windows; bash and pwsh on Linux and
macOS) with a fake rg/grep that records its arguments, and requires that
every query searchCommandPattern reads is exactly what the tool
received. Git Bash on Windows is checked against the `either` reading,
which the Claude runtime uses there. On Windows the fake tool is a real
.exe built with Add-Type, since PowerShell passes arguments to .cmd and
.bat files the legacy way. Plain searches must stay readable in every
reading, so the check cannot pass by declining everything.

The file and test/unit/search-command-pattern.test.ts join the
cross-platform list. A run on windows-latest, ubuntu-latest and
macos-latest found the Git Bash path conversion fixed in the previous
commit; with it, all hook tests pass on Windows (796) and Ubuntu (809).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(hooks): give every pattern of a search graph context (#4002)

`rg -e FooService -e BarService src` searches for both, but the hooks
passed only the first pattern to `gitnexus augment`.

- search-command-pattern: searchCommandPatterns returns every `-e` /
  `--regexp` pattern (or the positional one), up to three, skipping ones
  shorter than three characters. A command is declined as a whole when
  any pattern is shell-expanded or, under `either`, would be converted
  by Git Bash; the two readings must agree on the whole list.
  searchCommandPattern stays as the first pattern.
- Claude runtime and Antigravity adapter: extractPatterns feeds every
  pattern to `augment -- <patterns...>`; the MCP hint keeps the first.
- `gitnexus augment <pattern...>` takes several patterns. The engine
  runs one lookup per pattern in the same process and merges the
  symbols; one pattern keeps its top five, several share six so the hook
  stays within its time limit. A single pattern behaves as before.
- Cursor, Factory and OpenCode keep one pattern: they may call an older
  `npx gitnexus`, which rejects extra arguments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(hooks): drop the unused extractPattern from the Claude runtime (#4002)

The runtime reads search patterns through extractPatterns; extractPattern
was only reached by the unit tests (CodeQL: unused function). The test
loader now exposes the first pattern from extractPatterns itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): name every search pattern in the MCP query hint (#4002)

When the MCP server holds the graph DB, the hooks point the agent at the
MCP `query` tool instead of running augment. That hint named only the
first pattern; it now names each one (`search_query "A", then
search_query "B"`), and reads as before for a single pattern. The hint
stays byte-identical in the Claude runtime and the Antigravity adapter.

The Cursor/Factory assignment comment now says a `$NAME` value is read
past and only a command substitution or array value ends the read.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(hooks): simplify the multi-pattern code paths (#4002)

- engine: each pattern's lookup stops querying files once it holds its
  share of symbols; the kept symbols are the same prefix as before.
- augment CLI: takes the string[] commander passes and leaves the
  length filter to the engine, keeping the early exit when no pattern is
  long enough.
- search-command-pattern: reuse `next` in the brace check, replace a
  nested ternary, reflow a comment.
- real-shell test: name temp files by shell index, not name length.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): read a Cursor/Factory search after leading blank lines (#4002)

- Cursor and Factory: a newline before the first command is whitespace
  again, so `\nrg UserService src` keeps its query; a newline after a
  command still ends it like `;`.
- real-shell test: escape `'` in the temp path written into the
  PowerShell build script.
- augment CLI comment: the result goes to stderr, not stdout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(hooks): preserve PowerShell search terms and leading blank lines (#4002)

Read literal PowerShell call-operator searches and embedded angle brackets.
Skip leading blank lines while keeping assignments on the search command's
own line. Assert that multi-pattern augmentation returns both symbol rows.

Validation: 790 focused tests passed, including native Bash and PowerShell.
The Swift nested-package and CLI registry-collision cases failed in the
broader concurrent run and passed on isolated retry.

---------

Co-authored-by: Gergő Magyar <gergomagyar@icloud.com>
Co-authored-by: Gergo Magyar <gergomagyar0@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-20 05:22:14 +00:00

275 lines
9.9 KiB
TypeScript

/**
* Runs search commands through the real shells on this machine and checks the
* hook's reading against what a fake `rg` / `grep` actually receives: whenever
* searchCommandPattern returns a query, the real shell must have started the
* search tool with exactly that query.
*
* Windows runs Git Bash, Windows PowerShell and pwsh; Linux and macOS run bash
* and pwsh when installed. On Windows the fake tool is a real .exe, because
* PowerShell passes arguments to .cmd and .bat files the legacy way
* (about_Parsing, $PSNativeCommandArgumentPassing).
*/
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import { spawnSync } from 'node:child_process';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
type Mode = 'bash' | 'powershell' | 'either';
const HELPER = path.resolve(__dirname, '..', '..', 'hooks', 'claude', 'search-command-pattern.cjs');
const { searchCommandPattern } = createRequire(import.meta.url)(HELPER) as {
searchCommandPattern: (command: string, shell: Mode) => string | null;
};
const WINDOWS = process.platform === 'win32';
const NUL = String.fromCharCode(0);
const PATH_KEY = Object.keys(process.env).find((key) => key.toLowerCase() === 'path') ?? 'PATH';
function onPath(name: string): string | null {
const found = spawnSync(WINDOWS ? 'where' : 'which', [name], { encoding: 'utf8' });
const first = found.status === 0 ? found.stdout.split(/\r?\n/)[0].trim() : '';
return first || null;
}
// `bash` on a Windows PATH may be WSL. Git Bash is `bin/bash.exe` under the
// Git root, an ancestor of git.exe (`cmd/` or `mingw64/bin/`).
function gitBash(): string | null {
const roots = [path.join(process.env.ProgramFiles ?? 'C:/Program Files', 'Git')];
const git = onPath('git');
for (let dir = git ? path.dirname(git) : ''; dir && dir !== path.dirname(dir); ) {
roots.push(dir);
dir = path.dirname(dir);
}
return (
roots.map((root) => path.join(root, 'bin', 'bash.exe')).find((bash) => fs.existsSync(bash)) ??
null
);
}
const POWERSHELL_ARGS = ['-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass'];
type Shell = {
name: string;
mode: Mode;
exe: string | null;
ext: string;
args: (script: string) => string[];
version: string[];
};
const SHELLS: Shell[] = [
// Claude Code and Codex on Windows read a Bash tool command as `either`; the
// plain bash reading only runs on Linux and macOS.
{
name: 'bash',
mode: WINDOWS ? 'either' : 'bash',
exe: WINDOWS ? gitBash() : onPath('bash'),
ext: '.sh',
args: (script) => [script.replaceAll('\\', '/')],
version: ['--version'],
},
{
name: 'Windows PowerShell',
mode: 'powershell',
exe: WINDOWS ? onPath('powershell') : null,
ext: '.ps1',
args: (script) => [...POWERSHELL_ARGS, '-File', script],
version: [...POWERSHELL_ARGS, '-Command', '$PSVersionTable.PSVersion.ToString()'],
},
{
name: 'pwsh',
mode: 'powershell',
exe: onPath('pwsh'),
ext: '.ps1',
args: (script) => [...POWERSHELL_ARGS, '-File', script],
version: [...POWERSHELL_ARGS, '-Command', '$PSVersionTable.PSVersion.ToString()'],
},
];
const AVAILABLE = SHELLS.filter((shell) => shell.exe !== null);
const CASES = [
'rg UserService src',
'\nrg UserService src',
'\nNO_COLOR=1 rg UserService src',
'& rg UserService src',
"&'grep' UserService src",
'grep -rn UserService src',
"rg 'user service' src",
'rg "user service" src',
'rg -e LongPattern src',
'rg --glob *.ts UserService src',
'rg UserService src; echo done',
'NO_COLOR=1 rg UserService src',
'rg UserService ~/src',
'rg ~/UserService src',
"rg '~/UserService' src",
'rg ~UserService src',
'rg Foo~Bar src',
'rg {foo,bar} src',
'rg --glob {foo,bar} UserService src',
'grep -rn UserService --include=*.{ts,tsx} src',
String.raw`rg C:\Users src`,
String.raw`rg 'path\name' src`,
"rg 'can''t' src",
'rg first,second src',
'rg List<notes.md',
'rg UserService 2>errors.txt',
'rg /api/users src',
"rg '/api/users' src",
'rg //api/users src',
'rg api/users src',
'rg key=/api src',
'rg --regexp=/api src',
];
// Searches every reading must keep, so the invariant below cannot pass by
// declining everything.
const PLAIN = ['rg UserService src', 'grep -rn UserService src', "rg 'user service' src"];
/** The query rg or grep received, for the options these cases use. */
function receivedPattern(argv: string[] | undefined): string | undefined {
const takesValue = new Set(['--glob', '-g', '--include', '--max-count', '-m']);
for (let i = 0; argv && i < argv.length; i++) {
const arg = argv[i];
if (arg === '-e' || arg === '--regexp' || arg === '--') return argv[i + 1];
if (arg.startsWith('--regexp=')) return arg.slice('--regexp='.length);
if (takesValue.has(arg)) i++;
else if (!arg.startsWith('-') || arg === '-') return arg;
}
return undefined;
}
const accepted = (mode: Mode) =>
CASES.map((command) => [command, searchCommandPattern(command, mode)] as const).filter(
(entry): entry is readonly [string, string] => entry[1] !== null,
);
let tmp = '';
const received = new Map<string, Map<string, string[] | undefined>>();
/** Fake rg and grep that write the arguments they received, NUL-separated. */
function installFakeTools(bin: string): void {
fs.mkdirSync(bin, { recursive: true });
if (WINDOWS) {
const source = [
'public static class Program {',
' public static void Main(string[] args) {',
' System.IO.File.WriteAllText(',
' System.Environment.GetEnvironmentVariable("GN_ARGV_DUMP"),',
' string.Join(((char)0).ToString(), args));',
' }',
'}',
].join('\n');
const build = path.join(tmp, 'build-fake-tool.ps1');
const exe = path.join(bin, 'rg.exe');
fs.writeFileSync(
build,
`Add-Type -OutputType ConsoleApplication -OutputAssembly '${exe.replaceAll("'", "''")}' -TypeDefinition @'\n${source}\n'@\n`,
);
const powershell = onPath('powershell');
const built = spawnSync(powershell ?? 'powershell', [...POWERSHELL_ARGS, '-File', build], {
encoding: 'utf8',
});
if (!fs.existsSync(exe)) throw new Error(`could not build fake rg.exe: ${built.stderr}`);
fs.copyFileSync(exe, path.join(bin, 'grep.exe'));
return;
}
const dump = path.join(tmp, 'dump-argv.cjs');
fs.writeFileSync(
dump,
"require('fs').writeFileSync(process.env.GN_ARGV_DUMP, process.argv.slice(2).join(String.fromCharCode(0)));\n",
);
for (const tool of ['rg', 'grep']) {
const file = path.join(bin, tool);
fs.writeFileSync(file, `#!/bin/sh\nexec '${process.execPath}' '${dump}' "$@"\n`);
fs.chmodSync(file, 0o755);
}
}
function runInShell(shell: Shell, command: string, index: number, bin: string, work: string) {
const shellIndex = SHELLS.indexOf(shell);
const script = path.join(tmp, `case-${shellIndex}-${index}${shell.ext}`);
const dump = path.join(tmp, `argv-${shellIndex}-${index}`);
// Git's bin/bash.exe puts its own /usr/bin (with a real grep) first on PATH,
// so a bash script puts the fake tools back in front before the command.
const posixBin = WINDOWS ? `/${bin[0].toLowerCase()}${bin.slice(2).replaceAll('\\', '/')}` : bin;
const prefix = shell.ext === '.sh' ? `PATH="${posixBin}:$PATH"\n` : '';
fs.writeFileSync(script, `${prefix}${command}\n`);
spawnSync(shell.exe as string, shell.args(script), {
cwd: work,
encoding: 'utf8',
timeout: 60_000,
windowsHide: true,
env: {
...process.env,
[PATH_KEY]: `${bin}${path.delimiter}${process.env[PATH_KEY] ?? ''}`,
GN_ARGV_DUMP: dump,
},
});
return fs.existsSync(dump) ? fs.readFileSync(dump, 'utf8').split(NUL) : undefined;
}
beforeAll(() => {
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gn-real-shells-'));
const bin = path.join(tmp, 'bin');
const work = path.join(tmp, 'work');
fs.mkdirSync(path.join(work, 'src'), { recursive: true });
fs.writeFileSync(path.join(work, 'notes.md'), 'notes\n');
installFakeTools(bin);
const table: string[] = [];
for (const shell of AVAILABLE) {
const version = spawnSync(shell.exe as string, shell.version, { encoding: 'utf8' });
table.push(`## ${shell.name} (${shell.exe}): ${version.stdout.split(/\r?\n/)[0]}`);
const byCommand = new Map<string, string[] | undefined>();
CASES.forEach((command, index) => {
const argv = runInShell(shell, command, index, bin, work);
byCommand.set(command, argv);
const query = searchCommandPattern(command, shell.mode);
table.push(
`${JSON.stringify(command)} -> hook ${JSON.stringify(query)} | rg ${JSON.stringify(argv ?? null)}`,
);
});
received.set(shell.name, byCommand);
}
console.log(table.join('\n'));
}, 600_000);
afterAll(() => {
if (tmp) fs.rmSync(tmp, { recursive: true, force: true });
});
for (const shell of SHELLS) {
describe.skipIf(shell.exe === null)(`real ${shell.name} (${shell.mode} reading)`, () => {
it.each(PLAIN)('reads %j', (command) => {
expect(searchCommandPattern(command, shell.mode)).not.toBeNull();
});
it.each(accepted(shell.mode))(
'starts the tool with the query read from %j',
(command, query) => {
expect(receivedPattern(received.get(shell.name)?.get(command))).toBe(query);
},
);
});
}
// Claude Code and Codex on Windows cannot tell which shell runs the command,
// so a query read as `either` must be the one every real shell passes.
describe.skipIf(AVAILABLE.length === 0)('either reading', () => {
it.each(PLAIN)('reads %j', (command) => {
expect(searchCommandPattern(command, 'either')).not.toBeNull();
});
it.each(accepted('either'))(
'every real shell starts the tool with the query read from %j',
(command, query) => {
const seen = AVAILABLE.map((shell) =>
receivedPattern(received.get(shell.name)?.get(command)),
);
expect(seen).toEqual(AVAILABLE.map(() => query));
},
);
});