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/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, HashSet};
// 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
    casebook: bool,
    // hlx:14
}
// hlx:16
pub struct Report {
    // hlx:17
    pub source: usize,
    // hlx:18
    pub added: usize,
    // hlx:19
    pub had: usize,
    // hlx:20
    pub conflicts: usize,
    // hlx:21
}
// hlx:23
pub struct Plan {
    // hlx:24
    pub missing: Vec<String>,
    // hlx:25
    pub had: usize,
    // hlx:26
    pub conflicts: usize,
    // hlx:27
}
// hlx:30
fn row(line: &str, label: &str, n: usize) -> Result<Row, String> {
    // hlx:31
    let line = line.trim();
    // hlx:32
    let v = parse_json(line).map_err(|e| format!("{label}:{n}: {e}"))?;
    // hlx:33
    let kind = v
        .get("kind")
        .and_then(Json::as_str)
        .ok_or_else(|| format!("{label}:{n}: event has no string kind"))?;
    // hlx:34
    let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("");
    // hlx:35
    if matches!(kind, "hit" | "miss") && !s("outcome_id").is_empty() {
        // hlx:36
        return Ok(Row {
            line: line.to_string(),
            key: format!("o\t{}\t{}", s("id"), s("outcome_id")),
            outcome: Some(kind == "hit"),
            casebook: false,
        });
        // hlx:37
    }
    // hlx:38
    Ok(Row {
        line: line.to_string(),
        key: format!("l\t{line}"),
        outcome: None,
        casebook: kind == "casebook",
    })
    // hlx:39
}
// hlx:42
fn read_rows(path: &Path) -> Result<Vec<Row>, String> {
    // hlx:43
    let text = journal::read(path)?;
    // hlx:44
    let label = path.display().to_string();
    // hlx:45
    let mut rows = Vec::new();
    // hlx:46
    for (n, line) in text
        .lines()
        .enumerate()
        .filter(|(_, l)| !l.trim().is_empty())
    {
        // hlx:47
        rows.push(row(line, &label, n + 1)?);
        // hlx:48
    }
    // hlx:49
    Ok(rows)
    // hlx:50
}
// hlx:55
fn plan(src: &[Row], dst: &[Row], dest: &Path) -> Result<Plan, String> {
    // hlx:56
    let mut verdicts: HashMap<&str, Option<bool>> = HashMap::new();
    // hlx:57
    let mut copies: HashMap<&str, usize> = HashMap::new();
    // hlx:58
    for r in dst {
        // hlx:59
        if r.outcome.is_some() {
            // hlx:60
            verdicts.entry(&r.key).or_insert(r.outcome);
            // hlx:61
        } else {
            // hlx:62
            *copies.entry(&r.key).or_insert(0) += 1;
            // hlx:63
        }
        // hlx:64
    }
    // hlx:65
    let mut plan = Plan {
        missing: Vec::new(),
        had: 0,
        conflicts: 0,
    };
    // hlx:66
    let mut adds_cases = false;
    // hlx:67
    let mut conflicting_outcomes = HashSet::new();
    // hlx:68
    for r in src {
        // hlx:69
        if r.outcome.is_some() {
            // hlx:70
            if let Some(held) = verdicts.get(r.key.as_str()) {
                // hlx:71
                if *held == r.outcome {
                    // hlx:72
                    plan.had += 1;
                    // hlx:73
                } else {
                    // hlx:74
                    plan.conflicts += 1;
                    // hlx:75
                    conflicting_outcomes.insert(r.key.as_str());
                    // hlx:76
                }
                // hlx:77
                continue;
                // hlx:78
            }
            // hlx:79
            verdicts.insert(&r.key, r.outcome);
            // hlx:80
        } else {
            // hlx:81
            if let Some(n) = copies.get_mut(r.key.as_str()).filter(|n| **n > 0) {
                // hlx:82
                *n -= 1;
                // hlx:83
                plan.had += 1;
                // hlx:84
                continue;
                // hlx:85
            }
            // hlx:86
        }
        // hlx:87
        plan.missing.push(r.line.clone());
        // hlx:88
        adds_cases |= r.casebook;
        // hlx:89
    }
    // hlx:90
    if adds_cases {
        // hlx:91
        if super::is_team_bank(dest) {
            // hlx:92
            return Err("cannot sync personal casebooks into a team bank".into());
            // hlx:93
        }
        // hlx:94
        if !conflicting_outcomes.is_empty() {
            // hlx:95
            for line in &plan.missing {
                // hlx:96
                check_case_verdicts(line, &conflicting_outcomes)?;
                // hlx:97
            }
            // hlx:98
        }
        // hlx:99
        // Independent sites may have assigned different observations to one reference. Validate before appending any row.
        // hlx:100
        let prospective = dst
            .iter()
            .map(|r| r.line.as_str())
            .chain(plan.missing.iter().map(String::as_str))
            .collect::<Vec<_>>()
            .join("\n");
        // hlx:101
        super::fold_text(&prospective, &dest.display().to_string(), |_, _, _, _| {})?;
        // hlx:102
    }
    // hlx:103
    Ok(plan)
    // hlx:104
}
// hlx:107
fn check_case_verdicts(line: &str, conflicting: &HashSet<&str>) -> Result<(), String> {
    // hlx:108
    let v = parse_json(line)?;
    // hlx:109
    if v.get("kind").and_then(Json::as_str) != Some("casebook") {
        // hlx:110
        return Ok(());
        // hlx:111
    }
    // hlx:112
    let id = v.get("id").and_then(Json::as_str).unwrap_or("");
    // hlx:113
    let Some(Json::Arr(examples)) = v.get("casebook").and_then(|b| b.get("examples")) else {
        return Err("invalid casebook examples".into());
    };
    // hlx:114
    for reference in examples
        .iter()
        .filter_map(|row| row.get("ref").and_then(Json::as_str))
    {
        // hlx:115
        if conflicting.contains(format!("o\t{id}\t{reference}").as_str()) {
            // hlx:116
            return Err(format!(
                "conflicting verdict for case {reference}; nothing copied"
            ));
            // hlx:117
        }
        // hlx:118
    }
    // hlx:119
    Ok(())
    // hlx:120
}
// hlx:122
fn same_file(a: &Path, b: &Path) -> bool {
    // hlx:123
    match (a.canonicalize(), b.canonicalize()) {
        (Ok(x), Ok(y)) => x == y,
        _ => a == b,
    }
    // hlx:124
}
// hlx:128
pub fn pull(dest: &Path, source: &Path) -> Result<Report, String> {
    // hlx:129
    if !source.try_exists().map_err(|e| e.to_string())? {
        // hlx:130
        return Err(format!("source bank {} does not exist", source.display()));
        // hlx:131
    }
    // hlx:132
    if same_file(dest, source) {
        // hlx:133
        return Err("source and destination are the same bank".into());
        // hlx:134
    }
    // hlx:135
    let _lock = journal::identity_lock(dest)?;
    // hlx:136
    let src = read_rows(source)?;
    // hlx:137
    let dst = read_rows(dest)?;
    // hlx:138
    let plan = plan(&src, &dst, dest)?;
    // hlx:139
    journal::append_many(
        dest,
        &plan.missing.iter().map(String::as_str).collect::<Vec<_>>(),
    )?;
    // hlx:140
    Ok(Report {
        source: src.len(),
        added: plan.missing.len(),
        had: plan.had,
        conflicts: plan.conflicts,
    })
    // hlx:141
}
// hlx:144
pub fn status(a: &Path, b: &Path) -> Result<(usize, usize, usize), String> {
    // hlx:145
    if !b.try_exists().map_err(|e| e.to_string())? {
        // hlx:146
        return Err(format!("bank {} does not exist", b.display()));
        // hlx:147
    }
    // hlx:148
    let (ra, rb) = (read_rows(a)?, read_rows(b)?);
    // hlx:149
    let (from_b, from_a) = (plan(&rb, &ra, a)?, plan(&ra, &rb, b)?);
    // hlx:150
    Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
    // hlx:151
}