sherd 0.6.0

two-axis federation of SPEC.md and source over a dir DAG, for small-context local models
Documentation
//! Verbs `run_args` never reached in a test: each is driven through dispatch
//! against a fixture it cannot harm, and asserted on the exit code `§I`
//! documents. The verbs' own logic is tested where it lives; what these hold
//! is the ROUTE -- argv to the right function, with the root taken from argv.

use super::fixtures::*;
use super::*;
use crate::testrepo::TestRepo;

fn at(verb: &[&str], repo: &TestRepo) -> Vec<String> {
    let mut a = argv(verb);
    a.push(repo.path().display().to_string());
    a
}

/// `coverage` and `debt` route to the ratchets with the root from argv.
/// Neither fixture carries a ratchet file, so both are USAGE (2): nothing
/// to compare against is a bad argument, never a clean bill (`.:V48`).
#[test]
fn the_ratchet_verbs_refuse_a_tree_with_no_ratchet() -> Result<(), String> {
    let r = TestRepo::new("route-ratchets")?;
    assert_eq!(
        run_args(at(&["coverage", "--check"], &r)),
        ExitCode::from(2)
    );
    assert_eq!(run_args(at(&["debt", "--check"], &r)), ExitCode::from(2));
    Ok(())
}

/// `land` from `main` refuses before any gate runs, and says so with the
/// violation code: the request was well-formed, the state is wrong.
#[test]
fn land_on_main_is_refused_as_a_violation() -> Result<(), String> {
    let r = TestRepo::new("route-land")?;
    assert_eq!(run_args(at(&["land"], &r)), ExitCode::from(1));
    assert_eq!(run_args(at(&["land", "--push"], &r)), ExitCode::from(1));
    Ok(())
}

/// A `--depth` that is neither `rule` nor `why` is usage, not a pack.
#[test]
fn lens_with_an_unknown_depth_is_usage() {
    assert_eq!(
        run_args(argv(&["lens", ".", "--depth", "deep"])),
        ExitCode::from(2)
    );
}

/// `route` without a query is usage; with one it resolves against the root
/// named in argv, not the one the test runs in.
#[test]
fn route_needs_a_query_and_reads_the_named_root() {
    let r = routing_fixture("route-query");
    assert_eq!(run_args(argv(&["route"])), ExitCode::from(2));
    assert_eq!(run_args(at(&["route", "sprockets"], &r)), ExitCode::SUCCESS);
    assert_eq!(run_args(at(&["route", "wombat"], &r)), ExitCode::from(2));
}

/// `sync --check` on this repo is clean: the gate's `nav` step holds the
/// same claim on every commit.
#[test]
fn sync_check_is_clean_on_this_repo() {
    assert_eq!(run_args(argv(&["sync", "--check"])), ExitCode::SUCCESS);
}

/// `split` on a node with no declared modules reports rather than guesses
/// (`src/split:V1`), and on a dir with no SPEC.md it is usage.
#[test]
fn split_routes_the_named_dir_and_refuses_a_non_node() -> Result<(), String> {
    let r = routing_fixture("route-split");
    assert_eq!(run_args(at(&["split"], &r)), ExitCode::SUCCESS);
    assert_eq!(run_args(argv(&["split", "no-such-dir"])), ExitCode::from(2));
    Ok(())
}

/// `plan --milestone` plans a milestone some node declares, and refuses one
/// nobody does (a typo is not a plan).
#[test]
fn plan_milestone_accepts_a_declared_id_only() -> Result<(), String> {
    let r = TestRepo::new("route-milestone")?;
    r.write(
        "SPEC.md",
        "# SPEC\n\n## \u{a7}G GOAL\n\ntoy\n\n## \u{a7}T TASKS\n\n\
         | id | scope | tasks | done-when |\n|----|-------|-------|-----------|\n\
         | M1 | first | T1 | shipped |\n\nid|status|task|cites\nT1|.|one|-\n",
    )?;
    assert_eq!(
        run_args(at(&["plan", "--milestone", "M1"], &r)),
        ExitCode::SUCCESS
    );
    assert_eq!(
        run_args(at(&["plan", "--milestone", "M9"], &r)),
        ExitCode::from(2)
    );
    Ok(())
}

