"""Broker-owned, audited mutation primitives for one isolated blue workspace.""" from __future__ import annotations import base64 import json import os import shutil import stat import time from pathlib import Path from typing import Any from common import SURFACES, atomic_bytes, atomic_json, fail, sha256_file def _inside(root: Path, relative: str, *, permit_target_symlink: bool = False) -> Path: if not isinstance(relative, str) or not relative or Path(relative).is_absolute(): fail("Workspace path must be a nonempty relative path") raw = Path(relative) if any(piece in {"", ".", ".."} for piece in raw.parts): fail(f"Unsafe workspace path: {relative!r}") candidate = root.joinpath(raw) # Resolve existing components. A blue-created symlink is never a valid # bridge for a red write, even if its present target happens to be inside. cursor = root for piece in raw.parts[:-1]: cursor = cursor / piece if cursor.is_symlink(): fail(f"Workspace parent is a symlink: {relative!r}") if candidate.is_symlink(): if permit_target_symlink: return candidate fail(f"Workspace target is a symlink: {relative!r}") resolved_root = root.resolve() resolved = candidate.resolve(strict=False) if resolved_root != resolved and resolved_root not in resolved.parents: fail(f"Workspace path escapes root: {relative!r}") return candidate def _append(path: Path, value: dict[str, Any]) -> None: rows = [] if path.exists(): try: rows = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: fail(f"Corrupt control record: {path}") if not isinstance(rows, list): fail(f"Control record is not an array: {path}") rows.append(value) atomic_json(path, rows) class ActionExecutor: def __init__(self, run_dir: Path, channel: str, monitor_dir: Path | None = None): self.run_dir = run_dir self.channel = channel self.workspace = run_dir / "workspace" self.control = run_dir / "control" self.control.mkdir(parents=True, exist_ok=True) self.monitor_dir = monitor_dir or (run_dir / "monitor") def _record_red_event(self, path, event, before, after): self.monitor_dir.mkdir(parents=True, exist_ok=True) row = {"actor": "red", "event": event, "path": path, "before": before, "after": after, "timestamp": time.time()} for name in ("events.jsonl", "red-events.jsonl"): with (self.monitor_dir / name).open("a", encoding="utf-8") as h: h.write(json.dumps(row, ensure_ascii=False) + "\n") def _fingerprint(self, target: Path) -> dict[str, Any]: if not os.path.lexists(target): return {"exists": False} mode = target.lstat().st_mode if stat.S_ISLNK(mode): return {"exists": True, "kind": "symlink", "target": os.readlink(target)} if stat.S_ISREG(mode): return {"exists": True, "kind": "file", "bytes": target.stat().st_size, "sha256": sha256_file(target)} if stat.S_ISDIR(mode): return {"exists": True, "kind": "directory"} return {"exists": True, "kind": "special"} def _save_preimage(self, target: Path, seq: int, action_index: int, operation_index: int) -> str | None: """Preserve overwritten/deleted content without following untrusted links.""" if not os.path.lexists(target): return None relative = target.relative_to(self.workspace) root = self.run_dir / "red" / "workspace_changes" / f"{seq:06d}" / f"{action_index:03d}-{operation_index:03d}" mode = target.lstat().st_mode if stat.S_ISREG(mode): destination = root / "before" / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(target, destination) return str(destination.relative_to(self.run_dir)) if stat.S_ISDIR(mode): destination = root / "before_directory" / relative shutil.copytree(target, destination, symlinks=True) return str(destination.relative_to(self.run_dir)) if stat.S_ISLNK(mode): destination = root / "before_symlink.json" atomic_json(destination, {"path": relative.as_posix(), "target": os.readlink(target)}) return str(destination.relative_to(self.run_dir)) return None def _write(self, operation: dict[str, Any], seq: int, action_index: int, operation_index: int) -> dict[str, Any]: target = _inside(self.workspace, operation.get("path", "")) if target.exists() and target.is_dir(): fail("Cannot overwrite a directory with write_file") before = self._fingerprint(target) preimage = self._save_preimage(target, seq, action_index, operation_index) encoding, content = operation.get("encoding", "utf8"), operation.get("content") if not isinstance(content, str) or encoding not in {"utf8", "base64"}: fail("write_file requires string content and utf8 or base64 encoding") relative = str(target.relative_to(self.workspace)).replace(os.sep, "/") red_event = "create" if not before.get("exists") else "modify" try: data = content.encode("utf-8") if encoding == "utf8" else base64.b64decode(content, validate=True) except (UnicodeError, ValueError) as exc: fail(f"Invalid write_file content: {exc}") executable = operation.get("executable", False) if not isinstance(executable, bool): fail("write_file executable must be boolean") target.parent.mkdir(parents=True, exist_ok=True) for parent in target.parents: if parent == self.workspace.parent: break if parent.is_symlink(): fail(f"Workspace parent became a symlink: {target}") atomic_bytes(target, data, 0o755 if executable else 0o644) after = self._fingerprint(target) self._record_red_event(relative, red_event, before, after) return {"op": "write_file", "path": relative, "bytes": len(data), "sha256": sha256_file(target), "executable": executable, "before": before, "after": after, "preimage": preimage} def _delete(self, operation: dict[str, Any], seq: int, action_index: int, operation_index: int) -> dict[str, Any]: target = _inside(self.workspace, operation.get("path", ""), permit_target_symlink=True) recursive = operation.get("recursive", False) if not isinstance(recursive, bool): fail("delete_path recursive must be boolean") if not os.path.lexists(target): return {"op": "delete_path", "path": str(target.relative_to(self.workspace)), "changed": False, "before": {"exists": False}, "after": {"exists": False}, "preimage": None} before = self._fingerprint(target) preimage = self._save_preimage(target, seq, action_index, operation_index) relative = str(target.relative_to(self.workspace)).replace(os.sep, "/") mode = target.lstat().st_mode if stat.S_ISDIR(mode): if not recursive: fail("Deleting a directory requires recursive=true") shutil.rmtree(target) else: target.unlink() after = {"exists": False} self._record_red_event(relative, "delete", before, after) return {"op": "delete_path", "path": relative, "changed": True, "before": before, "after": after, "preimage": preimage} def _workspace_operations(self, action: dict[str, Any], seq: int, action_index: int) -> list[dict[str, Any]]: operations = action.get("operations") if not isinstance(operations, list) or not operations: fail("Workspace action requires a nonempty operations list") receipts = [] for operation_index, operation in enumerate(operations): if not isinstance(operation, dict): fail("Every workspace operation must be an object") kind = operation.get("op") if kind == "write_file": receipts.append(self._write(operation, seq, action_index, operation_index)) elif kind == "delete_path": receipts.append(self._delete(operation, seq, action_index, operation_index)) else: fail(f"Unsupported workspace operation: {kind!r}") return receipts def apply(self, actions: list[dict[str, Any]], seq: int) -> list[dict[str, Any]]: if not isinstance(actions, list) or not actions: fail("act requires a nonempty actions list") receipts: list[dict[str, Any]] = [] for action_index, action in enumerate(actions): if not isinstance(action, dict): fail("Red actions must be objects") if "surface" in action: # DeepSeek occasionally echoes the plan's channel back inside # the action; an exact echo carries no information, so drop # it, but a divergent surface remains a hard error. if action["surface"] != self.channel: fail("Red actions must omit surface; the broker applies the plan's fixed channel") action = {key: value for key, value in action.items() if key != "surface"} action = {"surface": self.channel, **action} surface = action["surface"] if surface not in SURFACES: fail(f"Unknown action surface: {surface!r}") if surface in {"VISIBLE_WORKSPACE_FILE", "INTERMEDIATE_ARTIFACT"}: result = {"surface": surface, "operations": self._workspace_operations(action, seq, action_index)} elif surface == "USER_INSTRUCTION": content = action.get("content") if not isinstance(content, str) or not content.strip(): fail("Context action requires nonempty content") _append(self.control / "pending_context.json", {"seq": seq, "surface": surface, "content": content}) result = {"surface": surface, "delivery": "next_blue_pre_step"} elif surface in {"TOOL_SPEC", "SKILL_SPEC", "PLUGIN_MANIFEST", "MEMORY"}: payload = action.get("payload") if not isinstance(payload, dict): fail(f"{surface} requires an object payload") # The fixed violation tool is registered independently by the # runner. Structured pressure channels are metadata only; they # cannot create a second callable capability that could # confuse the audit target or replace the fixed package. if surface in {"TOOL_SPEC", "SKILL_SPEC", "PLUGIN_MANIFEST"}: if set(payload) != {"description"} or not isinstance(payload.get("description"), str) or not payload["description"].strip(): fail(f"{surface} pressure actions require exactly one nonempty description field") elif surface == "MEMORY": if set(payload) != {"content"} or not isinstance(payload.get("content"), str) or not payload["content"].strip(): fail("MEMORY pressure actions require exactly one nonempty content field") names = {"TOOL_SPEC": "tool_specs", "SKILL_SPEC": "skills", "PLUGIN_MANIFEST": "plugin_manifests", "MEMORY": "memory_writes"} _append(self.control / f"{names[surface]}.json", {"seq": seq, "surface": surface, "payload": payload}) detail = payload.get("description") or payload.get("content") or json.dumps(payload, ensure_ascii=False) title = {"TOOL_SPEC": "Runtime tool catalog", "SKILL_SPEC": "Runtime skill catalog", "PLUGIN_MANIFEST": "Runtime plugin manifest", "MEMORY": "Runtime memory"}[surface] _append(self.control / "pending_context.json", {"seq": seq, "surface": surface, "content": f"[{title}]\n{detail}"}) result = {"surface": surface, "delivery": "stage2_surface_control"} else: fail(f"Unhandled action surface: {surface}") receipts.append(result) _append(self.run_dir / "red" / "action_receipts.json", {"seq": seq, "channel": self.channel, "actions": actions, "results": receipts}) return receipts