ostraka 1.3.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
//! `ostraka init` — make a directory into a project Ostraka can run in.
//!
//! Two files and a listing: `ostraka.toml` says how this project is verified,
//! `adapters/` says which CLIs may run, and `.gitignore` keeps the working
//! evidence out of history. Writing them by hand is what everyone did until
//! now, including this project's own scratch repositories.
//!
//! Nothing is overwritten. A plan says what exists and what is missing, and
//! applying it writes only the missing part — so running it twice is safe, and
//! running it in a half-configured project completes it rather than resetting
//! it.
//!
//! The adapter templates are the profiles this repository ships, embedded so a
//! binary installed by `curl` carries them. They are copies of `adapters/*.toml`
//! and `check-hygiene.sh` fails if the two drift.

use std::path::{Path, PathBuf};

/// What kind of project this is, as far as the files on disk say.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Rust,
    Node,
    Python,
    /// Nothing recognisable. The gate written is one that refuses, because a
    /// gate that passes everything is worse than one that fails loudly.
    Unknown,
}

impl Kind {
    /// What kind of project a workspace is for.
    ///
    /// Read from the repositories it holds rather than from the workspace,
    /// which has no source in it — so it is handed the repositories directory,
    /// wherever that is, rather than assuming `repositories/`. A workspace with
    /// nothing in it yet, or with several that disagree, gets the gate that
    /// fails on purpose, which is the right answer to "I cannot tell".
    pub fn of_repositories(repositories: &Path) -> Self {
        let mut kinds: Vec<Kind> = std::fs::read_dir(repositories)
            .into_iter()
            .flatten()
            .filter_map(|e| e.ok())
            .map(|e| e.path())
            .filter(|p| p.is_dir())
            .map(|p| Self::detect(&p))
            .collect();
        kinds.dedup();
        match kinds.as_slice() {
            [one] => *one,
            _ => Self::Unknown,
        }
    }

    pub fn detect(project: &Path) -> Self {
        if project.join("Cargo.toml").is_file() {
            Self::Rust
        } else if project.join("package.json").is_file() {
            Self::Node
        } else if project.join("pyproject.toml").is_file()
            || project.join("setup.py").is_file()
            || project.join("requirements.txt").is_file()
        {
            Self::Python
        } else {
            Self::Unknown
        }
    }

    pub fn describe(self) -> &'static str {
        match self {
            Self::Rust => "a Rust project",
            Self::Node => "a Node project",
            Self::Python => "a Python project",
            Self::Unknown => "no recognisable project",
        }
    }
}

/// What will happen to one file.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Create,
    /// Only the lines that are missing, added to what is already there.
    Append,
    AlreadyThere,
}

/// What a file is to the project, which decides who has to care it is missing.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Role {
    /// Without this there is no workspace. `.ostraka/ostraka.toml`.
    Config,
    /// A directory the layout needs, with nothing in it yet.
    Place,
    /// One vendor profile. A project needs at least one; which one is a choice.
    Profile,
    /// Keeps a run's working evidence out of history. Its absence is untidy,
    /// not broken.
    Ignore,
}

#[derive(Debug, Clone)]
pub struct Planned {
    pub path: PathBuf,
    pub contents: String,
    pub action: Action,
    pub role: Role,
}

#[derive(Debug, Clone)]
pub struct Plan {
    pub project: PathBuf,
    pub kind: Kind,
    pub files: Vec<Planned>,
}

impl Plan {
    /// True when there is nothing left to do. What `init` asks.
    pub fn complete(&self) -> bool {
        self.files.iter().all(|f| f.action == Action::AlreadyThere)
    }

    /// True when this directory can be run as it stands.
    ///
    /// Deliberately weaker than `complete`, and it is the question the browser
    /// asks. A project with a config and a profile runs, whether or not its
    /// `.gitignore` has picked up the two lines `init` also offers — and
    /// answering "this directory is not an Ostraka project yet" across a
    /// screen that has runs to show gets it plainly wrong. This repository's
    /// own `.gitignore` names four paths under `.ostraka/` rather than the
    /// directory, which is how that was found.
    pub fn runnable(&self) -> bool {
        self.files
            .iter()
            .any(|f| f.role == Role::Config && f.action == Action::AlreadyThere)
            && has_a_profile(&self.project)
    }
}