/// Without the `ollama` feature the model verbs are NOT COMPILED IN, and
/// that is usage with its own message, not "unknown command".
#[cfg(not(feature = "ollama"))]
#[test]
fn a_model_verb_in_the_default_build_is_usage() {
    for verb in ["apply", "ask", "oneshot", "tdd"] {
        assert_eq!(run_args(argv(&[verb])), ExitCode::from(2), "{verb}");
    }
}

/// `lens` on a dir that is no node is a MISS (2), the same answer `budget`
/// gives (`src/cli:V2`, `src/lens:B2`). It printed the root's pack, exit 0.
#[test]
fn lens_on_a_dir_that_is_no_node_is_a_miss() -> Result<(), String> {
    let r = TestRepo::new("route-lens-miss")?;
    assert_eq!(
        lens_cmd(r.path(), &r.path().join("nowhere"), lens::Depth::Rule),
        ExitCode::from(2)
    );
    assert_eq!(run_args(argv(&["lens", "nowhere"])), ExitCode::from(2));
    Ok(())
}

/// The verbs that read a fixture and write nothing, driven through the
/// parsed route. Each flag spelling reaches its own arm: `--stdout` for
/// `init`, the four `graph` renderings, both `validate` forms and each
/// `slice` mode.
#[test]
fn parsed_verbs_reach_their_arms_on_a_fixture() {
    let r = routing_fixture("route-parsed");
    for flag in ["--dot", "--table", "--tree", "--mermaid"] {
        assert_eq!(run_args(at(&["graph", flag], &r)), ExitCode::SUCCESS);
    }
    let preview = vec![
        "init".into(),
        r.path().join("alpha").display().to_string(),
        "--stdout".into(),
    ];
    assert_ne!(run_args(preview), ExitCode::from(2));
    for verb in [
        &["check"][..],
        &["validate"],
        &["validate", "--format", "json"],
        &["slice"],
        &["slice", "--check"],
        &["slice", "--list"],
    ] {
        let code = run_args(at(verb, &r));
        assert_ne!(code, ExitCode::from(2), "`sherd {}`", verb.join(" "));
    }
}

#[test]
fn ratchet_reads_the_flag_and_defaults_to_none() {
    assert_eq!(ratchet(true, false).map(Ratchet::flag), Some("--check"));
    assert_eq!(ratchet(false, true).map(Ratchet::flag), Some("--record"));
    assert!(ratchet(false, false).is_none());
}

#[test]
fn graph_flags_pick_four_different_renderings() {
    let r = routing_fixture("route-graph-render");
    let p = r.path();
    let all = [
        graph_render(p, GraphView::Dot),
        graph_render(p, GraphView::Table),
        graph_render(p, GraphView::Tree),
        graph_render(p, GraphView::Mermaid),
    ];
    for (i, a) in all.iter().enumerate() {
        for b in all.iter().skip(i + 1) {
            assert_ne!(a, b);
        }
    }
}

#[test]
fn only_kept_scores_as_kept() {
    assert!(Verdict::Kept.is_kept());
    assert!(!Verdict::Reverted.is_kept());
    assert!(!Verdict::Failed.is_kept());
}

/// With no feature the model verbs each name themselves.
#[cfg(not(feature = "ollama"))]
#[test]
fn each_model_verb_names_itself_when_not_compiled_in() {
    for a in [
        &["apply"][..],
        &["ask", "d", "q"],
        &["oneshot", "d", "V1", "t"],
        &["tdd", "d", "V1", "t"],
    ] {
        assert_eq!(run_args(argv(a)), ExitCode::from(2), "{a:?}");
    }
}

/// A missing or non-directory `At` selector is usage, not a silent fall
/// back to the CWD's repository.
#[test]
fn a_selector_that_is_not_a_directory_is_usage() {
    for verb in ["validate", "graph", "plan", "land", "slice", "debt"] {
        assert_eq!(
            run_args(argv(&[verb, "/nonexistent/sherd-at"])),
            ExitCode::from(2),
            "{verb}"
        );
    }
}

