From 2df95648d466c72db9f20e6b0f3d225959f29741 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Mon, 16 Nov 2026 14:03:59 -0500 Subject: [PATCH] feat(provenance,router): support hybrid ~/Workloads monorepo subpath inspection and git pull (#33) - Update provenance.get_local_checkout_status to check /.git first and fall back to /.git with subpath-scoped git status --porcelain -- / - Update OperationalRouter._op_workload_update via _resolve_git_context to target parent monorepo .git for status, pull --ff-only, and rev-parse when /.git is absent - Add real git init tests in test_provenance.py for monorepo subpath dirty-state isolation and standalone /.git precedence - Add router unit test in test_appctl_router.py verifying monorepo git pull and subpath status checks during workload.update --- scripts/appctl_router.py | 27 +++++++-- scripts/provenance.py | 24 +++++--- tests/unit/test_appctl_router.py | 63 +++++++++++++++++++++ tests/unit/test_provenance.py | 97 ++++++++++++++++++++++++++++++++ 4 files changed, 198 insertions(+), 13 deletions(-) diff --git a/scripts/appctl_router.py b/scripts/appctl_router.py index 50a9764..e22da0f 100644 --- a/scripts/appctl_router.py +++ b/scripts/appctl_router.py @@ -1021,6 +1021,15 @@ class OperationalRouter: "message": f"Workload '{app.name}' pulled and updated", } + @staticmethod + def _resolve_git_context(app_dir: Path) -> tuple[Path, str | None]: + """Resolve (git_root, subpath) supporting standalone /.git and parent monorepo .git.""" + if (app_dir / ".git").exists(): + return app_dir, None + if (app_dir.parent / ".git").exists(): + return app_dir.parent, f"{app_dir.name}/" + return app_dir, None + def _op_workload_update( self, request: OperationRequest, app: Any ) -> tuple[dict[str, Any], str | None]: @@ -1037,11 +1046,17 @@ class OperationalRouter: app_dir = Path(app.dir_path) is_core = self._is_core_target(app) container = self._target_container(app) + git_root, git_subpath = ( + (app_dir, None) if is_core else self._resolve_git_context(app_dir) + ) # 1. Clean working tree check + status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"] + if git_subpath is not None: + status_cmd.extend(["--", git_subpath]) code, status_out, _ = run_bounded_subprocess( - ["git", "-C", str(app_dir), "status", "--porcelain"], - cwd=app_dir, + status_cmd, + cwd=git_root, timeout=5.0, ) if code != 0 or status_out.strip(): @@ -1050,11 +1065,11 @@ class OperationalRouter: ) # 2. git pull --ff-only - pull_cmd = ["git", "-C", str(app_dir), "pull", "--ff-only"] + pull_cmd = ["git", "-C", str(git_root), "pull", "--ff-only"] if params.expected_branch: pull_cmd.extend(["origin", "--", params.expected_branch]) code, pull_out, pull_err = run_bounded_subprocess( - pull_cmd, cwd=app_dir, timeout=60.0 + pull_cmd, cwd=git_root, timeout=60.0 ) if code != 0: raise RouterExecutionError( @@ -1132,8 +1147,8 @@ class OperationalRouter: # 5. Extract current commit SHA _, sha_out, _ = run_bounded_subprocess( - ["git", "-C", str(app_dir), "rev-parse", "--short", "HEAD"], - cwd=app_dir, + ["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"], + cwd=git_root, timeout=5.0, ) commit_sha = sha_out.strip() or None diff --git a/scripts/provenance.py b/scripts/provenance.py index f9a700e..e521e23 100644 --- a/scripts/provenance.py +++ b/scripts/provenance.py @@ -92,10 +92,17 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: """ Inspect local git repository checkout state. Reports clean/dirty status, active branch/ref, and current commit SHA. + Supports standalone /.git checkouts (checked first) and + unified monorepo checkouts where .parent/.git exists. """ path = Path(dir_path) - git_dir = path / ".git" - if not git_dir.exists(): + subpath: str | None = None + if (path / ".git").exists(): + git_root = path + elif (path.parent / ".git").exists(): + git_root = path.parent + subpath = f"{path.name}/" + else: return CheckoutStatus( is_git=False, is_dirty=False, @@ -107,12 +114,15 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: # Clean git environment so calls are not polluted by outer hooks git_env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} - # 1. Check cleanliness + # 1. Check cleanliness (scoped to workload subpath in monorepo mode) is_dirty = False git_error: str | None = None + status_cmd = ["git", "-C", str(git_root), "status", "--porcelain"] + if subpath is not None: + status_cmd.extend(["--", subpath]) try: status_res = subprocess.run( - ["git", "-C", str(path), "status", "--porcelain"], + status_cmd, capture_output=True, text=True, check=False, @@ -132,7 +142,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: branch = "" try: branch_res = subprocess.run( - ["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"], + ["git", "-C", str(git_root), "rev-parse", "--abbrev-ref", "HEAD"], capture_output=True, text=True, check=False, @@ -144,7 +154,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: if branch == "HEAD": # Detached HEAD, check describe desc_res = subprocess.run( - ["git", "-C", str(path), "describe", "--tags", "--exact-match"], + ["git", "-C", str(git_root), "describe", "--tags", "--exact-match"], capture_output=True, text=True, check=False, @@ -160,7 +170,7 @@ def get_local_checkout_status(dir_path: Path | str) -> CheckoutStatus: commit_sha = "" try: sha_res = subprocess.run( - ["git", "-C", str(path), "rev-parse", "--short", "HEAD"], + ["git", "-C", str(git_root), "rev-parse", "--short", "HEAD"], capture_output=True, text=True, check=False, diff --git a/tests/unit/test_appctl_router.py b/tests/unit/test_appctl_router.py index de9bbb0..70ee7b1 100644 --- a/tests/unit/test_appctl_router.py +++ b/tests/unit/test_appctl_router.py @@ -1618,3 +1618,66 @@ def test_trigger_homepage_sync_acquires_homepage_sync_lock(tmp_path: Path, mock_ with patch("appctl_router.cmd_sync_homepage", side_effect=mock_sync): router._trigger_homepage_sync() assert lock_acquired is True + + +def test_operational_router_workload_update_pulls_monorepo_when_parent_git_exists( + tmp_path: Path, admin_principal: Principal, mock_workload_dir: Path +): + """Ensure workload.update targets parent monorepo .git when /.git is absent (#33).""" + monorepo_root = mock_workload_dir.parent + (monorepo_root / ".git").mkdir() + + router = OperationalRouter( + audit_logger=AuditLogger(tmp_path / "audit.jsonl"), + lock_manager=TargetLockManager(tmp_path / "locks"), + sites_dir=monorepo_root, + ) + req = OperationRequest.model_validate( + { + "operation": "workload.update", + "target": "snappymail", + "parameters": {"expected_branch": "main"}, + } + ) + + mock_app = MagicMock() + mock_app.name = "snappymail" + mock_app.dir_path = str(mock_workload_dir) + + executed: list[tuple[list[str], Path | None]] = [] + + def mock_subproc(cmd: list[str], **kwargs): + executed.append((cmd, kwargs.get("cwd"))) + if "status" in cmd: + return 0, "", "" + if "pull" in cmd: + return 0, "Updating 1111..2222\nFast-forward", "" + if "rev-parse" in cmd: + return 0, "beef123", "" + return 0, "success", "" + + with ( + patch("appctl_router.resolve_app", return_value=mock_app), + patch("appctl_router.run_bounded_subprocess", side_effect=mock_subproc), + patch("appctl_router.cmd_sync_homepage"), + ): + resp = router.dispatch(req, admin_principal) + assert resp.success is True + assert resp.result is not None + assert resp.result["commit_sha"] == "beef123" + + status_calls = [c for c, _ in executed if c[0] == "git" and "status" in c] + assert status_calls == [ + ["git", "-C", str(monorepo_root), "status", "--porcelain", "--", "snappymail/"] + ] + git_pull_calls = [(c, cwd) for c, cwd in executed if c[0] == "git" and "pull" in c] + assert git_pull_calls == [ + (["git", "-C", str(monorepo_root), "pull", "--ff-only", "origin", "--", "main"], monorepo_root) + ] + rev_parse_calls = [c for c, _ in executed if c[0] == "git" and "rev-parse" in c] + assert rev_parse_calls == [ + ["git", "-C", str(monorepo_root), "rev-parse", "--short", "HEAD"] + ] + # Compose commands still run in app_dir + compose_cwds = [cwd for c, cwd in executed if c[0] == "docker"] + assert compose_cwds and all(cwd == mock_workload_dir for cwd in compose_cwds) diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py index 458afad..8262ffa 100644 --- a/tests/unit/test_provenance.py +++ b/tests/unit/test_provenance.py @@ -266,3 +266,100 @@ def test_get_local_checkout_status_git_error(tmp_path: Path): assert status.is_dirty is False assert status.status_label == "⚠️ Git Error (exit 128)" + +def _init_git_repo(repo_dir: Path, branch: str = "main") -> None: + env = _clean_git_env() + subprocess.run( + ["git", "-C", str(repo_dir), "init", "-b", branch], + check=True, + capture_output=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo_dir), "config", "user.email", "test@example.com"], + check=True, + env=env, + ) + subprocess.run( + ["git", "-C", str(repo_dir), "config", "user.name", "Test"], + check=True, + env=env, + ) + + +def test_get_local_checkout_status_monorepo_subpath_isolation(tmp_path: Path): + """Ensure monorepo subpath inspection isolates dirty state per workload directory (#33).""" + workloads_dir = tmp_path / "Workloads" + app_a = workloads_dir / "app_a" + app_b = workloads_dir / "app_b" + app_a.mkdir(parents=True) + app_b.mkdir(parents=True) + _init_git_repo(workloads_dir, branch="main") + + (app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8") + (app_b / "app.yaml").write_text("name: app_b\n", encoding="utf-8") + + env = _clean_git_env() + subprocess.run(["git", "-C", str(workloads_dir), "add", "."], check=True, env=env) + subprocess.run( + ["git", "-C", str(workloads_dir), "commit", "-m", "init monorepo"], + check=True, + capture_output=True, + env=env, + ) + + # Dirty only app_b + (app_b / "app.yaml").write_text("name: app_b_dirty\n", encoding="utf-8") + (app_b / "untracked.txt").write_text("dirty\n", encoding="utf-8") + + status_a = get_local_checkout_status(app_a) + assert status_a.is_git is True + assert status_a.is_dirty is False + assert status_a.branch == "main" + assert status_a.commit_sha != "" + assert "✓ Clean" in status_a.status_label + + status_b = get_local_checkout_status(app_b) + assert status_b.is_git is True + assert status_b.is_dirty is True + assert status_b.branch == "main" + assert "* Dirty" in status_b.status_label + + +def test_get_local_checkout_status_hybrid_precedence_standalone_over_monorepo( + tmp_path: Path, +): + """Ensure standalone /.git takes precedence over parent monorepo .git (#33).""" + workloads_dir = tmp_path / "Workloads" + app_a = workloads_dir / "app_a" + app_a.mkdir(parents=True) + _init_git_repo(workloads_dir, branch="main") + + env = _clean_git_env() + (workloads_dir / "README.md").write_text("monorepo\n", encoding="utf-8") + subprocess.run( + ["git", "-C", str(workloads_dir), "add", "README.md"], check=True, env=env + ) + subprocess.run( + ["git", "-C", str(workloads_dir), "commit", "-m", "monorepo root"], + check=True, + capture_output=True, + env=env, + ) + + # Nested standalone .git inside app_a on a distinct branch + _init_git_repo(app_a, branch="standalone-branch") + (app_a / "app.yaml").write_text("name: app_a\n", encoding="utf-8") + subprocess.run(["git", "-C", str(app_a), "add", "app.yaml"], check=True, env=env) + subprocess.run( + ["git", "-C", str(app_a), "commit", "-m", "standalone commit"], + check=True, + capture_output=True, + env=env, + ) + + status_a = get_local_checkout_status(app_a) + assert status_a.is_git is True + assert status_a.is_dirty is False + assert status_a.branch == "standalone-branch" +