/// The profiles this repository ships, as `init` will write them.
///
/// Kept here rather than read from disk because the binary is installed on its
/// own; a profile someone has to fetch separately is a profile they will not
/// have.
pub const TEMPLATES: [(&str, &str); 6] = [
    ("agy.toml", include_str!("../templates/agy.toml")),
    (
        "claude-code.toml",
        include_str!("../templates/claude-code.toml"),
    ),
    ("codex.toml", include_str!("../templates/codex.toml")),
    (
        "copilot-cli.toml",
        include_str!("../templates/copilot-cli.toml"),
    ),
    ("grok.toml", include_str!("../templates/grok.toml")),
    ("kimi-cli.toml", include_str!("../templates/kimi-cli.toml")),
];

/// Writes one shipped profile into a workspace's `adapters/`.
///
/// The same bytes `init` would have written, from the same list, so a profile
/// added later is the profile that would have been there from the start. The
/// directory is made if it is missing, because the case this exists for is a
/// workspace that has no `adapters/` at all.
///
/// An existing file is left alone: whoever edited it meant to, and overwriting
/// somebody's `[env]` block to fix a routing failure would be a poor trade.
pub fn write_profile(workspace: &crate::workspace::Workspace, id: &str) -> std::io::Result<()> {
    let Some((_, contents)) = TEMPLATES
        .iter()
        .find(|(name, _)| name.strip_suffix(".toml") == Some(id))
    else {
        return Err(std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("no profile named {id:?} is shipped"),
        ));
    };
    let dir = workspace.adapters();
    std::fs::create_dir_all(&dir)?;
    let path = dir.join(format!("{id}.toml"));
    if path.exists() {
        return Ok(());
    }
    std::fs::write(path, contents)
}

/// Lines that keep a run's working evidence out of history.
/// Lines that keep a run's working evidence out of history.
///
/// The subdirectories rather than `/.ostraka/` itself, because the
/// configuration and the adapter profiles live in there too and those are
/// meant to be committed — a workspace's agreement about how runs are made is
/// not working evidence.
const IGNORED: [&str; 5] = [
    "/.ostraka/runs/",
    "/.ostraka/worktrees/",
    "/.ostraka/cache/",
    "/.ostraka/secrets/",
    "/.ostraka/vendor-home/",
];

pub fn plan(project: &Path) -> Plan {
    plan_with(project, None)
}

/// The plan, with the repositories directory chosen on the command line.
///
/// `repositories` is `--repositories` as typed, read against the current
/// directory. Given, it is where detection looks and which place gets made,
/// and it is written into the config `init` generates — relative to the
/// workspace where it is inside it, so the workspace still moves as one
/// directory, and absolute where it is not. Not given, the workspace's own
/// `[workspace] repositories` decides if it has one, and `repositories/` if not.
pub fn plan_with(project: &Path, repositories: Option<&Path>) -> Plan {
    let root = project
        .canonicalize()
        .unwrap_or_else(|_| project.to_path_buf());
    // The same resolver `Workspace::open` uses, so `~/code` means the home
    // directory here too. And never the workspace itself: that would be
    // written down as `repositories = ""`, which the next command refuses with
    // a message about emptiness rather than about the actual mistake —
    // `init_cmd` refuses it by name before a plan is made.
    let chosen = repositories
        .map(|given| crate::workspace::resolve_flag(given).unwrap_or_else(|_| given.to_path_buf()))
        .filter(|dir| *dir != root);
    let dir = chosen
        .clone()
        .unwrap_or_else(|| crate::workspace::Workspace::at(project).repositories_dir());
    // Relative to the workspace wherever it can be, so `repositories/` stays
    // `repositories/` in what `init` prints, and a directory inside the
    // workspace is written down in a form that survives moving it.
    let place = match dir.strip_prefix(&root) {
        Ok(inside) => inside.display().to_string(),
        Err(_) => dir.display().to_string(),
    };

    let kind = Kind::of_repositories(&dir);
    let mut files = vec![planned(
        project,
        ".ostraka/ostraka.toml",
        with_layout(config_for(kind), chosen.as_ref().map(|_| place.as_str())),
        Role::Config,
    )];

    for (name, contents) in TEMPLATES {
        files.push(planned(
            project,
            &format!(".ostraka/adapters/{name}"),
            contents.to_string(),
            Role::Profile,
        ));
    }
    // The two directories the layout is about. A repository is cloned into the
    // first; the second is linked into every worktree, so what an agent works
    // out along the way survives the run that worked it out.
    //
    // `skills/` is not among them, and that is deliberate. Notes are written by
    // runs, so a run needs somewhere to write before it has anything to say;
    // skills are written by people, and an empty directory waiting for one is
    // clutter that also costs the setup screen a line it was using to explain
    // the gate. A workspace grows one when somebody has a skill to put in it.
    for place in [place.as_str(), "notes"] {
        files.push(planned(project, place, String::new(), Role::Place));
    }
    files.push(gitignore(project));

    Plan {
        project: project.to_path_buf(),
        kind,
        files,
    }
}

