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/sync.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:4
use super::{journal, parse_json, Json};
// hlx:5
use std::collections::HashMap;
// hlx:6
use std::path::Path;
// hlx:9
struct Row {
    // hlx:10
    line: String,
    // hlx:11
    key: String,
    // hlx:12
    outcome: Option<bool>,
    // hlx:13
}
// hlx:15
pub struct Report {
    // hlx:16
    pub source: usize,
    // hlx:17
    pub added: usize,
    // hlx:18
    pub had: usize,
    // hlx:19
    pub conflicts: usize,
    // hlx:20
}
// hlx:22
pub struct Plan {
    // hlx:23
    pub missing: Vec<String>,
    // hlx:24
    pub had: usize,
    // hlx:25
    pub conflicts: usize,
    // hlx:26
}
// hlx:29
fn row(line: &str, label: &str, n: usize) -> Result<Row, String> {
    // hlx:30
    let line = line.trim();
    // hlx:31
    let v = parse_json(line).map_err(|e| format!("{label}:{n}: {e}"))?;
    // hlx:32
    let kind = v
        .get("kind")
        .and_then(Json::as_str)
        .ok_or_else(|| format!("{label}:{n}: event has no string kind"))?;
    // hlx:33
    let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("");
    // hlx:34
    if matches!(kind, "hit" | "miss") && !s("outcome_id").is_empty() {
        // hlx:35
        return Ok(Row {
            line: line.to_string(),
            key: format!("o\t{}\t{}", s("id"), s("outcome_id")),
            outcome: Some(kind == "hit"),
        });
        // hlx:36
    }
    // hlx:37
    Ok(Row {
        line: line.to_string(),
        key: format!("l\t{line}"),
        outcome: None,
    })
    // hlx:38
}
// hlx:41
fn read_rows(path: &Path) -> Result<Vec<Row>, String> {
    // hlx:42
    let text = journal::read(path)?;
    // hlx:43
    let label = path.display().to_string();
    // hlx:44
    let mut rows = Vec::new();
    // hlx:45
    for (n, line) in text
        .lines()
        .enumerate()
        .filter(|(_, l)| !l.trim().is_empty())
    {
        // hlx:46
        rows.push(row(line, &label, n + 1)?);
        // hlx:47
    }
    // hlx:48
    Ok(rows)
    // hlx:49
}
// hlx:54
fn plan(src: &[Row], dst: &[Row]) -> Plan {
    // hlx:55
    let mut verdicts: HashMap<&str, Option<bool>> = HashMap::new();
    // hlx:56
    let mut copies: HashMap<&str, usize> = HashMap::new();
    // hlx:57
    for r in dst {
        // hlx:58
        if r.outcome.is_some() {
            // hlx:59
            verdicts.entry(&r.key).or_insert(r.outcome);
            // hlx:60
        } else {
            // hlx:61
            *copies.entry(&r.key).or_insert(0) += 1;
            // hlx:62
        }
        // hlx:63
    }
    // hlx:64
    let mut plan = Plan {
        missing: Vec::new(),
        had: 0,
        conflicts: 0,
    };
    // hlx:65
    for r in src {
        // hlx:66
        if r.outcome.is_some() {
            // hlx:67
            if let Some(held) = verdicts.get(r.key.as_str()) {
                // hlx:68
                if *held == r.outcome {
                    // hlx:69
                    plan.had += 1;
                    // hlx:70
                } else {
                    // hlx:71
                    plan.conflicts += 1;
                    // hlx:72
                }
                // hlx:73
                continue;
                // hlx:74
            }
            // hlx:75
            verdicts.insert(&r.key, r.outcome);
            // hlx:76
        } else {
            // hlx:77
            if let Some(n) = copies.get_mut(r.key.as_str()).filter(|n| **n > 0) {
                // hlx:78
                *n -= 1;
                // hlx:79
                plan.had += 1;
                // hlx:80
                continue;
                // hlx:81
            }
            // hlx:82
        }
        // hlx:83
        plan.missing.push(r.line.clone());
        // hlx:84
    }
    // hlx:85
    plan
    // hlx:86
}
// hlx:88
fn same_file(a: &Path, b: &Path) -> bool {
    // hlx:89
    match (a.canonicalize(), b.canonicalize()) {
        (Ok(x), Ok(y)) => x == y,
        _ => a == b,
    }
    // hlx:90
}
// hlx:94
pub fn pull(dest: &Path, source: &Path) -> Result<Report, String> {
    // hlx:95
    if !source.try_exists().map_err(|e| e.to_string())? {
        // hlx:96
        return Err(format!("source bank {} does not exist", source.display()));
        // hlx:97
    }
    // hlx:98
    if same_file(dest, source) {
        // hlx:99
        return Err("source and destination are the same bank".into());
        // hlx:100
    }
    // hlx:101
    let _lock = journal::identity_lock(dest)?;
    // hlx:102
    let src = read_rows(source)?;
    // hlx:103
    let dst = read_rows(dest)?;
    // hlx:104
    let plan = plan(&src, &dst);
    // hlx:105
    journal::append_many(
        dest,
        &plan.missing.iter().map(String::as_str).collect::<Vec<_>>(),
    )?;
    // hlx:106
    Ok(Report {
        source: src.len(),
        added: plan.missing.len(),
        had: plan.had,
        conflicts: plan.conflicts,
    })
    // hlx:107
}
// hlx:110
pub fn status(a: &Path, b: &Path) -> Result<(usize, usize, usize), String> {
    // hlx:111
    if !b.try_exists().map_err(|e| e.to_string())? {
        // hlx:112
        return Err(format!("bank {} does not exist", b.display()));
        // hlx:113
    }
    // hlx:114
    let (ra, rb) = (read_rows(a)?, read_rows(b)?);
    // hlx:115
    let (from_b, from_a) = (plan(&rb, &ra), plan(&ra, &rb));
    // hlx:116
    Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
    // hlx:117
}