Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
23 changes: 22 additions & 1 deletion infra/worktree-reaper/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ A tree is reaped only when **all** gates hold at decision time:
| Gate | Proof |
|---|---|
| PUSHED | Branch tip is on origin: equal to `origin/<branch>`, an ancestor of it, contained in origin's default branch, or patch-equivalent to either (`git cherry`). Origin refs are refreshed first with a full-refspec fetch (`+refs/heads/*:refs/remotes/origin/* --prune`); if the fetch fails, that primary is skipped entirely (fail closed). Detached HEADs are **never** reaped in v1. |
| CLEAN | `git status` shows no tracked changes and no untracked files beyond the generated-dirt allowlist (below). |
| CLEAN | `git status` shows no tracked changes and no untracked files beyond the generated-dirt allowlist (below). Ignored files are enumerated too (`--ignored=matching`): any ignored path beyond the ignored-dirt allowlist (below) blocks the reap — ignored content is by definition not proven on origin — and allowlisted ignored paths in a reaped tree are recorded by path in the run record before removal. |
| QUIET | Last activity ≥ `quiet_hours` (default 6) ago, absolute epoch. Activity = newest working-tree file mtime (the tree's root `.git` entry excluded) max()ed with the HEAD reflog timestamp. |
| UNOCCUPIED | A fresh `/proc` cwd scan shows no process inside the tree; re-scanned immediately before each removal. |
| NOT DENIED | Not on the config denylist, not locked, and not the tree the running script lives in (install-tree self-protection). |
Expand Down Expand Up @@ -57,6 +57,27 @@ Allowlisting applies to **untracked** entries only: a *modified tracked*
`fleet-feed.json` is real dirt and keeps the tree. Everything else
untracked — probe WIP, `.cloudflare/`, notes — keeps the tree.

### Ignored-dirt allowlist (#6734)

Ignored files are the blind spot the PUSHED gate cannot cover: they
are never pushed, so a tree whose only extra content is ignored
(local state, ignored databases, scratch) would otherwise reap as
"clean" and the content would be deleted unrecorded. The CLEAN gate
therefore enumerates ignored paths (`git status --ignored=matching`;
ignored directories collapse to one `target/`-style entry) and fails
closed on any of them beyond the ignored-dirt allowlist (config keys
`ignored_dirt_names` — matched on any path component, so build output
is covered at any depth — plus `ignored_dirt_prefixes` /
`ignored_dirt_files`, mirroring the generated-dirt keys):

- `target`, `node_modules`, `__pycache__`, `.direnv` — regenerable
build/tool output, ignored by design in fleet worktrees.

An unlisted ignored path — an ignored database, a local-state file —
always keeps the tree. When a tree *is* reaped, every allowlisted
ignored path it contained is recorded by path in the run record
(`ignored_removed`) before the removal runs.

## Logs and state

All state lives in `~/.local/state/worktree-reaper/` on the laptop
Expand Down
83 changes: 71 additions & 12 deletions infra/worktree-reaper/bin/worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@
e.g. pkgs/mcpx/internal/cli/logs/, and generated_dirt_files,
e.g. fleet-feed.json — matched on untracked entries only,
re-verified in the same run just before removal).
Ignored files are enumerated too (#6734): any ignored
path beyond the ignored-dirt allowlist (config:
ignored_dirt_names — a path component at any depth, e.g.
target — plus ignored_dirt_prefixes / ignored_dirt_files)
blocks the reap the same way, because ignored content is
by definition not proven on origin. Allowlisted ignored
paths in a reaped tree are recorded by path in the run
record before removal.
3. QUIET last activity >= quiet_hours ago (absolute epoch). Activity
= newest working-tree file mtime excluding the tree's root
.git entry, max()ed with the HEAD reflog timestamp.
Expand Down Expand Up @@ -68,6 +76,13 @@
"deny_names": [],
"generated_dirt_prefixes": ["pkgs/mcpx/internal/cli/logs/"],
"generated_dirt_files": ["fleet-feed.json"],
# Ignored dirt (#6734): build output is ignored by design, so an
# ignored path whose component/prefix/basename is named here does
# not block a reap (it is recorded in the run record instead); any
# OTHER ignored path fails the CLEAN gate closed.
"ignored_dirt_names": ["target", "node_modules", "__pycache__", ".direnv"],
"ignored_dirt_prefixes": [],
"ignored_dirt_files": [],
"fetch": True,
}

