graphify icon indicating copy to clipboard operation
graphify copied to clipboard

Nested .gitignore rules apply outside their own subtree, zeroing the scan

Open AmirRaguan opened this issue 4 months ago • 4 comments

Summary

detect() loads nested ignore files during the walk (_load_dir_own_ignore(dp), ref #1206) and appends their patterns to the shared ignore_patterns list — but _is_ignored then applies those patterns to paths outside the loading directory's subtree. Git scopes a nested .gitignore to its own directory tree; graphify applies it globally.

Repro

mkdir -p repo/tooldir repo/src
echo '*' > repo/tooldir/.gitignore        # common pattern in tool-managed dirs
echo 'x = 1' > repo/src/app.py
cd repo && python -c "
from graphify.detect import detect
from pathlib import Path
print(detect(Path('.'))['total_files'])   # 0 — expected: 1 (src/app.py)
"

Because the walk visits tooldir (alphabetically) before src, its * pattern is in the list when src/app.py is evaluated → every file in the repo is ignored and detect returns an empty corpus with no warning.

Hit in the wild: a Claude Code plugin state dir (.superpowers/sdd/.gitignore containing *) silently zeroed a whole-repo scan (v0.9.15).

Direct evidence

from graphify.detect import _load_dir_own_ignore, _is_ignored
pats = _load_dir_own_ignore(root / 'tooldir')    # [(<root>/tooldir, '*')]
_is_ignored(root / 'src/app.py', root, pats)      # True — should be False

Expected

A pattern loaded from dir/.gitignore should only match paths under dir/ (the tuple already carries the base dir — the matcher just needs to enforce it).

Workaround

Root .graphifyignore excluding the offending directory (so the walk prunes it before loading its ignore file).

Aside, minor: **/name patterns from the global git ignore also fail to match their own target (_is_ignored(root/'.claude/settings.local.json', ...) is False for pattern **/.claude/settings.local.json) — opposite direction, may share a root cause in the matcher.

AmirRaguan avatar Jul 14 '26 00:07 AmirRaguan

Independently hit and root-caused the same bug on v0.9.15 — confirming with a second in-the-wild trigger and a tested fix.

Second wild trigger: the hypothesis testing library auto-writes .hypothesis/.gitignore containing a bare * into any repo that runs property tests. On our repo, detect() returned 0 files (expected 204) with no warning. Any tool-managed state dir that self-gitignores reproduces it, so real-world exposure is broad.

Root cause (detect.py, _is_ignored, v0.9.15 around L958–976): the anchored (leading-/) branch correctly matches against target.relative_to(anchor), but the non-anchored branch first matches against target.relative_to(root) regardless of the pattern's anchor — so a nested .gitignore's * matches every path in the corpus. The anchor != root fallback afterwards only ever adds matches; it never scopes them.

Fix that passes the full detect suite (143/143 including the existing nested-negation tests like sub/.gitignore: !important.py, plus two new regression tests below) — match every pattern only against its anchor-relative path, with the anchor dir itself exempt:

matched = False
try:
    rel_anchor = str(target.relative_to(anchor)).replace(os.sep, "/")
except ValueError:
    continue  # target outside this pattern's anchor: cannot match
if rel_anchor != ".":
    matched = _matches(rel_anchor, p, anchored=anchored)

(When anchor == root this is behavior-identical to the old root-relative match, so root-level ignore semantics are unchanged.)

Regression tests:

def test_nested_gitignore_star_does_not_ignore_outside_its_dir(tmp_path):
    (tmp_path / "README.md").write_text("# hello")
    (tmp_path / "main.py").write_text("x = 1")
    hyp = tmp_path / ".hypothesis"
    hyp.mkdir()
    (hyp / ".gitignore").write_text("*\n")
    (hyp / "cached.py").write_text("y = 2")
    assert detect(tmp_path)["total_files"] == 2

def test_nested_gitignore_patterns_still_apply_inside_their_dir(tmp_path):
    (tmp_path / "main.py").write_text("x = 1")
    sub = tmp_path / "sub"
    sub.mkdir()
    (sub / ".gitignore").write_text("*.log\n")
    (sub / "keep.py").write_text("y = 2")
    (sub / "noise.log").write_text("z")
    assert detect(tmp_path)["total_files"] == 2

One adjacent observation while debugging: graphify update/--watch re-run detect() internally without any extra_excludes escape hatch, so on affected repos updates keep failing even after a first successful build made with a workaround (the shrink-guard catches the data loss, but updates are dead until this is fixed).

Happy to open a PR with the patch + tests if useful.

Alwyn93 avatar Jul 14 '26 09:07 Alwyn93

Confirming this independently — hit the exact same symptom on a PHP/Laravel + React monorepo (unrelated stack, different repo).

Repro on my end:

  • detect(Path('.')) on the repo root → total_files: 0
  • detect(Path('Backend-laravel')) (has its own .gitignore) → total_files: 0
  • detect(Path('Backend-laravel/app')) (no nested .gitignore inside) → total_files: 459 (correct)
  • Same pattern for a second subproject (Frontend → 0, Frontend/src → 337, correct)

So any directory that itself contains a .gitignore returns an empty corpus, while a directory one level deeper (past the last nested .gitignore) scans fine — consistent with the root-cause you described (_is_ignored applying a nested ignore file's patterns outside its own subtree during the walk).

Workaround I used: point /graphify at the subfolder just past the last nested .gitignore instead of the project root, then graphify merge-graphs the resulting graphs back together. Works, but means the root-level project docs/config never get scanned unless they happen to live below that point.

graphify 0.9.15, Windows (Git Bash).

Nicolas-SalasP avatar Jul 14 '26 12:07 Nicolas-SalasP

Confirming independently on graphifyy==0.9.15 (macOS arm64). Adding one thing I don't see covered yet: this bug escalates from "empty scan" into "the existing graph gets destroyed", and the on-screen guidance actively leads users into the destructive path.

Scope note (to save others a wrong turn)

I initially suspected .pytest_cache/.gitignore and .ruff_cache/.gitignore — both are auto-generated with a bare * — would make this near-universal for Python. They don't, and it's worth stating explicitly: _SKIP_DIRS (detect.py:689) already prunes .pytest_cache, .ruff_cache, .mypy_cache, .venv, .tox, .nox, so the walk never descends into them and never loads their ignore file. I audited 9 repos on this machine: 7 had those cache files and scanned fine.

The trigger is narrower: a bare-* .gitignore in a directory that is not in _SKIP_DIRS. In my case, two of them:

  • eval/maintenance/corpus/.gitignore — hand-written, the standard *\n!.gitignore idiom for versioning an empty directory
  • .venv.symlink-bak/.gitignore — a renamed venv; _SKIP_DIRS matches .venv exactly, so .venv.symlink-bak is walked

Same tree, single delta, to isolate it:

detect(repo)                       →  total_files: 0
detect(repo/src)                   →  95 files          # no nested bare-* below it
detect(repo) w/ those 2 removed    →  396 code, 49 docs # correct

This is consistent with the .hypothesis report above: any tool-managed state dir that isn't already pruned triggers it.

The part that hurt: silent pruning, then guided data loss

The scan returning zero is not where it ends. update/extract don't report "I found no files" — they interpret the invisible files as deleted and prune the graph accordingly:

[graphify extract] 0 code, 0 docs changed; 0 unchanged; 590 deleted
[graphify] Pruned 5495 node(s) from 590 deleted source file(s)
[graphify extract] wrote graph.json: 143 nodes, 0 edges     # was 5,649 nodes / 10,049 links

The anti-regression guard is the only thing standing between the user and that outcome:

[graphify] WARNING: new graph has 84 nodes but existing graph.json has 5649.
Refusing to overwrite — you may be missing chunk files from a previous session.
Pass --force to override.

But the guard's own message recommends --force — and, separately, loading an older graph prints rebuild with 'graphify extract --force' to get path-qualified IDs (#1504). So a user hitting this bug is told, twice, by the tool itself, to pass the exact flag that destroys their graph. I followed that advice and went from 5,649 nodes to 143. I had a backup. Someone following the on-screen instructions may not.

Two suggestions, independent of the scoping fix in #1885:

  1. A 100%-corpus-loss prune should be a hard error, not a prune. "Every source file in the repository disappeared at once" is never a legitimate incremental state — it's a scanner failure. Refuse, and say so.
  2. --force should override the node-count guard but never the corpus-went-to-zero condition, and the guard message should not name --force as the remedy.

Secondary: watch and git hooks are permanently broken on an affected repo

Every rebuild path re-runs detect(), so on an affected repo graphify watch and the post-commit hook can never update the graph — they scan, find 0 files, and (correctly) refuse to write. The graph silently freezes at whatever commit it was last built from, with no warning. Mine had been stale across a full merge and I only noticed while debugging something else.

The .graphifyignore workaround from the issue body does fix this, and it's worth highlighting why it's the right workaround rather than --exclude: ignore files are re-read from disk on every detect(), so they survive update/watch/hooks, whereas --exclude only applies to the initial scan (#1886).

Unrelated gap noticed while debugging

graphify hook install installs post-commit and post-checkout but not post-merge. Git fires post-merge (not post-commit) for a merge commit, so merges never trigger a rebuild even on a healthy repo. Happy to open that separately if useful.

Environment: graphifyy==0.9.15 (uv tool), macOS arm64, Python 3.12, ~400 source files.

AndreLFSMartins avatar Jul 14 '26 14:07 AndreLFSMartins

Confirming independently on graphifyy==0.9.15 (macOS arm64). Same root cause as reported — adding a trigger that I don't see in either this thread or #1887, and that I think changes the priority calculus: husky.

The trigger is auto-generated into ~every JS/TS repo that uses husky

The wild triggers listed so far (.superpowers/sdd/, .hypothesis/, .pytest_cache/, .ruff_cache/) are all opt-in-ish: you hit them if you happen to use that tool. husky is different — it writes the poison file as part of its normal install, from its own source:

// node_modules/husky/index.js:20  (husky 9.1.7)
w(_('.gitignore'), '*')

That creates .husky/_/.gitignore containing exactly one byte:

$ xxd .husky/_/.gitignore
00000000: 2a                                       *

npm install regenerates it, so it comes back even if you delete it. husky is at 29.3M downloads/week (npm, week of 2026-07-07). So the practical statement is: graphify returns found 0 code on a large fraction of JS/TS repos out of the box, and the user has no way to connect the symptom to husky.

Measured on a real repo

Node/TypeScript + Drizzle/Postgres monorepo, husky 9.1.7:

files found graph
as-is 0 empty
with .husky/ excluded 1053 6355 nodes / 15881 edges / 585 communities

Nothing else changed. As others noted, there's no warning — found 0 code, 0 docs, 0 papers, 0 images and an empty graph is the entire signal.

Minimal repro (3 files, no husky install needed)

mkdir -p repo/.husky/_ repo/src && cd repo
echo 'export const a = 1' > src/a.ts
printf '*' > .husky/_/.gitignore     # exactly what husky 9 writes
graphify extract . --code-only
# → [graphify extract] found 0 code, 0 docs, 0 papers, 0 images

Delete .husky/_/.gitignore and the same command finds src/a.ts.

Interaction worth flagging: this is the same dir graphify installs its own hooks into

graphify hook install resolves core.hooksPath (.husky/_ on husky 9) and writes .husky/post-commit. So graphify's own git integration lives next to the file that makes graphify blind. Both features are pointed at .husky/ and they currently work against each other.

Workaround, for anyone landing here from a husky repo

Add .husky/ to a root .graphifyignore:

.husky/

This has to be the root ignore specifically. In detect()'s walk, _load_dir_own_ignore(dp) runs when a directory is visited, while the noise/ignore pruning applies to that directory's children — so a root-level rule prunes .husky/ before the walk ever descends into .husky/_ and reads its *. Anything that only matches after the walk enters is too late; the pattern is already in the shared list.

Fully agree with the fix proposed in #1887 (scope a non-anchored nested pattern to its own anchor subtree; drop the unconditional target.relative_to(root) attempt for non-root anchors). Just noting that until that lands, husky alone probably accounts for more silent zeroed scans than all the other triggers in these threads combined.

rjmarin avatar Jul 14 '26 22:07 rjmarin