yoagent 0.18.0

Simple, effective agent loop with tool execution and event streaming
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
//! Tests for the GASP bridge (feature `gasp`): event mapping, commit
//! behavior, goal reuse, and interrupted-run recovery.
#![cfg(feature = "gasp")]

use std::process::Command;
use yoagent::gasp::{GaspRecorder, GoalRef};
use yoagent::provider::mock::*;
use yoagent::provider::{MockProvider, ModelConfig};
use yoagent::*;

struct NoopTool;

#[async_trait::async_trait]
impl AgentTool for NoopTool {
    fn name(&self) -> &str {
        "noop"
    }
    fn label(&self) -> &str {
        "Noop"
    }
    fn description(&self) -> &str {
        "does nothing"
    }
    fn parameters_schema(&self) -> serde_json::Value {
        serde_json::json!({"type": "object"})
    }
    async fn execute(
        &self,
        _params: serde_json::Value,
        _ctx: ToolContext,
    ) -> Result<ToolResult, ToolError> {
        Ok(ToolResult {
            content: vec![Content::Text { text: "ok".into() }],
            details: serde_json::Value::Null,
        })
    }
}

/// CI runners have no git identity configured; commit_run shells out to
/// plain `git commit`, so provide one via env (idempotent across tests).
fn ensure_git_identity() {
    for (k, v) in [
        ("GIT_AUTHOR_NAME", "yoagent-test"),
        ("GIT_AUTHOR_EMAIL", "test@yolog.dev"),
        ("GIT_COMMITTER_NAME", "yoagent-test"),
        ("GIT_COMMITTER_EMAIL", "test@yolog.dev"),
    ] {
        std::env::set_var(k, v);
    }
}

fn tool_then_text_provider() -> MockProvider {
    MockProvider::new(vec![
        MockResponse::ToolCalls(vec![MockToolCall {
            provider_metadata: None,
            name: "noop".into(),
            arguments: serde_json::json!({}),
        }]),
        MockResponse::Text("done".into()),
    ])
}

/// Like `event_kinds`, but tolerant of a file that is still being written:
/// missing file, or a torn final line, yield what is readable so far. Used by
/// barriers that poll while the recorder appends.
fn event_kinds_lenient(repo: &std::path::Path) -> Vec<String> {
    std::fs::read_to_string(repo.join("state/events.jsonl"))
        .unwrap_or_default()
        .lines()
        .filter_map(|l| {
            serde_json::from_str::<serde_json::Value>(l)
                .ok()?
                .get("kind")?
                .as_str()
                .map(str::to_owned)
        })
        .collect()
}

fn event_kinds(repo: &std::path::Path) -> Vec<String> {
    std::fs::read_to_string(repo.join("state/events.jsonl"))
        .expect("events.jsonl exists")
        .lines()
        .map(|l| {
            serde_json::from_str::<serde_json::Value>(l).unwrap()["kind"]
                .as_str()
                .unwrap()
                .to_string()
        })
        .collect()
}

#[tokio::test]
async fn records_a_full_run_with_expected_kinds_and_commit() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "test goal".into(),
        },
    )
    .await
    .unwrap();

    let mut agent = Agent::from_provider(tool_then_text_provider(), ModelConfig::mock())
        .with_tools(vec![Box::new(NoopTool)]);
    let (tx, handle) = recorder.recording_sender("do the thing", None);
    agent.prompt_with_sender("do the thing", tx).await;
    let run_id = handle.await.unwrap().unwrap().expect("run recorded");

    let kinds = event_kinds(dir.path());
    // Semantic skeleton, in order (ops_applied lines interleave freely).
    // Allowlist the semantic kinds (bookkeeping kinds like state.ops_applied
    // may grow in yoagent-state minors without breaking this test).
    let semantic: Vec<&str> = kinds
        .iter()
        .map(|s| s.as_str())
        .filter(|k| {
            ["goal.", "run.", "model.", "tool."]
                .iter()
                .any(|p| k.starts_with(p))
        })
        .collect();
    assert_eq!(
        semantic,
        vec![
            "goal.created",
            "run.started",
            "model.called",
            "model.finished",
            "tool.called",
            "tool.finished",
            "model.called",
            "model.finished",
            "run.finished",
        ],
        "full log: {kinds:?}"
    );

    // The run is committed (append-only history is what conformance walks).
    let log = Command::new("git")
        .args(["log", "--oneline"])
        .current_dir(dir.path())
        .output()
        .unwrap();
    let log = String::from_utf8_lossy(&log.stdout);
    assert!(
        log.contains(&format!("run {run_id}")),
        "commit missing: {log}"
    );
    assert!(log.contains("completed"));
}

