vivac 0.12.6

Provenance tree for work: every node knows which node it was born from
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
//! `vivac setup` — writes what a harness needs, after showing it.
//!
//! `t565` §7, amended by `t579` §4. This module holds what every harness
//! shares: the two roots a harness is set up against, the all-or-nothing
//! commit with its verification and rollback, the confirmation prompt, and
//! the fingerprint that tells an untouched generated file apart from an
//! edited one. `claude_code` is the one harness that exists today, with its
//! own files, its own hook shape and its own rules for "already there"
//! versus "conflict" (`t565` §9 on `INTEGRATION.md`).
//!
//! Not exposed over MCP: setup reforms the environment rather than
//! recording work, which is for whoever has a terminal, the same reason
//! `abandon` and `restore` stay off that server.

mod claude_code;
mod codex;
mod init;
pub mod json;
mod tree;

use crate::args::Args;
use crate::failure::Failure;
use std::io::IsTerminal;
use std::path::{Path, PathBuf};

const HARNESSES: &[&str] = &["claude-code", "codex"];

/// Which harness this run was invoked as, so a command this run proposes
/// is one the person can actually run from where they are (`f714`): the
/// second-map refusal used to name `claude-code` to a person who had
/// typed `codex`, and the flag it proposed that person was refused by
/// name.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub(super) enum Harness {
    ClaudeCode,
    Codex,
}

impl Harness {
    /// The word `vivac setup` itself takes.
    pub(super) fn word(self) -> &'static str {
        match self {
            Self::ClaudeCode => "claude-code",
            Self::Codex => "codex",
        }
    }
}

/// The four flags that used to be `setup`'s own, before `d723` piece B gave
/// them to `init`: which tree a folder belongs to reads the same wherever
/// an agent is opened, so it is `init`'s question to answer and not a
/// harness's. Still recognised rather than unknown, in this order, so a
/// script that still passes one is sent to the command that reads it now.
const MOVED_TO_INIT: &[&str] = &["join", "new-tree", "lane-name", "name"];

/// A tombstone for whichever of [`MOVED_TO_INIT`] this run still carries,
/// naming that flag and the harness this run was invoked as (`f714`'s own
/// reason): `None` once none of the four are present, which is every
/// ordinary run.
///
/// The opening paragraph goes through [`claude_code::wrapped`] rather than
/// a hand-picked line break: `--lane-name` is longer than the other three,
/// and a break placed by hand for the shortest of them ran past 76 columns
/// once the flag itself grew (`f724`'s own lesson, measured a second time
/// here). The command line stays whole -- it is two commands to paste, not
/// prose to wrap.
fn moved_to_init_tombstone(a: &Args, h: Harness) -> Option<Failure> {
    let flag = MOVED_TO_INIT.iter().find(|f| a.has(f))?;
    let mut message = claude_code::wrapped(&format!(
        "--{flag} is vivac init's, not setup's: which tree this folder belongs to \
         reads the same wherever an agent is opened, so it is not a harness's \
         question to answer."
    ));
    message.push('\n');
    message.push_str(&format!(
        "  Run vivac init --{flag} first, then vivac setup {} here.",
        h.word()
    ));
    Some(Failure::Usage(message))
}

pub fn dispatch(cwd: &Path, a: &Args) -> Result<i32, Failure> {
    if a.has("dry-run") && a.has("yes") {
        return Err(Failure::usage(
            "--dry-run writes nothing, so there is nothing for --yes to confirm.\n\n  \
             Give one or the other.",
        ));
    }
    if let [first, ..] = a.extra(1) {
        return Err(Failure::usage(format!(
            "setup does not take \"{first}\".\n\n  It takes one word of its own: the harness to set up."
        )));
    }
    let Some(harness) = a.positional(0) else {
        return Err(Failure::usage(
            "vivac setup needs the harness to set up:  vivac setup claude-code\n  \
             It knows claude-code and codex today.",
        ));
    };
    let h = match harness {
        "claude-code" => Harness::ClaudeCode,
        "codex" => Harness::Codex,
        other => {
            return Err(Failure::usage(format!(
                "vivac setup does not know \"{other}\" yet. It knows: {}",
                HARNESSES.join(", ")
            )))
        }
    };
    if let Some(tombstone) = moved_to_init_tombstone(a, h) {
        return Err(tombstone);
    }
    match h {
        Harness::ClaudeCode => claude_code::run(cwd, a),
        Harness::Codex => codex::run(cwd, a),
    }
}

