silcrow 0.2.1

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
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
use anyhow::{Context, Result};
use clap::{CommandFactory, Parser, Subcommand};

mod accept;
mod cache;
mod check;
mod conflict;
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 out;
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.";

// § dfkjbzska.d@3hg4m
/// The version `--version` prints, with the hashing scheme of `scheme::PARTS` written as its
/// trailer, which a test holds equal, so `upgrade` can read the scheme of the binary it installed.
const VERSION: &str = concat!(
    env!("CARGO_PKG_VERSION"),
    ", hashing scheme 25 rust=26 js=26 python=26 yaml=26"
);
// § end dfkjbzska.d

#[derive(Parser)]
#[command(
    name = "silcrow",
    about = "Silcrow CLI",
    version = VERSION,
    disable_help_subcommand = true,
    after_help = HELP_AFTER
)]
struct Cli {
    /// Run as if started in this directory, as `git -C` does
    #[arg(short = 'C', value_name = "DIR", global = true)]
    dir: Option<std::path::PathBuf>,
    #[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@9znkg
        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@87zfz
#[derive(Parser)]
struct ListArgs {
    /// Show the metadata of each law
    #[arg(long)]
    long: bool,
    /// Print the register as JSON
    #[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 {
    /// Print the figures as JSON
    #[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,
    /// Print the review as JSON
    #[arg(long, conflicts_with = "md")]
    json: bool,
    /// Print the markdown review packet, to hand to a reviewing agent
    #[arg(long)]
    md: bool,
    /// Diff every project of the workspace
    #[arg(long)]
    all: bool,
}

#[derive(Parser)]
struct AcceptArgs {
    /// Laws or clauses to accept as they now stand, each `[projectpath:]id` or `[projectpath:]id.letter`.
    /// Several are re-pinned in one reading of the tree, and a failing one writes nothing
    #[arg(value_name = "ADDRESS", required_unless_present = "drifted")]
    addrs: Vec<String>,
    /// Every address with a drifted pin, a bare marker that drifted since HEAD included, each named
    /// as it is re-pinned. Read them in `diff` first
    #[arg(long, conflicts_with = "addrs")]
    drifted: bool,
    /// With `--drifted`, every project of the workspace
    #[arg(long, requires = "drifted")]
    all: bool,
    // § one xnsbksxv6.i@wb31z
    /// With `--drifted`, only the drifted pins in this file or whose pin reads it, through a
    /// followed body or the YAML keys above its span; repeatable
    #[arg(long, value_name = "FILE", requires = "drifted")]
    path: Vec<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@sxfbd
    /// 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, conflicts_with = "json")]
    verbose: bool,
    /// Print the findings as one JSON object, of the schema the README documents
    #[arg(long)]
    json: bool,
    /// Keep only the findings in this file; repeatable. Others are neither printed, counted nor failed on
    #[arg(long, value_name = "FILE")]
    path: Vec<String>,
    /// Write the review packet of a comparing check to this file, empty when it holds none,
    /// for a forge with no job summary, such as a GitLab artifact
    #[arg(long, value_name = "FILE")]
    review_out: Option<std::path::PathBuf>,
}

#[derive(Parser)]
struct FixArgs {
    // § jed5hb8sa.a@q3new
    /// 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.1) 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 laws or clauses as they now stand: remint a law whose sentence moved, re-pin their 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();
    start_in(cli.dir.as_deref())?;
    // § smn8drkh4.c@6fpw2
    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@9t3cq
    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)?;
    cache::open(&ws.root);
    let near = ws.enclosing(&cwd);
    // § fcknw57x1@33p4r
    if matches!(
        cli.command,
        Some(Commands::Check(_) | Commands::Accept(_) | Commands::List(_) | Commands::Diff(_))
    ) {
        conflict::refuse(&ws, &std::collections::BTreeMap::new())?;
    }
    // § end fcknw57x1

