silcrow 0.1.0

Deterministic CLI for a citable, checkable graph of laws in a git tree.
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
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};

mod accept;
mod check;
mod diff;
mod eject;
mod fallback;
mod follow;
mod graph;
mod harness;
mod hash;
mod hook;
mod list;
mod list_path;
mod list_tty;
mod log;
mod marker;
mod merge;
mod meta;
mod model;
#[cfg(test)]
mod note_gen;
mod notice;
mod par;
mod parse;
mod plane;
mod policy;
mod published;
mod remove;
mod resolve;
mod scheme;
mod skill;
mod span;
mod span_lang;
mod squash;
mod stats;
mod stats_history;
mod upgrade;
mod walk;
mod workspace;
mod write;

const HELP_AFTER: &str = "\
`agent` is the live index of what an agent can do. A topic prints that protocol. \
`install` writes the skill pointer, the `AGENTS.md` block and the hooks in this repo, the pointer at `.agents/skills/silcrow/SKILL.md`, \
and `install --dry-run` reports each one that differs from this binary.";

#[derive(Parser)]
#[command(
    name = "silcrow",
    about = "Silcrow CLI",
    version = env!("CARGO_PKG_VERSION"),
    disable_help_subcommand = true,
    after_help = HELP_AFTER
)]
struct Cli {
    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(clap::Args, Clone, Copy, Default)]
struct WriteFlags {
    // § j3m715h92.b@yxq14
    /// Simulate every write and change nothing (default in a development build)
    #[arg(long, conflicts_with = "write")]
    dry_run: bool,

    /// Perform writes (default in a release build)
    #[arg(long)]
    write: bool,
}

#[derive(Copy, Clone, PartialEq, Eq, Debug)]
enum WriteMode {
    Dry,
    Write,
}

impl WriteMode {
    fn resolve(dry_run: bool, write: bool, dev_build: bool) -> Self {
        // § j3m715h92.c@t7ftf
        match (dry_run, write) {
            (true, _) => Self::Dry,
            (_, true) => Self::Write,
            _ if dev_build => Self::Dry,
            _ => Self::Write,
        }
    }

    fn label(self) -> &'static str {
        match self {
            Self::Dry => "dry-run: nothing will be written",
            Self::Write => "write: the tree will be modified",
        }
    }

    fn is_dry(self) -> bool {
        matches!(self, Self::Dry)
    }
}

fn dev_build() -> bool {
    // § j3m715h92.a@0bsa6
    cfg!(debug_assertions)
}

// § j3m715h92.e@jrh55
#[derive(Parser)]
struct ListArgs {
    /// Show the metadata of each law
    #[arg(long)]
    long: bool,
    /// Force JSON on a TTY
    #[arg(long)]
    json: bool,
    /// Every project of the workspace, each law tagged with its project path
    #[arg(long, conflicts_with = "id")]
    all: bool,
    /// Law id whose metadata to print
    #[arg(value_name = "ID")]
    id: Option<String>,
    /// Only the laws and clauses whose pins read this file or line, `<file>[:<line>]`; repeatable
    #[arg(long, value_name = "FILE[:LINE]", conflicts_with_all = ["id", "all", "long"])]
    path: Vec<String>,
}

#[derive(Parser)]
struct StatsArgs {
    /// Force JSON on a TTY
    #[arg(long)]
    json: bool,
    /// Measure the history: re-pins by cause, weekly totals and marker overhead
    #[arg(long)]
    history: bool,
    /// Revision or range git reads (default: the history of the default branch)
    #[arg(value_name = "RANGE", requires = "history")]
    range: Option<String>,
    /// Read only the commits after this date, as `git log --since` reads it
    #[arg(long, value_name = "DATE", requires = "history")]
    since: Option<String>,
}

