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/compose.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::{
    json::{self, J},
    kernel::{self, Mode},
    receipt,
};
// hlx:3
use std::collections::BTreeMap;
// hlx:4
fn object(v: &J) -> Result<&[(String, J)], String> {
    if let J::Obj(o) = v {
        Ok(o)
    } else {
        Err("composition requires objects".into())
    }
}
// hlx:5
fn field<'a>(o: &'a [(String, J)], k: &str) -> Option<&'a J> {
    o.iter().find(|(n, _)| n == k).map(|(_, v)| v)
}
// hlx:6
fn needed<'a>(o: &'a [(String, J)], k: &str) -> Result<&'a J, String> {
    field(o, k).ok_or_else(|| format!("composition missing {k}"))
}
// hlx:7
fn only(o: &[(String, J)], keys: &[&str]) -> Result<(), String> {
    if o.iter().any(|(k, _)| !keys.contains(&k.as_str())) {
        Err("unknown composition field".into())
    } else {
        Ok(())
    }
}
// hlx:8
fn string(v: &J) -> Result<&str, String> {
    if let J::Str(s) = v {
        Ok(s)
    } else {
        Err("composition name must be a string".into())
    }
}
// hlx:9
fn serialize(v: &J) -> String {
    let mut out = String::new();
    receipt::ser(v, &mut out);
    out
}
// hlx:10
fn failure(reason: &str) -> String {
    kernel::error_json(reason)
}
// hlx:11
fn rename(v: &J, names: &BTreeMap<String, String>) -> Result<J, String> {
    match v {
        J::Obj(o) => {
            let mut result = Vec::new();
            for (k, v) in o {
                if k == "fact" {
                    let old = string(v)?;
                    let new = names.get(old).ok_or("composition unknown fact reference")?;
                    result.push((k.clone(), J::Str(new.clone())))
                } else {
                    result.push((k.clone(), rename(v, names)?))
                }
            }
            Ok(J::Obj(result))
        }
        J::Arr(a) => Ok(J::Arr(
            a.iter()
                .map(|v| rename(v, names))
                .collect::<Result<_, _>>()?,
        )),
        other => Ok(other.clone()),
    }
}
// hlx:12
fn compile(raw: &[u8]) -> Result<String, String> {
    // hlx:13
    let value = json::parse(raw)?;
    let top = object(&value)?;
    only(top, &["id", "revision", "checks", "scope"])?;
    // hlx:14
    let id = needed(top, "id")?.clone();
    let revision = needed(top, "revision")?.clone();
    let current = field(top, "scope").cloned().unwrap_or(J::Obj(vec![]));
    // hlx:15
    let J::Arr(children) = needed(top, "checks")? else {
        return Err("checks must be an array".into());
    };
    if children.is_empty() || children.len() > 16 {
        return Err("composition requires 1 to 16 checks".into());
    }
    // hlx:16
    let mut inputs = Vec::new();
    let mut facts = Vec::new();
    let mut conditions = Vec::new();
    let mut required = Vec::new();
    let mut claims = Vec::new();
    let mut scope: BTreeMap<String, J> = BTreeMap::new();
    // hlx:17
    for (i, child) in children.iter().enumerate() {
        let child_fields = object(child)?;
        only(child_fields, &["check", "facts", "conditions"])?;
        // hlx:18
        let (validated, bad) = kernel::evaluate(Mode::Validate, serialize(child).as_bytes());
        if bad {
            return Err(format!("child {i} invalid: {validated}"));
        }
        // hlx:19
        let def = object(needed(child_fields, "check")?)?;
        let mut names = BTreeMap::new();
        // hlx:20
        for (j, (old, ty)) in object(needed(def, "inputs")?)?.iter().enumerate() {
            let new = format!("c{i}.f{j}");
            names.insert(old.clone(), new.clone());
            inputs.push((new, ty.clone()));
        }
        // hlx:21
        if let Some(raw_facts) = field(child_fields, "facts") {
            for (old, v) in object(raw_facts)? {
                facts.push((
                    names.get(old).ok_or("unknown child fact")?.clone(),
                    v.clone(),
                ));
            }
        }
        // hlx:22
        let mut condition_names = BTreeMap::new();
        if let Some(J::Arr(list)) = field(def, "required_conditions") {
            for (j, name) in list.iter().enumerate() {
                let new = format!("c{i}.r{j}");
                condition_names.insert(string(name)?.to_owned(), new.clone());
                required.push(J::Str(new));
            }
        }
        // hlx:23
        if let Some(raw_conditions) = field(child_fields, "conditions") {
            for (old, v) in object(raw_conditions)? {
                conditions.push((
                    condition_names
                        .get(old)
                        .ok_or("unknown child condition")?
                        .clone(),
                    v.clone(),
                ));
            }
        }
        // hlx:24
        if let Some(raw_scope) = field(def, "scope") {
            for (key, v) in object(raw_scope)? {
                if let Some(previous) = scope.get(key) {
                    if previous != v {
                        return Err(format!("conflicting child scope: {key}"));
                    }
                } else {
                    scope.insert(key.clone(), v.clone());
                }
            }
        }
        // hlx:25
        claims.push(rename(needed(def, "claim")?, &names)?);
        // hlx:26
    }
    // hlx:27
    let definition = J::Obj(vec![
        ("schema".into(), J::Str("instinct.check/v1".into())),
        ("id".into(), id),
        ("revision".into(), revision),
        ("inputs".into(), J::Obj(inputs)),
        ("required_conditions".into(), J::Arr(required)),
        ("scope".into(), J::Obj(scope.into_iter().collect())),
        (
            "claim".into(),
            J::Obj(vec![
                ("op".into(), J::Str("all".into())),
                ("args".into(), J::Arr(claims)),
            ]),
        ),
    ]);
    // hlx:28
    let compiled = J::Obj(vec![
        ("check".into(), definition),
        ("facts".into(), J::Obj(facts)),
        ("conditions".into(), J::Obj(conditions)),
        ("scope".into(), current),
    ]);
    let out = serialize(&compiled);
    // hlx:29
    let (validated, bad) = kernel::evaluate(Mode::Validate, out.as_bytes());
    if bad {
        return Err(format!("aggregate invalid: {validated}"));
    }
    // hlx:30
    if out.len() > kernel::MAX_OUTPUT_BYTES {
        return Err("composition output exceeds 64 KiB".into());
    }
    Ok(out)
    // hlx:31
}
// hlx:32
pub fn compose(raw: &[u8]) -> (String, bool) {
    match compile(raw) {
        Ok(out) => (out, false),
        Err(e) => (failure(&e), true),
    }
}