#[tokio::test]
async fn events_are_teed_to_the_forward_sender() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "tee".into(),
        },
    )
    .await
    .unwrap();

    let (ui_tx, mut ui_rx) = tokio::sync::mpsc::unbounded_channel();
    let mut agent = Agent::from_provider(MockProvider::text("hi"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("t", Some(ui_tx));
    agent.prompt_with_sender("t", tx).await;
    handle.await.unwrap().unwrap();

    let mut forwarded = 0;
    while ui_rx.try_recv().is_ok() {
        forwarded += 1;
    }
    assert!(forwarded > 0, "UI sender must receive the teed events");
}

#[tokio::test]
async fn goal_is_reused_across_runs_and_recorder_reopens() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "persistent goal".into(),
        },
    )
    .await
    .unwrap();
    let goal = recorder.goal().clone();

    // Run 1.
    let mut agent = Agent::from_provider(MockProvider::text("one"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("run one", None);
    agent.prompt_with_sender("one", tx).await;
    handle.await.unwrap().unwrap();
    drop(recorder);

    // Reopen with the SAME goal — no new goal.created may appear.
    let recorder = GaspRecorder::open(
        dir.path().to_path_buf(),
        "test-agent",
        "w1",
        GoalRef::Existing(goal.clone()),
    )
    .await
    .unwrap();
    assert_eq!(recorder.goal(), &goal);

    let mut agent = Agent::from_provider(MockProvider::text("two"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("run two", None);
    agent.prompt_with_sender("two", tx).await;
    handle.await.unwrap().unwrap();

    let kinds = event_kinds(dir.path());
    assert_eq!(
        kinds.iter().filter(|k| *k == "goal.created").count(),
        1,
        "existing goal must be reused"
    );
    assert_eq!(kinds.iter().filter(|k| *k == "run.finished").count(), 2);
}

#[tokio::test]
async fn dropped_sender_without_agent_end_closes_run_as_interrupted() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "crash".into(),
        },
    )
    .await
    .unwrap();

    // Simulate a crashed loop: send AgentStart, then drop the sender.
    let (tx, handle) = recorder.recording_sender("doomed", None);
    tx.send(AgentEvent::AgentStart).unwrap();
    drop(tx);
    handle.await.unwrap().unwrap();

    let kinds = event_kinds(dir.path());
    assert!(kinds.iter().any(|k| k == "run.finished"));
    let last_finish = std::fs::read_to_string(dir.path().join("state/events.jsonl"))
        .unwrap()
        .lines()
        .rfind(|l| l.contains("run.finished"))
        .unwrap()
        .to_string();
    assert!(last_finish.contains("interrupted"), "got: {last_finish}");
}

// ---------------------------------------------------------------------------
// Review batch: restore-from-clone, failure paths, outcomes, validation
// ---------------------------------------------------------------------------

