Skip to content
Merged
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
2 changes: 1 addition & 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, no untracked files beyond the generated-dirt allowlist (below), and no ignored files beyond the ignored-dirt allowlist (`ignored_dirt_prefixes`/`ignored_dirt_files`, default `target/`, `node_modules/`). Ignored paths in a reaped tree are recorded by path (`ignored_paths`) before removal (#6734). |
| 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
68 changes: 59 additions & 9 deletions infra/worktree-reaper/bin/worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,16 @@
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 gated too (#6734): the PUSHED proof
cannot cover content git ignores, so any ignored path
beyond the ignored-dirt allowlist (config:
ignored_dirt_prefixes, e.g. target/ and node_modules/
build output, and ignored_dirt_files) blocks the reap —
fail closed, at this gate and at the pre-removal
re-verification. Every ignored path present in a reaped
tree is recorded by path in the run record
(ignored_paths) before removal: a reap never silently
deletes unlisted content.
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 +78,8 @@
"deny_names": [],
"generated_dirt_prefixes": ["pkgs/mcpx/internal/cli/logs/"],
"generated_dirt_files": ["fleet-feed.json"],
"ignored_dirt_prefixes": ["target/", "node_modules/"],
"ignored_dirt_files": [],
"fetch": True,
}

Expand Down Expand Up @@ -286,24 +298,52 @@ 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 path lists.

Ignored entries (porcelain `!!`, via --ignored=matching) are
enumerated explicitly (#6734): without the flag they are invisible
to every gate, yet `git worktree remove` deletes them with the
tree. With =matching, git lists an ignored directory itself (path
ending in /) when the directory matches an ignore rule, and
individual ignored files otherwise.
"""
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's
ignored-dirt lists. Prefixes match on whole path segments (target/
matches target/ and pkgs/id/target/ alike): build output lives at
crate roots, not only at the tree root. Files match on basename,
like the generated-dirt allowlist."""
prefixes = [p.strip("/") for p in cfg.get("ignored_dirt_prefixes", [])]
names = set(cfg.get("ignored_dirt_files", []))
allow, other = [], []
for path in ignored:
segments = [seg for seg in path.split("/") if seg]
if any(seg in prefixes for seg in segments) or os.path.basename(path.rstrip("/")) in names:
allow.append(path)
else:
other.append(path)
return allow, other


def dirt_allowlisted(untracked, cfg):
Expand Down Expand Up @@ -445,18 +485,23 @@ 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)
ig_allow, ig_other = ignored_allowlisted(ignored, cfg)
# Clean = no tracked changes and no untracked files beyond the
# allowlisted generated dirt (allowlisted-only dirt reaps via --force).
# allowlisted generated dirt (allowlisted-only dirt reaps via --force),
# and no ignored files beyond the ignored-dirt allowlist (#6734:
# ignored content is exactly what the PUSHED proof cannot cover).
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],
"ignored_other": ig_other[:20], "ignored_allowlisted": ig_allow[:20],
"ignored": ignored,
"allowlisted_only": bool(allow) and not tracked and not other,
}
if not gates["clean"]["ok"]:
Expand Down Expand Up @@ -508,16 +553,21 @@ 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
# Record every ignored path in this tree before the irreversible
# step (#6734): only allowlisted ignored paths can be present
# here, and the record is the audit trail for their deletion.
rec["ignored_paths"] = ignored
force = bool(allow)
args = ["worktree", "remove"] + (["--force"] if force else []) + [tree]
rc, _, err = run_git(primary, *args)
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_prefixes": ["target/", "node_modules/"], "max_removals": 100, "primaries": [], "quiet_hours": 6, "state_dir": "~/.local/state/worktree-reaper"}
56 changes: 56 additions & 0 deletions infra/worktree-reaper/tests/test_worktree_reaper.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,8 @@ def run(self, *, quiet_hours=0, dry_run=False, deny_paths=()):
"deny_paths": list(deny_paths),
"generated_dirt_prefixes": ["pkgs/mcpx/internal/cli/logs/"],
"generated_dirt_files": ["fleet-feed.json"],
"ignored_dirt_prefixes": ["target/", "node_modules/"],
"ignored_dirt_files": [],
}
cfg_path = os.path.join(self.state_dir, "test-config.json")
os.makedirs(self.state_dir, exist_ok=True)
Expand Down Expand Up @@ -247,6 +249,50 @@ def test_03_reap_matrix(self):
# Caught either at evaluation or at the pre-removal re-scan.
self.assertTrue(decisions[t_occupied]["reason"].startswith("occupied"))