/// `vivac init`'s own entry point (`d723` piece A), reached once this run
/// carries at least one of the flags this piece gave `init` -- a bare
/// `vivac init` never reaches here at all (`main.rs`'s own guard). The four
/// checks below are `dispatch`'s own, repeated rather than shared: they
/// name the command that is actually stuck, `vivac init` rather than
/// `vivac setup <harness>`, and `dispatch`'s own copies are already tied to
/// `harness_word`, which `init` has none of to give them.
pub fn init(cwd: &Path, a: &Args) -> Result<i32, Failure> {
    if a.has("dry-run") && a.has("yes") {
        return Err(Failure::usage(
            "--dry-run writes nothing, so there is nothing for --yes to confirm.\n\n  \
             Give one or the other.",
        ));
    }
    if a.has("join") && a.has("new-tree") {
        return Err(Failure::usage(
            "--join joins a tree that already exists, and --new-tree plants a \
             separate one, so they contradict each other.\n\n  Give one or the other.",
        ));
    }
    // `t640`, point 2: `--name` fixes a product's name while planting it for
    // the first time, and both `--join` and `--undo` leave planting out of
    // the run entirely -- one joins a product that already has whatever
    // name it has, the other only takes earlier writes back. Left
    // unchecked, `apply`'s own join branch never reads `--name` at all,
    // which would accept the flag and quietly do nothing with it.
    if a.has("name") && a.has("join") {
        return Err(Failure::usage(
            "--name names a product for the first time, and --join always joins \
             one that already has a name, so they contradict each other.\n\n  \
             Give one or the other.",
        ));
    }
    if a.has("name") && a.has("undo") {
        return Err(Failure::usage(
            "--name names a product while planting it, and --undo only takes \
             earlier writes back, so they contradict each other.\n\n  \
             Give one or the other.",
        ));
    }
    // `f632`: `--join` takes a value, so with nothing after it the parser
    // records the flag as present and its value as absent, and every
    // reader downstream only ever asks for the value -- `opt("join")`,
    // never `has("join")`. Left unchecked, that falls straight through to
    // the plant branch and gives a second tree to someone who asked to
    // join one.
    if a.has("join") && a.opt("join").is_none() {
        return Err(Failure::usage(
            "--join needs the project to join, and nothing followed it. Without \
             that word init plants instead of joining, which is a second tree \
             for a product that already has one.\n\n  \
             vivac init --join <project>",
        ));
    }
    // `t640`, point 3: the same gap `f632` already closed for `--join`.
    if a.has("name") && a.opt("name").is_none() {
        return Err(Failure::usage(
            "--name needs the product's own name, and nothing followed it. \
             Without that word init has nothing to save.\n\n  \
             vivac init --name <name>",
        ));
    }
    init::run(cwd, a)
}

/// The two roots setup writes into (`t579` §4). Claude Code never reads
/// `.claude/settings.json` or `.mcp.json` from a folder above the one it was
/// opened in, so its own files always go in `here`. The tree is shared
/// instead, the same one every other command finds: `tree` is the `.vivac/`
/// found walking up from `here`, or `here` itself when none exists yet, so a
/// fresh project gets one planted right where it is opened.
pub struct Roots {
    pub here: PathBuf,
    pub tree: PathBuf,
    /// `None` when there is no tree yet and `setup` is about to plant one.
    pub located: Option<crate::store::Located>,
}

