adk-graph 3.0.0

Graph-based workflow orchestration for ADK-Rust agents
Documentation
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
//! Time-travel debugging for graph execution history.
//!
//! This module provides [`TimeTravelHandle`] for navigating, inspecting, and forking
//! graph execution history. It works with any [`Checkpointer`] implementation to
//! inspect past execution steps, resume from arbitrary points, and create divergent
//! execution branches.
//!
//! # Overview
//!
//! Time-travel debugging allows you to:
//! - List all checkpointed steps for a thread
//! - Resume execution from any historical step
//! - Fork a thread at a specific step into a new independent thread
//! - Fork from a checkpoint with edited state, recording the fork's lineage
//!   ([`fork_thread`], [`TimeTravelHandle::fork`]; spec 3.3 §12)
//! - Replay execution between two steps, collecting intermediate states
//!
//! # Example
//!
//! ```rust,ignore
//! use adk_graph::prelude::*;
//! use adk_graph::time_travel::{TimeTravelHandle, StepInfo};
//!
//! // Build and execute a graph
//! let graph = StateGraph::new(StateSchema::simple(&["data"]))
//!     .add_node("process", process_fn)
//!     .add_edge(START, "process")
//!     .add_edge("process", END)
//!     .compile(Some(checkpointer.clone()));
//!
//! // Get a time-travel handle for a thread
//! let handle = graph.time_travel("thread_1").unwrap();
//!
//! // List all steps
//! let steps = handle.steps().await?;
//! for step in &steps {
//!     println!("Step {}: checkpoint={}", step.step, step.checkpoint_id);
//! }
//!
//! // Fork at step 2 into a new thread
//! handle.fork_at(2, "thread_1_fork").await?;
//!
//! // Replay steps 0 through 3
//! let states = handle.state_history(0, Some(3)).await?;
//! ```

use std::collections::BTreeMap;
use std::sync::Arc;

use serde::Serialize;
use serde_json::Value;
use thiserror::Error;

use crate::checkpoint::Checkpointer;
use crate::error::{GraphError, Result};
use crate::graph::CompiledGraph;
use crate::node::ExecutionConfig;
use crate::record::{LINEAGE_METADATA_KEY, Lineage};
use crate::state::{Checkpoint, State, StateSchema};

/// Information about a single execution step in the graph history.
///
/// Each `StepInfo` corresponds to a checkpoint saved after a super-step
/// in the Pregel execution model. It provides metadata useful for
/// navigating and understanding the execution timeline.
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::time_travel::StepInfo;
///
/// let step = StepInfo {
///     step: 3,
///     checkpoint_id: "abc-123".to_string(),
///     timestamp: Some("2025-01-15T10:30:00Z".to_string()),
///     pending_nodes: vec!["transform".to_string()],
///     state_keys: vec!["data".to_string(), "result".to_string()],
/// };
///
/// println!("Step {} has {} pending nodes", step.step, step.pending_nodes.len());
/// ```
#[derive(Debug, Clone, Serialize)]
pub struct StepInfo {
    /// The step number in the execution sequence (0-indexed).
    pub step: usize,
    /// The unique checkpoint identifier for this step.
    pub checkpoint_id: String,
    /// ISO 8601 timestamp when this step was checkpointed, if available.
    pub timestamp: Option<String>,
    /// Node names that were pending execution at this step.
    pub pending_nodes: Vec<String>,
    /// State keys that were present at this step.
    pub state_keys: Vec<String>,
}