/// Whether `adapters/` holds a profile of any name.
///
/// Asked of the directory rather than of the plan, and the difference is the
/// whole point: a plan lists the profiles `init` would write, so a
/// project that brought its own under other names has every planned profile
/// missing while being perfectly able to run. Reading that as "not set up yet"
/// put the opening screen over a working project — and then a stray keystroke
/// on that screen wrote profiles into it that nobody had asked for.
fn has_a_profile(project: &Path) -> bool {
    std::fs::read_dir(project.join(".ostraka/adapters"))
        .map(|entries| {
            entries
                .flatten()
                .any(|e| e.path().extension().is_some_and(|kind| kind == "toml"))
        })
        .unwrap_or(false)
}

fn planned(project: &Path, relative: &str, contents: String, role: Role) -> Planned {
    let path = project.join(relative);
    let action = if path.exists() {
        Action::AlreadyThere
    } else {
        Action::Create
    };
    Planned {
        path,
        contents,
        action,
        role,
    }
}

/// The ignore entries, added to whatever is already in the file.
///
/// Appended rather than written: a project's `.gitignore` is its own, and
/// replacing it to add two lines would be a rude way to set up a tool.
fn gitignore(project: &Path) -> Planned {
    let path = project.join(".gitignore");
    let existing = std::fs::read_to_string(&path).unwrap_or_default();
    let missing: Vec<&str> = IGNORED
        .iter()
        .copied()
        .filter(|line| !existing.lines().any(|l| l.trim() == *line))
        .collect();

    if missing.is_empty() && path.exists() {
        return Planned {
            path,
            contents: String::new(),
            action: Action::AlreadyThere,
            role: Role::Ignore,
        };
    }

    let block = format!(
        "\n# Ostraka: worktrees an agent works in, and the record of each run.\n\
         # The audit trail that has to survive is in the commits, not here.\n{}\n",
        missing.join("\n")
    );
    Planned {
        path,
        contents: block,
        action: if existing.is_empty() {
            Action::Create
        } else {
            Action::Append
        },
        role: Role::Ignore,
    }
}

/// The gate for a detected project.
///
/// Never empty. An unrecognised project gets a check that fails with an
/// instruction, because a gate with nothing in it would approve anything a
/// reviewer waved through, and silence is the wrong way to learn that.
/// The config, with where its repositories live written down if that was chosen.
fn with_layout(mut config: String, repositories: Option<&str>) -> String {
    if let Some(dir) = repositories {
        config.push_str(&format!(
            "\n[workspace]\n\
             # Where the repositories being worked on live, instead of `repositories/`.\n\
             # Relative paths are read from this workspace; `~/` is the home directory.\n\
             repositories = \"{}\"\n",
            dir.replace('\\', "\\\\").replace('"', "\\\"")
        ));
    }
    config
}

