Skip to content

fix(disk-hygiene): inventory an empty directory at the scan depth boundary - #2661

Merged
kyle-sexton merged 1 commit into
mainfrom
fix/2618-empty-dir-at-scan-depth
Aug 15, 2026
Merged

kyle-sexton merged 1 commit into
mainfrom
fix/2618-empty-dir-at-scan-depth

Conversation

@kyle-sexton

Copy link
Copy Markdown
Member

No linked issue

Summary

scan_tree's depth cut was evaluated before any read of the child, so emptiness
was unobservable at the scan boundary: every directory at depth == max_depth
was marked walked=False regardless of what it held. That nulled its
logical_size, appended the not-walked qualifier, and put it in
truncated_paths, where preview refuses it as truncated-not-inventoried.

For an empty directory both effects are wrong in the same direction. It is
vacuously fully inventoried — there are no descendants left uncounted — and its
size is genuinely 0, not unknown. The consequence in a real run (#2618 F2) was
that no directory at depth N could ever be planned from a --max-depth N scan;
clearing one cost a delete-child → rescan-at-depth+1 → delete-parent cycle, two
extra approval-gated rounds per directory.

Fix

At the depth boundary only, probe for a first child before marking anything:

  • New directory_has_child() — one os.scandir, first entry only, no recursion
    and no count. Deliberately not top_level_entry_count(), which iterates every
    child to produce a number; a boundary directory with hundreds of thousands of
    entries is exactly the cost --max-depth exists to avoid. The question is
    "any?", not "how many?".
  • Fails closed. A directory that cannot be read reports True (assume
    content), so emptiness is proven, never assumed. The read sits inside the
    try because Windows surfaces an access denial on the first iteration step
    rather than on os.scandir itself. No new errors entry is recorded: the old
    code did no scandir there at all, so silence preserves prior behavior exactly.
  • Empty at the boundary now records walked=True, logical_size=0, no
    not-walked qualifier, and does not enter truncated_paths. With nothing left
    unwalked, target_identity also stops carrying a not-walked qualifier it did
    not earn.

Scoped to the depth branch only (constraint (a) of the issue's fix note). The
VCS_NAMES and protections branches wear the identical
subtotal = None; walked = False; truncated.append(...) shape, but they refuse a
walk for reasons emptiness does not answer — an empty protected directory or an
empty VCS root must still land in truncated. Two regression tests assert that,
and both were confirmed to fail when the probe is applied to those branches.

The four truncated_paths consumers, checked (constraint (b))

Consumer Effect of clearing an empty boundary directory
preview blocker (overlaps_truncated → truncated-not-inventoried) The directory becomes plannable. Safe: truncated-not-inventoried protects an uninventoried subtree, and an empty directory has none. It also arms the drift check rather than weakening it — see the TOCTOU note below.
preview unverified short-circuit The candidate no longer skips current_descendants / tracked_blocker / candidate_handle_state. Those short-circuits exist to avoid unbounded live walks on candidates that can never become approvable; an empty directory's walk is one scandir and it can be approvable, so running them is correct.
handoff_verify contested set Same shape, same reasoning. Note: the audit called this "apply's contested set" — it is actually handoff_verify, the read-only manual-handoff revalidation lane. apply itself never reads truncated_paths; it consumes preview's verdicts.
scan-complete passthrough Report-only. Two emit sites (normal scan and root-children mode), both pure passthrough; the reported list simply no longer names directories with nothing in them.

Fifth consumer, not in the audit's list: annotate_tracked subtracts each
truncated path from the git ls-files pathspec via :(exclude). A cleared empty
directory is no longer excluded, so the pathspec is marginally larger. No
behavior change: ls-files --cached reads the index, so a directory empty on
disk can still return index entries, but those paths were never scanned, so
by_path.get(relative) is None and no annotation changes.

TOCTOU. If a child appears between scan and preview, the directory is no
longer short-circuited, so current_descendants runs and
current_paths != expected_paths raises changed-since-scan. Asserted by
test_cleared_boundary_directory_that_gains_a_child_is_caught.

Rungs 2 and 3 of the issue's ladder (documenting the constraint; a separate
empty-verified qualifier) are deliberately not taken here.

Verification

Covering suite, run in full on this branch and on its merge base (b7e56070)
for comparison:

$ bash plugins/disk-hygiene/skills/clean/scripts/hygiene.test.sh

branch:   Ran 282 tests in 302.530s — FAILED (failures=3, skipped=4)
baseline: Ran 275 tests in 268.288s — FAILED (failures=3, errors=1, skipped=4)

The 282 − 275 = 7 added tests all pass. The three failures on this branch are a
strict subset of the baseline's four and are pre-existing and environmental on
this Windows workstation — test_stash_must_exist_in_an_independent_checkout
(8.3 short-path KYLESE~1 vs KyleSexton),
test_preview_allows_root_children_os_managed_snapshot, and
test_deny_emits_blocked_telemetry_when_sink_wired. The baseline's extra
test_every_local_branch_head_is_confirmed error did not recur. None are in this
diff's blast radius; CI runs the suite on a clean Linux runner.

The seven new tests, run in isolation — all ok:

$ python -m unittest -v test_hygiene.HygieneTests.test_empty_directory_at_scan_depth_is_inventoried_not_truncated ...
Ran 7 tests in 10.478s
OK
  • test_empty_directory_at_scan_depth_is_inventoried_not_truncated — size 0,
    no qualifier, truncated_paths == [], target roll-up exact.
  • test_non_empty_directory_at_scan_depth_stays_truncated — unchanged behavior.
  • test_empty_protected_directory_at_scan_depth_stays_truncated — regression guard.
  • test_empty_vcs_directory_at_scan_depth_stays_truncated — regression guard;
    hard_protection is stubbed so the VCS branch is the only thing that can
    truncate, otherwise .git's own vcs-metadata protection would keep the
    assertion green even if the probe had leaked into that branch.
  • test_directory_has_child_fails_closed_when_unreadable — fail-closed contract.
  • test_empty_directory_at_scan_depth_is_previewable — the payoff, at consumer 1.
  • test_cleared_boundary_directory_that_gains_a_child_is_caught — TOCTOU.

Mutation check on the regression guards. With the probe deliberately applied
to the VCS_NAMES and protections branches, both guards fail
(Lists differ: ['.git'] != []); reverted before commit. The guards discriminate.

Lint:

$ bash scripts/run-ruff.sh check plugins/disk-hygiene/skills/clean/scripts
All checks passed!

$ bash scripts/run-ruff.sh format --check plugins/disk-hygiene/skills/clean/scripts
3 files would be reformatted, 2 files already formatted

Both files in this diff are among the already-formatted two; the three
reformat candidates (destructive_guard.py, guard_launch_monitor.py,
test_guard_launch_monitor.py) are pre-existing and untouched here.

scripts/affected-tests.sh selects seven suites for this diff.
hygiene.test.sh is the one that covers the change and is reported above;
kill_switch_probe.test.sh and python3_alias_probe.test.sh also pass. The
remaining four are transitive dependents that do not touch the traversal branch
and blow the local wall-clock budget on Windows (the README's spawn-bound
caveat) — CI runs them.

Related


Not for auto-merge. This changes traversal logic that feeds a deletion
preview; it wants a human read of the four-consumer analysis above before it
lands.

@cursor

cursor Bot commented Aug 15, 2026

Copy link
Copy Markdown

Bugbot is not enabled for your account, so this pull request was not reviewed.

Enable Bugbot in the Cursor dashboard to get automatic reviews on future PRs.

@claude

claude Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @kyle-sexton's task in 3m 3s —— View job


Code review complete

  • Gather context (PR body, diff, CLAUDE.md/REVIEW.md)
  • Review hygiene.py changes for correctness
  • Review test_hygiene.py additions
  • Post findings

No blocking findings. This is a well-scoped, well-tested fix.

What I checked:

  • Traced visit()'s depth-boundary branch (hygiene.py#L1260-L1280) confirms the probe is gated strictly inside the elif max_depth is not None and depth >= max_depth arm, after the VCS-name and protections checks are already evaluated — so an empty .git or an empty protected directory still falls through to the old truncated.append(...) path, matching the PR's claim.
  • directory_has_child() (hygiene.py#L952-L972) fails closed correctly: the os.scandir call and the first next() step are both inside the try, and any OSError (including a plain "path vanished") returns True. metadata(path, kind, subtotal, walked=walked) at L1283 then records logical_size=0 with no not-walked qualifier only when walked was never flipped to False, which lines up with test_empty_directory_at_scan_depth_is_inventoried_not_truncated.
  • Walked the four consumers named in the PR body (preview's overlaps_truncated blocker and unverified short-circuit, handoff_verify's identical short-circuit, annotate_tracked's pathspec exclusion, and the scan-complete passthrough) against the current source — each is a straight read of truncated_paths/overlaps_truncated, so removing an empty boundary directory from that set has exactly the effect described, including the TOCTOU note: preview no longer short-circuits current_descendants for a cleared entry, so a child that appears between scan and preview is legitimately caught as changed-since-scan rather than hidden behind the old blanket block.
  • Cross-checked the seven new tests against this trace; each assertion matches what the traced code actually does (e.g., the VCS-branch regression guard stubs hard_protection to [] so .git's own vcs-metadata protection can't paper over a probe leak — that isolation is correct).

Not independently verified: this sandbox's Bash tool requires approval for any Python invocation (even python3 --version/python3 -c), which wasn't available in this run, so I could not execute hygiene.test.sh or the seven new tests myself. The pass/fail results and mutation-check in the PR description are author-claimed and unverified by me — the above is a static trace of the diff against its own test assertions, not a test run.

One non-blocking style observation, left out of the diff since it's a nit, not a defect: directory_has_child's next(iter(iterator), None) wraps the scandir iterator in a redundant iter() — os.scandir() already returns an iterator, so next(iterator, None) would be equivalent.

@claude

claude Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @kyle-sexton's task in 2m 16s —— View job


Security review — PR #2661

No security issues found.

This PR touches only plugins/disk-hygiene/skills/clean/scripts/hygiene.py and its test file. It changes traversal logic that feeds a destructive-operation preview/apply pipeline, so I specifically checked for TOCTOU and over-broad-deletion risk rather than treating it as routine.

What I verified:

  • New probe is fail-closed. directory_has_child() treats any OSError (unreadable, race-swapped, etc.) as "has content," so the old conservative not-walked marking is never cleared on a guess.
  • Scope is correctly limited to the depth-cut branch. The VCS-metadata and hard-protection branches (hygiene.py#L1238-L1259) are untouched, so an empty .git or protected directory still lands in truncated_paths and stays blocked — confirmed by the two regression tests in the diff.
  • TOCTOU between scan and preview is covered, not weakened. Clearing truncated_paths for an empty boundary directory removes the short-circuit in preview(), so current_descendants() now actually walks it; if a child appears before preview, current_paths != expected_paths raises changed-since-scan rather than silently allowing deletion. This is exercised by test_cleared_boundary_directory_that_gains_a_child_is_caught.
  • TOCTOU between preview and apply was already independently guarded, and this PR doesn't touch that guard: anchored_remove() opens the directory by fd and re-checks live emptiness (next(iterator, None) is not None → raise) immediately before os.rmdir, using O_NOFOLLOW and object-identity comparisons throughout. So even directories that this change newly makes "previewable" can never have rmdir succeed against them if they've gained content by apply time — the low-level removal path enforces emptiness on its own, independent of what the scan recorded.
  • No injection, credential-handling, permission-widening, or GitHub Actions surface in this diff (pure Python traversal + tests, no workflow files touched).

Net: the change is a reporting/planning correctness fix (lets a genuinely-empty boundary directory become plannable instead of stuck behind a rescan cycle), and the existing multi-layered identity/emptiness re-verification at both preview and apply means it doesn't open a path to deleting non-empty or attacker-modified directories.
· branch fix/2618-empty-dir-at-scan-depth

@github-actions

Copy link
Copy Markdown
Contributor

Last security-reviewed head: 51740f0eb13a7979627fa9d03dbc4ea969a68b71. On the next push, the relevance gate compares only the commits since this SHA; delete this comment to force a full re-review.

@github-actions

github-actions Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude has reviewed this PR 2 times. The lane skips further automatic reviews after 5; deleting this comment resets the count.

@kyle-sexton
kyle-sexton enabled auto-merge (squash) August 15, 2026 03:32
@cursor
cursor Bot force-pushed the fix/2618-empty-dir-at-scan-depth branch from 51740f0 to 540552d Compare August 15, 2026 03:33
Treat empty --max-depth boundary directories as walked size 0 instead of
truncated, via a fail-closed first-child probe. Bump to 0.20.1.

Closes #2618

Co-authored-by: Kyle Sexton <[email protected]>
@cursor
cursor Bot force-pushed the fix/2618-empty-dir-at-scan-depth branch from 540552d to 7fabb4a Compare August 15, 2026 03:33
@claude

claude Bot commented Aug 15, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @cursor[bot]'s task in 1m 49s —— View job


Code review — skip gate applied

  • Gather context (diff since prior review, custom instructions)
  • Check skip gate (open PR, not draft, non-trivial, no still-applying review at this head)
  • Review hygiene.py changes for correctness
  • Review test_hygiene.py additions
  • Post findings

No new findings — skip gate criteria 3/4 apply to this sync.

This lane already reviewed this PR at 51740f0 (see the "Code review complete" comment above). I diffed that reviewed commit against the current head (7fabb4a):

  • hygiene.py and test_hygiene.py are byte-identical between 51740f0 and 7fabb4a — git diff 51740f0 HEAD -- <those two paths> is empty. All correctness findings from that prior review still apply unchanged.
  • The only delta this sync introduced is version/changelog metadata:
    • plugin.json#L4 — patch bump 0.20.0 → 0.20.1, consistent with a bug-fix-only release per the plugin's declared semver policy.
    • CHANGELOG.md#L6-L16 — new ## [0.20.1] entry accurately summarizing the fix (matches the PR body's description of the probe, fail-closed behavior, and the two branches left untouched).

Both are correct, self-consistent, and outside the code-review lane's remit (no logic, no test coverage implications). This is a "trivial/automated, no meaningful review surface" sync per the skip gate — no inline comments posted.
· branch fix/2618-empty-dir-at-scan-depth

@kyle-sexton
kyle-sexton merged commit 72b86c4 into main Aug 15, 2026
1 check passed
@kyle-sexton
kyle-sexton deleted the fix/2618-empty-dir-at-scan-depth branch August 15, 2026 03:40
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.

1 participant