#[derive(Parser)]
struct DiffArgs {
    // § one cme63msgx.a@cbhzy
    /// Revisions as `git diff` takes them: none for the published tree against the worktree,
    /// `<rev>` against the worktree, `<a> <b>` or `<a>..<b>`, or `<a>...<b>` from their merge-base
    #[arg(value_name = "REV", num_args = 0..=2)]
    revs: Vec<String>,
    // § one cme63msgx.d@9s888
    /// Keep only this law or clause, `[projectpath:]id[.letter]`; repeatable
    #[arg(long = "law", value_name = "ADDRESS")]
    laws: Vec<String>,
    /// Show hash scheme remint detail
    #[arg(long)]
    verbose: bool,
    /// Force JSON on a TTY
    #[arg(long, conflicts_with = "md")]
    json: bool,
    /// Print the markdown review packet, piped or not, to hand to a reviewing agent
    #[arg(long)]
    md: bool,
    /// Diff every project of the workspace
    #[arg(long)]
    all: bool,
}

#[derive(Parser)]
struct AcceptArgs {
    /// Law or clause to accept as it now stands: `[projectpath:]id` or `[projectpath:]id.letter`
    #[arg(value_name = "ADDRESS")]
    addr: String,
    #[command(flatten)]
    flags: WriteFlags,
}

#[derive(Parser)]
struct LogArgs {
    /// Law id to trace
    #[arg(value_name = "ID")]
    id: String,
    /// Show hash scheme remint steps and each re-pin commit
    #[arg(long)]
    verbose: bool,
}

#[derive(Parser)]
struct HookArgs {
    /// Git hook event name
    #[arg(value_name = "EVENT")]
    event: String,
    /// Arguments passed by git
    #[arg(trailing_var_arg = true, allow_hyphen_values = true)]
    rest: Vec<String>,
}

#[derive(Parser)]
struct CheckArgs {
    // § f46qcnawn@v2xj4
    /// Revision to compare against, naming each change a person must see before the merge
    /// (default: under `CI`, the merge-base of the merge target the forge names)
    #[arg(long)]
    base: Option<String>,
    /// Check every project of the workspace in one report
    #[arg(long)]
    all: bool,
    /// Also print the scan count, every resolved reference, and every absent optional marker
    #[arg(long)]
    verbose: bool,
}

#[derive(Parser)]
struct FixArgs {
    // § jed5hb8sa.a@fbfek
    /// After a hashing scheme change, remint the pin digests that held at `HEAD`, or with no
    /// scheme change recorded, every law id that does not hash its sentence
    #[arg(long)]
    remint: bool,
    /// Fix every project of the workspace
    #[arg(long)]
    all: bool,
    #[command(flatten)]
    flags: WriteFlags,
}

#[derive(Parser)]
struct SquashArgs {
    #[command(flatten)]
    flags: WriteFlags,
}

#[derive(Parser)]
struct InstallArgs {
    #[command(flatten)]
    flags: WriteFlags,
}

#[derive(Parser)]
struct EjectArgs {
    /// Eject every project of the workspace
    #[arg(long)]
    all: bool,
    #[command(flatten)]
    flags: WriteFlags,
}

#[derive(Parser)]
struct UpgradeArgs {
    /// Install this version (e.g. 0.2.0) instead of the latest
    #[arg(long, value_name = "VERSION")]
    version: Option<String>,
    /// Skip the confirm
    #[arg(short, long)]
    yes: bool,
}

#[derive(Parser)]
struct AgentArgs {
    /// Topic from the index (`explore`, `code`, `author`, `adopt`, `review`, ...)
    #[arg(value_name = "TOPIC")]
    topic: Option<String>,
}
// § end j3m715h92.e

