From 689cb579563bde3e65294c41e632c15af0487219 Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Mon, 23 Nov 2026 15:40:49 +0100 Subject: [PATCH 1/3] feat(project-scanner): enforce wellmanifest git-lifecycle 6 hard vetos (ticket-184) --- fixos/diagnostics/project_scanner.py | 365 +++++++++++++++++++++++++++ project/ticket-184/README.md | 33 +++ project/ticket-184/intent.json | 76 ++++++ tests/unit/test_project_scanner.py | 237 +++++++++++++++++ 4 files changed, 711 insertions(+) create mode 100644 project/ticket-184/README.md create mode 100644 project/ticket-184/intent.json diff --git a/fixos/diagnostics/project_scanner.py b/fixos/diagnostics/project_scanner.py index 91df675..fea7ef7 100644 --- a/fixos/diagnostics/project_scanner.py +++ b/fixos/diagnostics/project_scanner.py @@ -12,13 +12,40 @@ from __future__ import annotations +import json import os import shlex import subprocess +from collections.abc import Callable from dataclasses import dataclass from datetime import datetime, timezone from pathlib import Path +VERDICT_ALLOW = "ALLOW" +VERDICT_HOLD_PROTECTED = "HOLD_PROTECTED" + +VETO_ACTIVE_PROCESS = "VETO_ACTIVE_PROCESS" +VETO_ACTIVE_LEASE = "VETO_ACTIVE_LEASE" +VETO_OPEN_PR_OR_UNMERGED = "VETO_OPEN_PR_OR_UNMERGED" +VETO_DIRTY_OR_STASH = "VETO_DIRTY_OR_STASH" +VETO_UNPUSHED_REFS = "VETO_UNPUSHED_REFS" +VETO_WORKTREE_OR_IDE_OWNERSHIP = "VETO_WORKTREE_OR_IDE_OWNERSHIP" + +ACTIVE_LEASE_PHASES: frozenset[str] = frozenset( + {"claimed", "editing", "validating", "publication_frozen"} +) +_DEFAULT_BRANCH_REFS: tuple[str, ...] = ( + "origin/main", + "origin/master", + "main", + "master", +) +_IDE_OWNERSHIP_MARKERS: tuple[str, ...] = ( + ".idea/.lock", + ".idea/workspace.xml", + ".vscode/.lock", +) + # A directory is a "project root" worth inspecting if it has one of these. PROJECT_MARKERS: tuple[str, ...] = ( ".git", @@ -85,6 +112,20 @@ _PRUNE_DIR_NAMES = frozenset({".git"} | set(REMOVABLE_ARTIFACTS)) +@dataclass(frozen=True) +class CleanupVetoReport: + """Result of evaluating the 6 canonical wellmanifest/git-lifecycle hard vetos.""" + + target: str + verdict: str + veto_codes: tuple[str, ...] = () + reasons: tuple[str, ...] = () + + @property + def protected(self) -> bool: + return self.verdict == VERDICT_HOLD_PROTECTED + + @dataclass class ProjectArtifact: """A single removable artifact directory found inside a project.""" @@ -102,6 +143,8 @@ class ProjectArtifact: stale: bool cleanup_command: str project_has_recent_activity: bool = False + verdict: str = VERDICT_ALLOW + veto_codes: tuple[str, ...] = () def _get_dir_size_mb(path: str) -> float: @@ -266,12 +309,312 @@ def _project_source_has_recent_activity( return False +def _run_git(repo: Path, *args: str) -> subprocess.CompletedProcess[str] | None: + try: + return subprocess.run( + ["git", "-C", str(repo), *args], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + + +def _is_real_git_worktree(target: Path) -> bool: + proc = _run_git(target, "rev-parse", "--is-inside-work-tree") + return proc is not None and proc.returncode == 0 and proc.stdout.strip() == "true" + + +def _path_is_within(candidate: str, root: str) -> bool: + return candidate == root or candidate.startswith(root + os.sep) + + +def _check_active_process_veto(target: Path, *, check_lsof: bool = False) -> str | None: + """Hard veto 1: active process has cwd or open fd inside target.""" + try: + resolved = str(target.resolve()) + except OSError: + resolved = str(target) + + skip_pids = {str(os.getpid()), str(os.getppid())} + proc_root = Path("/proc") + if proc_root.is_dir(): + try: + proc_entries = os.listdir(proc_root) + except OSError: + proc_entries = [] + for pid in proc_entries: + if not pid.isdigit() or pid in skip_pids: + continue + pid_dir = proc_root / pid + try: + cwd = os.readlink(pid_dir / "cwd") + if _path_is_within(cwd, resolved): + return f"Active process PID {pid} has cwd inside {resolved}" + except OSError: + pass + fd_dir = pid_dir / "fd" + try: + fds = os.listdir(fd_dir) + except OSError: + continue + for fd in fds: + try: + link = os.readlink(fd_dir / fd) + except OSError: + continue + if _path_is_within(link, resolved): + return f"Active process PID {pid} holds open fd inside {resolved}" + + if check_lsof: + try: + proc = subprocess.run( + ["lsof", "+D", resolved], + capture_output=True, + text=True, + timeout=10, + check=False, + ) + if proc.stdout.strip(): + return f"lsof reports open file handles under {resolved}" + except (OSError, subprocess.SubprocessError): + pass + return None + + +def _lease_dirs_for_target(target: Path, repo_root: Path | None) -> list[Path]: + candidates: list[Path] = [] + for base in (repo_root, target): + if base is not None: + ld = base / ".subactor" / "leases" + if ld.is_dir() and ld not in candidates: + candidates.append(ld) + if target.parent.name == ".worktrees": + primary_ld = target.parent.parent / ".subactor" / "leases" + if primary_ld.is_dir() and primary_ld not in candidates: + candidates.append(primary_ld) + return candidates + + +def _check_active_lease_veto( + target: Path, *, repo_root: Path | None = None +) -> str | None: + """Hard veto 2: active or unreadable/foreign lease in .subactor/leases/*.json.""" + wt_name = target.name if target.parent.name == ".worktrees" else None + for lease_dir in _lease_dirs_for_target(target, repo_root): + try: + lease_files = sorted(lease_dir.glob("*.json")) + except OSError: + continue + for lf in lease_files: + if lf.is_symlink(): + return f"Symlinked lease file {lf.name} requires HOLD_PROTECTED" + if wt_name is not None and lf.stem != wt_name: + continue + try: + data = json.loads(lf.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + return f"Unreadable/foreign lease file {lf.name}" + if not isinstance(data, dict): + return f"Malformed lease file {lf.name}" + phase = data.get("phase") + if phase in ACTIVE_LEASE_PHASES: + owner = data.get("ownerActor") or data.get("owner") or "unknown" + return f"Active lease {lf.name} (phase={phase}, owner={owner})" + return None + + +def _check_open_pr_or_unmerged_veto( + target: Path, + *, + repo_root: Path | None = None, + is_git: bool = False, + open_pr_checker: Callable[[Path], bool] | None = None, +) -> str | None: + """Hard veto 3: open PRs or unmerged commits against default branch.""" + if open_pr_checker is not None: + try: + if open_pr_checker(target): + return "Target branch has an open pull request" + except Exception: + return "Open PR check failed (fail-closed HOLD_PROTECTED)" + + for lease_dir in _lease_dirs_for_target(target, repo_root): + try: + lease_files = sorted(lease_dir.glob("*.json")) + except OSError: + continue + for lf in lease_files: + try: + data = json.loads(lf.read_text(encoding="utf-8")) + except (OSError, UnicodeDecodeError, json.JSONDecodeError): + continue + if not isinstance(data, dict): + continue + pr = data.get("pullRequest") + if isinstance(pr, dict): + pr_state = str(pr.get("state", "open")).lower() + if pr_state not in {"merged", "closed"}: + return f"Open PR recorded in lease {lf.name}" + elif isinstance(pr, (int, str)) and pr: + return f"PR reference recorded in lease {lf.name}" + + if is_git: + default_ref = None + for ref in _DEFAULT_BRANCH_REFS: + chk = _run_git(target, "rev-parse", "--verify", "--quiet", ref) + if chk is not None and chk.returncode == 0: + default_ref = ref + break + if default_ref is not None: + cnt = _run_git(target, "rev-list", "--count", f"{default_ref}..HEAD") + if cnt is not None and cnt.returncode == 0: + try: + ahead = int(cnt.stdout.strip() or "0") + except ValueError: + ahead = 0 + if ahead > 0: + return f"Branch has {ahead} unmerged commit(s) ahead of {default_ref}" + return None + + +def _check_dirty_or_stash_veto(target: Path, *, is_git: bool = False) -> str | None: + """Hard veto 4: dirty working tree or stashes.""" + if not is_git: + return None + status = _run_git(target, "status", "--porcelain") + if status is not None and status.returncode == 0 and status.stdout.strip(): + return "Dirty working tree (uncommitted changes or untracked files)" + stash = _run_git(target, "stash", "list") + if stash is not None and stash.returncode == 0 and stash.stdout.strip(): + return "Repository has unapplied Git stashes" + return None + + +def _check_unpushed_refs_veto(target: Path, *, is_git: bool = False) -> str | None: + """Hard veto 5: unpushed refs or branches ahead of upstream.""" + if not is_git: + return None + ahead_proc = _run_git(target, "rev-list", "--count", "@{u}..HEAD") + if ahead_proc is not None and ahead_proc.returncode == 0: + try: + ahead = int(ahead_proc.stdout.strip() or "0") + except ValueError: + ahead = 0 + if ahead > 0: + return f"Branch has {ahead} unpushed commit(s) ahead of upstream" + return None + + remotes = _run_git(target, "remote") + if remotes is not None and remotes.returncode == 0 and remotes.stdout.strip(): + head_cnt = _run_git(target, "rev-list", "--count", "HEAD") + if head_cnt is not None and head_cnt.returncode == 0: + try: + commits = int(head_cnt.stdout.strip() or "0") + except ValueError: + commits = 0 + if commits > 0: + return "Branch has commits with no configured upstream tracking ref" + return None + + +def _check_worktree_or_ide_veto( + target: Path, *, is_git: bool = False, is_directory_cleanup: bool = False +) -> str | None: + """Hard veto 6: active linked worktree, primary checkout, or IDE ownership.""" + for marker in _IDE_OWNERSHIP_MARKERS: + if (target / marker).exists(): + return f"IDE ownership marker present ({marker})" + + git_entry = target / ".git" + if git_entry.is_file(): + return "Target is an active linked Git worktree" + + if is_git: + wt_list = _run_git(target, "worktree", "list", "--porcelain") + if wt_list is not None and wt_list.returncode == 0: + wt_count = sum( + 1 for line in wt_list.stdout.splitlines() if line.startswith("worktree ") + ) + if wt_count > 1: + return f"Primary checkout owns {wt_count - 1} active linked worktree(s)" + if is_directory_cleanup and git_entry.is_dir(): + return "Target is a primary Git checkout" + return None + + +def evaluate_cleanup_vetos( + target: Path, + *, + repo_root: Path | None = None, + is_directory_cleanup: bool = False, + check_lsof: bool = False, + open_pr_checker: Callable[[Path], bool] | None = None, +) -> CleanupVetoReport: + """Evaluate all 6 canonical wellmanifest/git-lifecycle hard vetos for ``target``. + + Any triggered veto forces ``HOLD_PROTECTED`` so callers never propose unsafe + directory or worktree deletion. + """ + is_git = _is_real_git_worktree(target) + checks: tuple[tuple[str, str | None], ...] = ( + (VETO_ACTIVE_PROCESS, _check_active_process_veto(target, check_lsof=check_lsof)), + (VETO_ACTIVE_LEASE, _check_active_lease_veto(target, repo_root=repo_root)), + ( + VETO_OPEN_PR_OR_UNMERGED, + _check_open_pr_or_unmerged_veto( + target, + repo_root=repo_root, + is_git=is_git, + open_pr_checker=open_pr_checker, + ), + ), + (VETO_DIRTY_OR_STASH, _check_dirty_or_stash_veto(target, is_git=is_git)), + (VETO_UNPUSHED_REFS, _check_unpushed_refs_veto(target, is_git=is_git)), + ( + VETO_WORKTREE_OR_IDE_OWNERSHIP, + _check_worktree_or_ide_veto( + target, is_git=is_git, is_directory_cleanup=is_directory_cleanup + ), + ), + ) + + codes: list[str] = [] + reasons: list[str] = [] + for code, reason in checks: + if reason is not None: + codes.append(code) + reasons.append(reason) + + verdict = VERDICT_HOLD_PROTECTED if codes else VERDICT_ALLOW + return CleanupVetoReport( + target=str(target), + verdict=verdict, + veto_codes=tuple(codes), + reasons=tuple(reasons), + ) + + def scan_project_artifacts( project_root: Path, threshold_mb: float = 50, stale_days: int = 7, + *, + enforce_vetos: bool = True, + include_protected: bool = False, + open_pr_checker: Callable[[Path], bool] | None = None, ) -> list[ProjectArtifact]: """Find removable artifacts directly under a single project root.""" + veto_report: CleanupVetoReport | None = None + if enforce_vetos: + veto_report = evaluate_cleanup_vetos( + project_root, open_pr_checker=open_pr_checker + ) + if veto_report.protected and not include_protected: + return [] + artifacts: list[ProjectArtifact] = [] try: entries = os.listdir(project_root) @@ -306,6 +649,28 @@ def scan_project_artifacts( else: is_stale = False + if veto_report is not None and veto_report.protected: + artifacts.append( + ProjectArtifact( + project_name=project_root.name, + project_path=str(project_root), + artifact_name=entry, + artifact_path=str(artifact_path), + size_mb=round(size_mb, 2), + size_gb=round(size_mb / 1024, 3), + description=description, + ecosystem=ecosystem, + risk_level="protected", + days_since_modified=days, + stale=False, + cleanup_command="", + project_has_recent_activity=bool(has_recent_activity), + verdict=VERDICT_HOLD_PROTECTED, + veto_codes=veto_report.veto_codes, + ) + ) + continue + artifacts.append( ProjectArtifact( project_name=project_root.name, diff --git a/project/ticket-184/README.md b/project/ticket-184/README.md new file mode 100644 index 0000000..9a7a04e --- /dev/null +++ b/project/ticket-184/README.md @@ -0,0 +1,33 @@ +# Ticket 184: Enforce wellmanifest git-lifecycle 6 hard vetos in project_scanner + +- **ID**: ticket-184 +- **Owner**: agent:antigravity (SESSION_EXECUTION_AUTHORIZATION from user request) +- **Status**: IN_PROGRESS +- **Workflow state**: EDIT +- **Created**: 2026-11-23 +- **Issue**: semcod/fixos#235 + +## Goal and scope + +Enforce the 6 canonical `wellmanifest/git-lifecycle` hard vetos in +`fixos/diagnostics/project_scanner.py` before proposing directory/worktree +cleanup candidates so protected workspaces always resolve to `HOLD_PROTECTED` +and never emit unsafe deletion commands: + +1. Active processes (`/proc/*/cwd`, `/proc/*/fd`, or `lsof` inside target) +2. Active leases (`.subactor/leases/*.json` in active or unreadable/foreign state) +3. Open PRs / unmerged commits (unmerged vs default branch or open PR metadata) +4. Dirty working tree or stashes (`git status --porcelain` / `git stash list`) +5. Unpushed refs / ahead branches (`git rev-list --count @{u}..HEAD` / local-only branch) +6. Active linked worktree / primary checkout / IDE ownership (linked worktrees, primary checkout owning linked worktrees, or IDE lock/session) + +## Acceptance criteria + +- [x] AC-01: `evaluate_cleanup_vetos` enforces all 6 hard vetos and returns `HOLD_PROTECTED` with structured veto codes and reasons whenever any veto fires. +- [x] AC-02: `scan_project_artifacts` enforces the 6 hard vetos by default and never proposes unsafe `rm -rf` deletion candidates for protected repos/worktrees. +- [x] AC-03: Unit tests in `tests/unit/test_project_scanner.py` verify each of the 6 hard vetos forces `HOLD_PROTECTED` and blocks unsafe deletion proposals. + +## Tracking boundary + +This directory contains the minimal reviewed intent. Optional participant prose +and raw command logs are not required delivery output. diff --git a/project/ticket-184/intent.json b/project/ticket-184/intent.json new file mode 100644 index 0000000..5977e2d --- /dev/null +++ b/project/ticket-184/intent.json @@ -0,0 +1,76 @@ +{ + "schema": "new-project.intent/v3", + "ticket": "ticket-184", + "summary": "Enforce wellmanifest git-lifecycle 6 hard vetos in project_scanner", + "workstream": "application", + "classification": { + "kind": "SERVICE", + "priority": "P1", + "origin": "requested" + }, + "allowedPaths": [ + "project/ticket-184/**", + "TODO.md", + "project/TICKETS.md", + "fixos/diagnostics/project_scanner.py", + "tests/unit/test_project_scanner.py" + ], + "forbiddenPaths": [ + "project/ticket-*/user-*.md" + ], + "stacks": [], + "dependsOn": [], + "conflictsWith": [], + "integrationTicket": null, + "delivery": { + "targetBranch": "main", + "acceptedBaseSha": "ed56842e3f4e78055629df7d42a10648be4eba75", + "outcome": "Enforce all 6 canonical wellmanifest/git-lifecycle hard vetos in fixos/diagnostics/project_scanner.py so protected repos and worktrees resolve to HOLD_PROTECTED and never emit unsafe deletion candidates.", + "complexity": "S", + "estimatedMinutes": 25, + "budgets": { + "maxImplementationFiles": 2, + "maxAffectedComponents": 1, + "maxPublicInterfaceChanges": 1, + "maxRuntimeDependencies": 0 + }, + "runtimeDependencies": [], + "nonGoals": [ + "Modifying fixos/cli/fix_cmd.py or any file reserved by active foreign leases." + ], + "architecture": { + "status": "accepted", + "decision": "Add CleanupVetoReport and evaluate_cleanup_vetos covering active processes, active leases, open PRs/unmerged commits, dirty/stash state, unpushed refs, and linked worktree/primary/IDE ownership in fixos/diagnostics/project_scanner.py, enforced by default in scan_project_artifacts.", + "components": [ + { + "name": "project_scanner hard vetos", + "paths": [ + "fixos/diagnostics/project_scanner.py", + "tests/unit/test_project_scanner.py" + ] + } + ], + "responsibilityChanges": false, + "interfaceChanges": [ + "Add CleanupVetoReport, evaluate_cleanup_vetos, and optional enforce_vetos/include_protected/open_pr_checker parameters to scan_project_artifacts" + ], + "dataChanges": [], + "ui": { + "impact": "none", + "states": [], + "evidence": [] + }, + "rollback": "Revert the commit touching fixos/diagnostics/project_scanner.py and tests/unit/test_project_scanner.py." + }, + "validation": [ + { + "criterion": "AC-01", + "commands": [ + "python -m pytest -q tests/unit/test_project_scanner.py tests/unit/test_venv_cleanup.py", + "./project/governance-check.sh" + ], + "evidence": "All 6 canonical hard vetos force HOLD_PROTECTED and suppress unsafe deletion proposals in unit tests while keeping existing scanner tests passing." + } + ] + } +} diff --git a/tests/unit/test_project_scanner.py b/tests/unit/test_project_scanner.py index ccd77bb..8e9b330 100644 --- a/tests/unit/test_project_scanner.py +++ b/tests/unit/test_project_scanner.py @@ -615,3 +615,240 @@ def test_active_git_repo_with_old_venv_is_not_stale(self, tmp_path, monkeypatch) assert artifacts[0].stale is False +class TestGitLifecycleHardVetos: + """Verify all 6 canonical wellmanifest/git-lifecycle hard vetos force HOLD_PROTECTED.""" + + @staticmethod + def _init_real_git_repo(repo_dir, *, with_remote=False, bare_dir=None): + import subprocess + + repo_dir.mkdir(parents=True, exist_ok=True) + env = { + **os.environ, + "GIT_AUTHOR_NAME": "Test", + "GIT_AUTHOR_EMAIL": "test@example.com", + "GIT_COMMITTER_NAME": "Test", + "GIT_COMMITTER_EMAIL": "test@example.com", + } + subprocess.run( + ["git", "init", "-b", "main", str(repo_dir)], + check=True, + capture_output=True, + env=env, + ) + (repo_dir / "README.md").write_text("hello\n", encoding="utf-8") + subprocess.run( + ["git", "-C", str(repo_dir), "add", "README.md"], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo_dir), "commit", "-m", "init"], + check=True, + capture_output=True, + env=env, + ) + if with_remote and bare_dir is not None: + subprocess.run( + ["git", "init", "--bare", str(bare_dir)], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo_dir), "remote", "add", "origin", str(bare_dir)], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo_dir), "push", "-u", "origin", "main"], + check=True, + capture_output=True, + env=env, + ) + return env + + @staticmethod + def _add_fake_venv(repo_dir): + venv = repo_dir / ".venv" + venv.mkdir(exist_ok=True) + (venv / "pyvenv.cfg").write_text("home = /usr/bin\n", encoding="utf-8") + return venv + + def test_veto_1_active_process_forces_hold_protected(self, tmp_path, monkeypatch): + proj = _make_git_project(tmp_path, "active_proc_repo") + self._add_fake_venv(proj) + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + monkeypatch.setattr( + ps, + "_check_active_process_veto", + lambda target, check_lsof=False: f"Active process PID 99999 in {target}", + ) + + report = ps.evaluate_cleanup_vetos(proj) + assert report.verdict == ps.VERDICT_HOLD_PROTECTED + assert report.protected is True + assert ps.VETO_ACTIVE_PROCESS in report.veto_codes + assert ps.scan_project_artifacts(proj, threshold_mb=1) == [] + + protected = ps.scan_project_artifacts(proj, threshold_mb=1, include_protected=True) + assert len(protected) == 1 + assert protected[0].verdict == ps.VERDICT_HOLD_PROTECTED + assert protected[0].cleanup_command == "" + + def test_veto_2_active_lease_forces_hold_protected(self, tmp_path, monkeypatch): + import json + + proj = _make_git_project(tmp_path, "leased_repo") + self._add_fake_venv(proj) + lease_dir = proj / ".subactor" / "leases" + lease_dir.mkdir(parents=True) + (lease_dir / "ticket-001--demo.json").write_text( + json.dumps({"ticketId": "ticket-001", "phase": "claimed", "ownerActor": "agent:codex"}), + encoding="utf-8", + ) + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + + report = ps.evaluate_cleanup_vetos(proj) + assert report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_ACTIVE_LEASE in report.veto_codes + assert ps.scan_project_artifacts(proj, threshold_mb=1) == [] + + def test_veto_3_unmerged_commits_and_open_pr_force_hold_protected(self, tmp_path, monkeypatch): + import subprocess + + repo = tmp_path / "unmerged_repo" + env = self._init_real_git_repo(repo) + self._add_fake_venv(repo) + subprocess.run( + ["git", "-C", str(repo), "checkout", "-b", "feat/unmerged"], + check=True, + capture_output=True, + env=env, + ) + (repo / "feature.txt").write_text("wip\n", encoding="utf-8") + subprocess.run( + ["git", "-C", str(repo), "add", "feature.txt"], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo), "commit", "-m", "unmerged feature"], + check=True, + capture_output=True, + env=env, + ) + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + + report = ps.evaluate_cleanup_vetos(repo) + assert report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_OPEN_PR_OR_UNMERGED in report.veto_codes + assert ps.scan_project_artifacts(repo, threshold_mb=1) == [] + + # Also verify explicit open_pr_checker forces HOLD_PROTECTED on a clean repo + clean_proj = _make_git_project(tmp_path, "open_pr_repo") + self._add_fake_venv(clean_proj) + pr_report = ps.evaluate_cleanup_vetos(clean_proj, open_pr_checker=lambda _: True) + assert pr_report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_OPEN_PR_OR_UNMERGED in pr_report.veto_codes + assert ps.scan_project_artifacts(clean_proj, threshold_mb=1, open_pr_checker=lambda _: True) == [] + + def test_veto_4_dirty_tree_and_stash_force_hold_protected(self, tmp_path, monkeypatch): + import subprocess + + repo = tmp_path / "dirty_repo" + env = self._init_real_git_repo(repo) + self._add_fake_venv(repo) + (repo / "README.md").write_text("modified\n", encoding="utf-8") + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + + report_dirty = ps.evaluate_cleanup_vetos(repo) + assert report_dirty.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_DIRTY_OR_STASH in report_dirty.veto_codes + assert ps.scan_project_artifacts(repo, threshold_mb=1) == [] + + # Stash the change -> tree is clean, stash list is non-empty -> still HOLD_PROTECTED + subprocess.run( + ["git", "-C", str(repo), "stash", "push", "-m", "saved wip"], + check=True, + capture_output=True, + env=env, + ) + report_stash = ps.evaluate_cleanup_vetos(repo) + assert report_stash.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_DIRTY_OR_STASH in report_stash.veto_codes + assert ps.scan_project_artifacts(repo, threshold_mb=1) == [] + + def test_veto_5_unpushed_refs_force_hold_protected(self, tmp_path, monkeypatch): + import subprocess + + bare = tmp_path / "remote.git" + repo = tmp_path / "unpushed_repo" + env = self._init_real_git_repo(repo, with_remote=True, bare_dir=bare) + self._add_fake_venv(repo) + (repo / "local.txt").write_text("unpushed\n", encoding="utf-8") + subprocess.run( + ["git", "-C", str(repo), "add", "local.txt"], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo), "commit", "-m", "local ahead"], + check=True, + capture_output=True, + env=env, + ) + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + + report = ps.evaluate_cleanup_vetos(repo) + assert report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_UNPUSHED_REFS in report.veto_codes + assert ps.scan_project_artifacts(repo, threshold_mb=1) == [] + + def test_veto_6_linked_worktree_primary_and_ide_force_hold_protected( + self, tmp_path, monkeypatch + ): + import subprocess + + bare = tmp_path / "remote_wt.git" + primary = tmp_path / "primary_repo" + env = self._init_real_git_repo(primary, with_remote=True, bare_dir=bare) + self._add_fake_venv(primary) + wt_path = primary / ".worktrees" / "ticket-999--demo" + subprocess.run( + ["git", "-C", str(primary), "worktree", "add", "-b", "ticket/999-demo", str(wt_path)], + check=True, + capture_output=True, + env=env, + ) + self._add_fake_venv(wt_path) + monkeypatch.setattr(ps, "_get_dir_size_mb", lambda p: 200.0) + + # Linked worktree must be HOLD_PROTECTED + wt_report = ps.evaluate_cleanup_vetos(wt_path) + assert wt_report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_WORKTREE_OR_IDE_OWNERSHIP in wt_report.veto_codes + assert ps.scan_project_artifacts(wt_path, threshold_mb=1) == [] + + # Primary checkout owning linked worktrees must be HOLD_PROTECTED + primary_report = ps.evaluate_cleanup_vetos(primary) + assert primary_report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_WORKTREE_OR_IDE_OWNERSHIP in primary_report.veto_codes + assert ps.scan_project_artifacts(primary, threshold_mb=1) == [] + + # IDE ownership marker must force HOLD_PROTECTED + ide_proj = _make_git_project(tmp_path, "ide_repo") + self._add_fake_venv(ide_proj) + (ide_proj / ".idea").mkdir() + (ide_proj / ".idea" / ".lock").write_text("locked\n", encoding="utf-8") + ide_report = ps.evaluate_cleanup_vetos(ide_proj) + assert ide_report.verdict == ps.VERDICT_HOLD_PROTECTED + assert ps.VETO_WORKTREE_OR_IDE_OWNERSHIP in ide_report.veto_codes + assert ps.scan_project_artifacts(ide_proj, threshold_mb=1) == [] + + + From 3b80cde71b66ac091b6db0ac2bf0d346f9a1d8bd Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Mon, 23 Nov 2026 15:42:03 +0100 Subject: [PATCH 2/3] chore(tickets): register ticket-184 in project/TICKETS.md (ticket-184) --- project/TICKETS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/project/TICKETS.md b/project/TICKETS.md index 0373c9a..daaf70d 100644 --- a/project/TICKETS.md +++ b/project/TICKETS.md @@ -179,4 +179,5 @@ This file indexes governance tickets without taking ownership of | **ticket-181** | [`README.md`](./ticket-181/README.md) | - | - | - | - | - | | **ticket-182** | [`README.md`](./ticket-182/README.md) | - | - | - | - | - | | **ticket-183** | [`README.md`](./ticket-183/README.md) | - | - | - | - | - | +| **ticket-184** | [`README.md`](./ticket-184/README.md) | - | - | - | - | - | From 7c9f02b52fb58d54a01164c582d21dbd3751a265 Mon Sep 17 00:00:00 2001 From: Tom Softreck Date: Mon, 23 Nov 2026 15:51:14 +0100 Subject: [PATCH 3/3] style(project-scanner): avoid blind Exception catch for ruff BLE001 (ticket-184) --- fixos/diagnostics/project_scanner.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/fixos/diagnostics/project_scanner.py b/fixos/diagnostics/project_scanner.py index fea7ef7..9cc05f1 100644 --- a/fixos/diagnostics/project_scanner.py +++ b/fixos/diagnostics/project_scanner.py @@ -438,7 +438,7 @@ def _check_open_pr_or_unmerged_veto( try: if open_pr_checker(target): return "Target branch has an open pull request" - except Exception: + except (OSError, RuntimeError, ValueError, subprocess.SubprocessError): return "Open PR check failed (fail-closed HOLD_PROTECTED)" for lease_dir in _lease_dirs_for_target(target, repo_root):