/// The GASP restore operation IS `git clone` — a clone must contain the
/// manifest, identity, and the committed event log.
#[tokio::test]
async fn fresh_clone_restores_manifest_identity_and_log() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "clone me".into(),
        },
    )
    .await
    .unwrap();

    let mut agent = Agent::from_provider(MockProvider::text("hi"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("t", None);
    agent.prompt_with_sender("t", tx).await;
    handle.await.unwrap().unwrap().expect("run recorded");

    let clone_dir = tempfile::tempdir().unwrap();
    let clone_path = clone_dir.path().join("restored");
    let out = Command::new("git")
        .args(["clone", "-q", dir.path().to_str().unwrap()])
        .arg(&clone_path)
        .output()
        .unwrap();
    assert!(out.status.success());

    assert!(
        clone_path.join("AGENT.md").is_file(),
        "manifest must restore"
    );
    assert!(
        clone_path.join("identity").is_dir(),
        "identity must restore"
    );
    let kinds = event_kinds(&clone_path);
    assert!(kinds.iter().any(|k| k == "goal.created"));
    assert!(kinds.iter().any(|k| k == "run.finished"));
}

/// A mid-run recording failure must NOT blind the UI tee: forwarding
/// continues, the error surfaces via the handle, and nothing new commits.
#[tokio::test]
#[cfg(unix)]
async fn sink_failure_keeps_tee_alive_and_surfaces_error() {
    use std::os::unix::fs::PermissionsExt;
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "doomed".into(),
        },
    )
    .await
    .unwrap();

    // Make the log unwritable so the first append fails.
    let events = dir.path().join("state/events.jsonl");
    std::fs::set_permissions(&events, std::fs::Permissions::from_mode(0o444)).unwrap();

    let (ui_tx, mut ui_rx) = tokio::sync::mpsc::unbounded_channel();
    let mut agent = Agent::from_provider(MockProvider::text("hi"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("t", Some(ui_tx));
    agent.prompt_with_sender("t", tx).await;
    let result = handle.await.unwrap();

    // Restore permissions so the tempdir cleans up everywhere.
    std::fs::set_permissions(&events, std::fs::Permissions::from_mode(0o644)).unwrap();

    assert!(
        result.is_err(),
        "recording failure must surface via the handle"
    );
    // The tee survived: events kept flowing, ending with AgentEnd.
    let mut last = None;
    while let Ok(e) = ui_rx.try_recv() {
        last = Some(e);
    }
    assert!(
        matches!(last, Some(AgentEvent::AgentEnd { .. })),
        "tee must deliver events through AgentEnd despite recording failure"
    );
}

/// with_store's crash recovery: an aborted consumer leaves an open run; the
/// next open closes it as interrupted and can record again.
#[tokio::test]
async fn reopen_after_crash_closes_stale_run_and_records_again() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "crashy".into(),
        },
    )
    .await
    .unwrap();
    let goal = recorder.goal().clone();

    // Open a run, then kill the consumer before its drop-fallback can close
    // it — a faithful crash simulation.
    let (tx, handle) = recorder.recording_sender("doomed", None);
    tx.send(AgentEvent::AgentStart).unwrap();

    // Wait for the run to be *fully* open, not just logged. `record_run_started`
    // writes the `run.started` event, opens the run marker, and only then
    // applies the ops that create the run node — a window its own source
    // comments call out. Aborting on `run.started` alone can land inside it,
    // leaving a run whose node was never written; the reopen below then fails
    // with "node not found" instead of exercising the stale-run recovery this
    // test is about. The node-creating ops arrive as the `state.ops_applied`
    // event that follows, so that is the barrier.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        let kinds = event_kinds_lenient(dir.path());
        if let Some(started) = kinds.iter().position(|k| k == "run.started") {
            if kinds[started..].iter().any(|k| k == "state.ops_applied") {
                break;
            }
        }
        assert!(
            std::time::Instant::now() < deadline,
            "run never opened fully; saw events: {:?}",
            event_kinds_lenient(dir.path())
        );
        tokio::time::sleep(std::time::Duration::from_millis(10)).await;
    }

    handle.abort();
    let _ = handle.await;
    drop(tx);
    drop(recorder);

    // Reopen: the stale run must be closed and a new run must succeed.
    let recorder = GaspRecorder::open(
        dir.path().to_path_buf(),
        "test-agent",
        "w1",
        GoalRef::Existing(goal),
    )
    .await
    .expect("reopen after crash");

    let mut agent = Agent::from_provider(MockProvider::text("recovered"), ModelConfig::mock());
    let (tx, handle) = recorder.recording_sender("recovery run", None);
    agent.prompt_with_sender("go", tx).await;
    handle.await.unwrap().unwrap().expect("new run recorded");

    let kinds = event_kinds(dir.path());
    assert_eq!(kinds.iter().filter(|k| *k == "run.started").count(), 2);
    assert_eq!(kinds.iter().filter(|k| *k == "run.finished").count(), 2);
}