#[derive(Subcommand)]
enum Commands {
    // § smn8drkh4@2vdgg
    /// Active register of laws. TTY pages text. Non-TTY is JSON.
    List(ListArgs),
    /// Review of a change law by law, then what no law governs
    Diff(DiffArgs),
    /// Validate the graph. Never writes.
    Check(CheckArgs),
    /// Mint ids, rewrite pointers and links, pin bare markers
    Fix(FixArgs),
    // § one n5tk6t1rx@z1xjf
    /// Give the branch squash-merge semantics: drop what was born and struck on it
    Squash(SquashArgs),
    /// Accept a law or a clause as it now stands: remint a law whose sentence moved, re-pin its markers
    Accept(AcceptArgs),
    /// Print a law's genealogy from git log -S
    Log(LogArgs),
    /// Size of the law set and of what its pins read, or with --history how its pins moved. TTY prints a table. Non-TTY is JSON.
    Stats(StatsArgs),
    /// Index of what an agent can do. A topic prints that protocol.
    Agent(AgentArgs),
    /// Write the skill pointer, the `AGENTS.md` block, and the git hooks in this repo
    Install(InstallArgs),
    /// Remove Silcrow: markers, note grammar, the block, the skill pointer, and the hooks
    Eject(EjectArgs),
    /// Replace this binary with the latest GitHub release
    Upgrade(UpgradeArgs),
    /// Git hook entry point (written by `silcrow install`)
    #[command(hide = true)]
    Hook(HookArgs),
    /// Show available commands
    Help,
}

impl Commands {
    fn writes(&self) -> bool {
        // § smn8drkh4.a@345tk
        matches!(
            self,
            Commands::Fix(_)
                | Commands::Accept(_)
                | Commands::Squash(_)
                | Commands::Install(_)
                | Commands::Eject(_)
        )
    }

    /// The `--dry-run` and `--write` of a verb that writes, its own binary for `upgrade`.
    fn write_flags(&self) -> Option<WriteFlags> {
        // § j3m715h92.e@w4krz
        match self {
            Commands::Fix(FixArgs { flags, .. })
            | Commands::Accept(AcceptArgs { flags, .. })
            | Commands::Squash(SquashArgs { flags })
            | Commands::Install(InstallArgs { flags })
            | Commands::Eject(EjectArgs { flags, .. }) => Some(*flags),
            _ => None,
        }
    }
}

fn main() -> Result<()> {
    exit_quietly_on_a_closed_stdout();
    std::thread::Builder::new()
        .stack_size(par::STACK)
        .spawn(run)?
        .join()
        .unwrap_or_else(|panic| std::panic::resume_unwind(panic))
}

/// `silcrow log <id> | head -1` closes stdout early, and `println!` panics on the broken pipe.
/// Exit as a process killed by `SIGPIPE` does, with no message, rather than report a crash.
fn exit_quietly_on_a_closed_stdout() {
    let report = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        let payload = info.payload();
        let message = payload
            .downcast_ref::<String>()
            .map(String::as_str)
            .or_else(|| payload.downcast_ref::<&str>().copied())
            .unwrap_or_default();
        // `EPIPE` is 32 on Linux and macOS, and the panic message ends with the error it got.
        let broken_pipe = std::io::Error::from_raw_os_error(32).to_string();
        if message.starts_with("failed printing to stdout") && message.ends_with(&broken_pipe) {
            std::process::exit(141);
        }
        report(info);
    }));
}

