Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.
TypeScript ai-agentai-codingantigravityantigravity-cliantigravity-ideantigravity-pluginscoding-agentcontext-optimizationdeveloper-productivitydeveloper-toolsgeminigoogle-antigravitylatency-optimizationmcpmcp-pluginmcp-servermodel-context-protocolperformanceplugintoken-optimization
import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
import { promises as fs } from "node:fs";
import os from "node:os";
import path from "node:path";
import { after, before, describe, it } from "node:test";
import {
runBatchSearch,
tokenizeArgs,
validateReadonlyGitArgs,
} from "../src/tools/batch-search.js";
import { globToRegExp, resolvePath, walkFiles } from "../src/utils/fs-utils.js";
describe("batch_search", () => {
let tmpDir: string;
for (const forceNodeFallback of [false, true]) {
it(`supports file-only output, line counts and language filtering (forceNodeFallback=${forceNodeFallback})`, async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-search-modes-"));
try {
await fs.writeFile(path.join(cwd, "a.ts"), "needle needle\r\n".repeat(75));
await fs.writeFile(path.join(cwd, "b.tsx"), "needle\n");
await fs.writeFile(path.join(cwd, "c.py"), "needle\n");
const search = { type: "text", pattern: "needle", fileType: "TypeScript" } as const;
const { text } = await runBatchSearch({
cwd,
queries: [
{ ...search, outputMode: "count", glob: "*", maxResults: 1 },
{ ...search, outputMode: "files_with_matches", glob: "b.*" },
{ ...search, path: "c.py" },
{ type: "regex", pattern: "^$", outputMode: "count" },
],
}, { forceNodeFallback });
const sections = text.split("\n\n");
assert.match(sections[0]!, /a\.ts: 75 matching lines/);
assert.match(sections[0]!, /truncated; showing 1 files/);
assert.equal(sections[1]!.split("\n").at(-1), "b.tsx");
assert.match(sections[2]!, /\(no matches\)/);
assert.match(sections[3]!, /\(no matches\)/);
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
}
for (const forceNodeFallback of [false, true]) {
it(`supports multiline content, file lists and counts (forceNodeFallback=${forceNodeFallback})`, async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-multiline-"));
try {
await fs.writeFile(path.join(cwd, "a.ts"), "before\r\nstart one\r\nend\r\nafter\r\n");
await fs.writeFile(path.join(cwd, "b.ts"), "begin end begin end\n");
await fs.writeFile(path.join(cwd, "c.py"), "start two\nend\n");
await fs.writeFile(path.join(cwd, "emoji.ts"), "A😀B\n");
const search = { type: "regex", pattern: "^start.*?end$", fileType: "ts" } as const;
const { text } = await runBatchSearch({
cwd,
queries: [
{ ...search, multiline: true, contextLines: 1 },
{ ...search, multiline: true, maxResults: 1 },
{ ...search, multiline: true, outputMode: "files_with_matches" },
{ ...search, multiline: true, outputMode: "count", pattern: "begin.*?end" },
{ ...search, multiline: true, outputMode: "count" },
{ ...search },
{ type: "text", pattern: "start one\r\nend", multiline: true, outputMode: "files_with_matches" },
{ ...search, path: "a.ts", multiline: true, outputMode: "count", pattern: "^$" },
{ ...search, path: "a.ts", multiline: true, outputMode: "count", pattern: "one|$" },
{ ...search, path: "emoji.ts", multiline: true, outputMode: "count", pattern: "A.B" },
],
}, { forceNodeFallback });
const sections = text.split("\n\n");
assert.deepEqual(sections[0]!.split("\n").slice(1), [
"a.ts", " 1- before", " 2: start one", " 3: end", " 4- after",
]);
assert.match(sections[1]!, /2: start one\n\.\.\. \[truncated/);
assert.equal(sections[2]!.split("\n").at(-1), "a.ts");
assert.match(sections[3]!, /b\.ts: 2 matches/);
assert.match(sections[4]!, /a\.ts: 1 matches/);
assert.match(sections[5]!, /\(no matches\)/);
assert.equal(sections[6]!.split("\n").at(-1), "a.ts");
assert.match(sections[7]!, /\(no matches\)/);
assert.match(sections[8]!, /a\.ts: 4 matches/);
assert.match(sections[9]!, /emoji\.ts: 1 matches/);
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
}
it("ranks fuzzy paths and optionally sorts glob results by newest mtime", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-search-paths-"));
try {
for (const [file, seconds] of [["mcp-server.ts", 1000], ["mcpserv.ts", 2000], ["mcpserv.py", 3000]] as const) {
const target = path.join(cwd, file);
await fs.writeFile(target, "");
await fs.utimes(target, seconds, seconds);
}
const { text } = await runBatchSearch({
cwd,
queries: [
{ type: "fuzzy", pattern: "MCPSERV", fileType: "ts" },
{ type: "fuzzy", pattern: "SERV MCP", fileType: "ts", maxResults: 1 },
{ type: "glob", pattern: "*.ts", sortBy: "mtime", maxResults: 1 },
{ type: "glob", pattern: "*.ts" },
],
});
const sections = text.split("\n\n");
assert.deepEqual(sections[0]!.split("\n").slice(1), ["mcpserv.ts", "mcp-server.ts"]);
assert.equal(sections[1]!.split("\n")[1], "mcpserv.ts");
assert.match(sections[1]!, /truncated; showing 1 files/);
assert.equal(sections[2]!.split("\n")[1], "mcpserv.ts");
assert.deepEqual(sections[3]!.split("\n").slice(1), ["mcp-server.ts", "mcpserv.ts"]);
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
it("handles multiline identity escapes in Node fallback, Windows backslash fuzzy queries, and contiguous fuzzy ranking", async () => {
const cwd = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-search-polish-"));
try {
await fs.mkdir(path.join(cwd, "src", "tools"), { recursive: true });
await fs.writeFile(path.join(cwd, "src", "tools", "batch-search.ts"), "key:val\n#tag\n");
await fs.writeFile(path.join(cwd, "a_serv.ts"), "");
await fs.writeFile(path.join(cwd, "s_xx_serv.ts"), "");
await fs.writeFile(path.join(cwd, "s_xx_e_r_v.ts"), "");
for (const forceNodeFallback of [false, true]) {
const escRes = await runBatchSearch({
cwd,
queries: [
{ type: "regex", pattern: "key\\:val", multiline: true, path: "src/tools/batch-search.ts" },
{ type: "regex", pattern: "\\#tag", multiline: true, path: "src/tools/batch-search.ts" },
],
}, { forceNodeFallback });
assert.equal(escRes.isError, false);
assert.match(escRes.text, /1: key:val/);
assert.match(escRes.text, /2: #tag/);
}
const fuzzyRes = await runBatchSearch({
cwd,
queries: [
{ type: "fuzzy", pattern: "src\\tools\\batch" },
{ type: "fuzzy", pattern: "serv", fileType: "ts" },
],
});
const sections = fuzzyRes.text.split("\n\n");
assert.match(sections[0]!, /src\/tools\/batch-search\.ts/);
assert.deepEqual(sections[1]!.split("\n").slice(1), [
"a_serv.ts",
"s_xx_serv.ts",
"s_xx_e_r_v.ts",
]);
} finally {
await fs.rm(cwd, { recursive: true, force: true });
}
});
before(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-search-"));
await fs.mkdir(path.join(tmpDir, "src", "api"), { recursive: true });
await fs.mkdir(path.join(tmpDir, "node_modules", "ignored-pkg"), {
recursive: true,
});
await fs.writeFile(
path.join(tmpDir, "src", "api", "routes.ts"),
[
"export function getUsers() {",
" return fetchUsers('active');",
"}",
"",
"export function createOrder(id: string) {",
" return { id, status: 'PENDING' };",
"}",
].join("\n"),
"utf8",
);
await fs.writeFile(
path.join(tmpDir, "src", "utils.py"),
[
"def fetch_users(mode):",
" # helper for FetchUsers",
" return [mode]",
].join("\n"),
"utf8",
);
// Should be ignored by both rg and Node fallback
await fs.writeFile(
path.join(tmpDir, "node_modules", "ignored-pkg", "index.js"),
"export function getUsers() { return 'ignored'; }\n",
"utf8",
);
// Binary file containing NUL bytes
await fs.writeFile(
path.join(tmpDir, "src", "blob.bin"),
Buffer.from([0x67, 0x65, 0x74, 0x55, 0x73, 0x65, 0x72, 0x73, 0x00, 0xff]),
);
// Hidden dotfile that both rg and Node fallback should skip by default
await fs.writeFile(
path.join(tmpDir, ".env"),
"SECRET_KEY=getUsers_secret_token\n",
"utf8",
);
// Multi-file fixture for contextLines + maxResults orphan-context regression test
await fs.mkdir(path.join(tmpDir, "ctx"), { recursive: true });
await fs.writeFile(
path.join(tmpDir, "ctx", "a.txt"),
"a_pre\nCTX_NEEDLE\na_post\nmid1\nmid2\nmid3\na2_pre\nCTX_NEEDLE\na2_post\n",
"utf8",
);
await fs.writeFile(
path.join(tmpDir, "ctx", "b.txt"),
"b_pre\nCTX_NEEDLE\nb_post\n",
"utf8",
);
// Initialize git repo for read-only git query tests
execFileSync("git", ["init", "-q"], { cwd: tmpDir });
execFileSync("git", ["config", "user.email", "[email protected]"], {
cwd: tmpDir,
});
execFileSync("git", ["config", "user.name", "Test User"], { cwd: tmpDir });
execFileSync("git", ["add", "src/api/routes.ts", "src/utils.py"], {
cwd: tmpDir,
});
execFileSync("git", ["commit", "-q", "-m", "initial commit"], {
cwd: tmpDir,
});
});
after(async () => {
await fs.rm(tmpDir, { recursive: true, force: true });
});
it("runs text, regex, glob, and git queries concurrently in one call", async () => {
const res = await runBatchSearch({
cwd: tmpDir,
queries: [
{ type: "text", pattern: "getUsers", contextLines: 1 },
{ type: "regex", pattern: "fetch_?[uU]sers", caseSensitive: false },
{ type: "glob", pattern: "src/**/*.ts" },
{ type: "git", pattern: "log -n 1 --oneline" },
],
});
assert.equal(res.isError, false);
assert.match(res.text, /src\/api\/routes\.ts/);
assert.match(res.text, /1: export function getUsers/);
assert.match(res.text, /2- return fetchUsers/);
assert.match(res.text, /src\/utils\.py/);
assert.match(res.text, /initial commit/);
assert.doesNotMatch(res.text, /ignored-pkg/);
assert.doesNotMatch(res.text, /blob\.bin/);
});
it("produces consistent search matches between rg and Node fallback", async () => {
const queries = [
{ type: "text" as const, pattern: "createOrder", glob: "*.ts" },
{ type: "regex" as const, pattern: "fetch[_U]sers", caseSensitive: false },
];
const withRg = await runBatchSearch({ cwd: tmpDir, queries });
const withNode = await runBatchSearch(
{ cwd: tmpDir, queries },
{ forceNodeFallback: true },
);
assert.equal(withRg.isError, false);
assert.equal(withNode.isError, false);
assert.match(withRg.text, /5: export function createOrder/);
assert.match(withNode.text, /5: export function createOrder/);
assert.match(withRg.text, /src\/utils\.py/);
assert.match(withNode.text, /src\/utils\.py/);
assert.doesNotMatch(withNode.text, /ignored-pkg/);
assert.doesNotMatch(withNode.text, /blob\.bin/);
// Neither rg nor Node fallback should leak hidden .env files by default
const envRg = await runBatchSearch({
cwd: tmpDir,
queries: [{ type: "text", pattern: "getUsers_secret_token" }],
});
const envNode = await runBatchSearch(
{
cwd: tmpDir,
queries: [{ type: "text", pattern: "getUsers_secret_token" }],
},
{ forceNodeFallback: true },
);
assert.doesNotMatch(envRg.text, /\.env/);
assert.doesNotMatch(envNode.text, /\.env/);
});
it("strips optional 'git ' prefix and allows read-only git commands", () => {
assert.deepEqual(validateReadonlyGitArgs("status --short"), [
"--no-pager",
"status",
"--short",
]);
assert.deepEqual(validateReadonlyGitArgs('git log -n 5 --format="%h %s"'), [
"--no-pager",
"log",
"-n",
"5",
"--format=%h %s",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --list"), [
"--no-pager",
"branch",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("branch -av"), [
"--no-pager",
"branch",
"-av",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --show-current"), [
"--no-pager",
"branch",
"--show-current",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --color=always"), [
"--no-pager",
"branch",
"--color=always",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --color --list"), [
"--no-pager",
"branch",
"--color",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --color --list main*"), [
"--no-pager",
"branch",
"--color",
"--list",
"main*",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --abbrev=8 --list"), [
"--no-pager",
"branch",
"--abbrev=8",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --abbrev --list"), [
"--no-pager",
"branch",
"--abbrev",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --column=never"), [
"--no-pager",
"branch",
"--column=never",
]);
assert.deepEqual(validateReadonlyGitArgs("branch --column --all"), [
"--no-pager",
"branch",
"--column",
"--all",
]);
assert.deepEqual(validateReadonlyGitArgs("tag -l v*"), [
"--no-pager",
"tag",
"-l",
"v*",
]);
assert.deepEqual(validateReadonlyGitArgs("tag --color --list"), [
"--no-pager",
"tag",
"--color",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("tag --color --list v*"), [
"--no-pager",
"tag",
"--color",
"--list",
"v*",
]);
assert.deepEqual(validateReadonlyGitArgs("tag --column=never"), [
"--no-pager",
"tag",
"--column=never",
]);
assert.deepEqual(validateReadonlyGitArgs("tag --column --list"), [
"--no-pager",
"tag",
"--column",
"--list",
]);
assert.deepEqual(validateReadonlyGitArgs("remote -v"), [
"--no-pager",
"remote",
"-v",
]);
assert.deepEqual(validateReadonlyGitArgs("remote get-url origin"), [
"--no-pager",
"remote",
"get-url",
"origin",
]);
});
it("rejects mutating git subcommands, bypass flags, and combined short flags", () => {
const blocked = [
"commit -m evil",
"push origin main",
"reset --hard HEAD",
"checkout main",
"clean -fd",
"branch -D feature",
"branch -Dmain",
"branch -mrenamed",
"branch -l --no-list evil-branch",
"branch -l --no-list -qD main",
"branch -l --no-list -qm renamed",
"branch --create-reflog",
"branch new-branch",
"branch --color new-branch",
"branch --column new-branch",
"branch --abbrev new-branch",
"branch --color -D --column target",
"branch --column -D target",
"branch --abbrev -D target",
"branch --list --color -D target",
"branch --color=always new-branch",
"branch --color -- new-branch",
"tag v1.0.0",
"tag -d v1.0.0",
"tag -dv1.0.0",
"tag -l -fd v1.0.0",
"tag -l -am msg v1.0.0",
"tag --color evil-tag",
"tag --column evil-tag",
"tag --color -d --column v0.2.2",
"tag --column -d v0.2.2",
"tag -l --color -d v0.2.2",
"tag --color=always evil-tag",
"tag --color -- evil-tag",
"remote add origin https://example.com/repo.git",
"remote show --prune origin",
"diff --output=/tmp/leak",
"diff -c core.pager=sh",
"diff -ccore.pager=sh",
"log --ext-diff",
"-c core.fsmonitor=evil status",
'log "unterminated',
];
for (const cmd of blocked) {
assert.throws(
() => validateReadonlyGitArgs(cmd),
`Expected '${cmd}' to be rejected`,
);
}
});
it("handles file targets for git/glob and avoids orphan context lines at maxResults", async () => {
const filePathQueries = await runBatchSearch({
cwd: tmpDir,
queries: [
{ type: "git", pattern: "log -n 1 --oneline", path: "src/api/routes.ts" },
{ type: "glob", pattern: "*.ts", path: "src/api/routes.ts" },
],
});
assert.equal(filePathQueries.isError, false);
assert.match(filePathQueries.text, /initial commit/);
assert.match(filePathQueries.text, /src\/api\/routes\.ts/);
assert.doesNotMatch(filePathQueries.text, /ENOTDIR/);
const rgCtx = await runBatchSearch({
cwd: path.join(tmpDir, "ctx"),
queries: [{ type: "text", pattern: "CTX_NEEDLE", contextLines: 1, maxResults: 1 }],
});
const nodeCtx = await runBatchSearch(
{
cwd: path.join(tmpDir, "ctx"),
queries: [{ type: "text", pattern: "CTX_NEEDLE", contextLines: 1, maxResults: 1 }],
},
{ forceNodeFallback: true },
);
// Neither backend should include before-context for dropped matches
assert.doesNotMatch(rgCtx.text, /a2_pre/);
assert.doesNotMatch(nodeCtx.text, /a2_pre/);
assert.doesNotMatch(nodeCtx.text, /b_pre/);
// Ensure rg output contains only files that have at least one actual ':' match line
const rgFileBlocks = rgCtx.text.split(/\n(?=[ab]\.txt\n)/).slice(1);
for (const block of rgFileBlocks) {
assert.match(block, /\d+: /, `Orphan context block without match:\n${block}`);
}
});
it("keeps the first matches in path order when maxResults truncates", async () => {
const manyDir = path.join(tmpDir, "many");
for (let i = 0; i < 40; i++) {
const sub = path.join(manyDir, `d${i % 4}`);
await fs.mkdir(sub, { recursive: true });
await fs.writeFile(
path.join(sub, `f${String(i).padStart(2, "0")}.txt`),
"pre\nMANY_NEEDLE one\nmid\nMANY_NEEDLE two\npost\n",
"utf8",
);
}
const query = { type: "text" as const, pattern: "MANY_NEEDLE", contextLines: 1, maxResults: 7 };
const runs = await Promise.all(
Array.from({ length: 5 }, () => runBatchSearch({ cwd: manyDir, queries: [query] })),
);
const nodeRun = await runBatchSearch(
{ cwd: manyDir, queries: [query] },
{ forceNodeFallback: true },
);
// d0 holds f00, f04, f08, ...; two matches per file, so 7 matches end
// after the first match of the fourth file.
const expected = [
"d0/f00.txt",
" 1- pre",
" 2: MANY_NEEDLE one",
" 3- mid",
" 4: MANY_NEEDLE two",
" 5- post",
"d0/f04.txt",
" 1- pre",
" 2: MANY_NEEDLE one",
" 3- mid",
" 4: MANY_NEEDLE two",
" 5- post",
"d0/f08.txt",
" 1- pre",
" 2: MANY_NEEDLE one",
" 3- mid",
" 4: MANY_NEEDLE two",
" 5- post",
"d0/f12.txt",
" 1- pre",
" 2: MANY_NEEDLE one",
" 3- mid",
"... [truncated at 7 matches]",
].join("\n");
for (const res of [...runs, nodeRun]) {
assert.equal(res.isError, false);
assert.ok(res.text.includes(expected), `Unexpected result set:\n${res.text}`);
}
// Each line of a multiline match counts as one match.
const multilineQuery = {
type: "regex" as const,
pattern: "MANY_NEEDLE one\\nmid",
multiline: true,
maxResults: 5,
};
const multilineRuns = await Promise.all(
Array.from({ length: 5 }, () => runBatchSearch({ cwd: manyDir, queries: [multilineQuery] })),
);
const multilineNodeRun = await runBatchSearch(
{ cwd: manyDir, queries: [multilineQuery] },
{ forceNodeFallback: true },
);
const multilineExpected = [
"d0/f00.txt",
" 2: MANY_NEEDLE one",
" 3: mid",
"d0/f04.txt",
" 2: MANY_NEEDLE one",
" 3: mid",
"d0/f08.txt",
" 2: MANY_NEEDLE one",
"... [truncated at 5 matches]",
].join("\n");
for (const res of [...multilineRuns, multilineNodeRun]) {
assert.equal(res.isError, false);
assert.ok(res.text.includes(multilineExpected), `Unexpected result set:\n${res.text}`);
}
// Truncated adjacent matches with contextLines>0 must NOT leave line-number gaps,
// and single-file search / dash filename / RIPGREP_CONFIG_PATH must match Node parity.
const parityDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-rg-parity-"));
const prevRgrc = process.env.RIPGREP_CONFIG_PATH;
try {
await fs.writeFile(path.join(parityDir, "adj.txt"), "foo 1\nfoo 2\nbar 3\n", "utf8");
await fs.writeFile(path.join(parityDir, "multi.txt"), "pre\nalpha\nbeta\ngamma\npost1\n", "utf8");
await fs.writeFile(path.join(parityDir, "-"), "dash_file_hit\n", "utf8");
await fs.writeFile(path.join(parityDir, "crlf.txt"), "alpha\r\nbeta\r\n", "utf8");
await fs.writeFile(path.join(parityDir, "bin.dat"), Buffer.from("needle\x00binary\n"));
const rgrc = path.join(parityDir, ".ripgreprc");
await fs.writeFile(rgrc, "--color=always\n--smart-case\n--context=1\n", "utf8");
process.env.RIPGREP_CONFIG_PATH = rgrc;
for (const forceNodeFallback of [false, true]) {
const res = await runBatchSearch(
{
cwd: parityDir,
queries: [
{ type: "text", pattern: "foo", path: "adj.txt", contextLines: 2, maxResults: 1 },
{ type: "regex", pattern: "alpha\\nbeta\\ngamma", path: "multi.txt", multiline: true, contextLines: 2, maxResults: 2 },
{ type: "text", pattern: "dash_file_hit" },
{ type: "text", pattern: "foo", path: "adj.txt", glob: "*.ts" },
{ type: "text", pattern: "foo", path: "adj.txt", glob: "!*.ts" },
{ type: "text", pattern: "foo", path: "adj.txt", glob: "!*.txt" },
{ type: "text", pattern: "needle", path: "bin.dat" },
{ type: "regex", pattern: "^alpha$", path: "crlf.txt" },
],
},
{ forceNodeFallback },
);
assert.equal(res.isError, false);
const sections = res.text.split("\n\n");
assert.ok(sections[0]!.includes(" 1: foo 1\n 2- foo 2\n 3- bar 3"), sections[0]);
assert.ok(sections[1]!.includes(" 2: alpha\n 3: beta\n 4- gamma\n 5- post1"), sections[1]);
assert.match(sections[2]!, /dash_file_hit/);
assert.match(sections[3]!, /\(no matches\)/);
assert.match(sections[4]!, /1: foo 1/);
assert.match(sections[5]!, /\(no matches\)/);
assert.match(sections[6]!, /\(no matches\)/);
assert.match(sections[7]!, /1: alpha/);
}
} finally {
if (prevRgrc === undefined) delete process.env.RIPGREP_CONFIG_PATH;
else process.env.RIPGREP_CONFIG_PATH = prevRgrc;
await fs.rm(parityDir, { recursive: true, force: true });
}
});
it("tokenizes quoted arguments properly", () => {
assert.deepEqual(tokenizeArgs(`log --grep="hello world" -n 3`), [
"log",
"--grep=hello world",
"-n",
"3",
]);
});
it("enforces strict output budgets and reports invalid inputs cleanly", async () => {
const empty = await runBatchSearch({ cwd: tmpDir, queries: [] });
assert.equal(empty.isError, true);
const badCwd = await runBatchSearch({
cwd: path.join(tmpDir, "does-not-exist"),
queries: [{ type: "glob", pattern: "*" }],
});
assert.equal(badCwd.isError, true);
const badRegex = await runBatchSearch(
{ cwd: tmpDir, queries: [{ type: "regex", pattern: "[invalid(" }] },
{ forceNodeFallback: true },
);
assert.equal(badRegex.isError, false);
assert.match(badRegex.text, /ERROR:/);
const tinyBudget = await runBatchSearch({
cwd: tmpDir,
maxChars: 500,
queries: Array.from({ length: 6 }, (_, i) => ({
type: "text" as const,
pattern: i === 0 ? "e" : `QueryMiss_${i}`,
maxResults: 50,
})),
});
assert.ok(
tinyBudget.text.length <= 500,
`Expected <= 500 chars, got ${tinyBudget.text.length}`,
);
assert.match(tinyBudget.text, /## Query 6/);
// Default call with heavy multi-byte UTF-8 matches must stay <= 8,800 UTF-8 bytes to avoid host spill-to-disk
const cjkFile = path.join(tmpDir, "cjk-heavy.txt");
const cjkLines = Array.from(
{ length: 120 },
(_, i) => `第${i + 1}行:中文测试数据_CJK_MATCH_锚点_用于验证默认内联字节上限不触发落盘_${"测试内容".repeat(12)}`,
);
await fs.writeFile(cjkFile, cjkLines.join("\n"), "utf8");
const cjkRes = await runBatchSearch({
cwd: tmpDir,
queries: [
{ type: "text", pattern: "CJK_MATCH", path: "cjk-heavy.txt", maxResults: 120 },
{ type: "text", pattern: "getUsers", path: "src/api/routes.ts" },
],
});
assert.equal(cjkRes.isError, false);
const cjkBytes = Buffer.byteLength(cjkRes.text, "utf8");
assert.ok(
cjkBytes <= 8_800,
`Expected default batch_search UTF-8 bytes <= 8800, got ${cjkBytes}`,
);
assert.match(cjkRes.text, /## Query 2/);
assert.match(cjkRes.text, /getUsers/);
// Explicit maxChars > 8800 is still hard-capped <= 8800 UTF-8 bytes
const explicitLarge = await runBatchSearch({
cwd: tmpDir,
maxChars: 50_000,
queries: [{ type: "text", pattern: "CJK_MATCH", path: "cjk-heavy.txt", maxResults: 120 }],
});
assert.equal(explicitLarge.isError, false);
assert.ok(Buffer.byteLength(explicitLarge.text, "utf8") <= 8_800);
// Glob truncation reports omitted top-level directories
const globDir = path.join(tmpDir, "glob-many");
await fs.mkdir(path.join(globDir, "alpha"), { recursive: true });
await fs.mkdir(path.join(globDir, "views"), { recursive: true });
await fs.mkdir(path.join(globDir, "components"), { recursive: true });
for (let i = 0; i < 6; i++) {
await fs.writeFile(path.join(globDir, "alpha", `a${i}.ts`), "x", "utf8");
await fs.writeFile(path.join(globDir, "views", `v${i}.vue`), "x", "utf8");
await fs.writeFile(path.join(globDir, "components", `c${i}.vue`), "x", "utf8");
}
const globTrunc = await runBatchSearch({
cwd: globDir,
queries: [{ type: "glob", pattern: "**/*", maxResults: 5 }],
});
assert.equal(globTrunc.isError, false);
assert.match(globTrunc.text, /truncated at 5 of 18 files/);
assert.match(globTrunc.text, /omitted dirs:/);
assert.match(globTrunc.text, /views\/ \(6\)/);
});
it("auto-recovers regex alternation and bare keywords passed to glob queries", async () => {
const globDir = path.join(tmpDir, "glob-fallback");
await fs.mkdir(path.join(globDir, "proxy"), { recursive: true });
await fs.mkdir(path.join(globDir, "scripts"), { recursive: true });
await fs.writeFile(path.join(globDir, "proxy", "network.ts"), "export {};", "utf8");
await fs.writeFile(path.join(globDir, "scripts", "live-smoke.ts"), "export {};", "utf8");
await fs.writeFile(path.join(globDir, "scripts", "mission-check.mjs"), "export {};", "utf8");
const res = await runBatchSearch({
cwd: globDir,
queries: [
{ type: "glob", pattern: "proxy" },
{ type: "glob", pattern: "smoke|mission|lock", path: "scripts" },
{ type: "glob", pattern: "foo|bar", path: "scripts" },
{ type: "glob", pattern: "missing.ts" },
],
});
assert.equal(res.isError, false);
assert.match(res.text, /auto-expanded regex '\|'/);
assert.match(res.text, /showing case-insensitive path matches for "\*proxy\*"/);
assert.match(res.text, /proxy\/network\.ts/);
assert.match(res.text, /scripts\/live-smoke\.ts/);
assert.match(res.text, /scripts\/mission-check\.mjs/);
assert.match(res.text, /hint: glob uses \* and \{a,b\}, not regex \|/);
// Missing exact filename with extension stays clean "(no files matched)"
assert.match(res.text, /## Query 4 \[glob\] missing\.ts\n\(no files matched\)/);
// If an exact bare file exists, exact match wins without triggering fallback note
await fs.writeFile(path.join(globDir, "proxy", "exactfile"), "x", "utf8");
const exactRes = await runBatchSearch({
cwd: globDir,
queries: [{ type: "glob", pattern: "exactfile" }],
});
assert.equal(exactRes.isError, false);
assert.match(exactRes.text, /proxy\/exactfile/);
assert.doesNotMatch(exactRes.text, /auto-expanded|showing case-insensitive/);
});
it("circuit-breaks corrupted queries (boolean/null) without crashing and accepts stringified JSON arrays", async () => {
const corrupt = await runBatchSearch({
cwd: tmpDir,
queries: [null, true] as unknown as never[],
});
assert.equal(corrupt.isError, true);
assert.match(corrupt.text, /nested argument serialization corruption/i);
assert.match(corrupt.text, /queries\[0\]: received null/);
assert.match(corrupt.text, /queries\[1\]: received boolean \(true\)/);
const topCorrupt = await runBatchSearch({
cwd: tmpDir,
queries: false as unknown as never[],
});
assert.equal(topCorrupt.isError, true);
assert.match(topCorrupt.text, /queries: received boolean \(false\)/);
const stringified = await runBatchSearch({
cwd: tmpDir,
queries: JSON.stringify([{ type: "text", pattern: "getUsers", path: "src/api/routes.ts" }]) as unknown as never[],
});
assert.equal(stringified.isError, false);
assert.match(stringified.text, /getUsers/);
// Shell chaining operators in git queries are rejected with clear guidance
const chainedGit = await runBatchSearch({
cwd: tmpDir,
queries: [{ type: "git", pattern: "status && diff --stat" }],
});
assert.equal(chainedGit.isError, false);
assert.match(chainedGit.text, /Shell operator '&&' is not supported/);
});
it("hardens untrusted git config execution, fixes branch/tag --merged & shortlog, and enforces truncation + surrogate safety", async () => {
// 1. branch/tag --merged <commit> and tag --contains HEAD v* allowed; flag bypasses still blocked
assert.deepEqual(validateReadonlyGitArgs("branch --merged main"), ["--no-pager", "branch", "--merged", "main"]);
assert.deepEqual(validateReadonlyGitArgs("branch --no-merged origin/main"), ["--no-pager", "branch", "--no-merged", "origin/main"]);
assert.deepEqual(validateReadonlyGitArgs("tag --merged main"), ["--no-pager", "tag", "--merged", "main"]);
assert.deepEqual(validateReadonlyGitArgs("tag --contains HEAD v*"), ["--no-pager", "tag", "--contains", "HEAD", "v*"]);
for (const bad of [
"branch --merged -D victim",
"branch --merged --delete victim",
"branch --points-at -- --no-points-at -D victim",
"branch --merged -- -D victim",
"tag --merged -d v1.0",
"tag --points-at -- --no-points-at -d v1.0",
"tag --contains -- -d v1.0",
"tag -v v1.0",
"tag --verify v1.0",
"remote show ssh://[email protected]:2222/repo.git",
"remote show https://example.com/repo.git",
]) {
assert.throws(() => validateReadonlyGitArgs(bad), `Expected '${bad}' to be rejected`);
}
// 2. Untrusted .git/config diff.external, textconv, and core.fsmonitor must NOT execute
const untrustedRepo = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-git-hardening-"));
try {
execFileSync("git", ["init", "-q"], { cwd: untrustedRepo });
execFileSync("git", ["config", "user.email", "[email protected]"], { cwd: untrustedRepo });
execFileSync("git", ["config", "user.name", "Test User"], { cwd: untrustedRepo });
await fs.writeFile(path.join(untrustedRepo, "doc.txt"), "v1\n", "utf8");
await fs.writeFile(path.join(untrustedRepo, ".gitattributes"), "*.txt diff=evil\n", "utf8");
execFileSync("git", ["add", "."], { cwd: untrustedRepo });
execFileSync("git", ["commit", "-q", "-m", "init"], { cwd: untrustedRepo });
await fs.writeFile(path.join(untrustedRepo, "doc.txt"), "v2\n", "utf8");
const markerExt = path.join(untrustedRepo, "pwn_ext");
const markerTc = path.join(untrustedRepo, "pwn_tc");
const markerFs = path.join(untrustedRepo, "pwn_fs");
const markerGpg = path.join(untrustedRepo, "pwn_gpg");
const touchCmd = (p: string) =>
`${JSON.stringify(process.execPath)} -e ${JSON.stringify(`require('fs').writeFileSync(${JSON.stringify(p)},'1')`)}`;
execFileSync("git", ["config", "diff.external", touchCmd(markerExt)], { cwd: untrustedRepo });
execFileSync("git", ["config", "diff.evil.textconv", touchCmd(markerTc)], { cwd: untrustedRepo });
execFileSync("git", ["config", "core.fsmonitor", touchCmd(markerFs)], { cwd: untrustedRepo });
execFileSync("git", ["config", "gpg.program", touchCmd(markerGpg)], { cwd: untrustedRepo });
execFileSync("git", ["remote", "add", "show", "https://example.invalid/repo.git"], { cwd: untrustedRepo });
const gRes = await runBatchSearch({
cwd: untrustedRepo,
queries: [
{ type: "git", pattern: "status --short" },
{ type: "git", pattern: "diff" },
{ type: "git", pattern: "blame doc.txt" },
{ type: "git", pattern: "shortlog -sn" },
{ type: "git", pattern: "shortlog -S v1 HEAD" },
{ type: "git", pattern: "log --show-signature -n 1" },
{ type: "git", pattern: "remote get-url show" },
],
});
assert.equal(gRes.isError, false);
assert.match(gRes.text, /Test User/); // shortlog returns actual commit count instead of (empty output)
assert.match(gRes.text, /https:\/\/example\.invalid\/repo\.git/); // remote named 'show' must not inject -n
assert.equal(await fs.access(markerExt).then(() => true, () => false), false);
assert.equal(await fs.access(markerTc).then(() => true, () => false), false);
assert.equal(await fs.access(markerFs).then(() => true, () => false), false);
assert.equal(await fs.access(markerGpg).then(() => true, () => false), false);
// Prefix abbreviations of --ext-diff / --textconv and verbose git status flags are also rejected
assert.throws(() => validateReadonlyGitArgs("diff --textc"), /not allowed/i);
assert.throws(() => validateReadonlyGitArgs("diff --ext-dif"), /not allowed/i);
for (const badStatus of [
"status -v",
"status -vv",
"status --verbose",
"status --verb",
"status --v",
"status --verbose=2",
"status -bv",
"status -sv",
"status -vuall",
"status --long -v",
]) {
assert.throws(() => validateReadonlyGitArgs(badStatus), `Expected '${badStatus}' to be rejected`);
}
for (const okStatus of [
"status",
"status --short",
"status -sb",
"status -uall",
"status -suall",
"status -M50",
"status --no-verbose",
"status -- -v",
"status -- --verbose",
]) {
assert.doesNotThrow(() => validateReadonlyGitArgs(okStatus), `Expected '${okStatus}' to be allowed`);
}
// Stage doc.txt as well so both staged (-v/--verbose) and unstaged (-vv) textconv paths are covered
execFileSync("git", ["add", "doc.txt"], { cwd: untrustedRepo });
await fs.writeFile(path.join(untrustedRepo, "doc.txt"), "v3\n", "utf8");
const statusRes = await runBatchSearch({
cwd: untrustedRepo,
queries: [
{ type: "git", pattern: "status -v" },
{ type: "git", pattern: "status -vv" },
{ type: "git", pattern: "status --verbose" },
{ type: "git", pattern: "status --no-verbose" },
],
});
assert.equal(statusRes.isError, false);
assert.match(statusRes.text, /Flag '-v' is not allowed/);
assert.match(statusRes.text, /Flag '-vv' is not allowed/);
assert.match(statusRes.text, /Flag '--verbose' is not allowed/);
assert.equal(await fs.access(markerTc).then(() => true, () => false), false);
} finally {
await fs.rm(untrustedRepo, { recursive: true, force: true });
}
// 3. Single-file search accurately reports truncation, preserves contextLines across files after perFileCap, avoids phantom EOF ^$ match, and avoids lone surrogates
const edgeDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-search-edge-"));
try {
await fs.writeFile(
path.join(edgeDir, "a-many.txt"),
"needle\n".repeat(80) + "a" + "🚀".repeat(130) + "\n",
"utf8",
);
await fs.writeFile(path.join(edgeDir, "b-ctx.txt"), "before-ctx-line\nneedle\nafter-ctx-line\n", "utf8");
await fs.writeFile(path.join(edgeDir, "nonempty.txt"), "line1\nline2\n", "utf8");
for (let i = 0; i < 18; i++) {
await fs.writeFile(path.join(edgeDir, `m-pad-${String(i).padStart(2, "0")}.txt`), "filler\n", "utf8");
}
await fs.writeFile(path.join(edgeDir, "z-batch2.txt"), "batch2-before\nneedle\nbatch2-after\n", "utf8");
for (const forceNodeFallback of [false, true]) {
const res = await runBatchSearch(
{
cwd: edgeDir,
queries: [
{ type: "text", pattern: "needle", path: "a-many.txt", maxResults: 40 },
{ type: "text", pattern: "needle", path: "a-many.txt", maxResults: 60 },
{ type: "text", pattern: "a🚀", path: "a-many.txt" },
{ type: "regex", pattern: "^$", path: "nonempty.txt" },
{ type: "text", pattern: "needle", contextLines: 1, maxResults: 80 },
],
},
{ forceNodeFallback },
);
assert.equal(res.isError, false);
const sections = res.text.split("\n\n");
assert.match(sections[0]!, /truncated at 40 matches/);
assert.match(sections[1]!, /truncated at 60 matches/);
assert.equal(
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(res.text),
false,
"batch_search output must not contain lone UTF-16 surrogates",
);
assert.match(sections[3]!, /\(no matches\)/);
assert.match(sections[4]!, /before-ctx-line/);
assert.match(sections[4]!, /z-batch2\.txt/);
}
} finally {
await fs.rm(edgeDir, { recursive: true, force: true });
}
});
it("windows long-line matches past col 240 with accurate CJK/emoji offsets and surrogate safety (rg and Node fallback parity)", async () => {
const longDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-longline-"));
try {
const longLines = [
`# Doc ${"alpha ".repeat(110)}EXACT_COL650_PHRASE${" tail".repeat(40)}`,
`prefix ${"beta ".repeat(60)}CaseMixed_Regex_777${" end".repeat(50)}`,
`short_prefix_NEEDLE_EARLY ${"pad".repeat(120)}`,
`${"x".repeat(520)}END_OF_LINE_ANCHOR`,
`a${"🚀".repeat(160)}a${"中文前缀".repeat(30)}🎯CJK_EMOJI_TARGET🎉${"🎉".repeat(160)}`,
`ctx_long_line_${"c".repeat(300)}`,
`${"m".repeat(300)}MULTI_LINE_START`,
`MULTI_LINE_END${"n".repeat(300)}`,
];
await fs.writeFile(path.join(longDir, "long-md.md"), `${longLines.join("\n")}\n`, "utf8");
const queries = [
{ type: "text" as const, pattern: "EXACT_COL650_PHRASE", path: "long-md.md" },
{ type: "regex" as const, pattern: "casemixed_regex_\\d+", caseSensitive: false, path: "long-md.md" },
{ type: "text" as const, pattern: "NEEDLE_EARLY", path: "long-md.md" },
{ type: "text" as const, pattern: "END_OF_LINE_ANCHOR", path: "long-md.md" },
{ type: "text" as const, pattern: "🎯CJK_EMOJI_TARGET🎉", path: "long-md.md", contextLines: 1 },
{ type: "regex" as const, pattern: "MULTI_LINE_START\\nMULTI_LINE_END", multiline: true, path: "long-md.md" },
];
const rgRes = await runBatchSearch({ cwd: longDir, queries });
const nodeRes = await runBatchSearch({ cwd: longDir, queries }, { forceNodeFallback: true });
assert.equal(rgRes.isError, false);
assert.equal(nodeRes.isError, false);
assert.equal(rgRes.text, nodeRes.text, "rg and Node fallback long-line windowing must match exactly");
assert.equal(
/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/.test(rgRes.text),
false,
"windowed output must not contain lone UTF-16 surrogates",
);
const sections = rgRes.text.split("\n\n");
assert.equal(sections.length, 6);
// Q1: match past col 650 is windowed with leading + trailing "..." and visible
const q1Line = sections[0]!.split("\n").find((l) => l.startsWith(" 1: "));
assert.ok(q1Line, sections[0]);
assert.match(q1Line, /^ 1: \.\.\..*EXACT_COL650_PHRASE.*\.\.\.$/);
assert.ok(q1Line.length <= 260, `Expected compact window, got ${q1Line.length} chars`);
// Q2: case-insensitive regex past col 300 is visible
const q2Line = sections[1]!.split("\n").find((l) => l.startsWith(" 2: "));
assert.ok(q2Line, sections[1]);
assert.match(q2Line, /^ 2: \.\.\..*CaseMixed_Regex_777.*\.\.\.$/);
// Q3: match inside [0, 240] preserves exact prefix truncation (no leading "...")
const q3Line = sections[2]!.split("\n").find((l) => l.startsWith(" 3: "));
assert.ok(q3Line, sections[2]);
assert.match(q3Line, /^ 3: short_prefix_NEEDLE_EARLY .*\.\.\.$/);
assert.doesNotMatch(q3Line, /^ 3: \.\.\./);
// Q4: match at end of long line has leading "..." and no trailing "..."
const q4Line = sections[3]!.split("\n").find((l) => l.startsWith(" 4: "));
assert.ok(q4Line, sections[3]);
assert.match(q4Line, /^ 4: \.\.\..*END_OF_LINE_ANCHOR$/);
assert.doesNotMatch(q4Line, /\.\.\.$/);
// Q5: CJK + 4-byte emoji UTF-8 byte-to-UTF-16 conversion accuracy + context line prefix trimming
const q5MatchLine = sections[4]!.split("\n").find((l) => l.startsWith(" 5: "));
const q5CtxLine = sections[4]!.split("\n").find((l) => l.startsWith(" 6- "));
assert.ok(q5MatchLine, sections[4]);
assert.match(q5MatchLine, /^ 5: \.\.\..*🎯CJK_EMOJI_TARGET🎉.*\.\.\.$/);
assert.ok(q5CtxLine, sections[4]);
assert.match(q5CtxLine, /^ 6- ctx_long_line_c+\.\.\.$/);
assert.ok(q5CtxLine.length <= 255, `Expected context prefix trim <= 255, got ${q5CtxLine.length}`);
// Q6: multiline match across two long lines windows line 7 around MULTI_LINE_START and keeps line 8 prefix
const q6Line7 = sections[5]!.split("\n").find((l) => l.startsWith(" 7: "));
const q6Line8 = sections[5]!.split("\n").find((l) => l.startsWith(" 8: "));
assert.ok(q6Line7, sections[5]);
assert.ok(q6Line8, sections[5]);
assert.match(q6Line7, /^ 7: \.\.\..*MULTI_LINE_START$/);
assert.match(q6Line8, /^ 8: MULTI_LINE_ENDn+\.\.\.$/);
} finally {
await fs.rm(longDir, { recursive: true, force: true });
}
});
it("prevents multi-file starvation under tight budgets, avoids orphan context, and reports omitted files cleanly", async () => {
const budgetDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-budget-fair-"));
try {
// Helper to verify every rendered file block has >=1 real match and zero orphan context lines
const assertNoOrphanContext = (sectionText: string, ctxRadius: number) => {
const lines = sectionText.split("\n").slice(1); // skip "## Query ..."
let currentFile: string | null = null;
let matchNums: number[] = [];
let ctxNums: number[] = [];
const flush = () => {
if (!currentFile) return;
assert.ok(
matchNums.length > 0,
`File ${currentFile} rendered with 0 real match lines:\n${sectionText}`,
);
for (const cLn of ctxNums) {
const attached = matchNums.some((mLn) => Math.abs(cLn - mLn) <= ctxRadius);
assert.ok(
attached,
`Orphan context line ${cLn} in ${currentFile} (matches: ${matchNums.join(",")}):\n${sectionText}`,
);
}
};
for (const line of lines) {
if (line.startsWith("... [")) {
flush();
currentFile = null;
matchNums = [];
ctxNums = [];
continue;
}
if (line.startsWith(" ... (+")) continue;
const m = /^ (\d+)([:-]) /.exec(line);
if (m) {
const ln = Number(m[1]);
if (m[2] === ":") matchNums.push(ln);
else ctxNums.push(ln);
} else if (line.trim().length > 0) {
flush();
currentFile = line.trim();
matchNums = [];
ctxNums = [];
}
}
flush();
};
// 1. Exact 4-file `return ` with contextLines: 2 under tight maxChars (repro of file starvation bug)
const fourDir = path.join(budgetDir, "four");
await fs.mkdir(fourDir, { recursive: true });
for (const name of ["a.ts", "b.ts", "c.ts", "d.ts"]) {
const chunks: string[] = [];
for (let k = 1; k <= 8; k++) {
chunks.push(
`// ${name} fn${k} before-2 padding-text-for-context`,
`function ${name[0]}Fn${k}(arg: string) {`,
` return "${name}_val_${k}_" + arg;`,
`}`,
`// ${name} fn${k} after-2 padding-text-for-context`,
`// separator ${k}`,
);
}
await fs.writeFile(path.join(fourDir, name), `${chunks.join("\n")}\n`, "utf8");
}
const normalizeSpillPath = (text: string) =>
text.replace(/spill-\d+-[a-z0-9_-]+-[0-9a-f]+\.txt/g, "spill-<id>.txt");
const fourQuery = [{ type: "text" as const, pattern: "return ", contextLines: 2, maxResults: 40 }];
const rgFour = await runBatchSearch({ cwd: fourDir, maxChars: 1200, queries: fourQuery });
const nodeFour = await runBatchSearch(
{ cwd: fourDir, maxChars: 1200, queries: fourQuery },
{ forceNodeFallback: true },
);
assert.equal(rgFour.isError, false);
assert.equal(
normalizeSpillPath(rgFour.text),
normalizeSpillPath(nodeFour.text),
"4-file budgeted output must match between rg and Node fallback",
);
assert.ok(rgFour.text.length <= 1200, `Expected <= 1200 chars, got ${rgFour.text.length}`);
for (const name of ["a.ts", "b.ts", "c.ts", "d.ts"]) {
assert.ok(rgFour.text.includes(`\n${name}\n`), `Expected ${name} to be shown:\n${rgFour.text}`);
assert.ok(rgFour.text.includes(`${name}_val_1_`), `Expected first match of ${name}:\n${rgFour.text}`);
}
assert.match(rgFour.text, /\(\+\d+ more match/);
assert.match(rgFour.text, /\.\.\. \[truncated: showed \d+ of 32 matches across 4 files\]/);
assertNoOrphanContext(rgFour.text, 2);
// 2. All matches fit, only context lines omitted (verifies context-after-matches priority + zero orphans)
const ctxOnlyDir = path.join(budgetDir, "ctx-only");
await fs.mkdir(ctxOnlyDir, { recursive: true });
for (const name of ["f1.ts", "f2.ts", "f3.ts", "f4.ts"]) {
const lines = [
`// ${name} pre2 ${"p".repeat(90)}`,
`// ${name} pre1 ${"q".repeat(90)}`,
`return "${name}_m1";`,
`// ${name} post1 ${"r".repeat(90)}`,
`// ${name} post2 ${"s".repeat(90)}`,
`// gap`,
`// ${name} pre2b ${"t".repeat(90)}`,
`// ${name} pre1b ${"u".repeat(90)}`,
`return "${name}_m2";`,
`// ${name} post1b ${"v".repeat(90)}`,
`// ${name} post2b ${"w".repeat(90)}`,
];
await fs.writeFile(path.join(ctxOnlyDir, name), `${lines.join("\n")}\n`, "utf8");
}
const ctxOnlyQuery = [{ type: "text" as const, pattern: "return ", contextLines: 2 }];
const rgCtxOnly = await runBatchSearch({ cwd: ctxOnlyDir, maxChars: 900, queries: ctxOnlyQuery });
const nodeCtxOnly = await runBatchSearch(
{ cwd: ctxOnlyDir, maxChars: 900, queries: ctxOnlyQuery },
{ forceNodeFallback: true },
);
assert.equal(normalizeSpillPath(rgCtxOnly.text), normalizeSpillPath(nodeCtxOnly.text));
assert.ok(rgCtxOnly.text.length <= 900);
for (const name of ["f1.ts", "f2.ts", "f3.ts", "f4.ts"]) {
assert.ok(rgCtxOnly.text.includes(`${name}_m1`), rgCtxOnly.text);
assert.ok(rgCtxOnly.text.includes(`${name}_m2`), rgCtxOnly.text);
}
assert.match(rgCtxOnly.text, /showed all 8 matches across 4 files; omitted context lines/);
assertNoOrphanContext(rgCtxOnly.text, 2);
// 3. Extreme many-file truncation where not all files fit 1 match line (including CJK UTF-8 byte ceiling)
const manyFilesDir = path.join(budgetDir, "many-files");
await fs.mkdir(manyFilesDir, { recursive: true });
for (let i = 0; i < 65; i++) {
const file = `mod_${String(i).padStart(2, "0")}.ts`;
const content = [
`export const v1_${i} = "MANY_FILE_TOKEN_中文测试数据_${i}_a_${"填充".repeat(20)}";`,
`export const v2_${i} = "MANY_FILE_TOKEN_中文测试数据_${i}_b_${"填充".repeat(20)}";`,
`export const v3_${i} = "MANY_FILE_TOKEN_中文测试数据_${i}_c_${"填充".repeat(20)}";`,
].join("\n");
await fs.writeFile(path.join(manyFilesDir, file), `${content}\n`, "utf8");
}
const manyQuery = [{ type: "text" as const, pattern: "MANY_FILE_TOKEN", maxResults: 200 }];
const rgManyTight = await runBatchSearch({ cwd: manyFilesDir, maxChars: 1400, queries: manyQuery });
const nodeManyTight = await runBatchSearch(
{ cwd: manyFilesDir, maxChars: 1400, queries: manyQuery },
{ forceNodeFallback: true },
);
assert.equal(normalizeSpillPath(rgManyTight.text), normalizeSpillPath(nodeManyTight.text));
assert.ok(rgManyTight.text.length <= 1400);
assert.ok(Buffer.byteLength(rgManyTight.text, "utf8") <= 8_800);
assert.match(rgManyTight.text, /more files: mod_\d+\.ts \(3\)/);
assert.match(rgManyTight.text, /\+\d+ more files; use outputMode: "files_with_matches"/);
assert.match(rgManyTight.text, /\.\.\. \[truncated: showed \d+ of 195 matches across \d+ of 65 files\]/);
assertNoOrphanContext(rgManyTight.text, 0);
// Default maxChars (8500) with heavy CJK multi-byte payload across 65 files must stay <= 8800 UTF-8 bytes and report omitted files
const rgManyDefault = await runBatchSearch({ cwd: manyFilesDir, queries: manyQuery });
const nodeManyDefault = await runBatchSearch(
{ cwd: manyFilesDir, queries: manyQuery },
{ forceNodeFallback: true },
);
assert.equal(normalizeSpillPath(rgManyDefault.text), normalizeSpillPath(nodeManyDefault.text));
assert.ok(
Buffer.byteLength(rgManyDefault.text, "utf8") <= 8_800,
`Expected <= 8800 UTF-8 bytes, got ${Buffer.byteLength(rgManyDefault.text, "utf8")}`,
);
assert.match(rgManyDefault.text, /more files: mod_\d+\.ts \(3\)/);
assert.match(rgManyDefault.text, /use outputMode: "files_with_matches"/);
assert.match(rgManyDefault.text, /\.\.\. \[truncated: showed \d+ of 195 matches across \d+ of 65 files\]/);
assertNoOrphanContext(rgManyDefault.text, 0);
// 4. Mixed short + long multi-query water-filling, single-file many-match, multiline match, and exact-fit preservation
const mixedDir = path.join(budgetDir, "mixed");
await fs.mkdir(mixedDir, { recursive: true });
await fs.writeFile(path.join(mixedDir, "exact.ts"), "export const EXACT_SHORT_HIT = 42;\n", "utf8");
await fs.writeFile(
path.join(mixedDir, "single.ts"),
Array.from({ length: 40 }, (_, i) => `const singleRow${i + 1} = "SINGLE_MANY_HIT_${i + 1}_payload_text";`).join("\n") + "\n",
"utf8",
);
for (const name of ["m1.ts", "m2.ts", "m3.ts"]) {
const blocks = Array.from(
{ length: 6 },
(_, k) => `MULTI_START_${name}_${k}\nMULTI_END_${name}_${k}_${"z".repeat(40)}\n`,
).join("\n");
await fs.writeFile(path.join(mixedDir, name), blocks, "utf8");
}
const mixedQueries = [
{ type: "text" as const, pattern: "EXACT_SHORT_HIT", path: "exact.ts" },
{ type: "text" as const, pattern: "return ", path: "../four", contextLines: 2, maxResults: 40 },
{ type: "text" as const, pattern: "SINGLE_MANY_HIT", path: "single.ts", maxResults: 40 },
{ type: "regex" as const, pattern: "MULTI_START_\\S+\\nMULTI_END_\\S+", multiline: true, maxResults: 40 },
];
const rgMixed = await runBatchSearch({ cwd: mixedDir, maxChars: 2400, queries: mixedQueries });
const nodeMixed = await runBatchSearch(
{ cwd: mixedDir, maxChars: 2400, queries: mixedQueries },
{ forceNodeFallback: true },
);
assert.equal(rgMixed.isError, false);
assert.equal(
normalizeSpillPath(rgMixed.text),
normalizeSpillPath(nodeMixed.text),
"mixed multi-query budgeted output must match between rg and Node fallback",
);
assert.ok(rgMixed.text.length <= 2400, `Expected <= 2400 chars, got ${rgMixed.text.length}`);
assert.ok(Buffer.byteLength(rgMixed.text, "utf8") <= 8_800);
const mixedSections = rgMixed.text.split("\n\n");
assert.equal(mixedSections.length, 4);
// Q1 fits completely -> exact untouched output (no truncation notice)
assert.equal(
mixedSections[0],
"## Query 1 [text] EXACT_SHORT_HIT (in exact.ts)\nexact.ts\n 1: export const EXACT_SHORT_HIT = 42;",
);
// Q2 covers all 4 files instead of starving later files
for (const name of ["a.ts", "b.ts", "c.ts", "d.ts"]) {
assert.ok(mixedSections[1]!.includes(name), `Expected ${name} in Q2:\n${mixedSections[1]}`);
}
assertNoOrphanContext(mixedSections[1]!, 2);
// Q3 single-file many-match shows clean omission count + "in 1 file"
assert.match(mixedSections[2]!, /\(\+\d+ more matches\)/);
assert.match(mixedSections[2]!, /showed \d+ of 40 matches in 1 file/);
// Q4 multiline query covers all 3 files fairly
for (const name of ["m1.ts", "m2.ts", "m3.ts"]) {
assert.ok(mixedSections[3]!.includes(`\n${name}\n`), `Expected ${name} in Q4:\n${mixedSections[3]}`);
}
// 5. Fitting query preserves exact existing format without budget-truncation notices
const fitRes = await runBatchSearch({
cwd: fourDir,
maxChars: 8500,
queries: [{ type: "text", pattern: "return ", contextLines: 1, maxResults: 10 }],
});
assert.equal(fitRes.isError, false);
assert.doesNotMatch(fitRes.text, /\(\+\d+ more match/);
assert.match(fitRes.text, /\.\.\. \[truncated at 10 matches\]$/);
} finally {
await fs.rm(budgetDir, { recursive: true, force: true });
}
});
it("hardens fs-utils globToRegExp/walkFiles/resolvePath and batch_search stringified limits, hidden globs, and fast-path CRLF parity", async () => {
// 1. globToRegExp resists repeated `**/` ReDoS and handles brace spaces & negated/leading-`]` char classes
const redosStart = Date.now();
const collapsed = globToRegExp("**/**/**/**/**/**/**/**/nope.ts");
assert.equal(collapsed.test("a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/file.js"), false);
assert.ok(Date.now() - redosStart < 100, "Repeated **/ glob must stay linear-time");
assert.equal(globToRegExp("foo{ ,_}bar.ts").test("foo bar.ts"), true);
assert.equal(globToRegExp("foo{ ,_}bar.ts").test("foobar.ts"), false);
assert.equal(globToRegExp("[!a].ts").test("b.ts"), true);
assert.equal(globToRegExp("[!a].ts").test("/.ts"), false);
assert.equal(globToRegExp("[]a].ts").test("].ts"), true);
assert.equal(globToRegExp("{a[,],b}.ts").test("a,.ts"), true);
// 2. resolvePath binds drive-less leading-slash paths to baseDir's drive on Windows
if (process.platform === "win32") {
assert.equal(resolvePath("/src/index.ts", "D:\\repo"), "D:\\src\\index.ts");
}
// 3. walkFiles returns deterministic order and does not report truncated when file count === maxFiles
const walkDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-walk-exact-"));
try {
await fs.mkdir(path.join(walkDir, "b"), { recursive: true });
await fs.mkdir(path.join(walkDir, "a"), { recursive: true });
await fs.writeFile(path.join(walkDir, "a", "1.ts"), "export const a = 1;\r\n", "utf8");
await fs.writeFile(path.join(walkDir, "b", "2.ts"), "export const b = 2;\r\n", "utf8");
await fs.writeFile(path.join(walkDir, "c.ts"), "export const c = 3;\r\n", "utf8");
await fs.writeFile(path.join(walkDir, ".env"), "SECRET=1\n", "utf8");
await fs.mkdir(path.join(walkDir, ".hidden"), { recursive: true });
await fs.writeFile(path.join(walkDir, ".hidden", "skip.ts"), "export const h = 1;\n", "utf8");
const exact = await walkFiles(walkDir, { maxFiles: 3 });
assert.deepEqual(exact.files, ["c.ts", "a/1.ts", "b/2.ts"]);
assert.equal(exact.truncated, false);
const over = await walkFiles(walkDir, { maxFiles: 2 });
assert.deepEqual(over.files, ["c.ts", "a/1.ts"]);
assert.equal(over.truncated, true);
// 4. Stringified maxResults does not collapse to 1; `./` prefix does not crawl hidden dirs; `{.env,...}` finds dotfiles
const strLimit = await runBatchSearch({
cwd: walkDir,
queries: [
{ type: "glob", pattern: "**/*.ts", maxResults: "10" as unknown as number },
{ type: "glob", pattern: "./**/*.ts" },
{ type: "glob", pattern: "{.env,.env.local}" },
{ type: "regex", pattern: "const b = 2;$" },
],
}, { forceNodeFallback: true });
assert.equal(strLimit.isError, false);
const secs = strLimit.text.split("\n\n");
assert.match(secs[0]!, /a\/1\.ts/);
assert.match(secs[0]!, /b\/2\.ts/);
assert.match(secs[0]!, /c\.ts/);
assert.doesNotMatch(secs[0]!, /truncated/);
assert.doesNotMatch(secs[1]!, /\.hidden\/skip\.ts/);
assert.match(secs[2]!, /\.env/);
assert.match(secs[3]!, /b\/2\.ts\n\s+1: export const b = 2;/);
} finally {
await fs.rm(walkDir, { recursive: true, force: true });
}
});
it("keeps default excluded dirs ahead of positive user globs, honors explicit excluded-dir globs & external paths, preserves lookaround regexes, and bounds walkFiles on truncation", async () => {
const outerDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-glob-prec-"));
const wsDir = path.join(outerDir, "ws");
const externalDistDir = path.join(outerDir, "shared", "dist");
try {
await fs.mkdir(path.join(wsDir, "src"), { recursive: true });
await fs.mkdir(path.join(wsDir, "dist"), { recursive: true });
await fs.mkdir(path.join(wsDir, "node_modules", "pkg"), { recursive: true });
await fs.mkdir(externalDistDir, { recursive: true });
await fs.writeFile(path.join(wsDir, "src", "app.mjs"), "export const x = 'NEEDLE_GLOB_TEST src';\n", "utf8");
await fs.writeFile(path.join(wsDir, "dist", "bundle.mjs"), "export const x = 'NEEDLE_GLOB_TEST dist';\n", "utf8");
await fs.writeFile(path.join(wsDir, "node_modules", "pkg", "index.mjs"), "export const x = 'NEEDLE_GLOB_TEST nm';\n", "utf8");
await fs.writeFile(path.join(externalDistDir, "lib.mjs"), "export const x = 'NEEDLE_GLOB_TEST external_dist';\n", "utf8");
await fs.writeFile(path.join(wsDir, "src", "lookaround.txt"), "foo\nbar\nqux\r\nbaz\n", "utf8");
await fs.writeFile(path.join(wsDir, "src", "lookbehind.txt"), "bar\nfoo\n", "utf8");
// 1. Both ripgrep and Node fallback keep default exclusions for positive globs like `*.mjs`,
// while honoring explicit `dist/*.mjs`, `{dist,src}/*.mjs`, and external `../shared/dist`.
for (const forceNodeFallback of [false, true]) {
const res = await runBatchSearch(
{
cwd: wsDir,
queries: [
{ type: "text", pattern: "NEEDLE_GLOB_TEST", glob: "*.mjs" },
{ type: "text", pattern: "NEEDLE_GLOB_TEST", glob: "dist/*.mjs" },
{ type: "text", pattern: "NEEDLE_GLOB_TEST", glob: "{dist,src}/*.mjs" },
{ type: "text", pattern: "NEEDLE_GLOB_TEST", path: "../shared/dist" },
{ type: "text", pattern: "NEEDLE_GLOB_TEST", path: "../shared/dist", glob: "*.mjs" },
],
},
{ forceNodeFallback },
);
assert.equal(res.isError, false);
const sections = res.text.split("\n\n");
// Query 1: `*.mjs` must NOT pierce default exclusions (`dist/` or `node_modules/`)
assert.match(sections[0]!, /src\/app\.mjs/);
assert.doesNotMatch(sections[0]!, /dist\/bundle\.mjs/);
assert.doesNotMatch(sections[0]!, /node_modules/);
// Query 2: explicit `dist/*.mjs` searches `dist/` while keeping `node_modules/` excluded
assert.match(sections[1]!, /dist\/bundle\.mjs/);
assert.doesNotMatch(sections[1]!, /src\/app\.mjs/);
assert.doesNotMatch(sections[1]!, /node_modules/);
// Query 3: brace glob `{dist,src}/*.mjs` searches both `dist/` and `src/`
assert.match(sections[2]!, /src\/app\.mjs/);
assert.match(sections[2]!, /dist\/bundle\.mjs/);
assert.doesNotMatch(sections[2]!, /node_modules/);
// Query 4 & 5: external path `../shared/dist` is not wiped out by default `!**/dist/**`
assert.match(sections[3]!, /NEEDLE_GLOB_TEST external_dist/);
assert.match(sections[4]!, /NEEDLE_GLOB_TEST external_dist/);
}
// 2. Lookaround regexes must not false-negative in Node whole-file precheck
const lookRes = await runBatchSearch(
{
cwd: wsDir,
queries: [
{ type: "regex", pattern: "foo(?!\\s)" },
{ type: "regex", pattern: "(?<!\\s)foo" },
{ type: "regex", pattern: "qux(?![\\r\\n])" },
],
},
{ forceNodeFallback: true },
);
assert.equal(lookRes.isError, false);
const lookSecs = lookRes.text.split("\n\n");
assert.match(lookSecs[0]!, /src\/lookaround\.txt\n\s+1: foo/);
assert.match(lookSecs[0]!, /src\/lookbehind\.txt\n\s+2: foo/);
assert.match(lookSecs[1]!, /src\/lookaround\.txt\n\s+1: foo/);
assert.match(lookSecs[1]!, /src\/lookbehind\.txt\n\s+2: foo/);
assert.match(lookSecs[2]!, /src\/lookaround\.txt\n\s+3: qux/);
// 3. walkFiles keeps simultaneous fs.readdir <= 16 and leaves 0 in-flight calls after truncation
const nestedDir = path.join(outerDir, "nested");
for (let i = 0; i < 24; i++) {
const sub = path.join(nestedDir, `d${String(i).padStart(2, "0")}`, "leaf");
await fs.mkdir(sub, { recursive: true });
await fs.writeFile(path.join(sub, "f1.ts"), "export const a = 1;\n", "utf8");
await fs.writeFile(path.join(sub, "f2.ts"), "export const b = 2;\n", "utf8");
}
const origReaddir = fs.readdir as (...args: unknown[]) => Promise<unknown>;
let inFlight = 0;
let maxInFlight = 0;
(fs as unknown as { readdir: (...args: unknown[]) => Promise<unknown> }).readdir = async (
...args: unknown[]
) => {
inFlight++;
if (inFlight > maxInFlight) maxInFlight = inFlight;
try {
await new Promise((r) => setTimeout(r, 4));
return await origReaddir(...args);
} finally {
inFlight--;
}
};
try {
const fullWalk = await walkFiles(nestedDir, { maxFiles: 100 });
assert.equal(fullWalk.truncated, false);
assert.equal(fullWalk.files.length, 48);
assert.ok(maxInFlight <= 16, `Expected <=16 concurrent readdirs, got ${maxInFlight}`);
assert.equal(inFlight, 0);
maxInFlight = 0;
const truncWalk = await walkFiles(nestedDir, { maxFiles: 3 });
assert.equal(truncWalk.truncated, true);
assert.equal(truncWalk.files.length, 3);
assert.ok(maxInFlight <= 16, `Expected <=16 concurrent readdirs on truncation, got ${maxInFlight}`);
assert.equal(inFlight, 0, "walkFiles must not leave dangling readdir calls after truncation");
} finally {
(fs as unknown as { readdir: (...args: unknown[]) => Promise<unknown> }).readdir = origReaddir;
}
} finally {
await fs.rm(outerDir, { recursive: true, force: true });
}
});
it("handles anchored globs under symlinked workspaces in content and summary modes and preserves inline-modifier regexes", async () => {
const outerDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-symlink-glob-"));
const realWs = path.join(outerDir, "real-ws");
const linkWs = path.join(outerDir, "link-ws");
try {
await fs.mkdir(path.join(realWs, "src"), { recursive: true });
await fs.mkdir(path.join(realWs, "lib"), { recursive: true });
await fs.mkdir(path.join(realWs, "dist"), { recursive: true });
await fs.mkdir(path.join(realWs, "node_modules", "pkg"), { recursive: true });
await fs.writeFile(path.join(realWs, "src", "app.mjs"), "export const v = 'NEEDLE_LINK src';\n", "utf8");
await fs.writeFile(path.join(realWs, "lib", "util.mjs"), "export const v = 'NEEDLE_LINK lib';\n", "utf8");
await fs.writeFile(path.join(realWs, "dist", "bundle.mjs"), "export const v = 'NEEDLE_LINK dist';\n", "utf8");
await fs.writeFile(path.join(realWs, "node_modules", "pkg", "index.mjs"), "export const v = 'NEEDLE_LINK nm';\n", "utf8");
await fs.writeFile(path.join(realWs, "src", "mod.txt"), "bar\nfoo\n", "utf8");
let symlinkReady = true;
try {
await fs.symlink(realWs, linkWs, process.platform === "win32" ? "junction" : "dir");
} catch {
symlinkReady = false;
}
if (symlinkReady) {
for (const forceNodeFallback of [false, true]) {
const res = await runBatchSearch(
{
cwd: linkWs,
queries: [
{ type: "text", pattern: "NEEDLE_LINK", glob: "dist/*.mjs" },
{ type: "text", pattern: "NEEDLE_LINK", glob: "{dist,src}/*.mjs", outputMode: "files_with_matches" },
{ type: "text", pattern: "NEEDLE_LINK", glob: "dist/*.mjs", outputMode: "count" },
{ type: "text", pattern: "NEEDLE_LINK", glob: "!src/**" },
],
},
{ forceNodeFallback },
);
assert.equal(res.isError, false);
const secs = res.text.split("\n\n");
assert.match(secs[0]!, /dist\/bundle\.mjs/);
assert.doesNotMatch(secs[0]!, /src\/app\.mjs/);
assert.doesNotMatch(secs[0]!, /node_modules/);
assert.match(secs[1]!, /dist\/bundle\.mjs/);
assert.match(secs[1]!, /src\/app\.mjs/);
assert.doesNotMatch(secs[1]!, /node_modules/);
assert.match(secs[2]!, /dist\/bundle\.mjs.*1/);
assert.doesNotMatch(secs[2]!, /src\/app\.mjs/);
assert.match(secs[3]!, /lib\/util\.mjs/);
assert.doesNotMatch(secs[3]!, /src\/app\.mjs/);
assert.doesNotMatch(secs[3]!, /dist\/bundle\.mjs/);
}
}
let supportsInlineModifiers = false;
try {
new RegExp("(?-m:^foo)");
supportsInlineModifiers = true;
} catch {
// Node < 24 does not support ES2025 inline RegExp modifiers
}
if (supportsInlineModifiers) {
const modRes = await runBatchSearch(
{
cwd: realWs,
queries: [{ type: "regex", pattern: "(?-m:^foo)" }],
},
{ forceNodeFallback: true },
);
assert.equal(modRes.isError, false);
assert.match(modRes.text, /src\/mod\.txt\n\s+2: foo/);
}
} finally {
await fs.rm(outerDir, { recursive: true, force: true });
}
});
it("renders CJK filenames verbatim without octal escaping in git queries", async () => {
const cjkDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-cjk-git-"));
try {
execFileSync("git", ["init", "-q"], { cwd: cjkDir });
execFileSync("git", ["config", "user.email", "[email protected]"], { cwd: cjkDir });
execFileSync("git", ["config", "user.name", "Test"], { cwd: cjkDir });
execFileSync("git", ["config", "core.quotePath", "true"], { cwd: cjkDir });
await fs.writeFile(path.join(cjkDir, "base.ts"), "export const ok = 1;\n", "utf8");
execFileSync("git", ["add", "base.ts"], { cwd: cjkDir });
execFileSync("git", ["commit", "-q", "-m", "init"], { cwd: cjkDir });
await fs.writeFile(path.join(cjkDir, "中文模块.ts"), "export const zh = 1;\n", "utf8");
const res = await runBatchSearch({
cwd: cjkDir,
queries: [{ type: "git", pattern: "status --short" }],
});
assert.equal(res.isError, false);
assert.ok(res.text.includes("中文模块.ts"), `Expected verbatim CJK filename:\n${res.text}`);
assert.ok(!res.text.includes("\\344\\270\\255"), `Unexpected octal-escaped path:\n${res.text}`);
} finally {
await fs.rm(cjkDir, { recursive: true, force: true });
}
});
it("enforces walkFiles maxDirs/timeoutMs budgets and supports contextLines up to 10", async () => {
const budgetDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-walk-budget-"));
try {
// Create 12 sibling subdirectories + a 25-line file for contextLines: 10 verification
for (let i = 0; i < 12; i++) {
const sub = path.join(budgetDir, `dir_${String(i).padStart(2, "0")}`);
await fs.mkdir(sub, { recursive: true });
await fs.writeFile(path.join(sub, `file_${i}.ts`), `export const n = ${i};\n`, "utf8");
}
const ctxLines = Array.from({ length: 25 }, (_, idx) =>
idx === 12 ? "const CONTEXT_TARGET_LINE = true;" : `// line ${idx + 1}`,
);
await fs.writeFile(path.join(budgetDir, "ctx.ts"), `${ctxLines.join("\n")}\n`, "utf8");
// 1. maxDirs caps glob & fuzzy scans gracefully instead of walking unbounded trees
const globCapRes = await runBatchSearch(
{
cwd: budgetDir,
queries: [
{ type: "glob", pattern: "does-not-exist-*.xyz" },
{ type: "fuzzy", pattern: "zzz_missing_token" },
],
},
{ walkMaxDirs: 3 },
);
assert.equal(globCapRes.isError, false);
assert.match(globCapRes.text, /scan budget reached/);
// 2. Partial matches found before maxDirs cap are returned with a budget notice
const partialRes = await runBatchSearch(
{
cwd: budgetDir,
queries: [{ type: "glob", pattern: "**/*.ts" }],
},
{ walkMaxDirs: 3 },
);
assert.equal(partialRes.isError, false);
assert.match(partialRes.text, /ctx\.ts/);
assert.match(partialRes.text, /scan budget reached/);
// 3. Node fallback respects walkMaxDirs cleanly without hanging
const nodeCapRes = await runBatchSearch(
{
cwd: budgetDir,
queries: [{ type: "text", pattern: "NO_SUCH_TOKEN_XYZ" }],
},
{ forceNodeFallback: true, walkMaxDirs: 3 },
);
assert.equal(nodeCapRes.isError, false);
assert.match(nodeCapRes.text, /scan budget reached/);
// 4. contextLines: 10 works in both rg and Node fallback (no longer clamped at 5)
for (const forceNodeFallback of [false, true]) {
const ctxRes = await runBatchSearch(
{
cwd: budgetDir,
queries: [{ type: "text", pattern: "CONTEXT_TARGET_LINE", path: "ctx.ts", contextLines: 10 }],
},
{ forceNodeFallback },
);
assert.equal(ctxRes.isError, false);
assert.match(ctxRes.text, /3- \/\/ line 3/);
assert.match(ctxRes.text, /13: const CONTEXT_TARGET_LINE = true;/);
assert.match(ctxRes.text, /23- \/\/ line 23/);
}
// 5. walkFiles timeoutMs stops cleanly without throwing and marks timedOut + truncated
const timedWalk = await walkFiles(budgetDir, {
maxDirs: 1000,
timeoutMs: 1,
fileFilter: () => false,
});
assert.equal(Array.isArray(timedWalk.files), true);
if (timedWalk.timedOut) {
assert.equal(timedWalk.truncated, true);
}
} finally {
await fs.rm(budgetDir, { recursive: true, force: true });
}
});
it("appends a parseable 1-line Example JSON on validation errors", async () => {
const emptyRes = await runBatchSearch({ queries: [] });
assert.equal(emptyRes.isError, true);
const match = emptyRes.text.match(/\nExample: (\{.*\})$/);
assert.ok(match, emptyRes.text);
assert.ok(Array.isArray(JSON.parse(match[1]!).queries));
const badQueryRes = await runBatchSearch({
queries: [{ type: "unknown" as never, pattern: "foo" }],
});
assert.equal(badQueryRes.isError, false);
assert.match(badQueryRes.text, /Example: \{"queries":/);
});
it("appends a compact files_with_matches/count tip on broad truncated content scans within budget", async () => {
const tipDir = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-broad-tip-"));
try {
const manyLines = Array.from({ length: 60 }, (_, i) => `export const BROAD_TOKEN_${i} = ${i};`).join("\n") + "\n";
await fs.writeFile(path.join(tipDir, "many.ts"), manyLines, "utf8");
const cappedRes = await runBatchSearch({
cwd: tipDir,
queries: [{ type: "text", pattern: "BROAD_TOKEN_" }],
});
assert.equal(cappedRes.isError, false);
assert.match(cappedRes.text, /\.\.\. \[truncated at 40 matches\]/);
assert.match(cappedRes.text, /\.\.\. \[tip: for broad scans, use outputMode: "files_with_matches" or "count"\]/);
assert.ok(Buffer.byteLength(cappedRes.text, "utf8") <= 8_800);
// Explicit small maxResults (<40) and files_with_matches do NOT emit redundant tip
const smallCapRes = await runBatchSearch({
cwd: tipDir,
queries: [{ type: "text", pattern: "BROAD_TOKEN_", maxResults: 5 }],
});
assert.doesNotMatch(smallCapRes.text, /\[tip:/);
const filesModeRes = await runBatchSearch({
cwd: tipDir,
queries: [{ type: "text", pattern: "BROAD_TOKEN_", outputMode: "files_with_matches" }],
});
assert.doesNotMatch(filesModeRes.text, /\[tip:/);
// Non-overflowing 40-match cap where tip would push past maxChars must NOT evict real matches to fit tip
const baseLen = cappedRes.text.replace(/\n\.\.\. \[tip:.*$/, "").length;
const tightFitRes = await runBatchSearch({
cwd: tipDir,
maxChars: baseLen + 10,
queries: [{ type: "text", pattern: "BROAD_TOKEN_" }],
});
assert.equal(tightFitRes.isError, false);
assert.match(tightFitRes.text, /BROAD_TOKEN_39/);
assert.doesNotMatch(tightFitRes.text, /\[tip:/);
// Source lines containing literal "files_with_matches" must NOT suppress broadScanTip
const literalLines = Array.from(
{ length: 45 },
(_, i) => `export const LIT_${i} = "files_with_matches";`,
).join("\n") + "\n";
await fs.writeFile(path.join(tipDir, "literal.ts"), literalLines, "utf8");
const literalRes = await runBatchSearch({
cwd: tipDir,
queries: [{ type: "text", pattern: "LIT_", path: path.join(tipDir, "literal.ts") }],
});
assert.match(literalRes.text, /\.\.\. \[tip: for broad scans, use outputMode: "files_with_matches" or "count"\]/);
} finally {
await fs.rm(tipDir, { recursive: true, force: true });
}
});
});