File size: 9,970 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
"""Audited declarative mutations for real sandbox channels and the workspace."""
from __future__ import annotations

import json
import os
import stat
from pathlib import Path
from typing import Any

from common import atomic_bytes, atomic_json, fail, sha256_file


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 deployment record: {path}")
    if not isinstance(rows, list):
        fail(f"Deployment 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.sandbox = None
        self.workspace = run_dir / "workspace"
        self.control = run_dir / "control"
        self.control.mkdir(parents=True, exist_ok=True)
        self.deployment_log = run_dir / "runtime" / "deployment_operations.json"

    def _workspace_target(self, absolute: str) -> Path:
        prefix = "/run/workspace/"
        if not isinstance(absolute, str) or not absolute.startswith(prefix):
            fail("Workspace action path must be under /run/workspace")
        relative = Path(absolute[len(prefix):])
        if not relative.parts or any(piece in {"", ".", ".."} for piece in relative.parts):
            fail(f"Unsafe workspace path: {absolute!r}")
        target = self.workspace / relative
        cursor = self.workspace
        for piece in relative.parts[:-1]:
            cursor = cursor / piece
            if cursor.is_symlink():
                fail(f"Workspace parent is a symlink: {absolute!r}")
        if target.is_symlink():
            fail(f"Workspace target is a symlink: {absolute!r}")
        resolved_root = self.workspace.resolve()
        resolved = target.resolve(strict=False)
        if resolved_root != resolved and resolved_root not in resolved.parents:
            fail(f"Workspace path escapes root: {absolute!r}")
        return target

    def _save_preimage(self, target: Path, seq: int, action_index: int) -> str | None:
        if not os.path.lexists(target):
            return None
        mode = target.lstat().st_mode
        if not stat.S_ISREG(mode):
            fail("Only regular files can be modified")
        relative = target.relative_to(self.workspace)
        destination = self.run_dir / "red" / "workspace_changes" / f"{seq:06d}" / f"{action_index:03d}" / "before" / relative
        destination.parent.mkdir(parents=True, exist_ok=True)
        destination.write_bytes(target.read_bytes())
        return str(destination.relative_to(self.run_dir))

    def _apply_user_message(self, payload: dict[str, Any], seq: int, action_index: int) -> dict[str, Any]:
        """Deliver a Red-authored user turn to the live Blue session.

        The in-sandbox runner watches /run/control/red_user_turns/ and injects
        each file as a session/prompt on the running Blue session, so Red can
        steer Blue mid-task with the authority of the user.
        """
        if self.sandbox is None:
            fail("user_message requires a live Blue sandbox")
        text = payload.get("text")
        if not isinstance(text, str) or not text.strip():
            fail("user_message payload.text must be a nonempty string")
        remote = f"/run/control/red_user_turns/{seq:06d}-{action_index:03d}.json"
        data = json.dumps({"text": text}, ensure_ascii=False).encode("utf-8")
        self.sandbox._put_bytes(remote, data, mode="644")
        return {"op": "user_message", "deployment": "user_turn_mid_session",
                "bytes": len(data), "remote": remote}

    def _apply_memory_live(self, action_type: str, payload: dict[str, Any], seq: int, action_index: int) -> dict[str, Any]:
        """Read-modify-write the live sandbox memory.json during the session.

        The memory MCP server resolves read_graph from the file on every call,
        so a mid-session rewrite is visible to Blue immediately.  The merge
        runs against the current sandbox content (including Blue's own memory
        writes), not the possibly stale host mirror.
        """
        if action_type != "patch_text":
            fail("MEMORY live actions must be patch_text")
        if self.sandbox is None:
            fail("MEMORY live action requires a live Blue sandbox")
        from real_channel_runtime import _apply_memory_patch
        remote = payload["path"]
        if not isinstance(remote, str) or not remote.startswith("/run/workspace/"):
            fail(f"MEMORY live action path must be under /run/workspace: {remote}")
        work = self.run_dir / "red" / "memory_live" / f"{seq:06d}-{action_index:03d}"
        work.mkdir(parents=True, exist_ok=True)
        current = work / "current.json"
        downloaded = True
        try:
            self.sandbox._download_file(remote, current)
        except Exception:
            downloaded = False
        if not downloaded:
            if payload["find"]:
                fail(f"MEMORY live target missing in sandbox and find is nonempty: {remote}")
            current.write_text("", encoding="utf-8")
        try:
            _apply_memory_patch(payload, current)
        except RuntimeError as exc:
            fail(f"MEMORY live patch failed: {exc}")
        data = current.read_bytes()
        self.sandbox._put_bytes(remote, data, mode="644")
        # Keep the host mirror consistent for later patches and receipts.
        mirror = self._workspace_target(remote)
        mirror.parent.mkdir(parents=True, exist_ok=True)
        atomic_bytes(mirror, data, 0o644)
        return {"op": action_type, "path": remote, "bytes": len(data),
                "sha256": sha256_file(current), "deployment": "memory_live_mid_session",
                "downloaded": downloaded}

    def _apply_workspace(self, action_type: str, payload: dict[str, Any], seq: int, action_index: int) -> dict[str, Any]:
        target = self._workspace_target(payload["path"])
        before = {"exists": target.exists(), "sha256": sha256_file(target) if target.is_file() else None}
        preimage = self._save_preimage(target, seq, action_index) if target.exists() else None
        if action_type == "write_file":
            data = payload["text"].encode("utf-8")
        elif action_type == "append_file":
            previous = target.read_bytes() if target.exists() else b""
            data = previous + payload["text"].encode("utf-8")
        else:
            if target.is_file():
                previous_text = target.read_text(encoding="utf-8")
            elif payload["find"] or not (payload.get("append_if_absent") or payload.get("prepend_if_absent")):
                fail(f"patch_text target does not exist: {payload['path']}")
            else:
                previous_text = ""
            find = payload["find"]
            if find:
                count = previous_text.count(find)
                if count != 1:
                    fail(f"patch_text find-string must occur exactly once in {payload['path']}; found {count}")
                data = previous_text.replace(find, payload["replace"], 1).encode("utf-8")
            elif payload.get("append_if_absent"):
                data = (previous_text + payload["replace"]).encode("utf-8")
            elif payload.get("prepend_if_absent"):
                data = (payload["replace"] + previous_text).encode("utf-8")
            else:
                fail("patch_text requires a find string or explicit append/prepend")
        atomic_bytes(target, data, 0o644)
        return {"op": action_type, "path": payload["path"], "bytes": len(data),
                "sha256": sha256_file(target), "before": before, "preimage": preimage}

    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 set(action) != {"action_type", "payload"}:
                fail("Red actions must contain exactly action_type and payload")
            action_type, payload = action["action_type"], action["payload"]
            if action_type == "user_message":
                if self.channel != "USER_INSTRUCTION":
                    fail("user_message is only valid for the USER_INSTRUCTION channel")
                result = self._apply_user_message(payload, seq, action_index)
            elif self.channel in {"VISIBLE_WORKSPACE_FILE", "INTERMEDIATE_ARTIFACT"}:
                result = self._apply_workspace(action_type, payload, seq, action_index)
            elif self.channel == "MEMORY":
                if self.sandbox is None:
                    # session/start deployment: the sandbox-side apply_prestart
                    # applies the frozen actions from deployment_operations.json
                    # before Blue boots; there is nothing live to patch yet.
                    result = {"op": action_type, "path": payload["path"],
                              "deployment": "real_channel_before_blue_start"}
                else:
                    result = self._apply_memory_live(action_type, payload, seq, action_index)
            else:
                result = {"op": action_type, "path": payload["path"],
                          "deployment": "real_channel_before_blue_start"}
            _append(self.deployment_log, {"seq": seq, "channel": self.channel,
                                          "action_type": action_type, "payload": payload})
            receipts.append(result)
        _append(self.run_dir / "red" / "action_receipts.json", {
            "seq": seq, "channel": self.channel, "actions": actions, "results": receipts})
        return receipts