fn run() -> Result<()> {
    let cli = Cli::parse();
    // § smn8drkh4.c@gf0kv
    if cli.command.is_none() {
        Cli::command().print_help()?;
        println!();
        return Ok(());
    }
    // § end smn8drkh4.c
    let flags = cli.command.as_ref().and_then(Commands::write_flags);
    let flags = flags.unwrap_or_default();
    let mode = WriteMode::resolve(flags.dry_run, flags.write, dev_build());
    // § g24nqa18j.b@amb91
    if let Some(Commands::Upgrade(args)) = &cli.command {
        return upgrade::self_upgrade(args.version.as_deref(), args.yes, dev_build());
    }
    // § end g24nqa18j.b
    let cwd = std::env::current_dir()?;
    let ws = workspace::Workspace::discover(&cwd)?;
    let near = ws.enclosing(&cwd);

    // § j3m715h92.d@5m5kx
    let writes = cli.command.as_ref().is_some_and(Commands::writes);
    if dev_build() && writes && !matches!(cli.command, Some(Commands::Hook(_))) {
        eprintln!("silcrow: {}", mode.label());
    }
    // § end j3m715h92.d

    let acts_on_project = matches!(
        cli.command,
        None | Some(
            Commands::List(_)
                | Commands::Diff(_)
                | Commands::Check(_)
                | Commands::Fix(_)
                | Commands::Squash(_)
                | Commands::Accept(_)
                | Commands::Log(_)
                | Commands::Stats(_)
                | Commands::Eject(_)
        )
    );
    if acts_on_project && ws.projects.is_empty() {
        // § egfcsmhyg.c@6wba3
        if !ws.root.join(".git").exists() {
            anyhow::bail!(
                "Silcrow is not installed here: no `AGENTS.md` carries a Silcrow block, and this folder is in no git repository, where `silcrow install` writes. Run `git init`, then `silcrow install`."
            );
        }
        anyhow::bail!(
            "Silcrow is not installed here: no `AGENTS.md` carries a Silcrow block. Run `silcrow install`."
        );
    }

    // § fgbh1bkcj.c@q8g1x
    let is_check = matches!(cli.command, Some(Commands::Check(_)));
    let probe_quiet = matches!(
        cli.command,
        Some(Commands::Hook(_) | Commands::Install(_) | Commands::Eject(_))
    );
    if !is_check && !probe_quiet {
        harness::report_drift(&ws.root, near.map(|project| project.dir.as_path()))?;
    }
    // § end fgbh1bkcj.c

    // § nfzrg1qsg.b@g4tzz
    let notice = notice::begin_release_check(
        !dev_build() && !matches!(cli.command, Some(Commands::Hook(_))),
    );
    // § end nfzrg1qsg.b
    let result = match cli.command {
        Some(Commands::List(args)) if !args.path.is_empty() => {
            list_path::run(&ws, ws.require(&cwd)?, &cwd, &args.path, args.json)
        }
        Some(Commands::List(args)) => {
            // § egfcsmhyg.a@jdms9
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            list::run(&projects, args.all, args.long, args.json, args.id)
        }
        Some(Commands::Diff(args)) => {
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            let rev = diff::revision(&args.revs)?;
            diff::refuse_unresolved(&ws.root, rev.as_deref())?;
            let end = diff::range_end(rev.as_deref());
            let mut held = Vec::new();
            for project in projects {
                let at_end = match &end {
                    Some(rev) => name_broken_graph_at(&ws, project, rev)?,
                    None => name_broken_graph(&ws, project).map(|()| true)?,
                };
                match at_end {
                    true => held.push(project),
                    // A project the right end of the range does not hold has nothing to compare.
                    false if args.all => {}
                    false => anyhow::bail!(
                        "`{}` holds no project `{}`",
                        end.as_deref().unwrap_or_default(),
                        project.key
                    ),
                }
            }
            let projects = held;
            let laws: Vec<String> = args.laws.iter().map(|law| law.to_lowercase()).collect();
            diff::run(
                &ws,
                &projects,
                args.all,
                rev,
                &laws,
                args.verbose,
                diff::Form::chosen(args.json, args.md),
            )
        }
        Some(Commands::Agent(args)) => skill::print(args.topic.as_deref()),
        Some(Commands::Install(_)) => plane::install(mode.is_dry()),
        Some(Commands::Help) => {
            Cli::command().print_help()?;
            println!();
            Ok(())
        }
        Some(Commands::Check(args)) => {
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            run_check(&ws, &projects, args.base.as_deref(), args.all, args.verbose)
        }
        Some(Commands::Fix(args)) => {
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            // § egfcsmhyg.b@0129a
            for project in projects {
                if args.all {
                    println!("[{}]", project.key);
                }
                resolve::run(&ws, project, mode.is_dry(), args.remint)?;
            }
            Ok(())
        }
        Some(Commands::Squash(_)) => squash::run(&ws, &ws.require(&cwd)?.dir, mode.is_dry()),
        Some(Commands::Eject(args)) => {
            // § qeka6zh48.a@71bvq
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            eject::run(&ws, &projects, mode.is_dry())
        }
        Some(Commands::Accept(args)) => {
            accept::run(&ws, ws.require(&cwd)?, &args.addr, mode.is_dry())
        }
        Some(Commands::Log(args)) => {
            let project = ws.require(&cwd)?;
            require_closed_graph(&ws, project)?;
            log::run(&project.dir, &args.id, args.verbose)
        }
        Some(Commands::Stats(args)) if args.history => stats_history::run(
            &ws.require(&cwd)?.dir,
            args.range.as_deref(),
            args.since.as_deref(),
            args.json,
        ),
        Some(Commands::Stats(args)) => stats::run(&ws, ws.require(&cwd)?, args.json),
        Some(Commands::Hook(args)) => hook::run(&ws, &args.event, &args.rest),
        Some(Commands::Upgrade(_)) => unreachable!("upgrade returns before the tree is read"),
        None => unreachable!("no verb prints the help before the tree is read"),
    };
    notice::print_release_notice(notice);
    result
}

