File size: 3,539 Bytes
2eee48c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Canonical task-start normalization used by the native Obstruction loader."""
from __future__ import annotations
import hashlib
import json
import re

def _normalize_execution_paths(value: str) -> str:
    return re.sub(r"(personal-agent-[A-Za-z0-9_]+-)[0-9a-f]{12}(?=/tasks/)", r"\1<execution>", value)

def _volatile_task_start_path(path: tuple) -> bool:
    return (path in {
        ("observation", "timestamp"),
        ("environment_snapshot", "snapshot_sha256"),
        ("environment_snapshot", "source_snapshot_sha256"),
    } or (len(path) == 4 and path[:2] == ("environment_snapshot", "files")
          and isinstance(path[2], int) and path[3] == "mtime_ns"))

def task_start_semantic_digest(observation: dict, snapshot: dict) -> str:
    def scrub(value, path):
        if isinstance(value, dict):
            return {key: scrub(nested, path + (key,)) for key, nested in value.items()
                    if not _volatile_task_start_path(path + (key,))}
        if isinstance(value, list):
            return [scrub(nested, path + (index,)) for index, nested in enumerate(value)]
        if isinstance(value, str):
            return _normalize_execution_paths(value)
        return value
    content = {"observation": scrub(observation, ("observation",)),
               "environment_snapshot": scrub(snapshot, ("environment_snapshot",))}
    return hashlib.sha256(json.dumps(content, ensure_ascii=False, sort_keys=True,
                                     separators=(",", ":")).encode()).hexdigest()

def canonical_prompt_context(prompt: str, system_prompt: str) -> str:
    prefix = system_prompt + "\n\n"
    if not isinstance(prompt, str) or not prompt.startswith(prefix):
        raise ValueError("task_start prompt system prefix differs")
    context = json.loads(prompt[len(prefix):])
    if not isinstance(context, dict):
        raise ValueError("task_start prompt context must be a JSON object")
    def scrub(value, path=()):
        if path == ("event", "timestamp") or _volatile_task_start_path(path):
            return "<task-start-dynamic>"
        if isinstance(value, dict):
            return {key: scrub(nested, path + (key,)) for key, nested in value.items()}
        if isinstance(value, list):
            return [scrub(nested, path + (index,)) for index, nested in enumerate(value)]
        if isinstance(value, str):
            return _normalize_execution_paths(value)
        return value
    return json.dumps(scrub(context), ensure_ascii=False, sort_keys=True, separators=(",", ":"))


def validate_frozen_start(start: dict, initialization: dict, plan: dict) -> str:
    """Bind the frozen prompt to the plan that the native controller will load."""
    system = initialization['red_config']['system_prompt']
    prompt = start['red_prompt']
    expected = canonical_prompt_context(prompt, system)
    context = json.loads(prompt[len(system + '\n\n'):])
    if not isinstance(context.get('attack_plan'), dict):
        raise ValueError('Frozen Red prompt lacks its attack plan')
    reconstructed = {**context, 'attack_plan': plan}
    actual = canonical_prompt_context(system + '\n\n' + json.dumps(reconstructed, ensure_ascii=False), system)
    if actual != expected:
        raise ValueError('Frozen Red prompt differs from the published attack plan')
    return expected

def blue_initial_semantic_digest(value: dict) -> str:
    return hashlib.sha256(json.dumps(value, ensure_ascii=False, sort_keys=True,
                                     separators=(",", ":")).encode()).hexdigest()