use crate::{code, fed, lens, plan, slice, spec, split, state, tokens, wave};
use std::path::{Path, PathBuf};
use std::process::ExitCode;
mod parse;
use clap::Parser;
use parse::{Cmd, Verdict};
mod args;
use args::*;
mod propose;
use propose::*;
mod author;
use author::*;
mod adopt;
use adopt::*;
mod steps;
use steps::*;
mod measure;
use measure::*;
mod swift;
use swift::*;
mod check;
use check::*;
mod validate;
use validate::*;
mod plumb;
use plumb::*;
pub const USAGE: &str = "\
sherd -- federated SPEC.md for small-context local models
sherd init [dir] [--stdout] scaffold a SPEC.md, §F rows from child dirs
sherd budget [dir] [--format text|json] token cost of every node, against the working budget
sherd lens <dir> [--depth rule|why|all] the context pack for one node
sherd fed [dir] the federation edges declared by a node
sherd check [dir] [--format text|json] microlith structural check of every node
sherd debt [--check|--record] lint ratchet: density & shape vs .lint-debt
sherd coverage [--check|--record] coverage floor vs .coverage
sherd validate [--format text|json] DAG + ids + ceilings + slice drift, one verdict
sherd split [dir] propose a federation split. writes nothing
sherd seam [dir] the public types each node declares. writes nothing
sherd wave [dir] the rounds a parallel build would run. writes nothing
sherd adopt <dir> [--map FILE] [--check] migrate a single-file SPEC.md onto a federation
sherd sync [dir] [--check] regenerate §N from §F. exit 1 if it wrote
sherd route <query> which node owns a question. 0 hit · 2 miss · 3 ambiguous
sherd review [rev] mechanical checks on what a commit added (default HEAD)
sherd slice [--check|--list] regenerate distilled slices from their sources
sherd outcome <node> <kept|reverted> record whether a node's work survived review
sherd graph [--tree|--table|--dot] federation DAG, generated from §F
sherd plan [--format text|json] next 3 steps, with what would invalidate each
sherd plan --triage unmanaged rows, with a proposed home for each
sherd plan --milestone <M> [--format text|json] next 3 steps among the rows milestone M claims
sherd apply [--land] execute step 1 only, commit it to a run branch, stop
sherd land [--push] fast-forward main to this run branch, if it earned it
sherd ask <dir> <q> ask the endpoint from a node's lens pack
sherd tdd <dir> <Vn> <task> red -> judge -> green -> gate -> repair
sherd oneshot <dir> <Vn> <task> the monolith arm: one call, whole repo
sherd completions <shell> shell completion script (bash zsh fish elvish powershell)
sherd man the man page, roff, on stdout
-v, --verbose dump every prompt and stream every reply
-V, --version print `sherd <semver>` and exit 0
exit: 0 clean · 1 violation · 2 usage";
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
#[must_use]
pub fn run() -> ExitCode {
run_args(std::env::args().skip(1).collect())
}
#[must_use]
pub fn run_args(args: Vec<String>) -> ExitCode {
let cli = match parse::Cli::try_parse_from(
std::iter::once("sherd".to_string()).chain(args.iter().cloned()),
) {
Ok(c) => c,
Err(e) => {
let code = if e.use_stderr() { 2 } else { 0 };
let _ = e.print();
return ExitCode::from(code);
}
};
#[cfg(feature = "ollama")]
if cli.verbose {
crate::ollama::set_verbose(true);
}
let Some(mut cmd) = cli.cmd else {
println!("{USAGE}");
return ExitCode::SUCCESS;
};
let root = match at_of(&cmd) {
Some(at) => match root_at(at.as_deref()) {
Ok(r) => r,
Err(e) => return usage(&e),
},
None => {
let named: Vec<String> = std::iter::once("sherd".to_string())
.chain(dir_of(&cmd).map(String::from))
.collect();
let root = root_for(&named);
absolutize_dir(&mut cmd, &root, &cwd());
root
}
};
#[cfg(feature = "ollama")]
crate::ollama::load_pace();
dispatch(&root, cmd)
}
fn at_of(cmd: &Cmd) -> Option<&Option<String>> {
match cmd {
Cmd::Debt { at, .. }
| Cmd::Coverage { at, .. }
| Cmd::Validate { at, .. }
| Cmd::Graph { at, .. }
| Cmd::Route { at, .. }
| Cmd::Outcome { at, .. }
| Cmd::Slice { at, .. }
| Cmd::Review { at, .. }
| Cmd::Plan { at, .. }
| Cmd::Apply { at, .. }
| Cmd::Land { at, .. } => Some(&at.at),
_ => None,
}
}
fn absolutize_dir(cmd: &mut Cmd, root: &Path, here: &Path) {
if same_dir(&repo_root_from(here), root) {
return;
}
let fix = |d: &mut String| {
let p = here.join(&*d);
if p.is_dir() {
*d = p.to_string_lossy().into_owned();
}
};
match cmd {
Cmd::Init { dir, .. }
| Cmd::Budget { dir, .. }
| Cmd::Fed { dir }
| Cmd::Check { dir, .. }
| Cmd::Split { dir, .. }
| Cmd::Seam { dir }
| Cmd::Wave { dir, .. }
| Cmd::Sync { dir, .. } => {
if let Some(d) = dir {
fix(d);
}
}
Cmd::Lens { dir, .. }
| Cmd::Adopt { dir, .. }
| Cmd::Ask { dir, .. }
| Cmd::Tdd { dir, .. }
| Cmd::Oneshot { dir, .. } => fix(dir),
_ => {}
}
}
fn same_dir(a: &Path, b: &Path) -> bool {
match (a.canonicalize(), b.canonicalize()) {
(Ok(x), Ok(y)) => x == y,
_ => a == b,
}
}
fn dir_of(cmd: &Cmd) -> Option<&str> {
match cmd {
Cmd::Init { dir, .. }
| Cmd::Budget { dir, .. }
| Cmd::Fed { dir }
| Cmd::Check { dir, .. }
| Cmd::Split { dir, .. }
| Cmd::Seam { dir }
| Cmd::Wave { dir, .. }
| Cmd::Sync { dir, .. } => dir.as_deref(),
Cmd::Lens { dir, .. }
| Cmd::Adopt { dir, .. }
| Cmd::Ask { dir, .. }
| Cmd::Tdd { dir, .. }
| Cmd::Oneshot { dir, .. } => Some(dir),
_ => None,
}
}
fn root_at(at: Option<&str>) -> Result<PathBuf, String> {
let here = cwd();
let Some(a) = at else {
return Ok(repo_root_from(&here));
};
let p = here.join(a);
if p.is_dir() {
Ok(repo_root_from(&p))
} else {
Err(format!("`{a}` is not a directory"))
}
}
fn dispatch(root: &Path, cmd: Cmd) -> ExitCode {
match cmd {
Cmd::Budget { dir, format } => budget_as(
root,
&arg_dir(dir.as_deref(), root),
format.format.is_json(),
),
Cmd::Debt { check, record, .. } => debt_cmd(
root,
ratchet(check, record).map(Ratchet::flag),
&crate::land::cargo_bin(),
),
Cmd::Coverage { check, record, .. } => coverage_in(
root,
ratchet(check, record).map(Ratchet::flag),
&crate::land::cargo_bin(),
&crate::debt::swift_bin(),
),
Cmd::Lens { dir, depth } => {
lens_cmd(root, &arg_dir(Some(&dir), root), depth.into())
}
Cmd::Fed { dir } => fed_cmd(&arg_dir(dir.as_deref(), root)),
Cmd::Init { dir, stdout } => init_cmd(root, dir.as_deref(), stdout),
Cmd::Graph {
tree, table, dot, ..
} => {
let view = match (dot, table, tree) {
(true, _, _) => GraphView::Dot,
(_, true, _) => GraphView::Table,
(_, _, true) => GraphView::Tree,
_ => GraphView::Mermaid,
};
print!("{}", graph_render(root, view));
ExitCode::SUCCESS
}
Cmd::Check { format, .. } => check_as(root, format.format.is_json()),
Cmd::Validate { format, .. } if format.format.is_json() => {
validate_json_cmd(root)
}
Cmd::Validate { .. } => validate(root),
Cmd::Split { dir, apply } => split_cmd(
root,
&dir.map_or_else(|| root.to_path_buf(), |d| root.join(d)),
apply,
),
Cmd::Seam { dir } => seam_cmd(root, &arg_dir(dir.as_deref(), root)),
Cmd::Wave { dir, format } if format.format.is_json() => {
wave_json_cmd(root, &arg_dir(dir.as_deref(), root))
}
Cmd::Wave { dir, .. } => wave_cmd(root, &arg_dir(dir.as_deref(), root)),
Cmd::Adopt { dir, map, check } => {
adopt_cmd(root, &dir, map.as_deref(), check)
}
Cmd::Sync { dir, check } => {
sync_cmd(root, dir.map(|d| root.join(d)).as_ref(), check)
}
Cmd::Route { query, .. } => route_cmd(root, &query),
Cmd::Outcome { node, verdict, .. } => outcome_cmd(root, &node, verdict),
Cmd::Slice { check, list, .. } => slice_cmd(
root,
match (check, list) {
(true, _) => "--check",
(_, true) => "--list",
_ => "",
},
),
Cmd::Review { rev, .. } => {
review_cmd(root, rev.as_deref().unwrap_or("HEAD"))
}
Cmd::Plan {
format,
triage,
milestone,
..
} => {
let mode = match (triage, milestone) {
(true, _) => PlanMode::Triage,
(_, Some(m)) => PlanMode::Milestone(m),
_ => PlanMode::Current,
};
plan_verb(root, format.format.is_json(), mode)
}
Cmd::Land { push, .. } => land_verb(root, push),
Cmd::Completions { shell } => {
clap_complete::generate(
clap_complete::Shell::from(shell),
&mut parse::command(),
"sherd",
&mut std::io::stdout(),
);
ExitCode::SUCCESS
}
Cmd::Man => match clap_mangen::Man::new(parse::command())
.render(&mut std::io::stdout())
{
Ok(()) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("sherd: man: {e}");
ExitCode::from(1)
}
},
model => model_verb(root, model),
}
}
#[derive(Clone, Copy)]
enum Ratchet {
Check,
Record,
}
impl Ratchet {
const fn flag(self) -> &'static str {
match self {
Self::Check => "--check",
Self::Record => "--record",
}
}
}
fn ratchet(check: bool, record: bool) -> Option<Ratchet> {
match (check, record) {
(true, _) => Some(Ratchet::Check),
(_, true) => Some(Ratchet::Record),
_ => None,
}
}
#[derive(Clone, Copy)]
enum GraphView {
Dot,
Table,
Tree,
Mermaid,
}
fn graph_render(root: &Path, view: GraphView) -> String {
match view {
GraphView::Dot => fed::dot(root),
GraphView::Table => fed::table(root),
GraphView::Tree => fed::tree(root),
GraphView::Mermaid => fed::mermaid(root),
}
}
enum PlanMode {
Triage,
Milestone(String),
Current,
}
fn outcome_cmd(root: &Path, node: &str, verdict: Verdict) -> ExitCode {
let store = crate::state::resolve(
std::env::var("SHERD_STATE").ok(),
crate::state::git_common_dir(root),
);
outcome_in(&store, node, verdict)
}
fn outcome_in(store: &Path, node: &str, verdict: Verdict) -> ExitCode {
let mut st = crate::state::State::at(store);
plan::record_outcome_in(&mut st, Path::new(node), verdict.is_kept());
st.save();
let (tried, k) = plan::record_in(&st, Path::new(node));
eprintln!(
"{node}: {k}/{tried} kept · believability {:.2}",
plan::believability_in(&st, Path::new(node))
);
ExitCode::SUCCESS
}
fn plan_verb(root: &Path, json: bool, mode: PlanMode) -> ExitCode {
match mode {
PlanMode::Triage if json => {
usage("plan --triage has no --format json yet")
}
PlanMode::Triage => triage_cmd(root),
PlanMode::Milestone(m) if plan::milestone_declared(root, &m) => {
plan_cmd(root, Some(&m), json)
}
PlanMode::Milestone(m) => usage(&format!(
"no node declares milestone `{m}` -- a `| {m} |` row in some node's \u{a7}T"
)),
PlanMode::Current => plan_cmd(root, None, json),
}
}
#[cfg(not(feature = "ollama"))]
fn model_verb(_root: &Path, cmd: Cmd) -> ExitCode {
let verb = match cmd {
Cmd::Apply { .. } => "apply",
Cmd::Ask { .. } => "ask",
Cmd::Oneshot { .. } => "oneshot",
_ => "tdd",
};
needs_ollama(verb)
}
#[cfg(feature = "ollama")]
fn model_verb(root: &Path, cmd: Cmd) -> ExitCode {
match cmd {
Cmd::Apply { land, push, .. } => match plan::apply(root, 3) {
Ok(sha) => {
eprintln!(
"\napplied as {sha}. Run `sherd plan` again before the next step -- \
this commit changed the specs that plan it."
);
if land {
land_verb(root, push)
} else {
ExitCode::SUCCESS
}
}
Err(e) => {
eprintln!("sherd: {e}");
ExitCode::from(1)
}
},
Cmd::Ask { dir, question } => {
ask(root, &arg_dir(Some(&dir), root), &question)
}
Cmd::Oneshot {
dir,
invariant,
task,
} => {
let dir = arg_dir(Some(&dir), root);
let run = crate::tdd::Run::new(root, &dir, &invariant, &task);
match crate::tdd::oneshot(&run) {
Ok(_) => ExitCode::SUCCESS,
Err(e) => {
eprintln!("sherd: {e}");
ExitCode::from(1)
}
}
}
Cmd::Tdd {
dir,
invariant,
task,
} => tdd_cmd(root, &arg_dir(Some(&dir), root), &invariant, &task),
_ => ExitCode::from(2),
}
}
#[cfg(not(feature = "ollama"))]
fn needs_ollama(verb: &str) -> ExitCode {
eprintln!(
"sherd: `{verb}` needs the `ollama` feature, which this build does not \
carry. Install it with `cargo install sherd --features ollama`."
);
ExitCode::from(2)
}
fn land_verb(root: &Path, push: bool) -> ExitCode {
match crate::land::land(root, push) {
Ok(msg) => {
eprintln!("{msg}");
ExitCode::SUCCESS
}
Err(e) => {
eprintln!("sherd: not landing -- {e}");
eprintln!(
" the branch is untouched; it is the record of the try"
);
ExitCode::from(1)
}
}
}
fn usage(msg: &str) -> ExitCode {
eprintln!("sherd: {msg}\n\n{USAGE}");
ExitCode::from(2)
}
#[cfg(test)]
#[path = "tests/fixtures.rs"]
mod fixtures;
#[cfg(test)]
#[path = "tests/dispatch.rs"]
mod tests;
#[cfg(test)]
#[path = "tests/routes.rs"]
mod routes;
#[cfg(test)]
#[path = "tests/unread.rs"]
pub(crate) mod unread;
#[cfg(test)]
#[path = "tests/verdicts.rs"]
mod verdicts;