fn run_check(
    ws: &workspace::Workspace,
    projects: &[&workspace::ProjectRef],
    base: Option<&str>,
    prefix: bool,
    verbose: bool,
) -> Result<()> {
    // § f46qcnawn.a@smj6w
    let point = check_point(ws, base)?;
    // § j44p1s9z8.f@3v1dz
    let every = ws.local();
    let (projects, prefix) = match point {
        Some(_) => (every.as_slice(), true),
        None => (projects, prefix),
    };
    // § end j44p1s9z8.f
    let mut report = check::validate(ws, projects, prefix)?;
    if prefix {
        report.errors.extend(hook::stray_markers(ws)?);
    }
    if let Some(base) = point {
        report.named = check::accepted_pins(ws, projects, &base, prefix)?;
        report
            .errors
            .extend(check::returned_tokens(projects, &base, prefix)?);
        // § j44p1s9z8.k@pez7s
        let (packet, holds) = diff::packet(ws, projects, &base)?;
        if holds || !report.named.is_empty() {
            let packet = match report.named.is_empty() {
                true => packet,
                false => format!("{}{packet}", check::named_summary(&report.named)),
            };
            print!("{packet}");
            if let Some(path) = std::env::var_os("GITHUB_STEP_SUMMARY").filter(|p| !p.is_empty()) {
                use std::io::Write;
                std::fs::OpenOptions::new()
                    .create(true)
                    .append(true)
                    .open(&path)
                    .and_then(|mut file| file.write_all(packet.as_bytes()))
                    .with_context(|| {
                        format!(
                            "cannot append the packet to `{}`, the file GITHUB_STEP_SUMMARY names",
                            path.to_string_lossy()
                        )
                    })?;
            }
        }
        // § end j44p1s9z8.k
    }
    if !check::print_report(&report, verbose) {
        std::process::exit(1);
    }
    Ok(())
}

/// The revision a `check` compares against: the one `--base` names, else under `CI` the
/// merge-base of the merge target the forge names, else none.
fn check_point(ws: &workspace::Workspace, base: Option<&str>) -> Result<Option<String>> {
    // § j44p1s9z8.h@3ja7n
    if let Some(base) = base {
        return Ok(Some(base.to_string()));
    }
    if !notice::ci_job(std::env::var("CI").ok().as_deref()) {
        return Ok(None);
    }
    let target = published::merge_target(|var| std::env::var(var).ok());
    // § end j44p1s9z8.h
    // § j44p1s9z8.i@j80wm
    let Some(target) = target else {
        println!(
            "CI names no merge target and no `--base` is given: this check compared nothing, and holds the tree to itself alone."
        );
        return Ok(None);
    };
    // § end j44p1s9z8.i
    published::merge_point(&ws.root, &target).map(Some)
}

/// `log` reads the graph as check leaves it, so it refuses a broken one, a drifted pin
/// included. A drifted harness is not the graph: the probe already reported it on stderr.
fn require_closed_graph(ws: &workspace::Workspace, project: &workspace::ProjectRef) -> Result<()> {
    // § j38jtk0t2.a@kbpbd
    let report = check::validate(ws, &[project], false)?;
    let blocking = report.errors.len() + report.drifts.len();
    if blocking > 0 {
        anyhow::bail!(
            "the graph is broken ({blocking} error(s)). Run `silcrow check` and fix it first."
        );
    }
    Ok(())
}

