qua 0.74.0

Structure-aware query CLI for the Quarb engine
//! The walk's shorter forms change no answer (the review of
//! 2026-11-23). A quantified group is walked exactly, one walk per
//! history, or in a form that has fewer walks in flight: the set walk
//! (one arrival per node), the merge under an acyclic promise, the
//! search by total under a cost budget. Each asks what the group
//! reads before it runs, and a read that tells two walks to one node
//! apart takes the exact walk: the same question written with a
//! count, which is always exact, must answer the same.
//!
//! Beside them: two walks of two totals are two walks under a budget,
//! a budget over a group that holds a group is refused until its
//! inner steps are weighed, a tie cut at the quantifier bound is
//! said, and `edges` refuses what is written on a group and not read.

use std::path::{Path, PathBuf};

const REFS: &str = "ref /links/*::from --> /nodes/*[::name = $];\n\
                    ref /links/*::to --> /nodes/*[::name = $];\n";

/// A graph by its edges, each `(from, to, fare)`; the nodes are the
/// names in order of first mention.
fn graph(edges: &[(&str, &str, u32)]) -> String {
    let mut names: Vec<&str> = Vec::new();
    for (a, b, _) in edges {
        for n in [a, b] {
            if !names.contains(n) {
                names.push(n);
            }
        }
    }
    let nodes: Vec<String> = names
        .iter()
        .map(|n| format!(r#"{{"name": "{n}"}}"#))
        .collect();
    let links: Vec<String> = edges
        .iter()
        .map(|(a, b, f)| format!(r#"{{"from": "{a}", "to": "{b}", "kind": "x", "fare": {f}}}"#))
        .collect();
    format!(
        r#"{{"nodes": [{}], "links": [{}]}}"#,
        nodes.join(", "),
        links.join(", ")
    )
}

fn fixture(tag: &str, edges: &[(&str, &str, u32)]) -> PathBuf {
    let dir = std::env::temp_dir().join(format!("quarb-walkforms-{}-{tag}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("g.json"), graph(edges)).unwrap();
    let edge = "edge /links/*: ::from -- ::to as ::kind weights(::fare<_EUR>)";
    std::fs::write(dir.join("plain.model"), format!("{REFS}{edge};\n")).unwrap();
    std::fs::write(
        dir.join("acyclic.model"),
        format!("{REFS}{edge} acyclic;\n"),
    )
    .unwrap();
    dir
}

fn run(dir: &Path, pre: &[&str], model: &str, query: &str) -> Result<Vec<String>, String> {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_qua"))
        .env("QUARB_LOCALE", "C")
        .current_dir(dir)
        .args(pre)
        .args(["--model", model, query, "g.json"])
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    match out.status.success() {
        true => Ok(String::from_utf8(out.stdout)
            .unwrap()
            .lines()
            .map(str::to_string)
            .collect()),
        false => Err(String::from_utf8_lossy(&out.stderr).to_string()),
    }
}

fn lines(dir: &Path, model: &str, query: &str) -> Vec<String> {
    run(dir, &[], model, query).unwrap_or_else(|e| panic!("{query}: {e}"))
}

fn refused(dir: &Path, pre: &[&str], model: &str, query: &str) -> String {
    match run(dir, pre, model, query) {
        Ok(out) => panic!("{query}: expected a refusal, got {out:?}"),
        Err(e) => e,
    }
}

const FROM_A: &str = r#"/nodes/*[::name = "A"]"#;

/// X is one step from A and two through B; Y is one step past X.
const TWO_WAYS: &[(&str, &str, u32)] =
    &[("A", "X", 5), ("A", "B", 1), ("B", "X", 1), ("X", "Y", 1)];

/// A step's condition that reads the repetition tells the two
/// arrivals at X apart: the second repetition admits X alone, so Y is
/// reached only through the arrival of the second repetition. The
/// set walk kept the first arrival and lost Y.
#[test]
fn a_steps_condition_on_the_repetition_takes_the_exact_walk() {
    let d = fixture("iter", TWO_WAYS);
    let body = r#"->*[$iter != 2 || ::name = "X"]"#;
    let counted = lines(
        &d,
        "plain.model",
        &format!("{FROM_A}({body}){{1;5}} @| collapse | ::name"),
    );
    assert_eq!(counted, ["X", "B", "Y"]);
    assert_eq!(
        lines(
            &d,
            "plain.model",
            &format!("{FROM_A}({body})+ @| collapse | ::name")
        ),
        counted
    );
    assert_eq!(
        lines(
            &d,
            "plain.model",
            &format!(r#"{FROM_A}({body})+[::name = "Y"]?::name"#)
        ),
        ["Y"]
    );
    // and under a budget the search by total is not taken: the
    // lightest walk to Y within two repetitions goes by X at 5
    for fact in ["$iter", "$steps"] {
        assert_eq!(
            lines(
                &d,
                "plain.model",
                &format!(r#"{FROM_A}(->*[{fact} <= 2]){{;300_EUR}}[::name = "Y"]? | $total"#)
            ),
            ["6_EUR"],
            "{fact}"
        );
    }
}

/// The search by total settles a node at its least total whatever
/// the walk recorded. A guard that reads the record is asked of the
/// dearer walk too: the walk whose first node is X costs 6, and the
/// lightest walk to Y, 3, goes by B.
#[test]
fn a_guard_on_what_the_walk_recorded_takes_the_exact_walk() {
    let d = fixture("capsa", TWO_WAYS);
    for braces in ["{1;5}{;300_EUR}", "{;300_EUR}"] {
        assert_eq!(
            lines(
                &d,
                "plain.model",
                &format!(r#"{FROM_A}(->* .(::name)){braces}[::name = "Y" && $.1 = "X"]? | $total"#)
            ),
            ["6_EUR"],
            "{braces}"
        );
    }
    // a guard on the node alone is still searched, and answers the
    // lightest
    assert_eq!(
        lines(
            &d,
            "plain.model",
            &format!(r#"{FROM_A}(->* .(::name)){{;300_EUR}}[::name = "Y"]? | $total"#)
        ),
        ["3_EUR"]
    );
}

/// An acyclic promise changes no answer: two histories of two and
/// three steps reach Y by one edge in one outer repetition, and a
/// guard on the count of steps tells them apart. The promise's merge
/// folded them and the guard was asked of one.
#[test]
fn a_guard_on_the_step_count_is_not_merged_under_the_promise() {
    let d = fixture("promise", TWO_WAYS);
    for q in [
        format!("{FROM_A}((->x){{1;2}}){{2}}[$steps = 3]?::name"),
        format!("{FROM_A}((->x){{1;2}}){{2}}[$steps = 3] @| collapse | ::name"),
    ] {
        let plain = lines(&d, "plain.model", &q);
        assert_eq!(plain, ["Y"], "{q}");
        assert_eq!(lines(&d, "acyclic.model", &q), plain, "{q}");
    }
}

/// Two walks cross A, B, C, D to E by the edge from D: one costs 4,
/// one 12. They are two walks under a budget, whose totals differ;
/// folded, a higher ceiling lost the cheaper one.
#[test]
fn two_walks_of_two_totals_are_two_under_a_budget() {
    let d = fixture(
        "totals",
        &[
            ("A", "C", 5),
            ("A", "B", 1),
            ("B", "C", 1),
            ("C", "B", 1),
            ("C", "D", 1),
            ("B", "D", 5),
            ("D", "E", 1),
        ],
    );
    let mut totals = lines(
        &d,
        "plain.model",
        &format!(r#"{FROM_A}(->*){{;300_EUR}}[::name = "E"] | $total"#),
    );
    totals.sort();
    assert_eq!(totals, ["12_EUR", "4_EUR", "7_EUR", "7_EUR"]);
    // the lightest is 4 in every form
    for braces in ["{;300_EUR}", "{1;9}{;300_EUR}", "{4}{;300_EUR}"] {
        assert_eq!(
            lines(
                &d,
                "plain.model",
                &format!(r#"{FROM_A}(->*){braces}[::name = "E"]? | $total"#)
            ),
            ["4_EUR"],
            "{braces}"
        );
    }
    // and a ceiling of 11 or of 12 keeps it
    for ceiling in [11, 12] {
        let found = lines(
            &d,
            "plain.model",
            &format!(r#"{FROM_A}(->*){{;{ceiling}_EUR}}[::name = "E"] | $total"#),
        );
        assert!(found.contains(&"4_EUR".to_string()), "{ceiling}: {found:?}");
    }
}

/// A budget weighs the steps of its own group. Over a group that
/// holds a group it bounded nothing and read a total of the first
/// leg: refused until the inner steps are weighed.
#[test]
fn a_budget_over_a_group_that_holds_a_group_is_refused() {
    let d = fixture("nested", &[("A", "B", 10), ("B", "C", 10), ("C", "D", 10)]);
    for q in [
        format!("{FROM_A}((->x){{1}}){{;15_EUR}}::name"),
        format!("{FROM_A}(->x (->x){{1;2}}){{;25_EUR}} | $total"),
    ] {
        let e = refused(&d, &[], "plain.model", &q);
        assert!(
            e.contains(
                "a cost budget on a group that holds a group does not weigh the inner group's \
                 steps yet"
            ),
            "{q}: {e}"
        );
    }
    // the steps written in one group are weighed
    assert_eq!(
        lines(
            &d,
            "plain.model",
            &format!("{FROM_A}(->x ->x){{;25_EUR}} | $total")
        ),
        ["0_EUR", "20_EUR"]
    );
    // and a budget on the inner group weighs its own
    assert_eq!(
        lines(
            &d,
            "plain.model",
            &format!("{FROM_A}((->x){{;15_EUR}}){{1}}::name")
        ),
        ["A", "B"]
    );
}

/// A walk that ties with the answer and is cut at the quantifier
/// bound leaves the tie unsaid: the search by total refused only a
/// cut below the answer's total. B is 10 from A; D is 10 too, two
/// legs of no weight further.
#[test]
fn a_tie_cut_at_the_quantifier_bound_is_refused() {
    let d = fixture("tie", &[("A", "B", 10), ("B", "C", 0), ("C", "D", 0)]);
    let q = format!(r#"{FROM_A}(->*){{;300_EUR}}[::name = "B" || ::name = "D"]? | ::name"#);
    assert_eq!(lines(&d, "plain.model", &q), ["B", "D"]);
    let e = refused(&d, &["--quantifier-bound", "2"], "plain.model", &q);
    assert!(e.contains("QUANTIFIER_BOUND"), "{e}");
}

/// The cycle refusal names the node the walk began at. The ground is
/// kept sorted, and its first node was printed: a walk from the
/// third node was said to begin at the first.
#[test]
fn the_cycle_refusal_names_the_walks_start() {
    let d = fixture("cycle", &[("C", "A", 1), ("A", "B", 1), ("B", "C", 1)]);
    // the nodes in order of first mention: C, A, B
    let e = refused(
        &d,
        &[],
        "acyclic.model",
        r#"/nodes/*[::name = "B"](->x){1;5}::name"#,
    );
    assert!(
        e.contains("the walk from /nodes/3 returns to /nodes/3 after 3 steps"),
        "{e}"
    );
}

/// `edges` reads the alternatives of a group and nothing written on
/// the group: a guard there was dropped in silence, and every edge
/// answered.
#[test]
fn edges_refuses_what_is_written_on_a_group() {
    let d = fixture("edges", TWO_WAYS);
    assert_eq!(
        lines(&d, "plain.model", "/nodes/* @| edges((->x|<-x)) | count"),
        lines(&d, "plain.model", "/nodes/* @| edges(--x) | count")
    );
    for group in [
        r#"(->x|<-x)[::name = "B"]"#,
        "(->x|<-x){1}{;5_EUR}",
        "(->x|<-x)?",
    ] {
        let e = refused(
            &d,
            &[],
            "plain.model",
            &format!("/nodes/* @| edges({group}) | count"),
        );
        assert!(e.contains("nothing written on the group"), "{group}: {e}");
    }
    // a condition on the step is read
    assert_eq!(
        lines(
            &d,
            "plain.model",
            r#"/nodes/* @| edges(->x[::name = "B"]) | count"#
        ),
        ["1"]
    );
}