Skip to content

fix(realtime): exclude linked directories by their place in the tree - #481

Open
fstrasz wants to merge 16 commits into
chunkhound:mainfrom
fstrasz:fix/realtime-exclude-linked-dirs
Open

fstrasz wants to merge 16 commits into
chunkhound:mainfrom
fstrasz:fix/realtime-exclude-linked-dirs

Conversation

@fstrasz

@fstrasz fstrasz commented Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Realtime indexing no longer indexes files behind a link inside an excluded directory, such as a local package that npm install links into node_modules/.

What happened. For a file: dependency, npm links the package into node_modules/ as a junction on Windows (a symlink elsewhere). The ignore engine resolved every path before matching it, so a file behind that link was matched at its target, outside the root. No root-relative rule applies there, so node_modules/** did not exclude it. Realtime then picked such files up in two ways:

  1. A directory created above the link was walked with rglob, which descends the junction. Its files passed the filter and were stored under node_modules/….
  2. A directory event for the link itself was resolved to its target and walked from there. Each file then failed at the store step with "not in the subpath", once per file.

The startup scan already prunes excluded directories by their in-tree path, so it was never affected. Only realtime was.

Reproduced with a real chunkhound mcp --no-daemon on Windows: create node_modules/@scope, then junction node_modules/@scope/pkg to a directory outside the root, while the server runs.

  • Before: a regex search finds the outside files, as node_modules\@scope\pkg\build.mjs and index.ts.
  • With this change: nothing from behind the link is stored.
  • Control: the same files copied (not linked) into node_modules/ were excluded before and after.

Change.

  • Ignore rules match a path by where it sits under the root, as Git does. This applies to IgnoreEngine, the repo-aware evaluator and the libgit2 evaluator. The resolved path is used only when the path is not lexically under the root, which keeps the existing handling of already-resolved paths such as /private/var on macOS.
  • RealtimePathFilter respells a path given under the root as requested onto the resolved root before matching. Watchman reports paths that way, so a root reached through a link (/var is /private/var on macOS) is handled too. Only the root part changes, so a link further down is still judged where it sits.
  • A created directory that an ignore rule excludes is dropped before it is resolved or walked (RealtimePathFilter.excludes_directory), by the watchdog handler and by the Watchman adapter. Deleted directories are still always admitted, so cleanup of previously indexed files is unchanged.
  • A directory counts as excluded only when nothing beneath it can be included, which is what pruning it assumes. Under foo/** then !foo/bar.py, foo/ is no longer reported excluded, so a new foo/ is expanded and foo/bar.py is found, as git includes it. A directory re-include inside a contents pattern (foo/** then !foo/bar/) re-includes only the directory, as in git. These two commits come from review of perf(realtime): decide each excluded directory once, not once per file #490/fix(watchman): no watch root for a junction under an excluded directory #491, and fix(realtime): admit file events before resolving and skip linked directories in walks #485/perf(realtime): decide each excluded directory once, not once per file #490/fix(watchman): no watch root for a junction under an excluded directory #491 already carry them.
  • A repository linked into the workspace (linked/ to a checkout outside it) keeps its own ignore rules. Repositories are chosen by where they sit in the workspace, and a path is then mapped onto the chosen repository's resolved root. Both repo-aware evaluators do this, and a path that is already resolved is looked up among the resolved roots as before.
  • A linked file is judged by its target too. should_index judges a path where it sits and, when resolving it changes it, judges the resolved target as well, so src/a.py -> vendor/x.py with vendor/ ignored is not indexed. The default startup scan never indexes a symlinked file. A link under an excluded directory is still rejected where it sits, before its target is looked at.
  • When the ignore policy cannot be evaluated, a directory is not excluded, and each file under it is still checked and rejected as before. should_index and excludes_directory share one guard, so an evaluation error on a directory marks the filter degraded and warns once, as one on a file already did.
  • The engine reads pathspec 1.x's compiled patterns as well as 0.12's (d450191). pathspec 1.x spells the tail of a compiled pattern differently and applies its regexes with re.search, so before this, under an installed 1.x, any plain or glob line (Thumbs.db, *.log) degraded its whole spec: no directory was pruned, and re-includes followed pathspec alone. New test: test_a_plain_file_pattern_keeps_ignored_directories_pruned. CI runs only the locked pathspec 0.12.1. On Windows, tests/ignore (17 passed) and the 11-case git parity test pass under both 0.12.1 and 1.1.1, and under 1.1.1 both tests in tests/ignore/test_pathspec_contract.py fail without this change. A CI leg that runs tests/ignore against the latest pathspec 1.x would catch the next change of this kind; that is a suggestion for the maintainers, not part of this PR.

Linked directories that are not excluded behave as before. Junction-backed scopes keep their logical paths.

Tests. Each fails without its part of the change.

  • test_linked_package_under_node_modules_is_never_indexed makes a real junction (a symlink off Windows) under node_modules/ to a package outside the root. It asserts that neither the link's directory event nor a walk of the directory above it queues anything. Without the event-handler check, the link's event is queued as the resolved outside path. Without the in-tree matching, the walk queues node_modules/@scope/pkg/build.py.
  • test_watchman_new_directory_inside_excluded_path_is_not_queued: a Watchman batch with new directories under node_modules/ and src/ queues only the src/ one.
  • test_linked_package_is_excluded_when_the_root_is_spelled_through_a_link: with the root reached through a link, the linked package is still excluded and its file is not indexed.
  • test_ignore_engine_error_on_a_new_directory_marks_the_filter_degraded: an engine error while judging a directory marks the filter degraded.
  • test_scan_walk_and_admission_agree_with_git_on_reincluded_files: for 11 .gitignore layouts with negations, the full scan, the polling walk, file events and new-directory events all agree with git check-ignore. tests/ignore/test_pathspec_contract.py compares the engine with git check-ignore on a tiny repository that pathspec alone decides differently, so a pathspec change that degrades the rules fails a test.
  • test_linked_nested_repository_keeps_its_own_ignore_rules: a repository linked into the workspace through a junction (a symlink off Windows) still excludes what its .gitignore ignores.
  • test_file_link_to_an_ignored_file_is_not_indexed: a real file symlink src/a.py -> vendor/x.py, with vendor/ gitignored, is not indexed.

Checks.

  • All 22 test files that use the ignore engine, RealtimePathFilter or SimpleEventHandler give 185 passed, 6 failed. The same 6 tests (Watchman event translation, realtime functional) fail on main on this Windows machine.
  • After the third review round, on Windows: tests/test_realtime_functional.py and tests/realtime give 146 passed, 35 skipped; tests/ignore gives 16 passed.
  • After the second review round, on Windows: tests/test_realtime_functional.py and tests/realtime give 145 passed, 35 skipped; tests/ignore gives 16 passed.
  • After the first review round, on Windows: tests/test_realtime_functional.py and tests/realtime gave 131 passed, 35 skipped, 2 failed. One failure (test_realtime_path_filter_logs_include_failure_once) came from this round and is fixed in the pushed commit. Both filter test files then give 22 passed. The other, test_request_resync_is_debounced, timed out waiting for a resync callback and passed when rerun alone.
  • Smoke tests: 14 passed.
  • ruff and mypy report no new findings on the changed files.

🤖 Generated with Claude Code, reviewed by FStrasz

`npm install` links a local `file:` dependency into node_modules/ as a
junction (a symlink elsewhere). The ignore engine resolved every path
before matching, so a file behind that link was matched at its target,
outside the root, where no root-relative rule such as `node_modules/**`
applies. Realtime then indexed it:

- A directory created above the link was walked with rglob, which
  descends the junction, and its files passed the filter and were stored
  under node_modules/.
- A directory event for the link itself was resolved to the target and
  walked from there; every file failed at the store step ("not in the
  subpath").

The startup scan already prunes excluded directories by their in-tree
path, so only realtime was affected.

Ignore rules now match a path by its location under the root, falling
back to the resolved path only when it is not lexically under the root.
A created directory that an ignore rule excludes is dropped before it is
resolved or walked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Brings in the 24 commits merged to main since this branch was last updated, including chunkhound#534's rust-checks fix. No conflicts.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The watchdog handler already drops a dir_created event when the new
directory is excluded, so an excluded tree is never walked. The Watchman
adapter admitted every dir_created event, so a directory created under
node_modules/ (or any other excluded path) still became dir_index work
on the Watchman backend. It now applies the same excludes_directory
check. dir_deleted is still always admitted, so cleanup is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: This is a sound, minimal fix for realtime indexing of linked directories under excluded paths. It needs one change before merge: excludes_directory must handle engine failures the way should_index does.

Strengths

  • The root cause is fixed in one place. _in_tree_path is shared by IgnoreEngine and both repo-aware evaluators, and it falls back to resolve(), so existing handling of already-resolved paths is unchanged.
  • The dir_created fix covers both backends. The Watchman change keeps dir_deleted always admitted, so cleanup of previously indexed files still works.
  • _ensure_engine is extracted from should_index instead of duplicating engine construction.
  • The tests use real junctions and symlinks, cover each half of the fix, and cover the Watchman path.

Issues

Critical: none.

Major

  • chunkhound/services/realtime_path_filter.py (excludes_directory): except Exception: return False swallows errors silently. should_index handles the same failure by setting _ignore_engine_degraded and calling _warn_ignore_engine_degraded_once. Here a ged nor marked degraded. The fallback issafe, because each file is still rechecked by should_index, so nothing wrong gets indexed. The problem is that the failure is invisible and the code breaks the same degrade-and-warn path.
    nor
  • excludes_directory repeats the guards not _ensure_engine() or _ignore_engine_degraded and _engine is None. The second guard exists only for mypy. Foldinglso cover the Major item.
  • ignore_engine.py (_in_tree_path): the lexical check uses the resolved self.root. If the watch root is given through a symlinked spelling (for example /var/.../private/var/...), the path is not lexicallyunder the root. It then falls back to resolve(), and the original bug returns. The PR keeps the macOS handling deliberately, but it should say so, and id
  • os.path.abspath collapses .. lexically, which differs from resolve() when .. follows a link. That matches Git, but the docstring should say so.
  • Process: the Watchman commit cdfbf58 is not in the PR description, which only covers the watchdog handler.
  • The _index_directory(scope) assertion reliescending the junction with rglob is stillwasted work, so add a comment saying so.
  • _link_directory uses the private _winapi m

Reusability

  • Extract a single "ignore policy evaluable?" guard shared by should_index and excludes_directory.
  • The repeated _in_tree_path(path, X).relati the ignore_engine.py evaluators could become a small _relative_in_tree(path, root) helper.

Decision: REQUEST CHANGES. Fix the excludes_directory error handling (Major) and address or acknowledge the Minor items. I expect to approve once that's done.

…nk-spelled root in the tree

Review follow-up.

excludes_directory swallowed an ignore-engine error and returned False,
so the failure was invisible and the filter never marked itself
degraded. should_index and excludes_directory now share one guard,
_ignore_rule_matches: the first evaluation error marks the engine
degraded and warns once, whichever caller hit it, so is_degraded reports
it and cleanup keeps rows it can no longer prove are excluded. A filter
with no engine and no recorded failure still means no rule applies.

Watchman builds event paths from the root as it was requested, while
the ignore engine works on the resolved root. When the requested root
is spelled through a link (/var is /private/var on macOS), a path was
not lexically under the engine's root, so it was resolved and a link
under node_modules/ was judged at its target again. RealtimePathFilter
now respells such a path onto the resolved root before matching. Only
the root part changes, so links below the root are still judged where
they sit.

Also documents both cases in _in_tree_path (a link-spelled root, and
`..` collapsed lexically as Git does), and comments the test's private
_winapi junction helper and the rglob walk the walk test relies on.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Changes are in c3a7aeb:

  1. Major, excludes_directory swallowed errors: fixed. should_index and excludes_directory now share one guard, _ignore_rule_matches, which returns None when the ignore policy cannot be evaluated. The first evaluation error marks the engine degraded and warns once, whichever caller hit it. So is_degraded now reports a failure on a directory the same way it reports one on a file. New test: test_ignore_engine_error_on_a_new_directory_marks_the_filter_degraded. Without the change it fails: is_degraded stays False.
  2. Repeated guards: folded into that helper, so they appear once. One correction: the _engine is None check is not only for mypy. A filter with no engine and no recorded failure means no ignore rule applies, and test_realtime_path_filter_logs_include_failure_once relies on that, so the helper keeps that meaning.
  3. Root spelled through a link: I fixed this for the realtime filter instead of only documenting it. Watchman builds event paths from the root as requested (scope.requested_path.joinpath(...)), so a root spelled through a link did bring the original bug back on that backend. RealtimePathFilter now respells such a path under the resolved root before matching (_engine_path). Only the root part changes, so a link further down is still judged where it sits. Watchdog and polling already watch the resolved root (startup.py), so they were not affected. The _in_tree_path docstring now says this. New test: test_linked_package_is_excluded_when_the_root_is_spelled_through_a_link. It reaches the root through a junction (a symlink off Windows). Without the change it fails: the linked package is not excluded, and its file passes should_index. If you would rather review this part separately, I can move it into its own PR.
  4. .. collapsed lexically: the _in_tree_path docstring now says so.
  5. PR description: updated to cover the Watchman commit (cdfbf58) and this round.
  6. rglob descending the junction: I added a comment at the _index_directory(scope) assertion. fix(realtime): admit file events before resolving and skip linked directories in walks #485 prunes the walk itself.
  7. _winapi: I added a comment. The module is private, but it is the standard library's only way to make a junction, and a junction needs no admin rights or Developer Mode, unlike a symlink.
  8. _relative_in_tree helper: I left these inline. The call sites fall back differently: the in-tree path in IgnoreEngine, and path.name in the libgit2 evaluator. A shared helper would need a fallback parameter and would not shorten them much.

Verification on Windows: both new tests pass, and each one fails when its part of the change is removed. The realtime tests found one regression of my own (the case in item 2), which is fixed in the same commit, and one timing test that failed once and passed when rerun alone. The PR description has the details.

Your comment reached me cut off in a few places, for example after "should say so, and" in the macOS item, and in the _winapi item. If I have missed part of a point, tell me and I will follow up.

🤖 Generated with Claude Code, reviewed by FStrasz

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: The latest commit fixes the earlier review requests, but two verified ignore-policy regressions still need changes before merge.

Review groups:

  • Shared ignore engines — reviewed lexical paths, linked repositories, and repository boundaries.
  • Realtime admission and tests — reviewed watchdog/Watchman directory events, filter failures, cleanup, and regression coverage.

These groups were reviewed independently in parallel, then checked together.

Strengths:

  • Directory and file checks now share error handling: failures mark the filter degraded and warn once.
  • Both backends filter excluded directory creation while keeping deletion events available for cleanup.
  • The follow-up handles roots reached through links and adds real symlink/junction tests.

Issues:

  1. Major — Directory filtering drops explicitly re-included files.
    chunkhound/services/realtime/events.py:268, chunkhound/services/realtime/adapters/watchman.py:364, and chunkhound/services/realtime_path_filter.py:121

    The new admission checks treat a directory ignore match as proof that nothing beneath it should be indexed. That is not always true:

      foo/**                                                                                                                                                                                                                                                                       
      !foo/bar.py                                                                                                                                                                                                                                                                  

    On the PR head, excludes_directory(foo) returns True, while should_index(foo/bar.py) returns True and Git considers the file included. A watchdog directory-created event is therefore dropped instead of triggering directory expansion. This can miss included files when a
    populated directory enters the watched tree.

    The matcher’s directory answer was already inconsistent, but this PR newly uses it to reject directory events. PR fix(realtime): admit file events before resolving and skip linked directories in walks #485 discusses a fix; fix(realtime): exclude linked directories by their place in the tree #481 should include that fix or avoid pruning directories that may contain re-included files.

  2. Major — Linked nested repositories lose their own ignore rules.
    chunkhound/utils/ignore_engine.py:518–522; the same mismatch exists at :765–769

    _nearest_repo() now preserves the logical workspace path, but repository roots are still resolved in the constructors. For workspace/linked -> external-repo, the logical file path cannot match the resolved repository root, so evaluation falls back to the workspace
    policy.

    Using the public build_repo_aware_ignore_engine_from_roots() API with that linked repository, I verified:

    • Base: linked/private.secret.py is excluded by the repository’s .gitignore.
    • PR head: the same file is not excluded.

    Preserve logical repository locations for boundary selection, then map paths into the selected physical repository engine.

Reusability:

  • Keep the shared _ignore_rule_matches() helper; it addresses the earlier duplication and error-handling concerns.
  • Separate logical repository locations from resolved identities rather than mixing both path forms during boundary selection.
  • Give directory pruning an explicit contract: “no descendant can be included,” not merely “this directory matches an ignore pattern.”

Validation: Focused tests reported 35 passed, 6 skipped; the realtime suite reported 89 passed, 29 skipped. Both findings were reproduced separately. Whole-package mypy reported errors and was not a clean validation signal. GitHub metadata was read through public pages
because gh authentication failed. No repository files were changed or review submitted.

Decision: REQUEST CHANGES

fstrasz and others added 3 commits November 19, 2026 04:42
…cluded

Review of the stacked PRs (chunkhound#490, chunkhound#491) found that a file a .gitignore
negation re-includes was dropped by realtime:

  .gitignore      foo/**  then  !foo/bar.py   -> foo/bar.py
  src/.gitignore  **      then  !keep.py      -> src/keep.py

git does not ignore either file, the full scan indexes both, and event
admission accepted them, but excludes_directory() reported foo/ and src/
excluded, so the polling walk and new-directory expansion pruned them and
never saw the file. IgnoreEngine matched a directory in its "dir/" form,
and pathspec matches "foo/" against a contents pattern such as foo/** (or
the root-relative src/** of a nested "**") through an empty tail. Main had
the same wrong answer; this PR made it load-bearing by pruning on it.

A directory match now means its whole subtree is excluded, which is how
every caller uses it (the realtime walk and directory events, the Python
full-scan walker and its os.walk fallback, repo-root detection). Per spec,
in precedence order, a directory is excluded when:

- git excludes the directory itself: the last pattern matching it is not
  a negation, testing "dir/" against patterns written with a trailing "/"
  and the bare "dir" against the rest. foo/ and foo match foo; foo/**
  matches only what is inside it. A directory a negation re-includes is
  still excluded when an ancestor is, as in git.
- or a pattern covers its contents ("dir/" matches, e.g. foo/** or the
  default **/node_modules/**) and no negation in that spec could match
  beneath it. A negation could when it is unanchored (!keep.py, !*.md),
  starts with **/, or its literal prefix lies above or below the
  directory. Config excludes have no negations, so node_modules is still
  pruned without being walked.