/// No AgentStart → Ok(None): callers never get an id that isn't in the log.
#[tokio::test]
async fn no_agent_start_returns_none_and_writes_nothing() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "nothing".into(),
        },
    )
    .await
    .unwrap();

    let (tx, handle) = recorder.recording_sender("never runs", None);
    drop(tx);
    let outcome = handle.await.unwrap().unwrap();
    assert!(outcome.is_none(), "no run happened — no RunId");

    let kinds = event_kinds(dir.path());
    assert!(!kinds.iter().any(|k| k.starts_with("run.")));
}

/// outcome_for mapping, pinned through the durable log via synthetic events.
#[tokio::test]
async fn stop_reasons_map_to_distinct_outcomes() {
    ensure_git_identity();
    for (stop, expected) in [
        (StopReason::Length, "truncated"),
        (StopReason::Error, "error"),
        (StopReason::Aborted, "aborted"),
        (StopReason::Refusal, "refused"),
    ] {
        let dir = tempfile::tempdir().unwrap();
        let recorder = GaspRecorder::init(
            dir.path(),
            "test-agent",
            "w1",
            GoalRef::New {
                title: "outcomes".into(),
            },
        )
        .await
        .unwrap();
        let (tx, handle) = recorder.recording_sender("t", None);
        tx.send(AgentEvent::AgentStart).unwrap();
        tx.send(AgentEvent::MessageEnd {
            message: AgentMessage::Llm(Message::assistant(
                vec![Content::Text { text: "x".into() }],
                stop.clone(),
                "m",
                "mock",
                Usage::default(),
            )),
        })
        .unwrap();
        tx.send(AgentEvent::agent_end(vec![], Default::default()))
            .unwrap();
        drop(tx);
        handle.await.unwrap().unwrap().expect("recorded");

        let log = std::fs::read_to_string(dir.path().join("state/events.jsonl")).unwrap();
        let finish = log
            .lines()
            .rfind(|l| l.contains("run.finished"))
            .unwrap()
            .to_string();
        assert!(
            finish.contains(expected),
            "stop {stop:?} must record outcome {expected}; got {finish}"
        );
    }
}

/// An input-filter rejection is a policy outcome, not a crash.
#[tokio::test]
async fn input_rejected_runs_record_outcome_rejected() {
    ensure_git_identity();
    struct RejectAll;
    impl InputFilter for RejectAll {
        fn filter(&self, _text: &str) -> FilterResult {
            FilterResult::Reject("policy".into())
        }
    }

    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "reject".into(),
        },
    )
    .await
    .unwrap();

    let mut agent = Agent::from_provider(MockProvider::text("unused"), ModelConfig::mock())
        .with_input_filter(RejectAll);
    let (tx, handle) = recorder.recording_sender("t", None);
    agent.prompt_with_sender("anything", tx).await;
    handle.await.unwrap().unwrap().expect("recorded");

    let log = std::fs::read_to_string(dir.path().join("state/events.jsonl")).unwrap();
    let finish = log.lines().rfind(|l| l.contains("run.finished")).unwrap();
    assert!(finish.contains("rejected"), "got: {finish}");
}

/// A dangling GoalRef::Existing must fail loudly at open.
#[tokio::test]
async fn dangling_existing_goal_errors_at_open() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    // Create a valid repo first.
    let r = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "real".into(),
        },
    )
    .await
    .unwrap();
    drop(r);

    let bogus = yoagent::gasp::GoalId::generate();
    let err = GaspRecorder::open(
        dir.path().to_path_buf(),
        "test-agent",
        "w1",
        GoalRef::Existing(bogus),
    )
    .await;
    assert!(err.is_err(), "dangling goal id must be rejected");
}

