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 checkpoint_step_after_user_input_round_trips() {
389        let step = CheckpointStep::AfterUserInput;
390        let json = serde_json::to_string(&step).unwrap();
391        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
392        assert!(matches!(decoded, CheckpointStep::AfterUserInput));
393    }
394
395    #[test]
396    fn checkpoint_step_before_llm_round_trips() {
397        let step = CheckpointStep::BeforeLlm {
398            messages: sample_messages(),
399            tools: sample_tools(),
400        };
401        let json = serde_json::to_string(&step).unwrap();
402        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
403        match decoded {
404            CheckpointStep::BeforeLlm { messages, tools } => {
405                // ChatMessage has no PartialEq, so compare canonical JSON.
406                assert_eq!(
407                    serde_json::to_string(&messages).unwrap(),
408                    serde_json::to_string(&sample_messages()).unwrap()
409                );
410                assert_eq!(tools, sample_tools());
411            }
412            other => panic!("expected BeforeLlm, got {other:?}"),
413        }
414    }
415
416    #[test]
417    fn checkpoint_step_before_actions_round_trips() {
418        let step = CheckpointStep::BeforeActions {
419            actions: sample_actions(),
420        };
421        let json = serde_json::to_string(&step).unwrap();
422        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
423        match decoded {
424            CheckpointStep::BeforeActions { actions } => {
425                assert_eq!(actions, sample_actions());
426            }
427            other => panic!("expected BeforeActions, got {other:?}"),
428        }
429    }
430
431    #[test]
432    fn checkpoint_step_after_actions_round_trips() {
433        let step = CheckpointStep::AfterActions {
434            actions: sample_actions(),
435            observation: Some(sample_observation()),
436        };
437        let json = serde_json::to_string(&step).unwrap();
438        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
439        match decoded {
440            CheckpointStep::AfterActions {
441                actions,
442                observation,
443            } => {
444                assert_eq!(actions, sample_actions());
445                let observation = observation.expect("observation must survive the round trip");
446                assert_eq!(observation.outcomes.len(), 2);
447                assert_eq!(observation.outcomes[0].action_id, "call_1");
448                assert_eq!(observation.outcomes[0].name, "weather");
449                assert_eq!(observation.outcomes[0].summary, "20C, clear");
450                assert_eq!(observation.outcomes[1].action_id, "call_2");
451                assert_eq!(observation.outcomes[1].name, "time");
452                assert_eq!(observation.outcomes[1].summary, "09:41 JST");
453                assert_eq!(observation.batch_status, BatchStatus::Completed);
454                // ChatMessage has no PartialEq — canonical JSON comparison.
455                assert_eq!(
456                    serde_json::to_string(&observation.history_messages).unwrap(),
457                    serde_json::to_string(&sample_observation().history_messages).unwrap()
458                );
459            }
460            other => panic!("expected AfterActions, got {other:?}"),
461        }
462    }
463
464    #[test]
465    fn checkpoint_step_after_actions_observation_is_optional() {
466        // A batch checkpoint written before the observation was available
467        // still deserializes (T5 migration fills what it can).
468        let step = CheckpointStep::AfterActions {
469            actions: sample_actions(),
470            observation: None,
471        };
472        let json = serde_json::to_string(&step).unwrap();
473        assert!(!json.contains("observation"));
474        let decoded: CheckpointStep = serde_json::from_str(&json).unwrap();
475        match decoded {
476            CheckpointStep::AfterActions { observation, .. } => {
477                assert!(observation.is_none());
478            }
479            other => panic!("expected AfterActions, got {other:?}"),
480        }
481    }
482
483    #[test]
484    fn checkpoint_data_round_trips_for_every_step_variant() {
485        let variants = [
486            CheckpointStep::AfterUserInput,
487            CheckpointStep::BeforeLlm {
488                messages: sample_messages(),
489                tools: sample_tools(),
490            },
491            CheckpointStep::BeforeActions {
492                actions: sample_actions(),
493            },
494            CheckpointStep::AfterActions {
495                actions: sample_actions(),
496                observation: Some(sample_observation()),
497            },
498        ];
499
500        for step in variants {
501            let data = checkpoint_data(step);
502            let json = serde_json::to_string(&data).unwrap();
503            let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
504            assert_eq!(decoded.session_id, data.session_id);
505            assert_eq!(decoded.user_input, data.user_input);
506            assert_eq!(decoded.turn_count, data.turn_count);
507            // CheckpointStep does not derive PartialEq, so compare variant
508            // discriminants for the step round-trip.
509            assert_eq!(
510                std::mem::discriminant(&data.step),
511                std::mem::discriminant(&decoded.step)
512            );
513        }
514    }
515
516    #[test]
517    fn checkpoint_step_deserialization_fails_gracefully_on_malformed_input() {
518        // Unknown variant tag.
519        assert!(serde_json::from_str::<CheckpointStep>(r#"{"NotAStep":{}}"#).is_err());
520        // Wrong field type on a known variant.
521        assert!(
522            serde_json::from_str::<CheckpointStep>(
523                r#"{"BeforeLlm":{"messages":"not-a-list","tools":[]}}"#,
524            )
525            .is_err()
526        );
527        // Truncated JSON.
528        assert!(serde_json::from_str::<CheckpointStep>(r#"{"AfterUserInput""#).is_err());
529        // Empty input.
530        assert!(serde_json::from_str::<CheckpointStep>("").is_err());
531    }
532
533    #[test]
534    fn checkpoint_data_deserialization_fails_gracefully_on_malformed_input() {
535        // Missing required fields.
536        assert!(
537            serde_json::from_str::<CheckpointData>(r#"{"session_id":{"id":1},"user_input":"hi"}"#,)
538                .is_err()
539        );
540        // Wrong session_id shape.
541        assert!(
542            serde_json::from_str::<CheckpointData>(
543                r#"{"session_id":"oops","user_input":"hi","step":"AfterUserInput","turn_count":1}"#,
544            )
545            .is_err()
546        );
547        // turn_count is not a number.
548        assert!(
549            serde_json::from_str::<CheckpointData>(
550                r#"{"session_id":{"id":1},"user_input":"hi","step":"AfterUserInput","turn_count":"three"}"#,
551            )
552            .is_err()
553        );
554    }
555
556    // -----------------------------------------------------------------------
557    // T5 persistence contract: versioning, source marks, backend affinity.
558    // -----------------------------------------------------------------------
559
560    #[test]
561    fn native_checkpoint_pins_version_and_backend() {
562        let data = checkpoint_data(CheckpointStep::AfterUserInput);
563        assert_eq!(data.version, CHECKPOINT_VERSION);
564        assert_eq!(data.backend, ActionFormat::ToolCall);
565        assert!(data.migrated_from.is_none());
566
567        let json = serde_json::to_string(&data).unwrap();
568        assert!(
569            json.contains("\"version\":1"),
570            "native write carries version: {json}"
571        );
572        assert!(
573            json.contains("\"backend\":\"tool_call\""),
574            "native write carries the format label: {json}"
575        );
576        let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
577        assert_eq!(decoded.version, CHECKPOINT_VERSION);
578        assert_eq!(decoded.backend, ActionFormat::ToolCall);
579        assert!(decoded.migrated_from.is_none());
580    }
581
582    #[test]
583    fn pre_versioning_payload_reads_as_version_zero_without_a_mark() {
584        // A pre-M3 `AfterUserInput`/`BeforeLlm` payload is shape-identical to
585        // the native one — nothing migrated, so nothing is marked (不猜).
586        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":"AfterUserInput","turn_count":1}"#;
587        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
588        assert_eq!(decoded.version, 0, "absent version must not be backfilled");
589        assert_eq!(decoded.backend, ActionFormat::ToolCall);
590        assert!(decoded.migrated_from.is_none());
591    }
592
593    #[test]
594    fn legacy_before_tool_calls_migrates_with_source_mark() {
595        // A checkpoint line written by a pre-M3 binary: tool-call triples, no
596        // version/backend fields.
597        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}"#;
598        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
599        assert_eq!(decoded.version, 0);
600        assert_eq!(decoded.backend, ActionFormat::ToolCall);
601        let mark = decoded
602            .migrated_from
603            .as_ref()
604            .expect("legacy shape must carry its source mark");
605        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
606        assert!(mark.legacy_results.is_empty());
607        match &decoded.step {
608            CheckpointStep::BeforeActions { actions } => {
609                assert_eq!(actions.len(), 1);
610                assert_eq!(actions[0].id, "call_1");
611                assert_eq!(actions[0].name, "echo");
612                assert_eq!(actions[0].raw_args(), r#"{"text":"hi"}"#);
613                assert_eq!(actions[0].format, ActionFormat::ToolCall);
614                assert_eq!(
615                    actions[0].identity,
616                    Action::tool_call_identity("echo", r#"{"text":"hi"}"#)
617                );
618            }
619            other => panic!("expected BeforeActions, got {other:?}"),
620        }
621    }
622
623    #[test]
624    fn legacy_after_tool_calls_migrates_without_backfilling_an_observation() {
625        let json = r#"{"session_id":{"id":8,"external_id":"s8"},"user_input":"go","step":{"AfterToolCalls":{"tool_calls":[["call_2","ls","{}"]],"results":[]}},"turn_count":3}"#;
626        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
627        let mark = decoded
628            .migrated_from
629            .as_ref()
630            .expect("legacy shape must carry its source mark");
631        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
632        assert!(mark.legacy_results.is_empty());
633        match &decoded.step {
634            CheckpointStep::AfterActions {
635                actions,
636                observation,
637            } => {
638                assert_eq!(actions.len(), 1);
639                assert_eq!(actions[0].id, "call_2");
640                assert!(
641                    observation.is_none(),
642                    "nothing observed was recorded — no backfill"
643                );
644            }
645            other => panic!("expected AfterActions, got {other:?}"),
646        }
647    }
648
649    #[test]
650    fn legacy_after_tool_calls_results_ride_along_verbatim() {
651        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}"#;
652        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
653        let mark = decoded
654            .migrated_from
655            .as_ref()
656            .expect("legacy shape must carry its source mark");
657        assert_eq!(
658            mark.legacy_results,
659            vec![ToolResultData {
660                tool_call_id: "call_2".to_string(),
661                tool_name: "ls".to_string(),
662                summary: "file list".to_string(),
663            }],
664            "legacy results are preserved as-is, not guessed into fates"
665        );
666        match &decoded.step {
667            CheckpointStep::AfterActions { observation, .. } => {
668                assert!(
669                    observation.is_none(),
670                    "results ≠ observation (no fates recorded)"
671                );
672            }
673            other => panic!("expected AfterActions, got {other:?}"),
674        }
675    }
676
677    #[test]
678    fn legacy_payload_unknown_fields_are_tolerated() {
679        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"}"#;
680        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
681        assert_eq!(decoded.version, 0);
682        assert!(decoded.migrated_from.is_some());
683        assert!(matches!(decoded.step, CheckpointStep::BeforeActions { .. }));
684    }
685
686    #[test]
687    fn migrated_checkpoint_re_serializes_in_the_native_shape_and_keeps_its_mark() {
688        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}"#;
689        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
690        let rewritten = serde_json::to_string(&decoded).unwrap();
691        assert!(
692            rewritten.contains("\"AfterActions\""),
693            "rewrite is native-shape: {rewritten}"
694        );
695        assert!(!rewritten.contains("AfterToolCalls"));
696        assert!(
697            rewritten.contains("\"migrated_from\""),
698            "the source mark survives persistence: {rewritten}"
699        );
700        assert!(rewritten.contains("\"legacy_results\""));
701
702        let again: CheckpointData = serde_json::from_str(&rewritten).unwrap();
703        assert_eq!(
704            again.version, 0,
705            "the mark and version keep agreeing across rounds"
706        );
707        let mark = again.migrated_from.expect("mark survives the round trip");
708        assert_eq!(mark.kind, MigrationKind::ToolCallTriplesV0);
709        assert_eq!(mark.legacy_results.len(), 1);
710        assert_eq!(mark.legacy_results[0].summary, "file list");
711    }
712
713    #[test]
714    fn future_version_payload_is_refused_explicitly() {
715        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":"AfterUserInput","turn_count":1,"version":2}"#;
716        let err = serde_json::from_str::<CheckpointData>(json).unwrap_err();
717        let msg = err.to_string();
718        assert!(
719            msg.contains("version 2"),
720            "refusal names the version: {msg}"
721        );
722        assert!(msg.contains("refusing"), "refusal is explicit: {msg}");
723    }
724
725    #[test]
726    fn unrecognized_step_payload_is_refused_explicitly() {
727        let json = r#"{"session_id":{"id":1,"external_id":"s1"},"user_input":"hi","step":{"NotAStep":{}},"turn_count":1}"#;
728        let err = serde_json::from_str::<CheckpointData>(json).unwrap_err();
729        let msg = err.to_string();
730        assert!(msg.contains("NotAStep"), "refusal names the payload: {msg}");
731        assert!(msg.contains("unrecognized"), "refusal is explicit: {msg}");
732    }
733
734    #[test]
735    fn verify_for_resume_accepts_a_native_tool_call_checkpoint() {
736        let data = checkpoint_data(CheckpointStep::BeforeActions {
737            actions: sample_actions(),
738        });
739        assert!(data.verify_for_resume(ActionFormat::ToolCall).is_ok());
740    }
741
742    #[test]
743    fn verify_for_resume_refuses_cross_backend_pinning() {
744        let data = CheckpointData::new(
745            SessionId::with_external_id(1, "s1"),
746            "go",
747            CheckpointStep::AfterUserInput,
748            0,
749            ActionFormat::CodeAct,
750            RunState::default(),
751        );
752        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
753        assert!(
754            msg.contains("CodeAct"),
755            "refusal names the pinned backend: {msg}"
756        );
757        assert!(
758            msg.contains("ToolCall"),
759            "refusal names the resuming backend: {msg}"
760        );
761        assert!(msg.contains("refused"), "refusal is explicit: {msg}");
762    }
763
764    #[test]
765    fn verify_for_resume_refuses_mismatched_format_labels() {
766        // Hand-built contradiction: the pin says tool_call, the payload says
767        // code_act. The label is the evidence — no guessing.
768        let data = CheckpointData::new(
769            SessionId::with_external_id(1, "s1"),
770            "go",
771            CheckpointStep::BeforeActions {
772                actions: vec![Action {
773                    id: "cell_1".to_string(),
774                    name: "code_cell".to_string(),
775                    args: Value::String(r#"{"code":"1+1"}"#.to_string()),
776                    identity: r#"code_cell::{"code":"1+1"}"#.to_string(),
777                    format: ActionFormat::CodeAct,
778                }],
779            },
780            0,
781            ActionFormat::ToolCall,
782            RunState::default(),
783        );
784        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
785        assert!(msg.contains("cell_1"), "refusal names the action: {msg}");
786        assert!(
787            msg.contains("format label"),
788            "refusal explains the label mismatch: {msg}"
789        );
790    }
791
792    #[test]
793    fn verify_for_resume_refuses_a_future_version_value() {
794        // Hand-built value — the read-side check is the real gate; this covers
795        // callers that assemble CheckpointData in memory.
796        let mut data = checkpoint_data(CheckpointStep::AfterUserInput);
797        data.version = CHECKPOINT_VERSION + 1;
798        let msg = data.verify_for_resume(ActionFormat::ToolCall).unwrap_err();
799        assert!(msg.contains("newer"), "refusal explains the version: {msg}");
800    }
801
802    #[test]
803    fn native_checkpoint_co_writes_run_state() {
804        // D5+OV-11 事务同写: a native write always carries the counting state
805        // alongside the step in one payload.
806        let mut run_state = RunState::default();
807        run_state.record_actions(2, &[]);
808        let data = CheckpointData::new(
809            SessionId::with_external_id(42, "test-session"),
810            "go",
811            CheckpointStep::BeforeActions {
812                actions: sample_actions(),
813            },
814            3,
815            ActionFormat::ToolCall,
816            run_state,
817        );
818        let carried = data
819            .run_state
820            .clone()
821            .expect("native write co-writes RunState");
822        assert_eq!(carried.turn_actions, 2);
823        assert_eq!(carried.total_actions, 2);
824
825        let json = serde_json::to_string(&data).unwrap();
826        assert!(
827            json.contains("\"run_state\""),
828            "wire carries the state: {json}"
829        );
830        let decoded: CheckpointData = serde_json::from_str(&json).unwrap();
831        let restored = decoded.run_state.expect("state survives the round trip");
832        assert_eq!(restored.turn_actions, 2);
833        assert_eq!(restored.total_actions, 2);
834        assert!(restored.run_has_actions);
835    }
836
837    #[test]
838    fn pre_t7_checkpoint_reads_without_run_state() {
839        // The pre-T7 corpus has no counting state on the wire. It must read
840        // with the field genuinely absent — never guessed, never backfilled
841        // (不猜不回填) — so restores fall back to the old-format paths.
842        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"}"#;
843        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
844        assert!(
845            decoded.run_state.is_none(),
846            "absent stays absent: {:?}",
847            decoded.run_state
848        );
849    }
850
851    #[test]
852    fn converted_legacy_checkpoint_keeps_run_state_absent() {
853        // A migrated pre-M3 payload gains the step migration and source mark,
854        // but not a counting state — conversion must not invent one.
855        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}"#;
856        let decoded: CheckpointData = serde_json::from_str(json).unwrap();
857        assert!(decoded.migrated_from.is_some(), "step migration is marked");
858        assert!(
859            decoded.run_state.is_none(),
860            "conversion does not invent counting state: {:?}",
861            decoded.run_state
862        );
863    }
864}