/// Handle for time-travel operations on a graph thread.
///
/// `TimeTravelHandle` provides methods to navigate, replay, and fork
/// graph execution history. It holds a reference to the compiled graph
/// and uses the associated checkpointer to access historical state.
///
/// Create a handle via [`CompiledGraph::time_travel`].
///
/// # Example
///
/// ```rust,ignore
/// use adk_graph::prelude::*;
/// use adk_graph::time_travel::TimeTravelHandle;
///
/// let graph = StateGraph::new(StateSchema::simple(&["count"]))
///     .add_node("increment", increment_fn)
///     .add_edge(START, "increment")
///     .add_edge("increment", END)
///     .compile(Some(checkpointer.clone()));
///
/// // Create a time-travel handle
/// let handle = graph.time_travel("my_thread");
///
/// // Inspect execution history
/// let steps = handle.steps().await?;
/// println!("Thread has {} steps", steps.len());
///
/// // Fork at step 1 to explore an alternative path
/// handle.fork_at(1, "alternative_thread").await?;
/// ```
pub struct TimeTravelHandle<'g> {
    /// Reference to the compiled graph for re-execution in `resume_from`.
    pub(crate) graph: &'g CompiledGraph,
    /// The thread identifier whose history is being navigated.
    pub(crate) thread_id: String,
    /// The checkpointer used to load and save checkpoints.
    pub(crate) checkpointer: Arc<dyn Checkpointer>,
}

impl<'g> TimeTravelHandle<'g> {
    /// Create a new `TimeTravelHandle` for the given thread.
    ///
    /// # Arguments
    ///
    /// * `graph` - Reference to the compiled graph
    /// * `thread_id` - The thread whose history to navigate
    /// * `checkpointer` - The checkpointer for accessing historical state
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_graph::time_travel::TimeTravelHandle;
    ///
    /// let handle = TimeTravelHandle::new(&graph, "thread_1", checkpointer.clone());
    /// ```
    pub fn new(
        graph: &'g CompiledGraph,
        thread_id: &str,
        checkpointer: Arc<dyn Checkpointer>,
    ) -> Self {
        Self { graph, thread_id: thread_id.to_string(), checkpointer }
    }

    /// List all checkpointed steps for this thread, ordered by step number.
    ///
    /// Returns a [`StepInfo`] for each checkpoint, providing metadata about
    /// the execution state at that point in time.
    ///
    /// # Errors
    ///
    /// Returns [`GraphError`] if the checkpointer fails to list checkpoints.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let handle = graph.time_travel("thread_1").unwrap();
    /// let steps = handle.steps().await?;
    ///
    /// for step in &steps {
    ///     println!(
    ///         "Step {}: {} (pending: {:?})",
    ///         step.step, step.checkpoint_id, step.pending_nodes
    ///     );
    /// }
    /// ```
    pub async fn steps(&self) -> Result<Vec<StepInfo>> {
        let checkpoints = self.checkpointer.list(&self.thread_id).await?;
        let mut steps: Vec<StepInfo> = checkpoints
            .into_iter()
            .map(|cp| StepInfo {
                step: cp.step,
                checkpoint_id: cp.checkpoint_id,
                timestamp: Some(cp.created_at.to_rfc3339()),
                pending_nodes: cp.pending_nodes,
                state_keys: cp.state.keys().cloned().collect(),
            })
            .collect();
        steps.sort_by_key(|s| s.step);
        Ok(steps)
    }

    /// Resume graph execution from the checkpoint at the specified step.
    ///
    /// Loads the state from the checkpoint at `step` and re-executes the graph
    /// from that point forward using the provided execution configuration.
    ///
    /// # Arguments
    ///
    /// * `step` - The step number to resume from
    /// * `config` - Execution configuration for the resumed run
    ///
    /// # Errors
    ///
    /// Returns [`GraphError`] if:
    /// - No checkpoint exists at the specified step
    /// - The graph execution fails after resuming
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let handle = graph.time_travel("thread_1").unwrap();
    ///
    /// // Resume from step 3
    /// let config = ExecutionConfig::new("thread_1");
    /// let final_state = handle.resume_from(3, config).await?;
    /// println!("Resumed execution produced: {:?}", final_state);
    /// ```
    pub async fn resume_from(&self, step: usize, config: ExecutionConfig) -> Result<State> {
        // List all checkpoints for this thread
        let checkpoints = self.checkpointer.list(&self.thread_id).await?;

        // Find the checkpoint at the specified step
        let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
            GraphError::CheckpointError(format!(
                "no checkpoint found at step {step} for thread '{}'",
                self.thread_id
            ))
        })?;

        // Create an ExecutionConfig that resumes from this checkpoint
        let mut resume_config =
            ExecutionConfig::new(&config.thread_id).with_resume_from(&checkpoint.checkpoint_id);
        resume_config.recursion_limit = config.recursion_limit;

        // Invoke the graph with the checkpoint's state — the executor will
        // restore state from the checkpoint and continue execution from there
        self.graph.invoke(State::new(), resume_config).await
    }

    /// Fork the thread at a specific step into a new independent thread.
    ///
    /// Loads the checkpoint at `step` and saves it under `new_thread_id`,
    /// creating a new execution branch. The original thread remains unchanged.
    /// The fork keeps the arrivals of joins still waiting and records its
    /// [`Lineage`]; see [`fork_thread`] for what else it carries.
    ///
    /// # Arguments
    ///
    /// * `step` - The step number to fork from
    /// * `new_thread_id` - The identifier for the new forked thread
    ///
    /// # Errors
    ///
    /// Returns [`GraphError`] if:
    /// - No checkpoint exists at the specified step
    /// - The checkpointer fails to save the forked checkpoint
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let handle = graph.time_travel("thread_1").unwrap();
    ///
    /// // Fork at step 2 to explore an alternative execution path
    /// handle.fork_at(2, "thread_1_experiment").await?;
    ///
    /// // The original thread_1 is unaffected
    /// let original_steps = handle.steps().await?;
    /// ```
    pub async fn fork_at(&self, step: usize, new_thread_id: &str) -> Result<()> {
        // List all checkpoints for this thread
        let checkpoints = self.checkpointer.list(&self.thread_id).await?;

        // Find the checkpoint at the specified step
        let checkpoint = checkpoints.into_iter().find(|cp| cp.step == step).ok_or_else(|| {
            GraphError::CheckpointError(format!(
                "no checkpoint found at step {step} for thread '{}'",
                self.thread_id
            ))
        })?;

        // Clone the checkpoint under the new thread_id, after its newest.
        let version =
            self.checkpointer.load(new_thread_id).await?.map_or(1, |newest| newest.version + 1);
        let forked =
            forked_checkpoint(&checkpoint, new_thread_id, version, &BTreeMap::new(), true)?;

        // Save the forked checkpoint
        self.checkpointer.save(&forked).await?;
        Ok(())
    }

    /// Returns the stored state at each checkpointed step in a range.
    ///
    /// This **reads** checkpoints; it does not execute anything. No node runs, no
    /// event is regenerated, and no side effect is repeated — the states returned are
    /// the snapshots that were saved when the graph originally ran. Use it to inspect
    /// how state evolved, not to reproduce a decision.
    ///
    /// To re-run from a point in history, fork that checkpoint with `fork_at`
    /// and invoke the graph on the forked thread.
    ///
    /// # Arguments
    ///
    /// * `from_step` - First step to include
    /// * `to_step` - Last step to include, or `None` for the last checkpointed step
    ///
    /// # Errors
    ///
    /// Returns [`GraphError`] when no checkpoint exists at `from_step`.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let handle = graph.time_travel("thread_1").unwrap();
    ///
    /// // The stored state at steps 1 through 4
    /// let transitions = handle.state_history(1, Some(4)).await?;
    /// for (step, state) in &transitions {
    ///     println!("Step {}: {:?}", step, state.keys().collect::<Vec<_>>());
    /// }
    ///
    /// // From step 2 to the last checkpoint
    /// let all_remaining = handle.state_history(2, None).await?;
    /// ```
    pub async fn state_history(
        &self,
        from_step: usize,
        to_step: Option<usize>,
    ) -> Result<Vec<(usize, State)>> {
        // List all checkpoints for this thread
        let mut checkpoints = self.checkpointer.list(&self.thread_id).await?;

        // Sort by step to ensure correct ordering
        checkpoints.sort_by_key(|cp| cp.step);

        // Filter to checkpoints in the requested range
        let results: Vec<(usize, State)> = checkpoints
            .into_iter()
            .filter(|cp| cp.step >= from_step && to_step.is_none_or(|end| cp.step <= end))
            .map(|cp| (cp.step, cp.state))
            .collect();

        // Verify that from_step exists in the results
        if results.is_empty() || results[0].0 != from_step {
            return Err(GraphError::CheckpointError(format!(
                "no checkpoint found at step {from_step} for thread '{}'",
                self.thread_id
            )));
        }

        Ok(results)
    }
}

impl TimeTravelHandle<'_> {
    /// Forks this thread at the checkpoint `spec.from`, with edits checked against the
    /// graph's declared channels (spec 3.3 §12).
    ///
    /// See [`fork_thread`].
    ///
    /// # Errors
    ///
    /// Returns [`ForkError::OtherThread`] when the checkpoint belongs to another thread,
    /// and every error [`fork_thread`] returns.
    ///
    /// # Example
    ///
    /// ```
    /// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
    /// use adk_graph::edge::{END, START};
    /// use adk_graph::graph::StateGraph;
    /// use adk_graph::node::{ExecutionConfig, NodeOutput};
    /// use adk_graph::state::State;
    /// use adk_graph::time_travel::ForkSpec;
    /// use serde_json::json;
    /// use std::sync::Arc;
    ///
    /// # #[tokio::main(flavor = "current_thread")]
    /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let checkpointer = Arc::new(MemoryCheckpointer::new());
    /// let graph = StateGraph::with_channels(&["note", "done"])
    ///     .add_node_fn("draft", |_ctx| async { Ok(NodeOutput::new().with_update("note", json!("v1"))) })
    ///     .add_node_fn("send", |_ctx| async { Ok(NodeOutput::new().with_update("done", json!(true))) })
    ///     .add_edge(START, "draft")
    ///     .add_edge("draft", "send")
    ///     .add_edge("send", END)
    ///     .compile()?
    ///     .with_checkpointer_arc(checkpointer.clone());
    /// graph.invoke(State::new(), ExecutionConfig::new("t1")).await?;
    ///
    /// let after_draft = checkpointer.list("t1").await?[0].checkpoint_id.clone();
    /// let fork = graph
    ///     .time_travel("t1")?
    ///     .fork(ForkSpec::new(&after_draft, "t1-fork").set("note", json!("v2")))
    ///     .await?;
    /// assert_eq!(fork.state["note"], json!("v2"));
    /// assert_eq!(fork.lineage()?.map(|l| l.edited), Some(vec!["note".to_string()]));
    /// # Ok(())
    /// # }
    /// ```
    pub async fn fork(&self, spec: ForkSpec) -> std::result::Result<Checkpoint, ForkError> {
        let source = self
            .checkpointer
            .load_by_id(&spec.from)
            .await?
            .ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
        if source.thread_id != self.thread_id {
            return Err(ForkError::OtherThread {
                id: spec.from,
                thread: source.thread_id,
                expected: self.thread_id.clone(),
            });
        }
        fork_thread(self.checkpointer.as_ref(), spec, Some(self.graph.schema())).await
    }
}

/// What to fork, where to, and which state to overwrite (spec 3.3 §12).
///
/// # Example
///
/// ```
/// use adk_graph::time_travel::ForkSpec;
/// use serde_json::json;
///
/// let spec = ForkSpec::new("c1", "t1-fork").set("note", json!("re-run for audit"));
/// assert_eq!(spec.set["note"], json!("re-run for audit"));
/// ```
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ForkSpec {
    /// The id of the checkpoint to fork from: the completed checkpoint of a step.
    pub from: String,
    /// The thread the fork is written to; it must have no checkpoints yet.
    pub new_thread_id: String,
    /// Channels to overwrite in the fork, whole: no reducer is applied.
    pub set: BTreeMap<String, Value>,
}

impl ForkSpec {
    /// A fork of checkpoint `from` into `new_thread_id`, with no edits.
    pub fn new(from: impl Into<String>, new_thread_id: impl Into<String>) -> Self {
        Self { from: from.into(), new_thread_id: new_thread_id.into(), set: BTreeMap::new() }
    }

    /// Overwrites channel `key` with `value` in the fork.
    #[must_use]
    pub fn set(mut self, key: impl Into<String>, value: Value) -> Self {
        self.set.insert(key.into(), value);
        self
    }
}

/// Why a fork was refused (spec 3.3 §12).
///
/// Every message starts with the stable [`code`](Self::code).
///
/// # Example
///
/// ```
/// use adk_graph::time_travel::ForkError;
///
/// let error = ForkError::NothingToRun { id: "c3".to_string() };
/// assert_eq!(error.code(), "fork.nothing_to_run");
/// assert!(error.to_string().starts_with("fork.nothing_to_run:"));
/// ```
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ForkError {
    /// No checkpoint has the id.
    #[error("fork.unknown_checkpoint: no checkpoint '{id}'")]
    UnknownCheckpoint {
        /// The id asked for.
        id: String,
    },
    /// The checkpoint belongs to another thread than the handle's.
    #[error("fork.other_thread: checkpoint '{id}' belongs to thread '{thread}', not '{expected}'")]
    OtherThread {
        /// The id asked for.
        id: String,
        /// The thread the checkpoint belongs to.
        thread: String,
        /// The handle's thread.
        expected: String,
    },
    /// The checkpoint is a pause: a node of its step waits.
    #[error(
        "fork.paused: checkpoint '{id}' is a pause, where a node waits mid-step; fork from the \
         completed checkpoint of its step"
    )]
    Paused {
        /// The id asked for.
        id: String,
    },
    /// The checkpoint ends its run, so nothing would run in the fork.
    #[error(
        "fork.nothing_to_run: nothing runs after the last step: checkpoint '{id}' has no pending nodes"
    )]
    NothingToRun {
        /// The id asked for.
        id: String,
    },
    /// An edit names a channel the graph does not declare.
    #[error("fork.undeclared_channel: '{key}' is not a channel of this graph")]
    UndeclaredChannel {
        /// The edited key.
        key: String,
    },
    /// An unchecked edit names a key the checkpoint's state does not hold.
    #[error(
        "fork.unknown_key: '{key}' is not a key of this checkpoint; without the graph's channels \
         only existing keys can be edited"
    )]
    UnknownKey {
        /// The edited key.
        key: String,
    },
    /// The target thread already has checkpoints.
    #[error(
        "fork.thread_exists: thread '{thread}' already has checkpoints; fork into a new thread"
    )]
    ThreadExists {
        /// The target thread.
        thread: String,
    },
    /// The checkpointer failed.
    #[error(transparent)]
    Checkpointer(#[from] GraphError),
}

impl ForkError {
    /// The stable code this refusal's message starts with; `fork.checkpointer` for a
    /// checkpointer failure.
    pub fn code(&self) -> &'static str {
        match self {
            Self::UnknownCheckpoint { .. } => "fork.unknown_checkpoint",
            Self::OtherThread { .. } => "fork.other_thread",
            Self::Paused { .. } => "fork.paused",
            Self::NothingToRun { .. } => "fork.nothing_to_run",
            Self::UndeclaredChannel { .. } => "fork.undeclared_channel",
            Self::UnknownKey { .. } => "fork.unknown_key",
            Self::ThreadExists { .. } => "fork.thread_exists",
            Self::Checkpointer(_) => "fork.checkpointer",
        }
    }
}

impl From<ForkError> for GraphError {
    fn from(error: ForkError) -> Self {
        match error {
            ForkError::Checkpointer(error) => error,
            refusal => GraphError::CheckpointError(refusal.to_string()),
        }
    }
}

/// Forks the checkpoint `spec.from` into the new thread `spec.new_thread_id`, with the
/// channels in `spec.set` overwritten (spec 3.3 §12).
///
/// | Carried | Dropped |
/// |---------|---------|
/// | State (with the edits), step, pending nodes, the arrivals of joins still waiting, each governed node's completed runs | The retry budget, the answered gate, pending writes, finished children, the paused marker and its waiting requests, the run and its step records |
///
/// A pause asks again in the fork, and the fork opens its own run when it first runs. The
/// fork records its [`Lineage`]: `root` is the source's root, else the source's thread.
/// Edits overwrite whole channels and never go through reducers. With `schema`, each
/// edited key must be a declared channel and the lineage records `checked: true`;
/// without one, only keys the source state holds are accepted and it records
/// `checked: false`. The source thread is never written.
///
/// # Errors
///
/// Returns a [`ForkError`] for an unknown id, a pause, a checkpoint with no pending nodes,
/// an edit that names an undeclared channel or an unknown key, a target thread that
/// already has checkpoints, or a checkpointer failure.
///
/// # Example
///
/// ```
/// use adk_graph::checkpoint::{Checkpointer, MemoryCheckpointer};
/// use adk_graph::state::{Checkpoint, State};
/// use adk_graph::time_travel::{ForkSpec, fork_thread};
/// use serde_json::json;
///
/// # #[tokio::main(flavor = "current_thread")]
/// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let checkpointer = MemoryCheckpointer::new();
/// let state = State::from([("note".to_string(), json!("v1"))]);
/// let source = Checkpoint::new("t1", state, 1, vec!["send".to_string()]);
/// checkpointer.save(&source).await?;
///
/// let fork = fork_thread(
///     &checkpointer,
///     ForkSpec::new(&source.checkpoint_id, "t2").set("note", json!("v2")),
///     None,
/// )
/// .await?;
/// let lineage = fork.lineage()?.expect("a fork records its lineage");
/// assert_eq!((lineage.root.as_str(), lineage.checked), ("t1", false));
/// # Ok(())
/// # }
/// ```
pub async fn fork_thread(
    checkpointer: &dyn Checkpointer,
    spec: ForkSpec,
    schema: Option<&StateSchema>,
) -> std::result::Result<Checkpoint, ForkError> {
    let source = checkpointer
        .load_by_id(&spec.from)
        .await?
        .ok_or_else(|| ForkError::UnknownCheckpoint { id: spec.from.clone() })?;
    if source.is_paused() {
        return Err(ForkError::Paused { id: spec.from });
    }
    if source.pending_nodes.is_empty() {
        return Err(ForkError::NothingToRun { id: spec.from });
    }
    let schema = schema.filter(|schema| !schema.channels.is_empty());
    for key in spec.set.keys() {
        match schema {
            Some(schema) if !schema.channels.contains_key(key) => {
                return Err(ForkError::UndeclaredChannel { key: key.clone() });
            }
            None if !source.state.contains_key(key) => {
                return Err(ForkError::UnknownKey { key: key.clone() });
            }
            _ => {}
        }
    }
    if spec.new_thread_id == source.thread_id
        || checkpointer.load(&spec.new_thread_id).await?.is_some()
    {
        return Err(ForkError::ThreadExists { thread: spec.new_thread_id });
    }
    let fork = forked_checkpoint(&source, &spec.new_thread_id, 1, &spec.set, schema.is_some())?;
    checkpointer.save(&fork).await?;
    tracing::info!(
        thread_id = %source.thread_id,
        fork.thread_id = %spec.new_thread_id,
        fork.edited = spec.set.len(),
        "forked a graph thread"
    );
    Ok(fork)
}

/// The first checkpoint of a fork of `source` into `thread`.
fn forked_checkpoint(
    source: &Checkpoint,
    thread: &str,
    version: u64,
    set: &BTreeMap<String, Value>,
    checked: bool,
) -> Result<Checkpoint> {
    let mut state = source.state.clone();
    for (key, value) in set {
        state.insert(key.clone(), value.clone());
    }
    let mut fork = Checkpoint::new(thread, state, source.step, source.pending_nodes.clone())
        .with_version(version);
    for key in [crate::deferred::FAN_IN_METADATA_KEY, crate::executor::OCCURRENCES_METADATA_KEY] {
        if let Some(value) = source.metadata.get(key) {
            fork.metadata.insert(key.to_string(), value.clone());
        }
    }
    let root = source.lineage()?.map_or_else(|| source.thread_id.clone(), |lineage| lineage.root);
    let lineage = Lineage {
        root,
        parent: source.thread_id.clone(),
        parent_checkpoint: source.checkpoint_id.clone(),
        parent_step: source.step_label(),
        edited: set.keys().cloned().collect(),
        checked,
    };
    fork.metadata.insert(LINEAGE_METADATA_KEY.to_string(), serde_json::to_value(lineage)?);
    Ok(fork)
}

impl CompiledGraph {
    /// Create a [`TimeTravelHandle`] for navigating the execution history of a thread.
    ///
    /// Requires that the graph was compiled with a checkpointer. If no checkpointer
    /// is configured, this method panics.
    ///
    /// # Arguments
    ///
    /// * `thread_id` - The thread identifier whose history to navigate
    ///
    /// # Panics
    ///
    /// Panics if the graph was compiled without a checkpointer.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use adk_graph::prelude::*;
    ///
    /// let checkpointer = Arc::new(MemoryCheckpointer::new());
    /// let graph = StateGraph::new(StateSchema::simple(&["data"]))
    ///     .add_node("process", process_fn)
    ///     .add_edge(START, "process")
    ///     .add_edge("process", END)
    ///     .compile(Some(checkpointer));
    ///
    /// let handle = graph.time_travel("thread_1").unwrap();
    /// let steps = handle.steps().await?;
    /// ```
    /// # Errors
    ///
    /// Returns [`GraphError::CheckpointError`] when the graph has no
    /// checkpointer, because every operation on the handle reads checkpoints.
    pub fn time_travel(&self, thread_id: &str) -> Result<TimeTravelHandle<'_>> {
        let checkpointer = self.checkpointer.clone().ok_or_else(|| {
            GraphError::CheckpointError(
                "time travel needs a checkpointer. Add one with with_checkpointer before calling time_travel"
                    .to_string(),
            )
        })?;
        Ok(TimeTravelHandle::new(self, thread_id, checkpointer))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::checkpoint::MemoryCheckpointer;
    use crate::graph::StateGraph;
    use crate::node::{ExecutionConfig, FunctionNode, NodeContext, NodeOutput};
    use crate::state::{Checkpoint, State, StateSchema};
    use serde_json::json;

    /// Helper: build a simple graph with a checkpointer for testing.
    fn build_test_graph() -> (CompiledGraph, Arc<MemoryCheckpointer>) {
        let checkpointer = Arc::new(MemoryCheckpointer::new());

        let node = FunctionNode::new("increment", |ctx: NodeContext| {
            let count = ctx.get("count").and_then(|v| v.as_i64()).unwrap_or(0);
            Box::pin(async move { Ok(NodeOutput::new().with_update("count", json!(count + 1))) })
        });

        let graph = StateGraph::new(StateSchema::simple(&["count"]))
            .add_node(node)
            .add_edge("__start__", "increment")
            .add_edge("increment", "__end__")
            .compile()
            .unwrap()
            .with_checkpointer_arc(checkpointer.clone());

        (graph, checkpointer)
    }

    /// Helper: seed checkpoints for a thread.
    async fn seed_checkpoints(checkpointer: &MemoryCheckpointer, thread_id: &str, count: usize) {
        for step in 0..count {
            let mut state = State::new();
            state.insert("count".to_string(), json!(step));
            let cp = Checkpoint::new(thread_id, state, step, vec!["increment".to_string()])
                .with_version(step as u64 + 1);
            checkpointer.save(&cp).await.unwrap();
        }
    }

    #[tokio::test]
    async fn test_fork_at_creates_new_thread() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 5).await;

        let handle = graph.time_travel("thread_1").unwrap();

        // Fork at step 2
        handle.fork_at(2, "thread_1_fork").await.unwrap();

        // Verify the forked thread has a checkpoint
        let forked_checkpoints = checkpointer.list("thread_1_fork").await.unwrap();
        assert_eq!(forked_checkpoints.len(), 1);
        assert_eq!(forked_checkpoints[0].step, 2);
        assert_eq!(forked_checkpoints[0].state.get("count"), Some(&json!(2)));

        // Verify original thread is unchanged
        let original_checkpoints = checkpointer.list("thread_1").await.unwrap();
        assert_eq!(original_checkpoints.len(), 5);
    }

    #[tokio::test]
    async fn test_fork_at_nonexistent_step_errors() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 3).await;

        let handle = graph.time_travel("thread_1").unwrap();

        let result = handle.fork_at(99, "new_thread").await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("no checkpoint found at step 99"));
    }

    #[tokio::test]
    async fn test_state_history_returns_states_in_range() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 5).await;

        let handle = graph.time_travel("thread_1").unwrap();

        // Replay steps 1 through 3
        let results = handle.state_history(1, Some(3)).await.unwrap();
        assert_eq!(results.len(), 3);
        assert_eq!(
            results[0],
            (1, {
                let mut s = State::new();
                s.insert("count".to_string(), json!(1));
                s
            })
        );
        assert_eq!(results[1].0, 2);
        assert_eq!(results[2].0, 3);
    }

    #[tokio::test]
    async fn test_state_history_to_end() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 5).await;

        let handle = graph.time_travel("thread_1").unwrap();

        // Replay from step 2 to end (None)
        let results = handle.state_history(2, None).await.unwrap();
        assert_eq!(results.len(), 3); // steps 2, 3, 4
        assert_eq!(results[0].0, 2);
        assert_eq!(results[1].0, 3);
        assert_eq!(results[2].0, 4);
    }

    #[tokio::test]
    async fn test_replay_nonexistent_from_step_errors() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 3).await;

        let handle = graph.time_travel("thread_1").unwrap();

        let result = handle.state_history(99, None).await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("no checkpoint found at step 99"));
    }

    #[tokio::test]
    async fn test_resume_from_executes_graph() {
        let (graph, checkpointer) = build_test_graph();

        // Seed a checkpoint at step 0 with count=5
        let mut state = State::new();
        state.insert("count".to_string(), json!(5));
        let cp =
            Checkpoint::new("thread_1", state, 0, vec!["increment".to_string()]).with_version(1);
        checkpointer.save(&cp).await.unwrap();

        let handle = graph.time_travel("thread_1").unwrap();

        // Resume from step 0 — the graph should execute "increment" and produce count=6
        let config = ExecutionConfig::new("thread_1");
        let final_state = handle.resume_from(0, config).await.unwrap();
        assert_eq!(final_state.get("count"), Some(&json!(6)));
    }

    #[tokio::test]
    async fn test_resume_from_nonexistent_step_errors() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 3).await;

        let handle = graph.time_travel("thread_1").unwrap();

        let config = ExecutionConfig::new("thread_1");
        let result = handle.resume_from(99, config).await;
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(err_msg.contains("no checkpoint found at step 99"));
    }

    #[tokio::test]
    async fn test_fork_independence() {
        let (graph, checkpointer) = build_test_graph();
        seed_checkpoints(&checkpointer, "thread_1", 5).await;

        let handle = graph.time_travel("thread_1").unwrap();

        // Fork at step 2
        handle.fork_at(2, "forked").await.unwrap();

        // Modify the forked thread by adding another checkpoint
        let mut new_state = State::new();
        new_state.insert("count".to_string(), json!(100));
        let new_cp = Checkpoint::new("forked", new_state, 3, vec![]).with_version(2);
        checkpointer.save(&new_cp).await.unwrap();

        // Verify original thread is unchanged
        let original = checkpointer.list("thread_1").await.unwrap();
        assert_eq!(original.len(), 5);
        for cp in &original {
            assert_ne!(cp.state.get("count"), Some(&json!(100)));
        }
    }
}