Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 70 additions & 0 deletions packages/core/src/tools/glob.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -644,6 +644,76 @@ describe('GlobTool', () => {
expect(result.llmContent).toContain('visible.txt');
expect(result.llmContent).not.toContain('hidden.secret');
});

it('does not over-ignore nested dirs for a root-anchored gitignore pattern', async () => {
// Regression: `/dist` is anchored to the repo root and must NOT exclude

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] Tests don't verify that the ignore option is actually passed to glob.

All 3 new tests assert only on result.llmContent (post-filter output). The post-filter (filterFilesWithReport) would produce identical results without the ignore option — removing the ignore: { ignored, childrenIgnored } block from the glob call would not cause any test to fail.

The core change of this PR has no test coverage.

Suggested fix — add at least one assertion verifying the glob spy received the ignore callbacks:

const lastCall = vi.mocked(glob.glob).mock.calls.at(-1);
const globOptions = lastCall?.[1];
expect(globOptions?.ignore).toBeDefined();
expect(globOptions?.ignore?.childrenIgnored).toBeTypeOf('function');

— qwen3.7-max via Qwen Code /review

// a nested `src/dist`. Traversal pruning delegates to the real gitignore
// logic, so anchoring is preserved (a lossy `/dist` -> `**/dist/**`
// conversion would wrongly prune src/dist while walking).
await fs.writeFile(path.join(tempRootDir, '.gitignore'), '/dist\n');
await fs.mkdir(path.join(tempRootDir, 'dist'));
await fs.writeFile(path.join(tempRootDir, 'dist', 'root.keep'), 'x');
await fs.mkdir(path.join(tempRootDir, 'src', 'dist'), {
recursive: true,
});
await fs.writeFile(
path.join(tempRootDir, 'src', 'dist', 'nested.keep'),
'x',
);

const invocation = new GlobTool(mockConfig).build({
pattern: '**/*.keep',
});
const result = await invocation.execute(abortSignal);

expect(result.llmContent).toContain('nested.keep');
expect(result.llmContent).not.toContain('root.keep');
});

it('prunes a gitignored directory (e.g. node_modules) during traversal', async () => {
await fs.writeFile(
path.join(tempRootDir, '.gitignore'),
'node_modules/\n',
);
await fs.mkdir(path.join(tempRootDir, 'node_modules', 'pkg'), {
recursive: true,
});
await fs.writeFile(
path.join(tempRootDir, 'node_modules', 'pkg', 'dep.keep'),
'x',
);
await fs.mkdir(path.join(tempRootDir, 'app'));
await fs.writeFile(path.join(tempRootDir, 'app', 'main.keep'), 'x');

const invocation = new GlobTool(mockConfig).build({
pattern: '**/*.keep',
});
const result = await invocation.execute(abortSignal);

expect(result.llmContent).toContain('main.keep');
expect(result.llmContent).not.toContain('dep.keep');
});

it('honors gitignore negation re-inclusion during traversal', async () => {
// `!build/keep.keep` re-includes a file under an otherwise-ignored path.
// Dropping negations (as a pattern conversion must) would wrongly prune
// it; delegating to the real ignore logic preserves re-inclusion.
await fs.writeFile(
path.join(tempRootDir, '.gitignore'),
'build/**\n!build/keep.keep\n',
);
await fs.mkdir(path.join(tempRootDir, 'build'));
await fs.writeFile(path.join(tempRootDir, 'build', 'keep.keep'), 'x');
await fs.writeFile(path.join(tempRootDir, 'build', 'skip.keep'), 'x');

const invocation = new GlobTool(mockConfig).build({
pattern: '**/*.keep',
});
const result = await invocation.execute(abortSignal);

expect(result.llmContent).toContain('keep.keep');
expect(result.llmContent).not.toContain('skip.keep');
});
});