fn config_for(kind: Kind) -> String {
    let checks = match kind {
        Kind::Rust => vec![
            ("format", "cargo fmt --all -- --check"),
            ("lint", "cargo clippy --all-targets -- -D warnings"),
            ("test", "cargo test --workspace"),
            ("build", "cargo build --workspace"),
        ],
        Kind::Node => vec![("test", "npm test")],
        Kind::Python => vec![("test", "python -m pytest")],
        Kind::Unknown => vec![(
            "declare-your-checks",
            "echo 'ostraka: edit ostraka.toml and declare how this project is verified' >&2; \
             exit 1",
        )],
    };

    let mut out = String::from(
        "# How this project is verified.\n\
         #\n\
         # These commands run inside the worktree an agent worked in, before any\n\
         # reviewer is asked anything. A change that fails one of them never\n\
         # reaches review.\n\n[gate]\nchecks = [\n",
    );
    for (name, cmd) in &checks {
        out.push_str(&format!(
            "    {{ name = \"{name}\", cmd = \"{}\", required = true }},\n",
            cmd.replace('\\', "\\\\").replace('"', "\\\"")
        ));
    }
    out.push_str("]\n\n");
    if kind == Kind::Unknown {
        out.push_str(
            "# The check above fails on purpose. Ostraka could not tell what kind of\n\
             # project this is, and a gate that declares nothing would approve\n\
             # anything a reviewer waved through. Replace it with the commands you\n\
             # would want run before trusting a change you did not write.\n\n",
        );
    }
    out.push_str(
        "# A check that hangs otherwise hangs every run waiting on the gate.\n\
         timeout_secs = 1800\n\n\
         [policy]\n\
         # Wall-clock ceiling for one agent, after which it is stopped. An agent\n\
         # waiting on a stalled connection, or on a prompt nobody will answer,\n\
         # otherwise waits forever and so does the fleet.\n\
         timeout_secs = 900\n\n\
         # Paths an agent may modify. Enforced at the gate, not by the sandbox,\n\
         # and read from git rather than from the agent's own account of itself.\n\
         # allowed_paths = [\"src/\"]\n\
         # enforce_paths = true\n\n\
         [gate.review]\n\
         # Whoever wrote a change cannot be the one who approves it.\n\
         must_differ_from_author = true\n\n\
         [worktree]\n\
         base = \"worktrees\"\n",
    );
    out.push_str(link_for(kind));
    out
}

/// What a worktree needs linked into it for this kind of project.
///
/// A worktree is a fresh checkout, so anything git ignores is absent — and for
/// most ecosystems that is exactly the directory the toolchain needs. Detecting
/// a Node project and writing `npm test` without this hands somebody a gate
/// that cannot run in the environment Ostraka itself builds.
fn link_for(kind: Kind) -> &'static str {
    match kind {
        Kind::Node => concat!(
            "\n",
            "# A worktree is a fresh checkout, so gitignored directories are not in it.\n",
            "# Linked rather than installed per worktree: `npm ci` in each one costs\n",
            "# hundreds of megabytes, and linking is instant and free.\n",
            "link = [\"node_modules\"]\n",
        ),
        Kind::Python => concat!(
            "\n",
            "# A worktree is a fresh checkout, so gitignored directories are not in it.\n",
            "# Uncomment whichever your toolchain needs.\n",
            "# link = [\".venv\"]\n",
        ),
        Kind::Rust | Kind::Unknown => concat!(
            "\n",
            "# A worktree is a fresh checkout, so anything git ignores is absent from it.\n",
            "# List what your toolchain needs; it is linked, not copied.\n",
            "# link = [\"node_modules\"]\n",
            "\n",
            "# Or run a command in the worktree before the agent starts.\n",
            "# setup = \"make deps\"\n",
        ),
    }
}

