loopflow 0.10.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
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
use std::cell::RefCell;
use std::fs::{self, OpenOptions};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::Command;

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

use crate::engine::worktrees::{main_repo_root, wave_name_from_worktree_and_main};
use crate::lfd::id::LfdId;
use crate::lfdb::sqlite::SqliteStore;
use crate::lfdb::RunEventRow;

const JOURNAL_ROOT: &str = ".lf/journal/runs";
const JOURNAL_EXCLUDE_ENTRY: &str = ".lf/journal/";
pub const LF_RUN_ID_ENV: &str = "LF_RUN_ID";

/// Serializes tests that mutate process-global env (LF_HOME, LF_RUN_ID).
/// Every test in the crate that touches these vars must hold this lock —
/// the ledger path is resolved from env at write time.
#[cfg(test)]
pub(crate) fn test_env_lock() -> std::sync::MutexGuard<'static, ()> {
    static LOCK: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new();
    LOCK.get_or_init(|| std::sync::Mutex::new(()))
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
}

thread_local! {
    static RUN_CONTEXT: RefCell<Option<RunContext>> = const { RefCell::new(None) };
    static PENDING_USAGE: RefCell<PendingUsage> = const { RefCell::new(PendingUsage::new()) };
}

#[derive(Debug, Clone)]
struct RunContext {
    run_id: LfdId,
    /// File-journal directory. Written in any git repo (main, wave worktree,
    /// or plain worktree); None only when the journal can't be git-excluded.
    /// The daemon's poller tails wave worktrees; the SQLite ledger records
    /// every run regardless.
    run_dir: Option<PathBuf>,
    repo: Option<String>,
    wave: Option<String>,
    seq: i64,
    /// True when this process minted the run id (vs inheriting LF_RUN_ID);
    /// the export is removed again when the run ends.
    minted_run_id: bool,
}

/// Token/cost totals accumulated from the agent stream on this thread,
/// attached to ledger rows as the run progresses.
#[derive(Debug, Clone, Copy, Default)]
struct PendingUsage {
    input_tokens: u64,
    output_tokens: u64,
    cache_read_tokens: u64,
    cost_usd: Option<f64>,
    duration_secs: Option<f64>,
    seen: bool,
}

impl PendingUsage {
    const fn new() -> Self {
        Self {
            input_tokens: 0,
            output_tokens: 0,
            cache_read_tokens: 0,
            cost_usd: None,
            duration_secs: None,
            seen: false,
        }
    }
}

/// Accumulate token usage reported by the agent stream for the current run.
pub fn record_usage(input: Option<u64>, output: Option<u64>, cache_read: Option<u64>) {
    PENDING_USAGE.with(|cell| {
        let mut usage = cell.borrow_mut();
        usage.input_tokens += input.unwrap_or(0);
        usage.output_tokens += output.unwrap_or(0);
        usage.cache_read_tokens += cache_read.unwrap_or(0);
        usage.seen = true;
    });
}

/// Record the stream's final cost/duration report for the current run.
pub fn record_result(cost_usd: Option<f64>, duration_secs: Option<f64>) {
    PENDING_USAGE.with(|cell| {
        let mut usage = cell.borrow_mut();
        if cost_usd.is_some() {
            usage.cost_usd = cost_usd;
        }
        if duration_secs.is_some() {
            usage.duration_secs = match usage.duration_secs {
                Some(existing) => Some(existing + duration_secs.unwrap_or(0.0)),
                None => duration_secs,
            };
        }
        usage.seen = true;
    });
}

fn snapshot_usage() -> Option<PendingUsage> {
    PENDING_USAGE.with(|cell| {
        let usage = *cell.borrow();
        usage.seen.then_some(usage)
    })
}