/// The tee must deliver the complete stream: identical event kinds to a
/// direct (untee'd) run of the same deterministic agent.
#[tokio::test]
async fn tee_delivers_the_complete_event_stream() {
    ensure_git_identity();
    fn kind_of(e: &AgentEvent) -> &'static str {
        match e {
            AgentEvent::AgentStart => "AgentStart",
            AgentEvent::AgentEnd { .. } => "AgentEnd",
            AgentEvent::TurnStart => "TurnStart",
            AgentEvent::TurnEnd { .. } => "TurnEnd",
            AgentEvent::MessageStart { .. } => "MessageStart",
            AgentEvent::MessageUpdate { .. } => "MessageUpdate",
            AgentEvent::MessageEnd { .. } => "MessageEnd",
            AgentEvent::ToolExecutionStart { .. } => "ToolExecutionStart",
            AgentEvent::ToolExecutionUpdate { .. } => "ToolExecutionUpdate",
            AgentEvent::ToolExecutionEnd { .. } => "ToolExecutionEnd",
            AgentEvent::ProgressMessage { .. } => "ProgressMessage",
            AgentEvent::InputRejected { .. } => "InputRejected",
            _ => "Unknown",
        }
    }

    // Direct run.
    let mut agent = Agent::from_provider(MockProvider::text("same"), ModelConfig::mock());
    let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
    agent.prompt_with_sender("t", tx).await;
    let mut direct = Vec::new();
    while let Ok(e) = rx.try_recv() {
        direct.push(kind_of(&e));
    }

    // Teed run of the identical agent config.
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "tee-eq".into(),
        },
    )
    .await
    .unwrap();
    let mut agent = Agent::from_provider(MockProvider::text("same"), ModelConfig::mock());
    let (ui_tx, mut ui_rx) = tokio::sync::mpsc::unbounded_channel();
    let (tx, handle) = recorder.recording_sender("t", Some(ui_tx));
    agent.prompt_with_sender("t", tx).await;
    handle.await.unwrap().unwrap().expect("recorded");
    let mut teed = Vec::new();
    while let Ok(e) = ui_rx.try_recv() {
        teed.push(kind_of(&e));
    }

    assert_eq!(direct, teed, "tee must deliver every event, in order");
}

#[tokio::test]
async fn tool_fingerprint_and_usage_reach_the_log() {
    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "measurement goal".into(),
        },
    )
    .await
    .unwrap();

    let mut agent = Agent::from_provider(tool_then_text_provider(), ModelConfig::mock())
        .with_tools(vec![Box::new(NoopTool)]);
    let (tx, handle) = recorder.recording_sender("measured run", None);
    agent.prompt_with_sender("measured run", tx).await;
    handle.await.unwrap().unwrap().expect("run recorded");

    let raw = std::fs::read_to_string(dir.path().join("state/events.jsonl")).unwrap();
    let events: Vec<serde_json::Value> = raw
        .lines()
        .map(|l| serde_json::from_str(l).unwrap())
        .collect();

    // tool.called must carry a stable fingerprint so calls can be matched
    // across the log — input_summary is truncated and cannot be.
    let tool_called = events
        .iter()
        .find(|e| e["kind"] == "tool.called")
        .expect("tool.called recorded");
    let fp = tool_called["payload"]["metadata"]["args_fingerprint"]
        .as_str()
        .expect("args_fingerprint present");
    assert!(fp.starts_with("noop:"), "got {fp}");

    // model.finished must carry usage — this is what makes the log
    // sufficient for cost analysis and compaction inference.
    let model_finished = events
        .iter()
        .find(|e| e["kind"] == "model.finished")
        .expect("model.finished recorded");
    let usage = &model_finished["payload"]["metadata"]["usage"];
    assert!(usage["input"].is_number(), "usage.input missing: {usage}");
    assert!(usage["output"].is_number());
    assert!(usage["cache_read"].is_number());
    assert!(usage["cache_write"].is_number());
}

// ---------------------------------------------------------------------------
// The documented extension path must actually be reachable (#111): recording
// the goal/task/verdict tier alongside the recorder's run/tool tier, using
// only `yoagent::gasp` — no direct `yoagent-state` dependency.
// ---------------------------------------------------------------------------