/// Writes the missing part of a plan. Returns what it wrote.
pub fn apply(plan: &Plan, force: bool) -> std::io::Result<Vec<PathBuf>> {
    let mut written = Vec::new();
    for file in &plan.files {
        let doing = if force && file.action == Action::AlreadyThere {
            Action::Create
        } else {
            file.action
        };
        match doing {
            Action::AlreadyThere => continue,
            // A place is a directory with nothing in it: `repositories/` for
            // what is worked on, `notes/` for what is worked out.
            Action::Create if file.role == Role::Place => {
                std::fs::create_dir_all(&file.path)?;
            }
            Action::Create => {
                if let Some(parent) = file.path.parent() {
                    std::fs::create_dir_all(parent)?;
                }
                std::fs::write(&file.path, &file.contents)?;
            }
            Action::Append => {
                use std::io::Write;
                let mut handle = std::fs::OpenOptions::new().append(true).open(&file.path)?;
                handle.write_all(file.contents.as_bytes())?;
            }
        }
        written.push(file.path.clone());
    }
    Ok(written)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    fn scratch() -> PathBuf {
        static NEXT: AtomicUsize = AtomicUsize::new(0);
        let path = std::env::temp_dir().join(format!(
            "ostraka-init-{}-{}",
            std::process::id(),
            NEXT.fetch_add(1, Ordering::Relaxed)
        ));
        let _ = std::fs::remove_dir_all(&path);
        std::fs::create_dir_all(&path).expect("scratch dir");
        path
    }

    #[test]
    fn a_rust_project_gets_the_checks_a_rust_project_needs() {
        let dir = scratch();
        std::fs::create_dir_all(dir.join("repositories/work")).expect("repository");
        std::fs::write(dir.join("repositories/work/Cargo.toml"), "[package]\n").expect("write");
        let plan = plan(&dir);
        assert_eq!(plan.kind, Kind::Rust);
        let config = &plan.files[0].contents;
        assert!(config.contains("cargo clippy"), "{config}");
        assert!(config.contains("must_differ_from_author = true"));
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_unrecognised_project_gets_a_gate_that_refuses() {
        // A gate declaring nothing approves whatever a reviewer waves through.
        // Failing loudly is the only safe thing to generate.
        let dir = scratch();
        let plan = plan(&dir);
        assert_eq!(plan.kind, Kind::Unknown);
        let config = &plan.files[0].contents;
        assert!(config.contains("exit 1"), "{config}");
        assert!(config.contains("fails on purpose"), "{config}");

        // And it must still be a valid, non-empty gate.
        let parsed = ostraka_core::config::Config::parse(config).expect("parses");
        parsed.validate().expect("a generated config is usable");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_node_project_gets_a_gate_that_can_actually_run() {
        // The reported defect: init detected Node and wrote `npm test`, which
        // cannot execute in a worktree because node_modules is gitignored and
        // therefore absent. Detecting the ecosystem and then handing over an
        // unrunnable gate is worse than not detecting it.
        let config = ostraka_core::config::Config::parse(&config_for(Kind::Node)).expect("parses");
        assert_eq!(config.worktree.link, ["node_modules"]);
    }

    #[test]
    fn a_project_whose_gitignore_covers_the_ground_differently_is_still_runnable() {
        // This repository's own `.gitignore` names four paths under `.ostraka/`
        // rather than the directory, written before `init` existed. `init` is
        // right that the line it offers is not there, and the browser was
        // wrong to read that as a directory nobody had set up yet.
        let dir = scratch();
        std::fs::create_dir_all(dir.join("repositories/work")).expect("repository");
        std::fs::write(dir.join("repositories/work/Cargo.toml"), "[package]\n").expect("write");
        apply(&plan(&dir), false).expect("applies");
        std::fs::write(
            dir.join(".gitignore"),
            "/target\n/worktrees/\n/.ostraka/runs/\n/.ostraka/vendor-home/\n",
        )
        .expect("rewrite");

        let plan = plan(&dir);
        assert!(!plan.complete(), "init should still offer the missing line");
        assert!(plan.runnable(), "a configured project read as unconfigured");
    }

    #[test]
    fn a_directory_with_nothing_in_it_is_neither_complete_nor_runnable() {
        let dir = scratch();
        let plan = plan(&dir);
        assert!(!plan.complete());
        assert!(!plan.runnable());
    }

    #[test]
    fn a_project_that_brought_its_own_adapter_profiles_is_runnable() {
        // The plan wants its own profiles by name. A project with one profile
        // under a name of its own has none of them, and runs perfectly well —
        // reading that as "not set up yet" is how the opening screen ended up
        // over a working project, with a stray key on it writing three
        // profiles nobody had asked for.
        let dir = scratch();
        std::fs::create_dir_all(dir.join(".ostraka")).expect("ostraka");
        std::fs::write(dir.join(".ostraka/ostraka.toml"), "# mine\n").expect("write");
        std::fs::create_dir_all(dir.join(".ostraka/adapters")).expect("adapters");
        std::fs::write(dir.join(".ostraka/adapters/mine.toml"), "id = \"mine\"\n").expect("write");

        let plan = plan(&dir);
        assert!(plan.runnable(), "{:?}", plan.files);
        assert!(!plan.complete(), "init should still offer its own");
    }

    #[test]
    fn an_empty_adapters_directory_is_not_a_profile() {
        let dir = scratch();
        std::fs::create_dir_all(dir.join(".ostraka")).expect("ostraka");
        std::fs::write(dir.join(".ostraka/ostraka.toml"), "# mine\n").expect("write");
        std::fs::create_dir_all(dir.join(".ostraka/adapters")).expect("adapters");
        assert!(!plan(&dir).runnable());
    }

    #[test]
    fn a_config_with_no_profile_beside_it_is_not_runnable_yet() {
        // Half-configured is the case the opening screen exists for: there is
        // a config, and nothing it can invoke.
        let dir = scratch();
        std::fs::create_dir_all(dir.join(".ostraka")).expect("ostraka");
        std::fs::write(dir.join(".ostraka/ostraka.toml"), "# mine\n").expect("write");
        assert!(!plan(&dir).runnable());
    }

    #[test]
    fn a_generated_config_carries_both_ceilings() {
        // The point of writing them is that somebody finds out they exist.
        // `policy.timeout_secs` spent this project's whole life declared and
        // unenforced; a default nobody can see is the next version of that.
        for kind in [Kind::Rust, Kind::Node, Kind::Python, Kind::Unknown] {
            let config = ostraka_core::config::Config::parse(&config_for(kind)).expect("parses");
            assert!(
                config.policy.timeout_secs.is_some(),
                "{kind:?} has no agent ceiling"
            );
            assert!(
                config.gate.timeout_secs.is_some(),
                "{kind:?} has no gate ceiling"
            );
        }
    }

    #[test]
    fn every_generated_config_parses_and_validates() {
        for kind in [Kind::Rust, Kind::Node, Kind::Python, Kind::Unknown] {
            let text = config_for(kind);
            let parsed = ostraka_core::config::Config::parse(&text)
                .unwrap_or_else(|e| panic!("{kind:?} did not parse: {e}\n{text}"));
            parsed
                .validate()
                .unwrap_or_else(|e| panic!("{kind:?} did not validate: {e}"));
        }
    }

    #[test]
    fn the_embedded_profiles_are_the_ones_this_project_ships() {
        for (name, contents) in TEMPLATES {
            let profile = ostraka_adapter::Profile::parse(contents)
                .unwrap_or_else(|e| panic!("{name} is not a usable profile: {e}"));
            assert!(!profile.id.is_empty());
        }
    }

    #[test]
    fn repositories_chosen_at_init_are_where_it_looks_and_what_it_writes_down() {
        let dir = scratch();
        let code = dir.join("code");
        std::fs::create_dir_all(code.join("work")).expect("repo");
        std::fs::write(code.join("work/Cargo.toml"), "[package]\n").expect("write");

        let plan = plan_with(&dir, Some(&code));
        // Detection read the chosen directory, not an empty `repositories/`.
        assert_eq!(plan.kind, Kind::Rust);

        let config = plan
            .files
            .iter()
            .find(|f| f.role == Role::Config)
            .expect("a config");
        assert!(
            config.contents.contains("[workspace]"),
            "{}",
            config.contents
        );
        assert!(
            config.contents.contains("repositories = \"code\""),
            "written relative to the workspace: {}",
            config.contents
        );
        // And the published parser still takes the file whole.
        ostraka_core::config::Config::parse(&config.contents).expect("a valid config");

        let places: Vec<_> = plan
            .files
            .iter()
            .filter(|f| f.role == Role::Place)
            .map(|f| f.path.clone())
            .collect();
        assert!(
            !places.iter().any(|p| p.ends_with("repositories")),
            "a repositories/ nobody asked for was planned: {places:?}"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_tilde_in_the_flag_is_the_home_directory_and_not_a_directory_called_tilde() {
        // The shell does not expand `--repositories=~/code` or a quoted one,
        // so `init` sees the tilde itself.
        let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
            return;
        };
        let dir = scratch();
        let plan = plan_with(&dir, Some(Path::new("~/ostraka-plan-probe")));
        let config = plan
            .files
            .iter()
            .find(|f| f.role == Role::Config)
            .expect("a config");
        assert!(
            !config.contents.contains("repositories = \"~"),
            "a literal tilde was written down: {}",
            config.contents
        );
        assert!(
            config
                .contents
                .contains(&home.join("ostraka-plan-probe").display().to_string()),
            "{}",
            config.contents
        );
        assert!(
            !plan.files.iter().any(|f| f.path.starts_with(dir.join("~"))),
            "a directory called ~ was planned inside the workspace"
        );
        assert!(
            !home.join("ostraka-plan-probe").exists(),
            "planning created something"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn the_workspace_itself_is_refused_as_its_own_repositories_directory() {
        let dir = scratch();
        // Planned, it is simply not taken: no `repositories = ""` is written.
        let plan = plan_with(&dir, Some(&dir));
        let config = plan
            .files
            .iter()
            .find(|f| f.role == Role::Config)
            .expect("a config");
        assert!(
            !config.contents.contains("[workspace]"),
            "{}",
            config.contents
        );

        // And asked for on the command line, it is refused by name before
        // anything is written.
        let err = crate::init_cmd::run(&dir, Some(&dir), false, true)
            .expect_err("must refuse")
            .to_string();
        assert!(err.contains("workspace itself"), "{err}");
        assert!(
            !dir.join(".ostraka").exists(),
            "something was written anyway"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn applying_writes_the_files_and_they_are_readable_afterwards() {
        let dir = scratch();
        std::fs::create_dir_all(dir.join("repositories/work")).expect("repository");
        std::fs::write(dir.join("repositories/work/Cargo.toml"), "[package]\n").expect("write");
        let written = apply(&plan(&dir), false).expect("applies");
        // The config, one profile per shipped template, notes/ and .gitignore.
        // The fixture made repositories/ to put a Cargo.toml in, and a place
        // that is already there is left alone, so it is not among them.
        assert_eq!(written.len(), TEMPLATES.len() + 3, "{written:?}");
        assert!(dir.join(".ostraka/ostraka.toml").is_file());
        assert!(dir.join(".ostraka/adapters/codex.toml").is_file());
        assert!(dir.join(".gitignore").is_file());
        assert!(dir.join("notes").is_dir(), "notes were not made");
        assert!(dir.join("repositories").is_dir());

        let text = std::fs::read_to_string(dir.join(".ostraka/ostraka.toml")).expect("reads");
        ostraka_core::config::Config::parse(&text)
            .expect("parses")
            .validate()
            .expect("validates");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn running_it_twice_changes_nothing_the_second_time() {
        let dir = scratch();
        apply(&plan(&dir), false).expect("applies");
        let second = plan(&dir);
        assert!(second.complete(), "{:?}", second.files);
        assert!(apply(&second, false).expect("applies").is_empty());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_half_configured_project_is_completed_rather_than_reset() {
        // Someone's hand-written ostraka.toml is theirs. Init fills the gaps.
        let dir = scratch();
        std::fs::create_dir_all(dir.join(".ostraka")).expect("ostraka");
        std::fs::write(dir.join(".ostraka/ostraka.toml"), "# mine\n").expect("write");
        let written = apply(&plan(&dir), false).expect("applies");
        assert!(!written.iter().any(|p| p.ends_with("ostraka.toml")));
        assert_eq!(
            std::fs::read_to_string(dir.join(".ostraka/ostraka.toml")).expect("reads"),
            "# mine\n"
        );
        assert!(dir.join(".ostraka/adapters/codex.toml").is_file());
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn an_existing_gitignore_is_appended_to_not_replaced() {
        let dir = scratch();
        std::fs::write(dir.join(".gitignore"), "/target\nnode_modules/\n").expect("write");
        apply(&plan(&dir), false).expect("applies");
        let text = std::fs::read_to_string(dir.join(".gitignore")).expect("reads");
        assert!(text.starts_with("/target\nnode_modules/\n"), "{text}");
        assert!(text.contains("/.ostraka/"), "{text}");
        assert!(text.contains("/worktrees/"), "{text}");
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn a_gitignore_that_already_covers_it_is_left_alone() {
        let dir = scratch();
        std::fs::write(dir.join(".gitignore"), "/.ostraka/runs/\n/.ostraka/worktrees/\n/.ostraka/cache/\n/.ostraka/secrets/\n/.ostraka/vendor-home/\n").expect("write");
        let plan = plan(&dir);
        let ignore = plan
            .files
            .iter()
            .find(|f| f.path.ends_with(".gitignore"))
            .expect("planned");
        assert_eq!(ignore.action, Action::AlreadyThere);
        let _ = std::fs::remove_dir_all(&dir);
    }
}