    // § j3m715h92.d@pnsee
    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
    // `fix`, `accept` and a hook write through `write` alone, and a hook forgets its walks when
    // it writes the index out. `install`, `eject` and `squash` write or run git besides.
    let walks_once = !writes || matches!(cli.command, Some(Commands::Fix(_) | Commands::Accept(_)));
    if walks_once {
        walk::read_only_run();
    }

    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@d5cf0
        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@bqc9m
    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@aep37
    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@my94k
            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)?]
            };
            let filter = check_filter(&ws, &cwd, &args.path)?;
            run_check(
                &ws,
                &projects,
                args.base.as_deref(),
                args.all,
                CheckOutput {
                    verbose: args.verbose,
                    json: args.json,
                    filter,
                    review_out: args.review_out.as_ref().map(|path| cwd.join(path)),
                },
            )
        }
        Some(Commands::Fix(args)) => {
            // § egfcsmhyg.b@re4fg
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            // § fcknw57x1.c@sacae
            let resolved = conflict::resolve_digests(&ws, &projects, mode.is_dry())?;
            conflict::refuse(&ws, &resolved)?;
            // § end fcknw57x1.c
            // § egfcsmhyg.d@0g70j
            let mut failed = Vec::new();
            // Projects that rewrite no decision note read nothing another writes: they run
            // beside each other, and each prints in project order what it would have printed
            // alone.
            let independent = (args.all && !args.remint && projects.len() > 1)
                .then(|| {
                    let unscoped: Vec<_> = projects.iter().map(|p| (*p, None)).collect();
                    resolve::independent_plans(&ws, &unscoped)
                })
                .flatten();
            match independent {
                Some(plans) => {
                    let runs = par::map(
                        projects.iter().zip(plans).collect(),
                        |_| 1,
                        |(p, plan)| {
                            out::held(|| {
                                say!("[{}]", p.key);
                                resolve::run_planned(&ws, p, mode.is_dry(), plan)
                            })
                        },
                    );
                    for (project, (result, written)) in projects.iter().zip(runs) {
                        out::release(&written);
                        if let Err(e) = result {
                            failed.push(format!("[{}] {e:#}", project.key));
                        }
                    }
                }
                None => {
                    for project in projects {
                        if args.all {
                            println!("[{}]", project.key);
                        }
                        match resolve::run(&ws, project, mode.is_dry(), args.remint) {
                            Err(e) if args.all => failed.push(format!("[{}] {e:#}", project.key)),
                            result => result?,
                        }
                    }
                }
            }
            if !failed.is_empty() {
                anyhow::bail!(
                    "fix failed in {} project(s), and fixed every other:\n{}",
                    failed.len(),
                    failed.join("\n")
                );
            }
            // § end egfcsmhyg.d
            Ok(())
        }
        Some(Commands::Squash(_)) => squash::run(&ws, &ws.require(&cwd)?.dir, mode.is_dry()),
        Some(Commands::Eject(args)) => {
            // § qeka6zh48.a@587fj
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            eject::run(&ws, &projects, mode.is_dry())
        }
        Some(Commands::Accept(args)) if args.drifted => {
            // § xnsbksxv6.h@axy2k
            let projects = if args.all {
                ws.local()
            } else {
                vec![ws.require(&cwd)?]
            };
            // § end xnsbksxv6.h
            // § xnsbksxv6.i@k9byn
            let filter = check_filter(&ws, &cwd, &args.path)?;
            let paths = filter.as_ref().map_or(&[][..], |f| f.paths.as_slice());
            let label = filter.as_ref().map(|f| f.label.as_str());
            accept::run_drifted(&ws, &projects, paths, label, mode.is_dry())
            // § end xnsbksxv6.i
        }
        Some(Commands::Accept(args)) => {
            accept::run(&ws, ws.require(&cwd)?, &args.addrs, 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);
    cache::flush();
    result
}

/// How `check` prints its report.
struct CheckOutput {
    verbose: bool,
    json: bool,
    filter: Option<check::Filter>,
    /// The file `--review-out` names, read from the working directory.
    review_out: Option<std::path::PathBuf>,
}

/// The filter `--path` names, each path read from `cwd`.
fn check_filter(
    ws: &workspace::Workspace,
    cwd: &std::path::Path,
    paths: &[String],
) -> Result<Option<check::Filter>> {
    // § awnw08yp4.a@gmxa5
    if paths.is_empty() {
        return Ok(None);
    }
    let mut label = Vec::new();
    let mut kept = Vec::new();
    for arg in paths {
        let path = check::normalize(&cwd.join(arg));
        if !path.starts_with(&ws.root) {
            anyhow::bail!(
                "`--path {arg}` names a path outside the workspace `{}`",
                ws.root.display()
            );
        }
        if !path.is_file() {
            anyhow::bail!("`--path {arg}` names no file");
        }
        let read = match path.parent().and_then(|dir| ws.enclosing(dir)) {
            Some(project) => {
                project.dir.join("AGENTS.md") == path
                    || walk::code_files(&project.dir)?.contains(&path)
                    || walk::decision_files(&project.dir)?.contains(&path)
            }
            None => false,
        };
        if !read {
            anyhow::bail!(
                "`--path {arg}` names a file no project reads: neither code, a decision note nor an `AGENTS.md`, so no finding is about it"
            );
        }
        label.push(format!("--path {arg}"));
        kept.push(path);
    }
    Ok(Some(check::Filter {
        paths: kept,
        label: label.join(" "),
    }))
}