/// Whether `tree` is the very folder that holds the registry of every tree
/// on the machine (`t565` §7.2): a project's tree living inside that one
/// would mix a project with the registry that lists every project. Shared
/// by [`resolve_roots`] (`init`'s own root, planted or not) and
/// [`resolve_for_setup`] (`setup`'s, which only ever reads one that already
/// exists).
fn refuse_registry_as_tree(tree: &Path) -> Option<Failure> {
    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    let is_registry = crate::store::store_dir().is_some_and(|d| canon(&d) == canon(tree));
    is_registry.then(|| registry_refusal(tree))
}

/// Resolves both roots, and refuses if the tree root turns out to be the
/// registry's own folder (`refuse_registry_as_tree`). `init`'s own: a tree
/// this run may be about to plant has nothing at `cwd` yet, so `tree` falls
/// back to `cwd` itself rather than failing the way `store::locate` alone
/// would.
pub fn resolve_roots(cwd: &Path) -> Result<Roots, Failure> {
    let located = crate::store::locate(cwd)?;
    let tree = located
        .as_ref()
        .map(|l| l.root.clone())
        .unwrap_or_else(|| cwd.to_path_buf());
    if let Some(refusal) = refuse_registry_as_tree(&tree) {
        return Err(refusal);
    }
    Ok(Roots {
        here: cwd.to_path_buf(),
        tree,
        located,
    })
}

/// `setup`'s own roots (`d723` piece B): `setup` never plants, so there is
/// no folder to fall back to the way `resolve_roots` falls back to `cwd`
/// for `init` -- no tree resolvable from here at all is `setup`'s first
/// refusal (`Failure::SetupNoTree`), and a tree that resolves from here
/// without this exact folder being either its own or one of its declared
/// lanes yet is its second (`Failure::not_a_lane_yet`): writing the three
/// pieces there would record them under a lane this folder is not.
///
/// `Located::lane_dir` already answers which folder a lane's own files
/// belong to -- the same folder `find_root` stops the upward walk at, once
/// it carries a `.vivac/` of its own -- so comparing it to `cwd` is the
/// whole check; nothing here reads a repository or a lane's own name.
pub(super) fn resolve_for_setup(cwd: &Path) -> Result<Roots, Failure> {
    let Some(located) = crate::store::locate(cwd)? else {
        return Err(Failure::SetupNoTree);
    };
    if !crate::anchor::same_folder(&located.lane_dir, cwd) {
        return Err(Failure::not_a_lane_yet());
    }
    let tree = located.root.clone();
    if let Some(refusal) = refuse_registry_as_tree(&tree) {
        return Err(refusal);
    }
    Ok(Roots {
        here: cwd.to_path_buf(),
        tree,
        located: Some(located),
    })
}

/// The text `t565` §7.2 refuses with, naming `path`: shared between
/// `resolve_roots`, where `path` is the tree root itself, and
/// [`refuse_home_or_global_store`], where `path` is a `.vivac/` found
/// underneath it (`t579` §4.1).
fn registry_refusal(path: &Path) -> Failure {
    Failure::Model(format!(
        "  {} holds the registry of the trees on this machine, so it cannot\n  \
         hold a tree too. Run setup inside a project.",
        path.display()
    ))
}