Expand Down Expand Up @@ -286,24 +301,58 @@ def pushed_proof(primary, tip, branch):


def status_entries(tree):
"""Return (tracked_dirty, untracked) repo-relative path lists."""
"""Return (tracked_dirty, untracked, ignored) repo-relative paths.

Ignored paths come from `--ignored=matching` (#6734): ignored files
are listed individually and ignored directories collapse to one
trailing-slash entry (e.g. `target/`, `sub/target/`) even with
`--untracked-files=all`, so the lists stay small enough to record.
"""
rc, out, err = run_git(
tree, "status", "--porcelain=v1", "-z", "--no-renames",
"--untracked-files=all",
"--untracked-files=all", "--ignored=matching",
)
if rc != 0:
raise RuntimeError(f"status failed in {tree}: {err.strip()}")
tracked, untracked = [], []
tracked, untracked, ignored = [], [], []
for token in out.split(b"\0"):
if len(token) < 4:
continue
xy = token[:2].decode("ascii", "replace")
path = token[3:].decode("utf-8", "surrogateescape")
if xy == "??":
untracked.append(path)
elif xy == "!!":
ignored.append(path)
else:
tracked.append(path)
return tracked, untracked
return tracked, untracked, ignored


def ignored_allowlisted(ignored, cfg):
"""Split ignored paths into (allowlisted, other) per the config.

Mirrors dirt_allowlisted for untracked files, plus component
matching: build output sits at any depth (`pkgs/id/target/`,
`web/node_modules/`), so a name in ignored_dirt_names allowlists
any path that has it as a component — which also covers git's
collapsed directory entries (`target/`) and files under them.
"""
prefixes = [p if p.endswith("/") else p + "/" for p in cfg.get("ignored_dirt_prefixes", [])]
names = set(cfg.get("ignored_dirt_files", []))
components = set(cfg.get("ignored_dirt_names", []))
allow, other = [], []
for path in ignored:
parts = [part for part in path.split("/") if part]
if (
any(path.startswith(p) for p in prefixes)
or os.path.basename(path.rstrip("/")) in names
or any(part in components for part in parts)
):
allow.append(path)
else:
other.append(path)
return allow, other