def _tree_with_ignored(self, branch, rule, ignored_rel):
"""A pushed tree whose branch commits a .gitignore rule, with an
ignored file present in the working tree."""
tree = self.repo.branch_tree(branch, push=True)
self.repo.write(tree, ".gitignore", rule + "\n")
git(tree, "add", ".gitignore")
git(tree, "commit", "--quiet", "-m", "ignore rule")
git(tree, "push", "--quiet", "origin", branch)
self.repo.write(tree, ignored_rel, "local state\n")
return tree

def test_05_ignored_gate(self):
# Ignored-only tree: the CLEAN gate must see the ignored file
# and keep the tree (#6734 — before the fix, status_entries
# returned ([], []) for this tree and it reaped as clean).
t_ignored = self._tree_with_ignored("t/ignored-only", "local-state.db", "local-state.db")
tracked, untracked, ignored = wr.status_entries(t_ignored)
self.assertEqual((tracked, untracked), ([], []))
self.assertEqual(ignored, ["local-state.db"])

# Allowlisted untracked dirt does not launder an unlisted
# ignored file: the tree is still kept.
t_mixed = self._tree_with_ignored("t/untracked-plus-ignored", "notes.db", "notes.db")
self.repo.write(t_mixed, "fleet-feed.json", "{}\n")

# Ignored build output under an allowlisted prefix reaps, and
# the record names the ignored paths it deleted.
t_target = self._tree_with_ignored("t/ignored-target", "target/", "target/build.o")

decisions = self.runner.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.db", decisions[t_ignored]["gates"]["clean"]["ignored_other"])
self.assertIn("notes.db", decisions[t_mixed]["gates"]["clean"]["ignored_other"])

self.assertFalse(os.path.isdir(t_target), "allowlisted ignored dirt should reap")
self.assertEqual(decisions[t_target]["action"], "reaped")
self.assertTrue(
any("target" in p for p in decisions[t_target]["ignored_paths"]),
f"reaped tree's record must name its ignored paths: {decisions[t_target]}",
)

def test_04_quiet_gate(self):
tree = self.repo.branch_tree("t/fresh", push=True)
decisions = self.runner.run(quiet_hours=100000)
Expand Down Expand Up @@ -290,6 +336,16 @@ def test_porcelain_parser(self):
self.assertEqual(entries[2]["branch"], "queue/1-2-z")
self.assertTrue(entries[2]["locked"])

def test_ignored_allowlisted(self):
cfg = {"ignored_dirt_prefixes": ["target/", "node_modules/"],
"ignored_dirt_files": ["scratch.db"]}
allow, other = wr.ignored_allowlisted(
["target/", "target/build.o", "pkgs/id/target/deps/x.o",
"node_modules/pkg/index.js", "data/scratch.db",
"pkgs/id/.identity.db", "local-state.db"], cfg)
self.assertEqual(len(allow), 5)
self.assertEqual(other, ["pkgs/id/.identity.db", "local-state.db"])

def test_dirt_allowlisted(self):
cfg = {"generated_dirt_prefixes": ["pkgs/mcpx/internal/cli/logs/"],
"generated_dirt_files": ["fleet-feed.json"]}
Expand Down
Loading