loopflow 0.12.0

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
//! Turn vocabulary: `ChatTurn`, the wire type Loopflow consumes.
//!
//! The wave's loop runs each turn as a bounded `wave` child inside
//! the RESIDENT process (see [`crate::flowloop::wave`]) and reports it as
//! resident wire deltas ([`crate::wave::wire`]), folded by the listener's
//! runtime into journaled, broadcast turns.
//!
//! Mapping:
//! - a human message becomes one `user` turn;
//! - each agent turn (text + tool activity, closed by the vendor's turn
//!   completion) becomes one `assistant` turn whose `items` capture the
//!   commands/edits/messages it ran.

use serde::{Deserialize, Serialize};

use crate::chat::types::{ConversationItem, Lifecycle};
use crate::child_session::{
    ChildBodyOutcome, ChildCommandEffect, ChildCommandState, ChildProcessGeneration,
};
use crate::project_session::{ProjectEventKind, ProjectObservation};
use crate::task::{TaskEventKind, TaskObservation};
use crate::wave::playhead::{now_rfc3339, BodyProvenance};

/// Who authored a turn. Mirrors Swift `MessageRole` (user/assistant).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChatRole {
    User,
    Assistant,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChildActivitySubject {
    Project,
    Task,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ChildActivityKind {
    StateChanged,
    ControlApplied,
    ControlUncertain,
    Directed,
    Incorporated,
    DecisionRequired,
    DecisionResolved,
    PrOpened,
    Completed,
    Failed,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ChildControlActivity {
    pub id: String,
    pub subject: ChildActivitySubject,
    pub subject_id: String,
    pub session_id: String,
    pub kind: ChildActivityKind,
    pub title: String,
    pub summary: String,
    pub directive_version: Option<u32>,
    pub command_id: Option<String>,
    pub effect: Option<ChildCommandEffect>,
    pub source: Option<crate::child_session::ChildCommandSource>,
    pub decision_id: Option<String>,
    pub options: Vec<String>,
}

impl ChildControlActivity {
    pub fn from_task(observation: &TaskObservation) -> Self {
        let fields = task_activity_fields(&observation.event);
        Self {
            id: observation.inbox_id(),
            subject: ChildActivitySubject::Task,
            subject_id: observation.issue_identifier.clone(),
            session_id: observation.session_id.to_string(),
            kind: fields.kind,
            title: fields.title,
            summary: fields.summary,
            directive_version: fields.directive_version,
            command_id: fields.command_id,
            effect: fields.effect,
            source: observation.control_source.clone(),
            decision_id: fields.decision_id,
            options: fields.options,
        }
    }

    pub fn from_project(observation: &ProjectObservation) -> Self {
        let fields = project_activity_fields(&observation.event);
        Self {
            id: observation.inbox_id(),
            subject: ChildActivitySubject::Project,
            subject_id: observation.project.clone(),
            session_id: observation.session_id.to_string(),
            kind: fields.kind,
            title: fields.title,
            summary: fields.summary,
            directive_version: fields.directive_version,
            command_id: fields.command_id,
            effect: fields.effect,
            source: observation.control_source.clone(),
            decision_id: fields.decision_id,
            options: fields.options,
        }
    }
}

/// One turn in a wave chat — the unit the chat server streams.
///
/// Wire type consumed by Loopflow. Every field is required (no serde defaults):
/// the same shape round-trips through Rust and Swift.
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct ChatTurn {
    /// Stable within the wave journal across restarts: `"turn-1"`, `"turn-2"`, …
    pub id: String,
    pub role: ChatRole,
    /// Accumulated assistant prose (or the human message for a `user` turn).
    pub text: String,
    /// Lifecycle of the turn. A `user` turn is always `Completed`.
    pub status: Lifecycle,
    /// Tool/command/file/message items the agent produced, in order.
    pub items: Vec<ConversationItem>,
    /// RFC 3339 timestamp of when the turn opened.
    pub created_at: String,
    /// Speaker label for attributed emissions (`lf radio pub` — worker reports,
    /// child-wave escalations). Absent for the loop's own turns and plain
    /// user turns.
    pub from: Option<String>,
    /// Body that produced an assistant span. Required on the wire and
    /// explicitly null for human/attributed turns.
    pub body: Option<BodyProvenance>,
    /// Structured child motion rendered as a linked activity card. Required on
    /// the wire and explicitly null for ordinary conversation turns.
    pub activity: Option<ChildControlActivity>,
}

/// One live increment to an open turn: the `turn-delta` SSE frame. The listener
/// broadcasts one per non-finalizing content delta instead of re-serializing the
/// whole `ChatTurn` (see `crate::wave::runtime` — that whole-turn-per-token
/// re-broadcast was O(prose²) on the wire). The client applies it with
/// [`ChatTurn::absorb_item`] against the turn named by `turn_id`, reconstructing
/// exactly what the listener holds; the finalized whole `turn` frame then
/// re-baselines it at turn close. Every field required — same DTO discipline as
/// [`ChatTurn`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct TurnDelta {
    /// The open turn this increment grows (`"turn-<n>"`).
    pub turn_id: String,
    /// The item to absorb — a stream `Message` fragment grows `text`, any other
    /// item appends to `items`, exactly as the listener's fold does.
    pub item: ConversationItem,
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum ChatTurnError {
    #[error("child activity entries cannot also carry prose, items, or a provider body")]
    MixedActivity,
    #[error("child activity entries must be completed attributed user-side entries")]
    InvalidActivityEnvelope,
    #[error("human turns must be completed and cannot carry provider items or a body")]
    InvalidHumanTurn,
}

impl ChatTurn {
    /// A completed `user` turn carrying a human message.
    pub fn user(id: String, text: String) -> Self {
        Self {
            id,
            role: ChatRole::User,
            text,
            status: Lifecycle::Completed,
            items: Vec::new(),
            created_at: now_rfc3339(),
            from: None,
            body: None,
            activity: None,
        }
    }

    pub fn child_activity(
        id: String,
        created_at: String,
        from: String,
        activity: ChildControlActivity,
    ) -> Self {
        Self {
            id,
            role: ChatRole::User,
            text: String::new(),
            status: Lifecycle::Completed,
            items: Vec::new(),
            created_at,
            from: Some(from),
            body: None,
            activity: Some(activity),
        }
    }

    pub fn validate(&self) -> Result<(), ChatTurnError> {
        if self.activity.is_some() {
            if !self.text.is_empty() || !self.items.is_empty() || self.body.is_some() {
                return Err(ChatTurnError::MixedActivity);
            }
            if self.role != ChatRole::User
                || self.status != Lifecycle::Completed
                || self.from.is_none()
            {
                return Err(ChatTurnError::InvalidActivityEnvelope);
            }
        } else if self.role == ChatRole::User
            && (self.status != Lifecycle::Completed
                || !self.items.is_empty()
                || self.body.is_some())
        {
            return Err(ChatTurnError::InvalidHumanTurn);
        }
        Ok(())
    }

    /// The one turn-growth rule every projection shares. The listener's
    /// open-turn snapshot, the journal fold (`fold_thread`), and the resident's
    /// adapter (`EventAdapter`) all grow turns through this — a second copy is
    /// the live-vs-replay split-brain the journal exists to kill.
    ///
    /// Prose joins `text`: a `stream` fragment concatenates verbatim, any other
    /// message (a `final_answer`, an untagged span) joins newline-separated.
    /// The one exception is `commentary` — operational narration the provider
    /// tagged as process, not conclusion. It stays a discrete item so the
    /// surface can curate it behind a disclosure (see Swift `turnPresentation`);
    /// folding it into `text` erased the tag and left that curation with nothing
    /// to fold. Every non-message item appends to `items` as before.
    pub fn absorb_item(&mut self, item: ConversationItem) {
        if let ConversationItem::Message { text, phase, .. } = &item {
            match phase.as_deref() {
                Some("stream") => {
                    self.text.push_str(text);
                    return;
                }
                Some("commentary") => {}
                _ => {
                    self.push_text(text);
                    return;
                }
            }
        }
        self.items.push(item);
    }

    /// Close the body that produced this turn, if it had one. Every terminal
    /// path goes through here — the live finalizers, the boot janitor, and the
    /// journal fold — so a replayed turn's body reads exactly as the live one
    /// did. Human and attributed turns have no body and close as a no-op.
    pub fn close_body(&mut self, ended_at: String, reason: Option<String>) {
        if let Some(body) = self.body.as_mut() {
            body.ended_at = Some(ended_at);
            body.termination_reason = reason;
        }
    }

    /// Join a prose fragment into the turn text, newline-separated.
    pub fn push_text(&mut self, fragment: &str) {
        if !self.text.is_empty() {
            self.text.push('\n');
        }
        self.text.push_str(fragment);
    }
}

impl<'de> Deserialize<'de> for ChatTurn {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Wire {
            id: String,
            role: ChatRole,
            text: String,
            status: Lifecycle,
            items: Vec<ConversationItem>,
            created_at: String,
            from: Option<String>,
            body: Option<BodyProvenance>,
            activity: Option<ChildControlActivity>,
        }

        let wire = Wire::deserialize(deserializer)?;
        let turn = Self {
            id: wire.id,
            role: wire.role,
            text: wire.text,
            status: wire.status,
            items: wire.items,
            created_at: wire.created_at,
            from: wire.from,
            body: wire.body,
            activity: wire.activity,
        };
        turn.validate().map_err(serde::de::Error::custom)?;
        Ok(turn)
    }
}

struct ActivityFields {
    kind: ChildActivityKind,
    title: String,
    summary: String,
    directive_version: Option<u32>,
    command_id: Option<String>,
    effect: Option<ChildCommandEffect>,
    decision_id: Option<String>,
    options: Vec<String>,
}

fn task_activity_fields(event: &TaskEventKind) -> ActivityFields {
    match event {
        TaskEventKind::Started => activity(ChildActivityKind::StateChanged, "Task started", ""),
        TaskEventKind::BodyHandedOff { handoff } => activity(
            ChildActivityKind::StateChanged,
            &format!(
                "Task body handed off: {} → {}",
                handoff.from_agent, handoff.to_agent
            ),
            &handoff.reason,
        ),
        TaskEventKind::BodyLeaseChanged { process } => body_lease_activity("Task", process),
        TaskEventKind::BodyRecoveryAttempted {
            attempt, reason, ..
        } => activity(
            ChildActivityKind::StateChanged,
            &format!("Task body recovered automatically (attempt {attempt})"),
            reason,
        ),
        TaskEventKind::StatusChanged { to, reason, .. } => activity(
            ChildActivityKind::StateChanged,
            &format!("Task is {}", to.as_str()),
            reason,
        ),
        TaskEventKind::CommandChanged {
            command_id,
            state,
            effect,
            error,
        } => ActivityFields {
            command_id: Some(command_id.to_string()),
            effect: *effect,
            ..activity(
                control_activity_kind(*state),
                &format!("Control {}", state.as_str()),
                error.as_deref().unwrap_or_default(),
            )
        },
        TaskEventKind::DirectiveChanged { version, .. } => ActivityFields {
            directive_version: Some(*version),
            ..activity(
                ChildActivityKind::Directed,
                &format!("Direction v{version}"),
                "Waiting for incorporation",
            )
        },
        TaskEventKind::DirectiveIncorporated {
            version, summary, ..
        } => ActivityFields {
            directive_version: Some(*version),
            ..activity(
                ChildActivityKind::Incorporated,
                &format!("Incorporated direction v{version}"),
                summary,
            )
        },
        TaskEventKind::DirectiveReconciled {
            version, summary, ..
        } => ActivityFields {
            directive_version: Some(*version),
            ..activity(
                ChildActivityKind::Incorporated,
                &format!("Reconciled direction v{version} by out-of-band attestation"),
                summary,
            )
        },
        TaskEventKind::DecisionRequested {
            decision_id,
            prompt,
            options,
        } => ActivityFields {
            decision_id: Some(decision_id.to_string()),
            options: options.clone(),
            ..activity(
                ChildActivityKind::DecisionRequired,
                "Decision required",
                prompt,
            )
        },
        TaskEventKind::DecisionResolved { choice, .. } => activity(
            ChildActivityKind::DecisionResolved,
            "Decision resolved",
            choice,
        ),
        TaskEventKind::Progress { summary } => {
            activity(ChildActivityKind::StateChanged, "Task progress", summary)
        }
        TaskEventKind::InteractionReviewRequested { review } => activity(
            ChildActivityKind::DecisionRequired,
            &format!("{} review requested", review.step),
            &review.reason,
        ),
        TaskEventKind::InteractionReviewMessage { author, text, .. } => activity(
            ChildActivityKind::StateChanged,
            &format!("Review message from {}", author.as_str()),
            text,
        ),
        TaskEventKind::InteractionReviewCompleted {
            disposition,
            outcome,
            ..
        } => activity(
            ChildActivityKind::DecisionResolved,
            &format!("Review {}", disposition.as_str()),
            outcome,
        ),
        TaskEventKind::PrStarted {
            sequence, branch, ..
        } => activity(
            ChildActivityKind::StateChanged,
            &format!("Started PR {sequence}"),
            branch,
        ),
        TaskEventKind::PrOpened { number, url, .. } => activity(
            ChildActivityKind::PrOpened,
            &format!("Opened PR #{number}"),
            url,
        ),
        TaskEventKind::PrMerged { number, url, .. } => activity(
            ChildActivityKind::StateChanged,
            &format!("Merged PR #{number}"),
            url,
        ),
        TaskEventKind::Completed { summary, .. } => {
            activity(ChildActivityKind::Completed, "Task completed", summary)
        }
        TaskEventKind::Failed { error, .. } => {
            activity(ChildActivityKind::Failed, "Task failed", error)
        }
    }
}

fn project_activity_fields(event: &ProjectEventKind) -> ActivityFields {
    match event {
        ProjectEventKind::Started => {
            activity(ChildActivityKind::StateChanged, "Project started", "")
        }
        ProjectEventKind::BodyHandedOff { handoff } => activity(
            ChildActivityKind::StateChanged,
            &format!(
                "Project body handed off: {} → {}",
                handoff.from_agent, handoff.to_agent
            ),
            &handoff.reason,
        ),
        ProjectEventKind::BodyLeaseChanged { process } => body_lease_activity("Project", process),
        ProjectEventKind::StatusChanged { to, reason, .. } => activity(
            ChildActivityKind::StateChanged,
            &format!("Project is {}", to.as_str()),
            reason,
        ),
        ProjectEventKind::CommandChanged {
            command_id,
            state,
            effect,
            error,
        } => ActivityFields {
            command_id: Some(command_id.to_string()),
            effect: *effect,
            ..activity(
                control_activity_kind(*state),
                &format!("Control {}", state.as_str()),
                error.as_deref().unwrap_or_default(),
            )
        },
        ProjectEventKind::DirectiveChanged { version, .. } => ActivityFields {
            directive_version: Some(*version),
            ..activity(
                ChildActivityKind::Directed,
                &format!("Direction v{version}"),
                "Waiting for incorporation",
            )
        },
        ProjectEventKind::DirectiveIncorporated {
            version, summary, ..
        } => ActivityFields {
            directive_version: Some(*version),
            ..activity(
                ChildActivityKind::Incorporated,
                &format!("Incorporated direction v{version}"),
                summary,
            )
        },
        ProjectEventKind::TaskObserved { event, .. } => task_activity_fields(event),
        ProjectEventKind::DecisionRequested {
            decision_id,
            prompt,
            options,
        } => ActivityFields {
            decision_id: Some(decision_id.to_string()),
            options: options.clone(),
            ..activity(
                ChildActivityKind::DecisionRequired,
                "Decision required",
                prompt,
            )
        },
        ProjectEventKind::DecisionResolved { choice, .. } => activity(
            ChildActivityKind::DecisionResolved,
            "Decision resolved",
            choice,
        ),
        ProjectEventKind::IterationCompleted { summary, .. } => activity(
            ChildActivityKind::StateChanged,
            "Project iteration completed",
            summary,
        ),
        ProjectEventKind::Completed { summary } => {
            activity(ChildActivityKind::Completed, "Project completed", summary)
        }
        ProjectEventKind::Failed { error, .. } => {
            activity(ChildActivityKind::Failed, "Project failed", error)
        }
    }
}

fn body_lease_activity(subject: &str, process: &ChildProcessGeneration) -> ActivityFields {
    let summary = match process.outcome.as_ref() {
        Some(ChildBodyOutcome::Completed) => "completed",
        Some(ChildBodyOutcome::Interrupted { reason })
        | Some(ChildBodyOutcome::Failed { reason })
        | Some(ChildBodyOutcome::Lost { reason })
        | Some(ChildBodyOutcome::Superseded { reason })
        | Some(ChildBodyOutcome::LegacyStopped { reason }) => reason,
        None => "",
    };
    activity(
        ChildActivityKind::StateChanged,
        &format!(
            "{subject} body generation {} is {}",
            process.generation,
            process.state.as_str()
        ),
        summary,
    )
}

fn activity(kind: ChildActivityKind, title: &str, summary: &str) -> ActivityFields {
    ActivityFields {
        kind,
        title: title.to_string(),
        summary: summary.to_string(),
        directive_version: None,
        command_id: None,
        effect: None,
        decision_id: None,
        options: Vec::new(),
    }
}

fn control_activity_kind(state: ChildCommandState) -> ChildActivityKind {
    if state == ChildCommandState::Uncertain {
        ChildActivityKind::ControlUncertain
    } else {
        ChildActivityKind::ControlApplied
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn user_turn_round_trips_through_json() {
        let turn = ChatTurn::user("turn-0".into(), "please fix the build".into());
        let value = serde_json::to_value(&turn).expect("serialize");
        let decoded: ChatTurn = serde_json::from_value(value).expect("deserialize");
        assert_eq!(decoded, turn);
        assert_eq!(decoded.role, ChatRole::User);
    }

    #[test]
    fn attributed_turn_round_trips_and_absent_from_decodes_none() {
        let mut turn = ChatTurn::user("turn-1".into(), "worker report".into());
        turn.from = Some("worker".to_string());
        let value = serde_json::to_value(&turn).expect("serialize");
        assert_eq!(value["from"], "worker");
        let decoded: ChatTurn = serde_json::from_value(value).expect("deserialize");
        assert_eq!(decoded.from.as_deref(), Some("worker"));

        // Absent `from` is None — no default masking on the wire.
        let mut value =
            serde_json::to_value(ChatTurn::user("turn-2".into(), "hi".into())).expect("serialize");
        value.as_object_mut().expect("object").remove("from");
        let decoded: ChatTurn = serde_json::from_value(value).expect("deserialize");
        assert_eq!(decoded.from, None);
    }

    #[test]
    fn child_activity_envelope_rejects_mixed_conversation_content() {
        let activity = ChildControlActivity {
            id: "task-ts_example-1".to_string(),
            subject: ChildActivitySubject::Task,
            subject_id: "INF-123".to_string(),
            session_id: "ts_example".to_string(),
            kind: ChildActivityKind::StateChanged,
            title: "Task started".to_string(),
            summary: String::new(),
            directive_version: None,
            command_id: None,
            effect: None,
            source: None,
            decision_id: None,
            options: Vec::new(),
        };
        let turn = ChatTurn::child_activity(
            "turn-activity".to_string(),
            "2026-07-13T20:00:00Z".to_string(),
            "Task INF-123".to_string(),
            activity,
        );
        let mut value = serde_json::to_value(turn).expect("serialize activity turn");
        value["text"] = serde_json::Value::String("mixed prose".to_string());

        let error = serde_json::from_value::<ChatTurn>(value).expect_err("reject mixed activity");
        assert!(error.to_string().contains("cannot also carry prose"));
    }

    #[test]
    fn turn_delta_fixture_round_trips() {
        let fixture = include_str!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../tests/fixtures/dto/turn_delta.json"
        ));
        let delta: TurnDelta = serde_json::from_str(fixture).expect("decode turn_delta fixture");
        assert_eq!(delta.turn_id, "turn-3");
        match &delta.item {
            ConversationItem::Message { id, text, phase } => {
                assert_eq!(id, "text-7");
                assert_eq!(phase.as_deref(), Some("stream"));
                assert!(text.contains("edge case"));
            }
            other => panic!("expected a stream message item, got {other:?}"),
        }
        // Applying the delta grows a turn exactly as the listener's fold does.
        let mut turn = ChatTurn::user("turn-3".into(), String::new());
        turn.role = ChatRole::Assistant;
        turn.push_text("so ");
        turn.absorb_item(delta.item.clone());
        assert_eq!(turn.text, "so the parser handles the edge case now.");
        assert!(
            turn.items.is_empty(),
            "a stream message joins text, not items"
        );

        // Round-trips: re-serialize and decode to the same value.
        let reencoded = serde_json::to_string(&delta).expect("serialize");
        let again: TurnDelta = serde_json::from_str(&reencoded).expect("decode");
        assert_eq!(again, delta);
    }

    #[test]
    fn absorb_item_joins_prose_and_appends_the_rest() {
        let mut turn = ChatTurn::user("turn-3".into(), String::new());
        turn.absorb_item(ConversationItem::Message {
            id: "m-1".into(),
            text: "first".into(),
            phase: None,
        });
        turn.absorb_item(ConversationItem::Tool {
            id: "t-1".into(),
            name: "Bash".into(),
            status: Lifecycle::Completed,
            input: None,
            output: None,
        });
        turn.absorb_item(ConversationItem::Message {
            id: "m-2".into(),
            text: "second".into(),
            phase: None,
        });

        assert_eq!(turn.text, "first\nsecond");
        assert_eq!(turn.items.len(), 1, "prose joins text, tools append");
    }

    #[test]
    fn absorb_item_keeps_commentary_as_a_curatable_item() {
        // The provider tags operational narration `commentary`; it must survive
        // the fold as a discrete item so the surface can curate it. Folding it
        // into `text` (as every message once did) erased the tag.
        let mut turn = ChatTurn::user("turn-10".into(), String::new());
        turn.role = ChatRole::Assistant;
        turn.absorb_item(ConversationItem::Message {
            id: "m-0".into(),
            text: "I'm using `wave_clarify` to audit the plan.".into(),
            phase: Some("commentary".into()),
        });
        turn.absorb_item(ConversationItem::Message {
            id: "m-1".into(),
            text: "Clarification complete.".into(),
            phase: Some("final_answer".into()),
        });

        // The conclusion is the prose; the narration waits in items, untangled
        // from the text so `turnPresentation` can fold it behind a disclosure.
        assert_eq!(turn.text, "Clarification complete.");
        assert_eq!(turn.items.len(), 1);
        match &turn.items[0] {
            ConversationItem::Message { text, phase, .. } => {
                assert_eq!(phase.as_deref(), Some("commentary"));
                assert!(text.contains("wave_clarify"));
            }
            other => panic!("expected the commentary message in items, got {other:?}"),
        }
    }

    #[test]
    fn absorb_item_concatenates_stream_fragments_exactly() {
        let mut turn = ChatTurn::user("turn-4".into(), String::new());
        for text in ["hello", " ", "world"] {
            turn.absorb_item(ConversationItem::Message {
                id: format!("m-{}", turn.text.len()),
                text: text.into(),
                phase: Some("stream".into()),
            });
        }

        assert_eq!(turn.text, "hello world");
    }

    #[test]
    fn decision_activity_keeps_options_and_lineage() {
        let decision_id = crate::child_session::ChildDecisionId::new();
        let observation = TaskObservation {
            session_id: crate::task::TaskSessionId::new(),
            issue_identifier: "INF-123".to_string(),
            event_id: 9,
            control_source: None,
            event: TaskEventKind::DecisionRequested {
                decision_id: decision_id.clone(),
                prompt: "Which parser mode?".to_string(),
                options: vec!["strict".to_string(), "permissive".to_string()],
            },
        };

        let activity = ChildControlActivity::from_task(&observation);
        assert_eq!(activity.kind, ChildActivityKind::DecisionRequired);
        assert_eq!(activity.decision_id.as_deref(), Some(decision_id.as_str()));
        assert_eq!(activity.options, ["strict", "permissive"]);
    }

    #[test]
    fn command_activity_keeps_the_applied_effect() {
        let command_id = crate::child_session::ChildCommandId::new();
        let wave_id = crate::id::WaveId::new();
        let observation = TaskObservation {
            session_id: crate::task::TaskSessionId::new(),
            issue_identifier: "INF-123".to_string(),
            event_id: 10,
            control_source: Some(crate::child_session::ChildCommandSource::Wave(
                wave_id.clone(),
            )),
            event: TaskEventKind::CommandChanged {
                command_id: command_id.clone(),
                state: crate::child_session::ChildCommandState::Accepted,
                effect: Some(ChildCommandEffect::LiveSteer),
                error: None,
            },
        };

        let activity = ChildControlActivity::from_task(&observation);
        assert_eq!(activity.kind, ChildActivityKind::ControlApplied);
        assert_eq!(activity.command_id.as_deref(), Some(command_id.as_str()));
        assert_eq!(activity.effect, Some(ChildCommandEffect::LiveSteer));
        assert_eq!(activity.directive_version, None);
        assert_eq!(
            activity.source,
            Some(crate::child_session::ChildCommandSource::Wave(wave_id))
        );
    }

    #[test]
    fn ambiguous_provider_delivery_is_visibly_uncertain() {
        let observation = TaskObservation {
            session_id: crate::task::TaskSessionId::new(),
            issue_identifier: "INF-123".to_string(),
            event_id: 11,
            control_source: Some(crate::child_session::ChildCommandSource::System),
            event: TaskEventKind::CommandChanged {
                command_id: crate::child_session::ChildCommandId::new(),
                state: ChildCommandState::Uncertain,
                effect: None,
                error: Some("provider delivery outcome is unknown".to_string()),
            },
        };

        let activity = ChildControlActivity::from_task(&observation);
        assert_eq!(activity.kind, ChildActivityKind::ControlUncertain);
        assert_eq!(activity.title, "Control uncertain");
        assert!(activity.summary.contains("unknown"));
    }
}