graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
perf(ci): reuse verified Zig toolchains
Rach Pradhan039c88c64ad5
diff --git a/.github/actions/setup-codegraff-zig/action.yml b/.github/actions/setup-codegraff-zig/action.ymlindex 170022f6..78c36034 100644--- a/.github/actions/setup-codegraff-zig/action.yml+++ b/.github/actions/setup-codegraff-zig/action.yml@@ -9,7 +9,15 @@ inputs:runs:using: compositesteps:+ - name: Restore verified Zig toolchain+ id: toolchain-cache+ uses: actions/cache@v6+ with:+ path: ${{ runner.temp }}/codegraff-zig-${{ inputs.version }}+ key: codegraff-zig-toolchain-v1-${{ runner.os }}-${{ runner.arch }}-${{ inputs.version }}+- name: Restore verified Zig archive+ if: steps.toolchain-cache.outputs.cache-hit != 'true'uses: actions/cache@v6with:path: ${{ runner.temp }}/codegraff-zig-archivesdiff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 977552c0..ae62751c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -12,6 +12,9 @@ jobs:steps:- uses: actions/checkout@v7+ - name: Pinned Zig installer integrity tests+ run: python3 scripts/test-install-zig-ci.py+- name: Python SDK import smokerun: python3 -c "import sys; sys.path.insert(0, 'sdk/py'); import harness_sdk; assert harness_sdk.MODELS and harness_sdk.TOOLS; print('py sdk ok:', len(harness_sdk.MODELS), 'models')"diff --git a/scripts/install-zig-ci.py b/scripts/install-zig-ci.pyindex d559453f..8fec9bea 100644--- a/scripts/install-zig-ci.py+++ b/scripts/install-zig-ci.py@@ -22,11 +22,13 @@ ASSETS = {"zig-x86_64-linux-{version}.tar.xz","b0d46ffc4587b9e8dd0b524ee5bc4da1e67f28bba55e7c534cec64af2f2d7a74","08241893d9dad32a3d0e71937d6f659e8fba4598ca29b8c9eaa75ee31c9edb4c",+ "e75b3cba834758312b1ac4c1fcf10301851bc05ca53386ed6956c84fcd48ec77",),("Windows", "x86_64"): ("zig-x86_64-windows-{version}.zip","2a8f1a34402076ab7931e4535bd379b20c83fc263d1387cb3f70cb2e397f9ebe","ba08d13e71268f7305887293bf6726f2effa0b6b3b9b4169be45f34cc7730c73",+ "364e24705f60cc8a7433c8002ebf0d9dd0be40a4b0a183447112795afe35813d",),}MIRRORS = (@@ -51,6 +53,31 @@ def sha256(path: Path) -> str:return digest.hexdigest()+def tree_sha256(root: Path) -> str:+ """Hash every toolchain path and byte using an unambiguous record format."""+ digest = hashlib.sha256()+ entries = sorted(root.rglob("*"), key=lambda item: item.relative_to(root).as_posix())+ for entry in entries:+ if not entry.is_symlink() and entry.is_dir():+ continue+ relative = entry.relative_to(root).as_posix().encode("utf-8")+ digest.update(b"L" if entry.is_symlink() else b"F")+ digest.update(len(relative).to_bytes(4, "big"))+ digest.update(relative)+ if entry.is_symlink():+ target = os.readlink(entry).encode("utf-8")+ digest.update(len(target).to_bytes(4, "big"))+ digest.update(target)+ elif entry.is_file():+ digest.update(entry.stat().st_size.to_bytes(8, "big"))+ with entry.open("rb") as source:+ while chunk := source.read(1024 * 1024):+ digest.update(chunk)+ elif not entry.is_dir():+ raise RuntimeError(f"unsupported Zig toolchain entry: {entry}")+ return digest.hexdigest()++def download(filename: str, destination: Path, expected_sha: str) -> None:partial = destination.with_suffix(destination.suffix + ".part")request_headers = {"User-Agent": "codegraff-ci-zig-installer/1"}@@ -105,6 +132,30 @@ def installed_version(binary: Path) -> str | None:return None+def validate_toolchain(+ install_dir: Path,+ system: str,+ version: str,+ expected_binary_sha: str,+ expected_tree_sha: str,+) -> tuple[bool, str]:+ if not install_dir.is_dir():+ return False, "toolchain directory is missing"+ try:+ actual_tree_sha = tree_sha256(install_dir)+ except (OSError, RuntimeError) as error:+ return False, f"tree validation failed: {error}"+ if actual_tree_sha != expected_tree_sha:+ return False, f"tree SHA-256 mismatch: got {actual_tree_sha}"+ binary = zig_binary(install_dir, system)+ if not binary.is_file() or sha256(binary) != expected_binary_sha:+ return False, "Zig binary failed its pinned SHA-256 check"+ actual_version = installed_version(binary)+ if actual_version != version:+ return False, f"Zig reports {actual_version!r}, expected {version!r}"+ return True, actual_version++def main() -> int:parser = argparse.ArgumentParser()parser.add_argument("--version", default=PINNED_VERSION)@@ -116,7 +167,7 @@ def main() -> int:asset = ASSETS.get((system, normalized_arch()))if asset is None:parser.error(f"unsupported runner {system}/{platform.machine()}")- filename_template, expected_sha, expected_binary_sha = asset+ filename_template, expected_sha, expected_binary_sha, expected_tree_sha = assetfilename = filename_template.format(version=args.version)runner_temp_value = os.environ.get("RUNNER_TEMP")if not runner_temp_value:@@ -125,22 +176,30 @@ def main() -> int:if not runner_temp.is_dir():parser.error("RUNNER_TEMP must name an existing directory")install_dir = runner_temp / f"codegraff-zig-{args.version}"- binary = zig_binary(install_dir, system)- archive_dir = runner_temp / "codegraff-zig-archives"- archive_dir.mkdir(exist_ok=True)- archive = archive_dir / filename- if not archive.is_file() or sha256(archive) != expected_sha:- archive.unlink(missing_ok=True)- download(filename, archive, expected_sha)- # Re-extract verified bytes every run. Only the archive is cached, never an- # executable tool tree that could bypass the checksum on a later job.- extract(archive, install_dir)- if sha256(binary) != expected_binary_sha:- raise RuntimeError("extracted Zig binary failed its pinned SHA-256 check")- actual_version = installed_version(binary)- if actual_version != args.version:- raise RuntimeError(f"installed Zig reports {actual_version!r}, expected {args.version!r}")+ valid, result = validate_toolchain(+ install_dir, system, args.version, expected_binary_sha, expected_tree_sha+ )+ if valid:+ actual_version = result+ print(f"Verified cached Zig toolchain at {install_dir}")+ else:+ if install_dir.exists():+ print(f"Cached Zig toolchain rejected ({result}); recovering from archive")+ archive_dir = runner_temp / "codegraff-zig-archives"+ archive_dir.mkdir(exist_ok=True)+ archive = archive_dir / filename+ if not archive.is_file() or sha256(archive) != expected_sha:+ archive.unlink(missing_ok=True)+ download(filename, archive, expected_sha)+ extract(archive, install_dir)+ valid, result = validate_toolchain(+ install_dir, system, args.version, expected_binary_sha, expected_tree_sha+ )+ if not valid:+ shutil.rmtree(install_dir, ignore_errors=True)+ raise RuntimeError(f"extracted Zig toolchain failed validation: {result}")+ actual_version = resultgithub_path = os.environ.get("GITHUB_PATH")if not github_path:diff --git a/scripts/test-install-zig-ci.py b/scripts/test-install-zig-ci.pynew file mode 100644index 00000000..db4f902a--- /dev/null+++ b/scripts/test-install-zig-ci.py@@ -0,0 +1,126 @@+#!/usr/bin/env python3+"""Focused integrity tests for the pinned CI Zig installer."""++from __future__ import annotations++import importlib.util+import os+from pathlib import Path+import shutil+import sys+import tarfile+import tempfile+import unittest+from unittest import mock+++INSTALLER_PATH = Path(__file__).with_name("install-zig-ci.py")+SPEC = importlib.util.spec_from_file_location("install_zig_ci", INSTALLER_PATH)+if SPEC is None or SPEC.loader is None:+ raise RuntimeError(f"cannot import {INSTALLER_PATH}")+installer = importlib.util.module_from_spec(SPEC)+SPEC.loader.exec_module(installer)+++class ToolchainIntegrityTests(unittest.TestCase):+ def setUp(self) -> None:+ self.scratch = tempfile.TemporaryDirectory(prefix="codegraff-installer-test-")+ self.root = Path(self.scratch.name) / "toolchain"+ (self.root / "lib").mkdir(parents=True)+ (self.root / "lib" / "std.zig").write_bytes(b"pub const answer: u8 = 42;\n")+ self.binary = self.root / "zig"+ self.binary.write_text(+ f"#!/bin/sh\nprintf '%s\\n' '{installer.PINNED_VERSION}'\n",+ encoding="utf-8",+ )+ self.binary.chmod(0o755)+ (self.root / "std-link").symlink_to("lib/std.zig")+ self.binary_sha = installer.sha256(self.binary)+ self.tree_sha = installer.tree_sha256(self.root)++ def tearDown(self) -> None:+ self.scratch.cleanup()++ def validate(self) -> tuple[bool, str]:+ return installer.validate_toolchain(+ self.root,+ "Linux",+ installer.PINNED_VERSION,+ self.binary_sha,+ self.tree_sha,+ )++ def test_exact_tree_is_accepted(self) -> None:+ self.assertEqual(self.validate(), (True, installer.PINNED_VERSION))++ def test_modified_file_is_rejected(self) -> None:+ (self.root / "lib" / "std.zig").write_bytes(b"tampered\n")+ valid, reason = self.validate()+ self.assertFalse(valid)+ self.assertIn("tree SHA-256 mismatch", reason)++ def test_added_file_is_rejected(self) -> None:+ (self.root / "unexpected").write_bytes(b"extra")+ valid, reason = self.validate()+ self.assertFalse(valid)+ self.assertIn("tree SHA-256 mismatch", reason)++ def test_retargeted_symlink_is_rejected(self) -> None:+ (self.root / "std-link").unlink()+ (self.root / "std-link").symlink_to("zig")+ valid, reason = self.validate()+ self.assertFalse(valid)+ self.assertIn("tree SHA-256 mismatch", reason)++ def test_invalid_cache_recovers_from_verified_archive(self) -> None:+ runner_temp = Path(self.scratch.name)+ archive_dir = runner_temp / "codegraff-zig-archives"+ archive_dir.mkdir()+ filename_template = "zig-x86_64-linux-{version}.tar.xz"+ filename = filename_template.format(version=installer.PINNED_VERSION)+ archive = archive_dir / filename+ with tarfile.open(archive, "w:xz") as bundle:+ bundle.add(self.root, arcname=f"zig-x86_64-linux-{installer.PINNED_VERSION}")++ install_dir = runner_temp / f"codegraff-zig-{installer.PINNED_VERSION}"+ shutil.copytree(self.root, install_dir, symlinks=True)+ (install_dir / "lib" / "std.zig").write_bytes(b"tampered cache\n")++ workspace = runner_temp / "workspace"+ workspace.mkdir()+ github_path = runner_temp / "github-path"+ github_env = runner_temp / "github-env"+ fake_asset = (+ filename_template,+ installer.sha256(archive),+ self.binary_sha,+ self.tree_sha,+ )+ environment = {+ "RUNNER_TEMP": str(runner_temp),+ "GITHUB_PATH": str(github_path),+ "GITHUB_ENV": str(github_env),+ "GITHUB_WORKSPACE": str(workspace),+ }+ with (+ mock.patch.dict(installer.ASSETS, {("Linux", "x86_64"): fake_asset}, clear=True),+ mock.patch.dict(os.environ, environment),+ mock.patch.object(installer.platform, "system", return_value="Linux"),+ mock.patch.object(installer.platform, "machine", return_value="x86_64"),+ mock.patch.object(sys, "argv", [str(INSTALLER_PATH)]),+ ):+ self.assertEqual(installer.main(), 0)++ valid, reason = installer.validate_toolchain(+ install_dir,+ "Linux",+ installer.PINNED_VERSION,+ self.binary_sha,+ self.tree_sha,+ )+ self.assertTrue(valid, reason)+ self.assertIn(str(install_dir), github_path.read_text(encoding="utf-8"))+++if __name__ == "__main__":+ unittest.main()