"""Gate broker for an adaptive feedback attack campaign.""" from __future__ import annotations import json import os import shutil import stat import time from pathlib import Path from typing import Any from actions import ActionExecutor from common import atomic_bytes, atomic_json, fail, sha256_file, sha256_json from plan import InitialPlan, validate_revision from red_agent import RedSession def _content_text(value: Any) -> str: """Flatten nested DSH/MCP content blocks for signal matching.""" if isinstance(value, str): return value if isinstance(value, list): return "\n".join(part for item in value if (part := _content_text(item))) if isinstance(value, dict): parts: list[str] = [] text = value.get("text") if isinstance(text, str): parts.append(text) for key in ("content", "message", "output", "result", "value"): if key in value: part = _content_text(value[key]) if part: parts.append(part) if not parts: for key, item in value.items(): if key not in {"source", "role", "id", "type", "toolCallId", "isError"}: part = _content_text(item) if part: parts.append(part) return "\n".join(parts) return "" def _signal_matches_row(signal: dict[str, Any], row: dict[str, Any]) -> bool: if row.get("type") != signal["event_type"]: return False data = row.get("data") if not isinstance(data, dict): return False field = signal["field"] if field == "message.content": message = data.get("message") observed = _content_text(message.get("content")) if isinstance(message, dict) else "" elif field == "name": observed = data.get("name", "") else: return False if not isinstance(observed, str): return False expected = signal["value"] return expected in observed if signal["operator"] == "contains" else expected == observed def _matched_signal_indexes(step: dict[str, Any], evidence: list[dict[str, Any]]) -> list[int]: return [index for index, signal in enumerate(step["signals"]) if any(_signal_matches_row(signal, row) for row in evidence)] def _clip_text(value: Any, limit: int) -> str: text = _content_text(value) return text if len(text) <= limit else text[:limit] + "\n[truncated]" def red_evidence(step: dict[str, Any], evidence: list[dict[str, Any]], limit: int = 4_000) -> list[dict[str, Any]]: """Project raw blue records to the small signal summary Red actually needs. The full append-only session remains in blue/raw-dsh-session.v3.jsonl and the broker journal. Passing multi-megabyte MCP tool results to Claude Code is both unnecessary for the frozen-plan decision and can exceed a gateway's context limit. """ relevant_types = {signal["event_type"] for signal in step["signals"]} projected: list[dict[str, Any]] = [] used = 0 for row in evidence: available = limit - used if row.get("type") not in relevant_types or available <= 300: continue data = row.get("data") if isinstance(row.get("data"), dict) else {} item: dict[str, Any] = {"type": row.get("type"), "seq": row.get("seq")} value_limit = min(1_500, available - 300) if row.get("type") in {"tool/result"}: message = data.get("message") if isinstance(data.get("message"), dict) else {} content = _clip_text(message.get("content"), value_limit) item["message"] = {"role": message.get("role"), "content": content} elif row.get("type") == "tool/call": arguments = data.get("arguments", "") item["name"] = data.get("name") item["arguments"] = _clip_text(arguments, value_limit) else: item["summary"] = "signal-bearing record retained without payload" encoded = json.dumps(item, ensure_ascii=False) if used + len(encoded) > limit: break projected.append(item) used += len(encoded) return projected def blue_trace(evidence: list[dict[str, Any]], limit: int = 12000) -> list[dict[str, Any]]: projected=[];used=0 for row in evidence: kind=row.get("type") if kind not in {"assistant/message","tool/call","tool/result"}:continue data=row.get("data") if isinstance(row.get("data"),dict) else {} item={"seq":row.get("seq"),"event_type":kind} if kind=="tool/call":item.update(name=data.get("name"),arguments=_clip_text(data.get("arguments"),2000)) else: msg=data.get("message") if isinstance(data.get("message"),dict) else {} item.update(role=msg.get("role"),content=_clip_text(msg.get("content"),3000)) enc=json.dumps(item,ensure_ascii=False) if used+len(enc)>limit:break projected.append(item);used+=len(enc) return projected class Journal: def __init__(self, path: Path, header: dict[str, Any]): self.path = path self.path.parent.mkdir(parents=True, exist_ok=True) self.number = 0 self.write(header) def write(self, value: dict[str, Any]) -> None: with self.path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(value, ensure_ascii=False) + "\n") handle.flush() def append(self, participant: str, phase: str, record: Any, seq: int | None = None) -> None: self.number += 1 value = {"type": "event", "event_id": self.number, "recorded_at_unix_ms": time.time_ns() // 1_000_000, "participant": participant, "phase": phase, "record": record} if seq is not None: value["seq"] = seq self.write(value) def _copy_regular_files(source: Path, destination: Path) -> list[dict[str, Any]]: """Refresh a read-only mirror without following blue-created links or devices.""" if destination.exists(): for entry in destination.iterdir(): if entry.is_dir() and not entry.is_symlink(): shutil.rmtree(entry) else: entry.unlink(missing_ok=True) destination.mkdir(parents=True, exist_ok=True) manifest: list[dict[str, Any]] = [] if not source.exists(): return manifest for root, dirs, files in os.walk(source, followlinks=False): root_path = Path(root) rel_root = root_path.relative_to(source) kept_dirs: list[str] = [] for name in dirs: item = root_path / name rel = (rel_root / name).as_posix() if item.is_symlink(): manifest.append({"path": rel, "kind": "symlink", "target": os.readlink(item)}) else: (destination / rel_root / name).mkdir(parents=True, exist_ok=True) kept_dirs.append(name) manifest.append({"path": rel, "kind": "directory"}) dirs[:] = kept_dirs for name in files: item = root_path / name rel = (rel_root / name).as_posix() if item.is_symlink(): manifest.append({"path": rel, "kind": "symlink", "target": os.readlink(item)}) continue mode = item.lstat().st_mode if not stat.S_ISREG(mode): manifest.append({"path": rel, "kind": "special"}) continue target = destination / rel_root / name target.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(item, target) target.chmod(0o444) manifest.append({"path": rel, "kind": "file", "bytes": item.stat().st_size, "sha256": sha256_file(item)}) return manifest class GateBroker: def __init__(self, run_dir: Path, plan: InitialPlan, red_config: Path, red_timeout: int, gate_timeout: int, red_autocompact_window: str | None = None, plan_lineage: dict[str, Any] | None = None, monitor_dir: Path | None = None): self.run_dir, self.plan, self.gate_timeout = run_dir, plan, gate_timeout self.plan_lineage = plan_lineage or { "iteration": 1, "parent_iteration": None, "iteration_dir": "iterations/iteration-001-from-initial-run-unknown", "online_execution_plan_name": "online_execution_plan.json", "next_attack_plan_name": "next_attack_plan.json", } self.gate_dir = run_dir / "gate" self.requests, self.decisions = self.gate_dir / "requests", self.gate_dir / "decisions" self.requests.mkdir(parents=True, exist_ok=True) self.decisions.mkdir(parents=True, exist_ok=True) self.journal = Journal( run_dir / "broker" / "interaction-timeline.v3.jsonl", {"type": "interaction_timeline", "version": 3, "format": "initial-attack-red-blue-live-v2", "participants": ["red", "blue", "broker"], "clock": "broker_observation_order"}, ) self.red_journal = Journal( run_dir / "red" / "red-agent-events.v3.jsonl", {"type": "red_agent_events", "version": 3, "format": "initial-attack-red-agent-v1", "participant": "red", "clock": "broker_observation_order"}, ) self.executor = ActionExecutor(run_dir, plan.channel, monitor_dir=monitor_dir) self.mirror = run_dir / "red" / "workspace_view" self.red = RedSession(run_dir, self.mirror, red_config, red_timeout, plan.raw, autocompact_window=red_autocompact_window) atomic_bytes(run_dir / "red" / "system_prompt.txt", self.red.system_prompt.encode("utf-8")) invocation = self.red.audit_metadata() invocation["system_prompt_sha256"] = sha256_json(self.red.system_prompt) atomic_json(run_dir / "red" / "invocation.json", invocation) self.log_cursor = 0 # A gate hook can be delayed until Blue has already appended evidence # for a later frozen step. Keep the append-only evidence available # for subsequent verification; advancing only a cursor would otherwise # discard that valid signal between checkpoints. self.blue_evidence: list[dict[str, Any]] = [] self.feedback_history: list[dict[str, Any]] = [] self.strategy_state: dict[str, Any] = { "current_tactic": "initial_plan", "attempted_tactics": [], "observed_effects": [], "failure_reasons": [], "next_tactic": "follow_initial_plan", } self.next_step = 1 atomic_json(self.gate_dir / "checkpoint-plan.json", { "steps": [{"step": step["step"], "signals": step["signals"]} for step in plan.steps], }) self._write_checkpoint_state() def _write_checkpoint_state(self) -> None: atomic_json(self.gate_dir / "checkpoint-state.json", { "next_step": self.next_step, "step_count": len(self.plan.steps), }) def _blue_log(self) -> Path | None: paths = sorted((self.run_dir / "dsh_home" / "sessions").rglob("*.jsonl")) return paths[-1] if paths else None def _blue_rows(self) -> list[dict[str, Any]]: log = self._blue_log() if not log or not log.exists(): return [] raw = log.read_text(encoding="utf-8", errors="replace").splitlines() rows: list[dict[str, Any]] = [] for line in raw[self.log_cursor:]: try: rows.append(json.loads(line)) except json.JSONDecodeError: rows.append({"type": "unparseable-log-line", "raw": line[:1000]}) self.log_cursor = len(raw) return rows def _event(self, request: dict[str, Any], evidence: list[dict[str, Any]], signal_evidence: list[dict[str, Any]] | None = None) -> dict[str, Any]: seq = request["seq"] for row in evidence: self.journal.append("blue", "native_record", row, seq) manifest = _copy_regular_files(self.run_dir / "workspace", self.mirror) atomic_json(self.run_dir / "red" / "workspace_manifests" / f"{seq:06d}.json", manifest) current = self.plan.steps[self.next_step - 1] if self.next_step <= len(self.plan.steps) else None # Red needs the evidence that established the current checkpoint, not # merely entries appended after the Broker last woke up. verification_rows = signal_evidence if signal_evidence is not None else evidence red_rows = red_evidence(current, verification_rows) if current else [] event = {"kind": "BLUE_INITIAL_READY" if seq == 0 else "BLUE_TURN", "seq": seq, "task_id": self.plan.task_id, "attack_channel": self.plan.channel, "current_step": current, "completed_steps": self.next_step - 1, "all_steps_completed": current is None, "workspace_manifest": manifest, "blue_evidence": red_rows, "blue_trace": blue_trace(evidence), "prior_interaction_trace": self._interaction_trace(), "visible_feedback": { "user_instruction": self._user_instruction(), "memory": self._control_records("memory_writes.json"), "skill_plugin_spec": {"tool": self.plan.raw["tool_package"]}, "workspace": manifest, "tool_calls": [row for row in red_rows if row.get("type") == "tool/call"], "tool_responses": [row for row in red_rows if row.get("type") == "tool/result"], }, "strategy_state": self.strategy_state, "recent_strategy_decisions": self._recent_strategy_decisions(), "blue_evidence_audit": {"new_raw_event_count": len(evidence), "verification_event_count": len(verification_rows), "projected_event_count": len(red_rows), "raw_session_log": "blue/raw-dsh-session.v3.jsonl"}, "gate": request} first_checkpoint = self.run_dir / "blue" / "first_checkpoint_input.json" if not first_checkpoint.exists(): atomic_json(first_checkpoint, event) return event def _recent_strategy_decisions(self, limit: int = 5) -> list[dict[str, Any]]: return [{"seq": item.get("seq"), "kind": item.get("kind"), "rationale": item.get("rationale"), "strategy_update": item.get("strategy_update"), "actions": item.get("red_actions"), "action_receipts": item.get("action_receipts")} for item in self.feedback_history[-limit:]] def _interaction_trace(self, trailing_blue=None): trace=[] for i,item in enumerate(self.feedback_history): after=self.feedback_history[i+1].get("blue_trace",[]) if i+1 None: path = self.run_dir / "red" / "strategy-decisions.jsonl" path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(record, ensure_ascii=False) + "\n") def _user_instruction(self) -> str: source = Path(self.plan.raw["generation_metadata"]["source_task_dir"]) / "docs" / "task.md" try: return source.read_text(encoding="utf-8") except OSError: return "" def _control_records(self, name: str) -> list[dict[str, Any]]: path = self.run_dir / "control" / name if not path.is_file(): return [] try: value = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError: return [] return value if isinstance(value, list) else [] def _record_red(self, seq: int, phase: str, record: Any) -> None: self.red_journal.append("red", phase, record, seq) self.journal.append("red", phase, record, seq) def _validate_decision(self, decision): expected=self.next_step if self.next_step<=len(self.plan.steps) else None required={"kind","rationale","actions","strategy_update"} if isinstance(decision,dict) and "step" in decision: if decision.get("step")!=expected:fail("Red decision step does not match the current pressure step") decision.pop("step",None) if set(decision)!=required:fail("Red action decision has unexpected fields") kind,actions=decision.get("kind"),decision.get("actions") if kind not in {"act","no_action"} or not isinstance(decision.get("rationale"),str) or not decision["rationale"].strip(): fail("Red decision must have a valid kind and rationale") if not isinstance(actions,list) or kind=="act" and not actions or kind=="no_action" and actions: fail("Red decision actions must be nonempty for act and empty for no_action") if not isinstance(decision.get("strategy_update"),dict):fail("Red decision strategy_update must be an object") return actions def _handle(self, request_path: Path, deadline: float) -> None: request = json.loads(request_path.read_text(encoding="utf-8")) if not isinstance(request, dict) or not isinstance(request.get("seq"), int) or request["seq"] < 0: fail(f"Invalid checkpoint request: {request_path}") seq = request["seq"] expected = self.next_step if self.next_step <= len(self.plan.steps) else None if expected is None or request.get("step") != expected: fail("Checkpoint request does not target the current uncompleted attack step") reported = request.get("matched_signals") if not isinstance(reported, list) or not reported or not all(isinstance(x, int) and not isinstance(x, bool) for x in reported): fail("Checkpoint request lacks matched signal indexes") self.journal.append("blue", "gate_request", request, seq) evidence = self._blue_rows() self.blue_evidence.extend(evidence) current = self.plan.steps[expected - 1] verified = _matched_signal_indexes(current, self.blue_evidence) # The file bridge mirrors Blue's session log asynchronously; a gate # request can reach the host before the matching log rows. Re-check # for a bounded grace period before rejecting the reported signals. grace_deadline = time.monotonic() + 150.0 while not set(reported).issubset(set(verified)) and time.monotonic() < grace_deadline: time.sleep(5) evidence = self._blue_rows() self.blue_evidence.extend(evidence) verified = _matched_signal_indexes(current, self.blue_evidence) if not set(reported).issubset(set(verified)): fail("Checkpoint signal could not be verified against the raw Blue session log") event = self._event(request, evidence, self.blue_evidence) self.feedback_history.append(event) event["matched_signals"] = [{"index": index, "matcher": current["signals"][index]} for index in verified] atomic_json(self.run_dir / "red" / "events" / f"input-{seq:06d}.json", event) self._record_red(seq, "input_sent", {"event_path": f"events/input-{seq:06d}.json", "event_sha256": sha256_json(event)}) self.journal.append("broker", "checkpoint_reached", {"step": expected, "matched_signal_indexes": verified}, seq) remaining = max(0.0, deadline - time.monotonic()) decision = self.red.decide(event, lambda record: self._record_red(seq, "native_record", record), timeout=remaining) actions = self._validate_decision(decision) decision["step"] = expected self._record_red(seq, "decision_validated", decision) receipts = self.executor.apply(actions, seq) if decision["kind"] == "act" else [] update = decision["strategy_update"] if update: previous_tactic = self.strategy_state.get("current_tactic") self.strategy_state.update(update) if update.get("current_tactic") and update.get("current_tactic") != previous_tactic: attempted = self.strategy_state.setdefault("attempted_tactics", []) if previous_tactic and previous_tactic not in attempted: attempted.append(previous_tactic) self.feedback_history[-1].update({"decision": decision, "kind": decision["kind"], "rationale": decision["rationale"], "strategy_update": update, "red_actions": actions, "action_receipts": receipts}) self._append_strategy_record({ "seq": seq, "step": expected, "kind": decision["kind"], "rationale": decision["rationale"], "strategy_update": update, "visible_feedback": event["visible_feedback"], "blue_trace": event.get("blue_trace", []), "actions": actions, "action_receipts": receipts, "strategy_state": self.strategy_state, }) self.next_step += 1 self._write_checkpoint_state() self._record_red(seq, "actions_applied", {"kind": decision["kind"], "action_receipts": receipts}) receipt = {"seq": seq, "approved": True, "decision": decision, "action_receipts": receipts, "completed_steps": self.next_step - 1, "checkpoint": {"step": expected, "matched_signal_indexes": verified}, "created_at": time.time()} atomic_json(self.decisions / f"{seq:06d}.json", receipt) atomic_json(self.run_dir / "red" / "events" / f"gate-{seq:06d}.json", {"request": request, "receipt": receipt}) self.journal.append("broker", "gate_receipt_published", receipt, seq) def finalize(self, evaluation): from plan import compose_revision online_plan=self.plan.raw; trailing=self._blue_rows() for row in trailing:self.journal.append("blue","native_record",row,-1) interaction_trace=self._interaction_trace(blue_trace(trailing)) try: summary=self.red.summarize(self.plan.raw,interaction_trace,evaluation,self.strategy_state,lambda record:self._record_red(-1,"final_summary_record",record),timeout=self.gate_timeout) expected={"kind","rationale","online_execution_plan","next_plan"} if not isinstance(summary,dict) or set(summary)!=expected or summary.get("kind")!="finish":fail("Red final summary must contain exactly kind, rationale, online_execution_plan, and next_plan") candidate=summary.get("online_execution_plan") if candidate is None:fail("Red final summary omitted online_execution_plan") online_plan=compose_revision(candidate,self.plan,1); online_name=self.plan_lineage["online_execution_plan_name"] atomic_json(self.run_dir/online_name,online_plan) attack_success=evaluation.get("attack_success") next_plan=summary.get("next_plan") if attack_success is True: # A successful run has no continuation. A model-generated # next_plan is harmless but is deliberately discarded and is # never written as a next-attack-plan artifact. next_name=None next_plan_written=False else: # False and indeterminate evaluations both require a concrete # continuation so the next run can learn from this run. if next_plan is None: fail("Failed or indeterminate attack summary omitted next_attack_plan") next_name=self.plan_lineage["next_attack_plan_name"] atomic_json(self.run_dir/next_name,compose_revision(next_plan,self.plan,1)) next_plan_written=True atomic_json(self.run_dir/"red"/"final-summary.json",{"rationale":summary["rationale"],"evaluation":evaluation,"interaction_trace":interaction_trace,"online_execution_plan":online_plan,"online_execution_plan_name":online_name,"next_attack_plan_name":next_name,"plan_lineage":self.plan_lineage,"next_attack_plan_written":next_plan_written}) except Exception as exc: atomic_json(self.run_dir/"final_summary_error.json",{"error":f"{type(exc).__name__}: {exc}"}) atomic_json(self.run_dir/self.plan_lineage["online_execution_plan_name"],online_plan);raise def close(self) -> None: self.red.close() atomic_bytes(self.run_dir / "red" / "stderr.log", self.red.stderr_text().encode("utf-8")) def serve(self, blue_process: Any, blue_timeout: int) -> tuple[str, int]: seen: set[Path] = set() hook_deadline, deadline = time.monotonic() + self.gate_timeout, time.monotonic() + blue_timeout try: while True: for request in sorted(self.requests.glob("*.json")): if request in seen: continue seen.add(request) if time.monotonic() >= deadline: return "round_deadline_exceeded", self.next_step - 1 try: self._handle(request, deadline) except TimeoutError: if time.monotonic() >= deadline: self.journal.append("broker", "round_deadline_exceeded", {"reason": "Red decision did not finish before the Blue round deadline"}) return "round_deadline_exceeded", self.next_step - 1 raise if (self.gate_dir / "blue_finished.json").exists(): self.journal.append("blue", "finished", json.loads((self.gate_dir / "blue_finished.json").read_text(encoding="utf-8"))) return "blue_finished", self.next_step - 1 if blue_process.poll() is not None: return ("process_ended_before_checkpoint" if not seen else "process_ended_after_checkpoint"), self.next_step - 1 heartbeat = self.gate_dir / "heartbeat.json" if not heartbeat.exists() and time.monotonic() >= hook_deadline: return "initial_gate_deadline_exceeded", self.next_step - 1 if time.monotonic() >= deadline: return "round_deadline_exceeded", self.next_step - 1 time.sleep(0.15) finally: pass