File size: 11,341 Bytes
04d5e92
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
"""Broker-owned, audited mutation primitives for one isolated blue workspace."""
from __future__ import annotations

import base64
import json
import os
import shutil
import stat
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):
        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)

    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")
        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)
        return {"op": "write_file", "path": str(target.relative_to(self.workspace)), "bytes": len(data),
                "sha256": sha256_file(target), "executable": executable, "before": before,
                "after": self._fingerprint(target), "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)
        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()
        return {"op": "delete_path", "path": str(target.relative_to(self.workspace)), "changed": True,
                "before": before, "after": {"exists": False}, "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) or "surface" in action:
                fail("Red actions must omit surface; the plan's fixed channel is applied by the broker")
            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