File size: 7,461 Bytes
a5c1fa0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
211
212
213
214
215
216
217
218
219
220
221
222
# server/trajectory.py
"""
Full trajectory recording and deterministic replay system.

Records every action, observation, reward, file diff, and timing.
Enables post-hoc analysis and deterministic replay of agent episodes.
"""
import time
import copy
import hashlib
from typing import Optional, List, Dict, Any
from dataclasses import dataclass, field, asdict


@dataclass
class FileDiff:
    """Represents a file change made by the agent."""
    path: str
    before: Optional[str]  # None if file was created
    after: str
    chars_changed: int


@dataclass
class TrajectoryStep:
    """Complete record of one agent step."""
    step_number: int
    timestamp: float
    action_type: str
    action_path: Optional[str]
    action_query: Optional[str]
    action_content_length: Optional[int]  # Don't store full content — too large
    observation_snapshot: Dict[str, Any]   # Compact snapshot
    reward: float
    cumulative_reward: float
    done: bool
    error: Optional[str]
    file_diff: Optional[Dict[str, Any]]   # If write_file, the diff
    test_pass_rate: Optional[float]        # If run_tests, the pass rate
    duration_ms: float                     # How long this step took server-side
    security_flags: List[str] = field(default_factory=list)


@dataclass
class TrajectoryRecord:
    """Complete episode trajectory — everything needed for replay + analysis."""
    episode_id: str
    task: str
    variant_id: str
    start_time: float
    end_time: Optional[float] = None
    steps: List[TrajectoryStep] = field(default_factory=list)
    final_score: float = 0.0
    total_steps: int = 0
    metadata: Dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict:
        """Convert to JSON-serializable dict."""
        return {
            "episode_id": self.episode_id,
            "task": self.task,
            "variant_id": self.variant_id,
            "start_time": self.start_time,
            "end_time": self.end_time,
            "duration_seconds": round(self.end_time - self.start_time, 2) if self.end_time else None,
            "steps": [asdict(s) for s in self.steps],
            "final_score": self.final_score,
            "total_steps": self.total_steps,
            "metadata": self.metadata,
        }


class TrajectoryLogger:
    """
    Records full agent trajectories for analysis and replay.

    Usage:
        logger = TrajectoryLogger()
        logger.start_episode("task1", "variant_3")
        logger.record_step(step_number=1, action=..., obs=..., ...)
        logger.end_episode(final_score=0.75)
        trajectory = logger.get_trajectory()
    """

    def __init__(self):
        self._current: Optional[TrajectoryRecord] = None
        self._history: List[TrajectoryRecord] = []  # Last N episodes
        self._max_history = 10

    def start_episode(self, task: str, variant_id: str) -> str:
        """Start recording a new episode. Returns episode_id."""
        # Finalize previous episode if still active
        if self._current and self._current.end_time is None:
            self._current.end_time = time.time()
            self._history.append(self._current)

        episode_id = hashlib.md5(
            f"{task}_{variant_id}_{time.time()}".encode()
        ).hexdigest()[:12]

        self._current = TrajectoryRecord(
            episode_id=episode_id,
            task=task,
            variant_id=variant_id,
            start_time=time.time(),
        )
        return episode_id

    def record_step(
        self,
        step_number: int,
        action_type: str,
        action_path: Optional[str],
        action_query: Optional[str],
        action_content_length: Optional[int],
        reward: float,
        cumulative_reward: float,
        done: bool,
        error: Optional[str],
        file_diff: Optional[FileDiff],
        test_pass_rate: Optional[float],
        duration_ms: float,
        observation_compact: Dict[str, Any],
        security_flags: List[str] = None,
    ):
        """Record one step in the current trajectory."""
        if not self._current:
            return

        step = TrajectoryStep(
            step_number=step_number,
            timestamp=time.time(),
            action_type=action_type,
            action_path=action_path,
            action_query=action_query,
            action_content_length=action_content_length,
            observation_snapshot=observation_compact,
            reward=reward,
            cumulative_reward=cumulative_reward,
            done=done,
            error=error,
            file_diff=asdict(file_diff) if file_diff else None,
            test_pass_rate=test_pass_rate,
            duration_ms=duration_ms,
            security_flags=security_flags or [],
        )
        self._current.steps.append(step)
        self._current.total_steps = step_number

    def end_episode(self, final_score: float):
        """Finalize the current episode."""
        if not self._current:
            return

        self._current.end_time = time.time()
        self._current.final_score = final_score

        # Maintain history buffer
        self._history.append(self._current)
        if len(self._history) > self._max_history:
            self._history.pop(0)

    def get_trajectory(self) -> Optional[dict]:
        """Get the current/latest trajectory as dict."""
        if self._current:
            return self._current.to_dict()
        if self._history:
            return self._history[-1].to_dict()
        return None

    def get_replay_actions(self) -> List[dict]:
        """Extract action sequence for deterministic replay."""
        if not self._current and not self._history:
            return []

        record = self._current or self._history[-1]
        actions = []
        for step in record.steps:
            action = {"action_type": step.action_type}
            if step.action_path:
                action["path"] = step.action_path
            if step.action_query:
                action["query"] = step.action_query
            # Note: content not stored in trajectory — replay requires re-supplying it
            actions.append(action)
        return actions

    def get_step_timeline(self) -> List[dict]:
        """Get compact timeline of actions and outcomes for visualization."""
        if not self._current:
            return []

        timeline = []
        for step in self._current.steps:
            timeline.append({
                "step": step.step_number,
                "action": step.action_type,
                "path": step.action_path,
                "reward": step.reward,
                "error": step.error,
                "duration_ms": step.duration_ms,
                "pass_rate": step.test_pass_rate,
                "security_flags": step.security_flags,
            })
        return timeline

    def get_history_summary(self) -> List[dict]:
        """Get summary of recent episodes."""
        summaries = []
        for record in self._history:
            summaries.append({
                "episode_id": record.episode_id,
                "task": record.task,
                "variant_id": record.variant_id,
                "final_score": record.final_score,
                "total_steps": record.total_steps,
                "duration_seconds": round(
                    record.end_time - record.start_time, 2
                ) if record.end_time else None,
            })
        return summaries