/// Two more ways for the roots `resolve_roots` already accepted to still be
/// dangerous to write into, caught by `claude_code::run` before it decides
/// between planting and joining (`t579` §4.1, `f583`, `d584`). It used to be
/// caught by `apply` alone, which is exactly what let `--join` bypass it
/// (`t594`): a guard checked inside one branch is a guard
/// the next branch does not have. Both were reachable under 0.10.0, and
/// `--undo` never calls this: undoing whatever an earlier setup wrote there
/// is always safe, and is the only way out for whoever already fell into
/// either shape.
///
/// - `here` itself is the user's home folder: Claude Code's settings and
///   skills there belong to every project that opens in it, not to this
///   one, and the security pillar forbids setup from writing them there.
/// - `tree`'s own `.vivac/` is the global store: `resolve_roots` only
///   catches the tree root equalling `store_dir()` directly, but `find_root`
///   skips a global store it finds walking up and falls back to `here`, so
///   a global store can also turn up as the `.vivac/` `apply` would plant or
///   reuse right under the current directory.
pub fn refuse_home_or_global_store(roots: &Roots) -> Option<Failure> {
    let canon = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    if crate::store::home_dir().is_some_and(|h| canon(&h) == canon(&roots.here)) {
        return Some(Failure::Model(format!(
            "  {} is your home folder. Claude Code's settings and skills here are\n  \
             yours for every project, not this one's, and setup never writes there.\n  \
             Run setup in the folder you open Claude Code in, inside a project.",
            roots.here.display()
        )));
    }
    let vivac_dir = roots.tree.join(crate::store::DIR);
    let is_global_store = crate::registry::marks_global_store(&vivac_dir)
        || crate::store::store_dir().is_some_and(|d| canon(&d) == canon(&vivac_dir));
    if is_global_store {
        return Some(registry_refusal(&vivac_dir));
    }
    None
}

/// The closest strict ancestor of `dir` holding a `.git` entry, folder or
/// worktree file alike -- `dir` itself never counts. Filesystem only: `t579`
/// §4 forbids running git or any other program to answer this.
pub fn git_root_above(dir: &Path) -> Option<PathBuf> {
    let mut d = dir.to_path_buf();
    while d.pop() {
        if d.join(".git").exists() {
            return Some(d);
        }
    }
    None
}

/// What a `PlannedWrite` does to its file.
pub enum Action {
    Write(String),
    /// Removing the file entirely -- an `--undo` that empties a JSON file
    /// out, or a skill no longer wanted. Goes through the same commit as a
    /// write, so it shares its rollback.
    Delete,
}

/// A structural check on a JSON write, run against the file re-read and
/// re-parsed after writing: see [`PlannedWrite::preserved`].
type PreservedCheck = Box<dyn Fn(&json::Value) -> bool>;

/// One file `setup` is about to change, with what was there before so a
/// failed commit can put it back exactly.
pub struct PlannedWrite {
    pub path: PathBuf,
    pub action: Action,
    /// `None` for a file that does not exist yet: rollback removes it
    /// instead of restoring bytes that never existed.
    pub original: Option<Vec<u8>>,
    /// For a JSON write: checked against the file re-read and re-parsed
    /// after writing, in whichever direction this call goes -- a superset
    /// of the original for `apply`, a subsequence of it for `--undo`.
    /// `t565` §7.6's second check, on top of the byte-for-byte one every
    /// write already gets. `None` for the skill file and for every
    /// `Delete`, neither of which this applies to.
    pub preserved: Option<PreservedCheck>,
}

impl PlannedWrite {
    pub fn write(path: PathBuf, content: String, original: Option<Vec<u8>>) -> PlannedWrite {
        PlannedWrite {
            path,
            action: Action::Write(content),
            original,
            preserved: None,
        }
    }

    pub fn delete(path: PathBuf, original: Vec<u8>) -> PlannedWrite {
        PlannedWrite {
            path,
            action: Action::Delete,
            original: Some(original),
            preserved: None,
        }
    }
}

fn sibling_temp(path: &Path) -> PathBuf {
    let mut name = path.file_name().unwrap_or_default().to_os_string();
    name.push(".tmp");
    path.with_file_name(name)
}

/// A temporary file next to `path`, renamed over it -- `write_config_atomic`'s
/// own shape, so a process that dies mid-write leaves the original untouched.
///
/// A temporary left behind by a failed write or rename is removed before the
/// error goes up. It holds the whole new file, and a settings file can carry
/// credentials in its `env` block: a `settings.json.tmp` lying next to the
/// original is exactly the copy under another name that §7.6 keeps setup
/// from ever making.
fn write_atomic(path: &Path, content: &[u8]) -> std::io::Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    let tmp = sibling_temp(path);
    let written = std::fs::write(&tmp, content).and_then(|()| std::fs::rename(&tmp, path));
    if written.is_err() {
        let _ = std::fs::remove_file(&tmp);
    }
    written
}

