diff --git a/.release-please-manifest.json b/.release-please-manifest.json index f47357f55..8e8002a42 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,4 +1,4 @@ { - ".": "0.21.0", - "adk": "0.21.0" + ".": "0.22.0", + "adk": "0.22.0" } diff --git a/CHANGELOG.md b/CHANGELOG.md index 78871950d..11a7ee5e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,24 @@ * **tracing:** emit OTel metrics for async span queue depth, batch drain, and SGP export success/failure (HTTP status labels). Disable SDK-side recording with ``AGENTEX_TRACING_METRICS=0``. +## 0.22.0 (2026-07-29) + +Full Changelog: [agentex-client-v0.21.0...agentex-client-v0.22.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-client-v0.21.0...agentex-client-v0.22.0) + +### Features + +* **lib:** capture client-attested build provenance ([#454](https://github.com/scaleapi/scale-agentex-python/issues/454)) ([8964044](https://github.com/scaleapi/scale-agentex-python/commit/896404475a1e93955eabd562caa1670364335c29)) + + +### Bug Fixes + +* **lib:** default 'agentex agents build' to --no-cache so stale layers can't ship stale source ([#476](https://github.com/scaleapi/scale-agentex-python/issues/476)) ([632d82c](https://github.com/scaleapi/scale-agentex-python/commit/632d82c2e4eeb1f7113b575b8666ffd53a1ab2eb)) + + +### Refactors + +* **lib:** remove the dead build-info.json registration read-path ([#455](https://github.com/scaleapi/scale-agentex-python/issues/455)) ([2078f9f](https://github.com/scaleapi/scale-agentex-python/commit/2078f9fabb3099fa2d5d02f67ed5af50b8efbc09)) + ## 0.21.0 (2026-07-28) Full Changelog: [agentex-client-v0.20.0...agentex-client-v0.21.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-client-v0.20.0...agentex-client-v0.21.0) diff --git a/adk/CHANGELOG.md b/adk/CHANGELOG.md index 7fc13e59d..c702e50cb 100644 --- a/adk/CHANGELOG.md +++ b/adk/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## 0.22.0 (2026-07-29) + +Full Changelog: [agentex-sdk-v0.21.0...agentex-sdk-v0.22.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-sdk-v0.21.0...agentex-sdk-v0.22.0) + +### Chores + +* **agentex-sdk:** Synchronize agentex versions + ## 0.21.0 (2026-07-28) Full Changelog: [agentex-sdk-v0.20.0...agentex-sdk-v0.21.0](https://github.com/scaleapi/scale-agentex-python/compare/agentex-sdk-v0.20.0...agentex-sdk-v0.21.0) diff --git a/adk/pyproject.toml b/adk/pyproject.toml index 808e2945f..bc786195b 100644 --- a/adk/pyproject.toml +++ b/adk/pyproject.toml @@ -4,7 +4,7 @@ # (agentex/{__init__.py, _*.py, types/, resources/}) ships from the slim # sibling package `agentex-client` which is pinned as a runtime dep. name = "agentex-sdk" -version = "0.21.0" +version = "0.22.0" description = "Agent Development Kit (ADK) overlay for the Agentex API — FastACP server, Temporal workflows, LLM provider integrations, observability" license = "Apache-2.0" authors = [ diff --git a/pyproject.toml b/pyproject.toml index 6aa945921..f45a46cd6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,7 +3,7 @@ # overlay (formerly `src/agentex/lib/*`) now lives in `adk/` and ships # as the sibling `agentex-sdk` package — see `adk/pyproject.toml`. name = "agentex-client" -version = "0.21.0" +version = "0.22.0" description = "The official Python REST client for the Agentex API" dynamic = ["readme"] license = "Apache-2.0" diff --git a/src/agentex/_version.py b/src/agentex/_version.py index 9bc04e166..77712eefa 100644 --- a/src/agentex/_version.py +++ b/src/agentex/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. __title__ = "agentex" -__version__ = "0.21.0" # x-release-please-version +__version__ = "0.22.0" # x-release-please-version diff --git a/src/agentex/lib/cli/commands/agents.py b/src/agentex/lib/cli/commands/agents.py index c4b49a15e..801fda350 100644 --- a/src/agentex/lib/cli/commands/agents.py +++ b/src/agentex/lib/cli/commands/agents.py @@ -127,6 +127,13 @@ def build( None, help="Docker build argument in the format 'KEY=VALUE' (can be used multiple times)", ), + cache: bool = typer.Option( + False, + "--cache/--no-cache", + help="Whether to use the build cache. Defaults to off so a stale cached layer " + "can't silently ship source that no longer matches the checkout (notably when " + "republishing a moving tag like ':latest'). Pass --cache to opt back in.", + ), ): """ Build an agent image locally from the given manifest. @@ -155,6 +162,7 @@ def build( secret=secret or "", # Provide default empty string tag=tag or "latest", # Provide default build_args=build_arg or [], # Provide default empty list + cache=cache, ) if image_url: typer.echo(f"Successfully built image: {image_url}") diff --git a/src/agentex/lib/cli/handlers/agent_handlers.py b/src/agentex/lib/cli/handlers/agent_handlers.py index 1f2ccc7ef..322154b92 100644 --- a/src/agentex/lib/cli/handlers/agent_handlers.py +++ b/src/agentex/lib/cli/handlers/agent_handlers.py @@ -39,6 +39,7 @@ def build_agent( secret: str | None = None, tag: str | None = None, build_args: list[str] | None = None, + cache: bool = False, ) -> str: """Build the agent locally and optionally push to registry @@ -49,6 +50,10 @@ def build_agent( secret: Docker build secret in format 'id=secret-id,src=path-to-secret-file' tag: Image tag to use (defaults to 'latest') build_args: List of Docker build arguments in format 'KEY=VALUE' + cache: Whether to use the build cache. Defaults to False (passes --no-cache to + buildx) so a stale cached layer can't silently ship source that no longer + matches the checkout, notably when republishing a moving tag like ':latest'. + Pass True to opt back in for faster local rebuilds. Returns: The image URL @@ -85,7 +90,10 @@ def build_agent( "file": str(build_context.path / build_context.dockerfile_path), # type: ignore[operator] "tags": [image_name], "platforms": platforms, + "cache": cache, # cache=False -> `docker buildx build --no-cache` } + if not cache: + logger.info("Build cache disabled (--no-cache)") # Add Docker build args if provided if build_args: diff --git a/src/agentex/lib/environment_variables.py b/src/agentex/lib/environment_variables.py index 3113b78f4..4afae3e60 100644 --- a/src/agentex/lib/environment_variables.py +++ b/src/agentex/lib/environment_variables.py @@ -37,8 +37,6 @@ class EnvVarKeys(str, Enum): HEALTH_CHECK_PORT = "HEALTH_CHECK_PORT" # Auth Configuration AUTH_PRINCIPAL_B64 = "AUTH_PRINCIPAL_B64" - # Build Information - BUILD_INFO_PATH = "BUILD_INFO_PATH" AGENT_INPUT_TYPE = "AGENT_INPUT_TYPE" # Deployment AGENTEX_DEPLOYMENT_ID = "AGENTEX_DEPLOYMENT_ID" @@ -87,8 +85,6 @@ class EnvironmentVariables(BaseModel): HEALTH_CHECK_PORT: int = 80 # Auth Configuration AUTH_PRINCIPAL_B64: str | None = None - # Build Information - BUILD_INFO_PATH: str | None = None # Deployment AGENTEX_DEPLOYMENT_ID: str | None = None # Claude Agents SDK Configuration diff --git a/src/agentex/lib/sdk/config/agent_manifest.py b/src/agentex/lib/sdk/config/agent_manifest.py index fd743e635..c2fe03052 100644 --- a/src/agentex/lib/sdk/config/agent_manifest.py +++ b/src/agentex/lib/sdk/config/agent_manifest.py @@ -24,6 +24,7 @@ from agentex.lib.utils.io import load_yaml_file from agentex.lib.utils.logging import make_logger from agentex.config.agent_manifest import AgentManifest # noqa: F401 +from agentex.lib.utils.build_provenance import iter_context_files logger = make_logger(__name__) @@ -189,12 +190,11 @@ def zipped(root_path: Path | None = None) -> Iterator[IO[bytes]]: tar_buffer = io.BytesIO() + # Sorted, relpath-stable enumeration (shared with the content hash) so the + # archive's member order is deterministic across machines. with tarfile.open(fileobj=tar_buffer, mode="w:gz") as tar_file: - for path in Path(root_path).rglob( - "*" - ): # Recursively add files to the tar.gz - if path.is_file(): # Ensure that we're only adding files - tar_file.add(path, arcname=path.relative_to(root_path)) + for path in iter_context_files(Path(root_path)): + tar_file.add(path, arcname=path.relative_to(root_path)) tar_buffer.seek(0) # Reset the buffer position to the beginning yield tar_buffer diff --git a/src/agentex/lib/sdk/fastacp/fastacp.py b/src/agentex/lib/sdk/fastacp/fastacp.py index 42859793d..4a76c294e 100644 --- a/src/agentex/lib/sdk/fastacp/fastacp.py +++ b/src/agentex/lib/sdk/fastacp/fastacp.py @@ -1,9 +1,6 @@ from __future__ import annotations -import os -import inspect from typing import Any, Literal -from pathlib import Path from typing_extensions import deprecated from agentex.lib.types.fastacp import ( @@ -82,14 +79,6 @@ def create_agentic_acp(config: AgenticACPConfig, **kwargs) -> BaseACPServer: """ return FastACP.create_async_acp(config, **kwargs) - @staticmethod - def locate_build_info_path() -> None: - """If a build-info.json file is present, set the BUILD_INFO_PATH environment variable""" - acp_root = Path(inspect.stack()[2].filename).resolve().parents[0] - build_info_path = acp_root / "build-info.json" - if build_info_path.exists(): - os.environ["BUILD_INFO_PATH"] = str(build_info_path) - @staticmethod def create( acp_type: Literal["sync", "async", "agentic"], @@ -105,8 +94,6 @@ def create( **kwargs: Additional configuration parameters """ - FastACP.locate_build_info_path() - if acp_type == "sync": sync_config = config if isinstance(config, SyncACPConfig) else None instance = FastACP.create_sync_acp(sync_config, **kwargs) diff --git a/src/agentex/lib/utils/build_provenance.py b/src/agentex/lib/utils/build_provenance.py new file mode 100644 index 000000000..447980263 --- /dev/null +++ b/src/agentex/lib/utils/build_provenance.py @@ -0,0 +1,189 @@ +"""Capture client-attested source identity without failing agent builds.""" + +from __future__ import annotations + +import os +import stat +import hashlib +import subprocess +from typing import Optional +from pathlib import Path +from datetime import datetime, timezone +from dataclasses import dataclass + +from agentex.lib.utils.logging import make_logger + +logger = make_logger(__name__) + +_GIT_TIMEOUT_S = 5 +_HASH_CHUNK_BYTES = 1 << 20 + + +@dataclass(frozen=True) +class BuildProvenance: + """Source identity for one build; unavailable fields degrade to ``None``.""" + + repo: Optional[str] = None + commit: Optional[str] = None + ref: Optional[str] = None + subpath: Optional[str] = None + working_tree_hash: Optional[str] = None + dirty: Optional[bool] = None + author_name: Optional[str] = None + author_email: Optional[str] = None + build_timestamp: Optional[str] = None + + def source_fields(self) -> dict[str, object]: + """The ``source_*`` form fields for the cloud-build upload (None omitted).""" + fields = { + "source_repo": self.repo, + "source_commit": self.commit, + "source_ref": self.ref, + "source_subpath": self.subpath, + "working_tree_hash": self.working_tree_hash, + "source_dirty": self.dirty, + } + return {key: value for key, value in fields.items() if value is not None} + + def build_info(self) -> dict[str, object]: + """Return provenance using the runtime registration metadata field names.""" + info = { + "repo": self.repo, + "commit_hash": self.commit, + "branch_name": self.ref, + "subpath": self.subpath, + "working_tree_hash": self.working_tree_hash, + "dirty": self.dirty, + "author_name": self.author_name, + "author_email": self.author_email, + "build_timestamp": self.build_timestamp, + } + return {key: value for key, value in info.items() if value is not None} + + +def _git(repo_root: Path, *args: str) -> Optional[str]: + """Run a git command under ``repo_root``; return stripped stdout or None.""" + try: + proc = subprocess.run( + ("git", "-C", str(repo_root), *args), + capture_output=True, + text=True, + timeout=_GIT_TIMEOUT_S, + check=False, + ) + except (OSError, subprocess.SubprocessError): + return None + if proc.returncode != 0: + return None + return proc.stdout.strip() or None + + +def normalize_remote(url: Optional[str]) -> Optional[str]: + """Strip credentials and scheme from a remote, returning ``host/path``.""" + if not url: + return None + candidate = url.strip() + # scp-like syntax: git@host:org/repo(.git) — no scheme, host/path split on ':' + if "://" not in candidate and ":" in candidate and "/" not in candidate.split(":", 1)[0]: + candidate = candidate.split("@", 1)[-1].replace(":", "/", 1) + else: + if "://" in candidate: + candidate = candidate.split("://", 1)[1] + candidate = candidate.split("@", 1)[-1] + if candidate.endswith(".git"): + candidate = candidate[: -len(".git")] + candidate = candidate.strip("/") + if not candidate: + return None + host, slash, path = candidate.partition("/") + return f"{host.lower()}{slash}{path}" + + +def _sha256_file(path: Path) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + while chunk := handle.read(_HASH_CHUNK_BYTES): + digest.update(chunk) + return digest.hexdigest() + + +def iter_context_files(root: Path) -> list[Path]: + """Return files and symlinks under ``root``, sorted by POSIX relative path.""" + return sorted( + (path for path in root.rglob("*") if path.is_symlink() or path.is_file()), + key=lambda path: path.relative_to(root).as_posix(), + ) + + +def working_tree_hash(root: Path) -> str: + """Hash sorted build inputs, normalized modes, and symlink target strings.""" + lines: list[str] = [] + for path in iter_context_files(root): + relpath = path.relative_to(root).as_posix() + if path.is_symlink(): + mode = "120000" + content_digest = hashlib.sha256(os.readlink(path).encode("utf-8")).hexdigest() + else: + executable = bool(path.stat().st_mode & stat.S_IXUSR) + mode = "100755" if executable else "100644" + content_digest = _sha256_file(path) + lines.append(f"{relpath}\x00{mode}\x00{content_digest}") + return hashlib.sha256("\n".join(lines).encode("utf-8")).hexdigest() + + +def _safe_working_tree_hash(root: Path) -> Optional[str]: + """Compute the context hash without allowing capture to fail a build.""" + try: + return working_tree_hash(root) + except Exception: + logger.warning("build-provenance: content hash failed; omitting", exc_info=True) + return None + + +def capture_build_provenance( + repo_path: Path, context_root: Path, content_root: Optional[Path] = None +) -> BuildProvenance: + """Capture git coordinates and the staged build-context hash.""" + timestamp = datetime.now(timezone.utc).isoformat() + hash_root = content_root if content_root is not None else context_root + tree_hash = _safe_working_tree_hash(hash_root) + + repo_root = _git(repo_path, "rev-parse", "--show-toplevel") + if repo_root is None: + # No git — the content hash is the only identity available. + logger.info("build-provenance: %s is not a git work tree; content hash only", repo_path) + return BuildProvenance(working_tree_hash=tree_hash, build_timestamp=timestamp) + + repo_root_path = Path(repo_root) + commit = _git(repo_root_path, "rev-parse", "HEAD") + # symbolic-ref fails on a detached HEAD (→ None); fall back to an exact tag. + ref = _git(repo_root_path, "symbolic-ref", "--short", "HEAD") or _git( + repo_root_path, "describe", "--tags", "--exact-match" + ) + remote = normalize_remote(_git(repo_root_path, "remote", "get-url", "origin")) + author_name = _git(repo_root_path, "log", "-1", "--format=%an") + author_email = _git(repo_root_path, "log", "-1", "--format=%ae") + + subpath: Optional[str] = None + try: + relative = context_root.resolve().relative_to(repo_root_path.resolve()).as_posix() + subpath = relative if relative != "." else None + except ValueError: + subpath = None + + status_args = ("status", "--porcelain") + if subpath is not None: + status_args += ("--", subpath) + dirty = _git(repo_root_path, *status_args) is not None + + return BuildProvenance( + repo=remote, + commit=commit, + ref=ref, + subpath=subpath, + working_tree_hash=tree_hash, + dirty=dirty, + author_name=author_name, + author_email=author_email, + build_timestamp=timestamp, + ) diff --git a/src/agentex/lib/utils/registration.py b/src/agentex/lib/utils/registration.py index e2bfbc00c..5fc4d4be5 100644 --- a/src/agentex/lib/utils/registration.py +++ b/src/agentex/lib/utils/registration.py @@ -20,17 +20,6 @@ def get_auth_principal(env_vars: EnvironmentVariables): except Exception: return None -def get_build_info(): - build_info_path = os.environ.get("BUILD_INFO_PATH") - logger.info(f"Getting build info from {build_info_path}") - if not build_info_path: - return None - try: - with open(build_info_path, "r") as f: - return json.load(f) - except Exception: - return None - async def register_agent(env_vars: EnvironmentVariables, agent_card=None): """Register this agent with the Agentex server""" if not env_vars.AGENTEX_BASE_URL: @@ -44,8 +33,8 @@ async def register_agent(env_vars: EnvironmentVariables, agent_card=None): or f"Generic description for agent: {env_vars.AGENT_NAME}" ) - # Build registration metadata from build-info.json + deployment env var - registration_metadata = get_build_info() or {} + # Registration metadata carries the deployment id and agent card. + registration_metadata: dict = {} if env_vars.AGENTEX_DEPLOYMENT_ID: registration_metadata["deployment_id"] = env_vars.AGENTEX_DEPLOYMENT_ID if agent_card is not None: diff --git a/tests/lib/test_agent_card.py b/tests/lib/test_agent_card.py index ccde4d33c..5d57f9e8e 100644 --- a/tests/lib/test_agent_card.py +++ b/tests/lib/test_agent_card.py @@ -358,40 +358,39 @@ async def test_agent_card_merged_into_metadata(self, mock_env_vars): card = AgentCard(input_types=["text"], data_events=["result"]) mock_client = self._make_mock_client() - with patch("agentex.lib.utils.registration.get_build_info", return_value={"version": "1.0"}): - with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): - from agentex.lib.utils.registration import register_agent - await register_agent(mock_env_vars, agent_card=card) + with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): + from agentex.lib.utils.registration import register_agent - sent_data = mock_client.post.call_args.kwargs["json"] - metadata = sent_data["registration_metadata"] + await register_agent(mock_env_vars, agent_card=card) - assert "agent_card" in metadata - assert metadata["agent_card"]["input_types"] == ["text"] - assert metadata["agent_card"]["data_events"] == ["result"] - assert metadata["version"] == "1.0" + sent_data = mock_client.post.call_args.kwargs["json"] + metadata = sent_data["registration_metadata"] - async def test_none_preserved_when_no_card_no_build_info(self, mock_env_vars): + assert "agent_card" in metadata + assert metadata["agent_card"]["input_types"] == ["text"] + assert metadata["agent_card"]["data_events"] == ["result"] + + async def test_none_preserved_when_no_card(self, mock_env_vars): mock_client = self._make_mock_client() - with patch("agentex.lib.utils.registration.get_build_info", return_value=None): - with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): - from agentex.lib.utils.registration import register_agent - await register_agent(mock_env_vars, agent_card=None) + with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): + from agentex.lib.utils.registration import register_agent + + await register_agent(mock_env_vars, agent_card=None) - sent_data = mock_client.post.call_args.kwargs["json"] - assert sent_data["registration_metadata"] is None + sent_data = mock_client.post.call_args.kwargs["json"] + assert sent_data["registration_metadata"] is None - async def test_card_creates_metadata_when_build_info_none(self, mock_env_vars): + async def test_card_creates_metadata(self, mock_env_vars): card = AgentCard(input_types=["text"]) mock_client = self._make_mock_client() - with patch("agentex.lib.utils.registration.get_build_info", return_value=None): - with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): - from agentex.lib.utils.registration import register_agent - await register_agent(mock_env_vars, agent_card=card) + with patch("agentex.lib.utils.registration.httpx.AsyncClient", return_value=mock_client): + from agentex.lib.utils.registration import register_agent + + await register_agent(mock_env_vars, agent_card=card) - sent_data = mock_client.post.call_args.kwargs["json"] - metadata = sent_data["registration_metadata"] - assert metadata is not None - assert "agent_card" in metadata + sent_data = mock_client.post.call_args.kwargs["json"] + metadata = sent_data["registration_metadata"] + assert metadata is not None + assert "agent_card" in metadata diff --git a/tests/lib/test_build_provenance.py b/tests/lib/test_build_provenance.py new file mode 100644 index 000000000..9115e2804 --- /dev/null +++ b/tests/lib/test_build_provenance.py @@ -0,0 +1,257 @@ +from __future__ import annotations + +import subprocess +from pathlib import Path + +import pytest + +from agentex.lib.utils.build_provenance import ( + normalize_remote, + working_tree_hash, + iter_context_files, + capture_build_provenance, +) + + +def _git(repo: Path, *args: str) -> None: + subprocess.run(("git", "-C", str(repo), *args), check=True, capture_output=True, text=True) + + +def _init_repo(path: Path, *, remote: str | None = "git@github.com:scaleapi/demo.git") -> Path: + path.mkdir(parents=True, exist_ok=True) + _git(path, "init", "-q") + _git(path, "config", "user.email", "dev@scale.com") + _git(path, "config", "user.name", "Dev") + _git(path, "config", "commit.gpgsign", "false") + if remote: + _git(path, "remote", "add", "origin", remote) + return path + + +def _commit_all(path: Path, message: str = "init") -> None: + _git(path, "add", "-A") + _git(path, "commit", "-q", "-m", message) + _git(path, "branch", "-M", "main") + + +def _write(root: Path, rel: str, content: str = "x") -> None: + target = root / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(content) + + +# --- normalize_remote --------------------------------------------------------- + + +@pytest.mark.parametrize( + ("raw", "expected"), + [ + ("git@github.com:scaleapi/Repo.git", "github.com/scaleapi/Repo"), + ("https://github.com/scaleapi/Repo.git", "github.com/scaleapi/Repo"), + ("https://x-token:secret@GitHub.com/scaleapi/Repo", "github.com/scaleapi/Repo"), + ("ssh://git@gitlab.com/group/sub/proj.git", "gitlab.com/group/sub/proj"), + ("", None), + (None, None), + ], +) +def test_normalize_remote(raw: str | None, expected: str | None) -> None: + assert normalize_remote(raw) == expected + + +# --- working_tree_hash -------------------------------------------------------- + + +def test_hash_is_order_independent(tmp_path: Path) -> None: + first = tmp_path / "a" + second = tmp_path / "b" + for rel in ("z.txt", "a/b.txt", "m.txt"): + _write(first, rel, rel) + # Same content, different creation order. + for rel in ("m.txt", "z.txt", "a/b.txt"): + _write(second, rel, rel) + assert working_tree_hash(first) == working_tree_hash(second) + + +def test_hash_changes_on_one_byte(tmp_path: Path) -> None: + root = tmp_path / "ctx" + _write(root, "f.txt", "hello") + before = working_tree_hash(root) + _write(root, "f.txt", "hellp") + assert working_tree_hash(root) != before + + +def test_hash_changes_when_file_added(tmp_path: Path) -> None: + root = tmp_path / "ctx" + _write(root, "f.txt", "hello") + before = working_tree_hash(root) + _write(root, "g.txt", "new") + assert working_tree_hash(root) != before + + +def test_hash_changes_on_executable_bit(tmp_path: Path) -> None: + root = tmp_path / "ctx" + script = root / "run.sh" + _write(root, "run.sh", "#!/bin/sh\n") + before = working_tree_hash(root) + script.chmod(0o755) + assert working_tree_hash(root) != before + + +def test_symlink_hashes_target_not_resolved_content(tmp_path: Path) -> None: + root = tmp_path / "ctx" + root.mkdir() + # Dangling symlinks: distinct hashes prove the target string is hashed, not + # resolved content (resolving would raise). + (root / "link").symlink_to("points/to/a") + hash_a = working_tree_hash(root) + (root / "link").unlink() + (root / "link").symlink_to("points/to/b") + assert working_tree_hash(root) != hash_a + + +def test_iter_context_files_skips_directories(tmp_path: Path) -> None: + root = tmp_path / "ctx" + _write(root, "pkg/mod.py", "x") + _write(root, "top.txt", "y") + rels = [path.relative_to(root).as_posix() for path in iter_context_files(root)] + assert rels == ["pkg/mod.py", "top.txt"] + + +# --- capture_build_provenance ------------------------------------------------- + + +def test_capture_clean_tree(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "main.py", "print(1)") + _commit_all(repo) + + prov = capture_build_provenance(repo, repo) + + assert prov.repo == "github.com/scaleapi/demo" + assert prov.ref == "main" + assert prov.commit is not None and len(prov.commit) == 40 + assert prov.working_tree_hash is not None # always computed + assert prov.dirty is False + assert prov.subpath is None + assert prov.author_email == "dev@scale.com" + + +def test_capture_untracked_file_changes_hash(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "main.py", "print(1)") + _commit_all(repo) + _write(repo, "scratch.py", "debug = True") # untracked + + prov = capture_build_provenance(repo, repo) + + # The stale-code guard: an untracked file is part of the build context, so it + # must move the hash (a `git diff` of tracked files alone would miss it). + assert prov.dirty is True + assert prov.working_tree_hash == working_tree_hash(repo) + assert working_tree_hash(repo) != _hash_without(repo, "scratch.py") + + +def _hash_without(repo: Path, rel: str) -> str: + removed = repo / rel + saved = removed.read_text() + removed.unlink() + try: + return working_tree_hash(repo) + finally: + removed.write_text(saved) + + +def test_capture_detached_head_has_no_ref(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "main.py", "print(1)") + _commit_all(repo) + _write(repo, "main.py", "print(2)") + _git(repo, "add", "-A") + _git(repo, "commit", "-q", "-m", "second") + first = subprocess.run( + ("git", "-C", str(repo), "rev-list", "--max-parents=0", "HEAD"), + check=True, + capture_output=True, + text=True, + ).stdout.strip() + _git(repo, "checkout", "-q", first) + + prov = capture_build_provenance(repo, repo) + + assert prov.commit == first + assert prov.ref is None + + +def test_capture_detached_on_tag_uses_tag(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "main.py", "print(1)") + _commit_all(repo) + _git(repo, "tag", "v1.2.3") + _git(repo, "checkout", "-q", "v1.2.3") + + assert capture_build_provenance(repo, repo).ref == "v1.2.3" + + +def test_capture_no_remote(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo", remote=None) + _write(repo, "main.py", "print(1)") + _commit_all(repo) + + prov = capture_build_provenance(repo, repo) + + assert prov.repo is None + assert prov.commit is not None + assert prov.working_tree_hash is not None # always computed + + +def test_capture_non_git_dir(tmp_path: Path) -> None: + plain = tmp_path / "plain" + _write(plain, "main.py", "print(1)") + + prov = capture_build_provenance(plain, plain) + + assert prov.repo is None + assert prov.commit is None + assert prov.ref is None + # No commit → the content hash is the identity; dirtiness is undefined (no VCS). + assert prov.working_tree_hash == working_tree_hash(plain) + assert prov.dirty is None + assert prov.build_timestamp is not None + + +def test_capture_never_raises_when_hash_fails(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + import agentex.lib.utils.build_provenance as bp + + plain = tmp_path / "plain" # non-git → would hash, which we force to fail + _write(plain, "main.py", "print(1)") + + def _boom(_root: Path) -> str: + raise OSError("permission denied") + + monkeypatch.setattr(bp, "working_tree_hash", _boom) + + prov = bp.capture_build_provenance(plain, plain) # must not raise + + assert prov.working_tree_hash is None + + +def test_capture_monorepo_subpath(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "agents/foo/main.py", "print(1)") + _commit_all(repo) + + prov = capture_build_provenance(repo, repo / "agents" / "foo") + + assert prov.subpath == "agents/foo" + + +def test_capture_monorepo_ignores_changes_outside_context(tmp_path: Path) -> None: + repo = _init_repo(tmp_path / "repo") + _write(repo, "agents/foo/main.py", "print(1)") + _write(repo, "agents/bar/main.py", "print(2)") + _commit_all(repo) + _write(repo, "agents/bar/scratch.py", "debug = True") + + prov = capture_build_provenance(repo, repo / "agents" / "foo") + + assert prov.dirty is False diff --git a/uv.lock b/uv.lock index 43de6493c..f925c2dce 100644 --- a/uv.lock +++ b/uv.lock @@ -15,7 +15,7 @@ members = [ [[package]] name = "agentex-client" -version = "0.17.0" +version = "0.21.0" source = { editable = "." } dependencies = [ { name = "anyio" }, @@ -91,7 +91,7 @@ dev = [ [[package]] name = "agentex-sdk" -version = "0.17.0" +version = "0.21.0" source = { editable = "adk" } dependencies = [ { name = "agentex-client" },