/// Each error of the graph `diff` reviews, on stderr before the review, which still shows every
/// law it can read. A drifted pin is what the review exists to show, so it is none.
fn name_broken_graph(ws: &workspace::Workspace, project: &workspace::ProjectRef) -> Result<()> {
    // § j38jtk0t2@jztn8
    let report = check::validate(ws, &[project], false)?;
    print_graph_errors(&report.errors, None);
    Ok(())
}

/// A range never reads the worktree, so `diff` names the errors of the graph its right end
/// commits.
fn name_broken_graph_at(
    ws: &workspace::Workspace,
    project: &workspace::ProjectRef,
    rev: &str,
) -> Result<bool> {
    // § j38jtk0t2.b@h912s
    let tree = tempfile::tempdir()?;
    published::write_tree(&ws.root, rev, tree.path())?;
    let at = workspace::Workspace::at(tree.path().to_path_buf())?;
    let Some(held) = at.get(&project.key) else {
        return Ok(false);
    };
    let report = check::validate(&at, &[held], false)?;
    print_graph_errors(&report.errors, Some(rev));
    Ok(true)
}

fn print_graph_errors(errors: &[String], rev: Option<&str>) {
    // § j38jtk0t2@8dmm0
    if errors.is_empty() {
        return;
    }
    let at = rev.map_or(String::new(), |rev| format!(" at `{rev}`"));
    eprintln!(
        "silcrow: the graph{at} is broken ({} error(s)), so the review leaves out what they keep it from reading. Run `silcrow check` to fix them:",
        errors.len()
    );
    for err in errors {
        eprintln!("  ERR {err}");
    }
}

/// A `git` command that reads no global or system config, so a test commits unsigned, with no
/// template and no hooks path of the machine it runs on.
#[cfg(test)]
pub(crate) fn test_git() -> std::process::Command {
    let mut cmd = std::process::Command::new("git");
    cmd.env("GIT_CONFIG_GLOBAL", "/dev/null")
        .env("GIT_CONFIG_NOSYSTEM", "1");
    cmd
}

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

    #[test]
    fn dev_build_defaults_to_dry_run() {
        assert_eq!(WriteMode::resolve(false, false, true), WriteMode::Dry);
        assert_eq!(WriteMode::resolve(false, false, false), WriteMode::Write);
    }

    #[test]
    fn explicit_flag_beats_the_build_default() {
        assert_eq!(WriteMode::resolve(false, true, true), WriteMode::Write);
        assert_eq!(WriteMode::resolve(true, false, false), WriteMode::Dry);
    }

    #[test]
    fn only_the_mutating_verbs_write() {
        assert!(!Commands::Check(CheckArgs {
            base: None,
            all: false,
            verbose: false,
        })
        .writes());
        assert!(Commands::Fix(FixArgs {
            remint: false,
            all: false,
            flags: WriteFlags::default(),
        })
        .writes());
        assert!(Commands::Accept(AcceptArgs {
            addr: "abcdefgh1".into(),
            flags: WriteFlags::default(),
        })
        .writes());
        assert!(Commands::Squash(SquashArgs {
            flags: WriteFlags::default()
        })
        .writes());
        assert!(!Commands::Log(LogArgs {
            id: "abcdefgh1".into(),
            verbose: false,
        })
        .writes());
        assert!(!Commands::Agent(AgentArgs { topic: None }).writes());
        assert!(!Commands::Stats(StatsArgs {
            json: false,
            history: true,
            range: None,
            since: None,
        })
        .writes());
        assert!(Commands::Install(InstallArgs {
            flags: WriteFlags::default()
        })
        .writes());
        assert!(Commands::Eject(EjectArgs {
            all: false,
            flags: WriteFlags::default(),
        })
        .writes());
        assert!(!Commands::Upgrade(UpgradeArgs {
            version: None,
            yes: false,
        })
        .writes());
    }
}