instinct-cli 0.3.8

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/mod.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
// `instinct check`: scoped deterministic checks. The pure kernel (`kernel`, `json`) is Helix-authored
// hlx:3
// (`*.hlx`, exported to the sibling `.rs` files); this file is only the CLI adapter, the one place that reads input.
// hlx:4
// Pure operations open no bank. Explicit attach writes only its private sidecar; no operation grants authority.
// hlx:5
#[allow(dead_code)]
// hlx:6
pub(crate) mod json;
// hlx:7
#[allow(dead_code)]
// hlx:8
mod kernel;
// hlx:9
mod observe;
// hlx:10
#[allow(dead_code)]
// hlx:11
mod digest;
// hlx:12
#[allow(dead_code)]
// hlx:13
mod receipt;
// hlx:14
mod compose;
// hlx:15
mod pack;
// hlx:16
mod refine;
mod export_boundary;
mod integrity;
// hlx:17
pub(crate) mod feedback;
// hlx:18
pub(crate) mod mcp;
// hlx:19
pub use kernel::{evaluate, Mode};
// hlx:20
use std::io::Read;
// hlx:21
const USAGE: &str = "usage: instinct check validate|run|explain|receipt|replay|compose|refine|export-boundary|integrity --input FILE|-\n  Reads one JSON request (at most 1 MiB) and prints one JSON result. Spec: docs/checks.md.\n  receipt prints a byte-identity receipt for a request; replay recomputes {request, receipt}; neither authenticates or authorizes.\n  observe --root ABS --input FILE|- observes a trusted staging inventory read-only; see check observe --help.\n  attach --lesson ID --store BANK --input FILE|- explicitly attaches a policy.\n  detach --lesson ID --store BANK withdraws a policy without deleting history.\n  pack preview|export|import explicitly handles declarative packages; see check pack --help.\n  Pure operations open no bank; attach/detach explicitly write their sidecar. Exit 0 for pass, fail and abstain, exit 2 for an error result.";
// hlx:22
fn usage_error(why: &str) -> String {
    // hlx:23
    kernel::error_json(&format!("usage: {why}"))
    // hlx:24
}
// hlx:25
fn read_input(path: &str) -> Result<Vec<u8>, String> {
    // hlx:26
    read_input_capped(path, json::MAX_BYTES)
    // hlx:27
}
// hlx:28
fn read_input_capped(path: &str, max: usize) -> Result<Vec<u8>, String> {
    // hlx:29
    let cap = (max as u64) + 1;
    // hlx:30
    let mut buf = Vec::new();
    // hlx:31
    let got = if path == "-" {
        // hlx:32
        std::io::stdin().lock().take(cap).read_to_end(&mut buf)
    // hlx:33
    } else {
        // hlx:34
        match std::fs::File::open(path) {
            // hlx:35
            Ok(f) => f.take(cap).read_to_end(&mut buf),
            // hlx:36
            Err(e) => return Err(format!("input_io: cannot open input ({})", e.kind())),
            // hlx:37
        }
        // hlx:38
    };
    // hlx:39
    if let Err(e) = got {
        // hlx:40
        return Err(format!("input_io: cannot read input ({})", e.kind()));
        // hlx:41
    }
    // hlx:42
    if buf.len() > max {
        // hlx:43
        return Err(if max == json::MAX_BYTES {
            "input_too_large: more than 1 MiB".to_string()
        } else {
            "input_too_large: replay envelope exceeds 1 MiB plus 4096 bytes".to_string()
        });
        // hlx:44
    }
    // hlx:45
    Ok(buf)
    // hlx:46
}
// hlx:47
/// Runs the subcommand and returns the process exit code. Output goes to stdout only, as one JSON object.
// hlx:48
pub fn cli(args: &[String]) -> i32 {
    // hlx:49
    if args.first().map(String::as_str) == Some("pack") {
        // hlx:50
        return match pack::cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:51
    }
    // hlx:52
    if args.first().map(String::as_str) == Some("attach") {
        // hlx:53
        return match feedback::attach_cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:54
    }
    // hlx:55
    if args.first().map(String::as_str) == Some("detach") {
        // hlx:56
        return match feedback::detach_cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:57
    }
    // hlx:58
    // Observation requires an explicit --root grant.
    // hlx:59
    if args.first().map(String::as_str) == Some("observe") {
        // hlx:60
        return observe::cli(&args[1..]);
        // hlx:61
    }
    // hlx:62
    let is_help = |a: &String| a == "--help" || a == "-h";
    // hlx:63
    let sub_ok = |a: &String| {
        matches!(
            a.as_str(),
            "validate" | "run" | "explain" | "receipt" | "replay" | "compose" | "refine" | "export-boundary" | "integrity"
        )
    };
    // hlx:64
    if (args.len() == 1 && is_help(&args[0]))
        || (args.len() == 2 && sub_ok(&args[0]) && is_help(&args[1]))
    {
        // hlx:65
        println!("{USAGE}");
        // hlx:66
        return 0;
        // hlx:67
    }
    // hlx:68
    let mode = match args.first().map(String::as_str) {
        // hlx:69
        Some("validate") => Mode::Validate,
        // hlx:70
        Some("run") => Mode::Run,
        // hlx:71
        Some("explain") => Mode::Explain,
        // hlx:72
        Some("receipt") | Some("replay") | Some("compose") | Some("refine") | Some("export-boundary") | Some("integrity") => Mode::Run,
        // hlx:73
        Some(other) if other.starts_with('-') => {
            return fail(&usage_error("expected validate, run or explain first"))
        }
        // hlx:74
        Some(_) => {
            return fail(&usage_error(
                "unknown subcommand; expected validate, run or explain",
            ))
        }
        // hlx:75
        None => {
            return fail(&usage_error(
                "missing subcommand; expected validate, run or explain",
            ))
        }
        // hlx:76
    };
    // hlx:77
    let mut input: Option<String> = None;
    // hlx:78
    let mut i = 1;
    // hlx:79
    while i < args.len() {
        // hlx:80
        let a = &args[i];
        // hlx:81
        let value = if a == "--input" {
            // hlx:82
            i += 1;
            // hlx:83
            match args.get(i) {
                // hlx:84
                Some(v) if v == "-" || !v.starts_with("--") => v.clone(),
                // hlx:85
                _ => return fail(&usage_error("--input needs a file path or -")),
                // hlx:86
            }
        // hlx:87
        } else if let Some(v) = a.strip_prefix("--input=") {
            // hlx:88
            v.to_string()
        // hlx:89
        } else if a.starts_with('-') && a != "-" {
            // hlx:90
            return fail(&usage_error("unknown option (only --input is accepted; --help is only accepted as `check --help` or `check SUBCOMMAND --help`)"));
        // hlx:91
        } else {
            // hlx:92
            return fail(&usage_error("unexpected positional argument"));
            // hlx:93
        };
        // hlx:94
        if input.is_some() {
            // hlx:95
            return fail(&usage_error("--input given more than once"));
            // hlx:96
        }
        // hlx:97
        input = Some(value);
        // hlx:98
        i += 1;
        // hlx:99
    }
    // hlx:100
    let path = match input {
        // hlx:101
        Some(p) if !p.is_empty() => p,
        // hlx:102
        _ => return fail(&usage_error("--input FILE|- is required")),
        // hlx:103
    };
    // hlx:104
    let max = if args[0] == "replay" {
        json::MAX_BYTES + json::REPLAY_EXTRA_BYTES
    } else {
        json::MAX_BYTES
    };
    // hlx:105
    let bytes = match read_input_capped(&path, max) {
        // hlx:106
        Ok(b) => b,
        // hlx:107
        Err(e) => return fail(&kernel::error_json(&e)),
        // hlx:108
    };
    // hlx:109
    let (out, is_error) = match args[0].as_str() {
        // hlx:110
        "receipt" => receipt::create(&bytes),
        // hlx:111
        "replay" => receipt::replay(&bytes),
        // hlx:112
        "compose" => compose::compose(&bytes),
        // hlx:113
        "refine" => refine::evaluate(&bytes),
        "export-boundary" => export_boundary::evaluate(&bytes),
        "integrity" => integrity::evaluate(&bytes),
        // hlx:114
        _ => evaluate(mode, &bytes),
        // hlx:115
    };
    // hlx:116
    println!("{out}");
    // hlx:117
    if is_error {
        // hlx:118
        2
    // hlx:119
    } else {
        // hlx:120
        0
        // hlx:121
    }
    // hlx:122
}
// hlx:123
fn fail(json: &str) -> i32 {
    // hlx:124
    println!("{json}");
    // hlx:125
    2
    // hlx:126
}