fn remove_if_present(path: &Path) -> std::io::Result<()> {
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(e),
    }
}

fn apply_action(w: &PlannedWrite) -> std::io::Result<()> {
    match &w.action {
        Action::Write(content) => write_atomic(&w.path, content.as_bytes()),
        Action::Delete => remove_if_present(&w.path),
    }
}

/// Puts `w` back exactly as it was: whether it was written or deleted makes
/// no difference to undoing it, only what `original` says was there.
fn restore_one(w: &PlannedWrite) -> std::io::Result<()> {
    match &w.original {
        Some(bytes) => write_atomic(&w.path, bytes),
        None => remove_if_present(&w.path),
    }
}

fn verify_one(w: &PlannedWrite) -> bool {
    match &w.action {
        Action::Write(content) => {
            let Ok(actual) = std::fs::read(&w.path) else {
                return false;
            };
            if actual != content.as_bytes() {
                return false;
            }
            match &w.preserved {
                Some(check) => std::str::from_utf8(&actual)
                    .ok()
                    .and_then(|s| json::parse(s).ok())
                    .is_some_and(|v| check(&v)),
                None => true,
            }
        }
        Action::Delete => !w.path.exists(),
    }
}

/// Rolls every one of `writes` back, in reverse, and returns the paths it
/// could not restore. `t565` §7.6: the order matters because a later write
/// can depend on an earlier one existing (a directory it lives in).
///
/// Public so a caller whose own next step fails *after* a successful commit
/// -- planting `.vivac/`, say -- can undo the commit by hand and report it
/// with [`failure_with_rollback`], the same way a failure inside the commit
/// itself does.
pub fn rollback(writes: &[PlannedWrite]) -> Vec<PathBuf> {
    let mut failed = Vec::new();
    for w in writes.iter().rev() {
        if restore_one(w).is_err() {
            failed.push(w.path.clone());
        }
    }
    failed
}

enum Cause {
    Write(std::io::Error),
    Verify,
}

/// The exit-5 text for a rollback that just ran: `clause` names what went
/// wrong, and `unrestored` lists whatever the rollback itself could not put
/// back -- empty in the common case, where it says so plainly instead.
pub fn failure_with_rollback(clause: String, unrestored: &[PathBuf]) -> Failure {
    let message = if unrestored.is_empty() {
        format!("{clause}, so setup put every file it\n  touched back as it was.")
    } else {
        let mut m = format!("{clause}, and setup could not put these back as they were:\n");
        for p in unrestored {
            m.push_str(&format!("      {}\n", p.display()));
        }
        m.push_str(
            "  setup keeps no copy on disk, so the only other copy is whatever\n  \
             version control holds.",
        );
        m
    };
    Failure::Io(std::io::Error::other(message))
}

fn rollback_failure(path: &Path, cause: Cause, writes: &[PlannedWrite]) -> Failure {
    let unrestored = rollback(writes);
    let clause = match cause {
        Cause::Write(e) => format!("{} could not be written ({e})", path.display()),
        Cause::Verify => format!("{} did not read back as written", path.display()),
    };
    failure_with_rollback(clause, &unrestored)
}

/// Applies every one of `writes`, in order; on any failure to write or to
/// verify, rolls every one of them back and fails instead of leaving a
/// partial result. `t565` §7.6: this is what makes the four pieces all or
/// nothing, the same promise the security pillar was given.
pub fn commit(writes: &[PlannedWrite]) -> Result<(), Failure> {
    for (i, w) in writes.iter().enumerate() {
        if let Err(e) = apply_action(w) {
            // `w` itself never changed -- a failed write leaves its target
            // exactly as it was, since `write_atomic`'s last step is one
            // rename -- so only the entries before it need rolling back.
            return Err(rollback_failure(&w.path, Cause::Write(e), &writes[..i]));
        }
    }
    for w in writes {
        if !verify_one(w) {
            return Err(rollback_failure(&w.path, Cause::Verify, writes));
        }
    }
    Ok(())
}

