ostraka 1.0.0

Run agent fleets you can actually review.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! Whole journeys through the browser: keys in, screen out.
//!
//! The other tests in this module are about one thing each — a list that
//! scrolls, a status line that totals correctly. These are about getting
//! somewhere: opening a directory that is not a project yet and leaving it set
//! up, typing a task and watching it through to a verdict, changing your mind
//! halfway and having the browser stop rather than walk away.
//!
//! They drive the real key handler and the real drawing, and the run flows
//! drive the real orchestrator — the "vendors" are shell scripts, which is the
//! point, and the same point `milestone_one` makes one crate down: the runtime
//! knows nothing about any particular CLI, so a script is as valid an adapter
//! as a commercial tool. Nothing is stubbed but the agent, and only because
//! spending a vendor to find out whether a key works would be absurd.
//!
//! What they cannot cover is the terminal itself. A pty is not something `std`
//! can open and `script(1)` takes different arguments on every platform this
//! releases for, so the boundary these stop at is `handle` and `draw`. The one
//! thing on the far side of it — that a browser with no terminal says so
//! rather than panicking somewhere inside a dependency — is asserted directly.

use super::view::{App, Dialog, Focus, Screen};
use super::{handle, take_stock};
use crate::workspace::Workspace;
use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::time::{Duration, Instant};

/// The interrupt flag is one global for the process, so the flows that read or
/// write it take this first. Without it, stopping one run stops the next.
static SIGNALS: std::sync::Mutex<()> = std::sync::Mutex::new(());

fn exclusive() -> std::sync::MutexGuard<'static, ()> {
    let guard = SIGNALS.lock().unwrap_or_else(|e| e.into_inner());
    ostraka_adapter::interrupt::clear();
    guard
}

/// A temporary directory that cleans up after itself.
struct Scratch(PathBuf);

impl Drop for Scratch {
    fn drop(&mut self) {
        std::fs::remove_dir_all(&self.0).ok();
    }
}

impl Scratch {
    fn new(name: &str) -> Self {
        let path = std::env::temp_dir().join(format!("ostraka-flow-{}-{name}", std::process::id()));
        std::fs::remove_dir_all(&path).ok();
        std::fs::create_dir_all(&path).expect("scratch dir");
        Self(path)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

fn git(repo: &Path, args: &[&str]) {
    let out = Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()
        .expect("git runs");
    assert!(
        out.status.success(),
        "git {args:?}: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

/// A workspace the browser can actually run something in.
///
/// ```text
/// <workspace>/.ostraka/{ostraka.toml, adapters/}
/// <workspace>/repositories/work   a git repository with one commit
/// <workspace>/notes/
/// ```
///
/// `pause` is what the author sleeps for before it writes: zero for the flows
/// that want a verdict, and long enough to press a key for the flows that want
/// to interrupt one.
fn project(name: &str, pause: u32) -> Scratch {
    let scratch = Scratch::new(name);
    let dir = scratch.path();
    std::fs::create_dir_all(dir.join(".ostraka/adapters")).expect("ostraka");
    std::fs::create_dir_all(dir.join("notes")).expect("notes");
    let repo = dir.join("repositories/work");
    std::fs::create_dir_all(&repo).expect("repository");

    // One script, two profiles. It answers a review by reading the marker out
    // of the prompt it was handed — which is the mechanism, not a shortcut —
    // and otherwise writes a file.
    let body = format!(
        "#!/bin/sh\n\
         case \"$1\" in --probe) echo ok; exit 0;; esac\n\
         marker=$(printf '%s' \"$1\" | grep -o 'VERDICT-[0-9a-f]*:' | head -1)\n\
         if [ -n \"$marker\" ]; then\n\
         \x20 echo \"the change does what the task asked\"\n\
         \x20 echo \"$marker APPROVE\"\n\
         else\n\
         \x20 echo 'reading the repository'\n\
         \x20 sleep {pause}\n\
         \x20 printf 'written by the agent\\n' >> wrote.txt\n\
         \x20 echo 'done'\n\
         fi\n"
    );
    for id in ["writer", "reader"] {
        let script = dir.join(format!("{id}.sh"));
        std::fs::write(&script, &body).expect("script");
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755))
                .expect("chmod");
        }
        std::fs::write(
            dir.join(format!(".ostraka/adapters/{id}.toml")),
            format!(
                "id = \"{id}\"\ncommand = \"{}\"\nargs = [\"{{{{prompt}}}}\"]\nprobe_args = [\"--probe\"]\n",
                script.display()
            ),
        )
        .expect("profile");
    }

    std::fs::write(
        dir.join(".ostraka/ostraka.toml"),
        "[gate]\n\
         checks = [{ name = \"check\", cmd = \"true\", required = true }]\n\n\
         [gate.review]\n\
         must_differ_from_author = true\n",
    )
    .expect("config");
    std::fs::write(repo.join(".gitignore"), "/.ostraka/\n").expect("gitignore");
    std::fs::write(repo.join("seed.txt"), "seed\n").expect("seed");

    git(&repo, &["init", "-q", "-b", "main"]);
    git(&repo, &["config", "user.email", "flow@example.invalid"]);
    git(&repo, &["config", "user.name", "flow"]);
    git(&repo, &["add", "-A"]);
    git(&repo, &["commit", "-q", "-m", "seed"]);
    scratch
}

/// The one repository a fixture workspace holds.
fn repo_of(scratch: &Scratch) -> PathBuf {
    scratch.path().join("repositories/work")
}

/// The browser, driven the way an operator drives it.
struct Driver {
    app: App,
    records_root: PathBuf,
    width: u16,
    height: u16,
}

impl Driver {
    /// Opens where `ostraka tui` opens, through the same function.
    fn open(root: &Path) -> Self {
        let workspace = Workspace::at(root);
        let records_root = workspace.records();
        let app = super::open(&workspace, &records_root).expect("the browser opens");
        Self {
            app,
            records_root,
            width: 110,
            height: 26,
        }
    }

