instinct-cli 0.3.9

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 pack_fixtures;
// hlx:17
mod observed_receipt;
// hlx:18
mod dependencies;
// hlx:19
mod refine;
// hlx:20
mod export_boundary;
// hlx:21
mod integrity;
// hlx:22
pub(crate) mod feedback;
// hlx:23
pub(crate) mod mcp;
// hlx:24
pub use kernel::{evaluate, Mode};
// hlx:25
use std::io::Read;
// hlx:26
const USAGE: &str = "usage: instinct check validate|run|explain|receipt|replay|compose|refine|export-boundary|integrity|dependencies --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:27
fn usage_error(why: &str) -> String {
    // hlx:28
    kernel::error_json(&format!("usage: {why}"))
    // hlx:29
}
// hlx:30
fn read_input(path: &str) -> Result<Vec<u8>, String> {
    // hlx:31
    read_input_capped(path, json::MAX_BYTES)
    // hlx:32
}
// hlx:33
fn read_input_capped(path: &str, max: usize) -> Result<Vec<u8>, String> {
    // hlx:34
    let cap = (max as u64) + 1;
    // hlx:35
    let mut buf = Vec::new();
    // hlx:36
    let got = if path == "-" {
        // hlx:37
        std::io::stdin().lock().take(cap).read_to_end(&mut buf)
    // hlx:38
    } else {
        // hlx:39
        match std::fs::File::open(path) {
            // hlx:40
            Ok(f) => f.take(cap).read_to_end(&mut buf),
            // hlx:41
            Err(e) => return Err(format!("input_io: cannot open input ({})", e.kind())),
            // hlx:42
        }
        // hlx:43
    };
    // hlx:44
    if let Err(e) = got {
        // hlx:45
        return Err(format!("input_io: cannot read input ({})", e.kind()));
        // hlx:46
    }
    // hlx:47
    if buf.len() > max {
        // hlx:48
        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:49
    }
    // hlx:50
    Ok(buf)
    // hlx:51
}
// hlx:52
/// Runs the subcommand and returns the process exit code. Output goes to stdout only, as one JSON object.
// hlx:53
pub fn cli(args: &[String]) -> i32 {
    // hlx:54
    if args.first().map(String::as_str) == Some("pack") {
        // hlx:55
        return match pack::cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:56
    }
    // hlx:57
    if args.first().map(String::as_str) == Some("attach") {
        // hlx:58
        return match feedback::attach_cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:59
    }
    // hlx:60
    if args.first().map(String::as_str) == Some("detach") {
        // hlx:61
        return match feedback::detach_cli(&args[1..]) {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:62
    }
    // hlx:63
    // Observation requires an explicit --root grant.
    // hlx:64
    if args.first().map(String::as_str) == Some("observe") {
        // hlx:65
        return observe::cli(&args[1..]);
        // hlx:66
    }
    // hlx:67
    if matches!(
        args.first().map(String::as_str),
        Some("observe-receipt" | "observe-replay")
    ) {
        // hlx:68
        return match observed_receipt::cli(&args[1..], args[0] == "observe-replay") {
            Ok(s) => {
                println!("{s}");
                0
            }
            Err(e) => fail(&kernel::error_json(&e)),
        };
        // hlx:69
    }
    // hlx:70
    let is_help = |a: &String| a == "--help" || a == "-h";
    // hlx:71
    let sub_ok = |a: &String| {
        matches!(
            a.as_str(),
            "validate"
                | "run"
                | "explain"
                | "receipt"
                | "replay"
                | "compose"
                | "refine"
                | "export-boundary"
                | "integrity"
                | "dependencies"
        )
    };
    // hlx:72
    if (args.len() == 1 && is_help(&args[0]))
        || (args.len() == 2 && sub_ok(&args[0]) && is_help(&args[1]))
    {
        // hlx:73
        println!("{USAGE}");
        // hlx:74
        return 0;
        // hlx:75
    }
    // hlx:76
    let mode = match args.first().map(String::as_str) {
        // hlx:77
        Some("validate") => Mode::Validate,
        // hlx:78
        Some("run") => Mode::Run,
        // hlx:79
        Some("explain") => Mode::Explain,
        // hlx:80
        Some("receipt")
        | Some("replay")
        | Some("compose")
        | Some("refine")
        | Some("export-boundary")
        | Some("integrity")
        | Some("dependencies") => Mode::Run,
        // hlx:81
        Some(other) if other.starts_with('-') => {
            return fail(&usage_error("expected validate, run or explain first"))
        }
        // hlx:82
        Some(_) => {
            return fail(&usage_error(
                "unknown subcommand; expected validate, run or explain",
            ))
        }
        // hlx:83
        None => {
            return fail(&usage_error(
                "missing subcommand; expected validate, run or explain",
            ))
        }
        // hlx:84
    };
    // hlx:85
    let mut input: Option<String> = None;
    // hlx:86
    let mut i = 1;
    // hlx:87
    while i < args.len() {
        // hlx:88
        let a = &args[i];
        // hlx:89
        let value = if a == "--input" {
            // hlx:90
            i += 1;
            // hlx:91
            match args.get(i) {
                // hlx:92
                Some(v) if v == "-" || !v.starts_with("--") => v.clone(),
                // hlx:93
                _ => return fail(&usage_error("--input needs a file path or -")),
                // hlx:94
            }
        // hlx:95
        } else if let Some(v) = a.strip_prefix("--input=") {
            // hlx:96
            v.to_string()
        // hlx:97
        } else if a.starts_with('-') && a != "-" {
            // hlx:98
            return fail(&usage_error("unknown option (only --input is accepted; --help is only accepted as `check --help` or `check SUBCOMMAND --help`)"));
        // hlx:99
        } else {
            // hlx:100
            return fail(&usage_error("unexpected positional argument"));
            // hlx:101
        };
        // hlx:102
        if input.is_some() {
            // hlx:103
            return fail(&usage_error("--input given more than once"));
            // hlx:104
        }
        // hlx:105
        input = Some(value);
        // hlx:106
        i += 1;
        // hlx:107
    }
    // hlx:108
    let path = match input {
        // hlx:109
        Some(p) if !p.is_empty() => p,
        // hlx:110
        _ => return fail(&usage_error("--input FILE|- is required")),
        // hlx:111
    };
    // hlx:112
    let max = if args[0] == "replay" {
        json::MAX_BYTES + json::REPLAY_EXTRA_BYTES
    } else {
        json::MAX_BYTES
    };
    // hlx:113
    let bytes = match read_input_capped(&path, max) {
        // hlx:114
        Ok(b) => b,
        // hlx:115
        Err(e) => return fail(&kernel::error_json(&e)),
        // hlx:116
    };
    // hlx:117
    let (out, is_error) = match args[0].as_str() {
        // hlx:118
        "receipt" => receipt::create(&bytes),
        // hlx:119
        "replay" => receipt::replay(&bytes),
        // hlx:120
        "compose" => compose::compose(&bytes),
        // hlx:121
        "dependencies" => dependencies::evaluate(&bytes),
        // hlx:122
        "refine" => refine::evaluate(&bytes),
        // hlx:123
        "export-boundary" => export_boundary::evaluate(&bytes),
        // hlx:124
        "integrity" => integrity::evaluate(&bytes),
        // hlx:125
        _ => evaluate(mode, &bytes),
        // hlx:126
    };
    // hlx:127
    println!("{out}");
    // hlx:128
    if is_error {
        // hlx:129
        2
    // hlx:130
    } else {
        // hlx:131
        0
        // hlx:132
    }
    // hlx:133
}
// hlx:134
fn fail(json: &str) -> i32 {
    // hlx:135
    println!("{json}");
    // hlx:136
    2
    // hlx:137
}