fn clear_usage() {
    PENDING_USAGE.with(|cell| {
        *cell.borrow_mut() = PendingUsage::new();
    });
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LfNode {
    Run,
    Flow,
    Step,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LfEventType {
    Started,
    Completed,
    Errored,
    Escalated,
}

#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct LfEventFields {
    pub wave_name: Option<String>,
    pub worktree: Option<String>,
    pub command: Option<Vec<String>>,
    pub flow: Option<String>,
    pub step: Option<String>,
    pub index: Option<u32>,
    pub error: Option<String>,
    pub signal: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct LfEvent {
    pub run_id: LfdId,
    #[serde(with = "time::serde::rfc3339")]
    pub ts: OffsetDateTime,
    pub node: LfNode,
    pub event: LfEventType,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub wave_name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub worktree: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub command: Option<Vec<String>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub flow: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub step: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub index: Option<u32>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub signal: Option<String>,
}

pub fn emit(repo_root: &Path, node: LfNode, event: LfEventType, fields: LfEventFields) {
    if let Err(err) = try_emit(repo_root, node, event, fields) {
        debug!(
            error = %err,
            repo = %repo_root.display(),
            ?node,
            ?event,
            "journal append failed"
        );
    }
}

pub fn runs_root(worktree: &Path) -> PathBuf {
    worktree.join(JOURNAL_ROOT)
}

pub fn events_path(run_dir: &Path) -> PathBuf {
    run_dir.join("events.jsonl")
}

pub fn read_events(run_dir: &Path) -> Result<Vec<LfEvent>, std::io::Error> {
    let path = events_path(run_dir);
    if !path.exists() {
        return Ok(Vec::new());
    }

    let file = fs::File::open(path)?;
    let mut events = Vec::new();
    for line in BufReader::new(file).lines() {
        let line = line?;
        if line.trim().is_empty() {
            continue;
        }
        let event = serde_json::from_str(&line).map_err(std::io::Error::other)?;
        events.push(event);
    }
    Ok(events)
}

fn try_emit(
    repo_root: &Path,
    node: LfNode,
    event: LfEventType,
    fields: LfEventFields,
) -> Result<(), std::io::Error> {
    let is_run_started = matches!((node, event), (LfNode::Run, LfEventType::Started));
    let maybe_context = if is_run_started {
        ensure_run_context(repo_root, &fields)?
    } else {
        current_context()
    };

    let Some(context) = maybe_context else {
        return Ok(());
    };

    let event = LfEvent {
        run_id: context.run_id.clone(),
        ts: OffsetDateTime::now_utc(),
        node,
        event,
        wave_name: fields.wave_name,
        worktree: fields.worktree,
        command: fields.command,
        flow: fields.flow,
        step: fields.step,
        index: fields.index,
        error: fields.error,
        signal: fields.signal,
    };

    if let Some(run_dir) = &context.run_dir {
        append_event(run_dir, &event)?;
    }

    let seq = next_seq();
    ledger_insert(&context, &event, seq, repo_root);

    if matches!(node, LfNode::Run)
        && matches!(
            event.event,
            LfEventType::Completed | LfEventType::Errored | LfEventType::Escalated
        )
    {
        if context.minted_run_id {
            std::env::remove_var(LF_RUN_ID_ENV);
        }
        clear_context();
        clear_usage();
    }

    Ok(())
}

/// Best-effort write into the machine-grain SQLite ledger. Never fails the
/// run: a locked or missing store degrades to a debug log line. Local-only —
/// the ledger never leaves the machine.
fn ledger_insert(context: &RunContext, event: &LfEvent, seq: i64, repo_root: &Path) {
    let is_terminal_run = matches!(event.node, LfNode::Run)
        && matches!(
            event.event,
            LfEventType::Completed | LfEventType::Errored | LfEventType::Escalated
        );
    let is_step_boundary = matches!(event.node, LfNode::Step)
        && matches!(event.event, LfEventType::Completed | LfEventType::Errored);
    // Terminal run rows carry the run's totals; step boundaries carry a
    // cumulative snapshot so a reader can diff consecutive steps.
    let usage = if is_terminal_run || is_step_boundary {
        snapshot_usage()
    } else {
        None
    };

    let row = RunEventRow {
        run_id: event.run_id.as_str().to_string(),
        seq,
        ts: event.ts.unix_timestamp(),
        repo: context.repo.clone(),
        worktree: Some(repo_root.display().to_string()),
        wave: context.wave.clone(),
        node: node_name(event.node).to_string(),
        event: event_name(event.event).to_string(),
        command: event
            .command
            .as_ref()
            .and_then(|argv| serde_json::to_string(argv).ok()),
        flow: event.flow.clone(),
        step: event.step.clone(),
        step_index: event.index.map(i64::from),
        error: event.error.clone(),
        input_tokens: usage.map(|u| u.input_tokens as i64),
        output_tokens: usage.map(|u| u.output_tokens as i64),
        cache_read_tokens: usage.map(|u| u.cache_read_tokens as i64),
        cost_usd: usage.and_then(|u| u.cost_usd),
        duration_secs: usage.and_then(|u| u.duration_secs),
    };

    match open_ledger() {
        Ok(store) => {
            if let Err(err) = store.insert_run_event(&row) {
                debug!(error = %err, run_id = %row.run_id, "ledger insert failed");
            }
        }
        Err(err) => {
            debug!(error = %err, "ledger unavailable");
        }
    }
}

/// Open the local ledger store, creating and migrating it if needed.
pub fn open_ledger() -> Result<SqliteStore, crate::lfdb::StoreError> {
    SqliteStore::new(&ledger_db_path())
}

#[cfg(not(test))]
fn ledger_db_path() -> PathBuf {
    crate::lfd::default_db_path()
}

/// In lib tests, never touch the real ~/.lf ledger: honor a test's LF_HOME
/// if set, else fall back to one process-wide temp store.
#[cfg(test)]
fn ledger_db_path() -> PathBuf {
    if let Ok(home) = std::env::var("LF_HOME") {
        return PathBuf::from(home).join("lfd.db");
    }
    static TEST_HOME: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
    TEST_HOME
        .get_or_init(|| tempfile::TempDir::new().expect("test ledger home"))
        .path()
        .join("lfd.db")
}

fn node_name(node: LfNode) -> &'static str {
    match node {
        LfNode::Run => "run",
        LfNode::Flow => "flow",
        LfNode::Step => "step",
    }
}

fn event_name(event: LfEventType) -> &'static str {
    match event {
        LfEventType::Started => "started",
        LfEventType::Completed => "completed",
        LfEventType::Errored => "errored",
        LfEventType::Escalated => "escalated",
    }
}