    fn key(&mut self, code: KeyCode) -> &mut Self {
        handle(
            &mut self.app,
            KeyEvent::new(code, KeyModifiers::NONE),
            &self.records_root,
        );
        self
    }

    fn ctrl(&mut self, c: char) -> &mut Self {
        handle(
            &mut self.app,
            KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL),
            &self.records_root,
        );
        self
    }

    fn typed(&mut self, text: &str) -> &mut Self {
        for c in text.chars() {
            self.key(KeyCode::Char(c));
        }
        self
    }

    /// One turn of the event loop, minus the keyboard.
    fn tick(&mut self) -> &mut Self {
        self.app.tick = self.app.tick.wrapping_add(1);
        take_stock(&mut self.app, &self.records_root);
        self
    }

    /// Turns the loop until something is true, or gives up saying what it was
    /// still looking at.
    fn until(&mut self, what: &str, done: impl Fn(&App) -> bool) -> &mut Self {
        let deadline = Instant::now() + Duration::from_secs(60);
        while !done(&self.app) {
            assert!(
                Instant::now() < deadline,
                "waited a minute for {what}, and the screen said:\n{}",
                self.screen()
            );
            self.tick();
            std::thread::sleep(Duration::from_millis(10));
        }
        self
    }

    /// Types a task, runs it, and waits for it to be over.
    fn task(&mut self, text: &str) -> &mut Self {
        let done = self.app.thread().turns.len() + 1;
        self.typed(text).key(KeyCode::Enter);
        self.until("the run to finish", move |app| {
            app.thread().turns.len() == done
        })
    }

    /// The last turn in the thread.
    fn last(&self) -> &super::thread::Turn {
        self.app.thread().turns.last().expect("a finished turn")
    }