/// `review` is a verb with no `[dir]` of its own, so it takes the trailing
/// `At` dir every such verb does (`src/cli:V21`). The rev exists only in the
/// fixture: read from the CWD's repository instead, it is a miss.
#[test]
fn review_reads_the_repository_it_is_pointed_at() -> Result<(), String> {
    let r = TestRepo::new("route-review")?;
    r.git(&["branch", "only-in-this-fixture"])?;
    assert_eq!(
        run_args(at(&["review", "only-in-this-fixture"], &r)),
        ExitCode::SUCCESS
    );
    assert_eq!(
        run_args(argv(&["review", "only-in-this-fixture"])),
        ExitCode::from(2)
    );
    Ok(())
}

/// The `dir` of a seam run, as `absolutize_dir` leaves it.
fn resolved(dir: &str, root: &Path, here: &Path) -> Option<String> {
    let mut cmd = Cmd::Seam {
        dir: Some(dir.into()),
    };
    absolutize_dir(&mut cmd, root, here);
    dir_of(&cmd).map(String::from)
}

/// `src/cli:V17`: inside the repository it was typed in, `[dir]` stays
/// ROOT-relative wherever the caller stands, even with a same-named directory
/// right there.
#[test]
fn a_dir_in_the_typed_repository_stays_root_relative() -> Result<(), String> {
    let r = TestRepo::new("route-root-relative")?;
    r.write("src/code/SPEC.md", "# SPEC\n")?;
    let here = r.path().join("src");
    assert_eq!(resolved("code", r.path(), &here), Some("code".into()));
    Ok(())
}

/// A relative `[dir]` that named ANOTHER repository is that root already, so
/// it must not be joined onto it a second time (`src/cli:B9`'s doubling).
#[test]
fn a_dir_naming_another_repository_is_made_absolute() -> Result<(), String> {
    let outer = TestRepo::new("route-outer")?;
    let inner = outer.path().join("inner");
    outer.write("inner/SPEC.md", "# SPEC\n")?;
    outer.write("inner/.git/HEAD", "")?;
    let want = inner.display().to_string();
    assert_eq!(resolved("inner", &inner, outer.path()), Some(want.clone()));
    // Every verb with a `dir` field, through the real grammar.
    for verb in [
        &["init", "inner"][..],
        &["budget", "inner"],
        &["fed", "inner"],
        &["check", "inner"],
        &["split", "inner"],
        &["wave", "inner"],
        &["sync", "inner"],
        &["lens", "inner"],
        &["adopt", "inner"],
        &["ask", "inner", "q"],
        &["tdd", "inner", "V1", "t"],
        &["oneshot", "inner", "V1", "t"],
    ] {
        let parsed = parse::Cli::try_parse_from(
            std::iter::once(&"sherd").chain(verb).copied(),
        );
        let Ok(parse::Cli {
            cmd: Some(mut cmd), ..
        }) = parsed
        else {
            return Err(format!("{verb:?} does not parse"));
        };
        absolutize_dir(&mut cmd, &inner, outer.path());
        assert_eq!(dir_of(&cmd), Some(want.as_str()), "{verb:?}");
    }
    // A word that names no directory, and a verb with no `dir`, are left be.
    assert_eq!(
        resolved("no-such-dir", &inner, outer.path()),
        Some("no-such-dir".into())
    );
    let mut man = Cmd::Man;
    absolutize_dir(&mut man, &inner, outer.path());
    assert_eq!(dir_of(&man), None);
    Ok(())
}

/// `outcome` writes its verdict to the store it is GIVEN and reports from
/// that same store: a kept then a failed outcome leave 2 tried and 1 kept.
/// The store is the test's own file, so the ambient state is never touched.
#[test]
fn an_outcome_is_recorded_in_the_store_it_is_given() -> Result<(), String> {
    let r = TestRepo::new("route-outcome")?;
    let store = r.path().join("store");
    assert_eq!(
        outcome_in(&store, "src/fed", Verdict::Kept),
        ExitCode::SUCCESS
    );
    assert_eq!(
        outcome_in(&store, "src/fed", Verdict::Failed),
        ExitCode::SUCCESS
    );
    let st = crate::state::State::at(&store);
    assert_eq!(crate::plan::record_in(&st, Path::new("src/fed")), (2, 1));
    Ok(())
}