#[tokio::test]
async fn extension_path_records_the_task_tier_without_a_direct_state_dependency() {
    use yoagent::gasp::{ActorRef, NodeId, Task, TaskId, TaskStatus, YoAgentState};

    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "extension goal".into(),
        },
    )
    .await
    .unwrap();

    // Every type the extension path needs must be nameable from `yoagent::gasp`.
    let state: &YoAgentState<yoagent::gasp::GitEventStore> = recorder.state();
    let actor: &ActorRef = recorder.actor();
    let goal = recorder.goal().clone();

    state
        .record_task(Task {
            id: TaskId::new("task_1"),
            title: "ship the thing".into(),
            summary: "planned this session".into(),
            status: TaskStatus::Open,
            goal: Some(goal.clone()),
            created_by: actor.clone(),
            metadata: serde_json::json!({"kind": "feature"}),
        })
        .await
        .expect("record_task via the recorder's own state");

    // And the graph is queryable — how a caller checks whether a node exists.
    let graph = state.graph().await;
    let node = graph
        .nodes
        .get(&NodeId::new("task_1"))
        .expect("task folded into the graph");
    assert_eq!(node.props["title"], "ship the thing");

    // The task tier lands in the same log as the run tier, one writer.
    let kinds = event_kinds_lenient(dir.path());
    assert!(kinds.iter().any(|k| k == "task.created"), "got {kinds:?}");
    assert!(kinds.iter().any(|k| k == "goal.created"), "got {kinds:?}");
}

#[tokio::test]
async fn recorder_store_accessor_shares_the_lease_rather_than_colliding() {
    use yoagent::gasp::EventStore;

    ensure_git_identity();
    let dir = tempfile::tempdir().unwrap();
    let recorder = GaspRecorder::init(
        dir.path(),
        "test-agent",
        "w1",
        GoalRef::New {
            title: "lease goal".into(),
        },
    )
    .await
    .unwrap();

    // Reading through the recorder's own store works while it holds the lease.
    // Opening a second GitEventStore on this root is what would collide.
    let events = recorder.store().scan().await.expect("scan via accessor");
    assert!(
        events.iter().any(|e| e.kind == "goal.created"),
        "expected the goal event through the shared store"
    );
}

/// Every struct re-exported from `yoagent::gasp` must be *constructible* using
/// only `yoagent::gasp` — no direct `yoagent-state` dependency.
///
/// This is the invariant behind #111 and #115: a struct whose id or field
/// types are missing is nameable but unbuildable, and the re-export list looks
/// complete either way. The 0.16.3 notes demonstrated the extension path with
/// `Task` — the one struct whose id type happened to be exported — so it
/// compiled while three siblings did not. Constructing all of them is what
/// makes the gap impossible to reintroduce silently.
///
/// This test exists to *compile*. The assertions are incidental.
#[test]
fn every_reexported_struct_is_constructible_from_gasp_alone() {
    use yoagent::gasp::{
        ActorRef, ArtifactRef, Decision, DecisionId, DecisionStatus, EvalId, EvalResult,
        EvalStatus, GaspGoal, GoalId, GoalStatus, Hypothesis, HypothesisId, NodeId, Observation,
        ObservationId, PatchId, RunId, StatePatch, Task, TaskId, TaskStatus,
    };

    let actor = ActorRef::agent("yoyo");

    let _goal = GaspGoal {
        id: GoalId::new("goal_1"),
        title: "t".into(),
        summary: "s".into(),
        status: GoalStatus::Open,
        owner: actor.clone(),
        metadata: serde_json::json!({}),
    };

    let _task = Task {
        id: TaskId::new("task_1"),
        title: "t".into(),
        summary: "s".into(),
        status: TaskStatus::Open,
        goal: Some(GoalId::new("goal_1")),
        created_by: actor.clone(),
        metadata: serde_json::json!({}),
    };

    // The three named in #115 — each blocked on its id type alone.
    let _eval = EvalResult {
        id: EvalId::new("eval_1"),
        command: "cargo test".into(),
        status: EvalStatus::Passed,
        score: Some(1.0),
        metadata: serde_json::json!({}),
    };

    let _decision = Decision {
        id: DecisionId::new("decision_1"),
        status: DecisionStatus::Approved,
        reason: "green".into(),
        decided_by: actor.clone(),
        metadata: serde_json::json!({}),
    };

    let patch = StatePatch::new(PatchId::new("patch_1"), "title", "summary", actor.clone());
    assert_eq!(patch.id, PatchId::new("patch_1"));

    // Found by audit rather than by the report — same class, same fix.
    let _observation = Observation {
        id: ObservationId::new("obs_1"),
        title: "t".into(),
        summary: "s".into(),
        observed_in: Some(RunId::new("run_1")),
        metadata: serde_json::json!({}),
    };

    let _hypothesis = Hypothesis {
        id: HypothesisId::new("hyp_1"),
        title: "t".into(),
        summary: "s".into(),
        confidence: Some(0.5),
        metadata: serde_json::json!({}),
    };

    // Field types a caller needs to populate a patch, not just open one.
    let _evidence: Vec<NodeId> = vec![NodeId::new("node_1")];
    let _artifacts: Vec<ArtifactRef> = Vec::new();
}

