instinct-cli 0.3.10

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
// generated by hxc 1.0.0-acgt-compiler from src/check/graph.hlx -- do not edit by hand

#[cfg(windows)]
#[allow(dead_code)]
const SYS_CURL: &str = "C:\\Windows\\System32\\curl.exe";
#[cfg(not(windows))]
#[allow(dead_code)]
const SYS_CURL: &str = "curl";
#[allow(dead_code)]
fn _helix_allowed(var: &str, what: &str) -> bool {
    let ok = std::env::var(var).map(|v| v == "1").unwrap_or(false);
    if !ok {
        eprintln!("helix: BLOCKED {} -- permission denied (set {}=1 to allow; `hxc run` allows by default, a `hxc build`/`export-rust` binary does not)", what, var);
    }
    ok
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_exec(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_exec(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_RUN", "process execution") {
        std::process::exit(13);
    }
    c
}
#[cfg(windows)]
#[allow(dead_code)]
fn _nw_net(mut c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    use std::os::windows::process::CommandExt;
    c.creation_flags(0x08000000);
    c
}
#[cfg(not(windows))]
#[allow(dead_code)]
fn _nw_net(c: std::process::Command) -> std::process::Command {
    if !_helix_allowed("HELIX_ALLOW_NET", "network access") {
        std::process::exit(13);
    }
    c
}

// hlx:2
use super::super::json::J;
// hlx:3
use std::collections::{BTreeMap, BTreeSet, VecDeque};
// hlx:4
#[derive(Debug, PartialEq, Eq)]
// hlx:5
pub(super) struct Graph {
    nodes: Vec<String>,
    edges: Vec<(usize, usize)>,
    adjacency: Vec<Vec<usize>>,
}
// hlx:6
impl Graph {
    // hlx:7
    pub(super) fn parse(value: &J) -> Result<Self, String> {
        // hlx:8
        let J::Obj(fields) = value else {
            return Err("type_mismatch: graph requires an object".into());
        };
        // hlx:9
        if fields.len() != 2
            || fields
                .iter()
                .any(|(k, _)| !matches!(k.as_str(), "nodes" | "edges"))
        {
            return Err("invalid_graph: expected only nodes and edges".into());
        }
        // hlx:10
        let field = |key: &str| fields.iter().find(|(k, _)| k == key).map(|(_, v)| v);
        // hlx:11
        let Some(J::Arr(raw_nodes)) = field("nodes") else {
            return Err("invalid_graph: nodes must be an array".into());
        };
        // hlx:12
        let Some(J::Arr(raw_edges)) = field("edges") else {
            return Err("invalid_graph: edges must be an array".into());
        };
        // hlx:13
        if raw_nodes.len() + raw_edges.len() > 10000 {
            return Err("limit_exceeded: graph has more than 10000 nodes and edges".into());
        }
        // hlx:14
        let mut nodes = Vec::new();
        for node in raw_nodes {
            match node {
                J::Str(s) if !s.is_empty() => nodes.push(s.clone()),
                _ => return Err("invalid_graph: nodes must be nonempty strings".into()),
            }
        }
        // hlx:15
        nodes.sort();
        if nodes.windows(2).any(|p| p[0] == p[1]) {
            return Err("duplicate_member: repeated graph node".into());
        }
        // hlx:16
        let ids: BTreeMap<&str, usize> = nodes
            .iter()
            .enumerate()
            .map(|(i, s)| (s.as_str(), i))
            .collect();
        let mut edges = Vec::new();
        // hlx:17
        for edge in raw_edges {
            let J::Arr(pair) = edge else {
                return Err("invalid_graph: edge must be a two-node array".into());
            };
            if pair.len() != 2 {
                return Err("invalid_graph: edge must contain two nodes".into());
            }
            let (J::Str(a), J::Str(b)) = (&pair[0], &pair[1]) else {
                return Err("invalid_graph: edge nodes must be strings".into());
            };
            let (Some(&a), Some(&b)) = (ids.get(a.as_str()), ids.get(b.as_str())) else {
                return Err("invalid_graph: edge references undeclared node".into());
            };
            edges.push((a, b));
        }
        // hlx:18
        edges.sort();
        if edges.windows(2).any(|p| p[0] == p[1]) {
            return Err("duplicate_member: repeated graph edge".into());
        }
        let mut adjacency = vec![Vec::new(); nodes.len()];
        for &(a, b) in &edges {
            adjacency[a].push(b);
        }
        Ok(Self {
            nodes,
            edges,
            adjacency,
        })
        // hlx:19
    }
    // hlx:20
    pub(super) fn entries(&self) -> usize {
        self.nodes.len() + self.edges.len()
    }
    // hlx:21
    /// None: an endpoint is not declared, not evidence that a path is absent.
    // hlx:22
    pub(super) fn reachable<E>(
        &self,
        start: &str,
        end: &str,
        mut charge: impl FnMut(u64) -> Result<(), E>,
    ) -> Result<Option<bool>, E> {
        // hlx:23
        charge(1)?;
        let (Ok(start), Ok(end)) = (
            self.nodes.binary_search_by(|s| s.as_str().cmp(start)),
            self.nodes.binary_search_by(|s| s.as_str().cmp(end)),
        ) else {
            return Ok(None);
        };
        // hlx:24
        let mut seen = BTreeSet::new();
        let mut queue = VecDeque::from([start]);
        seen.insert(start);
        while let Some(node) = queue.pop_front() {
            charge(1)?;
            if node == end {
                return Ok(Some(true));
            }
            for &next in &self.adjacency[node] {
                charge(1)?;
                if seen.insert(next) {
                    queue.push_back(next);
                }
            }
        }
        Ok(Some(false))
        // hlx:25
    }
    // hlx:26
}
// hlx:27
#[cfg(test)]
mod tests {
    // hlx:28
    use super::*;
    // hlx:29
    fn fixture(mask: u32) -> Graph {
        let nodes = (0..3).map(|n| n.to_string()).collect::<Vec<_>>();
        let edges = (0..9)
            .filter(|i| mask & (1 << i) != 0)
            .map(|i| (i / 3, i % 3))
            .collect::<Vec<_>>();
        let mut adjacency = vec![Vec::new(); 3];
        for &(a, b) in &edges {
            adjacency[a].push(b)
        }
        Graph {
            nodes,
            edges,
            adjacency,
        }
    }
    // hlx:30
    #[test]
    fn all_three_node_graphs_match_independent_transitive_closure() {
        for mask in 0..512 {
            let g = fixture(mask);
            let mut reach = [[false; 3]; 3];
            for i in 0..3 {
                reach[i][i] = true;
            }
            for &(a, b) in &g.edges {
                reach[a][b] = true;
            }
            for k in 0..3 {
                for i in 0..3 {
                    for j in 0..3 {
                        reach[i][j] |= reach[i][k] && reach[k][j];
                    }
                }
            }
            for i in 0..3 {
                for j in 0..3 {
                    let actual = g
                        .reachable(&i.to_string(), &j.to_string(), |_| Ok::<(), ()>(()))
                        .unwrap();
                    assert_eq!(actual, Some(reach[i][j]), "mask {mask} {i} {j}");
                }
            }
        }
    }
    // hlx:31
    #[test]
    fn missing_endpoint_is_unknown() {
        assert_eq!(
            fixture(0)
                .reachable("missing", "0", |_| Ok::<(), ()>(()))
                .unwrap(),
            None
        );
    }
    // hlx:32
    #[test]
    fn exhausted_budget_cannot_return_false_or_true() {
        let mut fuel = 0;
        assert!(fixture(511)
            .reachable("0", "2", |n| {
                fuel += n;
                if fuel > 1 {
                    Err(())
                } else {
                    Ok(())
                }
            })
            .is_err());
    }
    // hlx:33
}