snapkitty
compilers
c
python
nasm
File size: 10,613 Bytes
9abace2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
"""

Checkpoint Management for Agent State Persistence

Part of SOVEREIGN PYTHON LLM ENGINE



Backed by binary struct storage (CheckpointFile from core.storage).

No JSONL, no text encoding, no injection surface.



Features:

- Save/restore agent state to disk (binary struct format)

- Cryptographic signing (Ed25519)

- WORM-compatible append-only log

- Support for pause/resume of long-running agents

- Time-travel debugging (replay from any checkpoint)

"""

from dataclasses import dataclass, asdict
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, AsyncIterator
import json
import uuid

from ..core.crypto import ContentHash, Signature, SigningKey, hash_content, sign_artifact
from ..core.storage import CheckpointFile, CheckpointRecord


# ==========================================
# Agent State
# ==========================================

@dataclass
class AgentState:
    """

    Complete agent state snapshot.



    Fields:

        agent_id: Unique agent identifier

        task: Current task description

        step_number: Current step in execution

        messages: Conversation history

        tool_results: Results from tool executions

        reasoning: Agent's reasoning trace

        metadata: Additional state data

    """
    agent_id: str
    task: str
    step_number: int
    messages: list[dict[str, str]]
    tool_results: list[dict[str, Any]]
    reasoning: list[str]
    metadata: dict[str, Any]

    def to_dict(self) -> dict[str, Any]:
        return asdict(self)

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> 'AgentState':
        return cls(**data)

    def to_bytes(self) -> bytes:
        return json.dumps(self.to_dict(), sort_keys=True, separators=(',', ':')).encode('utf-8')

    @classmethod
    def from_bytes(cls, raw: bytes) -> 'AgentState':
        return cls.from_dict(json.loads(raw.decode('utf-8')))


# ==========================================
# Checkpoint
# ==========================================

@dataclass(frozen=True)
class Checkpoint:
    """

    Immutable checkpoint record.



    Fields:

        checkpoint_id: Unique checkpoint ID (UUID)

        agent_id: Agent identifier

        step_number: Step number when checkpoint was created

        state: Full agent state snapshot

        timestamp: UTC timestamp (ISO 8601)

        previous_checkpoint: ID of previous checkpoint (for chain)

        hash: Blake2b hash of state

        signature: Ed25519 signature

    """
    checkpoint_id: str
    agent_id: str
    step_number: int
    state: AgentState
    timestamp: str
    previous_checkpoint: str | None
    hash: ContentHash
    signature: Signature

    def to_dict(self) -> dict[str, Any]:
        return {
            'checkpoint_id': self.checkpoint_id,
            'agent_id': self.agent_id,
            'step_number': self.step_number,
            'state': self.state.to_dict(),
            'timestamp': self.timestamp,
            'previous_checkpoint': self.previous_checkpoint,
            'hash': self.hash,
            'signature': self.signature
        }

    @classmethod
    def from_dict(cls, data: dict[str, Any]) -> 'Checkpoint':
        state_data = data['state']
        state = AgentState.from_dict(state_data)

        return cls(
            checkpoint_id=data['checkpoint_id'],
            agent_id=data['agent_id'],
            step_number=data['step_number'],
            state=state,
            timestamp=data['timestamp'],
            previous_checkpoint=data.get('previous_checkpoint'),
            hash=ContentHash(data['hash']),
            signature=Signature(data['signature'])
        )

    @classmethod
    def from_record(cls, rec: CheckpointRecord) -> 'Checkpoint':
        state = AgentState.from_bytes(rec.state)
        return cls(
            checkpoint_id=rec.checkpoint_id,
            agent_id=rec.agent_id,
            step_number=rec.step_number,
            state=state,
            timestamp=datetime.fromtimestamp(
                rec.timestamp_ns / 1_000_000_000, tz=timezone.utc
            ).isoformat(),
            previous_checkpoint=rec.prev_id or None,
            hash=rec.content_hash,
            signature=rec.signature
        )


# ==========================================
# Checkpoint Manager (binary storage)
# ==========================================

