use greenbelay_guard::activity;
use greenbelay_guard::analysis;
use greenbelay_guard::assertions;
use greenbelay_guard::backtest;
use greenbelay_guard::civil;
use greenbelay_guard::compliance;
use greenbelay_guard::corpus;
use greenbelay_guard::decision;
use greenbelay_guard::doctor;
use greenbelay_guard::git;
use greenbelay_guard::graduate;
use greenbelay_guard::guidance;
use greenbelay_guard::harness_review;
use greenbelay_guard::migrate_plugin;
use greenbelay_guard::names::BIN;
use greenbelay_process::attestations;
use greenbelay_process::block_fingerprint;
use greenbelay_process::block_registry;
use greenbelay_process::content_id;
mod hook;
mod open;
mod plugin_install;
use greenbelay_guard::journal;
use greenbelay_guard::json;
use greenbelay_guard::lsp;
use greenbelay_guard::mine;
use greenbelay_guard::payload;
use greenbelay_guard::push_target;
#[cfg(unix)]
use greenbelay_guard::quiet;
use greenbelay_process::clear_boundary;
use greenbelay_process::code_review;
use greenbelay_process::impl_review_outcomes;
use greenbelay_process::implementation_review;
use greenbelay_process::implementation_review_rule;
use greenbelay_process::plan_apply;
use greenbelay_process::plan_phases;
use greenbelay_process::plan_review;
use greenbelay_process::plan_text;
use greenbelay_process::plans;
use greenbelay_process::preview;
use greenbelay_process::push_preview;
use greenbelay_process::review_brief;
use greenbelay_process::review_outcomes;
mod rule_table;
mod suppressions;
use greenbelay_guard::rules;
use greenbelay_guard::session_state;
use greenbelay_guard::settings;
use greenbelay_guard::shape;
use greenbelay_guard::shell;
use greenbelay_guard::shim;
use greenbelay_guard::stale;
use greenbelay_guard::stance;
use greenbelay_guard::transcript;
use greenbelay_guard::ui;
use greenbelay_process::board;
use greenbelay_process::shipped;
use std::ffi::OsString;
use std::path::PathBuf;
use std::process::ExitCode;
const USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" <command>
hook read a Claude Code payload on stdin, decide
install [--write] add the hook to settings.json (prints it by default), and
place and enable the clear-relay plugin
uninstall [--write] remove exactly what install added, the plugin included
migrate [--reverse] [--dry-run]
move this machine's state, git config keys and plugin
registration to the current names (or back); --dry-run
says what would change and writes nothing
status every rule, its stance, and what it has seen
doctor [--json] is the guard installed, runnable, and actually firing?
--json prints the findings and, apart from health, the
hook integration: present, absent, partial or unknown
corpus check replay every reviewed judgement through the rules
graduate <rule> --to advise|deny
demote <rule> back to observing, no questions asked
mine [flags] shapes the model got wrong that no rule names yet
output-audit --since <UTC> --until <UTC> [--json]
where tool output went in a window, by kind of call
backtest [flags] replay your transcripts through the rules
harness-review [--json] [--check] [--model <id>] [--out <dir>]
one row per rule and assertion: firings, compliance
per model, shadow-arm share, replay count; writes
<out dir>/<date>.json, --out defaulting to
<journal dir>/harness-review. --model is the model
the review is for (default: the model with the most
Bash calls in your transcripts, named in the output).
--check prints one line and exits 1 when that default
model is not the one the last review was made for
explain <rule> every match for one rule, for review
check '<command>' run the rules over one command, no stdin
[--dialect bash|zsh|unknown, default unknown]
[--cwd <dir>, default this directory] [--explain]
decide as the hook would in <dir>; --explain also
lists rules that matched but were not confirmed
analyze '<command>' the shell analysis of one command, as JSON — the
interface tools/shell-oracle compares against real
shells [--dialect, as for check]
rules [--json] every rule, its stance and its evidence; --json is
one array, the interface the homebrew tap reads
preview register --url <url> --guide <file.md> [--repo <dir>] [--open]
validate a localhost preview of HEAD for approval
and render its guide to a page
suppressions --staged judge the staged change: a lint suppression it adds
without a reason blocks (exit 1); the pre-commit gate
open <url|path> open a page for the person, through the opener in
`git config --global greenbelay.opener`
plan-sha [--short] [--block [--lang <l>]] [--legacy] [--] <file|->
the sha256 of a plan's canonical body, as reviewed
plan-panel <plan.md> the review agents a plan still needs, as the
plan-review-panel hook will judge it
plan-review record <plan.md> [--transcript <path>]
keep what each reviewer of a plan did, as outcome rows
plan-review stats [--json] [--model <id>]
per (role, model): reviews, findings, accepted ones;
marks a seat that is a retire-candidate
plan-review stats --time [--since <YYYY-MM-DD>] [--json]
per landed plan: time to done, blocked and person
hours, stops, word growth since round 1
implementation-review record <plan.md> --verdict <v>
keep the implementation review's findings (JSON on
stdin) as one outcome row
plan-apply [--dry-run|--check|--record-fallback] <plan.md>
apply the reviewers' Patches to a plan with no model
(accepted findings on stdin; exit 3 = some unmatched)
attestations [--apply]
what ~/.claude/greenbelay/attestations keeps and
why; --apply moves the rest to a 7-day trash
tree-sha [--block] [-C <dir>] [--] [<rev>]
the content id an implementation review and a
preview approval bind to: HEAD's tree without
docs/plans/ (not attest's canonical tree)
block sha [-C <dir>] [--base <ref>]
the fingerprint of the branch's change, as a copy of
a reviewed block is recognised by
rules-sha [-C <dir>] the sha256 of the code rules `aval` reports, as an
implementation-review brief binds them
review-brief [-C <dir>] [--plan <path>] [--base <ref>]
the implementation-review brief: tree and rules
lines, plan, diff, full code rules, decisions
shipped <plan.md> [--json]
what shipped under a plan, derived from git: per
repository its merge commits, PRs, releases, and
signed provenance
board [--repo <name>...] [--since <dur>] [--fetch] [--json]
the work in flight per repository (worktrees, live
unmerged branches, their active plan, the sessions
working there) and what landed recently, from git
and the session activity files
quiet [--max-bytes N[k]] -- <cmd…>
run a command with its output in a log file: one line
on a pass, the failure on a fail, the real exit code.
N is 1 to 48k bytes of excerpt (default 16k); exits
1 wrapper failure, 2 usage, 126 cannot execute,
127 not found, the command's own code, or
128+signal
install/uninstall flags:
--write actually edit the file
--reformat accept a normalised file when we cannot match its style
--project .claude/settings.json instead of ~/.claude
--local .claude/settings.local.json
backtest/explain/mine flags:
--transcripts <dir> where the .jsonl transcripts live
--since <YYYY-MM-DD> ignore entries before this day
--rule <id> restrict to one rule (repeatable)
--sample <n> sample matches to print per rule
--format cases emit matches as reviewable case lines (explain, mine)
--json machine-readable output
mine flags:
--window <n> tool calls a correction may arrive within (default 3)
--min-support <n> calls a shape needs before it is proposed (default 5)
--min-rate <0..1> share of them that must have gone wrong (default 0.3)
explain flags:
--rank novelty label the matches least like the ones already reviewed
--out <dir> explain clear-at-boundary --format cases: write the Stop
fixtures there (default: the checkout's
tests/corpus/stop/clear-at-boundary/); --sample <n>
keeps the n most recent Stops
--cases <file> explain clear-at-boundary --format cases: the .cases
file whose Stop lines are not printed again (default:
the checkout's tests/corpus/clear-at-boundary.cases)
backtest flags:
--compliance per model, per week: what the model did NEXT after a
rule fired — did the advice change anything?
"
);
enum Sub {
Hook,
Install,
Uninstall,
Status,
Doctor,
Corpus,
Graduate,
Demote,
Backtest,
HarnessReview,
Explain,
Mine,
OutputAudit,
Check,
Analyze,
Rules,
Preview,
PlanSha,
PlanPanel,
PlanReview,
ImplementationReview,
PlanApply,
TreeSha,
Block,
RulesSha,
ReviewBrief,
Attestations,
Quiet,
Shipped,
Board,
Open,
Suppressions,
Migrate,
}
const SUBCOMMANDS: [(&str, Sub); 33] = [
("hook", Sub::Hook),
("install", Sub::Install),
("uninstall", Sub::Uninstall),
("status", Sub::Status),
("doctor", Sub::Doctor),
("corpus", Sub::Corpus),
("graduate", Sub::Graduate),
("demote", Sub::Demote),
("backtest", Sub::Backtest),
("harness-review", Sub::HarnessReview),
("explain", Sub::Explain),
("mine", Sub::Mine),
("output-audit", Sub::OutputAudit),
("check", Sub::Check),
("analyze", Sub::Analyze),
("rules", Sub::Rules),
("preview", Sub::Preview),
("plan-sha", Sub::PlanSha),
("plan-panel", Sub::PlanPanel),
("plan-review", Sub::PlanReview),
("implementation-review", Sub::ImplementationReview),
("plan-apply", Sub::PlanApply),
("tree-sha", Sub::TreeSha),
("block", Sub::Block),
("rules-sha", Sub::RulesSha),
("review-brief", Sub::ReviewBrief),
("attestations", Sub::Attestations),
("quiet", Sub::Quiet),
("shipped", Sub::Shipped),
("board", Sub::Board),
("open", Sub::Open),
("suppressions", Sub::Suppressions),
("migrate", Sub::Migrate),
];
enum Invocation {
Sub { name: Sub, args: Vec<OsString> },
Help,
Version,
Usage(String),
}
fn parse(argv: Vec<OsString>) -> Invocation {
let Some(first) = argv.first() else {
return Invocation::Usage("no command given".into());
};
let head = first.to_string_lossy().into_owned();
if head == "--help" || head == "-h" || head == "help" {
return Invocation::Help;
}
if head == "--version" || head == "-V" {
return Invocation::Version;
}
for (name, sub) in SUBCOMMANDS {
if head == name {
return Invocation::Sub {
name: sub,
args: argv[1..].to_vec(),
};
}
}
if argv.iter().any(|a| a == "--help" || a == "-h") {
return Invocation::Help;
}
Invocation::Usage(format!("unknown command `{head}`"))
}
#[cfg(unix)]
fn die_on_sigpipe() {
extern "C" {
fn signal(signum: i32, handler: usize) -> usize;
}
const SIGPIPE: i32 = 13;
const SIG_DFL: usize = 0;
unsafe {
signal(SIGPIPE, SIG_DFL);
}
}
#[cfg(not(unix))]
fn die_on_sigpipe() {}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum MigrationMode {
Skip,
Zero,
Capped(std::time::Duration),
}
const MIGRATE_WAIT_CAP: std::time::Duration = std::time::Duration::from_secs(30);
const ENV_MIGRATE_WAIT_MS: &str = greenbelay_guard::env_var!("TEST_MIGRATE_WAIT_MS");
fn migration_mode(name: &Sub, args: &[OsString]) -> MigrationMode {
let reads_only = args.iter().any(|arg| {
arg == "--help"
|| arg == "-h"
|| arg == "--version"
|| arg == "--dry-run"
|| arg == "--check"
});
if matches!(name, Sub::Migrate | Sub::Doctor) || reads_only {
return MigrationMode::Skip;
}
match name {
Sub::Install => MigrationMode::Capped(
std::env::var(ENV_MIGRATE_WAIT_MS)
.ok()
.and_then(|text| text.parse().ok())
.map_or(MIGRATE_WAIT_CAP, std::time::Duration::from_millis),
),
_ => MigrationMode::Zero,
}
}
fn preflight_migration(name: &Sub, args: &[OsString]) -> Result<(), String> {
match migration_mode(name, args) {
MigrationMode::Skip => Ok(()),
MigrationMode::Zero => {
let failed = greenbelay_guard::migrate::preflight();
if failed && !matches!(name, Sub::Hook) {
eprintln!("{BIN}: migration failed (see {BIN} doctor); run {BIN} migrate");
}
Ok(())
}
MigrationMode::Capped(wait) => greenbelay_guard::migrate::settle(wait).map_err(|error| {
format!(
"{error}\nnothing was installed; fix what it names, then run `{BIN} install` again"
)
}),
}
}
struct MigrateRequest {
direction: greenbelay_guard::migrate::Direction,
dry_run: bool,
}
fn parse_migrate(args: &[OsString]) -> Result<MigrateRequest, ExitCode> {
use greenbelay_guard::migrate::Direction;
let mut request = MigrateRequest {
direction: Direction::Forward,
dry_run: false,
};
for arg in args {
match arg.to_string_lossy().as_ref() {
"--reverse" => request.direction = Direction::Reverse,
"--dry-run" => request.dry_run = true,
"--help" | "-h" => {
println!(concat!(
"usage: ",
greenbelay_guard::bin!(),
" migrate [--reverse] [--dry-run]"
));
println!();
println!("Move this machine's state directories, git config keys and plugin");
println!("registration to the current names; --reverse moves them back.");
println!(" --dry-run print what would change; write nothing, take no lock");
return Err(ExitCode::SUCCESS);
}
other => {
eprintln!("{BIN}: migrate takes --reverse and --dry-run, not {other}");
return Err(ExitCode::from(2));
}
}
}
Ok(request)
}
fn run_migrate(args: &[OsString]) -> ExitCode {
use greenbelay_guard::migrate::{self, MigrateError};
let request = match parse_migrate(args) {
Ok(request) => request,
Err(code) => return code,
};
let direction = request.direction;
let Some(env) = migrate::Env::from_process() else {
eprintln!("{BIN}: {}", MigrateError::NoHome);
return ExitCode::FAILURE;
};
if request.dry_run {
return match migrate::machine_plan(&env, direction) {
Ok(lines) => {
let registry = migrate_plugin::registry_state_after(&env, direction);
if lines.is_empty() {
match registry.report() {
None => println!("nothing to do: {}", already(direction)),
Some(_) => println!("nothing to move: {}", already(direction)),
}
}
let mut refused = false;
for line in lines {
match line {
migrate::PlanLine::Action(text) => println!("would: {text}"),
migrate::PlanLine::Refusal { step, reason } => {
refused = true;
println!("would refuse: {step}: {reason}");
}
}
}
print_registry(®istry, RegistryVoice::WouldThenNeed);
if refused {
eprintln!("migrate would stop: fix what is named above first");
return ExitCode::FAILURE;
}
ExitCode::SUCCESS
}
Err(error) => {
eprintln!("{BIN}: {error}");
ExitCode::FAILURE
}
};
}
let probe = greenbelay_guard::lock::lock_within(
&env.config_dir
.join(greenbelay_guard::names::MIGRATE_LOCK_FILE),
std::time::Duration::ZERO,
);
if matches!(probe, Ok(None)) {
eprintln!("{BIN}: waiting for another migration to finish");
}
drop(probe);
let outcome = migrate::machine_in(&env, direction, migrate::Wait::Capped(MIGRATE_WAIT_CAP));
let verdict = match settled_verdict(&env, direction, outcome) {
Ok(verdict) => verdict,
Err(code) => return code,
};
if let Err(error) = migrate_local_repository(&env, direction) {
eprintln!("{BIN}: {error}");
return ExitCode::FAILURE;
}
eprintln!("{verdict}");
print_registry(&migrate_plugin::registry_state(&env), RegistryVoice::Run);
ExitCode::SUCCESS
}
#[derive(Clone, Copy)]
enum RegistryVoice {
Run,
WouldThenNeed,
}
fn print_registry(state: &migrate_plugin::RegistryState, voice: RegistryVoice) {
use greenbelay_guard::ui::sanitize;
let Some(report) = state.report() else {
return;
};
let what = sanitize(&report.what);
if report.commands.is_empty() {
eprintln!("{what}");
if let Some(hint) = report.hint {
eprintln!(" {hint}");
}
return;
}
match voice {
RegistryVoice::Run => {
eprintln!("{what}; run:");
for command in &report.commands {
eprintln!(" {}", sanitize(command));
}
}
RegistryVoice::WouldThenNeed => {
eprintln!("{what}; you would then need to run:");
for command in &report.commands {
eprintln!("would then need: {}", sanitize(command));
}
}
}
}
fn already(direction: greenbelay_guard::migrate::Direction) -> &'static str {
match direction {
greenbelay_guard::migrate::Direction::Forward => "already migrated",
greenbelay_guard::migrate::Direction::Reverse => "already reversed",
}
}
fn settled_verdict(
env: &greenbelay_guard::migrate::Env,
direction: greenbelay_guard::migrate::Direction,
outcome: Result<greenbelay_guard::migrate::Outcome, greenbelay_guard::migrate::MigrateError>,
) -> Result<String, ExitCode> {
use greenbelay_guard::migrate::{self, Direction, MigrateError, Outcome};
match outcome {
Ok(Outcome::Migrated { steps, elapsed }) => {
for step in &steps {
eprintln!("{step}");
}
Ok(if steps.is_empty() {
"nothing to move".to_string()
} else {
format!(
"migrated {} steps in {:.1}s",
steps.len(),
elapsed.as_secs_f64()
)
})
}
Ok(Outcome::AlreadyDone) => Ok(format!("nothing to do: {}", already(Direction::Forward))),
Ok(Outcome::ReversedAlready) => {
Ok(format!("nothing to do: {}", already(Direction::Reverse)))
}
Ok(Outcome::Reversed) => Ok("reversed".to_string()),
Ok(Outcome::Busy) => {
eprintln!(
"{BIN}: another process holds the migration lock {}; retry when it finishes",
env.config_dir
.join(greenbelay_guard::names::MIGRATE_LOCK_FILE)
.display()
);
Err(ExitCode::FAILURE)
}
Ok(Outcome::FailedBefore) => {
let note = migrate::failure_note(env).unwrap_or_default();
eprintln!(
"{BIN}: an earlier migration failed: {}; run {BIN} migrate to try again",
note.trim().replace('\n', ": ")
);
Err(ExitCode::FAILURE)
}
Err(error) => {
eprintln!("{BIN}: {error}");
match (&error, direction) {
(MigrateError::Locked { .. } | MigrateError::Step { .. }, _) => {}
(_, Direction::Forward) => eprintln!(
"fix what it names, then run {BIN} migrate again (or \
run {BIN} migrate --reverse to put everything back)"
),
(_, Direction::Reverse) => {
eprintln!("fix what it names, then run {BIN} migrate --reverse again");
}
}
Err(ExitCode::FAILURE)
}
}
}
fn migrate_local_repository(
env: &greenbelay_guard::migrate::Env,
direction: greenbelay_guard::migrate::Direction,
) -> Result<(), String> {
let Ok(here) = std::env::current_dir() else {
return Ok(());
};
let inside = std::process::Command::new("git")
.current_dir(&here)
.args(["rev-parse", "--is-inside-work-tree"])
.output()
.is_ok_and(|output| output.status.success());
if !inside {
return Ok(());
}
greenbelay_guard::migrate_config::migrate_local(env, &here, direction)
.map(drop)
.map_err(|error| error.to_string())
}
fn main() -> ExitCode {
let hook_index = std::env::var_os("GIT_INDEX_FILE");
let index_handoff = suppressions::IndexHandoff::from_env();
for key in [
"GIT_DIR",
"GIT_WORK_TREE",
"GIT_INDEX_FILE",
"GIT_COMMON_DIR",
"GIT_PREFIX",
"GIT_OBJECT_DIRECTORY",
"GIT_ALTERNATE_OBJECT_DIRECTORIES",
"GIT_NAMESPACE",
"GIT_REFLOG_ACTION",
"GIT_EXEC_PATH",
] {
std::env::remove_var(key);
}
let invocation = parse(std::env::args_os().skip(1).collect());
if !matches!(
invocation,
Invocation::Sub {
name: Sub::Hook | Sub::Board | Sub::Suppressions | Sub::PlanReview,
..
}
) {
die_on_sigpipe();
}
if let Invocation::Sub { name, args } = &invocation {
if let Err(why) = preflight_migration(name, args) {
eprintln!("{BIN}: {why}");
return ExitCode::FAILURE;
}
}
match invocation {
Invocation::Help => {
print!("{USAGE}");
ExitCode::SUCCESS
}
Invocation::Version => {
println!(
concat!(greenbelay_guard::bin!(), " {}"),
env!("CARGO_PKG_VERSION")
);
ExitCode::SUCCESS
}
Invocation::Usage(why) => {
eprintln!("{BIN}: {why}\n");
eprint!("{USAGE}");
ExitCode::from(2)
}
Invocation::Sub { name, args } => match name {
Sub::Hook => {
let _ = args;
hook::run()
}
Sub::Install => run_install(&args, true),
Sub::Uninstall => run_install(&args, false),
Sub::Status => run_status(),
Sub::Doctor => {
if args.iter().any(|a| a == "--help" || a == "-h") {
println!(concat!(
"usage: ",
greenbelay_guard::bin!(),
" doctor [--json]"
));
println!();
println!("Check that the guard is installed and alive; exit 0 when it is.");
println!(" --json print one JSON document: healthy, findings, integration");
return ExitCode::SUCCESS;
}
if let Some(bad) = args.iter().find(|a| *a != "--json") {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": doctor takes only --json, not {}"
),
bad.to_string_lossy()
);
return ExitCode::from(2);
}
let scanned = doctor::scan();
let mut findings =
doctor::run(rule_table::RULES, attestations::doctor_finding(), &scanned);
findings.push(plan_root_finding());
findings.push(open::opener_finding());
if let Ok(project) = std::env::current_dir() {
findings.extend(greenbelay_process::agents::review_gaps(&project));
}
let healthy = if args.iter().any(|a| a == "--json") {
println!(
"{}",
doctor::json(&findings, &doctor::integration(&scanned))
);
doctor::healthy(&findings)
} else {
doctor::report(&findings)
};
if healthy {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
Sub::Migrate => run_migrate(&args),
Sub::Corpus => run_corpus(&args),
Sub::Graduate => run_graduate(&args, true),
Sub::Demote => run_graduate(&args, false),
Sub::Backtest => run_backtest(&args, false),
Sub::HarnessReview => run_harness_review(&args),
Sub::Explain => run_backtest(&args, true),
Sub::Mine => run_mine(&args),
Sub::OutputAudit => run_output_audit(&args),
Sub::Check => run_check(&args),
Sub::Analyze => run_analyze(&args),
Sub::Rules => run_rules(&args),
Sub::Preview => run_preview(&args),
Sub::PlanSha => run_plan_sha(&args),
Sub::Shipped => shipped::run(&args),
Sub::Board => board::run(&args),
Sub::Open => open::run(&args),
Sub::Suppressions => suppressions::run(&args, index_handoff, hook_index),
Sub::PlanPanel => run_plan_panel(&args),
Sub::PlanReview => {
let (said, code) = review_outcomes::run(&args);
use std::io::Write as _;
let mut out = std::io::stdout().lock();
match out.write_all(said.as_bytes()).and_then(|()| out.flush()) {
Ok(()) => code,
Err(e) if e.kind() == std::io::ErrorKind::BrokenPipe => code,
Err(e) => {
eprintln!(
"{}: plan-review: cannot write output: {e}",
greenbelay_guard::names::BIN
);
ExitCode::from(1)
}
}
}
Sub::ImplementationReview => {
let (said, code) = impl_review_outcomes::run(&args);
print!("{said}");
code
}
Sub::PlanApply => {
let (said, code) = plan_apply::run(&args);
print!("{said}");
code
}
Sub::TreeSha => run_tree_sha(&args),
Sub::Block => run_block(&args),
Sub::RulesSha => run_rules_sha(&args),
Sub::ReviewBrief => run_review_brief(&args),
Sub::Attestations => attestations::run_cli(&args),
#[cfg(unix)]
Sub::Quiet => quiet::run(&args),
#[cfg(not(unix))]
Sub::Quiet => {
eprintln!(concat!(
greenbelay_guard::bin!(),
": quiet is not supported on this platform"
));
ExitCode::from(2)
}
},
}
}
#[derive(Default)]
struct Flags {
write: bool,
reformat: bool,
project: bool,
local: bool,
transcripts: Vec<PathBuf>,
since: Option<civil::Day>,
only: Vec<String>,
sample: Option<usize>,
json: bool,
format: Option<String>,
to: Option<String>,
force: bool,
window: Option<usize>,
min_support: Option<u32>,
min_rate: Option<f64>,
rank: Option<String>,
compliance: bool,
check: bool,
out: Option<PathBuf>,
cases: Option<PathBuf>,
model: Option<String>,
dialect: Option<rules::Dialect>,
cwd: Option<PathBuf>,
explain: bool,
rest: Vec<String>,
}
fn flags(args: &[OsString]) -> Result<Flags, String> {
let mut f = Flags::default();
let mut i = 0;
while i < args.len() {
let a = args[i].to_string_lossy().into_owned();
let value = |i: &mut usize, what: &str| -> Result<String, String> {
*i += 1;
args.get(*i)
.map(|v| v.to_string_lossy().into_owned())
.ok_or_else(|| format!("{what} needs a value"))
};
match a.as_str() {
"--out" => f.out = Some(PathBuf::from(value(&mut i, &a)?)),
"--cases" => f.cases = Some(PathBuf::from(value(&mut i, &a)?)),
"--model" => f.model = Some(value(&mut i, &a)?),
"--transcripts" => f.transcripts.push(PathBuf::from(value(&mut i, &a)?)),
"--since" => {
let v = value(&mut i, &a)?;
f.since =
Some(civil::day_of(&v).ok_or_else(|| format!("--since: `{v}` is not a date"))?);
}
"--rule" => f.only.push(value(&mut i, &a)?),
"--sample" => {
let v = value(&mut i, &a)?;
let count: usize = v
.parse()
.map_err(|_| format!("--sample: `{v}` is not a number"))?;
if count == 0 {
return Err("--sample: takes 1 or more".to_string());
}
f.sample = Some(count);
}
"--window" => {
let v = value(&mut i, &a)?;
f.window = Some(
v.parse()
.map_err(|_| format!("--window: `{v}` is not a number"))?,
);
}
"--min-support" => {
let v = value(&mut i, &a)?;
f.min_support = Some(
v.parse()
.map_err(|_| format!("--min-support: `{v}` is not a number"))?,
);
}
"--min-rate" => {
let v = value(&mut i, &a)?;
let rate: f64 = v
.parse()
.map_err(|_| format!("--min-rate: `{v}` is not a number"))?;
if !(0.0..=1.0).contains(&rate) {
return Err(format!("--min-rate: `{v}` is not a share between 0 and 1"));
}
f.min_rate = Some(rate);
}
"--rank" => f.rank = Some(value(&mut i, &a)?),
"--dialect" => {
let v = value(&mut i, &a)?;
f.dialect = Some(
rules::Dialect::parse(&v)
.ok_or_else(|| format!("--dialect: `{v}` is not bash, zsh or unknown"))?,
);
}
"--cwd" => f.cwd = Some(PathBuf::from(value(&mut i, &a)?)),
"--explain" => f.explain = true,
"--compliance" => f.compliance = true,
"--check" => f.check = true,
"--json" => f.json = true,
"--format" => f.format = Some(value(&mut i, &a)?),
"--to" => f.to = Some(value(&mut i, &a)?),
"--force" => f.force = true,
"--write" => f.write = true,
"--reformat" => f.reformat = true,
"--project" => f.project = true,
"--local" => f.local = true,
other if other.starts_with('-') => return Err(format!("unknown flag `{other}`")),
other => f.rest.push(other.to_string()),
}
i += 1;
}
Ok(f)
}
fn selected(only: &[String]) -> Result<Vec<backtest::Subject>, String> {
let everything = || {
rule_table::RULES
.iter()
.map(backtest::Subject::Rule)
.chain(
assertions::ASSERTIONS
.iter()
.map(backtest::Subject::Assertion),
)
.collect::<Vec<_>>()
};
if only.is_empty() {
return Ok(everything());
}
only.iter()
.map(|id| {
rules::by_id(rule_table::RULES, id)
.map(backtest::Subject::Rule)
.or_else(|| assertions::by_id(id).map(backtest::Subject::Assertion))
.ok_or_else(|| {
let known: Vec<&str> = everything().iter().map(|s| s.id()).collect();
format!("no rule `{id}` — known rules: {}", known.join(", "))
})
})
.collect()
}
fn run_backtest(args: &[OsString], explain: bool) -> ExitCode {
let mut f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
if explain {
match f.rest.len() {
1 => f.only.push(f.rest[0].clone()),
_ => {
eprintln!(concat!(
greenbelay_guard::bin!(),
": explain needs exactly one rule"
));
return ExitCode::from(2);
}
}
}
let chosen = match selected(&f.only) {
Ok(c) => c,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
let as_cases = explain && f.format.as_deref() == Some("cases");
if let Some(other) = f.format.as_deref() {
if other != "cases" {
eprintln!("{BIN}: --format takes `cases`, not `{other}`");
return ExitCode::from(2);
}
}
let exporting = as_cases && f.only == [greenbelay_guard::rules::clear_at_boundary::RULE.id];
let unused: &[(bool, &str)] = if exporting {
&[
(f.since.is_some(), "--since"),
(f.json, "--json"),
(f.rank.is_some(), "--rank"),
]
} else if explain {
&[(f.out.is_some(), "--out"), (f.cases.is_some(), "--cases")]
} else {
&[(f.cases.is_some(), "--cases")]
};
if let Some((_, name)) = unused.iter().find(|(given, _)| *given) {
let scope = if exporting {
"the Stop export does not use"
} else {
"only `explain clear-at-boundary --format cases` takes"
};
eprintln!("{BIN}: {name}: {scope} it");
return ExitCode::from(2);
}
if exporting {
return run_export_stops(&f);
}
let roots = match transcript::roots(&f.transcripts) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(2);
}
};
let scan = transcript::Scan {
roots: &roots,
tool: "Bash",
since: f.since,
};
let novelty = match f.rank.as_deref() {
None => false,
Some("novelty") if explain => true,
Some("novelty") => {
eprintln!(concat!(
greenbelay_guard::bin!(),
": --rank novelty is for `explain`, which prints the matches"
));
return ExitCode::from(2);
}
Some(other) => {
eprintln!("{BIN}: --rank takes `novelty`, not `{other}`");
return ExitCode::from(2);
}
};
if f.compliance {
return run_compliance(&f, &roots, &scan, &chosen);
}
let samples = if novelty {
usize::MAX
} else {
f.sample.unwrap_or(if as_cases {
usize::MAX
} else if explain {
40
} else {
2
})
};
match backtest::run(&scan, &chosen, samples) {
Ok(mut report) => {
if novelty {
rank_by_novelty(&mut report, f.sample.unwrap_or(20));
}
if as_cases {
println!("{}", corpus::HEADER);
let mut seen = std::collections::BTreeSet::new();
for group in &report.samples {
for sample in group {
if seen.insert(sample.command.clone()) {
print!(
"{}",
corpus::line_for(corpus::Verdict::Unreviewed, &sample.command)
);
}
}
}
} else if f.json {
println!("{}", report.to_json(&roots));
} else {
print!("{}", report.render(&roots));
}
ExitCode::SUCCESS
}
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
ExitCode::from(2)
}
}
}
fn run_export_stops(flags: &Flags) -> ExitCode {
let rule = greenbelay_guard::rules::clear_at_boundary::RULE.id;
let out = match &flags.out {
Some(dir) => dir.clone(),
None if corpus::checkout_present() => corpus::stop_dir_for(rule),
None => {
eprintln!(
concat!(
"{}: this build has no checkout to write fixtures into; ",
"pass --out <dir>, or run `cargo run -- explain {} --format cases` ",
"from a checkout of ",
greenbelay_guard::bin!()
),
BIN, rule
);
return ExitCode::from(2);
}
};
let roots = match transcript::roots(&flags.transcripts) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(2);
}
};
let Some(journal_dir) = journal::dir() else {
eprintln!("{BIN}: no journal directory: neither CLAUDE_CONFIG_DIR nor HOME is set");
return ExitCode::from(2);
};
let journal_files = match greenbelay_process::clear_boundary_export::journal_files(&journal_dir)
{
Ok(files) => files,
Err(error) => {
eprintln!("{BIN}: {}: {error}", journal_dir.display());
return ExitCode::from(2);
}
};
let cases_path = flags
.cases
.clone()
.unwrap_or_else(|| corpus::path_for(rule));
let cases_text = match std::fs::read_to_string(&cases_path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(error) => {
eprintln!("{BIN}: {}: {error}", cases_path.display());
return ExitCode::from(2);
}
};
let mut options = greenbelay_process::clear_boundary_export::Options::new(out);
options.journal = journal_files;
options.transcripts = transcript::files(&roots);
options.transcript_roots = roots.dirs.clone();
options.cases_text = cases_text;
options.sample = flags.sample;
options.home = std::env::var("HOME").ok();
let report = greenbelay_process::clear_boundary_export::export(&options);
for note in &report.notes {
eprintln!("{BIN}: {note}");
}
if report.found_nothing() {
eprintln!(
"{BIN}: no clear-at-boundary lines in {}",
journal_dir.display()
);
return ExitCode::FAILURE;
}
eprintln!("{}", report.summary());
for line in &report.stdout {
println!("{line}");
}
if report.failed() {
ExitCode::FAILURE
} else {
ExitCode::SUCCESS
}
}
fn rank_by_novelty(report: &mut backtest::Report, n: usize) {
for (i, subject) in report.rules.iter().enumerate() {
let seeds: Vec<shape::Shape> = corpus::read(subject.id())
.iter()
.map(|c| shape::Shape::of_command(&c.command))
.collect();
let candidates: Vec<shape::Shape> = report.samples[i]
.iter()
.map(|s| shape::Shape::of_command(&s.command))
.collect();
let picked = shape::pick_novel(&candidates, &seeds, n);
let mut held: Vec<Option<backtest::Sample>> =
report.samples[i].drain(..).map(Some).collect();
report.samples[i] = picked.iter().filter_map(|&j| held[j].take()).collect();
}
}
fn run_harness_review(args: &[OsString]) -> ExitCode {
if args.iter().any(|a| a == "--help" || a == "-h") {
println!(concat!("usage: ", greenbelay_guard::bin!(), " harness-review [--json] [--check] [--model <id>] [--transcripts <dir>] [--since <date>] [--out <dir>]"));
return ExitCode::SUCCESS;
}
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
if let Some(operand) = f.rest.first() {
eprintln!("{BIN}: harness-review takes no operand, got `{operand}`");
return ExitCode::from(2);
}
let Some(journal_dir) = journal::dir() else {
eprintln!(concat!(
greenbelay_guard::bin!(),
": no home directory, so no journal directory"
));
return ExitCode::from(2);
};
let roots = match transcript::roots(&f.transcripts) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(2);
}
};
let scan = transcript::Scan {
roots: &roots,
tool: "Bash",
since: f.since,
};
let out = f
.out
.clone()
.unwrap_or_else(|| harness_review::reviews_dir(&journal_dir));
if f.check {
return match harness_review::check(&out, &scan) {
Ok(None) => ExitCode::SUCCESS,
Ok(Some(line)) => {
println!("{line}");
ExitCode::FAILURE
}
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
ExitCode::from(2)
}
};
}
let today = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
Ok(d) => (d.as_secs() / 86_400) as civil::Day,
Err(e) => {
eprintln!("{BIN}: cannot read the clock: {e}");
return ExitCode::from(2);
}
};
let table: Vec<&'static rules::Rule> = rule_table::RULES.iter().collect();
let review = match harness_review::review(
&scan,
&table,
stance_of_part,
&journal::paths(),
today,
f.model.as_deref(),
) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(2);
}
};
if let Err(e) = harness_review::write(&out, &review) {
eprintln!("{BIN}: could not write the review file: {e}");
return ExitCode::from(2);
}
if f.json {
println!("{}", review.to_json());
} else {
print!("{}", review.render());
}
ExitCode::SUCCESS
}
fn stance_of_part(part: &backtest::Subject) -> rules::Stance {
match part {
backtest::Subject::Rule(r) => stance::resolve(r),
backtest::Subject::Assertion(a) => stance::resolve_assertion(a),
}
}
fn run_compliance(
f: &Flags,
roots: &transcript::Roots,
scan: &transcript::Scan,
chosen: &[backtest::Subject],
) -> ExitCode {
let rules: Vec<&'static rules::Rule> = chosen
.iter()
.filter_map(|s| match s {
backtest::Subject::Rule(r) => Some(*r),
backtest::Subject::Assertion(_) => None,
})
.collect();
if rules.is_empty() {
eprintln!(concat!(
greenbelay_guard::bin!(),
": --compliance is about rules, and none were selected"
));
return ExitCode::from(2);
}
let options = compliance::Options {
window: f.window.unwrap_or(compliance::Options::default().window),
};
match compliance::run(scan, &rules, options) {
Ok(report) => {
if f.json {
println!("{}", report.to_json(roots));
} else {
print!("{}", report.render(roots));
}
ExitCode::SUCCESS
}
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
ExitCode::from(2)
}
}
}
const OUTPUT_AUDIT_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" output-audit --since <UTC> --until <UTC>
[--transcripts <dir>]... [--json]
Where tool output went: the bytes tool results put into session context in
the window [since, until), by kind of call (ci-log-failed, ci-log,
ci-status, check, check-quiet, check-git-hook, git, shell, read, search,
edit, agent, lsp, web, mcp, other-tool, unmatched), apart from subagents,
beside the token usage the transcripts report, by model.
Each result, each agent launch and each message counts once, however many
times a resumed session copies it. `over 200 B` is the share of passing
results beyond 200 bytes each: what a one-line quiet summary would not
carry, a proxy, not a measure. Usage is what the transcripts report: not
billing and not quota. The output carries counts only, no command or
result text.
--since, --until UTC instants, YYYY-MM-DDTHH:MM:SS[.fff]Z
--transcripts a transcript root (repeatable; default: the Claude
config directory's projects/)
--json the aggregate as JSON, exact integers
Exit 0, also when some files could not be read (the coverage line and the
JSON `coverage.complete` say so); 1 when the transcripts cannot be found;
2 on a usage error.
"
);
fn run_output_audit(args: &[OsString]) -> ExitCode {
use greenbelay_guard::output_audit::{self, Instant, Window};
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
if args.iter().any(|a| a == "--help" || a == "-h") {
print!("{OUTPUT_AUDIT_USAGE}");
return ExitCode::SUCCESS;
}
let usage = |why: &str| {
eprintln!("{BIN}: output-audit: {why}; try `{BIN} output-audit --help`");
ExitCode::from(2)
};
let (mut since, mut until, mut roots, mut as_json) = (None, None, Vec::new(), false);
let mut words = args.iter();
while let Some(word) = words.next() {
if word == "--" {
if let Some(operand) = words.next() {
return usage(&format!("unexpected operand `{operand}`"));
}
break;
}
let (flag, attached) = match word.split_once('=') {
Some((flag, value)) if flag.starts_with("--") => (flag, Some(value.to_string())),
Some(_) | None => (word.as_str(), None),
};
if flag == "--json" {
if attached.is_some() {
return usage("--json takes no value");
}
as_json = true;
continue;
}
if !matches!(flag, "--since" | "--until" | "--transcripts") {
return usage(&format!("unknown argument `{word}`"));
}
let Some(value) = attached.or_else(|| words.next().cloned()) else {
return usage(&format!("{flag} needs a value"));
};
if flag == "--transcripts" {
roots.push(std::path::PathBuf::from(value));
continue;
}
let Some(at) = Instant::parse(&value) else {
return usage(&format!(
"{flag} takes a UTC instant like 2026-11-06T10:03:38Z, not `{value}`"
));
};
if flag == "--since" {
since = Some(at);
} else {
until = Some(at);
}
}
let (Some(since), Some(until)) = (since, until) else {
return usage("--since and --until are both required");
};
if since >= until {
return usage("--since must be before --until");
}
let roots = match transcript::roots(&roots) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(1);
}
};
let window = Window { since, until };
let audit = output_audit::audit(&roots, &window);
if as_json {
println!("{}", audit.to_json(&window));
} else {
print!("{}", output_audit_text(&audit, &window));
}
ExitCode::SUCCESS
}
fn scaled(count: u64) -> String {
let units = [(1e9, "G"), (1e6, "M"), (1e3, "K")];
let amount = count as f64;
units
.iter()
.find(|(size, _)| (amount / size * 10.0).round() >= 10.0)
.map_or_else(
|| count.to_string(),
|(size, unit)| format!("{:.1}{unit}", amount / size),
)
}
fn output_audit_text(
audit: &greenbelay_guard::output_audit::Audit,
window: &greenbelay_guard::output_audit::Window,
) -> String {
let mut out = format!(
"window {} .. {} (until excluded)\n{} sessions, {} agent launches\n",
window.since.as_str(),
window.until.as_str(),
audit.sessions,
audit.agent_launches
);
for (title, map) in [
("main conversation", &audit.main),
("subagents", &audit.sidechain),
] {
let total: u64 = map.values().map(|b| b.result_bytes).sum();
out.push_str(&format!("\n{title}: {}B of tool output\n", scaled(total)));
if map.is_empty() {
out.push_str(" none\n");
continue;
}
out.push_str(&format!(
" {:<15} {:>7} {:>7} {:>8} {:>6} {:>10}\n",
"kind", "calls", "failed", "bytes", "share", "over 200 B"
));
let mut rows: Vec<_> = map.iter().collect();
rows.sort_by(|a, b| b.1.result_bytes.cmp(&a.1.result_bytes));
for (kind, b) in rows {
let share = if total == 0 {
0.0
} else {
100.0 * b.result_bytes as f64 / total as f64
};
out.push_str(&format!(
" {:<15} {:>7} {:>7} {:>8} {:>5.1}% {:>10}\n",
kind.as_str(),
b.calls,
b.failed,
scaled(b.result_bytes),
share,
scaled(b.over_summary)
));
}
}
out.push_str("\nreported usage by model, tokens (not billing, not quota)\n");
if audit.usage.is_empty() {
out.push_str(" none\n");
} else {
out.push_str(&format!(
" {:<22} {:>8} {:>8} {:>9} {:>9} {:>8}\n",
"model", "messages", "input", "cache wr", "cache rd", "output"
));
for (model, u) in &audit.usage {
out.push_str(&format!(
" {:<22} {:>8} {:>8} {:>9} {:>9} {:>8}\n",
model.chars().take(22).collect::<String>(),
u.messages,
scaled(u.input),
scaled(u.cache_creation),
scaled(u.cache_read),
scaled(u.output)
));
}
}
let coverage = &audit.coverage;
let mut lost = Vec::new();
for (count, one, many) in [
(
coverage.files_unreadable,
"unreadable file",
"unreadable files",
),
(
coverage.files_truncated,
"file cut short by a read error",
"files cut short by a read error",
),
(coverage.bad_lines, "unparsable line", "unparsable lines"),
(
coverage.oversized_lines,
"oversized line",
"oversized lines",
),
] {
if count > 0 {
lost.push(format!("{count} {}", if count == 1 { one } else { many }));
}
}
out.push_str(&format!(
"\ncoverage: {} {} read ({} older skipped)",
coverage.files_scanned,
if coverage.files_scanned == 1 {
"file"
} else {
"files"
},
coverage.files_skipped
));
if lost.is_empty() {
out.push_str(", every line read\n");
} else {
out.push_str("; not counted:\n");
for problem in lost {
out.push_str(&format!(" {problem}\n"));
}
}
out
}
fn run_mine(args: &[OsString]) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
if !f.only.is_empty() {
eprintln!(concat!(
greenbelay_guard::bin!(),
": mine looks for what no rule names yet, so --rule means nothing"
));
return ExitCode::from(2);
}
let as_cases = f.format.as_deref() == Some("cases");
if let Some(other) = f.format.as_deref() {
if other != "cases" {
eprintln!("{BIN}: --format takes `cases`, not `{other}`");
return ExitCode::from(2);
}
}
let roots = match transcript::roots(&f.transcripts) {
Ok(r) => r,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
return ExitCode::from(2);
}
};
let scan = transcript::Scan {
roots: &roots,
tool: "Bash",
since: f.since,
};
let default = mine::Options::default();
let options = mine::Options {
window: f.window.unwrap_or(default.window),
min_support: f.min_support.unwrap_or(default.min_support),
min_rate: f.min_rate.unwrap_or(default.min_rate),
samples: f.sample.unwrap_or(default.samples),
};
match mine::run(&scan, options, rule_table::RULES) {
Ok(report) => {
if as_cases {
println!("{}", corpus::HEADER);
let mut seen = std::collections::BTreeSet::new();
for command in report.sample_commands() {
if seen.insert(command.to_string()) {
print!("{}", corpus::line_for(corpus::Verdict::Unreviewed, command));
}
}
} else if f.json {
println!("{}", report.to_json(&roots));
} else {
print!("{}", report.render(&roots));
}
ExitCode::SUCCESS
}
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
ExitCode::from(2)
}
}
}
fn run_analyze(args: &[OsString]) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
if f.rest.len() != 1 {
eprintln!(concat!(
greenbelay_guard::bin!(),
": analyze needs exactly one command, quoted"
));
return ExitCode::from(2);
}
let src = &f.rest[0];
let dialect = f.dialect.unwrap_or(rules::Dialect::Unknown);
let a = analysis::analyze(src, dialect);
let upper = |u: analysis::domain::Upper| match u {
analysis::domain::Upper::Finite(n) => serde_json::json!(n),
analysis::domain::Upper::Saturated => serde_json::json!("saturated"),
analysis::domain::Upper::Uncapped(_) => serde_json::json!("uncapped"),
analysis::domain::Upper::Unknown => serde_json::json!("unknown"),
};
let contributions: Vec<serde_json::Value> = a
.effects
.contributions
.iter()
.map(|c| {
serde_json::json!({
"program": c.program,
"span": [c.span.start, c.span.end],
"hosts": c.targets.hosts,
"unresolved": !c.targets.unresolved.is_empty(),
"local": c.targets.local,
"lower": c.transfers.lower,
"upper": upper(c.transfers.upper),
"paced": c.paced.map(|p| p.secs),
})
})
.collect();
let out = serde_json::json!({
"dialect": dialect.as_str(),
"parsed": analysis::frontend::parse(src).is_ok(),
"incomplete": a.incomplete.as_ref().map(|i| i.why),
"unknown": a.effects.unknown.len(),
"contributions": contributions,
});
println!("{out}");
ExitCode::SUCCESS
}
const PLAN_SHA_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" plan-sha [--short] [--block [--lang <language>] [--slice <role>]] [--legacy] [--] <file|->
The sha256 of what a plan says, which its review binds to (ADR-0022,
work.plan-review-panel). The plan is read without its YAML front matter,
its `## Review panel` section, its `## Full reviews` section and its
machine comment (`<!-- panel: ... -->` on the last line), so writing review
results into it never changes the sha. The rest is read as CommonMark:
counts every word, number and operator; code blocks and code
spans exactly as written; link destinations; the kind of
each block (list item, quote, heading, table cell, an
ordered list's start)
does not count blank lines, line wrapping, indentation outside code,
table padding, list-marker style (`*`/`-`), emphasis
style (`*x*`/`_x_`), escapes (`\\_`), CRLF
So a formatter such as prettier keeps the sha, unless it rewrites code.
--short the first 12 hex characters, for the machine comment
--block the review block a plan-review-* agent's prompt carries:
<<<PLAN path=<realpath> sha=<64 hex>>>>
--lang <language> with --block, for plan-review-language: adds lang=<l>
--slice <role> with --block, for a seat bound to its slice of the plan
(ADR-0061 work.review-slices): adds slice=<64 hex> and
prints a second line naming the phases of the slice.
A seat of a file type (lang:<x>, react, ui-design,
platform) on a plan whose every phase names a file has
a slice; on any other plan it gets the plain block, and
stderr says it binds the whole body. --slice lang:<x>
implies --lang <x>
(--lang=<l> and --slice=<role> work too)
--legacy the byte sha from before 2.25, to check a plan whose
machine comment was written then; temporary, removed
after the transition (not with --block)
- read the plan from stdin (not with --block, which
needs the file's path)
Prints one line on stdout, or two with --slice. Exit 0, 1 when the file
cannot be read or its sha cannot be computed (the reason on stderr), 2 on a
usage error.
"
);
fn slice_lang(role: &str, lang: Option<&str>) -> Result<Option<String>, String> {
if plan_review::remit(role).is_empty() {
return Err(format!(
"unknown role {role}; roles: {}, lang:<language>",
plan_review::NAMED_ROLES.join(", ")
));
}
if greenbelay_process::file_types::profile_reads(role).is_none() {
return Err(format!("{role} binds the whole body; drop --slice"));
}
match (role.strip_prefix("lang:"), lang) {
(Some(want), Some(have)) if have != want => Err(format!(
"--slice {role} conflicts with --lang {have}; pass --lang {want} or drop --lang"
)),
(Some(want), None) => Ok(Some(want.to_string())),
(_, have) => Ok(have.map(str::to_string)),
}
}
fn run_plan_sha(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let (mut short, mut block, mut lang, mut file) = (false, false, None, None);
let mut legacy = false;
let mut slice: Option<String> = None;
if args
.iter()
.take_while(|a| a.as_str() != "--")
.any(|a| a == "--help" || a == "-h")
{
print!("{PLAN_SHA_USAGE}");
return ExitCode::SUCCESS;
}
let mut i = 0;
let mut operands_only = false;
while i < args.len() {
let a = args[i].as_str();
if let Some((flag, value)) = a
.split_once('=')
.filter(|(f, _)| !operands_only && (*f == "--lang" || *f == "--slice"))
{
if value.is_empty() {
eprintln!("{BIN}: {flag} needs a value");
return ExitCode::from(2);
}
if flag == "--lang" {
lang = Some(value.to_string());
} else {
slice = Some(value.to_string());
}
i += 1;
continue;
}
match a {
_ if operands_only || a == "-" || !a.starts_with('-') => {
if file.is_some() {
eprintln!(concat!(
greenbelay_guard::bin!(),
": plan-sha takes one file; try `",
greenbelay_guard::bin!(),
" plan-sha --help`"
));
return ExitCode::from(2);
}
file = Some(a.to_string());
}
"--" => operands_only = true,
"--help" | "-h" => {
print!("{PLAN_SHA_USAGE}");
return ExitCode::SUCCESS;
}
"--short" => short = true,
"--block" => block = true,
"--legacy" => legacy = true,
"--lang" => {
i += 1;
match args.get(i) {
Some(v) => lang = Some(v.clone()),
None => {
eprintln!(concat!(greenbelay_guard::bin!(), ": --lang needs a value"));
return ExitCode::from(2);
}
}
}
"--slice" => {
i += 1;
match args.get(i) {
Some(v) if !v.starts_with('-') => slice = Some(v.clone()),
_ => {
eprintln!(concat!(greenbelay_guard::bin!(), ": --slice needs a value"));
return ExitCode::from(2);
}
}
}
other => {
eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} plan-sha --help`");
return ExitCode::from(2);
}
}
i += 1;
}
let Some(file) = file else {
eprint!("{BIN}: plan-sha needs a file, or - for stdin\n\n{PLAN_SHA_USAGE}");
return ExitCode::from(2);
};
let conflict = if short && block {
Some("--short and --block exclude each other")
} else if lang.is_some() && !block {
Some("--lang only goes with --block")
} else if block && file == "-" {
Some("--block needs the plan's file, not stdin")
} else if block && legacy {
Some("--legacy only prints a sha; drop --block")
} else if slice.is_some() && !block {
Some(concat!(
"--slice needs --block: ",
greenbelay_guard::bin!(),
" plan-sha --block --slice <role> <plan.md>"
))
} else {
None
};
if let Some(why) = conflict {
eprintln!("{BIN}: {why}; try `{BIN} plan-sha --help`");
return ExitCode::from(2);
}
if let Some(role) = slice.as_deref() {
match slice_lang(role, lang.as_deref()) {
Ok(l) => lang = l,
Err(why) => {
eprintln!("{BIN}: {why}; try `{BIN} plan-sha --help`");
return ExitCode::from(2);
}
}
}
let text = if file == "-" {
use std::io::Read;
let mut t = String::new();
if let Err(e) = std::io::stdin().read_to_string(&mut t) {
eprintln!("{BIN}: cannot read stdin: {e}");
return ExitCode::from(1);
}
t
} else {
match std::fs::read_to_string(&file) {
Ok(t) => t,
Err(e) => {
eprintln!("{BIN}: cannot read {file}: {e}");
return ExitCode::from(1);
}
}
};
let sha = if legacy {
eprintln!(concat!(
greenbelay_guard::bin!(),
": --legacy is removed after the transition"
));
plan_text::legacy_sha(&text)
} else {
match plan_text::shas(&text) {
Ok(s) => s.sha,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(1);
}
}
};
greenbelay_process::plan_id::remember_live(&text);
if block {
let path = plan_review::real(std::path::Path::new(&file));
let cut = match slice.as_deref() {
None => None,
Some(role) => match plan_review::slice_for(&text, role) {
Ok(s) => Some((role, s)),
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(1);
}
},
};
let slice_sha = match &cut {
Some((_, plan_review::SliceFor::Slice(s))) => Some(s.sha.as_str()),
_ => None,
};
println!(
"{}",
plan_review::block(&path, &sha, lang.as_deref(), slice_sha)
);
match &cut {
Some((_, plan_review::SliceFor::Slice(s))) => println!(
"Your slice: {} and the shared sections. The other phases belong to other seats: read them only to follow yours, and raise a finding there only if it blocks.",
s.kept.join(", ")
),
Some((role, plan_review::SliceFor::WholeBody(why))) => {
eprintln!("{BIN}: {role} binds the whole body ({})", why.as_str());
}
None => {}
}
} else if short {
println!("{}", &sha[..12]);
} else {
println!("{sha}");
}
ExitCode::SUCCESS
}
const BLOCK_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" block sha [-C <dir>] [--base <ref>]
",
greenbelay_guard::bin!(),
" block list [--json]
",
greenbelay_guard::bin!(),
" block revoke <fp> --because <text>
",
greenbelay_guard::bin!(),
" block reinstate <fp>
The fingerprint of a branch's change, which a copy of a reviewed block
shares with its source: the sha256 of the `+` and `-` lines of `git diff`
from the merge base to HEAD (docs/plans/ left out), without paths, line
numbers or context, the common indentation removed, and CR and trailing
blanks stripped. git runs with its own settings, not the person's.
sha print `<64 hex>` TAB `fp:<12 hex>` on stdout
-C <dir> the repository at <dir> (default: the current one)
--base <ref> the ref to take the merge base with (default: the default
branch of origin)
Exit codes of `sha`: 0; 1 when there is no fingerprint (a binary file in
the diff, which is never a copy, or git failing; the reason on stderr); 2 on
a usage error.
list one row per registered block, no header, on stdout:
fp:<12 hex> TAB active|revoked TAB <roles, comma-separated>
TAB <copy count> TAB <source repo, - when unknown>; --json
adds the copies and `source_repo` (null when unknown)
revoke revoke a block until the person reinstates it: the pilot is
printed as <source repo> TAB <branch> TAB - and every
recorded copy as <repo> TAB <branch> TAB <commit> for a
re-check; revoking again prints them again
reinstate lift a revocation, on stderr; the person runs it, not an agent
<fp> fp:<12 hex>, a unique prefix of it, or the 64 hex
Exit codes of `list`, `revoke` and `reinstate`: 0; 1 when the fingerprint
names no block or several (`give more hex`), the registry cannot be found or
written; 2 on a usage error.
"
);
const BLOCK_GIT_BUDGET: std::time::Duration = std::time::Duration::from_secs(20);
fn run_block(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
match args.first().map(String::as_str) {
Some("--help" | "-h") => block_help(),
Some("sha") => run_block_sha(&args[1..]),
Some("list") => run_block_list(&args[1..]),
Some("revoke") => run_block_revoke(&args[1..]),
Some("reinstate") => run_block_reinstate(&args[1..]),
Some(_) if args.iter().any(|word| is_help(word)) => block_help(),
Some(other) => {
eprintln!("{BIN}: block: unknown verb `{other}`; try `{BIN} block --help`");
eprint!("{BLOCK_USAGE}");
ExitCode::from(2)
}
None => {
eprintln!(concat!(
greenbelay_guard::bin!(),
": block: needs a verb; try `",
greenbelay_guard::bin!(),
" block --help`"
));
eprint!("{BLOCK_USAGE}");
ExitCode::from(2)
}
}
}
fn is_help(word: &str) -> bool {
word == "--help" || word == "-h"
}
fn block_help() -> ExitCode {
print!("{BLOCK_USAGE}");
ExitCode::SUCCESS
}
fn block_base() -> Option<std::path::PathBuf> {
let base = journal::dir();
if base.is_none() {
eprintln!(concat!(
greenbelay_guard::bin!(),
": block: no home or CLAUDE_CONFIG_DIR to find the registry in"
));
}
base
}
fn resolve_block_fp(base: &std::path::Path, given: &str) -> Result<String, ExitCode> {
let id = given.strip_prefix("fp:").unwrap_or(given);
let mut hits: Vec<String> = Vec::new();
if !id.is_empty() {
hits = block_registry::fingerprints(base)
.into_iter()
.filter(|fingerprint| fingerprint.starts_with(id))
.collect();
}
match hits.pop() {
Some(only) if hits.is_empty() => Ok(only),
Some(_) => {
eprintln!(
"{BIN}: block: fp:{id} matches {} blocks; give more hex",
hits.len() + 1
);
Err(ExitCode::from(1))
}
None => {
eprintln!("{BIN}: block: no entry fp:{id}; see {BIN} block list");
Err(ExitCode::from(1))
}
}
}
fn block_usage_error(why: &str) -> ExitCode {
eprintln!("{BIN}: block: {why}; try `{BIN} block --help`");
ExitCode::from(2)
}
fn run_block_list(args: &[String]) -> ExitCode {
let mut json = false;
for word in args {
match word.as_str() {
help if is_help(help) => return block_help(),
"--json" => json = true,
other => return block_usage_error(&format!("unknown argument `{other}`")),
}
}
let Some(base) = block_base() else {
return ExitCode::from(1);
};
let mut rows = Vec::new();
for fingerprint in block_registry::fingerprints(&base) {
let mut roles: Vec<String> = block_registry::entries(&base, &fingerprint)
.into_iter()
.flat_map(|entry| entry.registered.roles)
.collect();
roles.sort();
roles.dedup();
let copies = block_registry::copies(&base, &fingerprint);
let revoked = block_registry::revoked(&base, &fingerprint);
let source = block_registry::source_entry(&base, &fingerprint)
.and_then(|entry| entry.registered.source_repo);
let short = format!("fp:{}", &fingerprint[..12]);
if json {
let listed: Vec<serde_json::Value> = copies
.iter()
.map(|copy| {
serde_json::json!({
"repo": copy.repo,
"branch": copy.branch,
"commit": copy.commit,
})
})
.collect();
rows.push(serde_json::json!({
"fingerprint": fingerprint,
"short": short,
"state": if revoked.is_some() { "revoked" } else { "active" },
"because": revoked,
"roles": roles,
"copies": listed,
"source_repo": source,
}));
} else {
let state = if revoked.is_some() {
"revoked"
} else {
"active"
};
println!(
"{short}\t{state}\t{}\t{}\t{}",
roles.join(","),
copies.len(),
source.as_deref().unwrap_or("-")
);
}
}
if json {
println!("{}", serde_json::Value::Array(rows));
}
ExitCode::SUCCESS
}
fn run_block_revoke(args: &[String]) -> ExitCode {
let (mut fingerprint, mut because) = (None, None);
let mut i = 0;
while i < args.len() {
let word = args[i].as_str();
i += 1;
if is_help(word) {
return block_help();
} else if let Some(value) = word.strip_prefix("--because=") {
because = Some(value.to_string());
} else if word == "--because" {
let Some(value) = args.get(i) else {
return block_usage_error("--because needs a value");
};
i += 1;
because = Some(value.clone());
} else if word.starts_with('-') {
return block_usage_error(&format!("unknown argument `{word}`"));
} else if fingerprint.replace(word).is_some() {
return block_usage_error("revoke takes one fingerprint");
}
}
let Some(fingerprint) = fingerprint else {
return block_usage_error("revoke needs a fingerprint");
};
let because = because.unwrap_or_default();
if because.trim().is_empty() {
return block_usage_error("revoke needs --because <text>");
}
let Some(base) = block_base() else {
return ExitCode::from(1);
};
let fingerprint = match resolve_block_fp(&base, fingerprint) {
Ok(fingerprint) => fingerprint,
Err(code) => return code,
};
if let Err(why) = block_registry::revoke(&base, &fingerprint, &because) {
eprintln!(
"{BIN}: block: could not revoke fp:{}: {why}",
&fingerprint[..12]
);
return ExitCode::from(1);
}
eprintln!(
concat!(greenbelay_guard::bin!(), ": block: fp:{} is revoked"),
&fingerprint[..12]
);
if let Some(pilot) = block_registry::source_entry(&base, &fingerprint).or_else(|| {
block_registry::entries(&base, &fingerprint)
.into_iter()
.next()
}) {
let source = pilot.registered.source_repo.as_deref().unwrap_or("-");
println!("{source}\t{}\t-", pilot.registered.source_branch);
}
for copy in block_registry::copies(&base, &fingerprint) {
println!("{}\t{}\t{}", copy.repo, copy.branch, copy.commit);
}
ExitCode::SUCCESS
}
fn run_block_reinstate(args: &[String]) -> ExitCode {
if args.iter().any(|word| is_help(word)) {
return block_help();
}
let [given] = args else {
return block_usage_error("reinstate takes one fingerprint");
};
if given.starts_with('-') {
return block_usage_error(&format!("unknown argument `{given}`"));
}
let Some(base) = block_base() else {
return ExitCode::from(1);
};
let fingerprint = match resolve_block_fp(&base, given) {
Ok(fingerprint) => fingerprint,
Err(code) => return code,
};
let short = &fingerprint[..12];
if block_registry::revoked(&base, &fingerprint).is_none() {
eprintln!("{BIN}: block: fp:{short} was not revoked");
return ExitCode::SUCCESS;
}
if let Err(why) = block_registry::reinstate(&base, &fingerprint) {
eprintln!("{BIN}: block: could not reinstate fp:{short}: {why}");
return ExitCode::from(1);
}
eprintln!("{BIN}: block: fp:{short} reinstated");
ExitCode::SUCCESS
}
fn run_block_sha(args: &[String]) -> ExitCode {
let (mut dir, mut base) = (std::path::PathBuf::from("."), None);
let mut i = 0;
while i < args.len() {
let word = args[i].as_str();
i += 1;
if is_help(word) {
return block_help();
}
if word == "--" {
if let Some(extra) = args.get(i) {
return block_usage_error(&format!("unknown argument `{extra}`"));
}
break;
}
let (flag, attached) = match word.split_once('=') {
Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
_ => match (word.get(..2), word.get(2..)) {
(Some("-C"), Some(rest)) if !rest.is_empty() => ("-C", Some(rest.to_string())),
_ => (word, None),
},
};
if flag != "-C" && flag != "--base" {
eprintln!("{BIN}: block: unknown argument `{word}`; try `{BIN} block --help`");
return ExitCode::from(2);
}
let value = match attached {
Some(value) => value,
None => {
let Some(value) = args.get(i) else {
eprintln!("{BIN}: block: {flag} needs a value");
return ExitCode::from(2);
};
i += 1;
value.clone()
}
};
if value.is_empty() {
return block_usage_error(&format!("{flag} needs a non-empty value"));
}
if flag == "-C" {
dir = std::path::PathBuf::from(value);
} else {
base = Some(value);
}
}
let Some(repo) = push_target::toplevel(&dir) else {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": block: {} is not inside a git repository"
),
dir.display()
);
return ExitCode::from(1);
};
let Some(base) = base.or_else(|| {
git::default_ref(&repo, std::time::Instant::now() + BLOCK_GIT_BUDGET)
.map(|(reference, _)| reference)
}) else {
eprintln!(concat!(
greenbelay_guard::bin!(),
": block: no default branch of `origin` is known; pass --base <ref>"
));
return ExitCode::from(1);
};
let deadline = std::time::Instant::now() + BLOCK_GIT_BUDGET;
let Some(merge_base) =
git::stdout_bounded(&repo, &["merge-base", base.as_str(), "HEAD"], deadline)
else {
eprintln!("{BIN}: block: `git merge-base {base} HEAD` failed");
return ExitCode::from(1);
};
let diff = match block_fingerprint::diff_of(&repo, &merge_base, "HEAD", deadline) {
Ok(diff) => diff,
Err(why) => {
eprintln!("{BIN}: block: {why}");
return ExitCode::from(1);
}
};
match block_fingerprint::fingerprint_of_diff(&diff) {
Some(fingerprint) => {
println!("{}\t{}", fingerprint.full(), fingerprint.short());
ExitCode::SUCCESS
}
None => {
let path = block_fingerprint::binary_path(&diff).unwrap_or_default();
eprintln!(
"{BIN}: block: the diff has a binary file ({path}); a binary change is never a copy"
);
ExitCode::from(1)
}
}
}
const TREE_SHA_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" tree-sha [--block] [-C <dir>] [--] [<rev>]
The content id an implementation review and a preview approval bind to
(not attest's canonical tree): the sha256 of `git ls-tree -r -z` of <rev>
(default HEAD) with every entry under docs/plans/ left out, 64 hex in any
object format (attest SPEC, \"Content id\"). Recording the review in the
plan, or adding a plan, therefore never changes it; a code change does
(ADR-0022, ADR-0034, work.implementation-review).
--block the review block the implementation-review agent's prompt
carries: <<<TREE repo=<name> sha=<64 hex>>>>, where <name>
is the basename of the directory holding the common .git
-C <dir> answer for the repository at <dir> (default: the current one)
Prints one line on stdout. Exit 0; 1 outside a repository or for a rev
that names no tree (the reason on stderr); 2 on a usage error.
"
);
fn run_tree_sha(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
let (mut block, mut dir, mut rev) = (false, None, None);
let mut i = 0;
let mut operands_only = false;
while i < args.len() {
let a = args[i].as_str();
match a {
_ if operands_only || !a.starts_with('-') => {
if rev.is_some() {
eprintln!(concat!(
greenbelay_guard::bin!(),
": tree-sha takes one rev; try `",
greenbelay_guard::bin!(),
" tree-sha --help`"
));
return ExitCode::from(2);
}
rev = Some(a.to_string());
}
"--" => operands_only = true,
"--help" | "-h" => {
print!("{TREE_SHA_USAGE}");
return ExitCode::SUCCESS;
}
"--block" => block = true,
"-C" => {
i += 1;
match args.get(i) {
Some(v) => dir = Some(std::path::PathBuf::from(v)),
None => {
eprintln!(concat!(greenbelay_guard::bin!(), ": -C needs a directory"));
return ExitCode::from(2);
}
}
}
other => {
eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} tree-sha --help`");
return ExitCode::from(2);
}
}
i += 1;
}
let dir = dir.unwrap_or_else(|| {
std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from("."))
});
let Some(repo) = push_target::toplevel(&dir) else {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": {} is not inside a git repository"
),
dir.display()
);
return ExitCode::from(1);
};
let rev = rev.as_deref().unwrap_or("HEAD");
let sha = match content_id::content_id(&repo, rev) {
Ok(s) => s,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(1);
}
};
if block {
let Some(name) = implementation_review::repo_name(&repo) else {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": the repository at {} has no name (git rev-parse --git-common-dir failed)"
),
repo.display()
);
return ExitCode::from(1);
};
println!("{}", implementation_review::block(&name, &sha));
} else {
println!("{sha}");
}
ExitCode::SUCCESS
}
const RULES_SHA_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" rules-sha [-C <dir>]
The lowercase sha256 hex of the stdout of
`aval --json rules --level constraint --governs code --full`, run in <dir>
(default: the current directory). An implementation-review brief carries it
as <<<RULES sha=<64 hex>>>>; the push check compares it.
Prints one line on stdout. Exit 0; 3 when aval is missing or fails (the
command on stderr, nothing on stdout); 2 on a usage error.
"
);
const REVIEW_BRIEF_USAGE: &str = concat!("\
usage: ", greenbelay_guard::bin!(), " review-brief [-C <dir>] [--plan <path>] [--base <ref>] [--profile <role>]
[--interdiff <head>]
The markdown brief an implementation reviewer is launched with: the
<<<TREE ...>>> block, the <<<RULES sha=...>>> line and adr-lint's
<<<CANDIDATES ...>>> block (paste them verbatim into the reviewer prompt),
the plan's Verification section, the diff since the merge-base, the
candidates, the code rules in full (a --profile brief: its own judge rules
and an index of the rest, ADR-0065), the constraint rules, the decisions that
bear on the changed files, and the plan's Non-goals. A repository with no
.adr.yaml gets no rules line and a note that no decided code rules apply.
adr-lint is `adr-lint` from PATH, or $GREENBELAY_ADR_LINT; when it cannot
answer, the block is <<<CANDIDATES unavailable>>> and the brief goes on.
-C <dir> the repository (default: the current directory)
--plan <path> the plan (default: the one file under docs/plans/ changed
since the merge-base; the brief says when there is none
or several)
--base <ref> the base ref (default: the remote's default branch)
--profile <role>
a code-review profile (backend, platform, unix, tui,
react, ui-design, architect or lang:<x>): adds a `Profile:
<role>` line, the judge rules
whose `Reviewed by:` names that role, and the plan's Goal
and Behaviour. lang:<x>, react, ui-design and platform get
only their file types' part of the diff (renames as a
deletion and an addition), the stat whole and the other
files under `## Not in this brief`; the count is on
stderr. Without it the plan section carries the plan's
declared code review.
--interdiff <head>
a delta brief: the same headers, then only what changed
since <head> (7-64 hex digits: the head an earlier review
read, as the push check's stale line names it): the plain
diff when <head> is an ancestor of HEAD, else the diff
between the two branch patches. Refused (exit 1, naming
the brief to build) when <head> cannot be read, the rule
files changed since it, this role's last passed review of
the branch read another head, or what changed is 60 KB or more; it
is never cut.
Exit 0; 1 when the repository or its base cannot be read; 3 when aval is missing or fails (nothing on
stdout); 2 on a usage error.
");
struct BriefFlags {
dir: std::path::PathBuf,
plan: Option<std::path::PathBuf>,
base: Option<String>,
profile: Option<String>,
interdiff: Option<String>,
}
struct BriefCommand {
name: &'static str,
usage: &'static str,
flags: &'static [&'static str],
}
const RULES_SHA_COMMAND: BriefCommand = BriefCommand {
name: "rules-sha",
usage: RULES_SHA_USAGE,
flags: &["-C"],
};
const REVIEW_BRIEF_COMMAND: BriefCommand = BriefCommand {
name: "review-brief",
usage: REVIEW_BRIEF_USAGE,
flags: &["-C", "--plan", "--base", "--profile", "--interdiff"],
};
fn brief_flags(command: &BriefCommand, args: &[OsString]) -> Result<BriefFlags, ExitCode> {
let BriefCommand {
name,
usage,
flags: accepted,
} = command;
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
if args.iter().any(|a| a == "--help" || a == "-h") {
print!("{usage}");
return Err(ExitCode::SUCCESS);
}
let mut flags = BriefFlags {
dir: std::path::PathBuf::from("."),
plan: None,
base: None,
profile: None,
interdiff: None,
};
let mut i = 0;
while i < args.len() {
let word = args[i].as_str();
i += 1;
if word == "--" {
if let Some(operand) = args.get(i) {
eprintln!("{BIN}: {name}: unknown argument `{operand}`; try `{BIN} {name} --help`");
return Err(ExitCode::from(2));
}
break;
}
let (flag, attached) = match word.split_once('=') {
Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
_ => match (word.get(..2), word.get(2..)) {
(Some(short), Some(rest))
if !rest.is_empty() && !word.starts_with("--") && accepted.contains(&short) =>
{
(short, Some(rest.to_string()))
}
_ => (word, None),
},
};
if !accepted.contains(&flag) {
eprintln!("{BIN}: {name}: unknown argument `{word}`; try `{BIN} {name} --help`");
return Err(ExitCode::from(2));
}
let value = match attached {
Some(value) => value,
None => {
let Some(value) = args.get(i) else {
eprintln!("{BIN}: {name}: {flag} needs a value");
return Err(ExitCode::from(2));
};
i += 1;
value.clone()
}
};
match flag {
"-C" => flags.dir = std::path::PathBuf::from(value),
"--plan" => flags.plan = Some(std::path::PathBuf::from(value)),
"--base" => flags.base = Some(value),
"--interdiff" => {
let hex = value.bytes().all(|b| b.is_ascii_hexdigit());
if !hex || !(7..=64).contains(&value.len()) {
eprintln!(
"{BIN}: {name}: --interdiff takes a commit id (7 to 64 hex digits), not `{value}`"
);
return Err(ExitCode::from(2));
}
flags.interdiff = Some(value);
}
"--profile" => {
if !code_review::valid_profile(&value) {
eprintln!(
"{BIN}: {name}: unknown profile `{value}`; try `{BIN} {name} --help`"
);
return Err(ExitCode::from(2));
}
flags.profile = Some(value);
}
_ => {
unreachable!("`accepted` holds only -C, --plan, --base, --profile and --interdiff")
}
}
}
Ok(flags)
}
fn run_rules_sha(args: &[OsString]) -> ExitCode {
let flags = match brief_flags(&RULES_SHA_COMMAND, args) {
Ok(f) => f,
Err(code) => return code,
};
match review_brief::rules_sha(&flags.dir) {
Ok(sha) => {
println!("{sha}");
ExitCode::SUCCESS
}
Err(why) => {
eprintln!("{BIN}: {why}");
ExitCode::from(3)
}
}
}
fn run_review_brief(args: &[OsString]) -> ExitCode {
let flags = match brief_flags(&REVIEW_BRIEF_COMMAND, args) {
Ok(f) => f,
Err(code) => return code,
};
let request = review_brief::BriefRequest {
dir: flags.dir,
plan: flags.plan,
base: flags.base,
profile: flags.profile,
interdiff: flags.interdiff,
};
match review_brief::build(&request) {
Ok(brief) => {
for notice in &brief.notices {
eprintln!("{BIN}: review-brief: {notice}");
}
print!("{}", brief.text);
ExitCode::SUCCESS
}
Err(review_brief::BriefError::Aval(why)) => {
eprintln!("{BIN}: {why}");
ExitCode::from(3)
}
Err(review_brief::BriefError::Repository(why)) => {
eprintln!("{BIN}: {why}");
ExitCode::from(1)
}
Err(review_brief::BriefError::DeltaRefused(why)) => {
eprintln!("{BIN}: review-brief: {why}");
ExitCode::from(1)
}
}
}
const PLAN_PANEL_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" plan-panel [--code-review [-C <dir>] [--base <ref>]]
<plan.md>
The review agents a plan still needs, computed as the plan-review-panel
hook will judge it at ExitPlanMode, and whether this is the whole panel or
a delta since the plan's last accepted body. The seats come from the file
types of the paths in backticks under the plan's `## Phases` (seats=paths),
each attributed to the repository of the machine comment
(`<!-- panel: repos=... adds=... -->`) that holds it; when the Phases name
no path, from every area of those repositories (seats=areas), with advice
on stderr to name the files. adds= declares what no path shows: cli, ui,
screen, ops, contract, lang:<language>.
First line: repos=<names> areas=<classes> body=<12 hex>
panel=full|delta|current seats=paths|areas
(areas= lists the classes the seats came from, one line in the output).
Then one line per agent to launch: `plan-review-<role>`, and `--lang <l>`
for a language review (the flag its `plan-sha --block` call takes).
--code-review prints, instead, the code-review profiles proposed for each
repository of the machine comment, from the file types of the paths the
Phases name in it (from its areas when the seats come from areas): one
line `<repo>\t<profiles comma-separated>`, or `<repo>\tnone\t<reason>`
with the reason `markdown only`, `no reviewed file type`, `no file named`
or `no language area`; `cut -f2` reads `none`, and the line pastes as
`- <repo>: none — <reason>`. A plan's `## Code review` section
(`- <repo>: <profiles>` or `- <repo>: none — <reason>`, after Non-goals)
declares them; without the flag a plan with no such section is warned
about on stderr and the output above is unchanged.
-C <dir> with --code-review: also read the branch of the repository
at <dir>; a registered, unrevoked, pin-checked copy of a
reviewed block is proposed as `<repo>\tnone\tcopy of fp:<id>`
while the implementation-review hook enforces; otherwise
the profiles are proposed, with the cause on stderr
--base <ref> the branch starts at its merge base with <ref> (default:
origin's default branch); needs --code-review, like -C
(without it: exit 2)
Exit 0, 1 when the plan cannot be read, its comment is wrong or its Code
review section does not parse (the reason on stderr), 2 on a usage error.
"
);
fn plan_panel_branch(lines: &str, dir: Option<&str>, base: Option<&str>) -> Result<String, String> {
if dir.is_none() && base.is_none() {
return Ok(lines.to_string());
}
let hook = greenbelay_guard::stance::resolve(&implementation_review_rule::RULE);
let branch =
code_review::branch_proposal(std::path::Path::new(dir.unwrap_or(".")), base, hook)?;
for notice in &branch.notices {
eprintln!("{notice}");
}
let Some(id) = branch.copy_of else {
return Ok(lines.to_string());
};
let reason = code_review::NoReviewReason::CopyOf(id);
let mut out = String::new();
for line in lines.lines() {
if line.split('\t').next() == Some(branch.repo.as_str()) {
out.push_str(&format!("{}\tnone\t{reason}\n", branch.repo));
} else {
out.push_str(line);
out.push('\n');
}
}
Ok(out)
}
fn run_plan_panel(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
if args.iter().any(|a| a == "--help" || a == "-h") {
print!("{PLAN_PANEL_USAGE}");
return ExitCode::SUCCESS;
}
let mut proposing = false;
let (mut branch_dir, mut branch_base): (Option<String>, Option<String>) = (None, None);
let mut operands: Vec<&String> = Vec::new();
let mut i = 0;
while i < args.len() {
let word = args[i].as_str();
i += 1;
if word == "--code-review" {
proposing = true;
continue;
}
let (flag, attached) = match word.split_once('=') {
Some((long, value)) if long.starts_with("--") => (long, Some(value.to_string())),
_ => match (word.get(..2), word.get(2..)) {
(Some("-C"), Some(rest)) if !rest.is_empty() => ("-C", Some(rest.to_string())),
_ => (word, None),
},
};
if flag != "-C" && flag != "--base" {
operands.push(&args[i - 1]);
continue;
}
let value = match attached {
Some(value) => value,
None => {
let Some(value) = args.get(i) else {
eprintln!("{BIN}: plan-panel: {flag} needs a value");
return ExitCode::from(2);
};
i += 1;
value.clone()
}
};
if flag == "-C" {
branch_dir = Some(value);
} else {
branch_base = Some(value);
}
}
if !proposing && (branch_dir.is_some() || branch_base.is_some()) {
eprint!("{BIN}: plan-panel: -C and --base need --code-review\n\n{PLAN_PANEL_USAGE}");
return ExitCode::from(2);
}
let [file] = operands.as_slice() else {
eprint!("{BIN}: plan-panel takes one plan file\n\n{PLAN_PANEL_USAGE}");
return ExitCode::from(2);
};
let text = match code_review::read_plan(std::path::Path::new(file)) {
Ok(text) => text,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(1);
}
};
match code_review::parse(&text) {
Err(why) => {
eprintln!("{BIN}: plan-panel: ## Code review: {why}");
return ExitCode::from(1);
}
Ok(None) if !proposing => eprintln!(
concat!(greenbelay_guard::bin!(), ": plan-panel: no ## Code review section; run plan-panel --code-review and add it after ## Non-goals")
),
Ok(_) => {}
}
if proposing {
return match code_review::proposal(&text) {
Ok(lines) => {
let lines = match plan_panel_branch(
&lines,
branch_dir.as_deref(),
branch_base.as_deref(),
) {
Ok(lines) => lines,
Err(why) => {
eprintln!("{BIN}: plan-panel: {why}");
return ExitCode::from(1);
}
};
print!("{lines}");
ExitCode::SUCCESS
}
Err(why) => {
eprintln!("{BIN}: {why}");
ExitCode::from(1)
}
};
}
match plan_review::panel(std::path::Path::new(file)) {
Ok(p) => {
if let Some(note) = &p.id_note {
eprintln!("{BIN}: plan-panel: {note}");
}
for line in &p.misplaced_steps {
eprintln!(
"{BIN}: plan-panel: {file}:{line}: steps block outside ## Phases; not counted. Move it under ## Phases."
);
}
let areas = p.classes.iter().cloned().collect::<Vec<_>>().join(",");
println!(
"repos={} areas={} body={} panel={} seats={} {}",
p.repos,
if areas.is_empty() { "-" } else { &areas },
&p.sha[..12],
p.mode,
p.source.as_str(),
p.counts
);
if let Some(advice) = &p.advice {
eprintln!("{BIN}: plan-panel: {advice}");
}
for role in &p.needed {
let cut = if p.sliced.contains(role) {
format!(" --slice {role}")
} else {
String::new()
};
match plan_review::agent_for(role) {
(agent, Some(lang)) => println!("{agent} --lang {lang}{cut}"),
(agent, None) => println!("{agent}{cut}"),
}
}
ExitCode::SUCCESS
}
Err(why) => {
eprintln!("{BIN}: {why}");
ExitCode::from(1)
}
}
}
const PREVIEW_USAGE: &str = concat!(
"\
usage: ",
greenbelay_guard::bin!(),
" preview register --url <url> --guide <file.md> [--repo <dir>] [--open]
Validate a localhost preview of the repository's HEAD, for the person to
approve before a UI-changing push (ADR-0023), and render its guide to a
page (work.preview-is-guided). Run it in the foreground as the last
command of its line (`cd <wt> && npm run build && ",
greenbelay_guard::bin!(),
" preview
register …` is fine; nothing piped, redirected or after it): the Claude
Code hook binds its output to the session.
--url <url> where the clean worktree is served (http or https)
--guide <file.md> what the person needs to decide with. Must be OUTSIDE
the worktree (it and its page would dirty the commit
they describe) and carry these H2 sections, emoji
and case aside:
## Where we are project, branch, plan, why
they are asked
## What you should see in their words; \"nothing
new\" when that is the point
## Try it numbered steps (`1. ...`):
the URL, each click by its
label, what should appear
## Reference 

## Already checked what you verified, and what
to look at especially
A heading may carry a note: `## Try it (2 min)`.
Images are relative to the guide's directory; two
named *before* and *after* show side by side.
Mockup mode: when the branch (from its merge base
with the default branch) commits a picked mockup's
artboards (`*.dc.html` under docs/mockups/<screen>, or
`git config greenbelay.preview.mockups`), the guide
must also show, under ## Reference, the screen path,
`Viewport: <width>px · <theme>`, and the artboard
beside the built screen as files next to it
(artboard.png / after.png; also mockup / live, and
state pairs such as artboard-empty.png /
after-empty.png), plus a section
## Differences from the mockup
`None`, or bullets
`- fixed: …` /
`- deliberate: <reason>`
Copy the images beside the guide as their own step,
before this command.
--repo <dir> the repository (default: the current directory)
--open open the rendered page with the platform opener; a
failure to open never fails the command
--attestation <f> DEPRECATED alias of --guide, for one release: read as
the guide, and refused unless it is one
Writes index.html beside the guide and prints one JSON object, on one
line, on stdout: id, repo, commit, url, guide, page, page_url, label,
aliases, question_prefix. Start the marked question with `question_prefix`
(`[preview <id>] <label>`), verbatim: the id is what approves. Exit 0 when
valid, 1 when refused (the reason on stderr), 2 on a usage error.
example:
",
greenbelay_guard::bin!(),
" preview register --url http://localhost:5173/settings \\
--guide ~/.claude/greenbelay/attestations/abc1234/guide.md
"
);
fn run_preview(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
if args.is_empty() || args.iter().any(|a| a == "--help" || a == "-h") {
print!("{PREVIEW_USAGE}");
return if args.is_empty() {
ExitCode::from(2)
} else {
ExitCode::SUCCESS
};
}
if args[0] != "register" {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": unknown preview command `{}`; try `",
greenbelay_guard::bin!(),
" preview --help`"
),
args[0]
);
return ExitCode::from(2);
}
let (mut url, mut guide, mut attestation, mut repo) = (None, None, None, None);
let mut open = false;
let mut i = 1;
while i < args.len() {
if args[i] == "--open" {
open = true;
i += 1;
continue;
}
let (flag, inline) = match args[i].split_once('=') {
Some((f, v)) if f.starts_with("--") => (f.to_string(), Some(v.to_string())),
_ => (args[i].clone(), None),
};
let value = match inline {
Some(v) => v,
None => {
i += 1;
match args.get(i) {
Some(v) => v.clone(),
None => {
eprintln!("{BIN}: {flag} needs a value");
return ExitCode::from(2);
}
}
}
};
match flag.as_str() {
"--url" => url = Some(value),
"--guide" => guide = Some(value),
"--attestation" => attestation = Some(value),
"--repo" => repo = Some(value),
other => {
eprintln!("{BIN}: unknown flag `{other}`; try `{BIN} preview --help`");
return ExitCode::from(2);
}
}
i += 1;
}
let guide = match (guide, attestation) {
(Some(g), None) => g,
(Some(g), Some(_)) => {
eprintln!(concat!(
greenbelay_guard::bin!(),
": --attestation is deprecated and ignored beside --guide"
));
g
}
(None, Some(a)) => {
eprintln!(
concat!(greenbelay_guard::bin!(), ": --attestation is deprecated; use --guide. It is read as the guide, and refused unless it is one (see `", greenbelay_guard::bin!(), " preview --help`)")
);
a
}
(None, None) => {
eprintln!(
concat!(greenbelay_guard::bin!(), ": preview register needs --guide <file.md>: the person is guided, not quizzed (see `", greenbelay_guard::bin!(), " preview --help`)")
);
return ExitCode::from(2);
}
};
let Some(url) = url else {
eprintln!(concat!(
greenbelay_guard::bin!(),
": preview register needs --url"
));
return ExitCode::from(2);
};
let cwd = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let dir = repo.map(PathBuf::from).unwrap_or_else(|| cwd.clone());
let dir = if dir.is_absolute() {
dir
} else {
cwd.join(dir)
};
match preview::register(&dir, &url, std::path::Path::new(&guide)) {
Ok(mut r) => {
if r.unchanged {
eprintln!(concat!(greenbelay_guard::bin!(), ": before and after are byte-identical; the hook approves this preview as unchanged when it binds it, if they still are"));
}
if open {
r.opened = Some(open_page(std::path::Path::new(&r.page)));
}
println!("{}", r.to_json());
ExitCode::SUCCESS
}
Err(why) => {
eprintln!("{BIN}: preview not registered: {why}");
ExitCode::from(1)
}
}
}
fn open_page(page: &std::path::Path) -> bool {
match open::open_url(&greenbelay_process::guide::file_url(page)) {
Ok(()) => true,
Err(why) => {
eprintln!("{BIN}: {why}");
false
}
}
}
fn run_check(args: &[OsString]) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
if f.rest.len() != 1 {
eprintln!(concat!(
greenbelay_guard::bin!(),
": check needs exactly one command, quoted"
));
return ExitCode::from(2);
}
let src = &f.rest[0];
let parsed = shell::lex(src);
let input = rules::Input::new(src, f.dialect.unwrap_or(rules::Dialect::Unknown), &parsed);
let found = rules::evaluate(rule_table::RULES, &input);
if found.is_empty() {
match &parsed {
shell::Parsed::Opaque(why) => println!("no opinion: {}", why.why()),
_ => println!("no rule fires"),
}
return ExitCode::SUCCESS;
}
let cwd = match f.cwd.clone().map(Ok).unwrap_or_else(std::env::current_dir) {
Ok(dir) => dir,
Err(e) => {
eprintln!("{BIN}: check: the working directory cannot be read: {e}");
return ExitCode::from(2);
}
};
let mut printed = 0;
for (rule, finding) in found {
let mut now = stance::resolve(rule);
let mut reason = finding.reason.clone();
let mut remedy = finding.remedy.clone();
if rule.confirm.is_some() {
match hook::confirmed_for_check(rule, &finding, src, &cwd, &parsed) {
Ok(checked) => {
now = checked.stance;
if let Some((said, said_remedy)) = checked.said {
reason = said;
if let Some(said_remedy) = said_remedy {
remedy = said_remedy;
}
}
}
Err(why) => {
if f.explain {
println!("{} not confirmed: {why}", rule.id);
}
continue;
}
}
}
printed += 1;
if now == rule.default_stance {
println!("{} [{}]", rule.id, now.as_str());
} else {
println!(
"{} [{}, ships as {}]",
rule.id,
now.as_str(),
rule.default_stance.as_str()
);
}
println!(" {reason}");
println!(" → {remedy}");
println!(
" ▸ {}",
backtest::excerpt(src, finding.span.start, finding.span.end)
);
}
if printed == 0 {
match &parsed {
shell::Parsed::Opaque(why) => println!("no opinion: {}", why.why()),
_ => println!("no rule fires"),
}
}
name_the_unread(src, &parsed);
ExitCode::SUCCESS
}
fn name_the_unread(src: &str, parsed: &shell::Parsed) {
let clauses = parsed.clauses();
for (i, cmd) in clauses.iter().enumerate() {
let Some(why) = &cmd.opaque else { continue };
if cmd.prev.is_some_and(|c| c.is_pipe()) {
continue;
}
let mut end = i;
while clauses[end].next.is_some_and(|c| c.is_pipe()) && end + 1 < clauses.len() {
end += 1;
}
println!(" ⋯ not read: {}", why.why());
println!(" {}", backtest::excerpt(src, cmd.at, clauses[end].end));
}
}
fn stance_shown(now: rules::Stance, ships: rules::Stance) -> String {
if now == ships {
now.as_str().to_string()
} else {
format!("{} (ships as {})", now.as_str(), ships.as_str())
}
}
const RULES_USAGE: &str = concat!("usage: ", greenbelay_guard::bin!(), " rules [--json]\n");
fn run_rules(args: &[OsString]) -> ExitCode {
let args: Vec<String> = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect();
if args.iter().any(|a| a == "-h" || a == "--help") {
print!("{RULES_USAGE}");
return ExitCode::SUCCESS;
}
match args.as_slice() {
[] => print_rules_text(),
[a] if a == "--json" => print_rules_json(),
[a, rest @ ..] if a == "--json" => {
eprintln!(
concat!(
greenbelay_guard::bin!(),
": unexpected argument `{}`; `rules` takes only --json"
),
rest[0]
);
ExitCode::from(2)
}
[a, ..] => {
eprintln!("{BIN}: unknown argument `{a}`; `rules` takes only --json");
ExitCode::from(2)
}
}
}
fn print_rules_json() -> ExitCode {
let entry = |id: &str,
kind: &str,
ships: rules::Stance,
now: rules::Stance,
max: rules::Stance,
e: &rules::Evidence,
prevents: &str,
irreversible: bool| {
json::object(&[
json::string_field("id", id),
json::string_field("kind", kind),
json::string_field("default_stance", ships.as_str()),
json::string_field("stance", now.as_str()),
json::string_field("max_stance", max.as_str()),
json::float_field("per_1000", e.per_1000),
json::string_field("measured", e.measured),
json::string_field("prevents", prevents),
json::bool_field("irreversible", irreversible),
])
};
let mut items: Vec<String> = rule_table::RULES
.iter()
.map(|r| {
entry(
r.id,
"rule",
r.default_stance,
stance::resolve(r),
r.max_stance,
&r.evidence,
r.prevents,
r.irreversible,
)
})
.collect();
items.extend(assertions::ASSERTIONS.iter().map(|a| {
entry(
a.id,
"assertion",
a.default_stance,
stance::resolve_assertion(a),
rules::Stance::Deny,
&a.evidence,
a.prevents,
a.irreversible,
)
}));
println!("{}", json::array(&items));
ExitCode::SUCCESS
}
fn print_rules_text() -> ExitCode {
let w = ui::id_column(rule_table::RULES);
let rule_stances: Vec<String> = rule_table::RULES
.iter()
.map(|r| stance_shown(stance::resolve(r), r.default_stance))
.collect();
let assertion_stances: Vec<String> = assertions::ASSERTIONS
.iter()
.map(|a| stance_shown(stance::resolve_assertion(a), a.default_stance))
.collect();
let s = rule_stances
.iter()
.chain(&assertion_stances)
.map(String::len)
.max()
.unwrap_or(0)
.max(8);
for (r, shown) in rule_table::RULES.iter().zip(&rule_stances) {
let ceiling = if r.max_stance < rules::Stance::Deny {
format!(" (max {})", r.max_stance.as_str())
} else {
String::new()
};
println!(
"{:<w$}{:<s$} {:>6.1}/1000 measured {}{ceiling}",
r.id, shown, r.evidence.per_1000, r.evidence.measured
);
}
for (a, shown) in assertions::ASSERTIONS.iter().zip(&assertion_stances) {
println!(
"{:<w$}{:<s$} {:>6.1}/1000 measured {} (assertion)",
a.id, shown, a.evidence.per_1000, a.evidence.measured
);
}
ExitCode::SUCCESS
}
fn run_install(args: &[OsString], adding: bool) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
let scope = if f.local {
settings::Scope::ProjectLocal
} else if f.project {
settings::Scope::Project
} else {
settings::Scope::User
};
let project = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
let Some(path) = scope.path(&project) else {
eprintln!(concat!(
greenbelay_guard::bin!(),
": cannot find your Claude Code settings directory"
));
return ExitCode::from(2);
};
let bin = match std::env::current_exe() {
Ok(b) => b,
Err(e) => {
eprintln!("{BIN}: cannot resolve my own path: {e}");
return ExitCode::from(2);
}
};
let plugin = plugin_install::placement();
if plugin.is_none() {
eprintln!(
"{BIN}: no state directory resolves (XDG_STATE_HOME, CLAUDE_CONFIG_DIR, HOME), so the clear-relay plugin is left out"
);
}
let planned = if adding {
settings::plan_install(&path, &bin, f.reformat, plugin.as_ref())
} else {
settings::plan_uninstall(&path, f.reformat, plugin.as_ref())
};
let plan = match planned {
Ok(p) => p,
Err(e) => {
eprintln!(concat!(greenbelay_guard::bin!(), ": {}"), e.explain());
if adding {
eprintln!("\n{}", settings::snippet(&bin));
}
return ExitCode::from(2);
}
};
if !f.write {
if matches!(plan.change, settings::Change::RemoveFile) {
println!(
"{} would be removed: nothing else is left in it.",
plan.path.display()
);
if let Some(dir) = &plan.remove_dir {
println!("would remove {}", dir.display());
}
println!("Nothing written. Re-run with --write to apply.");
return ExitCode::SUCCESS;
}
println!("{}", plan.change.describe(&plan.path));
for (dest, _) in &plan.files {
println!("would write {}", dest.display());
}
if let Some(dir) = &plan.remove_dir {
println!("would remove {}", dir.display());
}
println!("Nothing written. Re-run with --write to apply:\n");
print!("{}", plan.after);
if adding && plugin.is_some() {
print_install_registry(RegistryVoice::WouldThenNeed);
}
return ExitCode::SUCCESS;
}
if matches!(plan.change, settings::Change::WouldReformat) {
eprintln!("{}\n", plan.change.describe(&plan.path));
eprint!("{}", settings::snippet(&bin));
return ExitCode::from(2);
}
match settings::apply(&plan) {
Ok(()) => {
println!("{}", plan.change.describe(&plan.path));
for (dest, _) in &plan.files {
eprintln!("wrote {}", dest.display());
}
if adding && !plan.files.is_empty() {
if let Some(placement) = &plugin {
eprintln!(
"enabled {}@{}: an answer ending \"safe to /clear; next: `<prompt>`\"",
placement.plugin, placement.marketplace
);
eprintln!(
" clears the session after 10 s, then submits <prompt> (type or /stay to keep it); remove: {BIN} uninstall --write"
);
}
}
if adding && plugin.is_some() {
print_install_registry(RegistryVoice::Run);
}
if let Some(dir) = &plan.remove_dir {
eprintln!("removed {}", dir.display());
}
ExitCode::SUCCESS
}
Err(e) => {
eprintln!(
"{BIN}: could not apply the change to {} and the clear-relay plugin: {e}",
plan.path.display()
);
ExitCode::from(2)
}
}
}
fn print_install_registry(voice: RegistryVoice) {
if let Some(env) = greenbelay_guard::migrate::Env::from_process() {
print_registry(
&migrate_plugin::registry_state_for(
&env,
greenbelay_guard::migrate::Direction::Forward,
),
voice,
);
}
}
const SEEN_WINDOW: u64 = 30 * 24 * 60 * 60;
fn plan_root_finding() -> doctor::Finding {
use plan_review::{RootSource, ROOT_REMEDY};
match plan_review::resolved_root() {
Some((path, RootSource::CwdFallback)) => doctor::Finding::warn(
format!("plan root: {} (cwd fallback)", path.display()),
format!("plan review falls back to the working directory and the attestations sweep removes nothing; {ROOT_REMEDY}"),
),
Some((path, source)) => doctor::Finding::good(format!(
"plan root: {} ({})",
path.display(),
source.label()
)),
None => doctor::Finding::warn(
"plan root: unset",
format!("plan review cannot resolve repos= and the attestations sweep removes nothing; {ROOT_REMEDY}"),
),
}
}
fn run_status() -> ExitCode {
let w = ui::id_column(rule_table::RULES);
let seen = journal::tally(SEEN_WINDOW);
println!(
"{:<w$}{:<10}{:<10} {:<31} seen, last 30 days",
"rule", "ships as", "now", "evidence"
);
for r in rule_table::RULES {
let now = stance::resolve(r);
println!(
"{:<w$}{:<10}{:<10} {:<31} {}",
r.id,
r.default_stance.as_str(),
now.as_str(),
format!(
"{:.1}/1000 measured {}",
r.evidence.per_1000, r.evidence.measured
),
describe_seen(seen.get(r.id))
);
}
if let Some(p) = journal::path() {
println!("\njournal: {}", p.display());
}
ExitCode::SUCCESS
}
fn describe_seen(seen: Option<&journal::Seen>) -> String {
let Some(s) = seen.filter(|s| s.total() > 0) else {
return "-".to_string();
};
let mut parts = Vec::new();
for (n, what) in [
(s.denied, "denied"),
(s.advised, "advised"),
(s.watched, "watched"),
] {
if n > 0 {
parts.push(format!("{n} {what}"));
}
}
if s.unconfirmed > 0 {
match s.top_reason() {
Some((why, n)) if why != "skipped" => parts.push(format!(
"{} unconfirmed ({} \u{d7}{n})",
s.unconfirmed,
why.replace('_', " ")
)),
_ => parts.push(format!("{} unconfirmed", s.unconfirmed)),
}
}
parts.join(", ")
}
fn run_corpus(args: &[OsString]) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
match f.rest.first().map(String::as_str) {
Some("check") | None => {}
Some(other) => {
eprintln!("{BIN}: corpus takes `check`, not `{other}`");
return ExitCode::from(2);
}
}
let mut healthy = true;
let w = ui::id_column(rule_table::RULES);
for rule in rule_table::RULES {
let score = corpus::score_with(rule, Some(greenbelay_process::clear_boundary::stop_judge));
if score.reviewed == 0 && score.unreviewed == 0 {
println!("{:<w$}no cases yet", rule.id);
continue;
}
let precision = match score.precision() {
Some(p) => format!("{:.0}%", p * 100.0),
None => "unmeasured".to_string(),
};
println!(
"{:<w$}{} reviewed ({} negative), {} unreviewed, precision {precision}",
rule.id, score.reviewed, score.negatives, score.unreviewed
);
for d in &score.disagreements {
healthy = false;
let path = corpus::path_for(rule.id);
let shown = if path.exists() {
path.display().to_string()
} else {
format!("{}.cases", rule.id)
};
match &d.fixture {
Some(fixture) => println!(
" {}:{} expected {} — {} ({fixture}): {}",
shown,
d.line,
d.expected.as_str(),
corpus::escape(&d.command),
d.why
),
None => println!(
" {}:{} expected {} — {}: {}",
shown,
d.line,
d.expected.as_str(),
corpus::escape(&d.command),
d.why
),
}
}
}
if healthy {
ExitCode::SUCCESS
} else {
ExitCode::FAILURE
}
}
fn run_graduate(args: &[OsString], promoting: bool) -> ExitCode {
let f = match flags(args) {
Ok(f) => f,
Err(why) => {
eprintln!("{BIN}: {why}");
return ExitCode::from(2);
}
};
let Some(id) = f.rest.first() else {
eprintln!(concat!(greenbelay_guard::bin!(), ": name a rule"));
return ExitCode::from(2);
};
let Some(rule) = rules::by_id(rule_table::RULES, id) else {
let known: Vec<&str> = rule_table::RULES.iter().map(|r| r.id).collect();
eprintln!("{BIN}: no rule `{id}` — known: {}", known.join(", "));
return ExitCode::from(2);
};
let to = if promoting {
let Some(to) = f.to.as_deref().and_then(rules::Stance::parse) else {
eprintln!(concat!(
greenbelay_guard::bin!(),
": graduate needs --to advise|deny"
));
return ExitCode::from(2);
};
to
} else {
rules::Stance::Observe
};
let verdict = graduate::assess_score(
rule,
to,
&corpus::score_with(rule, Some(greenbelay_process::clear_boundary::stop_judge)),
);
for (ok, line) in &verdict.lines {
println!(
" {} {line}",
if *ok {
crate::ui::valid_sign()
} else {
crate::ui::error_sign()
}
);
}
if !verdict.allowed && !f.force {
let where_ = if corpus::checkout_present() {
corpus::path_for(rule.id).display().to_string()
} else {
format!(
concat!(
"crates/greenbelay-guard/tests/corpus/{}.cases # in a checkout of ",
greenbelay_guard::bin!()
),
rule.id
)
};
eprintln!(
concat!(
"\nrefusing to move {} to {}: not enough evidence.\n\
Review its matches first:\n \
",
greenbelay_guard::bin!(),
" explain {} --format cases >> {}\n\
then label each line and re-run. `--force` overrides and is recorded as forced."
),
rule.id,
to.as_str(),
rule.id,
where_
);
return ExitCode::from(2);
}
match graduate::set(rule, to) {
Ok(()) => {
println!(
"{} is now `{}`{}",
rule.id,
to.as_str(),
if verdict.allowed { "" } else { " (forced)" }
);
ExitCode::SUCCESS
}
Err(why) => {
eprintln!("{BIN}: could not record the stance: {why}");
ExitCode::from(2)
}
}
}
#[cfg(test)]
mod migration_mode_tests {
use super::*;
fn args(list: &[&str]) -> Vec<OsString> {
list.iter().map(OsString::from).collect()
}
#[test]
fn each_command_gets_its_migration_mode() {
assert_eq!(migration_mode(&Sub::Migrate, &[]), MigrationMode::Skip);
assert_eq!(migration_mode(&Sub::Doctor, &[]), MigrationMode::Skip);
assert_eq!(migration_mode(&Sub::Hook, &[]), MigrationMode::Zero);
assert_eq!(migration_mode(&Sub::Status, &[]), MigrationMode::Zero);
assert_eq!(migration_mode(&Sub::Uninstall, &[]), MigrationMode::Zero);
for flag in ["--help", "-h", "--version", "--dry-run", "--check"] {
assert_eq!(
migration_mode(&Sub::PlanApply, &args(&[flag])),
MigrationMode::Skip,
"{flag}"
);
assert_eq!(
migration_mode(&Sub::Install, &args(&["--write", flag])),
MigrationMode::Skip,
"{flag}"
);
}
}
#[test]
fn install_waits_for_the_lock() {
assert!(matches!(
migration_mode(&Sub::Install, &args(&["--write"])),
MigrationMode::Capped(_)
));
}
}