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 bench/case-learning/compare.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
#[allow(dead_code)]
// hlx:3
mod baseline {
    include!(env!("INSTINCT_BENCH_BASELINE"));
}
// hlx:4
#[allow(dead_code)]
// hlx:5
mod candidate {
    include!(env!("INSTINCT_BENCH_CANDIDATE"));
}
// hlx:6
use std::hint::black_box;
// hlx:7
use std::time::Instant;
// hlx:10
#[derive(Debug, Clone, PartialEq)]
// hlx:11
enum Json {
    // hlx:12
    Bool(bool),
    // hlx:13
    Num(f64),
    // hlx:14
    Str(String),
    // hlx:15
    Arr(Vec<Json>),
    // hlx:16
    Obj(Vec<(String, Json)>),
    // hlx:17
}
// hlx:19
impl Json {
    // hlx:20
    fn get(&self, key: &str) -> Option<&Json> {
        // hlx:21
        let Self::Obj(fields) = self else { return None };
        // hlx:22
        fields
            .iter()
            .find(|(name, _)| name == key)
            .map(|(_, value)| value)
        // hlx:23
    }
    // hlx:24
    fn as_str(&self) -> Option<&str> {
        // hlx:25
        match self {
            Self::Str(s) => Some(s),
            _ => None,
        }
        // hlx:26
    }
    // hlx:27
    fn as_f64(&self) -> Option<f64> {
        // hlx:28
        match self {
            Self::Num(n) => Some(*n),
            _ => None,
        }
        // hlx:29
    }
    // hlx:30
}
// hlx:32
fn object<const N: usize>(entries: [(&str, Json); N]) -> Json {
    // hlx:33
    Json::Obj(
        entries
            .into_iter()
            .map(|(key, value)| (key.into(), value))
            .collect(),
    )
    // hlx:34
}
// hlx:37
struct Random(u64);
// hlx:38
impl Random {
    // hlx:39
    fn next(&mut self) -> u64 {
        // hlx:40
        self.0 ^= self.0 << 13;
        // hlx:41
        self.0 ^= self.0 >> 7;
        // hlx:42
        self.0 ^= self.0 << 17;
        // hlx:43
        self.0
        // hlx:44
    }
    // hlx:45
    fn index(&mut self, limit: usize) -> usize {
        // hlx:46
        (self.next() % limit as u64) as usize
        // hlx:47
    }
    // hlx:48
}
// hlx:50
fn facts(width: usize, known: u16, truth: u16) -> Json {
    // hlx:51
    Json::Obj(
        (0..width)
            .filter(|bit| known & (1 << bit) != 0)
            // hlx:52
            .map(|bit| {
                (
                    format!("feature{bit:02}"),
                    Json::Bool(truth & (1 << bit) != 0),
                )
            })
            .collect(),
    )
    // hlx:53
}
// hlx:55
fn casebook(rng: &mut Random, size: usize, width: usize, handoff: bool) -> Json {
    // hlx:56
    let checks = (0..width)
        .map(|bit| {
            object([
                // hlx:57
                ("key", Json::Str(format!("feature{bit:02}"))),
                // hlx:58
                (
                    "question",
                    Json::Str(format!("What did check {bit} observe?")),
                ),
                // hlx:59
                (
                    "cost",
                    Json::Num(if handoff {
                        1.0
                    } else {
                        (1 + rng.index(5)) as f64
                    }),
                ),
                // hlx:60
            ])
        })
        .collect();
    // hlx:61
    let mut history: Vec<(u16, usize)> = Vec::new();
    // hlx:62
    let mut examples = Vec::new();
    // hlx:63
    for i in 0..size {
        // hlx:64
        let (truth, action) = if handoff {
            // hlx:65
            (
                i as u16,
                if i & 1 != 0 {
                    0
                } else if i & 2 != 0 {
                    1
                } else if i & 4 != 0 {
                    2
                } else {
                    3
                },
            )
        // hlx:66
        } else if i % 5 == 1 {
            // hlx:67
            let (truth, prior_action) = history[rng.index(i)];
            // hlx:68
            (truth, prior_action + usize::from(i % 3 == 0))
        // hlx:69
        } else {
            // hlx:70
            (rng.next() as u16, rng.index(12))
            // hlx:71
        };
        // hlx:72
        history.push((truth, action));
        // hlx:73
        examples.push(object([
            ("ref", Json::Str(format!("row{i:03}"))),
            // hlx:74
            ("facts", facts(width, u16::MAX, truth)),
            ("action", Json::Str(format!("repair{action}"))),
        ]));
        // hlx:75
    }
    // hlx:76
    object([
        ("checks", Json::Arr(checks)),
        ("examples", Json::Arr(examples)),
    ])
    // hlx:77
}
// hlx:79
fn compare_advice() -> usize {
    // hlx:80
    let mut rng = Random(0x34210abc645a2f75);
    // hlx:81
    let mut compared = 0;
    // hlx:82
    for book in 0..192 {
        // hlx:83
        let width = 1 + rng.index(16);
        // hlx:84
        let size = 1 + rng.index(128);
        // hlx:85
        let input = casebook(&mut rng, size, width, false);
        // hlx:86
        let old = baseline::Casebook::parse(&input).unwrap();
        // hlx:87
        let new = candidate::Casebook::parse(&input).unwrap();
        // hlx:88
        for query in 0..64 {
            // hlx:89
            let known = match query % 4 {
                0 => 0,
                1 => rng.next() as u16,
                2 => u16::MAX,
                _ => 1 << rng.index(width),
            };
            // hlx:90
            let observed = facts(width, known, rng.next() as u16);
            // hlx:91
            assert_eq!(
                old.advise(&observed).unwrap(),
                new.advise(&observed).unwrap(),
                "book {book}, {size} rows, {width} checks, {observed:?}"
            );
            // hlx:92
            compared += 1;
            // hlx:93
        }
        // hlx:94
    }
    // hlx:95
    compared
    // hlx:96
}
// hlx:98
fn measure(iterations: usize, mut advise: impl FnMut() -> Json) -> f64 {
    // hlx:99
    let start = Instant::now();
    // hlx:100
    for _ in 0..iterations {
        // hlx:101
        black_box(advise());
        // hlx:102
    }
    // hlx:103
    start.elapsed().as_nanos() as f64 / iterations as f64
    // hlx:104
}
// hlx:106
fn median(mut values: [f64; 12]) -> f64 {
    // hlx:107
    values.sort_by(f64::total_cmp);
    // hlx:108
    (values[5] + values[6]) / 2.0
    // hlx:109
}
// hlx:111
fn benchmark(width: usize, size: usize, handoff: bool, known: u16, iterations: usize) {
    // hlx:112
    let input = casebook(&mut Random(0x5ca1a2c091821443), size, width, handoff);
    // hlx:113
    let old = baseline::Casebook::parse(&input).unwrap();
    // hlx:114
    let new = candidate::Casebook::parse(&input).unwrap();
    // hlx:115
    let observed = facts(width, known, 0);
    // hlx:116
    let run_old = || measure(iterations, || old.advise(black_box(&observed)).unwrap());
    // hlx:117
    let run_new = || measure(iterations, || new.advise(black_box(&observed)).unwrap());
    // hlx:118
    let mut times = [(0.0, 0.0); 12];
    // hlx:120
    black_box((run_old(), run_new()));
    // hlx:121
    for (round, slot) in times.iter_mut().enumerate() {
        // hlx:122
        *slot = if round % 2 == 0 {
            let new_time = run_new();
            (run_old(), new_time)
        } else {
            (run_old(), run_new())
        };
        // hlx:123
    }
    // hlx:124
    let old_ns = median(times.map(|(o, _)| o));
    // hlx:125
    let new_ns = median(times.map(|(_, n)| n));
    // hlx:126
    let ratio = median(times.map(|(o, n)| o / n));
    // hlx:127
    println!("{size} rows / {width} checks, mask {known:#x}: baseline {old_ns:.0} ns, candidate {new_ns:.0} ns, paired speedup {ratio:.3}x");
    // hlx:128
}
// hlx:130
fn main() {
    // hlx:131
    println!(
        "Full advice matched on {} seeded decisions.",
        compare_advice()
    );
    // hlx:132
    benchmark(3, 8, true, 0, 18_000);
    // hlx:133
    benchmark(3, 8, true, 1, 18_000);
    // hlx:134
    benchmark(16, 128, false, 0, 700);
    // hlx:135
    benchmark(16, 128, false, 1, 1_200);
    // hlx:136
}