File size: 11,181 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
208
209
210
"""Run rule-based and Claude Code semantic evaluators over a completed run."""
from __future__ import annotations
import json
import subprocess
import sys
import shutil
from pathlib import Path
from typing import Any
from common import atomic_json, sha256_file
from rule_based_judge import pg_scan, workspace_scan
from marker_runtime import load_marker
from semantic_evaluation import evaluate_semantic

JUDGE = Path(__file__).with_name("rule_based_judge.py")
SEMANTIC_JUDGE = Path(__file__).with_name("semantic_evaluation.py")

DEFAULT_MARKER = load_marker()

def capture_prerun_marker_counts(run_dir: Path, marker: str = DEFAULT_MARKER) -> dict[str, Any]:
    # Capture the marker baseline after setup/red start actions and before Blue acts.
    pg = pg_scan(marker, str(run_dir))
    workspace_hits, workspace_total = workspace_scan(str(run_dir / "workspace"), marker)
    pg_total = sum(max(0, int((value or {}).get("count", 0)))
                   for value in pg.values())
    counts = {
        "pg": pg_total,
        "workspace": workspace_total,
        "marker": marker,
        "pg_by_database": pg,
        "workspace_hits": workspace_hits,
        "captured_at": __import__("datetime").datetime.now(
            __import__("datetime").timezone.utc).isoformat(),
    }
    atomic_json(run_dir / "manifest" / "prerun_marker_counts.json", counts)
    return counts

def _load_prerun_counts(run_dir: Path) -> dict[str, Any]:
    path = run_dir / "manifest" / "prerun_marker_counts.json"
    if not path.is_file():
        raise RuntimeError(f"Missing real pre-run marker baseline: {path}")
    data = json.loads(path.read_text(encoding="utf-8"))
    if not isinstance(data, dict) or not isinstance(data.get("pg"), int) or not isinstance(data.get("workspace"), int):
        raise RuntimeError(f"Invalid pre-run marker baseline: {path}")
    return data

def _nonempty(path: Path) -> bool:
    try:
        return path.is_file() and path.stat().st_size > 0
    except OSError:
        return False


def _session_candidates(run_dir: Path) -> list[Path]:
    candidates: list[Path] = []
    for base in (run_dir, run_dir / "blue", run_dir / "protocol"):
        sessions_root = base / "dsh_home" / "sessions"
        if sessions_root.is_dir():
            candidates.extend(path for path in sessions_root.rglob("*.jsonl") if _nonempty(path))
    for path in (
        run_dir / "blue" / "raw-dsh-session.v3.jsonl",
        run_dir / "protocol" / "blue" / "raw-dsh-session.v3.jsonl",
    ):
        if _nonempty(path):
            candidates.append(path)
    return sorted(set(candidates), key=lambda item: (item.stat().st_size, str(item)))


def _first_nonempty(paths: list[Path]) -> Path | None:
    return next((path for path in paths if _nonempty(path)), None)


def _save_result(evaluation_dir: Path, result: dict[str, Any]) -> dict[str, Any]:
    atomic_json(evaluation_dir / "attack-evaluation.json", result)
    (evaluation_dir / "agent-semantic-pending.json").unlink(missing_ok=True)
    return result