    fn screen(&mut self) -> String {
        let mut terminal =
            Terminal::new(TestBackend::new(self.width, self.height)).expect("test terminal");
        let app = &mut self.app;
        terminal
            .draw(|frame| super::view::draw(frame, app))
            .expect("draws");
        let buffer = terminal.backend().buffer().clone();
        (0..buffer.area.height)
            .map(|y| {
                (0..buffer.area.width)
                    .map(|x| buffer[(x, y)].symbol().to_string())
                    .collect::<String>()
            })
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn shows(&mut self, text: &str) {
        let screen = self.screen();
        assert!(screen.contains(text), "expected {text:?} on:\n{screen}");
    }

    fn hides(&mut self, text: &str) {
        let screen = self.screen();
        assert!(
            !screen.contains(text),
            "did not expect {text:?} on:\n{screen}"
        );
    }
}

#[test]
fn a_browser_with_no_terminal_says_so_rather_than_panicking() {
    // Piped into `head`, the terminal library's own failure is a panic and a
    // backtrace naming a file inside a dependency, which tells the operator
    // nothing they can act on. A test's stdout is not a terminal, so this is
    // the real path.
    let scratch = Scratch::new("no-tty");
    let error = super::run(&Workspace::at(scratch.path())).expect_err("a pipe is not a terminal");
    let said = error.to_string();
    assert!(said.contains("needs a terminal"), "{said}");
    assert!(
        said.contains("ostraka runs"),
        "no way out was offered: {said}"
    );
}

#[test]
fn setting_up_a_directory_leaves_a_browser_that_can_run_something() {
    // The first five minutes: open somewhere that is not a project, read what
    // would be written, take the offer, and end up somewhere a task works.
    let scratch = Scratch::new("setup");
    std::fs::create_dir_all(scratch.path().join("repositories/work")).expect("repository");
    std::fs::write(
        scratch.path().join("repositories/work/Cargo.toml"),
        "[package]\n",
    )
    .expect("write");
    let mut d = Driver::open(scratch.path());

    d.shows("not an Ostraka project yet");
    d.shows("a Rust project");
    d.shows("i set this directory up");

    // Not offered here, and saying why beats a key that quietly does nothing.
    d.typed("a task this directory cannot take")
        .key(KeyCode::Enter);
    d.shows("cannot run anything yet");
    assert!(d.app.thread().live.is_none());

    d.ctrl('x').key(KeyCode::Char('i'));
    d.hides("not an Ostraka project yet");
    d.shows("Write a task below");
    assert!(
        scratch
            .path()
            .join(".ostraka/adapters/codex.toml")
            .is_file()
    );
}

#[test]
fn onboarding_an_empty_workspace_says_what_is_missing_before_it_is_missed() {
    // A workspace is set up before anything is cloned into it, so the first
    // thing wrong is that there is nothing to work on — and the second, once
    // there is, is whether git knows about it. Both used to be found out from
    // inside a run, in somebody else's words, after a vendor had been paid.
    let scratch = Scratch::new("no-git");
    let mut d = Driver::open(scratch.path());

    d.shows("not an Ostraka project yet");
    // An empty workspace's problem is not git yet — it is that there is
    // nothing to work on, and that is the sentence it gets.
    d.shows("Nothing has been cloned into");
    d.shows("x walks through it");
    // And no recognisable toolchain either, so the gate it would write is a
    // placeholder. Better said before the offer is taken.
    d.shows("fails on purpose");

    // Taking the offer does not make the warning untrue, so it stays.
    d.ctrl('x').key(KeyCode::Char('i'));
    assert!(scratch.path().join(".ostraka/ostraka.toml").is_file());
    assert!(
        d.app.blocked.is_some(),
        "the warning went away without the cause"
    );
}

#[test]
fn a_task_in_a_repository_git_does_not_know_offers_the_steps_out_of_it() {
    // What this replaces: the run started, spent a vendor, and came back with
    // "did not finish — git worktree add failed: fatal: not a git repository",
    // which is true, is git's account from two layers down, and leaves the
    // operator to work out both that the answer is `git init` and that `git
    // init` alone is not enough either.
    let scratch = Scratch::new("guided");
    // A workspace with something cloned in that git has never heard of, which
    // is what an operator who copied a directory rather than cloning one has.
    std::fs::create_dir_all(scratch.path().join("repositories/work")).expect("repository");
    let mut d = Driver::open(scratch.path());
    d.ctrl('x').key(KeyCode::Char('i'));

    d.typed("write a file").key(KeyCode::Enter);
    assert!(
        d.app.thread().live.is_none(),
        "a run was started with nowhere to work"
    );
    assert_eq!(d.app.dialog, Some(Dialog::Fix));
    assert_eq!(
        d.app.pane().prompt,
        "write a file",
        "the task was thrown away"
    );
    d.shows("not a git repository");
    d.shows("git init");

    // Step by step, and only when asked.
    d.key(KeyCode::Char('y'));
    assert!(
        scratch.path().join("repositories/work/.git").is_dir(),
        "step one did nothing"
    );
    d.shows("commits everything");

    // The commit needs an author, and a machine running these may have none
    // configured; that is the repository's business rather than this test's.
    for (key, value) in [
        ("user.email", "flow@example.invalid"),
        ("user.name", "flow"),
    ] {
        assert!(
            Command::new("git")
                .args(["config", key, value])
                .current_dir(scratch.path().join("repositories/work"))
                .status()
                .expect("git runs")
                .success()
        );
    }

    d.key(KeyCode::Char('y'));
    assert!(
        d.app.remedy.as_ref().is_some_and(|r| r.done()),
        "the steps did not finish"
    );
    d.key(KeyCode::Esc);

    d.ctrl('x').key(KeyCode::Char('x'));
    d.shows("nothing is in the way");
    assert!(d.app.blocked.is_none());
}

#[test]
fn a_workspace_with_nothing_in_it_can_start_a_repository_and_work_in_it() {
    // The whole first five minutes when there is nothing to clone: set the
    // place up, start something, and be walked through the one thing `git
    // init` does not do — the commit a worktree branches from.
    let scratch = Scratch::new("start-here");
    let mut d = Driver::open(scratch.path());
    d.ctrl('x').key(KeyCode::Char('i'));
    d.shows("Nothing has been cloned into");

    d.ctrl('x').key(KeyCode::Char('w'));
    assert_eq!(d.app.dialog, Some(Dialog::Repos));
    d.shows("start one here");

    d.key(KeyCode::Char('n')).typed("fresh").key(KeyCode::Enter);
    assert!(scratch.path().join("repositories/fresh/.git").is_dir());
    assert_eq!(
        d.app.repository().map(|r| r.name.clone()),
        Some("fresh".into())
    );

    // Started, not finished: a worktree needs a commit to branch from, and the
    // guided fix is what asks before making one.
    assert!(
        d.app.blocked.is_some(),
        "a repository with no commits read as ready"
    );
    d.ctrl('x').key(KeyCode::Char('x'));
    d.shows("no commits");
    d.shows("Commit what is here");
}

#[test]
fn a_task_typed_into_the_box_runs_and_is_recorded() {
    let _guard = exclusive();
    let scratch = project("run", 0);
    let mut d = Driver::open(scratch.path());
    d.shows("Write a task below");
    // Nothing to summarise yet, which is the honest version of that sentence.
    d.hides("Last asked here");

    d.task("write a file");

    let screen = d.screen();
    // What was asked, every phase it went through, the agent's own words, the
    // check that ran, the verdict, and how it ended.
    for expected in [
        "write a file",
        "isolate",
        "prepare",
        "author",
        "reading the repository",
        "gate",
        "check",
        "review",
        "APPROVE",
        "approved",
    ] {
        assert!(screen.contains(expected), "no {expected:?} on:\n{screen}");
    }

    let run_id = d
        .last()
        .finished
        .as_ref()
        .map(|f| f.run_id.clone())
        .expect("a finished run");
    assert!(
        scratch
            .path()
            .join(".ostraka/runs")
            .join(&run_id)
            .join("record.json")
            .is_file()
    );
    assert_eq!(d.app.runs.len(), 1);
}

#[test]
fn the_second_task_starts_where_the_first_one_finished() {
    // The whole reason a thread exists. Off `HEAD`, the second task cannot see
    // what the first one wrote, and "now add a test for that" is impossible.
    let _guard = exclusive();
    let scratch = project("thread", 0);
    let mut d = Driver::open(scratch.path());

    assert_eq!(d.app.thread().base_ref, "HEAD");
    d.task("write a file");
    let first = d
        .last()
        .finished
        .as_ref()
        .map(|f| f.run_id.clone())
        .expect("a finished run");
    assert!(d.last().approved(), "the first run was not approved");
    assert_eq!(d.app.thread().base_ref, format!("ostraka/{first}"));
    // And it says so, where you are rather than buried in a menu.
    d.shows("on ");

    d.task("write it again");
    assert_eq!(d.app.thread().turns.len(), 2);

    // The proof is in git: the second run's branch has the first run's commit
    // behind it, which is what "starting where the last one finished" means.
    let second = d
        .last()
        .finished
        .as_ref()
        .map(|f| f.run_id.clone())
        .expect("a second run");
    let out = Command::new("git")
        .args(["log", "--format=%H", &format!("ostraka/{second}")])
        .current_dir(repo_of(&scratch))
        .output()
        .expect("git log");
    let commits = String::from_utf8_lossy(&out.stdout).lines().count();
    assert_eq!(commits, 3, "the chain did not build on the first run");
}

#[test]
fn a_refused_run_is_not_the_ground_the_next_one_stands_on() {
    // Building on a change the gate would not take is a way of taking it.
    let _guard = exclusive();
    let scratch = project("refused", 0);
    // A gate nothing can pass.
    std::fs::write(
        scratch.path().join(".ostraka/ostraka.toml"),
        "[gate]\nchecks = [{ name = \"check\", cmd = \"false\", required = true }]\n\n\
         [gate.review]\nmust_differ_from_author = true\n",
    )
    .expect("config");
    let mut d = Driver::open(scratch.path());

    d.task("write a file");
    assert!(!d.last().approved());
    assert_eq!(
        d.app.thread().base_ref,
        "HEAD",
        "the chain advanced through a refusal"
    );
    d.shows("FAIL");
}

#[test]
fn the_command_line_continues_a_run_the_way_the_browser_does() {
    // Two paths, one pipeline — the claim `run::execute` makes in its own doc
    // comment. The browser threads by advancing `base_ref` on approval; `--from`
    // is that rule with a run id in front of it, so the piece of work that took
    // a browser can be done by a script or by CI.
    //
    // Before it, continuing meant passing `--base-ref ostraka/<id>`: a naming
    // convention that appears nowhere but the source.
    let _guard = exclusive();
    let scratch = project("cli-thread", 0);
    let workspace = Workspace::at(scratch.path());

    let first = crate::run::execute(
        &workspace,
        &crate::run::Args::for_task("write a file".into()),
        None,
    )
    .expect("the first run completes");
    assert!(first.approved(), "the first run was not approved");

    let mut args = crate::run::Args::for_task("write it again".into());
    args.from = Some(first.record.run_id.clone());
    let second = crate::run::execute(&workspace, &args, None).expect("the second run completes");
    assert!(second.approved(), "the second run was not approved");

    // The proof is in git, the same proof the browser's thread test takes: the
    // second run's branch has the first run's commit behind it.
    let out = Command::new("git")
        .args([
            "log",
            "--format=%H",
            &format!("ostraka/{}", second.record.run_id),
        ])
        .current_dir(repo_of(&scratch))
        .output()
        .expect("git log");
    let commits = String::from_utf8_lossy(&out.stdout).lines().count();
    assert_eq!(commits, 3, "the chain did not build on the first run");
}

#[test]
fn the_command_line_will_not_continue_a_refused_run() {
    // The browser's rule, held to on the other path. Building on a change the
    // gate would not take is a way of taking it, and the command line must not
    // be the way around a rule the browser enforces.
    //
    // The failure this prevents is quiet rather than loud: a refused run *has*
    // a branch — made before the agent started — whose head is the commit it
    // branched from, so `--base-ref ostraka/<refused>` succeeds and starts
    // somewhere else entirely.
    let _guard = exclusive();
    let scratch = project("cli-refused", 0);
    std::fs::write(
        scratch.path().join(".ostraka/ostraka.toml"),
        "[gate]\nchecks = [{ name = \"check\", cmd = \"false\", required = true }]\n\n\
         [gate.review]\nmust_differ_from_author = true\n",
    )
    .expect("config");
    let workspace = Workspace::at(scratch.path());

    let refused = crate::run::execute(
        &workspace,
        &crate::run::Args::for_task("write a file".into()),
        None,
    )
    .expect("the run completes");
    assert!(!refused.approved(), "the gate let it through");

    let mut args = crate::run::Args::for_task("carry on".into());
    args.from = Some(refused.record.run_id.clone());
    // `RunReport` is not `Debug`, so the refusal is taken by hand rather than
    // through `expect_err`.
    let refusal = match crate::run::execute(&workspace, &args, None) {
        Ok(_) => panic!("a refused run was continued"),
        Err(e) => e,
    };
    let said = refusal.to_string();
    assert!(
        said.contains("not a base to build on"),
        "the reason was not given: {said}"
    );
}

#[test]
fn continuing_a_run_nobody_recorded_says_so() {
    let _guard = exclusive();
    let scratch = project("cli-nosuch", 0);
    let workspace = Workspace::at(scratch.path());
    let mut args = crate::run::Args::for_task("carry on".into());
    args.from = Some("t-never-happened".into());
    let refusal = match crate::run::execute(&workspace, &args, None) {
        Ok(_) => panic!("a run nobody recorded was continued"),
        Err(e) => e,
    };
    assert!(
        refusal.to_string().contains("no run"),
        "{}",
        refusal.to_string()
    );
}

#[test]
fn choosing_an_agent_the_workspace_has_not_written_writes_it_first() {
    // Without the profile the name would be set and the run could not resolve
    // it: routing reads `adapters/` and nothing else, so being offered
    // something that fails when it is taken is worse than not being offered it.
    //
    // The list is seeded rather than discovered. Discovery asks the machine
    // what is installed, and a test that asks the machine is a test that does
    // nothing on a machine with nothing installed — which is every CI runner
    // this has. The earlier version of this test returned early there, passing
    // without exercising a line of what it was written for.
    let _guard = exclusive();
    let scratch = project("agents-adopt", 0);
    let dir = scratch.path();
    let mut d = Driver::open(dir);

    d.ctrl('x').key(KeyCode::Char('a'));
    assert_eq!(d.app.dialog, Some(Dialog::Agents));

    // A profile this build ships, which this workspace does not have. `codex`
    // is one of `init::TEMPLATES`, so writing it needs nothing installed.
    d.app.agents.push(super::view::Agent {
        id: "codex".into(),
        ready: true,
        note: "codex-cli 0.0.0".into(),
        configured: false,
    });
    d.app.pick = d.app.agents.len() - 1;
    assert!(
        !dir.join(".ostraka/adapters/codex.toml").exists(),
        "the fixture already had the profile this is about writing"
    );
    d.shows("not configured");

    d.key(KeyCode::Char('a'));
    assert_eq!(d.app.thread().adapter.as_deref(), Some("codex"));
    assert!(
        dir.join(".ostraka/adapters/codex.toml").is_file(),
        "the profile was named but never written"
    );

    // The bytes are the ones `init` ships, not an invention.
    let written = std::fs::read_to_string(dir.join(".ostraka/adapters/codex.toml")).expect("read");
    let shipped = crate::init::TEMPLATES
        .iter()
        .find(|(name, _)| *name == "codex.toml")
        .map(|(_, text)| *text)
        .expect("shipped");
    assert_eq!(written, shipped);

    // And it is one of the workspace's own now, not an offer.
    let now = d
        .app
        .agents
        .iter()
        .find(|a| a.id == "codex")
        .expect("still listed");
    assert!(
        now.configured,
        "the written profile is still offered as missing"
    );
}

#[test]
fn only_what_is_installed_is_ever_offered() {
    // The list is an offer. Anything in it that is not installed is a choice
    // that fails when it is taken, so the filter is the property worth pinning
    // — and it holds whatever this machine happens to have.
    let _guard = exclusive();
    let scratch = project("agents-offer", 0);
    let mut d = Driver::open(scratch.path());
    d.ctrl('x').key(KeyCode::Char('a'));

    assert!(
        d.app.agents.iter().any(|a| a.configured),
        "the workspace's own profiles are missing from its own list"
    );
    assert!(
        d.app
            .agents
            .iter()
            .filter(|a| !a.configured)
            .all(|a| a.ready),
        "something not installed was offered"
    );
}

#[test]
fn the_browser_shows_what_a_run_left_before_it_removes_any_of_it() {
    // A list before an action, the way the command line is a dry run before
    // `--apply`. Removing a directory is not a keystroke to offer without
    // saying what it will take.
    let _guard = exclusive();
    let scratch = project("prune", 0);
    let mut d = Driver::open(scratch.path());

    // A refused run keeps its worktree on purpose — it is the evidence — and
    // that is exactly what fills a disk later.
    std::fs::write(
        scratch.path().join(".ostraka/ostraka.toml"),
        "[gate]\nchecks = [{ name = \"check\", cmd = \"false\", required = true }]\n\n\
         [gate.review]\nmust_differ_from_author = true\n",
    )
    .expect("config");
    d.task("write a file");
    assert!(!d.last().approved(), "the gate let it through");

    d.ctrl('x').key(KeyCode::Char('u'));
    assert_eq!(d.app.dialog, Some(Dialog::Prune));
    assert_eq!(
        d.app.leftovers.len(),
        1,
        "the refused run's worktree is not listed"
    );
    let left = d.app.leftovers[0].path.clone();
    assert!(left.is_dir(), "the fixture is wrong: nothing is there");
    // The thing somebody is actually afraid of, said before the key is pressed.
    d.shows("Branches and run records are untouched");

    // Esc leaves it alone.
    d.key(KeyCode::Esc);
    assert!(left.is_dir(), "esc removed something");

    d.ctrl('x').key(KeyCode::Char('u'));
    d.key(KeyCode::Char('y'));
    assert!(!left.exists(), "y did not remove the worktree");
    assert_eq!(d.app.dialog, None);

    // The branch the run made is still there, which is the whole posture: a
    // checkout can be made again and a commit cannot.
    let run_id = d
        .last()
        .finished
        .as_ref()
        .map(|f| f.run_id.clone())
        .expect("a finished run");
    let out = Command::new("git")
        .args(["rev-parse", "--verify", &format!("ostraka/{run_id}")])
        .current_dir(repo_of(&scratch))
        .output()
        .expect("git");
    assert!(out.status.success(), "the branch went with the worktree");
}

/// Rewrites the writer in a fixture into one whose context fills halfway
/// through, which is what a token limit actually looks like from here: part of
/// a change on disk, a non-zero exit, and the reason on stderr.
fn out_of_context(dir: &Path) {
    std::fs::write(
        dir.join("writer.sh"),
        "#!/bin/sh\n\
         case \"$1\" in --probe) echo ok; exit 0;; esac\n\
         echo 'reading the repository'\n\
         printf 'half a line\\n' >> wrote.txt\n\
         echo 'Error: prompt is too long: 210000 tokens > 200000 maximum' >&2\n\
         exit 1\n",
    )
    .expect("script");
}

#[test]
fn a_task_whose_agent_runs_out_of_tokens_is_refused_and_says_why() {
    // The dangerous shape: the vendor had written part of the change when its
    // context filled, so the worktree is not empty and the exit code is not
    // zero. Half a change is not a change anybody should be asked to review,
    // and the chain must not stand on one.
    let _guard = exclusive();
    let scratch = project("out-of-tokens", 0);
    out_of_context(scratch.path());
    let mut d = Driver::open(scratch.path());
    // Pinned, so which of the two scripts authors is not left to routing.
    d.app.thread_mut().adapter = Some("writer".into());
    d.app.thread_mut().review_adapter = Some("reader".into());

    d.task("write something long");

    assert!(!d.last().approved(), "a half-written change was approved");
    assert_eq!(
        d.app.thread().base_ref,
        "HEAD",
        "the chain stood on a change that ran out"
    );

    // The vendor's own account of why, both where it said it and on the rule
    // that closes the turn.
    let screen = d.screen();
    assert!(screen.contains("prompt is too long"), "{screen}");
    assert!(
        screen.contains("could not run"),
        "the outcome did not say why:\n{screen}"
    );

    // The reviewer was never asked. There was nothing finished to review, and
    // asking would have spent a second vendor to be told so.
    assert!(
        !screen.contains("review"),
        "a reviewer was called on half a change:\n{screen}"
    );

    // And what it managed to write is kept, because that is the evidence.
    let left = std::fs::read_dir(scratch.path().join(".ostraka/worktrees"))
        .expect("a worktrees directory")
        .filter_map(|e| e.ok())
        .find(|e| e.path().join("wrote.txt").is_file());
    assert!(left.is_some(), "the evidence was thrown away");
}

#[test]
fn a_run_can_be_stopped_from_the_browser_and_is_not_called_a_verdict() {
    let _guard = exclusive();
    let scratch = project("stop", 30);
    let mut d = Driver::open(scratch.path());

    d.typed("a task nobody wants finished").key(KeyCode::Enter);
    // In the same breath as starting it, which is the ordering that used to
    // lose the request to the run clearing the flag behind it.
    d.ctrl('x').key(KeyCode::Char('s'));
    assert!(d.app.thread().live.as_ref().expect("a session").stopping);
    d.shows("stopping");

    d.until("the run to stop", |app| app.thread().turns.len() == 1);
    d.shows("stopped by the operator");
    ostraka_adapter::interrupt::clear();
}

#[test]
fn quitting_during_a_run_waits_for_it_rather_than_walking_away() {
    // A process that exited here would leave a vendor writing into a worktree.
    let _guard = exclusive();
    let scratch = project("quit", 30);
    let mut d = Driver::open(scratch.path());

    d.typed("a task interrupted by leaving").key(KeyCode::Enter);
    d.ctrl('c');
    // Asked first. It says what leaving costs before it costs it.
    assert_eq!(d.app.dialog, Some(Dialog::Leaving));
    d.shows("A run is going");
    d.key(KeyCode::Char('y'));

    assert!(!d.app.quit, "the browser left while a run was going");
    assert!(d.app.leaving);
    d.shows("stopping the run");

    d.until("the browser to leave", |app| app.quit);

    let runs = std::fs::read_dir(scratch.path().join(".ostraka/runs"))
        .expect("a runs directory")
        .count();
    assert_eq!(runs, 1, "the run was abandoned without a record");
    ostraka_adapter::interrupt::clear();
}

#[test]
fn a_run_is_looked_up_in_a_dialog_and_read_on_a_screen_of_its_own() {
    let _guard = exclusive();
    let scratch = project("lookup", 0);
    let mut d = Driver::open(scratch.path());
    d.task("write a file");
    d.task("write it again");

    d.ctrl('x').key(KeyCode::Char('l'));
    assert_eq!(d.app.dialog, Some(Dialog::Runs));
    d.shows("write a file");
    d.shows("enter opens it");

    // Typing in the dialog narrows it.
    d.typed("again");
    d.shows("1 of 2 runs");
    d.hides("write a file");

    d.key(KeyCode::Enter);
    assert_eq!(d.app.dialog, None);
    assert_eq!(d.app.screen, Screen::Record);
    assert_eq!(d.app.focus, Focus::Keys);

    // checks, then events, then the diff, which is read from the commit the
    // run made rather than from anything the agent said about itself.
    d.shows("check");
    d.key(KeyCode::Tab);
    d.shows("reading the repository");
    d.key(KeyCode::Tab);
    d.shows("written by the agent");

    // And escape comes back to the work, with the box.
    d.key(KeyCode::Esc);
    assert_eq!(d.app.screen, Screen::Work);
    assert_eq!(d.app.focus, Focus::Prompt);
    assert!(!d.app.quit);
}

#[test]
fn the_agents_dialog_names_who_writes_and_who_reviews() {
    let _guard = exclusive();
    let scratch = project("agents", 0);
    let mut d = Driver::open(scratch.path());

    d.ctrl('x').key(KeyCode::Char('a'));
    assert_eq!(d.app.dialog, Some(Dialog::Agents));
    d.shows("automatic");
    d.shows("writer");
    d.shows("reader");

    d.key(KeyCode::Char('a'));
    d.shows("writes");
    assert!(d.app.thread().adapter.is_some());
    d.key(KeyCode::Down).key(KeyCode::Char('r'));
    assert!(d.app.thread().review_adapter.is_some());
    assert_ne!(d.app.thread().adapter, d.app.thread().review_adapter);
    d.key(KeyCode::Esc);

    // And a run started afterwards is run by the pair that was named.
    let author = d.app.thread().adapter.clone().expect("an author");
    d.task("write a file");
    assert_eq!(
        d.app.current().map(|r| r.adapter.clone()),
        Some(author),
        "the named author did not write it"
    );
}

#[test]
fn a_fresh_thread_goes_back_to_head() {
    let _guard = exclusive();
    let scratch = project("fresh", 0);
    let mut d = Driver::open(scratch.path());
    d.task("write a file");
    assert!(d.app.thread().continuing());

    d.ctrl('x').key(KeyCode::Char('f'));
    assert_eq!(d.app.thread().base_ref, "HEAD");
    assert!(d.app.thread().turns.is_empty());
    // The thread is empty; the directory is not, and the screen says which.
    d.shows("Write a task below");
    d.shows("Last asked here");
    d.shows("write a file");
}

#[test]
fn the_palette_reaches_a_command_by_name_and_the_leader_by_letter() {
    let scratch = Scratch::new("commands");
    std::fs::create_dir_all(scratch.path().join("repositories/work")).expect("repository");
    std::fs::write(
        scratch.path().join("repositories/work/Cargo.toml"),
        "[package]\n",
    )
    .expect("write");
    let mut d = Driver::open(scratch.path());

    d.ctrl('k').typed("keys").key(KeyCode::Enter);
    assert_eq!(d.app.dialog, Some(Dialog::Keys));
    d.shows("promote a record");
    d.shows("ctrl-x");
    d.key(KeyCode::Esc);

    d.ctrl('x').key(KeyCode::Char('h'));
    assert_eq!(d.app.dialog, Some(Dialog::Keys));
    d.key(KeyCode::Esc);
    assert_eq!(d.app.dialog, None);
}