/// Whether typing `y` or `yes`, in any mix of case, answered a question.
/// Split out so the interpretation has a test that never has to fake a
/// terminal.
pub fn is_yes(answer: &str) -> bool {
    matches!(answer.trim().to_ascii_lowercase().as_str(), "y" | "yes")
}

/// Prints `prompt`, flushes it out with no line of its own, and reads one
/// line of the answer. Only ever called once a terminal is known to be
/// there -- `--yes` and the no-terminal refusal both skip this entirely.
pub fn ask(prompt: &str) -> bool {
    use std::io::Write;
    print!("{prompt}");
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    let _ = std::io::stdin().read_line(&mut line);
    is_yes(&line)
}

pub fn stdin_is_terminal() -> bool {
    std::io::stdin().is_terminal()
}

/// A value repeated into `no_terminal_text`, quoted only when it has a
/// space in it: the same rule the copied command line needs to survive a
/// shell, and no more than that -- an unquoted path or name with none
/// reads back exactly as it was typed.
fn quoted_if_it_has_a_space(value: &str) -> String {
    if value.contains(' ') {
        format!("\"{value}\"")
    } else {
        value.to_string()
    }
}

/// The flags this run was given, in the fixed order the two commands
/// `no_terminal_text` suggests repeat them in, and only the ones present.
/// `f675`: dropping them used to hand back two bare commands, and running
/// the first one literally -- `vivac setup claude-code --dry-run` -- plans
/// a plant even on a run that asked to `--join` a tree elsewhere. That is
/// not a shorter version of the advice, it is different advice.
fn no_terminal_flags(a: &Args) -> String {
    let mut s = String::new();
    // First, because it is the one flag that decides which of the two
    // sentences below gets built at all (`f718`): dropped, the command
    // this hands back takes the run's own files off nothing and writes
    // them instead, which is the opposite of what was asked.
    if a.has("undo") {
        s.push_str(" --undo");
    }
    if let Some(v) = a.opt("join") {
        s.push_str(" --join ");
        s.push_str(&quoted_if_it_has_a_space(v));
    }
    if a.has("new-tree") {
        s.push_str(" --new-tree");
    }
    if let Some(v) = a.opt("name") {
        s.push_str(" --name ");
        s.push_str(&quoted_if_it_has_a_space(v));
    }
    if let Some(v) = a.opt("lane-name") {
        s.push_str(" --lane-name ");
        s.push_str(&quoted_if_it_has_a_space(v));
    }
    s
}

/// `f675`: built rather than constant, so the two commands it suggests
/// name the run that is actually stuck rather than a bare plant. The two
/// columns keep the alignment a fixed label already fixes; only what
/// comes after the harness word grows. Moved here from `claude_code.rs`
/// alongside [`Harness`] (`f714`), which is what `codex.rs`'s own copy of
/// this text was missing: the same flags, but for a harness that was
/// never spelled out.
pub(super) fn no_terminal_text(h: Harness, a: &Args) -> String {
    let flags = no_terminal_flags(a);
    let word = h.word();
    // `f718`: `--undo` reached its own question without ever passing here,
    // so a run with nobody to answer printed the question anyway, did
    // nothing and exited 0 -- which a script reads as done. It says
    // "remove" rather than "write" because that is what the run asked for,
    // and a sentence about writing would send the reader to the other door.
    if a.has("undo") {
        return format!(
            "  setup asks before removing anything, and there is no terminal to ask.\n  See what it would remove:  vivac setup {word}{flags} --dry-run\n  Then remove it:            vivac setup {word}{flags} --yes"
        );
    }
    format!(
        "  setup asks before writing, and there is no terminal here to ask.\n  See what it would write:  vivac setup {word}{flags} --dry-run\n  Then write it:            vivac setup {word}{flags} --yes"
    )
}