def evaluate_attack(run_dir: Path, task: str, plan: dict[str, Any], task_suite: str | None = None,
                    red_config: Path | None = None, semantic_timeout: int = 900) -> dict[str, Any]:
    # Evaluation happens before final organization, while standalone re-runs
    # may happen after it. Search both layouts and materialize one canonical
    # session path before invoking the judge.
    sessions = _session_candidates(run_dir)
    if not sessions:
        observed = _first_nonempty([
            run_dir / "gate" / "observed-session.jsonl",
            run_dir / "protocol" / "gate" / "observed-session.jsonl",
        ])
        if observed is not None:
            fallback = run_dir / "dsh_home" / "sessions" / "fallback" / "session.v3.jsonl"
            fallback.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(observed, fallback)
            sessions = [fallback]
    if not sessions:
        timeline = _first_nonempty([
            run_dir / "broker" / "interaction-timeline.v3.jsonl",
            run_dir / "protocol" / "broker" / "interaction-timeline.v3.jsonl",
        ])
        if timeline is not None:
            fallback = run_dir / "dsh_home" / "sessions" / "fallback" / "session.v3.jsonl"
            fallback.parent.mkdir(parents=True, exist_ok=True)
            with timeline.open("r", encoding="utf-8", errors="replace") as source, fallback.open("w", encoding="utf-8") as target:
                for line in source:
                    try:
                        event = json.loads(line)
                    except json.JSONDecodeError:
                        continue
                    if event.get("participant") == "blue" and event.get("phase") == "native_record" and isinstance(event.get("record"), dict):
                        target.write(json.dumps(event["record"], ensure_ascii=False) + "\n")
            if _nonempty(fallback):
                sessions = [fallback]
    evaluation_dir = run_dir / "evaluation"
    evaluation_dir.mkdir(parents=True, exist_ok=True)
    atomic_json(evaluation_dir / "agent-semantic-pending.json", {"status": "pending"})
    fixed = plan["fixed_attack"]
    design = plan["red_design"]
    channel_map = {
        "USER_INSTRUCTION": "User Instruction",
        "TOOL_SPEC": "Tool Spec",
        "SKILL_SPEC": "Skill Spec",
        "PLUGIN_MANIFEST": "Plugin Manifest",
        "INTERMEDIATE_ARTIFACT": "Intermediate Artifact",
        "VISIBLE_WORKSPACE_FILE": "Workspace File",
        "MEMORY": "Retained State",
    }
    primary_channel = channel_map.get(fixed["channel"], fixed["channel"])
    marker = DEFAULT_MARKER
    deployment_path = run_dir / "runtime" / "prestart_deployment_and_probes.json"
    deployment = json.loads(deployment_path.read_text(encoding="utf-8")) if deployment_path.is_file() else {}
    created_files = [operation.get("path") for operation in deployment.get("operations", []) if operation.get("path")]
    # The judge consumes a flat contributor manifest. Keep the v5 plan wrapper
    # for lineage, but expose the red design and fixed program choices at the
    # top level where rule_based_judge.py reads them.
    manifest = {
        "schema_version": "attack-v5-evaluation-manifest-v2",
        "task_id": task,
        "fixed_attack": fixed,
        "red_design": design,
        "strategy": fixed["attack_strategy"],
        "primary_channel": primary_channel,
        "channels": [primary_channel],
        "failure_mode": fixed["failure_mode"],
        "marker": marker,
        "derived_goal": design["derived_goal"],
        "target_action": design["target_action"],
        "channel_binding": design["channel_binding"],
        "exposure_probes": design["exposure_probes"],
        "deployment_evidence": {"path": str(run_dir / "runtime" / "prestart_deployment_and_probes.json"), "format": "json"},
        "mode_evidence": design["mode_evidence"],
        "expected_evidence": design["expected_evidence"],
        "anchors": design["anchors"],
        "created_files": created_files,
        "prerun_marker_counts": _load_prerun_counts(run_dir),
        "materials": {
            "trajectory": {"path": str(run_dir / "blue" / "raw-dsh-session.v3.jsonl"), "format": "jsonl", "cot_visible": False},
            "interaction_trace": {"path": str(run_dir / "broker" / "interaction-timeline.v3.jsonl"), "format": "jsonl"},
            "workspace_dump": {"path": str(run_dir / "artifacts" / "workspace"), "format": "directory"},
            "task_result": {"path": str(run_dir / "blue" / "eval_res.json"), "format": "json"},
        },
    }
    manifest_path = evaluation_dir / "evaluation_manifest.json"
    atomic_json(manifest_path, manifest)
    output_path = evaluation_dir / "rule-based-result.json"
    if not JUDGE.is_file():
        return _save_result(evaluation_dir, {"status": "evaluator_missing", "attack_success": None, "reason": str(JUDGE)})
    suite = task_suite or ("permission84" if plan.get("generation_metadata", {}).get("task_suite") == "permission84" else "finalpool")
    source_task_dir = plan.get("generation_metadata", {}).get("source_task_dir")
    if not isinstance(source_task_dir, str) or not source_task_dir:
        return _save_result(evaluation_dir, {"status": "evaluation_error", "attack_success": None,
                                            "reason": "generation_metadata.source_task_dir is required for pristine evidence"})
    session = run_dir / "blue" / "raw-dsh-session.v3.jsonl"
    if not session.is_file():
        return _save_result(evaluation_dir, {"status": "evaluation_error", "attack_success": None,
                                            "reason": f"normalized Blue session is missing: {session}"})
    completed = subprocess.run([sys.executable, str(JUDGE), "--task", task, "--task-suite", suite,
                                "--tasks-root", str(Path(source_task_dir).parent),
                                "--manifest", str(manifest_path), "--dump", str(run_dir), "--out", str(output_path),
                                "--session", str(session), "--marker", marker],
                               text=True, capture_output=True)
    (evaluation_dir / "rule-based.stdout").write_text(completed.stdout, encoding="utf-8")
    (evaluation_dir / "rule-based.stderr").write_text(completed.stderr, encoding="utf-8")
    result: dict[str, Any] = {"evaluator_path": str(JUDGE), "evaluator_sha256": sha256_file(JUDGE),
                              "semantic_evaluator_path": str(SEMANTIC_JUDGE),
                              "semantic_evaluator_sha256": sha256_file(SEMANTIC_JUDGE),
                              "manifest": str(manifest_path), "returncode": completed.returncode}
    try:
        raw = json.loads(output_path.read_text(encoding="utf-8"))
    except Exception as exc:
        result.update({"status": "evaluation_error", "attack_success": None, "reason": str(exc)})
        return _save_result(evaluation_dir, result)
    if completed.returncode != 0 or not isinstance(raw, dict) or not isinstance(raw.get("attack_success"), bool):
        result.update({"status": "evaluation_error", "attack_success": None, "raw_result": raw})
        return _save_result(evaluation_dir, result)
    config = red_config or Path(__file__).resolve().parents[1] / "attack_v3.runtime.env"
    semantic = evaluate_semantic(run_dir, plan, config,
                                 timeout=semantic_timeout, source_task_dir=Path(source_task_dir))
    result.update({
        "status": semantic["status"],
        "attack_success": semantic["attack_success"],
        "verdict": "SUCCESS" if semantic["attack_success"] is True else "FAILED" if semantic["attack_success"] is False else "ERROR",
        "reason": semantic["reason"],
        "delivery_failure": bool(raw.get("delivery_failure")),
        "rule_based_attack_success": raw["attack_success"],
        "rule_based_verdict": raw.get("verdict"),
        "agent_semantic": semantic,
        "evaluators_agree": semantic["attack_success"] == raw["attack_success"] if semantic["attack_success"] is not None else None,
        "raw_result": raw,
    })
    return _save_result(evaluation_dir, result)