def dirt_allowlisted(untracked, cfg):
Expand Down Expand Up @@ -445,19 +494,24 @@ def evaluate_tree(primary, wt, cfg, now, cwds):
rec["reason"] = "unpushed"
return rec
try:
tracked, untracked = status_entries(tree)
tracked, untracked, ignored = status_entries(tree)
except RuntimeError as exc:
gates["clean"] = {"ok": False, "error": str(exc)}
rec["reason"] = "status-error"
return rec
allow, other = dirt_allowlisted(untracked, cfg)
# Clean = no tracked changes and no untracked files beyond the
# allowlisted generated dirt (allowlisted-only dirt reaps via --force).
ig_allow, ig_other = ignored_allowlisted(ignored, cfg)
# Clean = no tracked changes, no untracked files beyond the
# allowlisted generated dirt, and no ignored paths beyond the
# ignored-dirt allowlist (#6734 — ignored content is never proven
# on origin, so an unlisted ignored path fails closed like any
# other dirt; allowlisted dirt reaps via --force).
gates["clean"] = {
"ok": not tracked and not other,
"ok": not tracked and not other and not ig_other,
"tracked": tracked[:20], "untracked_other": other[:20],
"allowlisted": allow[:20],
"allowlisted_only": bool(allow) and not tracked and not other,
"ignored_allowlisted": ig_allow[:20], "ignored_other": ig_other[:20],
"allowlisted_only": bool(allow or ig_allow) and not tracked and not other and not ig_other,
}
if not gates["clean"]["ok"]:
rec["reason"] = "dirty"
Expand Down Expand Up @@ -508,17 +562,22 @@ def reap_tree(primary, rec, cfg):
rec["reason"] = "occupied-at-removal"
return False
try:
tracked, untracked = status_entries(tree)
tracked, untracked, ignored = status_entries(tree)
except RuntimeError as exc:
rec["action"] = "keep"
rec["reason"] = f"status-error-at-removal: {exc}"
return False
allow, other = dirt_allowlisted(untracked, cfg)
if tracked or other:
ig_allow, ig_other = ignored_allowlisted(ignored, cfg)
if tracked or other or ig_other:
rec["action"] = "keep"
rec["reason"] = "dirty-at-removal"
return False
force = bool(allow)
# Record every ignored path this removal is about to delete, by
# path, BEFORE the removal runs (#6734): a reap must never
# silently delete content the record does not name.
rec["ignored_removed"] = ig_allow
force = bool(allow or ig_allow)
args = ["worktree", "remove"] + (["--force"] if force else []) + [tree]
rc, _, err = run_git(primary, *args)
if rc != 0:
Expand Down
2 changes: 1 addition & 1 deletion infra/worktree-reaper/config.json
Original file line number Diff line number Diff line change
@@ -1 +1 @@
{"deny_names":[],"deny_paths":["~/git/cairn","~/git/code","~/git/dezren39","~/git/hardware-doc","~/git/nix","~/git/openchamber-fork","~/git/opencode","~/git/zettel"],"deny_prefixes":[],"fetch":true,"generated_dirt_files":["fleet-feed.json"],"generated_dirt_prefixes":["pkgs/mcpx/internal/cli/logs/"],"git_root":"~/git","max_removals":100,"primaries":[],"quiet_hours":6,"state_dir":"~/.local/state/worktree-reaper"}
{"deny_names": [], "deny_paths": ["~/git/cairn", "~/git/code", "~/git/dezren39", "~/git/hardware-doc", "~/git/nix", "~/git/openchamber-fork", "~/git/opencode", "~/git/zettel"], "deny_prefixes": [], "fetch": true, "generated_dirt_files": ["fleet-feed.json"], "generated_dirt_prefixes": ["pkgs/mcpx/internal/cli/logs/"], "git_root": "~/git", "ignored_dirt_files": [], "ignored_dirt_names": ["target", "node_modules", "__pycache__", ".direnv"], "ignored_dirt_prefixes": [], "max_removals": 100, "primaries": [], "quiet_hours": 6, "state_dir": "~/.local/state/worktree-reaper"}
78 changes: 78 additions & 0 deletions infra/worktree-reaper/tests/test_worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@
dirty tracked file -> kept (dirty)
untracked non-allowlisted file -> kept (dirty)
allowlisted generated dirt only -> reaped via --force
ignored file only (unlisted) -> kept (dirty, #6734)
allowlisted untracked + ignored -> kept (dirty, #6734)
allowlisted ignored build output -> reaped, ignored paths recorded (#6734)
detached HEAD -> kept (detached, v1 rule)
denylisted tree -> kept (denied)
process cwd inside tree -> kept (occupied)
Expand Down Expand Up @@ -255,6 +258,40 @@ def test_04_quiet_gate(self):
decisions = self.runner.run(quiet_hours=0)
self.assertFalse(os.path.isdir(tree))

def test_05_ignored_gate(self):
repo, run = self.repo, self.runner.run
# Ignore rules live in the shared repo exclude so every
# worktree sees them without touching tracked content.
exclude = os.path.join(repo.primary, ".git", "info", "exclude")
with open(exclude, "a") as fh:
fh.write("local-state\ntarget/\n")
# Ignored-only tree: kept — before #6734 this reaped as clean
# and the ignored file was deleted unrecorded.
t_ignored = repo.branch_tree("t/ignored-only", push=True)
repo.write(t_ignored, "local-state", "precious\n")
# Allowlisted untracked dirt does not rescue an unlisted
# ignored file either.
t_mixed = repo.branch_tree("t/ignored-mixed", push=True)
repo.write(t_mixed, "fleet-feed.json", "{}\n")
repo.write(t_mixed, "local-state", "precious\n")
decisions = run()
for tree in (t_ignored, t_mixed):
self.assertTrue(os.path.isdir(tree), f"{tree} must survive")
self.assertEqual(decisions[tree]["action"], "keep")
self.assertEqual(decisions[tree]["reason"], "dirty")
self.assertIn("local-state",
decisions[tree]["gates"]["clean"]["ignored_other"])
# Allowlisted ignored build output (target/, a default
# ignored_dirt_names component) reaps — and the run record
# names the ignored path that was deleted with the tree.
t_target = repo.branch_tree("t/ignored-target", push=True)
repo.write(t_target, "target/debug/app.bin", "build output\n")
decisions = run()
self.assertFalse(os.path.isdir(t_target),
"allowlisted-ignored tree should be reaped")
self.assertEqual(decisions[t_target]["action"], "reaped")
self.assertIn("target/", decisions[t_target]["ignored_removed"])


class RunLogCollisionTests(unittest.TestCase):
"""#5716: two runs in the same second must not share a run log."""
Expand Down Expand Up @@ -299,6 +336,47 @@ def test_dirt_allowlisted(self):
self.assertEqual(len(allow), 3)
self.assertEqual(other, ["src/real.py"])

def test_ignored_allowlisted(self):
cfg = {"ignored_dirt_names": ["target", "node_modules"],
"ignored_dirt_prefixes": ["build/"],
"ignored_dirt_files": [".DS_Store"]}
allow, other = wr.ignored_allowlisted(
["target/", "pkgs/id/target/", "web/node_modules/", "build/x.o",
".DS_Store", "local-state", "pkgs/id/.identity.db",
"src/target_notes.txt"], cfg)
self.assertEqual(len(allow), 5)
# A component match is exact: target_notes.txt is not target/,
# and unlisted ignored content (a local-state file, an ignored
# database) always fails closed.
self.assertEqual(other, ["local-state", "pkgs/id/.identity.db",
"src/target_notes.txt"])

def test_status_entries_enumerates_ignored(self):
root = tempfile.mkdtemp(prefix="wtreaper-status-")
try:
git(root, "init", "-q", "-b", "main")
with open(os.path.join(root, ".gitignore"), "w") as fh:
fh.write("local-state\ntarget/\n")
with open(os.path.join(root, "base.txt"), "w") as fh:
fh.write("base\n")
git(root, "add", ".")
git(root, "commit", "-q", "-m", "base")
with open(os.path.join(root, "local-state"), "w") as fh:
fh.write("x")
os.makedirs(os.path.join(root, "target"))
with open(os.path.join(root, "target", "app"), "w") as fh:
fh.write("x")
with open(os.path.join(root, "notes.txt"), "w") as fh:
fh.write("x")
tracked, untracked, ignored = wr.status_entries(root)
self.assertEqual(tracked, [])
self.assertEqual(untracked, ["notes.txt"])
# Ignored files list individually; the ignored directory
# collapses to one trailing-slash entry.
self.assertEqual(sorted(ignored), ["local-state", "target/"])
finally:
shutil.rmtree(root, ignore_errors=True)

def test_walk_activity(self):
root = tempfile.mkdtemp(prefix="wtreaper-walk-")
try:
Expand Down
Loading