So foo/** then !foo/bar.py leaves foo/ walkable, and each file is decided
on its own. The whitelist idiom (/* then !/src/) keeps src/ walkable.

To tell foo/ from foo/** the .gitignore transform now emits dir-only
patterns with their trailing "/" instead of "/**". pathspec matches the
same files for both, except that **/ no longer matches top-level files,
which git does not ignore either.

Files follow git as well: a file a negation re-includes stays excluded
when a parent directory is excluded. "foo/" then "!foo/bar.py" therefore
keeps foo/bar.py excluded in the walk, in event admission and in the
Python full scan, as git does; before, the engine admitted it.

The libgit2 backend's config-exclude layer uses the same rule; libgit2
already applies git semantics to .gitignore directories.

Tests compare the full scan, the polling walk and event admission with
git check-ignore for the two review cases, the dir-only case and the
whitelist idiom, and check that the walk never enters node_modules.

Ported to chunkhound#481 from b359531, found in review of chunkhound#490/chunkhound#491 and carried by
chunkhound#485/chunkhound#490/chunkhound#491. Conflict resolution: IgnoreEngine.matches and
RepoAwareLibgit2Evaluator._cfg_excluded take b359531's rule-based decision;
the lines it replaces here are main's originals rather than the stack's
interim "dir/ form only" lines (a902b55, not in chunkhound#481). The tests are adapted
to chunkhound#481's code: the walk test that needs pipeline._walk_files (chunkhound#485) is left
out, and the git-agreement test also sends a created-directory event for each
directory holding a file git includes, and requires it to be expanded rather
than dropped, which is the case this port fixes in chunkhound#481.

(cherry picked from commit b359531)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Review of b359531 found that a negation re-including a directory inside
a contents pattern opened files git ignores:

  foo/**  then  !foo/bar/             -> git ignores foo/bar/x.py
  /a/**   then  !/a/b/                -> git ignores a/b/x.py
  /s/**   with  s/.gitignore !/keep/  -> git ignores s/keep/a.py

foo/** still matches the file itself; !foo/bar/ only re-includes the
directory. pathspec has no notion of that: it matches "!foo/bar/" (as
"!foo/bar/**") against every file below, so the file was re-included.
Before b359531 the walk pruned foo/ and hid this; once foo/ became
walkable, polling and admission gained foo/bar/x.py while the full scan
(git ls-files) left it out.

Files and directories are now decided as git decides them whenever a
negation in the spec matches the path:

- each pattern is matched against the path itself, without pathspec's
  "and everything beneath" tail (the ps_d group in pathspec 0.12), and a
  directory pattern only against directories; the last match wins;
- a path is excluded regardless when a directory above it is excluded.

A path no negation matches keeps pathspec's answer, which is then git's.
The same exact matching decides when a directory is excluded, and the
"contents covered" pruning rule now counts only file patterns, so a
directory pattern such as foo/**/ no longer prunes foo/ itself.

This also brings these cases in line with git (checked against
git ls-files -o --exclude-standard): "*.md then !keep/", "* !*/ !*.py",
"* !**/ !*.py", "* !/**/ !*.py", and "a/b/ then !a/".

The .gitignore transform again emits a directory pattern "foo/" as
"foo/**", byte for byte as before b359531, and carries the "was a
directory pattern" flag beside the compiled spec instead of in the
string. b359531's trailing "/" changed what **/ and /**/ match for the
full scan; that change is reverted (those two still differ from git as
they always have).

Reading pathspec's pattern objects (include, regex, source, ps_d tail)
fails loudly in a guard test, and at runtime degrades to pathspec's own
answers with no pruning and logs one warning, rather than silently
restoring the old behaviour.

Git's answer for each directory is memoized per compiled spec. The rules
never change for the spec's lifetime, so the memo needs no invalidation;
it is bounded and cleared when full. With 1,806 patterns including
"* !*/ !*.py", 2,000 file decisions take about 1.8 s against 1.7 s on
a902b55, and 2,000 directory checks 0.9 s against 1.6 s.

The git-oracle test gains the three review cases, the directory
re-include of a file pattern and the three whitelist variants.

Ported to chunkhound#481 from 6e32b20, found in review of b359531 on chunkhound#490/chunkhound#491 and
carried by chunkhound#485/chunkhound#490/chunkhound#491. The engine change applies unchanged. In the
git-agreement test, the case table and the switch to "files" (.py and .md)
come from 6e32b20; the created-directory check added when b359531 was
ported to chunkhound#481 is kept.

(cherry picked from commit 6e32b20)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…e workspace

Review of chunkhound#481 found that a repository linked into the workspace lost its
own ignore rules. With workspace/linked pointing at a checkout outside the
workspace, files under linked/ fell back to the workspace policy, so a
pattern from the linked repository's .gitignore no longer applied.

The ignore engine now matches a path where it sits in the workspace, but
both repo-aware evaluators still resolved their repository roots. The
in-tree path workspace/linked/x was never under the resolved root of the
linked repository, so no repository was found for it. Before chunkhound#481 the path
was resolved too, which found the repository but judged links below the
root at their targets.

Each repository is now kept as (where it sits under the workspace, its
resolved root). The nearest repository is chosen by in-tree location, so
a linked repository nested in a workspace that is itself a repository
still wins over the workspace. The path is then mapped onto the chosen
repository's resolved root, where that repository's engine (or its libgit2
handle) matches it. A path under no in-tree location, such as one that was
already resolved, is looked up among the resolved roots as before. Both
evaluators share one helper for this.

Reproduced on Windows with a junction: build_repo_aware_ignore_engine_from_roots
with the repository at workspace/linked, and build_repo_aware_ignore_engine,
whose os.walk detection finds the repository through the junction at
workspace/linked. In both, linked/private.secret.py was not excluded
before this change and is excluded after it. A file the repository does
not ignore stays included.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. The changes are in three commits:

  1. Major 1, re-included files dropped: 535466f and 5122b33 port b359531 and 6e32b20 into fix(realtime): exclude linked directories by their place in the tree #481. Both come from review of perf(realtime): decide each excluded directory once, not once per file #490/fix(watchman): no watch root for a junction under an excluded directory #491, and fix(realtime): admit file events before resolving and skip linked directories in walks #485/perf(realtime): decide each excluded directory once, not once per file #490/fix(watchman): no watch root for a junction under an excluded directory #491 already carry them. A directory now counts as excluded only when nothing beneath it can be included, which is the explicit pruning contract you suggested. Under foo/** then !foo/bar.py, excludes_directory(foo) is now False, so a new foo/ is expanded and foo/bar.py is found. A directory re-include inside a contents pattern (foo/** then !foo/bar/) re-includes only the directory, as git does. In fix(realtime): exclude linked directories by their place in the tree #481, the ported git-agreement test also sends a created-directory event for each directory that holds a file git includes, and requires that directory to be expanded. Against the previous head it fails on your case: foo is dropped. I left out the ported walk test, because it needs _walk_files, which arrives in fix(realtime): admit file events before resolving and skip linked directories in walks #485.
  2. Major 2, linked nested repositories: 5b188ad. Each repository is now kept as a pair: where it sits in the workspace, and its resolved root. The nearest repository is chosen by its in-tree location. The path is then mapped onto that repository's resolved root, where its own engine (or libgit2 handle) matches it. A path that is already resolved is looked up among the resolved roots, as before. Both evaluators share this code. New test: test_linked_nested_repository_keeps_its_own_ignore_rules, your case through build_repo_aware_ignore_engine_from_roots, with a junction (a symlink off Windows). It fails against the previous selection.
    • Detection: I observed this path on Windows. detect_repo_roots walks into the junction and reports the repository at workspace\linked, and build_repo_aware_ignore_engine did not exclude linked/private.secret.py either. It does after this change, and the same test covers the evaluation.
    • Workspace that is itself a repository: on Windows the previous head still excluded the file in this case. The workspace repository's .gitignore collection walks through the junction and picks up linked/.gitignore. Off Windows, os.walk does not follow the symlink, so that path does not apply there. With this change the linked repository is chosen by its own location in both cases.

Verification on Windows: tests/test_realtime_functional.py and tests/realtime give 145 passed, 35 skipped, and tests/ignore gives 16 passed.

🤖 Generated with Claude Code, reviewed by FStrasz

@HananKavitzAmat

Copy link
Copy Markdown
Collaborator

Summary: The core ignore-rule fix looks correct, but one symlink behavior change needs an explicit decision before merge. Verdict: REQUEST CHANGES.

Review groups: I split the PR into two groups, reviewed in parallel:

  1. Ignore engine (chunkhound/utils/ignore_engine.py): directory pruning, re-include rules, and choosing the right nested repo. These share one code path, so they're one group.
  2. Realtime wiring and tests (realtime_path_filter.py, events.py, watchman.py, and the new tests): these depend on group 1, so I reviewed them after it.

Strengths:

  • The pruning and re-include logic matched git check-ignore on every case the reviewer tried, including foo/** followed by !foo/bar/.
  • The code fails safe. If the pathspec library changes, it drops to a degraded mode and warns, rather than silently letting files through.
  • The commit messages explain the bug and the fix clearly.

Issues:

  • Major (ignore_engine.py around line 45, _in_tree_path; realtime_path_filter.py should_index): A file that is a symlink is now judged by where it sits in the tree, not by its target. Example: repo/src/a.py links to repo/vendor/x.py, and vendor/ is gitignored. Before this
    PR the file was rejected; now it is indexed. The reviewer reported reproducing this, but I did not re-run it. No test covers it. Either confirm this is intended and add a test, or change the code.
  • Major (tests/ignore/test_pathspec_contract.py:20-34): The test checks internal pathspec fields (dir_only, include, exact). A harmless refactor would break it. It should instead check results against git on a small test repo.
  • Minor (realtime_path_filter.py, excludes_directory): It returns False when the policy can't be checked, which reads as "not excluded". The name or return value should make that clearer.
  • Minor (ignore_engine.py, around lines 395–400): The one-time warning flag is a global, so it isn't thread-safe. Harmless in practice.
  • Minor: The pathspec version pin has no upper bound, and the code depends on pathspec's internals.
  • Not verified: Windows junction and symlink behavior. The reviewer could not test it here.

Reusability:

  1. build_ignore_engine and RepoAwareIgnoreEvaluator.init repeat the same config-exclude and gitignore setup. One helper would cover both.
  2. RepoAwareLibgit2Evaluator compiles config_exclude twice (_cfg_spec and _cfg_rules). Keep only one.
  3. The "check at in-tree location, then map to the resolved root" logic is split between _in_tree_path and RealtimePathFilter._engine_path. Move it to one shared helper.
  4. events.py and watchman.py each make their own directory check. A single admit_directory_created(path) method on the filter would keep them in sync.

Decision: REQUEST CHANGES. Settle the symlink behavior with a test, and rewrite the pathspec test to check git-equivalent results.

fstrasz and others added 4 commits November 19, 2026 06:44
Review of chunkhound#481 found that a symlinked file was judged only where it sits.
With src/a.py -> vendor/x.py and vendor/ ignored, src/a.py was rejected
before chunkhound#481, because the ignore engine resolved every path, and admitted
after it. The watchdog handler resolves a file event before admission and
still rejected it, but the polling snapshot and the new-directory expansion
pass the unresolved path to should_index, so they would index the ignored
file's content under the link's name.

That is not intended. The default startup scan does not follow links and
never indexes a symlinked file. So should_index now judges a path where it
sits and, when resolving it changes it (the file or a directory between it
and the root is a link), judges the resolved target as well. This is the
rule the stacked PRs apply in the event handler (e888fd2). A link under an
excluded directory is still rejected where it sits, before its target is
looked at, and only a path that passed is resolved, which costs no more than
before chunkhound#481, when every path was resolved.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nternals

Review of chunkhound#481 found that test_pathspec_contract.py asserted pathspec's
internal pattern fields (dir_only, include, exact), so a harmless refactor
could break it. Its purpose is to fail first when a pathspec release changes
the pattern objects ChunkHound reads, which would otherwise degrade the
ignore rules to pathspec's own matching with only a logged warning.

It now builds a tiny repository whose .gitignore pairs a directory pattern
and a contents pattern with negations that git and pathspec alone decide
differently (dir/ then !dir/keep.py; contents/** then !contents/sub/), and
compares the engine's decision for each file with git check-ignore. The
degraded fallback re-includes both files, so the test fails if the rules
cannot be read. It uses two git processes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…valuator

Review of chunkhound#481 noted that RepoAwareLibgit2Evaluator kept both _cfg_spec and
_cfg_rules. The spec is compiled once and the rules are read from it, and
since b359531 nothing reads _cfg_spec after construction: across the
package and the tests its only use was building _cfg_rules on the next
line. It is no longer stored.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The pathspec contract test wrote the paths to git check-ignore in text
mode. On Windows that writes "\r\n", so git read each path with a trailing
"\r" and printed it quoted, and the comparison failed on spelling rather
than on what git decided. The paths now go in and out NUL-separated (-z),
as bytes.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

Thanks. The changes are in 10d03a2, 4f42f38 (plus 7b755eb, which feeds the paths to git NUL-separated so the test also holds on Windows) and ad130d3:

  1. Major, symlinked file judged where it sits: not intended, and fixed. The default startup scan does not follow links and never indexes a symlinked file (src/lib.rs: a symlink entry is neither a directory nor a file, so the walk skips it). Watchdog events in this PR are resolved before admission, so your example was still rejected there. The polling snapshot and new-directory expansion pass the unresolved path to should_index, though, and would have indexed vendor/x.py's content as src/a.py. should_index now judges a path where it sits and, when resolving it changes it, judges the resolved target too. This is the rule the stacked PRs already apply in the event handler (e888fd2). A link under an excluded directory is still rejected where it sits, before its target is looked at. New test: test_file_link_to_an_ignored_file_is_not_indexed, your example with a real file symlink. It fails without the change, and the existing node_modules link tests still pass.
  2. Major, pathspec contract test: rewritten. It builds a tiny repository whose .gitignore git and pathspec alone decide differently (dir/ then !dir/keep.py; contents/** then !contents/sub/), and compares the engine with git check-ignore. If the rules cannot be read from pathspec, the degraded fallback re-includes both files, and the test fails.
  3. excludes_directory returning False when the policy cannot be checked: kept. The docstring says so, and the callers rely on it meaning "walk it and check each file", which should_index then rejects.
  4. Global warn-once flag: agreed it is not thread-safe. The worst case is a second log line, so I left it.
  5. pathspec upper bound: I left that to you as a packaging decision. The degraded fallback and the rewritten test are there for this case.
  6. Windows: junction and symlink behaviour is verified on Windows, where these tests run with real junctions and a real file symlink.
  7. Reusability: (2) is done. The libgit2 evaluator no longer stores _cfg_spec: nothing in the package or tests read it after construction. The spec was compiled only once, though, and the rules were read from it. For (1), (3) and (4), I would rather not widen this PR. (4) overlaps the directory handling that perf(realtime): decide each excluded directory once, not once per file #490 reworks. I'm happy to do them as a follow-up if you want them.

Verification on Windows: both new tests pass. Each one fails when its fix is removed; the pathspec test fails when the degraded fallback is forced. tests/ignore gives 16 passed, and tests/test_realtime_functional.py with tests/realtime gives 146 passed, 35 skipped.

🤖 Generated with Claude Code, reviewed by FStrasz

@fstrasz

fstrasz commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

A correction to item 5 of my reply above: it understates the pathspec case. pathspec 1.x is already released, and this PR reads pathspec's compiled patterns in the form 0.12 produces. CI passes because the lock pins 0.12.1, but a fresh install today resolves 1.x, whose patterns this PR cannot read. The engine then takes the degraded fallback: it warns once, prunes no ignored directory, and decides files by pathspec alone, so the re-include cases this PR fixes go back to pathspec's answer. We hit this on our fork and fixed it there. I'm porting that fix to this PR and will run the tests under both 0.12.1 and 1.1.1. The upper bound is still your call.

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz and others added 4 commits November 19, 2026 08:51
…ories stay pruned

The ignore engine reads pathspec's compiled regexes to decide directories as
git does. It knew only pathspec 0.12's spelling of the tail, the group named
ps_d, that makes a match on a directory also match everything beneath it.
pathspec 1.x spells it "(?:(?P<ps_d>/)|$)" (file or directory) and a bare
"(?P<ps_d>/)" (directory). Under 1.x, any plain or glob line (Thumbs.db,
*.log, /build) therefore degraded its whole spec: no directory was pruned,
and every file was decided by pathspec's own match_file. The lock pins
0.12.1, so CI does not see this, but pathspec>=0.12.1 lets a fresh install
resolve 1.x.

pathspec 1.x also applies its regexes with re.search, and some are
unanchored ("*" compiles to "."). 0.12 anchors every regex, so re.search is
right for both, and the rules now use it at all three sites.

- Both versions' tails map to the end of the path.
- The fallback names the pattern and the installed pathspec version.
- New test: a Thumbs.db + node_modules/ .gitignore keeps ignored directories
  pruned. With the git comparison already in the file, it runs against the
  installed pathspec, whichever version that is.

Ported from fstrasz/chunkhound 0b13ace, without that fork's lock change.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…hunkhound#485 review)

The code that derives git's directory and re-include decisions from
pathspec's compiled patterns (_GLOB_CHARS through _spec_excludes_file)
moves unchanged from ignore_engine.py into gitignore_rules.py; the moved
259 lines are byte-identical. ignore_engine.py imports the four names it
uses. No test imports a moved name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…unkhound#485 review)

ignore_engine reads pathspec's compiled regexes, which are not public API.
pyproject bounds pathspec to the majors the contract test covers
(>=0.12.1,<2); uv.lock changes in metadata only and still resolves 0.12.1.
A new pathspec-1x job installs the newest 1.x over the lock and runs
tests/ignore and the realtime cleanup tests, so a 1.x release that changes
the regex shape fails CI instead of silently disabling pruning.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fstrasz

fstrasz commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

HananKavitzAmat, following up on my correction above: the pathspec 1.x port is in d450191. The engine now reads
both 0.12's and 1.x's compiled patterns, and the new test test_a_plain_file_pattern_keeps_ignored_directories_pruned
checks that a Thumbs.db line beside node_modules/ leaves the directory pruned. On Windows, tests/ignore and
the 11-case git comparison pass under both pathspec 0.12.1 and 1.1.1, and under 1.1.1 both tests in
tests/ignore/test_pathspec_contract.py fail without the change. CI runs only the locked 0.12.1 and is green on
d450191. The upper bound on pathspec is still your call.

With that, I believe every point from your three reviews is addressed or answered. Could you take another look?
Reusability items 1, 3 and 4 from your last review are still open as possible follow-ups; tell me if you want them
in this PR.

🤖 Generated with Claude Code, reviewed by FStrasz

@fstrasz

fstrasz commented Nov 25, 2026

Copy link
Copy Markdown
Contributor Author

Pushed head 0d9253b: two commits on top of d450191, then a merge of current main. They answer Majors 2 and 3 of the
review on #485 (that review read this ignore-engine work through #485, which carries it):

  1. 09e3716 moves the git-exact rule code (negation scopes, exact regexes, the directory memo) from ignore_engine.py
    into its own module, chunkhound/utils/gitignore_rules.py. The moved lines are byte-identical; ignore_engine.py
    imports the four names it uses.
  2. c20d46f bounds pathspec to >=0.12.1,<2 (uv.lock changes only that specifier and still resolves 0.12.1), and
    adds a pathspec-1x CI job. It installs the newest 1.x over the lock and runs tests/ignore and the realtime
    cleanup tests. With the main matrix on 0.12.1, both majors are tested, and a pathspec release that changes the
    compiled-regex shape fails that job instead of quietly turning pruning off.

On Windows, tests/ignore plus the cleanup tests pass under 0.12.1 and 1.1.1 (46 each). With the 1.x tail spellings
removed, the contract test fails under 1.1.1. Full suite at 0d9253b, serially on Windows: 6,143 passed, 509 skipped,
and no failure that d450191 does not also have (the 30 failures are environmental on this machine and fail there
too, or pass on rerun). CI on our fork at c20d46f (with our Rust toolchain pin, macOS jobs
off): every code job passed, including pathspec-1x; the macOS docs build got no runner.
https://github.com/fstrasz/chunkhound/actions/runs/45440594707

🤖 Generated with Claude Code, reviewed by FStrasz

fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
… fix/watcher-link-position (chunkhound#485)

Ordinary merge, so the stack carries chunkhound#481's review fixes (c3a7aeb,
5b188ad, 10d03a2, cdfbf58, 4f42f38, ad130d3, 7b755eb, d450191).
The two branches share only 0ab907b/293f8a6d; chunkhound#485's b359531,
6e32b20 and 81f1715 are parallel ports of chunkhound#481's 535466f, 5122b33
and d450191. Five files conflicted:

1. chunkhound/utils/ignore_engine.py (6 hunks): took chunkhound#481's side.
   chunkhound#485's file was a subset of it: chunkhound#481 adds the linked nested
   repository lookup (_repo_locations, _nearest_repo), the in-tree root
   respelling note and the config-exclude rules refactor. chunkhound#485's own
   ignore_engine change from a902b55 (match a directory in its "dir/"
   form only) is already in chunkhound#481's side. Dropped: chunkhound#485's "(TFS 65863)"
   comment tag.
2. chunkhound/services/realtime_path_filter.py (2 hunks): took chunkhound#481's
   side. It reports ignore-engine errors on directories instead of
   returning False (_ignore_rule_matches), respells a link-spelled root
   (_engine_path) and judges a linked file by its target in should_index.
   chunkhound#485's side was the older form of the same code.
3. chunkhound/services/realtime/events.py (1 hunk): took chunkhound#485's side.
   It contains chunkhound#481's change (excludes_directory before queuing a new
   directory) and builds on it: admission on the unresolved path,
   _queue_admitted and _target_admitted (a902b55, e888fd2).
4. tests/ignore/test_pathspec_contract.py (add/add, 3 hunks): took
   chunkhound#481's side, which compares the engine with git check-ignore instead
   of reading pathspec internals (4f42f38, 7b755eb, review request).
5. tests/realtime/test_filter_consistency_realtime_cleanup.py (6 hunks):
   union. chunkhound#481's side, plus chunkhound#485's tests copied verbatim from 81f1715:
   _linked_package_layout and the four tests after it, then
   test_polling_walk_does_not_enter_excluded_node_modules, _file_symlink
   and test_file_alias_to_excluded_target_is_not_queued, with their
   imports (os, typing.Any, pipeline._walk_files). Kept chunkhound#481's newer
   test_scan_walk_and_admission_agree_with_git_on_reincluded_files (it
   also checks new-directory expansion). Dropped chunkhound#481's comment that the
   walk "still descends the link with rglob": chunkhound#485 replaced rglob with a
   pruning os.walk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
…ink's target

chunkhound#481's RealtimePathFilter.should_index also requires a link's resolved
target to pass the policy, which is right for indexing. chunkhound#485 admits a
watchdog delete on the unresolved path through the same predicate, so
after chunkhound#481 was merged in, deleting alias.py -> node_modules/pkg/secret.py
was filtered and never queued, breaking chunkhound#485's contract that a delete is
still queued for cleanup
(test_file_alias_to_excluded_target_is_not_queued).

should_index gains check_target (default True). _should_admit_event
judges a "deleted" event with check_target=False; created and modified
events still require the target to pass.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
…luded-dir-memo (chunkhound#490)

Ordinary merge of chunkhound#485 after chunkhound#481 was merged into it, so chunkhound#490 carries
chunkhound#481's review fixes. Three files conflicted:

1. chunkhound/utils/ignore_engine.py: took the chunkhound#485 side. chunkhound#490's file was
   identical to chunkhound#485's head 81f1715 (4467926 is a parallel port of the
   same pathspec 1.x fix), so the conflict came only from the two ports.
2. tests/ignore/test_pathspec_contract.py: took the chunkhound#485 side, for the
   same reason.
3. chunkhound/services/realtime_path_filter.py: hand-merged. Started from
   the chunkhound#485 side (chunkhound#481's rewrite: _ignore_rule_matches, _engine_path,
   _admits) and added chunkhound#490's directory memo to it: _DIR_DECISIONS_MAX,
   _dir_decisions, _dir_decisions_engine, _keep_dir_decisions (off for
   the libgit2 evaluator), _in_tree_under_root and _directory_excluded.
   Two choices that the merge needed and neither side made:
   a. The memo now runs inside _ignore_rule_matches, for directories and
      for a file's parent, instead of inside excludes_directory and
      should_index. An engine error in the memo therefore marks the filter
      degraded and warns once, as chunkhound#481 made every other evaluation do;
      chunkhound#490's version returned False from excludes_directory silently.
   b. _directory_excluded matches each directory as _engine_path spells
      it, as every other match does since chunkhound#481. Without that, a root
      spelled through a link (/var vs /private/var on macOS) would send
      the memo's matches to the link targets, which
      test_linked_package_is_excluded_when_the_root_is_spelled_through_a_link
      checks against.
   _in_tree_root is defined once; both sides defined it identically.

No test ran on this merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fstrasz added a commit to fstrasz/chunkhound that referenced this pull request Nov 25, 2026
…ction-excluded (chunkhound#491)

Ordinary merge of chunkhound#485 after chunkhound#481 was merged into it, so chunkhound#491 carries
chunkhound#481's review fixes. Two files conflicted, both resolved to the chunkhound#485
side:

1. chunkhound/utils/ignore_engine.py
2. tests/ignore/test_pathspec_contract.py

In both, chunkhound#491's file was identical to chunkhound#485's head 81f1715 (6599cb3 is
a parallel port of the same pathspec 1.x fix), so the conflicts came only
from the two ports. realtime_path_filter.py, watchman.py and the cleanup
tests merged without conflict; chunkhound#491 had not changed
realtime_path_filter.py beyond chunkhound#485.

No test ran on this merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants