loopflow 0.12.5

Run steps and flows with coding 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
//! Durable input and execution identity shared by Wave, Project, and Task Work.

use std::path::PathBuf;

use serde::{Deserialize, Serialize};
use time::OffsetDateTime;

use crate::id::WaveId;

/// The one opaque capability inherited by every command inside an active Run.
pub const RUN_LEASE_ENV: &str = "LF_RUN_LEASE";

/// The exact core invocation started for an in-Run agent entrypoint.
pub const AGENT_INVOCATION_ENV: &str = "LF_AGENT_INVOCATION_ID";

/// Marks a process as an in-Run agent entrypoint even if its capability was
/// accidentally stripped. That case must fail closed rather than become User.
pub const RUN_CONTEXT_ENV: &str = "LF_RUN_CONTEXT";

macro_rules! durable_id {
    ($name:ident, $prefix:literal) => {
        #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
        #[serde(transparent)]
        pub struct $name(String);

        impl $name {
            pub fn new() -> Self {
                Self(format!("{}{}", $prefix, uuid::Uuid::new_v4().simple()))
            }

            pub fn parse(value: &str) -> Result<Self, DurableDataError> {
                let suffix = value.strip_prefix($prefix).ok_or_else(|| {
                    DurableDataError::InvalidId(format!("expected {} id", $prefix))
                })?;
                uuid::Uuid::parse_str(suffix)
                    .map_err(|error| DurableDataError::InvalidId(error.to_string()))?;
                Ok(Self(value.to_string()))
            }

            pub fn as_str(&self) -> &str {
                &self.0
            }
        }

        impl Default for $name {
            fn default() -> Self {
                Self::new()
            }
        }

        impl std::fmt::Display for $name {
            fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                formatter.write_str(&self.0)
            }
        }

        impl std::str::FromStr for $name {
            type Err = DurableDataError;

            fn from_str(value: &str) -> Result<Self, Self::Err> {
                Self::parse(value)
            }
        }
    };
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum DurableDataError {
    #[error("invalid durable id: {0}")]
    InvalidId(String),
    #[error("invalid epoch state: {0}")]
    InvalidEpochState(String),
    #[error("invalid send state: {0}")]
    InvalidSendState(String),
    #[error("invalid run state: {0}")]
    InvalidRunState(String),
    #[error("invalid invocation state: {0}")]
    InvalidInvocationState(String),
    #[error("invalid boundary state: {0}")]
    InvalidBoundaryState(String),
}

durable_id!(ProjectId, "proj_");
durable_id!(TaskId, "task_");
durable_id!(EpochId, "epoch_");
durable_id!(RunId, "run_");
durable_id!(AgentInvocationId, "invocation_");
durable_id!(TurnId, "turn_");
durable_id!(AskId, "ask_");
durable_id!(WaitId, "wait_");
durable_id!(HomeId, "home_");
durable_id!(SteerId, "steer_");
durable_id!(SendId, "send_");
durable_id!(ToolResponseId, "response_");
durable_id!(DoneProposalId, "done_");

impl ProjectId {
    pub(crate) fn from_raw(value: impl Into<String>) -> Self {
        Self(value.into())
    }
}

impl TaskId {
    pub(crate) fn from_raw(value: impl Into<String>) -> Self {
        Self(value.into())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum WorkRef {
    Wave(WaveId),
    Project(ProjectId),
    Task(TaskId),
}

impl WorkRef {
    pub fn kind(&self) -> &'static str {
        match self {
            Self::Wave(_) => "wave",
            Self::Project(_) => "project",
            Self::Task(_) => "task",
        }
    }

    pub fn id(&self) -> &str {
        match self {
            Self::Wave(id) => id.as_str(),
            Self::Project(id) => id.as_str(),
            Self::Task(id) => id.as_str(),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum EpochState {
    Open,
    Done,
    Abandoned,
}

impl EpochState {
    pub(crate) fn parse(value: &str) -> Result<Self, DurableDataError> {
        match value {
            "open" => Ok(Self::Open),
            "done" => Ok(Self::Done),
            "abandoned" => Ok(Self::Abandoned),
            value => Err(DurableDataError::InvalidEpochState(value.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct Basis {
    pub epoch_id: EpochId,
    pub revision: u64,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Epoch {
    pub id: EpochId,
    pub work: WorkRef,
    pub number: u32,
    pub state: EpochState,
    pub current_basis: Basis,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub terminal_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum RunState {
    Reserved,
    Active,
    Stopping,
    Ended,
}

impl RunState {
    pub(crate) fn parse(value: &str) -> Result<Self, DurableDataError> {
        match value {
            "reserved" => Ok(Self::Reserved),
            "active" => Ok(Self::Active),
            "stopping" => Ok(Self::Stopping),
            "ended" => Ok(Self::Ended),
            value => Err(DurableDataError::InvalidRunState(value.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum RunTrigger {
    Migration,
    Input {
        basis: Basis,
    },
    Time {
        #[serde(with = "time::serde::rfc3339")]
        scheduled_at: OffsetDateTime,
    },
    Event {
        event: EventRef,
    },
    Child {
        work: WorkRef,
    },
    CiIncident {
        incident_id: String,
    },
    Recovery {
        prior_run_id: RunId,
    },
    User,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Run {
    pub id: RunId,
    pub work: WorkRef,
    pub epoch_id: EpochId,
    pub home_id: HomeId,
    pub state: RunState,
    pub trigger: RunTrigger,
    pub retry_of: Option<RunId>,
    pub containment: Option<Containment>,
    pub cwd: Option<PathBuf>,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub started_at: Option<OffsetDateTime>,
    #[serde(with = "time::serde::rfc3339::option")]
    pub ended_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Home {
    pub id: HomeId,
    pub route: String,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339")]
    pub observed_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Placement {
    pub work: WorkRef,
    pub home_id: HomeId,
    #[serde(with = "time::serde::rfc3339")]
    pub placed_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum WaitOn {
    Input {
        after: Basis,
    },
    Time {
        #[serde(with = "time::serde::rfc3339")]
        not_before: OffsetDateTime,
    },
    Event {
        event: EventRef,
    },
    Child {
        work: WorkRef,
    },
    Capability {
        capability: CapabilityRef,
    },
    Effect {
        effect: EffectRef,
    },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventRef {
    pub source: String,
    pub id: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct CapabilityRef {
    pub kind: String,
    pub key: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EffectRef {
    pub kind: String,
    pub idempotency_key: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Wait {
    pub id: WaitId,
    pub work: WorkRef,
    pub epoch_id: EpochId,
    pub on: WaitOn,
    #[serde(with = "time::serde::rfc3339")]
    pub created_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub resolved_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvocationRoute {
    pub provider: String,
    pub model: Option<String>,
    pub account_id: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum Containment {
    ProcessGroup { id: i64 },
    Tmux { name: String },
}

impl Containment {
    pub(crate) fn parts(&self) -> (&'static str, String) {
        match self {
            Self::ProcessGroup { id } => ("process_group", id.to_string()),
            Self::Tmux { name } => ("tmux", name.clone()),
        }
    }

    pub(crate) fn parse(kind: &str, id: String) -> Result<Self, DurableDataError> {
        match kind {
            "process_group" => id
                .parse()
                .map(|id| Self::ProcessGroup { id })
                .map_err(|error| {
                    DurableDataError::InvalidRunState(format!(
                        "invalid process group {id:?}: {error}"
                    ))
                }),
            "tmux" => Ok(Self::Tmux { name: id }),
            value => Err(DurableDataError::InvalidRunState(format!(
                "invalid containment kind: {value}"
            ))),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AgentInvocation {
    pub id: AgentInvocationId,
    pub supervising_run_id: Option<RunId>,
    pub answer_ask_id: Option<AskId>,
    pub route: InvocationRoute,
    pub surface: String,
    pub resume_token: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub started_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub ended_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum BoundaryState {
    Starting,
    Active,
    Succeeded,
    Failed,
    Interrupted,
    Unknown,
}

impl BoundaryState {
    pub fn is_terminal(self) -> bool {
        matches!(
            self,
            Self::Succeeded | Self::Failed | Self::Interrupted | Self::Unknown
        )
    }

    pub(crate) fn parse_handback(value: &str) -> Result<Self, DurableDataError> {
        match value {
            "succeeded" => Ok(Self::Succeeded),
            "failed" => Ok(Self::Failed),
            "interrupted" => Ok(Self::Interrupted),
            "unknown" => Ok(Self::Unknown),
            value => Err(DurableDataError::InvalidInvocationState(format!(
                "invalid Invocation handback state: {value}"
            ))),
        }
    }

    pub(crate) fn as_invocation_outcome(self) -> &'static str {
        match self {
            Self::Starting | Self::Active => "running",
            Self::Succeeded => "completed",
            Self::Failed | Self::Unknown => "failed",
            Self::Interrupted => "interrupted",
        }
    }

    pub(crate) fn as_turn_status(self) -> &'static str {
        match self {
            Self::Starting | Self::Active => "running",
            Self::Succeeded => "completed",
            Self::Failed => "failed",
            Self::Interrupted => "interrupted",
            Self::Unknown => "partial",
        }
    }

    pub(crate) fn parse_turn(value: &str) -> Result<Self, DurableDataError> {
        match value {
            "running" => Ok(Self::Active),
            "completed" => Ok(Self::Succeeded),
            "failed" => Ok(Self::Failed),
            "interrupted" => Ok(Self::Interrupted),
            "partial" => Ok(Self::Unknown),
            value => Err(DurableDataError::InvalidBoundaryState(value.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Turn {
    pub id: TurnId,
    pub invocation_id: AgentInvocationId,
    pub basis: Basis,
    pub state: BoundaryState,
    pub provider_turn_id: Option<String>,
    pub root_output: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub started_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub ended_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "work", rename_all = "snake_case")]
pub enum AnswerRoute {
    User,
    Parent(WorkRef),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Answer {
    pub ask_id: AskId,
    pub author: Author,
    pub text: String,
    #[serde(with = "time::serde::rfc3339")]
    pub answered_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AskExchange {
    pub id: AskId,
    pub turn_id: TurnId,
    pub route: AnswerRoute,
    pub question: String,
    #[serde(with = "time::serde::rfc3339")]
    pub asked_at: OffsetDateTime,
    pub answer: Option<Answer>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnswerContext {
    pub ask: AskExchange,
    pub child: WorkRef,
    pub epoch_id: EpochId,
    pub prior_exchanges: Vec<AskExchange>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AnswerAttemptHistory {
    pub failed_attempts: u32,
    pub last_failed_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunAdvance {
    RunStarting {
        containment: Containment,
        cwd: PathBuf,
    },
    InvocationStarting {
        route: InvocationRoute,
        surface: String,
        resume_token: Option<String>,
        answer_ask_id: Option<AskId>,
    },
    InvocationEnded {
        invocation_id: AgentInvocationId,
        outcome: BoundaryState,
    },
    TurnStarting {
        invocation_id: AgentInvocationId,
    },
    TurnActive {
        turn_id: TurnId,
        provider_turn_id: Option<String>,
    },
    TurnEnded {
        turn_id: TurnId,
        outcome: BoundaryState,
    },
    Wait {
        on: WaitOn,
    },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AdvanceReceipt {
    Run(Run),
    Invocation(AgentInvocation),
    Turn(Turn),
    Wait(Wait),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", content = "id", rename_all = "snake_case")]
pub enum Author {
    User,
    Run(RunId),
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Steer {
    pub id: SteerId,
    pub work: WorkRef,
    pub basis: Basis,
    pub author: Author,
    pub text: String,
    #[serde(with = "time::serde::rfc3339")]
    pub issued_at: OffsetDateTime,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SendVia {
    Live,
    Seed,
}

impl SendVia {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Live => "live",
            Self::Seed => "seed",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SendState {
    Sending,
    Sent,
    Failed,
    Unknown,
}

impl SendState {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            Self::Sending => "sending",
            Self::Sent => "sent",
            Self::Failed => "failed",
            Self::Unknown => "unknown",
        }
    }

    pub(crate) fn parse(value: &str) -> Result<Self, DurableDataError> {
        match value {
            "sending" => Ok(Self::Sending),
            "sent" => Ok(Self::Sent),
            "failed" => Ok(Self::Failed),
            "unknown" => Ok(Self::Unknown),
            value => Err(DurableDataError::InvalidSendState(value.to_string())),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Send {
    pub id: SendId,
    pub steer_id: SteerId,
    pub turn_id: String,
    pub via: SendVia,
    pub state: SendState,
    pub provider_turn_id: Option<String>,
    pub reason: Option<String>,
    #[serde(with = "time::serde::rfc3339")]
    pub attempted_at: OffsetDateTime,
    #[serde(with = "time::serde::rfc3339::option")]
    pub finished_at: Option<OffsetDateTime>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SteerReceipt {
    pub steer: Steer,
    pub sends: Vec<Send>,
    pub applied_by: Option<Basis>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundarySeed {
    pub basis: Basis,
    pub steers: Vec<Steer>,
}

impl BoundarySeed {
    pub fn render(&self) -> String {
        if self.steers.is_empty() {
            return String::new();
        }
        let direction = self
            .steers
            .iter()
            .map(|steer| format!("- [rev {}] {}", steer.basis.revision, steer.text))
            .collect::<Vec<_>>()
            .join("\n");
        format!(
            "<lf:steers basis=\"{}:{}\">\n{}\n</lf:steers>",
            self.basis.epoch_id, self.basis.revision, direction
        )
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolResponseWrite {
    pub request_id: String,
    pub choice: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolResponseReceipt {
    pub id: ToolResponseId,
    pub work: WorkRef,
    pub basis: Basis,
    pub request_id: String,
    pub choice: String,
    #[serde(with = "time::serde::rfc3339")]
    pub responded_at: OffsetDateTime,
}

/// Authenticated Home-local entrypoint. It is deliberately not serializable.
#[derive(Debug)]
pub struct AuthenticatedRequest {
    _private: (),
}

impl AuthenticatedRequest {
    pub(crate) fn cli() -> Self {
        Self { _private: () }
    }
}

/// An already-validated Run capability. Tokens never enter durable DTOs.
#[derive(Debug, Clone)]
pub struct RunLease {
    pub run_id: RunId,
    pub work: WorkRef,
    pub basis: Basis,
    _token: RunLeaseToken,
}

/// Direct lifecycle control observed by the exact active Run.
///
/// This is a projection over Run, Epoch, AgentInvocation, and Turn state. It is not a
/// stored inbox: the mutation already landed on the authority it controls.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RunControl {
    Interrupt,
    Abandon { reason: String },
}

impl RunLease {
    pub(crate) fn new(run_id: RunId, work: WorkRef, basis: Basis, token: RunLeaseToken) -> Self {
        Self {
            run_id,
            work,
            basis,
            _token: token,
        }
    }

    pub(crate) fn token_hash(&self) -> String {
        self._token.hash()
    }

    pub(crate) fn env_value(&self) -> &str {
        self._token.env_value()
    }
}

/// Opaque capability for the one active Run. It is never serialized or shown.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct RunLeaseToken(String);

impl RunLeaseToken {
    pub(crate) fn new() -> Self {
        Self(format!("rl_{}", uuid::Uuid::new_v4().simple()))
    }

    pub(crate) fn parse(value: &str) -> Result<Self, DurableDataError> {
        let value = value.trim();
        let suffix = value
            .strip_prefix("rl_")
            .ok_or_else(|| DurableDataError::InvalidId("expected opaque Run lease".to_string()))?;
        uuid::Uuid::parse_str(suffix)
            .map_err(|error| DurableDataError::InvalidId(error.to_string()))?;
        Ok(Self(value.to_string()))
    }

    pub(crate) fn env_value(&self) -> &str {
        &self.0
    }

    pub(crate) fn hash(&self) -> String {
        use sha2::{Digest, Sha256};

        format!("{:x}", Sha256::digest(self.0.as_bytes()))
    }
}

impl std::fmt::Debug for RunLeaseToken {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter.write_str("RunLeaseToken([REDACTED])")
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DoneProposal {
    pub id: DoneProposalId,
    pub run_id: RunId,
    pub basis: Basis,
    #[serde(with = "time::serde::rfc3339")]
    pub proposed_at: OffsetDateTime,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WorkStatus {
    Ready,
    Running { run_id: RunId },
    Waiting { wait: Wait },
    Done,
    Abandoned,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FlowPosition {
    pub work: WorkRef,
    pub epoch_id: EpochId,
    pub flow: String,
    pub step: String,
    pub step_index: u32,
    pub iteration: u32,
    #[serde(with = "time::serde::rfc3339")]
    pub updated_at: OffsetDateTime,
}

/// The generic surface for reopening an opaque or provider-backed Invocation.
/// Attach is a route projection; it does not create identity or liveness.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InvocationSurface {
    pub invocation: AgentInvocation,
    pub run: Run,
    pub work: WorkRef,
    pub wave_id: WaveId,
    pub home_route: String,
    pub handback: Option<BoundaryState>,
    pub attach_argv: Option<Vec<String>>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ContainmentObservation {
    Absent,
    Present,
    Unprovable,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum StopCause {
    Requested,
    Interrupted,
    Failed { reason: String },
    Recovery,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct StopReceipt {
    pub run: Run,
    pub containment: ContainmentObservation,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct InterruptReceipt {
    pub run_id: RunId,
    pub turn_ids: Vec<TurnId>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EpochReceipt {
    pub epoch: Epoch,
}

#[derive(Debug)]
pub enum ControlCtx<'a> {
    User(&'a AuthenticatedRequest),
    Run(&'a RunLease),
}

#[cfg(test)]
mod tests {
    use super::{Basis, BoundarySeed, EpochId, InvocationSurface, Steer, WaitOn, WorkStatus};
    use crate::durable::{Author, ProjectId, SteerId, WorkRef};

    #[test]
    fn ordered_steers_render_as_one_basis_projection() {
        let epoch_id = EpochId::new();
        let work = WorkRef::Project(ProjectId::new());
        let steer = |revision, text: &str| Steer {
            id: SteerId::new(),
            work: work.clone(),
            basis: Basis {
                epoch_id: epoch_id.clone(),
                revision,
            },
            author: Author::User,
            text: text.to_string(),
            issued_at: time::OffsetDateTime::UNIX_EPOCH,
        };
        let seed = BoundarySeed {
            basis: Basis {
                epoch_id: epoch_id.clone(),
                revision: 3,
            },
            steers: vec![steer(2, "first"), steer(3, "second")],
        };

        assert_eq!(
            seed.render(),
            format!(
                "<lf:steers basis=\"{}:3\">\n- [rev 2] first\n- [rev 3] second\n</lf:steers>",
                seed.basis.epoch_id
            )
        );
    }

    #[test]
    fn invocation_surface_fixture_round_trips() {
        let fixture = include_str!("../../../tests/fixtures/dto/invocation_surface.json");
        let surface: InvocationSurface = serde_json::from_str(fixture).unwrap();
        assert_eq!(surface.invocation.route.provider, "opaque");
        assert_eq!(surface.work.kind(), "task");

        let encoded = serde_json::to_string(&surface).unwrap();
        let decoded: InvocationSurface = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded, surface);
    }

    #[test]
    fn work_status_fixture_round_trips_every_variant() {
        let fixture = include_str!("../../../tests/fixtures/dto/work_statuses.json");
        let statuses: Vec<WorkStatus> = serde_json::from_str(fixture).unwrap();

        assert!(matches!(statuses[0], WorkStatus::Ready));
        assert!(matches!(statuses[1], WorkStatus::Running { .. }));
        let wait_kinds = statuses[2..8]
            .iter()
            .map(|status| match status {
                WorkStatus::Waiting { wait } => match &wait.on {
                    WaitOn::Input { .. } => "input",
                    WaitOn::Time { .. } => "time",
                    WaitOn::Event { .. } => "event",
                    WaitOn::Child { .. } => "child",
                    WaitOn::Capability { .. } => "capability",
                    WaitOn::Effect { .. } => "effect",
                },
                _ => panic!("expected waiting status"),
            })
            .collect::<Vec<_>>();
        assert_eq!(
            wait_kinds,
            ["input", "time", "event", "child", "capability", "effect"]
        );
        assert!(matches!(statuses[8], WorkStatus::Done));
        assert!(matches!(statuses[9], WorkStatus::Abandoned));

        let encoded = serde_json::to_string(&statuses).unwrap();
        let decoded: Vec<WorkStatus> = serde_json::from_str(&encoded).unwrap();
        assert_eq!(decoded, statuses);
    }
}