Skip to main content

agent_types/
checkpoint.rs

1//! Checkpoint-related pure types: CheckpointData, CheckpointStep, ToolResultData.
2//!
3//! M3 seam: `Before/AfterActions` carry the action vocabulary (`Vec<Action>`)
4//! and, on the way out, the backend's [`Observation`] (D3 observation replay —
5//! resume rebuilds history from it and never re-executes). Pre-M3 payloads
6//! (`Before/AfterToolCalls` with `(id, name, args)` triples) are read by the
7//! T5 migration layer, not by serde aliases: the field shapes differ.
8//!
9//! Persistence contract (OV-5+11):
10//! - **Versioned** — native writes carry [`CHECKPOINT_VERSION`]; a payload
11//!   without a `version` field is the pre-versioning corpus and reads as 0.
12//!   A payload newer than this build is refused explicitly (拒绝时明说).
13//! - **Backend affinity** — `backend` pins the action protocol the payload
14//!   speaks; [`CheckpointData::verify_for_resume`] refuses cross-backend
15//!   resumes and label mismatches, spelling the mismatch out.
16//! - **Source marks** — data converted on read keeps a [`MigrationSource`]
17//!   mark: read what is on the wire, never guess, never backfill (不猜不回填).
18
19use llm_trait::message::ChatMessage;
20use serde::{Deserialize, Deserializer, Serialize, de};
21use serde_json::Value;
22
23use crate::action::{Action, ActionFormat, Observation};
24use crate::run_state::RunState;
25use crate::session::SessionId;
26
27/// The checkpoint payload version this build writes and understands. Payloads
28/// without a `version` field are pre-versioning and read as 0.
29pub const CHECKPOINT_VERSION: u32 = 1;
30
31#[derive(Clone, Debug, Serialize)]
32pub struct CheckpointData {
33    pub session_id: SessionId,
34    pub user_input: String,
35    pub step: CheckpointStep,
36    pub turn_count: u32,
37    /// Payload version ([`CHECKPOINT_VERSION`] on native writes; 0 for the
38    /// pre-versioning corpus, which had no such field). Never backfilled.
39    pub version: u32,
40    /// Backend affinity pin (OV-5+11): the action protocol this payload
41    /// speaks. Absent on the wire means the pre-labeling tool-call corpus —
42    /// the step shape itself is the evidence.
43    pub backend: ActionFormat,
44    /// Source mark set when the payload was converted on read (T5 migration
45    /// layer). Absent for natively written data.
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub migrated_from: Option<MigrationSource>,
48    /// The counting evidence (D5+OV-11): co-written with the step in the one
49    /// journal line, so the recorded batch and the counts can never disagree
50    /// across a crash window. Native writes ALWAYS carry it (`new` stores
51    /// `Some`); on the wire it is optional so the pre-T7 corpus (and converted
52    /// legacy payloads) stay readable with the field genuinely absent —
53    /// restores of those fall back to the old-format paths, never guessed
54    /// (不猜不回填).
55    #[serde(default, skip_serializing_if = "Option::is_none")]
56    pub run_state: Option<RunState>,
57}
58
59impl CheckpointData {
60    /// Native checkpoint of [`CHECKPOINT_VERSION`], pinned to `backend`, with
61    /// the counting state co-written (D5+OV-11 事务同写).
62    pub fn new(
63        session_id: SessionId,
64        user_input: impl Into<String>,
65        step: CheckpointStep,
66        turn_count: u32,
67        backend: ActionFormat,
68        run_state: RunState,
69    ) -> Self {
70        Self {
71            session_id,
72            user_input: user_input.into(),
73            step,
74            turn_count,
75            version: CHECKPOINT_VERSION,
76            backend,
77            migrated_from: None,
78            run_state: Some(run_state),
79        }
80    }
81
82    /// The T5 persistence contract, checked before resume: the checkpoint must
83    /// speak the resuming backend's protocol, and every action payload must
84    /// carry a matching format label. Refusals spell out the mismatch.
85    pub fn verify_for_resume(&self, expected: ActionFormat) -> Result<(), String> {
86        if self.version > CHECKPOINT_VERSION {
87            return Err(format!(
88                "resume refused: checkpoint version {} is newer than this build supports ({CHECKPOINT_VERSION})",
89                self.version
90            ));
91        }
92        if self.backend != expected {
93            return Err(format!(
94                "resume refused: checkpoint is pinned to the {:?} backend, this runtime resumes {:?} checkpoints",
95                self.backend, expected
96            ));
97        }
98        self.verify_action_labels()
99    }
100
101    /// The same contract over the set of formats one runtime can resume
102    /// (T10c): a session may interleave built-in tool-call turns with a
103    /// mounted backend's turns, so the pin check accepts every format the
104    /// runtime is assembled with — and refuses a pin naming a backend it does
105    /// not carry ("mount it to resume this session"), never a silent replay
106    /// through the wrong protocol.
107    pub fn verify_for_resume_any(&self, accepted: &[ActionFormat]) -> Result<(), String> {
108        if self.version > CHECKPOINT_VERSION {
109            return Err(format!(
110                "resume refused: checkpoint version {} is newer than this build supports ({CHECKPOINT_VERSION})",
111                self.version
112            ));
113        }
114        if !accepted.contains(&self.backend) {
115            return Err(format!(
116                "resume refused: checkpoint is pinned to the {:?} backend, this runtime resumes {:?} checkpoints",
117                self.backend, accepted
118            ));
119        }
120        self.verify_action_labels()
121    }
122
123    /// Every action payload must carry the pin's format label.
124    fn verify_action_labels(&self) -> Result<(), String> {
125        for action in self.step.actions() {
126            if action.format != self.backend {
127                return Err(format!(
128                    "resume refused: checkpoint action '{}' carries format label {:?} but the checkpoint is pinned to {:?}",
129                    action.id, action.format, self.backend
130                ));
131            }
132        }
133        Ok(())
134    }
135}
136
137/// `CheckpointData` is read through the T5 migration layer: native shapes
138/// first, then the pre-M3 shapes (converted, marked). Deserialize is manual so
139/// the version/backend/source-mark contract lives in one place — Serialize
140/// stays derived and always writes the native shape.
141impl<'de> Deserialize<'de> for CheckpointData {
142    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
143    where
144        D: Deserializer<'de>,
145    {
146        #[derive(Deserialize)]
147        struct Wire {
148            session_id: SessionId,
149            user_input: String,
150            step: Value,
151            turn_count: u32,
152            #[serde(default)]
153            version: Option<u32>,
154            #[serde(default)]
155            backend: Option<ActionFormat>,
156            #[serde(default)]
157            migrated_from: Option<MigrationSource>,
158            #[serde(default)]
159            run_state: Option<RunState>,
160        }
161
162        let wire = Wire::deserialize(deserializer)?;
163        // Absent version = pre-versioning corpus (0). Never backfilled upward.
164        let version = wire.version.unwrap_or(0);
165        if version > CHECKPOINT_VERSION {
166            return Err(de::Error::custom(format!(
167                "checkpoint version {version} is newer than this build supports ({CHECKPOINT_VERSION}); refusing to read"
168            )));
169        }
170
171        let (step, migrated_from) = match serde_json::from_value::<CheckpointStep>(
172            wire.step.clone(),
173        ) {
174            Ok(step) => (step, wire.migrated_from),
175            Err(native_err) => match serde_json::from_value::<LegacyStep>(wire.step) {
176                Ok(legacy) => {
177                    let (step, legacy_results) = legacy.into_step();
178                    let mark = wire.migrated_from.unwrap_or(MigrationSource {
179                        kind: MigrationKind::ToolCallTriplesV0,
180                        legacy_results,
181                    });
182                    (step, Some(mark))
183                }
184                Err(_) => {
185                    return Err(de::Error::custom(format!(
186                        "unrecognized checkpoint step payload (not a native or pre-M3 shape): {native_err}"
187                    )));
188                }
189            },
190        };
191
192        Ok(CheckpointData {
193            session_id: wire.session_id,
194            user_input: wire.user_input,
195            step,
196            turn_count: wire.turn_count,
197            version,
198            // Absent label = the pre-labeling tool-call corpus (the triples on
199            // the wire are the evidence).
200            backend: wire.backend.unwrap_or(ActionFormat::ToolCall),
201            migrated_from,
202            // Absent counting state = pre-T7 corpus (or a converted legacy
203            // payload). Restores of those fall back to the old-format paths.
204            run_state: wire.run_state,
205        })
206    }
207}
208
209#[derive(Clone, Debug, Serialize, Deserialize)]
210pub enum CheckpointStep {
211    AfterUserInput,
212    BeforeLlm {
213        messages: Vec<ChatMessage>,
214        tools: Vec<Value>,
215    },
216    /// About to execute a batch of actions (id-paired to the observation).
217    BeforeActions {
218        actions: Vec<Action>,
219    },
220    /// The batch ran; `observation` is what the backend observed (D3).
221    AfterActions {
222        actions: Vec<Action>,
223        #[serde(default, skip_serializing_if = "Option::is_none")]
224        observation: Option<Observation>,
225    },
226}
227
228impl CheckpointStep {
229    /// The batch this step pins (empty for non-action steps).
230    pub fn actions(&self) -> &[Action] {
231        match self {
232            CheckpointStep::AfterUserInput | CheckpointStep::BeforeLlm { .. } => &[],
233            CheckpointStep::BeforeActions { actions }
234            | CheckpointStep::AfterActions { actions, .. } => actions,
235        }
236    }
237}
238
239/// Provenance mark for checkpoint data converted on read (T5 migration layer):
240/// the payload was written by a pre-M3 binary in an older wire shape.
241#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
242pub struct MigrationSource {
243    /// Which pre-M3 wire shape was converted.
244    pub kind: MigrationKind,
245    /// `AfterToolCalls { results }` records kept verbatim. The pre-M3 payload
246    /// recorded no per-action fates, so nothing is guessed from them and no
247    /// observation is backfilled (不猜不回填).
248    #[serde(default, skip_serializing_if = "Vec::is_empty")]
249    pub legacy_results: Vec<ToolResultData>,
250}
251
252#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
253#[serde(rename_all = "snake_case")]
254pub enum MigrationKind {
255    /// Pre-M3 `Before/AfterToolCalls` steps: `(id, name, args)` triples.
256    ToolCallTriplesV0,
257}
258
259/// The pre-M3 checkpoint step wire shape (tool-call triples). Read-only
260/// migration input — never constructed, never serialized.
261#[derive(Deserialize)]
262enum LegacyStep {
263    BeforeToolCalls {
264        tool_calls: Vec<(String, String, String)>,
265    },
266    AfterToolCalls {
267        tool_calls: Vec<(String, String, String)>,
268        #[serde(default)]
269        results: Vec<ToolResultData>,
270    },
271}
272
273impl LegacyStep {
274    /// Convert to the action vocabulary. Nothing is guessed: triples become
275    /// tool-call actions (labels and identity computed by the one constructor),
276    /// and the pre-M3 `results` ride along as-is instead of being pressed into
277    /// an `Observation` (the payload recorded no fates).
278    fn into_step(self) -> (CheckpointStep, Vec<ToolResultData>) {
279        fn actions(triples: Vec<(String, String, String)>) -> Vec<Action> {
280            triples
281                .into_iter()
282                .map(|(id, name, args)| Action::from_tool_call(id, name, args))
283                .collect()
284        }
285        match self {
286            LegacyStep::BeforeToolCalls { tool_calls } => (
287                CheckpointStep::BeforeActions {
288                    actions: actions(tool_calls),
289                },
290                Vec::new(),
291            ),
292            LegacyStep::AfterToolCalls {
293                tool_calls,
294                results,
295            } => (
296                CheckpointStep::AfterActions {
297                    actions: actions(tool_calls),
298                    observation: None,
299                },
300                results,
301            ),
302        }
303    }
304}
305
306/// Legacy per-result record from the pre-M3 checkpoint payload. Kept so the
307/// T5 migration layer can read old `AfterToolCalls { results }` data.
308#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
309pub struct ToolResultData {
310    pub tool_call_id: String,
311    pub tool_name: String,
312    pub summary: String,
313}
314
315#[cfg(test)]
316mod tests {
317    use super::*;
318    use crate::action::{ActionFormat, ActionOutcome, BatchStatus};
319
320    fn sample_messages() -> Vec<ChatMessage> {
321        vec![
322            ChatMessage::system("You are a helpful agent."),
323            ChatMessage::user("What is the weather in Tokyo?"),
324        ]
325    }
326
327    fn sample_tools() -> Vec<Value> {
328        vec![serde_json::json!({"name": "weather", "args": {"city": "Tokyo"}})]
329    }
330
331    fn sample_actions() -> Vec<Action> {
332        vec![
333            Action {
334                id: "call_1".to_string(),
335                name: "weather".to_string(),
336                args: Value::String(r#"{"city": "Tokyo"}"#.to_string()),
337                identity: r#"weather::{"city":"Tokyo"}"#.to_string(),
338                format: ActionFormat::ToolCall,
339            },
340            Action {
341                id: "call_2".to_string(),
342                name: "time".to_string(),
343                args: Value::String(r#"{"tz": "Asia/Tokyo"}"#.to_string()),
344                identity: r#"time::{"tz":"Asia/Tokyo"}"#.to_string(),
345                format: ActionFormat::ToolCall,
346            },
347        ]
348    }
349
350    fn sample_observation() -> Observation {
351        Observation {
352            outcomes: vec![
353                ActionOutcome {
354                    action_id: "call_1".to_string(),
355                    name: "weather".to_string(),
356                    ok: true,
357                    denied: false,
358                    summary: "20C, clear".to_string(),
359                    details: None,
360                },
361                ActionOutcome {
362                    action_id: "call_2".to_string(),
363                    name: "time".to_string(),
364                    ok: true,
365                    denied: false,
366                    summary: "09:41 JST".to_string(),
367                    details: None,
368                },
369            ],
370            events: vec![],
371            history_messages: vec![ChatMessage::tool("call_1", "20C, clear")],
372            batch_status: BatchStatus::Completed,
373        }
374    }
375
376    fn checkpoint_data(step: CheckpointStep) -> CheckpointData {
377        CheckpointData::new(
378            SessionId::with_external_id(42, "test-session"),
379            "What is the weather in Tokyo?",
380            step,
381            3,
382            ActionFormat::ToolCall,
383            RunState::default(),
384        )
385    }
386
387    #[test]
388    fn after_user_input_variant_survives_serde() {
389        let wire = serde_json::to_string(&CheckpointStep::AfterUserInput).unwrap();
390        let back: CheckpointStep = serde_json::from_str(&wire).unwrap();
391        assert!(matches!(back, CheckpointStep::AfterUserInput));
392    }
393
394    #[test]
395    fn before_llm_variant_keeps_its_payload_through_serde() {
396        let original = CheckpointStep::BeforeLlm {
397            messages: sample_messages(),
398            tools: sample_tools(),
399        };
400        let wire = serde_json::to_string(&original).unwrap();
401        let back: CheckpointStep = serde_json::from_str(&wire).unwrap();
402        match back {
403            CheckpointStep::BeforeLlm { messages, tools } => {
404                // ChatMessage has no PartialEq, so compare canonical JSON.
405                assert_eq!(
406                    serde_json::to_string(&messages).unwrap(),
407                    serde_json::to_string(&sample_messages()).unwrap()
408                );
409                assert_eq!(tools, sample_tools());
410            }
411            other => panic!("expected BeforeLlm, got {other:?}"),
412        }
413    }
414
415    #[test]
416    fn before_actions_variant_keeps_its_payload_through_serde() {
417        let original = CheckpointStep::BeforeActions {
418            actions: sample_actions(),
419        };
420        let wire = serde_json::to_string(&original).unwrap();
421        let back: CheckpointStep = serde_json::from_str(&wire).unwrap();
422        match back {
423            CheckpointStep::BeforeActions { actions } => {
424                assert_eq!(actions, sample_actions());
425            }
426            other => panic!("expected BeforeActions, got {other:?}"),
427        }
428    }
429
430    #[test]
431    fn after_actions_variant_keeps_actions_and_observation_through_serde() {
432        let original = CheckpointStep::AfterActions {
433            actions: sample_actions(),
434            observation: Some(sample_observation()),
435        };
436        let wire = serde_json::to_string(&original).unwrap();
437        let back: CheckpointStep = serde_json::from_str(&wire).unwrap();
438        match back {
439            CheckpointStep::AfterActions {
440                actions,
441                observation,
442            } => {
443                assert_eq!(actions, sample_actions());
444                let observation = observation.expect("observation must survive the round trip");
445                assert_eq!(observation.outcomes.len(), 2);
446                assert_eq!(observation.outcomes[0].action_id, "call_1");
447                assert_eq!(observation.outcomes[0].name, "weather");
448                assert_eq!(observation.outcomes[0].summary, "20C, clear");
449                assert_eq!(observation.outcomes[1].action_id, "call_2");
450                assert_eq!(observation.outcomes[1].name, "time");
451                assert_eq!(observation.outcomes[1].summary, "09:41 JST");
452                assert_eq!(observation.batch_status, BatchStatus::Completed);
453                // ChatMessage has no PartialEq — canonical JSON comparison.
454                assert_eq!(
455                    serde_json::to_string(&observation.history_messages).unwrap(),
456                    serde_json::to_string(&sample_observation().history_messages).unwrap()
457                );
458            }
459            other => panic!("expected AfterActions, got {other:?}"),
460        }
461    }
462
463    #[test]
464    fn checkpoint_step_after_actions_observation_is_optional() {
465        // A batch checkpoint written before the observation was available
466        // still deserializes (T5 migration fills what it can).
467        let step = CheckpointStep::AfterActions {
468            actions: sample_actions(),
469            observation: None,
470        };
471        let json = serde_json::to_string(&step).unwrap();
472        assert!(!json.contains("observation"));
473        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
474        match decoded {
475            CheckpointStep::AfterActions { observation, .. } => {
476                assert!(observation.is_none());
477            }
478            other => panic!("expected AfterActions, got {other:?}"),
479        }
480    }
481
482    #[test]
483    fn checkpoint_data_round_trips_for_every_step_variant() {
484        let variants = [
485            CheckpointStep::AfterUserInput,
486            CheckpointStep::BeforeLlm {
487                messages: sample_messages(),
488                tools: sample_tools(),
489            },
490            CheckpointStep::BeforeActions {
491                actions: sample_actions(),
492            },
493            CheckpointStep::AfterActions {
494                actions: sample_actions(),
495                observation: Some(sample_observation()),
496            },
497        ];
498
499        for step in variants {
500            let data = checkpoint_data(step);
501            let json = serde_json::to_string(&data).unwrap();
502            let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
503            assert_eq!(decoded.session_id, data.session_id);
504            assert_eq!(decoded.user_input, data.user_input);
505            assert_eq!(decoded.turn_count, data.turn_count);
506            // CheckpointStep does not derive PartialEq, so compare variant
507            // discriminants for the step round-trip.
508            assert_eq!(
509                std::mem::discriminant(&data.step),
510                std::mem::discriminant(&decoded.step)
511            );
512        }
513    }
514
515    #[test]
516    fn checkpoint_step_rejects_malformed_json_instead_of_panicking() {
517        // Unknown variant tag.
518        assert!(serde_json::from_str::<CheckpointStep>(r#"{"NotAStep":{}}"#).is_err());
519        // Wrong field type on a known variant.
520        assert!(
521            serde_json::from_str::<CheckpointStep>(
522                r#"{"BeforeLlm":{"messages":"not-a-list","tools":[]}}"#,
523            )
524            .is_err()
525        );
526        // Truncated JSON.
527        assert!(serde_json::from_str::<CheckpointStep>(r#"{"AfterUserInput""#).is_err());
528        // Empty input.
529        assert!(serde_json::from_str::<CheckpointStep>("").is_err());
530    }
531
532    #[test]
533    fn checkpoint_data_rejects_malformed_json_instead_of_panicking() {
534        // Missing required fields.
535        assert!(
536            serde_json::from_str::<CheckpointData>(r#"{"session_id":{"id":1},"user_input":"hi"}"#,)
537                .is_err()
538        );
539        // Wrong session_id shape.
540        assert!(
541            serde_json::from_str::<CheckpointData>(
542                r#"{"session_id":"oops","user_input":"hi","step":"AfterUserInput","turn_count":1}"#,
543            )
544            .is_err()
545        );
546        // turn_count is not a number.
547        assert!(
548            serde_json::from_str::<CheckpointData>(
549                r#"{"session_id":{"id":1},"user_input":"hi","step":"AfterUserInput","turn_count":"three"}"#,
550            )
551            .is_err()
552        );
553    }
554
555    // -----------------------------------------------------------------------
556    // T5 persistence contract: versioning, source marks, backend affinity.
557    // -----------------------------------------------------------------------
558
559    #[test]
560    fn native_checkpoint_pins_version_and_backend() {
561        let data = checkpoint_data(CheckpointStep::AfterUserInput);
562        assert_eq!(data.version, CHECKPOINT_VERSION);
563        assert_eq!(data.backend, ActionFormat::ToolCall);
564        assert!(data.migrated_from.is_none());
565
566        let json = serde_json::to_string(&data).unwrap();
567        assert!(
568            json.contains("\"version\":1"),
569            "native write carries version: {json}"
570        );
571        assert!(
572            json.contains("\"backend\":\"tool_call\""),
573            "native write carries the format label: {json}"
574        );
575        let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
576        assert_eq!(decoded.version, CHECKPOINT_VERSION);
577        assert_eq!(decoded.backend, ActionFormat::ToolCall);
578        assert!(decoded.migrated_from.is_none());
579    }
580
581    #[test]
582    fn pre_versioning_payload_reads_as_version_zero_without_a_mark() {
583        // A pre-M3 `AfterUserInput`/`BeforeLlm` payload is shape-identical to
584        // the native one — nothing migrated, so nothing is marked (不猜).
585        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":"AfterUserInput","turn_count":1}"#;
586        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
587        assert_eq!(decoded.version, 0, "absent version must not be backfilled");
588        assert_eq!(decoded.backend, ActionFormat::ToolCall);
589        assert!(decoded.migrated_from.is_none());
590    }
591
592    #[test]
593    fn legacy_before_tool_calls_migrates_with_source_mark() {
594        // A checkpoint line written by a pre-M3 binary: tool-call triples, no
595        // version/backend fields.
596        let json = r#"{"session_id":{"id":7,"external_id":"s7"},"user_input":"resume me","step":{"BeforeToolCalls":{"tool_calls":[["call_1","echo","{\"text\":\"hi\"}"]]}},"turn_count":2}"#;
597        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
598        assert_eq!(decoded.version, 0);
599        assert_eq!(decoded.backend, ActionFormat::ToolCall);
600        let mark = decoded
601            .migrated_from
602            .as_ref()
603            .expect("legacy shape must carry its source mark");
604        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
605        assert!(mark.legacy_results.is_empty());
606        match &decoded.step {
607            CheckpointStep::BeforeActions { actions } => {
608                assert_eq!(actions.len(), 1);
609                assert_eq!(actions[0].id, "call_1");
610                assert_eq!(actions[0].name, "echo");
611                assert_eq!(actions[0].raw_args(), r#"{"text":"hi"}"#);
612                assert_eq!(actions[0].format, ActionFormat::ToolCall);
613                assert_eq!(
614                    actions[0].identity,
615                    Action::tool_call_identity("echo", r#"{"text":"hi"}"#)
616                );
617            }
618            other => panic!("expected BeforeActions, got {other:?}"),
619        }
620    }
621
622    #[test]
623    fn legacy_after_tool_calls_migrates_without_backfilling_an_observation() {
624        let json = r#"{"session_id":{"id":8,"external_id":"s8"},"user_input":"go","step":{"AfterToolCalls":{"tool_calls":[["call_2","ls","{}"]],"results":[]}},"turn_count":3}"#;
625        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
626        let mark = decoded
627            .migrated_from
628            .as_ref()
629            .expect("legacy shape must carry its source mark");
630        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
631        assert!(mark.legacy_results.is_empty());
632        match &decoded.step {
633            CheckpointStep::AfterActions {
634                actions,
635                observation,
636            } => {
637                assert_eq!(actions.len(), 1);
638                assert_eq!(actions[0].id, "call_2");
639                assert!(
640                    observation.is_none(),
641                    "nothing observed was recorded — no backfill"
642                );
643            }
644            other => panic!("expected AfterActions, got {other:?}"),
645        }
646    }
647
648    #[test]
649    fn legacy_after_tool_calls_results_ride_along_verbatim() {
650        let json = r#"{"session_id":{"id":8,"external_id":"s8"},"user_input":"go","step":{"AfterToolCalls":{"tool_calls":[["call_2","ls","{}"]],"results":[{"tool_call_id":"call_2","tool_name":"ls","summary":"file list"}]}},"turn_count":3}"#;
651        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
652        let mark = decoded
653            .migrated_from
654            .as_ref()
655            .expect("legacy shape must carry its source mark");
656        assert_eq!(
657            mark.legacy_results,
658            vec![ToolResultData {
659                tool_call_id: "call_2".to_string(),
660                tool_name: "ls".to_string(),
661                summary: "file list".to_string(),
662            }],
663            "legacy results are preserved as-is, not guessed into fates"
664        );
665        match &decoded.step {
666            CheckpointStep::AfterActions { observation, .. } => {
667                assert!(
668                    observation.is_none(),
669                    "results ≠ observation (no fates recorded)"
670                );
671            }
672            other => panic!("expected AfterActions, got {other:?}"),
673        }
674    }
675
676    #[test]
677    fn legacy_payload_unknown_fields_are_tolerated() {
678        let json = r#"{"session_id":{"id":9,"external_id":"s9"},"user_input":"hi","step":{"BeforeToolCalls":{"tool_calls":[["call_1","echo","{}"]],"future_field":true}},"turn_count":1,"some_new_top_level_field":"ignored"}"#;
679        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
680        assert_eq!(decoded.version, 0);
681        assert!(decoded.migrated_from.is_some());
682        assert!(matches!(decoded.step, CheckpointStep::BeforeActions { .. }));
683    }
684
685    #[test]
686    fn migrated_checkpoint_re_serializes_in_the_native_shape_and_keeps_its_mark() {
687        let json = r#"{"session_id":{"id":8,"external_id":"s8"},"user_input":"go","step":{"AfterToolCalls":{"tool_calls":[["call_2","ls","{}"]],"results":[{"tool_call_id":"call_2","tool_name":"ls","summary":"file list"}]}},"turn_count":3}"#;
688        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
689        let rewritten = serde_json::to_string(&decoded).unwrap();
690        assert!(
691            rewritten.contains("\"AfterActions\""),
692            "rewrite is native-shape: {rewritten}"
693        );
694        assert!(!rewritten.contains("AfterToolCalls"));
695        assert!(
696            rewritten.contains("\"migrated_from\""),
697            "the source mark survives persistence: {rewritten}"
698        );
699        assert!(rewritten.contains("\"legacy_results\""));
700
701        let again: CheckpointData = serde_json::from_str(&rewritten).unwrap();
702        assert_eq!(
703            again.version, 0,
704            "the mark and version keep agreeing across rounds"
705        );
706        let mark = again.migrated_from.expect("mark survives the round trip");
707        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
708        assert_eq!(mark.legacy_results.len(), 1);
709        assert_eq!(mark.legacy_results[0].summary, "file list");
710    }
711
712    #[test]
713    fn future_version_payload_is_refused_explicitly() {
714        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":"AfterUserInput","turn_count":1,"version":2}"#;
715        let err = serde_json::from_str::<CheckpointData>(json).unwrap_err();
716        let msg = err.to_string();
717        assert!(
718            msg.contains("version 2"),
719            "refusal names the version: {msg}"
720        );
721        assert!(msg.contains("refusing"), "refusal is explicit: {msg}");
722    }
723
724    #[test]
725    fn unrecognized_step_payload_is_refused_explicitly() {
726        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":{"NotAStep":{}},"turn_count":1}"#;
727        let err = serde_json::from_str::<CheckpointData>(json).unwrap_err();
728        let msg = err.to_string();
729        assert!(msg.contains("NotAStep"), "refusal names the payload: {msg}");
730        assert!(msg.contains("unrecognized"), "refusal is explicit: {msg}");
731    }
732
733    #[test]
734    fn verify_for_resume_accepts_a_native_tool_call_checkpoint() {
735        let data = checkpoint_data(CheckpointStep::BeforeActions {
736            actions: sample_actions(),
737        });
738        assert!(data.verify_for_resume(ActionFormat::ToolCall).is_ok());
739    }
740
741    #[test]
742    fn verify_for_resume_refuses_cross_backend_pinning() {
743        let data = CheckpointData::new(
744            SessionId::with_external_id(1, "s1"),
745            "go",
746            CheckpointStep::AfterUserInput,
747            0,
748            ActionFormat::CodeAct,
749            RunState::default(),
750        );
751        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
752        assert!(
753            msg.contains("CodeAct"),
754            "refusal names the pinned backend: {msg}"
755        );
756        assert!(
757            msg.contains("ToolCall"),
758            "refusal names the resuming backend: {msg}"
759        );
760        assert!(msg.contains("refused"), "refusal is explicit: {msg}");
761    }
762
763    #[test]
764    fn verify_for_resume_refuses_mismatched_format_labels() {
765        // Hand-built contradiction: the pin says tool_call, the payload says
766        // code_act. The label is the evidence — no guessing.
767        let data = CheckpointData::new(
768            SessionId::with_external_id(1, "s1"),
769            "go",
770            CheckpointStep::BeforeActions {
771                actions: vec![Action {
772                    id: "cell_1".to_string(),
773                    name: "code_cell".to_string(),
774                    args: Value::String(r#"{"code":"1+1"}"#.to_string()),
775                    identity: r#"code_cell::{"code":"1+1"}"#.to_string(),
776                    format: ActionFormat::CodeAct,
777                }],
778            },
779            0,
780            ActionFormat::ToolCall,
781            RunState::default(),
782        );
783        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
784        assert!(msg.contains("cell_1"), "refusal names the action: {msg}");
785        assert!(
786            msg.contains("format label"),
787            "refusal explains the label mismatch: {msg}"
788        );
789    }
790
791    #[test]
792    fn verify_for_resume_refuses_a_future_version_value() {
793        // Hand-built value — the read-side check is the real gate; this covers
794        // callers that assemble CheckpointData in memory.
795        let mut data = checkpoint_data(CheckpointStep::AfterUserInput);
796        data.version = CHECKPOINT_VERSION + 1;
797        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
798        assert!(msg.contains("newer"), "refusal explains the version: {msg}");
799    }
800
801    #[test]
802    fn native_checkpoint_co_writes_run_state() {
803        // D5+OV-11 事务同写: a native write always carries the counting state
804        // alongside the step in one payload.
805        let mut run_state = RunState::default();
806        run_state.record_actions(2, &[]);
807        let data = CheckpointData::new(
808            SessionId::with_external_id(42, "test-session"),
809            "go",
810            CheckpointStep::BeforeActions {
811                actions: sample_actions(),
812            },
813            3,
814            ActionFormat::ToolCall,
815            run_state,
816        );
817        let carried = data
818            .run_state
819            .clone()
820            .expect("native write co-writes RunState");
821        assert_eq!(carried.turn_actions, 2);
822        assert_eq!(carried.total_actions, 2);
823
824        let json = serde_json::to_string(&data).unwrap();
825        assert!(
826            json.contains("\"run_state\""),
827            "wire carries the state: {json}"
828        );
829        let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
830        let restored = decoded.run_state.expect("state survives the round trip");
831        assert_eq!(restored.turn_actions, 2);
832        assert_eq!(restored.total_actions, 2);
833        assert!(restored.run_has_actions);
834    }
835
836    #[test]
837    fn pre_t7_checkpoint_reads_without_run_state() {
838        // The pre-T7 corpus has no counting state on the wire. It must read
839        // with the field genuinely absent — never guessed, never backfilled
840        // (不猜不回填) — so restores fall back to the old-format paths.
841        let json = r#"{"session_id":{"id":42,"external_id":"test-session"},"user_input":"go","step":{"BeforeActions":{"actions":[]}},"turn_count":3,"version":1,"backend":"tool_call"}"#;
842        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
843        assert!(
844            decoded.run_state.is_none(),
845            "absent stays absent: {:?}",
846            decoded.run_state
847        );
848    }
849
850    #[test]
851    fn converted_legacy_checkpoint_keeps_run_state_absent() {
852        // A migrated pre-M3 payload gains the step migration and source mark,
853        // but not a counting state — conversion must not invent one.
854        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"go","step":{"BeforeToolCalls":{"tool_calls":[["call_1","weather","{\"city\":\"Tokyo\"}"]]}},"turn_count":1}"#;
855        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
856        assert!(decoded.migrated_from.is_some(), "step migration is marked");
857        assert!(
858            decoded.run_state.is_none(),
859            "conversion does not invent counting state: {:?}",
860            decoded.run_state
861        );
862    }
863}