From 1d35857ecc897e2d88a58c6d32668b5a8e1d8a7b Mon Sep 17 00:00:00 2001 From: Test Date: Tue, 13 Oct 2026 08:11:58 -0500 Subject: [PATCH] feat(provenance): implement two-axis inspection engine and bounded upstream resolver - Implement scripts/provenance.py evaluating local deployment checkout state independently from upstream software provenance. - Add bounded git ls-remote provenance resolver with 10s timeout to prevent hanging on unresponsive remotes during --fetch. - Add 10 unit tests in tests/unit/test_provenance.py covering clean/dirty detection, synced vs update-available states, timeout handling, and unreachable remotes. - Include git in test-suite nativeBuildInputs in flake.nix for hermetic sandbox execution. - Update todo.txt marking Tasks 3, 4, & 5 of Milestone P3 completed. --- flake.nix | 1 + scripts/provenance.py | 330 ++++++++++++++++++++++++++++++++++ tests/unit/test_provenance.py | 195 ++++++++++++++++++++ todo.txt | 6 +- 4 files changed, 529 insertions(+), 3 deletions(-) create mode 100644 scripts/provenance.py create mode 100644 tests/unit/test_provenance.py diff --git a/flake.nix b/flake.nix index b78b1f0..5cef7d8 100644 --- a/flake.nix +++ b/flake.nix @@ -43,6 +43,7 @@ checks.${system} = { test-suite = pkgs.runCommand "core-tests" { nativeBuildInputs = with pkgs; [ + git python3 python3Packages.pytest python3Packages.pyyaml diff --git a/scripts/provenance.py b/scripts/provenance.py new file mode 100644 index 0000000..ae1602a --- /dev/null +++ b/scripts/provenance.py @@ -0,0 +1,330 @@ +""" +provenance.py — Two-Axis Inspection & Upstream Provenance Resolver + +Evaluates workload health along two independent axes: +1. Local Deployment Axis: Local checkout cleanliness (* Dirty vs. ✓ Clean), branch, commit, and container runtime state. +2. Upstream Provenance Axis: Upstream git repository state resolved via bounded `git ls-remote` (10s timeout). +""" + +from __future__ import annotations + +import os +import subprocess +from dataclasses import dataclass +from enum import Enum +from pathlib import Path + +from core_manifest import Manifest, RefType, SourceConfig + + +class ProvenanceStatus(str, Enum): + """Evaluation result of local state vs. upstream software provenance.""" + SYNCED = "✓ Synced" + UPDATE_AVAILABLE = "↓ Update Available" + IMAGE_ONLY = "— Image-Only (Class B)" + DIRTY = "* Dirty" + UNREACHABLE = "⚠ Unreachable" + TIMEOUT = "⏱ Timed Out (10s)" + UNKNOWN = "— Not Checked" + NOT_CLONED = "✕ Missing Checkout" + + +@dataclass +class CheckoutStatus: + """Axis 1: Local deployment checkout state.""" + is_git: bool + is_dirty: bool + branch: str + commit_sha: str + status_label: str + + def to_dict(self) -> dict[str, str | bool]: + return { + "is_git": self.is_git, + "is_dirty": self.is_dirty, + "branch": self.branch, + "commit_sha": self.commit_sha, + "status_label": self.status_label, + } + + +@dataclass +class UpstreamProvenance: + """Axis 2: Upstream software provenance state.""" + status: ProvenanceStatus + remote_sha: str = "" + target_ref: str = "" + message: str = "" + + def to_dict(self) -> dict[str, str]: + return { + "status": self.status.value, + "remote_sha": self.remote_sha, + "target_ref": self.target_ref, + "message": self.message, + } + + +@dataclass +class TwoAxisStatus: + """Unified inspection combining local deployment and upstream provenance.""" + app_name: str + checkout: CheckoutStatus + provenance: UpstreamProvenance + docker_status: str + image_revision: str | None = None + + def to_dict(self) -> dict[str, object]: + return { + "app_name": self.app_name, + "checkout": self.checkout.to_dict(), + "provenance": self.provenance.to_dict(), + "docker_status": self.docker_status, + "image_revision": self.image_revision, + } + + +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. + """ + path = Path(dir_path) + git_dir = path / ".git" + if not git_dir.exists(): + return CheckoutStatus( + is_git=False, + is_dirty=False, + branch="", + commit_sha="", + status_label="— No Git Repo", + ) + + # 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 + is_dirty = False + try: + status_res = subprocess.run( + ["git", "-C", str(path), "status", "--porcelain"], + capture_output=True, + text=True, + check=False, + timeout=5.0, + env=git_env, + ) + if status_res.returncode == 0 and status_res.stdout.strip(): + is_dirty = True + except (subprocess.SubprocessError, OSError): + is_dirty = False + + # 2. Get active branch + branch = "" + try: + branch_res = subprocess.run( + ["git", "-C", str(path), "rev-parse", "--abbrev-ref", "HEAD"], + capture_output=True, + text=True, + check=False, + timeout=5.0, + env=git_env, + ) + if branch_res.returncode == 0: + branch = branch_res.stdout.strip() + if branch == "HEAD": + # Detached HEAD, check describe + desc_res = subprocess.run( + ["git", "-C", str(path), "describe", "--tags", "--exact-match"], + capture_output=True, + text=True, + check=False, + timeout=5.0, + env=git_env, + ) + if desc_res.returncode == 0 and desc_res.stdout.strip(): + branch = desc_res.stdout.strip() + except (subprocess.SubprocessError, OSError): + branch = "unknown" + + # 3. Get commit SHA + commit_sha = "" + try: + sha_res = subprocess.run( + ["git", "-C", str(path), "rev-parse", "--short", "HEAD"], + capture_output=True, + text=True, + check=False, + timeout=5.0, + env=git_env, + ) + if sha_res.returncode == 0: + commit_sha = sha_res.stdout.strip() + except (subprocess.SubprocessError, OSError): + commit_sha = "" + + # 4. Format status label + state_symbol = "* Dirty" if is_dirty else "✓ Clean" + ref_desc = f"{branch}@{commit_sha}" if commit_sha else branch + status_label = f"{state_symbol} ({ref_desc})" if ref_desc else state_symbol + + return CheckoutStatus( + is_git=True, + is_dirty=is_dirty, + branch=branch, + commit_sha=commit_sha, + status_label=status_label, + ) + + +def resolve_upstream_provenance( + source: SourceConfig | None, + local_commit: str = "", + timeout: float = 10.0, +) -> UpstreamProvenance: + """ + Resolve upstream provenance via bounded `git ls-remote`. + Compares the declared upstream ref with the deployed local commit. + Bounded by a 10-second timeout to prevent hanging on unresponsive remotes. + """ + if source is None: + return UpstreamProvenance( + status=ProvenanceStatus.IMAGE_ONLY, + message="Class B workload deploys prebuilt container images directly", + ) + + target_ref = source.ref + remote_url = source.url + + # Commits pinned directly in manifest cannot be checked via ls-remote ref matching + if source.ref_type == RefType.COMMIT: + is_match = ( + local_commit and ( + source.ref.startswith(local_commit) or local_commit.startswith(source.ref) + ) + ) + status = ProvenanceStatus.SYNCED if is_match else ProvenanceStatus.UPDATE_AVAILABLE + return UpstreamProvenance( + status=status, + remote_sha=source.ref, + target_ref=source.ref[:7], + message="Pinned immutable commit SHA", + ) + + cmd = ["git", "ls-remote", "--exit-code", remote_url, target_ref] + + try: + proc = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + except subprocess.TimeoutExpired: + return UpstreamProvenance( + status=ProvenanceStatus.TIMEOUT, + target_ref=target_ref, + message=f"Upstream check timed out after {int(timeout)}s ({remote_url})", + ) + except (subprocess.SubprocessError, OSError) as e: + return UpstreamProvenance( + status=ProvenanceStatus.UNREACHABLE, + target_ref=target_ref, + message=f"Network error querying upstream: {e}", + ) + + if proc.returncode != 0: + # Check if ref was not found on remote (exit code 2 for git ls-remote) + err_msg = proc.stderr.strip() or f"Ref '{target_ref}' not found on remote." + return UpstreamProvenance( + status=ProvenanceStatus.UNREACHABLE, + target_ref=target_ref, + message=f"Failed to query remote ({remote_url}): {err_msg}", + ) + + # Parse remote SHA from ls-remote output (Format: \t) + remote_sha = "" + for line in proc.stdout.splitlines(): + parts = line.strip().split() + if len(parts) >= 2 and ( + parts[1] == target_ref or + parts[1] == f"refs/heads/{target_ref}" or + parts[1] == f"refs/tags/{target_ref}" or + parts[1] == f"refs/tags/{target_ref}^{{}}" + ): + remote_sha = parts[0] + # Peaked tags (^{}) take precedence over lightweight tag refs + if parts[1].endswith("^{}"): + break + + if not remote_sha and proc.stdout.strip(): + # Fallback: take first match SHA + remote_sha = proc.stdout.strip().split()[0] + + if not remote_sha: + return UpstreamProvenance( + status=ProvenanceStatus.UNREACHABLE, + target_ref=target_ref, + message=f"No matching ref found for '{target_ref}' at {remote_url}", + ) + + # Compare local commit with remote SHA + is_synced = False + if local_commit and (remote_sha.startswith(local_commit) or local_commit.startswith(remote_sha[:7])): + is_synced = True + + status = ProvenanceStatus.SYNCED if is_synced else ProvenanceStatus.UPDATE_AVAILABLE + short_remote = remote_sha[:7] + msg = f"Upstream at {short_remote}" if not is_synced else "Up to date with upstream" + + return UpstreamProvenance( + status=status, + remote_sha=remote_sha, + target_ref=target_ref, + message=msg, + ) + + +def inspect_workload_two_axis( + app_dir: Path | str, + manifest: Manifest, + fetch_upstream: bool = False, + docker_status: str = "⚪ Not Stack", + image_revision: str | None = None, + timeout: float = 10.0, +) -> TwoAxisStatus: + """ + Perform two-axis status inspection of a single workload. + """ + path = Path(app_dir) + + # Axis 1: Local Deployment Checkout + checkout = get_local_checkout_status(path) + + # Axis 2: Upstream Provenance + if manifest.is_class_b: + provenance = UpstreamProvenance( + status=ProvenanceStatus.IMAGE_ONLY, + message="Class B (Image-Only)", + ) + elif not fetch_upstream: + provenance = UpstreamProvenance( + status=ProvenanceStatus.UNKNOWN, + target_ref=manifest.source.ref if manifest.source else "", + message="Pass --fetch to query upstream repository", + ) + else: + provenance = resolve_upstream_provenance( + manifest.source, + local_commit=checkout.commit_sha, + timeout=timeout, + ) + + return TwoAxisStatus( + app_name=manifest.name, + checkout=checkout, + provenance=provenance, + docker_status=docker_status, + image_revision=image_revision, + ) diff --git a/tests/unit/test_provenance.py b/tests/unit/test_provenance.py new file mode 100644 index 0000000..640a8c9 --- /dev/null +++ b/tests/unit/test_provenance.py @@ -0,0 +1,195 @@ +""" +Unit test suite for scripts/provenance.py (Two-Axis Inspection & Provenance Resolver). +""" + +import os +import subprocess +import sys +from pathlib import Path +from unittest.mock import MagicMock, patch + +# Add scripts directory to path +CORE_ROOT = Path(__file__).resolve().parent.parent.parent +sys.path.insert(0, str(CORE_ROOT / "scripts")) + +from core_manifest import Manifest, RefType, SourceConfig, TransportScheme +from provenance import ( + ProvenanceStatus, + get_local_checkout_status, + inspect_workload_two_axis, + resolve_upstream_provenance, +) + + +def _clean_git_env() -> dict[str, str]: + env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")} + env["GIT_AUTHOR_NAME"] = "Test" + env["GIT_AUTHOR_EMAIL"] = "test@example.com" + env["GIT_COMMITTER_NAME"] = "Test" + env["GIT_COMMITTER_EMAIL"] = "test@example.com" + return env + + +def test_get_local_checkout_status_non_git(tmp_path: Path): + non_git = tmp_path / "app" + non_git.mkdir() + status = get_local_checkout_status(non_git) + assert status.is_git is False + assert status.is_dirty is False + assert "No Git Repo" in status.status_label + + +def test_get_local_checkout_status_clean_repo(tmp_path: Path): + app_dir = tmp_path / "git_app" + app_dir.mkdir() + env = _clean_git_env() + subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env) + (app_dir / "file.txt").write_text("hello", encoding="utf-8") + subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env) + + status = get_local_checkout_status(app_dir) + assert status.is_git is True + assert status.is_dirty is False + assert status.branch == "main" + assert status.commit_sha != "" + assert "✓ Clean" in status.status_label + + +def test_get_local_checkout_status_dirty_repo(tmp_path: Path): + app_dir = tmp_path / "git_dirty_app" + app_dir.mkdir() + env = _clean_git_env() + subprocess.run(["git", "-C", str(app_dir), "init", "-b", "main"], check=True, capture_output=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "config", "user.email", "test@example.com"], check=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "config", "user.name", "Test"], check=True, env=env) + (app_dir / "file.txt").write_text("hello", encoding="utf-8") + subprocess.run(["git", "-C", str(app_dir), "add", "file.txt"], check=True, env=env) + subprocess.run(["git", "-C", str(app_dir), "commit", "-m", "init"], check=True, capture_output=True, env=env) + + # Modify file to create dirty state + (app_dir / "file.txt").write_text("modified", encoding="utf-8") + + status = get_local_checkout_status(app_dir) + assert status.is_git is True + assert status.is_dirty is True + assert "* Dirty" in status.status_label + + +def test_resolve_upstream_provenance_image_only(): + prov = resolve_upstream_provenance(None) + assert prov.status == ProvenanceStatus.IMAGE_ONLY + + +def test_resolve_upstream_provenance_synced(): + source = SourceConfig( + url="https://git.roadtotech.me/kiskaadee/app.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ) + mock_sha = "abc1234567890abcdef1234567890abcdef12345" + mock_output = f"{mock_sha}\trefs/heads/main\n" + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0, stdout=mock_output) + prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0) + + assert prov.status == ProvenanceStatus.SYNCED + assert prov.remote_sha == mock_sha + assert "Up to date" in prov.message + # Verify 10s timeout was passed to subprocess.run + assert mock_run.call_args[1]["timeout"] == 10.0 + + +def test_resolve_upstream_provenance_update_available(): + source = SourceConfig( + url="https://git.roadtotech.me/kiskaadee/app.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ) + mock_sha = "fff9999999990abcdef1234567890abcdef12345" + mock_output = f"{mock_sha}\trefs/heads/main\n" + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=0, stdout=mock_output) + prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0) + + assert prov.status == ProvenanceStatus.UPDATE_AVAILABLE + assert prov.remote_sha == mock_sha + assert "Upstream at fff9999" in prov.message + + +def test_resolve_upstream_provenance_timeout(): + source = SourceConfig( + url="https://slow-remote.test/repo.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ) + + with patch("subprocess.run", side_effect=subprocess.TimeoutExpired(cmd=["git"], timeout=10.0)): + prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0) + + assert prov.status == ProvenanceStatus.TIMEOUT + assert "timed out after 10s" in prov.message + + +def test_resolve_upstream_provenance_unreachable(): + source = SourceConfig( + url="https://bad-remote.test/repo.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ) + + with patch("subprocess.run") as mock_run: + mock_run.return_value = MagicMock(returncode=128, stderr="fatal: remote error") + prov = resolve_upstream_provenance(source, local_commit="abc1234", timeout=10.0) + + assert prov.status == ProvenanceStatus.UNREACHABLE + assert "Failed to query remote" in prov.message + + +def test_resolve_upstream_provenance_pinned_commit(): + sha = "1234567890abcdef1234567890abcdef12345678" + source = SourceConfig( + url="https://git.roadtotech.me/app.git", + ref=sha, + ref_type=RefType.COMMIT, + transport=TransportScheme.HTTPS, + ) + # Matched local commit + prov = resolve_upstream_provenance(source, local_commit="1234567") + assert prov.status == ProvenanceStatus.SYNCED + + # Differing local commit + prov_diff = resolve_upstream_provenance(source, local_commit="9999999") + assert prov_diff.status == ProvenanceStatus.UPDATE_AVAILABLE + + +def test_inspect_workload_two_axis(tmp_path: Path): + manifest = Manifest( + name="test-app", + source=SourceConfig( + url="https://git.test/app.git", + ref="main", + ref_type=RefType.BRANCH, + transport=TransportScheme.HTTPS, + ), + ) + + # Without fetch_upstream: Axis 2 returns UNKNOWN + status_no_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=False) + assert status_no_fetch.provenance.status == ProvenanceStatus.UNKNOWN + assert "Pass --fetch" in status_no_fetch.provenance.message + + # With fetch_upstream: Axis 2 queries remote + with patch("provenance.resolve_upstream_provenance") as mock_resolve: + mock_resolve.return_value = MagicMock(status=ProvenanceStatus.SYNCED) + status_fetch = inspect_workload_two_axis(tmp_path, manifest, fetch_upstream=True) + assert status_fetch.provenance.status == ProvenanceStatus.SYNCED + mock_resolve.assert_called_once() diff --git a/todo.txt b/todo.txt index 94c2f58..d3ae77f 100644 --- a/todo.txt +++ b/todo.txt @@ -1,7 +1,7 @@ x 2026-10-13 (A) Create core_manifest.py schema and parser with strict transport validation (https, ssh, git) and ref classification in scripts/core_manifest.py +manifest @core x 2026-10-13 (A) Implement unit tests for core_manifest.py covering valid manifests, invalid URLs, and ref types in tests/unit/test_core_manifest.py +test @core -(B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl -(B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @appctl -(B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl +x 2026-10-13 (B) Implement two-axis inspection engine in appctl evaluating local checkout state independently from upstream provenance +provenance @appctl +x 2026-10-13 (B) Implement bounded git ls-remote provenance resolver with 10s timeout for appctl status --fetch +provenance @appctl +x 2026-10-13 (B) Add unit tests for provenance resolution and timeout handling with mocked network fixtures in tests/unit/test_provenance.py +test @appctl (C) Promote scripts/appctl_engine_v2.py to authoritative scripts/appctl_engine.py +engine @appctl (C) Verify full test suite and update CLI wrappers for appctl v2 engine promotion +test @appctl