fn ensure_run_context(
    repo_root: &Path,
    fields: &LfEventFields,
) -> Result<Option<RunContext>, std::io::Error> {
    if let Some(context) = current_context() {
        return Ok(Some(context));
    }

    let main_repo = main_repo_root(repo_root).ok();
    let wave_name = main_repo
        .as_ref()
        .and_then(|main| wave_name_from_worktree_and_main(repo_root, main));

    let (run_id, minted_run_id) = match configured_run_id(repo_root) {
        Some(run_id) => (run_id, false),
        None => {
            // Mint and export the run id so prompt logs and child processes
            // carry the same identity as the ledger rows. The export is
            // removed when the run ends (see try_emit).
            let run_id = LfdId::default();
            std::env::set_var(LF_RUN_ID_ENV, run_id.as_str());
            (run_id, true)
        }
    };

    // Write the file journal wherever we can, wave or not — the daemon's
    // poller only tails wave worktrees today, but the record should exist in
    // any repo. Fall back to ledger-only when the journal can't be
    // git-excluded (e.g. not a git repo).
    let run_dir = match ensure_journal_ignored(repo_root) {
        Ok(()) => {
            let dir = runs_root(repo_root).join(run_id.as_str());
            fs::create_dir_all(&dir)?;
            Some(dir)
        }
        Err(err) => {
            debug!(
                error = %err,
                repo = %repo_root.display(),
                "file journal unavailable; recording to ledger only"
            );
            None
        }
    };

    let repo = main_repo
        .as_deref()
        .unwrap_or(repo_root)
        .file_name()
        .and_then(|name| name.to_str())
        .map(str::to_string);

    let context = RunContext {
        run_id,
        run_dir,
        repo,
        wave: wave_name.clone(),
        seq: 0,
        minted_run_id,
    };
    set_context(context.clone());

    if let Some(wave_name) = wave_name {
        if fields.wave_name.as_deref() != Some(wave_name.as_str()) {
            debug!(
                expected_wave = %wave_name,
                observed_wave = ?fields.wave_name,
                repo = %repo_root.display(),
                "journal run start received mismatched wave metadata"
            );
        }
    }

    Ok(Some(context))
}