/// Stronger than the test above, and the reason #117 slipped past it:
/// **constructibility is weaker than usability.** `StatePatch::new` defaults
/// `status: PatchStatus::Proposed` internally, so a `StatePatch` can be built
/// without the caller ever naming `PatchStatus` — construction passed while
/// the type stayed unreachable, and advancing a patch was impossible.
///
/// Binding each field to an explicitly named type closes that: a field whose
/// type is not re-exported fails to compile here. Same for the argument types
/// of the `YoAgentState` methods the extension path calls — re-exporting the
/// receiver makes them callable in principle, so their arguments must be
/// nameable too.
///
/// This test exists to *compile*.
#[test]
fn every_field_and_argument_type_is_nameable_from_gasp_alone() {
    use yoagent::gasp::{
        ActorRef, ArtifactRef, DecisionStatus, EvalStatus, Event, EventId, ExpectedEffect, Frame,
        FrameId, GoalId, GoalStatus, ModelCall, NodeId, PatchId, PatchStatus, Precondition,
        ProjectRef, ProjectSnapshot, RunId, StateOp, StatePatch, TaskStatus,
    };

    let patch = StatePatch::new(PatchId::new("p1"), "t", "s", ActorRef::agent("yoyo"));

    // Every field bound to a named type. `status` is the one #117 was about.
    let _: PatchId = patch.id.clone();
    let _: PatchStatus = patch.status.clone();
    let _: u64 = patch.base_state_version;
    let _: Option<ProjectRef> = patch.base_project_ref.clone();
    let _: Vec<StateOp> = patch.ops.clone();
    let _: Vec<Precondition> = patch.preconditions.clone();
    let _: Vec<ExpectedEffect> = patch.expected_effects.clone();
    let _: Vec<NodeId> = patch.evidence.clone();
    let _: Vec<ArtifactRef> = patch.artifacts.clone();

    // The status enums a caller compares or assigns.
    let _: [PatchStatus; 1] = [PatchStatus::Proposed];
    let _: [TaskStatus; 1] = [TaskStatus::Open];
    let _: [GoalStatus; 1] = [GoalStatus::Open];
    let _: [EvalStatus; 1] = [EvalStatus::Passed];
    let _: [DecisionStatus; 1] = [DecisionStatus::Pending];

    // Argument types of the remaining YoAgentState methods, so "the receiver
    // is re-exported" actually means its methods can be called.
    fn _takes<T>(_: Option<T>) {}
    _takes::<Event>(None);
    _takes::<EventId>(None);
    _takes::<Frame>(None);
    _takes::<FrameId>(None);
    _takes::<ModelCall>(None);
    _takes::<ProjectSnapshot>(None);
    _takes::<GoalId>(None);
    _takes::<RunId>(None);
}