class CheckpointManager:
    """

    Manage agent checkpoints with binary struct storage.



    Uses CheckpointFile from core.storage (128-byte fixed headers,

    Blake2b hash chain, Ed25519 signatures). No JSONL.

    """

    def __init__(self, checkpoint_dir: Path, signing_key: SigningKey):
        self.checkpoint_dir = checkpoint_dir
        self.signing_key = signing_key
        self.checkpoint_dir.mkdir(parents=True, exist_ok=True)
        self._last_checkpoint: dict[str, str] = {}

    def _get_checkpoint_file(self, agent_id: str) -> CheckpointFile:
        path = self.checkpoint_dir / f"{agent_id}.ckpt"
        return CheckpointFile(path, signing_key=self.signing_key)

    async def save_checkpoint(

        self,

        agent_id: str,

        state: AgentState,

        step_number: int | None = None

    ) -> Checkpoint:
        """

        Save agent state checkpoint to binary storage.

        """
        if step_number is None:
            step_number = state.step_number

        checkpoint_id = str(uuid.uuid4())
        previous_checkpoint = self._last_checkpoint.get(agent_id, "")

        state_bytes = state.to_bytes()
        state_hash = hash_content(state_bytes)

        signing_payload = f"{checkpoint_id}|{agent_id}|{step_number}|{state_hash}".encode('utf-8')
        signature = sign_artifact(self.signing_key, signing_payload)

        ckpt_file = self._get_checkpoint_file(agent_id)
        rec = ckpt_file.append(
            checkpoint_id=checkpoint_id,
            agent_id=agent_id,
            state=state_bytes,
            step=step_number,
            prev_id=previous_checkpoint
        )

        self._last_checkpoint[agent_id] = checkpoint_id

        return Checkpoint.from_record(rec)

    async def load_checkpoint(

        self,

        agent_id: str,

        checkpoint_id: str | None = None,

        step_number: int | None = None

    ) -> Checkpoint | None:
        """

        Load checkpoint by ID or step number.

        """
        ckpt_file = self._get_checkpoint_file(agent_id)

        if checkpoint_id:
            rec = ckpt_file.get_by_id(checkpoint_id)
            if rec:
                return Checkpoint.from_record(rec)
            return None

        if step_number is not None:
            rec = ckpt_file.get_by_step(step_number)
            if rec:
                return Checkpoint.from_record(rec)
            return None

        return None

    async def load_latest_checkpoint(self, agent_id: str) -> Checkpoint | None:
        """Load most recent checkpoint for agent."""
        ckpt_file = self._get_checkpoint_file(agent_id)
        rec = ckpt_file.get_latest()
        if rec:
            return Checkpoint.from_record(rec)
        return None

    async def list_checkpoints(

        self,

        agent_id: str,

        after_step: int | None = None

    ) -> list[Checkpoint]:
        """List all checkpoints for agent."""
        ckpt_file = self._get_checkpoint_file(agent_id)
        checkpoints = []
        for rec in ckpt_file.scan():
            if after_step is not None and rec.step_number <= after_step:
                continue
            checkpoints.append(Checkpoint.from_record(rec))
        return checkpoints

    async def verify_checkpoint_chain(self, agent_id: str) -> bool:
        """Verify cryptographic integrity of checkpoint chain."""
        checkpoints = await self.list_checkpoints(agent_id)
        if not checkpoints:
            return True

        expected_prev = ""
        for checkpoint in checkpoints:
            if (checkpoint.previous_checkpoint or "") != expected_prev:
                return False
            expected_prev = checkpoint.checkpoint_id
        return True

    async def get_checkpoint_stats(self, agent_id: str) -> dict[str, Any]:
        """Get checkpoint statistics for agent."""
        checkpoints = await self.list_checkpoints(agent_id)
        if not checkpoints:
            return {
                'total_checkpoints': 0,
                'first_checkpoint': None,
                'last_checkpoint': None,
                'chain_valid': True
            }
        return {
            'total_checkpoints': len(checkpoints),
            'first_checkpoint': checkpoints[0].checkpoint_id,
            'last_checkpoint': checkpoints[-1].checkpoint_id,
            'first_timestamp': checkpoints[0].timestamp,
            'last_timestamp': checkpoints[-1].timestamp,
            'step_range': (checkpoints[0].step_number, checkpoints[-1].step_number),
            'chain_valid': await self.verify_checkpoint_chain(agent_id)
        }


# ==========================================
# Checkpoint Iterator
# ==========================================

class CheckpointIterator:
    """Iterate through checkpoints in order."""

    def __init__(self, manager: CheckpointManager, agent_id: str):
        self.manager = manager
        self.agent_id = agent_id
        self._checkpoints: list[Checkpoint] | None = None
        self._index = 0

    async def __aiter__(self) -> AsyncIterator[Checkpoint]:
        if self._checkpoints is None:
            self._checkpoints = await self.manager.list_checkpoints(self.agent_id)
        for checkpoint in self._checkpoints:
            yield checkpoint

    async def next_checkpoint(self) -> Checkpoint | None:
        if self._checkpoints is None:
            self._checkpoints = await self.manager.list_checkpoints(self.agent_id)
        if self._index >= len(self._checkpoints):
            return None
        checkpoint = self._checkpoints[self._index]
        self._index += 1
        return checkpoint

    async def prev_checkpoint(self) -> Checkpoint | None:
        if self._checkpoints is None:
            self._checkpoints = await self.manager.list_checkpoints(self.agent_id)
        if self._index <= 0:
            return None
        self._index -= 1
        return self._checkpoints[self._index]

    def reset(self) -> None:
        self._index = 0