fn next_seq() -> i64 {
    RUN_CONTEXT.with(|cell| {
        let mut borrow = cell.borrow_mut();
        match borrow.as_mut() {
            Some(context) => {
                let seq = context.seq;
                context.seq += 1;
                seq
            }
            None => 0,
        }
    })
}

fn configured_run_id(repo_root: &Path) -> Option<LfdId> {
    let value = std::env::var(LF_RUN_ID_ENV).ok()?;
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return None;
    }

    match trimmed.parse() {
        Ok(run_id) => Some(run_id),
        Err(err) => {
            debug!(
                env = LF_RUN_ID_ENV,
                value = trimmed,
                repo = %repo_root.display(),
                error = %err,
                "ignoring invalid journal run id override"
            );
            None
        }
    }
}

fn append_event(run_dir: &Path, event: &LfEvent) -> Result<(), std::io::Error> {
    let mut file = OpenOptions::new()
        .create(true)
        .append(true)
        .open(events_path(run_dir))?;
    serde_json::to_writer(&mut file, event).map_err(std::io::Error::other)?;
    file.write_all(b"\n")?;
    Ok(())
}

fn current_context() -> Option<RunContext> {
    RUN_CONTEXT.with(|cell| cell.borrow().clone())
}

fn set_context(context: RunContext) {
    RUN_CONTEXT.with(|cell| {
        *cell.borrow_mut() = Some(context);
    });
}

fn clear_context() {
    RUN_CONTEXT.with(|cell| {
        *cell.borrow_mut() = None;
    });
}