/// Makes `dir`, which `-C` names, the working directory every verb starts from.
fn start_in(dir: Option<&std::path::Path>) -> Result<()> {
    // § xn501ngys@m5geg
    let Some(dir) = dir else {
        return Ok(());
    };
    // § xn501ngys.a@deg39
    std::env::set_current_dir(dir)
        .with_context(|| format!("-C {}: no directory to run in", dir.display()))
    // § end xn501ngys.a
}

fn run_check(
    ws: &workspace::Workspace,
    projects: &[&workspace::ProjectRef],
    base: Option<&str>,
    prefix: bool,
    output: CheckOutput,
) -> Result<()> {
    // § f46qcnawn.a@7646m
    let point = check_point(ws, base, output.json)?;
    // § j44p1s9z8.f@jfav5
    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)?;
    // § dfkjbzska.b@x3qvp
    let recorded = hook::recorded_scheme_at(&ws.root, "HEAD")?;
    let several = ws.local().len() > 1;
    let steps = match recorded {
        None if report.drifts.len() > report.held && check::has_history(&ws.root) => {
            Some(check::unrecorded_scheme_steps(several))
        }
        recorded => check::scheme_steps(recorded.as_ref(), &scheme::Scheme::binary(), several),
    };
    if let Some(steps) = steps {
        match output.json {
            true => eprint!("{steps}"),
            false => print!("{steps}"),
        }
    }
    // § end dfkjbzska.b
    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@yacb4
        let (packet, holds, shared) = diff::packet(ws, projects, base)?;
        let review = holds || !report.named.is_empty();
        let packet = match (review, report.named.is_empty()) {
            (false, _) => String::new(),
            (true, true) => format!("{shared}{packet}"),
            (true, false) => format!("{}{shared}{packet}", check::named_summary(&report.named)),
        };
        if let Some(out) = &output.review_out {
            // § j44p1s9z8.ka@dy661
            std::fs::write(out, &packet).with_context(|| {
                format!(
                    "cannot write the review packet to `{}`, the file --review-out names",
                    out.display()
                )
            })?;
        }
        if review {
            // § gbcb9abtz.b@8902m
            match output.json {
                true => eprint!("{packet}"),
                false => print!("{packet}"),
            }
            // § end gbcb9abtz.b
            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
    }
    // A path that names no project tag is read from the one project checked, or else from the
    // workspace root.
    let single = (!prefix).then(|| projects[0]);
    let untagged = single.map_or(ws.root.as_path(), |project| project.dir.as_path());
    let fork = check::fork_point(ws, point.as_deref());
    check::read_structure(ws, &fork, untagged, &mut report);
    if let Some(filter) = &output.filter {
        report.keep(filter, ws, untagged);
    }
    let label = output.filter.as_ref().map(|filter| filter.label.as_str());
    let owned = check::owned(ws, &fork, untagged, &report);
    // § j7vy53sbp.d@3s0y0
    let closed = match (output.json, point.is_some()) {
        (true, _) => check::print_json(
            &report,
            label,
            single.map(|project| project.key.as_str()),
            &owned,
        )?,
        (false, true) => {
            check::print_report(&report, output.verbose, label, false, &check::Owned::Off)
        }
        (false, false) => check::print_report(&report, output.verbose, label, false, &owned),
    };
    // § end j7vy53sbp.d
    if !closed {
        cache::flush();
        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>,
    json: bool,
) -> Result<Option<String>> {
    // § j44p1s9z8.h@j5376
    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@v1z9r
    let Some(target) = target else {
        let line = "CI names no merge target and no `--base` is given: this check compared nothing, and holds the tree to itself alone.";
        // § gbcb9abtz.b@63f39
        match json {
            true => eprintln!("{line}"),
            false => println!("{line}"),
        }
        // § end gbcb9abtz.b
        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 the_version_names_the_hashing_scheme_of_this_binary() {
        // § dfkjbzska.d@4bvqy
        assert!(
            VERSION.ends_with(&format!(", hashing scheme {}", scheme::Scheme::binary())),
            "{VERSION}"
        );
    }

    #[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,
            json: false,
            path: Vec::new(),
            review_out: None,
        })
        .writes());
        assert!(Commands::Fix(FixArgs {
            remint: false,
            all: false,
            flags: WriteFlags::default(),
        })
        .writes());
        assert!(Commands::Accept(AcceptArgs {
            addrs: vec!["abcdefgh1".into()],
            drifted: false,
            all: false,
            path: Vec::new(),
            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());
    }
}