/// [`no_terminal_text`]'s own mirror for `init` (`d723` piece A): the same
/// two commands, naming `vivac init` rather than a harness word `init` has
/// none of to give.
pub(super) fn init_no_terminal_text(a: &Args) -> String {
    let flags = no_terminal_flags(a);
    if a.has("undo") {
        return format!(
            "  init asks before removing anything, and there is no terminal to ask.\n  See what it would remove:  vivac init{flags} --dry-run\n  Then remove it:            vivac init{flags} --yes"
        );
    }
    format!(
        "  init asks before writing, and there is no terminal here to ask.\n  See what it would write:  vivac init{flags} --dry-run\n  Then write it:            vivac init{flags} --yes"
    )
}

/// 64-bit FNV-1a over `data`. Not a cryptographic hash and not meant to be
/// one: it only has to tell an untouched generated file apart from an
/// edited one, and that is what keeps this from pulling in a dependency
/// (`t565` §7.4).
pub fn fnv1a64(data: &[u8]) -> u64 {
    const OFFSET_BASIS: u64 = 0xcbf29ce484222325;
    const PRIME: u64 = 0x100000001b3;
    let mut hash = OFFSET_BASIS;
    for &byte in data {
        hash ^= u64::from(byte);
        hash = hash.wrapping_mul(PRIME);
    }
    hash
}

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

    #[test]
    fn fnv1a64_matches_the_reference_vectors() {
        // The two vectors fnvhash.info publishes for FNV-1a/64.
        assert_eq!(fnv1a64(b""), 0xcbf29ce484222325);
        assert_eq!(fnv1a64(b"a"), 0xaf63dc4c8601ec8c);
    }

    #[test]
    fn is_yes_takes_any_case_of_y_or_yes() {
        for s in ["y", "Y", "yes", "YES", "Yes", "  y  ", "y\n"] {
            assert!(is_yes(s), "{s:?} should count as yes");
        }
        for s in ["n", "no", "", "yep", "sure"] {
            assert!(!is_yes(s), "{s:?} should not count as yes");
        }
    }

    fn temp_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("vivac-setup-{name}-{}", crate::id::ulid()));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// A rename that fails must not leave the temporary behind: it holds the
    /// whole new file, credentials in `env` included, under another name.
    /// A directory where the file should go makes the rename fail on every
    /// platform.
    #[test]
    fn a_failed_rename_leaves_no_temporary_behind() {
        let dir = temp_dir("rename-fails");
        let target = dir.join("settings.json");
        std::fs::create_dir_all(target.join("occupied")).unwrap();
        assert!(write_atomic(&target, b"{\"env\":{}}").is_err());
        assert!(
            !sibling_temp(&target).exists(),
            "the temporary survived the failed rename"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_committed_write_leaves_every_file_as_written() {
        let dir = temp_dir("commit-ok");
        let writes = vec![
            PlannedWrite::write(dir.join("a.txt"), "A".to_string(), None),
            PlannedWrite::write(dir.join("b.txt"), "B".to_string(), None),
        ];
        commit(&writes).unwrap();
        assert_eq!(std::fs::read_to_string(dir.join("a.txt")).unwrap(), "A");
        assert_eq!(std::fs::read_to_string(dir.join("b.txt")).unwrap(), "B");
        std::fs::remove_dir_all(&dir).ok();
    }

    /// `t565` §11 test 15, and the coordinator's point A: a write that fails
    /// on the second file rolls the first one back too, exactly like a
    /// verification failure would. A directory sitting where the second
    /// file needs to be a file is the fault: `write_atomic`'s rename onto it
    /// fails on every platform this runs on, unlike a permission bit.
    #[test]
    fn a_write_failure_rolls_the_earlier_files_back() {
        let dir = temp_dir("commit-write-fails");
        let first = dir.join("first.txt");
        let second = dir.join("second.txt");
        std::fs::write(&first, "original first").unwrap();
        std::fs::create_dir(&second).unwrap(); // the fault

        let writes = vec![
            PlannedWrite::write(
                first.clone(),
                "new first".into(),
                Some(b"original first".to_vec()),
            ),
            PlannedWrite::write(second.clone(), "new second".into(), None),
        ];
        let err = commit(&writes).unwrap_err();
        let msg = err.message();
        assert!(msg.contains("could not be written"), "{msg}");
        assert!(msg.contains("put every file it"), "{msg}");
        assert_eq!(std::fs::read_to_string(&first).unwrap(), "original first");
        std::fs::remove_dir_all(&dir).ok();
    }

    #[test]
    fn a_verification_failure_rolls_every_file_back() {
        let dir = temp_dir("commit-verify-fails");
        let first = dir.join("first.txt");
        let second = dir.join("second.txt");
        std::fs::write(&first, "original first").unwrap();

        // `commit` only ever writes `content` itself, so the only way to
        // reach the verification path is a write whose declared content
        // does not match what actually lands on disk -- the shape of a
        // `preserved` check failing.
        let writes = vec![
            PlannedWrite::write(
                first.clone(),
                "new first".into(),
                Some(b"original first".to_vec()),
            ),
            PlannedWrite {
                path: second.clone(),
                action: Action::Write("new second".into()),
                original: None,
                preserved: Some(Box::new(|_| false)),
            },
        ];
        let err = commit(&writes).unwrap_err();
        assert!(err.message().contains("did not read back as written"));
        assert_eq!(std::fs::read_to_string(&first).unwrap(), "original first");
        assert!(
            !second.exists(),
            "a file with no original should be removed"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// Point A's other half: `--undo` deleting a file is part of the same
    /// transaction, and a delete that cannot complete rolls a write next to
    /// it back too.
    #[test]
    fn a_failed_delete_rolls_a_sibling_write_back() {
        let dir = temp_dir("commit-delete-fails");
        let written = dir.join("written.txt");
        let undone = dir.join("undone.txt");
        std::fs::write(&written, "original written").unwrap();
        std::fs::create_dir(&undone).unwrap(); // remove_file fails on a directory

        let writes = vec![
            PlannedWrite::write(
                written.clone(),
                "new written".into(),
                Some(b"original written".to_vec()),
            ),
            PlannedWrite::delete(undone.clone(), b"{}".to_vec()),
        ];
        let err = commit(&writes).unwrap_err();
        assert!(
            err.message().contains("could not be written")
                || err.message().contains("Input/output")
        );
        assert_eq!(
            std::fs::read_to_string(&written).unwrap(),
            "original written"
        );
        std::fs::remove_dir_all(&dir).ok();
    }

    /// When rollback itself cannot put a file back, the failure says so and
    /// names it, instead of a false "put back as it was".
    #[test]
    fn an_unrestorable_file_is_named_rather_than_claimed_fixed() {
        let dir = temp_dir("commit-unrestorable");
        let first = dir.join("first.txt");
        let second = dir.join("second.txt");
        std::fs::write(&second, "second").unwrap();
        // `first`'s rollback target cannot be written to at all: a
        // directory sits where the restored file would need to be.
        std::fs::create_dir(&first).unwrap();

        let writes = vec![
            PlannedWrite::write(
                first.clone(),
                "new first".into(),
                Some(b"original first".to_vec()),
            ),
            PlannedWrite::write(
                second.clone(),
                "new second".into(),
                Some(b"second".to_vec()),
            ),
        ];
        let unrestored = rollback(&writes);
        assert_eq!(unrestored, vec![first.clone()]);

        let msg = failure_with_rollback("something failed".to_string(), &unrestored).message();
        assert!(
            msg.contains("could not put these back as they were"),
            "{msg}"
        );
        assert!(msg.contains(&first.display().to_string()), "{msg}");
        assert!(msg.contains("version control"), "{msg}");
        std::fs::remove_dir_all(&dir).ok();
    }
}