fn ensure_journal_ignored(repo_root: &Path) -> Result<(), std::io::Error> {
    let output = Command::new("git")
        .arg("-C")
        .arg(repo_root)
        .args(["rev-parse", "--git-path", "info/exclude"])
        .output()?;
    if !output.status.success() {
        return Err(std::io::Error::other(format!(
            "git rev-parse --git-path info/exclude failed: {}",
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }

    // `--git-path` answers relative to the repo when run at its root (main
    // repos) and absolute for linked worktrees — absolutize before writing.
    let mut exclude_path = PathBuf::from(String::from_utf8_lossy(&output.stdout).trim());
    if exclude_path.is_relative() {
        exclude_path = repo_root.join(exclude_path);
    }
    if let Some(parent) = exclude_path.parent() {
        fs::create_dir_all(parent)?;
    }

    let existing = fs::read_to_string(&exclude_path).unwrap_or_default();
    if existing
        .lines()
        .any(|line| line.trim() == JOURNAL_EXCLUDE_ENTRY)
    {
        return Ok(());
    }

    let mut updated = existing;
    if !updated.is_empty() && !updated.ends_with('\n') {
        updated.push('\n');
    }
    updated.push_str(JOURNAL_EXCLUDE_ENTRY);
    updated.push('\n');
    fs::write(exclude_path, updated)
}

#[cfg(test)]
mod tests {
    use super::{emit, read_events, runs_root, test_env_lock, LfEventFields, LfEventType, LfNode};
    use crate::engine::git::is_clean;
    use crate::lfd::id::LfdId;
    use loopflow_test_support::TestRepo;

    fn with_run_id_env<T>(value: Option<&str>, run: impl FnOnce() -> T) -> T {
        let _guard = test_env_lock();
        super::clear_context();
        super::clear_usage();
        let home = tempfile::TempDir::new().expect("ledger home");
        std::env::set_var("LF_HOME", home.path());
        let previous = std::env::var(super::LF_RUN_ID_ENV).ok();
        match value {
            Some(value) => std::env::set_var(super::LF_RUN_ID_ENV, value),
            None => std::env::remove_var(super::LF_RUN_ID_ENV),
        }
        let result = run();
        super::clear_context();
        match previous {
            Some(value) => std::env::set_var(super::LF_RUN_ID_ENV, value),
            None => std::env::remove_var(super::LF_RUN_ID_ENV),
        }
        result
    }

    /// Holds the env lock and points the ledger (LF_HOME) at a tempdir so
    /// tests never touch the real ~/.lf store.
    fn journal_test_guard() -> (std::sync::MutexGuard<'static, ()>, tempfile::TempDir) {
        let guard = test_env_lock();
        super::clear_context();
        super::clear_usage();
        std::env::remove_var(super::LF_RUN_ID_ENV);
        let home = tempfile::TempDir::new().expect("ledger home");
        std::env::set_var("LF_HOME", home.path());
        (guard, home)
    }

    fn started_fields(
        command: &[String],
        worktree: &std::path::Path,
        wave_name: &str,
    ) -> LfEventFields {
        LfEventFields {
            wave_name: Some(wave_name.to_string()),
            worktree: Some(worktree.display().to_string()),
            command: Some(command.to_vec()),
            ..LfEventFields::default()
        }
    }

    fn only_run_dir(worktree: &std::path::Path) -> std::path::PathBuf {
        let mut entries = std::fs::read_dir(runs_root(worktree))
            .expect("read runs")
            .map(|entry| entry.expect("run dir entry").path())
            .collect::<Vec<_>>();
        assert_eq!(entries.len(), 1, "expected a single journal run dir");
        entries.pop().expect("run dir")
    }

    #[test]
    fn main_repo_runs_record_to_file_journal_and_ledger() {
        let _guard = journal_test_guard();
        let repo = TestRepo::new();
        let command = vec!["lf".to_string(), "implement".to_string()];

        emit(
            repo.path(),
            LfNode::Run,
            LfEventType::Started,
            started_fields(&command, repo.path(), "main"),
        );
        super::record_usage(Some(100), Some(20), Some(5));
        emit(
            repo.path(),
            LfNode::Run,
            LfEventType::Completed,
            LfEventFields::default(),
        );

        // The file journal exists in the main repo too — generic contexts
        // record as much as possible; only the wave field is absent.
        let run_dir = only_run_dir(repo.path());
        let file_events = read_events(&run_dir).expect("file events");
        assert_eq!(file_events.len(), 2);
        assert!(is_clean(repo.path()).expect("journal stays git-excluded"));

        // And the machine-grain ledger has the run, with usage on the
        // terminal event and a null wave. Filter by this repo's unique name —
        // concurrent tests may write other repos' rows into the ledger.
        let repo_name = repo.path().file_name().unwrap().to_str().unwrap();
        let store = super::open_ledger().expect("ledger");
        let events: Vec<_> = store
            .list_run_events_since(0)
            .expect("ledger rows")
            .into_iter()
            .filter(|event| event.repo.as_deref() == Some(repo_name))
            .collect();
        assert_eq!(events.len(), 2);
        assert_eq!(events[0].node, "run");
        assert_eq!(events[0].event, "started");
        assert!(events[0].repo.is_some());
        assert_eq!(events[0].wave, None);
        assert!(events[0]
            .command
            .as_deref()
            .unwrap_or("")
            .contains("implement"));
        assert_eq!(events[1].event, "completed");
        assert_eq!(events[1].input_tokens, Some(100));
        assert_eq!(events[1].output_tokens, Some(20));
        assert_eq!(events[1].cache_read_tokens, Some(5));
    }

    #[test]
    fn journal_writes_run_flow_and_step_events_in_wave_worktree() {
        let _guard = journal_test_guard();
        let repo = TestRepo::new();
        let worktree = repo.create_wave_worktree("runtime");
        let command = vec!["lf".to_string(), "build".to_string()];

        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Started,
            started_fields(&command, &worktree, "runtime"),
        );
        emit(
            &worktree,
            LfNode::Flow,
            LfEventType::Started,
            LfEventFields {
                flow: Some("build".to_string()),
                ..LfEventFields::default()
            },
        );
        emit(
            &worktree,
            LfNode::Step,
            LfEventType::Started,
            LfEventFields {
                step: Some("implement".to_string()),
                index: Some(0),
                ..LfEventFields::default()
            },
        );
        emit(
            &worktree,
            LfNode::Step,
            LfEventType::Completed,
            LfEventFields {
                step: Some("implement".to_string()),
                index: Some(0),
                ..LfEventFields::default()
            },
        );
        emit(
            &worktree,
            LfNode::Flow,
            LfEventType::Completed,
            LfEventFields::default(),
        );
        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Completed,
            LfEventFields::default(),
        );

        let run_dir = only_run_dir(&worktree);
        let events = read_events(&run_dir).expect("read events");
        assert_eq!(events.len(), 6);
        assert_eq!(events[0].node, LfNode::Run);
        assert_eq!(events[0].event, LfEventType::Started);
        assert_eq!(events[0].wave_name.as_deref(), Some("runtime"));
        assert_eq!(events[1].node, LfNode::Flow);
        assert_eq!(events[1].flow.as_deref(), Some("build"));
        assert_eq!(events[2].node, LfNode::Step);
        assert_eq!(events[2].step.as_deref(), Some("implement"));
        assert_eq!(events[2].index, Some(0));
        assert_eq!(events[3].event, LfEventType::Completed);
        assert_eq!(events[4].node, LfNode::Flow);
        assert_eq!(events[5].node, LfNode::Run);
        assert_eq!(events[5].event, LfEventType::Completed);
    }

    #[test]
    fn journal_keeps_worktree_clean() {
        let _guard = journal_test_guard();
        let repo = TestRepo::new();
        let worktree = repo.create_wave_worktree("runtime");
        let command = vec!["lf".to_string(), "build".to_string()];

        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Started,
            started_fields(&command, &worktree, "runtime"),
        );

        assert!(is_clean(&worktree).expect("worktree should stay clean"));
    }

    #[test]
    fn terminal_run_events_clear_context_for_the_next_run() {
        let _guard = journal_test_guard();
        let repo = TestRepo::new();
        let worktree = repo.create_wave_worktree("runtime");
        let command = vec!["lf".to_string(), "build".to_string()];

        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Started,
            started_fields(&command, &worktree, "runtime"),
        );
        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Completed,
            LfEventFields::default(),
        );
        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Started,
            started_fields(&command, &worktree, "runtime"),
        );
        emit(
            &worktree,
            LfNode::Run,
            LfEventType::Completed,
            LfEventFields::default(),
        );

        let entries = std::fs::read_dir(runs_root(&worktree))
            .expect("read runs")
            .count();
        assert_eq!(entries, 2);
    }

    #[test]
    fn journal_uses_configured_run_id_when_present() {
        with_run_id_env(Some("7c22895f-e4c1-49cc-a95d-2267e2356f16"), || {
            let repo = TestRepo::new();
            let worktree = repo.create_wave_worktree("runtime");
            let command = vec!["lf".to_string(), "build".to_string()];

            emit(
                &worktree,
                LfNode::Run,
                LfEventType::Started,
                started_fields(&command, &worktree, "runtime"),
            );
            emit(
                &worktree,
                LfNode::Run,
                LfEventType::Completed,
                LfEventFields::default(),
            );

            let run_dir = only_run_dir(&worktree);
            let run_id = run_dir
                .file_name()
                .and_then(|name| name.to_str())
                .expect("run dir name");
            assert_eq!(run_id, "7c22895f-e4c1-49cc-a95d-2267e2356f16");
        });
    }

    #[test]
    fn invalid_configured_run_id_falls_back_to_generated_id() {
        with_run_id_env(Some("not-a-uuid"), || {
            let repo = TestRepo::new();
            let worktree = repo.create_wave_worktree("runtime");
            let command = vec!["lf".to_string(), "build".to_string()];

            emit(
                &worktree,
                LfNode::Run,
                LfEventType::Started,
                started_fields(&command, &worktree, "runtime"),
            );
            emit(
                &worktree,
                LfNode::Run,
                LfEventType::Completed,
                LfEventFields::default(),
            );

            let run_dir = only_run_dir(&worktree);
            let run_id = run_dir
                .file_name()
                .and_then(|name| name.to_str())
                .expect("run dir name");
            assert!(
                LfdId::parse(run_id).is_ok(),
                "expected generated UUID run id"
            );
            assert_ne!(run_id, "not-a-uuid");
        });
    }
}