|
@@ -10,12 +10,18 @@ import shutil
|
|
|
import subprocess
|
|
import subprocess
|
|
|
import uuid
|
|
import uuid
|
|
|
from datetime import datetime, timezone
|
|
from datetime import datetime, timezone
|
|
|
-from pathlib import Path
|
|
|
|
|
-from typing import Any, Mapping
|
|
|
|
|
|
|
+from pathlib import Path, PurePosixPath
|
|
|
|
|
+from typing import Any, Iterable, Mapping, Sequence
|
|
|
|
|
|
|
|
|
|
|
|
|
RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
|
RUN_ID_RE = re.compile(r"^[0-9a-f]{32}$")
|
|
|
COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
|
|
COMMIT_RE = re.compile(r"^[0-9a-f]{8}$")
|
|
|
|
|
+FULL_COMMIT_RE = re.compile(r"^[0-9a-f]{40}$")
|
|
|
|
|
+AGENT_TASK_REPORT_SCHEMA = "prod2u-native-agent-task-report-v1"
|
|
|
|
|
+AGENT_SELECTION_SOURCES = frozenset(
|
|
|
|
|
+ {"explicit", "inherited", "automatic", "default", "not_exposed", "unknown"}
|
|
|
|
|
+)
|
|
|
|
|
+AGENT_TASK_STATUSES = frozenset({"completed", "blocked", "failed", "integration_conflict"})
|
|
|
PROJECT_ID = "prod2u-door-temp"
|
|
PROJECT_ID = "prod2u-door-temp"
|
|
|
PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
|
|
PROJECT_PATH = Path("projects/prod2u-door-temp/project.json")
|
|
|
SOURCE_PATHS = (
|
|
SOURCE_PATHS = (
|
|
@@ -123,6 +129,28 @@ def _repo_root(root: Path | None = None) -> Path:
|
|
|
return Path(root or Path(__file__).resolve().parents[1]).resolve()
|
|
return Path(root or Path(__file__).resolve().parents[1]).resolve()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+def _run_git(
|
|
|
|
|
+ root: Path,
|
|
|
|
|
+ args: Sequence[str],
|
|
|
|
|
+ *,
|
|
|
|
|
+ timeout_seconds: float = 10.0,
|
|
|
|
|
+ check: bool = True,
|
|
|
|
|
+) -> subprocess.CompletedProcess[bytes]:
|
|
|
|
|
+ if timeout_seconds <= 0:
|
|
|
|
|
+ raise ValueError("timeout_seconds must be positive")
|
|
|
|
|
+ values = [str(value) for value in args]
|
|
|
|
|
+ if not values or any(not value for value in values):
|
|
|
|
|
+ raise ValueError("git args must be a non-empty sequence of non-empty strings")
|
|
|
|
|
+ return subprocess.run(
|
|
|
|
|
+ ["git", "-C", str(_repo_root(root)), *values],
|
|
|
|
|
+ capture_output=True,
|
|
|
|
|
+ check=check,
|
|
|
|
|
+ shell=False,
|
|
|
|
|
+ text=False,
|
|
|
|
|
+ timeout=timeout_seconds,
|
|
|
|
|
+ )
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
|
|
def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
|
|
|
repo = _repo_root(root)
|
|
repo = _repo_root(root)
|
|
|
project_path = repo / PROJECT_PATH
|
|
project_path = repo / PROJECT_PATH
|
|
@@ -144,19 +172,229 @@ def build_source_manifest(root: Path | None = None) -> dict[str, Any]:
|
|
|
|
|
|
|
|
def current_commit8(root: Path | None = None) -> str:
|
|
def current_commit8(root: Path | None = None) -> str:
|
|
|
repo = _repo_root(root)
|
|
repo = _repo_root(root)
|
|
|
- result = subprocess.run(
|
|
|
|
|
- ["git", "rev-parse", "--short=8", "HEAD"],
|
|
|
|
|
- cwd=repo,
|
|
|
|
|
- check=True,
|
|
|
|
|
- capture_output=True,
|
|
|
|
|
- text=True,
|
|
|
|
|
- )
|
|
|
|
|
- commit = result.stdout.strip().lower()
|
|
|
|
|
|
|
+ result = _run_git(repo, ["rev-parse", "--short=8", "HEAD"])
|
|
|
|
|
+ commit = result.stdout.decode("ascii").strip().lower()
|
|
|
if not COMMIT_RE.fullmatch(commit):
|
|
if not COMMIT_RE.fullmatch(commit):
|
|
|
raise ValueError(f"unexpected commit: {commit}")
|
|
raise ValueError(f"unexpected commit: {commit}")
|
|
|
return commit
|
|
return commit
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
+def _validate_full_commit(value: Any, field: str, *, allow_none: bool = False) -> str | None:
|
|
|
|
|
+ if value is None and allow_none:
|
|
|
|
|
+ return None
|
|
|
|
|
+ if not isinstance(value, str) or not FULL_COMMIT_RE.fullmatch(value):
|
|
|
|
|
+ raise ValueError(f"{field} must be a 40-character lowercase hexadecimal commit")
|
|
|
|
|
+ return value
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _validate_observation_fields(native_thread: Mapping[str, Any]) -> None:
|
|
|
|
|
+ if native_thread.get("model_policy") != "unconstrained":
|
|
|
|
|
+ raise ValueError("native_thread.model_policy must be unconstrained")
|
|
|
|
|
+ if native_thread.get("reasoning_effort_policy") != "unconstrained":
|
|
|
|
|
+ raise ValueError("native_thread.reasoning_effort_policy must be unconstrained")
|
|
|
|
|
+ for field in ("model_selection_source", "effort_selection_source"):
|
|
|
|
|
+ value = native_thread.get(field)
|
|
|
|
|
+ if value is not None and value not in AGENT_SELECTION_SOURCES:
|
|
|
|
|
+ raise ValueError(f"{field} has an unsupported selection source")
|
|
|
|
|
+ observation_source = native_thread.get("observation_source")
|
|
|
|
|
+ if observation_source is not None and not isinstance(observation_source, str):
|
|
|
|
|
+ raise ValueError("observation_source must be a string or null")
|
|
|
|
|
+ for field in ("observed_model", "observed_reasoning_effort", "observed_permission_mode"):
|
|
|
|
|
+ value = native_thread.get(field)
|
|
|
|
|
+ if value is not None and not isinstance(value, str):
|
|
|
|
|
+ raise ValueError(f"{field} must be a string or null")
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _normalise_repo_path(value: Any, *, owned: bool = False) -> str:
|
|
|
|
|
+ if not isinstance(value, str) or not value:
|
|
|
|
|
+ raise ValueError("path must be a non-empty string")
|
|
|
|
|
+ raw = value.replace("\\", "/")
|
|
|
|
|
+ if raw.startswith("/") or re.match(r"^[A-Za-z]:", raw):
|
|
|
|
|
+ raise ValueError(f"path must be relative: {value}")
|
|
|
|
|
+ if any(part == ".." for part in PurePosixPath(raw).parts):
|
|
|
|
|
+ raise ValueError(f"path contains parent traversal: {value}")
|
|
|
|
|
+ normalised = PurePosixPath(raw).as_posix()
|
|
|
|
|
+ if normalised in {"", "."}:
|
|
|
|
|
+ raise ValueError(f"path is not a file or directory: {value}")
|
|
|
|
|
+ if owned and any(token in normalised for token in "*?["):
|
|
|
|
|
+ raise ValueError("owned paths must not contain glob syntax")
|
|
|
|
|
+ return normalised
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def _normalise_owned_path(value: Any) -> str:
|
|
|
|
|
+ directory = isinstance(value, str) and value.replace("\\", "/").endswith("/")
|
|
|
|
|
+ normalised = _normalise_repo_path(value, owned=True)
|
|
|
|
|
+ return normalised.rstrip("/") + "/" if directory else normalised
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def parse_name_status_z(payload: bytes) -> list[tuple[str, tuple[str, ...]]]:
|
|
|
|
|
+ tokens = payload.split(b"\0")
|
|
|
|
|
+ if tokens and tokens[-1] == b"":
|
|
|
|
|
+ tokens.pop()
|
|
|
|
|
+ events: list[tuple[str, tuple[str, ...]]] = []
|
|
|
|
|
+ index = 0
|
|
|
|
|
+ while index < len(tokens):
|
|
|
|
|
+ try:
|
|
|
|
|
+ status = tokens[index].decode("utf-8", "surrogateescape")
|
|
|
|
|
+ except UnicodeDecodeError as exc:
|
|
|
|
|
+ raise ValueError("git status contains undecodable status") from exc
|
|
|
|
|
+ index += 1
|
|
|
|
|
+ if not status:
|
|
|
|
|
+ raise ValueError("git status contains an empty status")
|
|
|
|
|
+ path_count = 2 if status[0] in {"R", "C"} else 1
|
|
|
|
|
+ if index + path_count > len(tokens):
|
|
|
|
|
+ raise ValueError("git status has an incomplete path record")
|
|
|
|
|
+ paths = tuple(token.decode("utf-8", "surrogateescape") for token in tokens[index : index + path_count])
|
|
|
|
|
+ events.append((status, paths))
|
|
|
|
|
+ index += path_count
|
|
|
|
|
+ return events
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def validate_changed_paths(
|
|
|
|
|
+ events: Iterable[tuple[str, Iterable[str]]],
|
|
|
|
|
+ owned_paths: Iterable[str],
|
|
|
|
|
+) -> list[str]:
|
|
|
|
|
+ owned = [_normalise_owned_path(path) for path in owned_paths]
|
|
|
|
|
+ changed: list[str] = []
|
|
|
|
|
+ for _status, raw_paths in events:
|
|
|
|
|
+ for raw_path in raw_paths:
|
|
|
|
|
+ path = _normalise_repo_path(raw_path)
|
|
|
|
|
+ changed.append(path)
|
|
|
|
|
+ if not any(
|
|
|
|
|
+ path == candidate
|
|
|
|
|
+ or (candidate.endswith("/") and path.startswith(candidate))
|
|
|
|
|
+ for candidate in owned
|
|
|
|
|
+ ):
|
|
|
|
|
+ raise ValueError(f"changed path is outside owned paths: {path}")
|
|
|
|
|
+ return changed
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def changed_paths_for_result(
|
|
|
|
|
+ root: Path,
|
|
|
|
|
+ assigned_base_commit: str,
|
|
|
|
|
+ result_commit: str,
|
|
|
|
|
+ owned_paths: Iterable[str],
|
|
|
|
|
+) -> list[str]:
|
|
|
|
|
+ _validate_full_commit(assigned_base_commit, "assigned_base_commit")
|
|
|
|
|
+ _validate_full_commit(result_commit, "result_commit")
|
|
|
|
|
+ result = _run_git(
|
|
|
|
|
+ root,
|
|
|
|
|
+ ["diff", "--name-status", "-z", "--find-renames", assigned_base_commit, result_commit],
|
|
|
|
|
+ )
|
|
|
|
|
+ return validate_changed_paths(parse_name_status_z(result.stdout), owned_paths)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def validate_agent_task_report(
|
|
|
|
|
+ report: Mapping[str, Any],
|
|
|
|
|
+ *,
|
|
|
|
|
+ expected_run_id: str,
|
|
|
|
|
+ expected_base_commit: str,
|
|
|
|
|
+ root: Path | None = None,
|
|
|
|
|
+ expected_dependencies: Mapping[str, Mapping[str, str | None]] | None = None,
|
|
|
|
|
+) -> dict[str, Any]:
|
|
|
|
|
+ if report.get("schema") != AGENT_TASK_REPORT_SCHEMA:
|
|
|
|
|
+ raise ValueError("unexpected agent task report schema")
|
|
|
|
|
+ if not RUN_ID_RE.fullmatch(expected_run_id) or report.get("run_id") != expected_run_id:
|
|
|
|
|
+ raise ValueError("run_id mismatch")
|
|
|
|
|
+ _validate_full_commit(expected_base_commit, "expected_base_commit")
|
|
|
|
|
+ assigned_base = _validate_full_commit(report.get("assigned_base_commit"), "assigned_base_commit")
|
|
|
|
|
+ if assigned_base != expected_base_commit:
|
|
|
|
|
+ raise ValueError("stale assigned base mismatch")
|
|
|
|
|
+ if not isinstance(report.get("task_id"), str) or not report["task_id"]:
|
|
|
|
|
+ raise ValueError("task_id must be non-empty")
|
|
|
|
|
+ if not isinstance(report.get("feature_branch"), str) or not report["feature_branch"]:
|
|
|
|
|
+ raise ValueError("feature_branch must be non-empty")
|
|
|
|
|
+ if not isinstance(report.get("worktree"), str) or not report["worktree"]:
|
|
|
|
|
+ raise ValueError("worktree must be non-empty")
|
|
|
|
|
+ status = report.get("status")
|
|
|
|
|
+ if status not in AGENT_TASK_STATUSES:
|
|
|
|
|
+ raise ValueError("unsupported agent task status")
|
|
|
|
|
+ dependencies = report.get("dependencies", [])
|
|
|
|
|
+ if not isinstance(dependencies, list):
|
|
|
|
|
+ raise ValueError("dependencies must be a list")
|
|
|
|
|
+ dependency_map: dict[str, dict[str, str | None]] = {}
|
|
|
|
|
+ for dependency in dependencies:
|
|
|
|
|
+ if not isinstance(dependency, Mapping) or not isinstance(dependency.get("task_id"), str):
|
|
|
|
|
+ raise ValueError("dependency entries must contain task_id")
|
|
|
|
|
+ task_id = dependency["task_id"]
|
|
|
|
|
+ result_commit = _validate_full_commit(
|
|
|
|
|
+ dependency.get("result_commit"), f"dependency {task_id} result_commit", allow_none=True
|
|
|
|
|
+ )
|
|
|
|
|
+ integration_commit = _validate_full_commit(
|
|
|
|
|
+ dependency.get("integration_commit"),
|
|
|
|
|
+ f"dependency {task_id} integration_commit",
|
|
|
|
|
+ allow_none=True,
|
|
|
|
|
+ )
|
|
|
|
|
+ dependency_map[task_id] = {
|
|
|
|
|
+ "result_commit": result_commit,
|
|
|
|
|
+ "integration_commit": integration_commit,
|
|
|
|
|
+ }
|
|
|
|
|
+ if expected_dependencies is not None and dependency_map != dict(expected_dependencies):
|
|
|
|
|
+ raise ValueError("stale dependency mismatch")
|
|
|
|
|
+ native_thread = report.get("native_thread")
|
|
|
|
|
+ if not isinstance(native_thread, Mapping):
|
|
|
|
|
+ raise ValueError("native_thread must be an object")
|
|
|
|
|
+ _validate_observation_fields(native_thread)
|
|
|
|
|
+ owned_paths = report.get("owned_paths", [])
|
|
|
|
|
+ if not isinstance(owned_paths, list):
|
|
|
|
|
+ raise ValueError("owned_paths must be a list")
|
|
|
|
|
+ [_normalise_owned_path(path) for path in owned_paths]
|
|
|
|
|
+ result_commit = _validate_full_commit(report.get("result_commit"), "result_commit", allow_none=True)
|
|
|
|
|
+ integration_commit = _validate_full_commit(
|
|
|
|
|
+ report.get("integration_commit"), "integration_commit", allow_none=True
|
|
|
|
|
+ )
|
|
|
|
|
+ read_only_report = report.get("read_only_report")
|
|
|
|
|
+ if result_commit is None and (not isinstance(read_only_report, str) or not read_only_report):
|
|
|
|
|
+ raise ValueError("task report requires result_commit or read_only_report")
|
|
|
|
|
+ if root is not None and result_commit is not None:
|
|
|
|
|
+ resolved = _run_git(root, ["rev-parse", "--verify", f"{result_commit}^{{commit}}"]).stdout
|
|
|
|
|
+ if resolved.decode("ascii", "strict").strip().lower() != result_commit:
|
|
|
|
|
+ raise ValueError("result commit does not resolve to the supplied full SHA")
|
|
|
|
|
+ ancestry = _run_git(
|
|
|
|
|
+ root,
|
|
|
|
|
+ ["merge-base", "--is-ancestor", assigned_base, result_commit],
|
|
|
|
|
+ check=False,
|
|
|
|
|
+ )
|
|
|
|
|
+ if ancestry.returncode != 0:
|
|
|
|
|
+ raise ValueError("stale result commit is not based on assigned base")
|
|
|
|
|
+ changed_paths_for_result(root, assigned_base, result_commit, owned_paths)
|
|
|
|
|
+ if root is not None and integration_commit is not None:
|
|
|
|
|
+ _run_git(root, ["rev-parse", "--verify", f"{integration_commit}^{{commit}}"])
|
|
|
|
|
+ return dict(report)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def aggregate_agent_receipt_bindings(
|
|
|
|
|
+ receipts: Mapping[str, Mapping[str, Any]],
|
|
|
|
|
+ *,
|
|
|
|
|
+ expected_run_id: str,
|
|
|
|
|
+ expected_commit: str,
|
|
|
|
|
+) -> dict[str, Any]:
|
|
|
|
|
+ if not RUN_ID_RE.fullmatch(expected_run_id):
|
|
|
|
|
+ raise ValueError("expected_run_id must be 32 lowercase hexadecimal characters")
|
|
|
|
|
+ aggregate: dict[str, Any] = {
|
|
|
|
|
+ "schema": "prod2u-native-agent-receipt-aggregate-v1",
|
|
|
|
|
+ "run_id": expected_run_id,
|
|
|
|
|
+ "commit": expected_commit,
|
|
|
|
|
+ "receipts": {},
|
|
|
|
|
+ }
|
|
|
|
|
+ for name, receipt in receipts.items():
|
|
|
|
|
+ if not isinstance(receipt, Mapping):
|
|
|
|
|
+ raise ValueError(f"receipt must be an object: {name}")
|
|
|
|
|
+ observed_run_id = receipt.get("verification_run_id", receipt.get("run_id"))
|
|
|
|
|
+ if observed_run_id != expected_run_id:
|
|
|
|
|
+ raise ValueError(f"receipt run_id mismatch: {name}")
|
|
|
|
|
+ if receipt.get("commit") != expected_commit:
|
|
|
|
|
+ raise ValueError(f"receipt commit mismatch: {name}")
|
|
|
|
|
+ hashes: dict[str, str] = {}
|
|
|
|
|
+ for field, value in receipt.items():
|
|
|
|
|
+ if field.endswith("_sha256"):
|
|
|
|
|
+ if not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
|
|
|
|
|
+ raise ValueError(f"receipt hash is invalid: {name}.{field}")
|
|
|
|
|
+ hashes[field] = value
|
|
|
|
|
+ aggregate["receipts"][name] = hashes
|
|
|
|
|
+ return aggregate
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
def _write_json(path: Path, value: Mapping[str, Any]) -> None:
|
|
def _write_json(path: Path, value: Mapping[str, Any]) -> None:
|
|
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
Path(path).parent.mkdir(parents=True, exist_ok=True)
|
|
|
Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
|
|
Path(path).write_text(json.dumps(dict(value), indent=2, sort_keys=True) + "\n", encoding="utf-8", newline="\n")
|