describe('file count truncation', () => {
Expand Down
32 changes: 30 additions & 2 deletions packages/core/src/tools/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,31 @@ class GlobToolInvocation extends BaseToolInvocation<
effectivePattern = escape(effectivePattern);
}

const projectRoot = this.config.getTargetDir();
const fileFilteringOptions = this.getFileFilteringOptions();

// Prune ignored directories DURING traversal (glob's `childrenIgnored`)
// rather than only post-filtering the results. Delegating to
// FileDiscoveryService reuses the real .gitignore/.qwenignore semantics
// (anchoring, negation/re-inclusion, nested ignore files) — a hand-rolled
// gitignore→glob pattern conversion cannot reproduce these correctly.
const isTraversalIgnored = (entry: { fullpath(): string }): boolean => {
const relativePath = path.relative(projectRoot, entry.fullpath());
// Never prune paths outside the project root (e.g. an external search

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] Redundant path.relative → path.resolve → path.relative round-trip.

isTraversalIgnored computes path.relative(projectRoot, entry.fullpath()) here, then passes the result to shouldIgnoreFile → GitIgnoreParser.isIgnored, which does path.resolve(projectRoot, filePath) and then path.relative(projectRoot, resolved) again internally. For a large project, this means 2 extra path operations per traversed entry.

Consider a future optimization to pass the already-computed relative path through, or add a shouldIgnoreFileByRelativePath method that skips the round-trip.

— qwen3.7-max via Qwen Code /review

// dir); ignore rules are only defined relative to the root.
if (
!relativePath ||
relativePath.startsWith('..') ||
path.isAbsolute(relativePath)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] relativePath.startsWith('..') is overly broad — a directory named ..foo is misclassified as outside the project root.

path.relative('/project', '/project/..foo') returns "..foo", which passes startsWith('..') but is a valid path inside the project root.

The existing isPathWithinRoot utility (workspaceContext.ts:324) handles this correctly:

Suggested change
path.isAbsolute(relativePath)
relativePath === '..' ||
relativePath.startsWith(`..${path.sep}`) ||

— qwen3.7-max via Qwen Code /review

) {
return false;
}
return this.fileService.shouldIgnoreFile(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Performance] shouldIgnoreFile ultimately calls GitIgnoreParser.isIgnored(), which creates a fresh ignore() instance and re-adds all patterns on every invocation. With childrenIgnored called for every directory during traversal and ignored called for every file, this is O(entries * patterns) with a non-trivial constant (instance creation + pattern parsing per entry).

For projects with thousands of files and many gitignore patterns, this per-entry overhead could partially offset the traversal-pruning benefit. Consider pre-building a single ignore() instance (with all patterns loaded once) and reusing it in the callback, or exposing a cached variant of shouldIgnoreFile that skips the per-call ignore() construction. The GitIgnoreParser already caches .gitignore file contents in this.cache -- the next step would be caching the assembled ignore() instance too.

Not a blocker -- the net effect is still positive since pruning large ignored trees (e.g. node_modules) avoids walking their entire contents.

relativePath,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Critical] Directory-only gitignore patterns (node_modules/, dist/, build/) are never pruned during traversal.

The ignore npm library requires a trailing / on the path to match directory-only patterns. Since path.relative() returns paths without trailing slashes, ig.ignores('node_modules') returns false for pattern node_modules/. The childrenIgnored callback never prunes the top-level ignored directory — glob still descends into it and enumerates all children.

Verified empirically: ig.ignores('node_modules') → false, ig.ignores('node_modules/') → true for pattern node_modules/.

The post-filter catches descendant files (multi-segment paths like node_modules/pkg/file.js do match), so functional correctness is preserved — but the performance optimization (the stated purpose of this PR) is defeated for the most common gitignore pattern forms.

Suggested fix: append / when the entry is a directory. The glob Path type exposes isDirectory():

Suggested change
relativePath,
const isTraversalIgnored = (entry: { fullpath(): string; isDirectory(): boolean }): boolean => {
const relativePath = path.relative(projectRoot, entry.fullpath());
// Never prune paths outside the project root (e.g. an external search
// dir); ignore rules are only defined relative to the root.
if (
!relativePath ||
relativePath === '..' ||
relativePath.startsWith(`..${path.sep}`) ||
path.isAbsolute(relativePath)
) {
return false;
}
const ignorePath = entry.isDirectory() ? relativePath + '/' : relativePath;
return this.fileService.shouldIgnoreFile(
ignorePath,
fileFilteringOptions,
);
};

Note: also verify that shouldIgnoreFile → GitIgnoreParser.isIgnored preserves the trailing / before passing to ig.ignores(). Currently path.resolve() inside isIgnored strips it, so the fix may need to go deeper into the ignore parser.

— qwen3.7-max via Qwen Code /review

fileFilteringOptions,
);
};

const entries = (await glob(effectivePattern, {
cwd: searchDir,
withFileTypes: true,
Expand All @@ -151,20 +176,23 @@ class GlobToolInvocation extends BaseToolInvocation<
dot: true,
follow: false,
signal,
ignore: {
ignored: isTraversalIgnored,
childrenIgnored: isTraversalIgnored,
},
})) as GlobPath[];

// Filter using paths relative to the project root (the base that
// FileDiscoveryService uses for .gitignore / .qwenignore evaluation).
// Using searchDir-relative paths would cause ignore rules to be
// evaluated against incorrect paths when searchDir != projectRoot.
const projectRoot = this.config.getTargetDir();
const relativePaths = entries.map((p) =>
path.relative(projectRoot, p.fullpath()),
);

const { filteredPaths } = this.fileService.filterFilesWithReport(
relativePaths,
this.getFileFilteringOptions(),
fileFilteringOptions,
);

const normalizePathForComparison = (p: string) =>
Expand Down
Loading