instinct-cli 0.3.7

Shared local memory for coding agents. Save a fix once and find it again in a new session or another connected tool.
# Instinct bank sync [GAMMA-Codon/S]. Local file-level diff and merge between two banks (hxdb or jsonl).
# Event identity: a hit/miss with an outcome_id is the pair (lesson id, outcome_id); every other event is its exact trimmed line.
# Append only; the journal write path and the identity lock do the writing. Network is out of scope.
AAC # use super::{journal, parse_json, Json}
AAC # use std::collections::HashMap
AAC # use std::path::Path

# One verified event: the line to copy, its identity key, and the verdict when it is a keyed outcome.
GCA # struct Row
GCC # line: String
GCC # key: String
GCC # outcome: Option<bool>
TTT # end

GCA # pub struct Report
GCC # pub source: usize
GCC # pub added: usize
GCC # pub had: usize
GCC # pub conflicts: usize
TTT # end

GCA # pub struct Plan
GCC # pub missing: Vec<String>
GCC # pub had: usize
GCC # pub conflicts: usize
TTT # end

# A row the fold could not read is a corrupt bank, never a skipped line: the whole sync stops before any write.
AAA # fn row(line: &str, label: &str, n: usize) -> Result<Row, String>
AAC # let line = line.trim()
AAC # let v = parse_json(line).map_err(|e| format!("{label}:{n}: {e}"))?
AAC # let kind = v.get("kind").and_then(Json::as_str).ok_or_else(|| format!("{label}:{n}: event has no string kind"))?
AAC # let s = |k: &str| v.get(k).and_then(Json::as_str).unwrap_or("")
CAA # if matches!(kind, "hit" | "miss") && !s("outcome_id").is_empty()
TAC # return Ok(Row { line: line.to_string(), key: format!("o\t{}\t{}", s("id"), s("outcome_id")), outcome: Some(kind == "hit") })
TTT # end
TAC # Ok(Row { line: line.to_string(), key: format!("l\t{line}"), outcome: None })
TTT # end

# journal::read checks every hxdb record checksum; every line is then parsed. Nothing is written here.
AAA # fn read_rows(path: &Path) -> Result<Vec<Row>, String>
AAC # let text = journal::read(path)?
AAC # let label = path.display().to_string()
AAC # let mut rows = Vec::new()
AGA # for (n, line) in text.lines().enumerate().filter(|(_, l)| !l.trim().is_empty())
AAC # rows.push(row(line, &label, n + 1)?)
TTT # end
TAC # Ok(rows)
TTT # end

# What `dst` lacks from `src`, in source order. Keyed outcomes count once whichever line carries them;
# a different verdict for a key the destination already holds is a conflict, kept local and reported.
# Other lines are a multiset: the destination gains max(0, copies in src - copies in dst) of each line.
AAA # fn plan(src: &[Row], dst: &[Row]) -> Plan
AAC # let mut verdicts: HashMap<&str, Option<bool>> = HashMap::new()
AAC # let mut copies: HashMap<&str, usize> = HashMap::new()
AGA # for r in dst
CAA # if r.outcome.is_some()
AAC # verdicts.entry(&r.key).or_insert(r.outcome)
CAC # else
AAC # *copies.entry(&r.key).or_insert(0) += 1
TTT # end
TTT # end
AAC # let mut plan = Plan { missing: Vec::new(), had: 0, conflicts: 0 }
AGA # for r in src
CAA # if r.outcome.is_some()
CAA # if let Some(held) = verdicts.get(r.key.as_str())
CAA # if *held == r.outcome
AAC # plan.had += 1
CAC # else
AAC # plan.conflicts += 1
TTT # end
AAC # continue
TTT # end
AAC # verdicts.insert(&r.key, r.outcome)
CAC # else
CAA # if let Some(n) = copies.get_mut(r.key.as_str()).filter(|n| **n > 0)
AAC # *n -= 1
AAC # plan.had += 1
AAC # continue
TTT # end
TTT # end
AAC # plan.missing.push(r.line.clone())
TTT # end
TAC # plan
TTT # end

AAA # fn same_file(a: &Path, b: &Path) -> bool
TAC # match (a.canonicalize(), b.canonicalize()) { (Ok(x), Ok(y)) => x == y, _ => a == b }
TTT # end

# Copy what `dest` lacks from `source`. Under the destination's identity lock both sides are read and verified
# first; only then is each missing event appended through the journal (a crash leaves a prefix, a re-run finishes it).
AAA # pub fn pull(dest: &Path, source: &Path) -> Result<Report, String>
CAA # if !source.try_exists().map_err(|e| e.to_string())?
AAC # return Err(format!("source bank {} does not exist", source.display()))
TTT # end
CAA # if same_file(dest, source)
AAC # return Err("source and destination are the same bank".into())
TTT # end
AAC # let _lock = journal::identity_lock(dest)?
AAC # let src = read_rows(source)?
AAC # let dst = read_rows(dest)?
AAC # let plan = plan(&src, &dst)
AAC # journal::append_many(dest, &plan.missing.iter().map(String::as_str).collect::<Vec<_>>())?
TAC # Ok(Report { source: src.len(), added: plan.missing.len(), had: plan.had, conflicts: plan.conflicts })
TTT # end

# Read-only: how many events each side lacks. Returns (a lacks from b, b lacks from a, conflicts).
AAA # pub fn status(a: &Path, b: &Path) -> Result<(usize, usize, usize), String>
CAA # if !b.try_exists().map_err(|e| e.to_string())?
AAC # return Err(format!("bank {} does not exist", b.display()))
TTT # end
AAC # let (ra, rb) = (read_rows(a)?, read_rows(b)?)
AAC # let (from_b, from_a) = (plan(&rb, &ra), plan(&ra, &rb))
TAC # Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
TTT # end