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.
# 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, HashSet}
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>
GCC # casebook: 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"), casebook: false })
TTT # end
TAC # Ok(Row { line: line.to_string(), key: format!("l\t{line}"), outcome: None, casebook: kind == "casebook" })
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], dest: &Path) -> Result<Plan, String>
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 }
AAC # let mut adds_cases = false
AAC # let mut conflicting_outcomes = HashSet::new()
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
AAC # conflicting_outcomes.insert(r.key.as_str())
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())
AAC # adds_cases |= r.casebook
TTT # end
CAA # if adds_cases
CAA # if super::is_team_bank(dest)
TAC # return Err("cannot sync personal casebooks into a team bank".into())
TTT # end
CAA # if !conflicting_outcomes.is_empty()
AGA # for line in &plan.missing
AAC # check_case_verdicts(line, &conflicting_outcomes)?
TTT # end
TTT # end
TGT # Independent sites may have assigned different observations to one reference. Validate before appending any row.
AAC # let prospective = dst.iter().map(|r| r.line.as_str()).chain(plan.missing.iter().map(String::as_str)).collect::<Vec<_>>().join("\n")
AAC # super::fold_text(&prospective, &dest.display().to_string(), |_, _, _, _| {})?
TTT # end
TAC # Ok(plan)
TTT # end

# The correction and its outcome share a reference. Never copy the correction while dropping its verdict.
AAA # fn check_case_verdicts(line: &str, conflicting: &HashSet<&str>) -> Result<(), String>
AAC # let v = parse_json(line)?
CAA # if v.get("kind").and_then(Json::as_str) != Some("casebook")
TAC # return Ok(())
TTT # end
AAC # let id = v.get("id").and_then(Json::as_str).unwrap_or("")
AAC # let Some(Json::Arr(examples)) = v.get("casebook").and_then(|b| b.get("examples")) else { return Err("invalid casebook examples".into()) }
AGA # for reference in examples.iter().filter_map(|row| row.get("ref").and_then(Json::as_str))
CAA # if conflicting.contains(format!("o\t{id}\t{reference}").as_str())
TAC # return Err(format!("conflicting verdict for case {reference}; nothing copied"))
TTT # end
TTT # end
TAC # Ok(())
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, dest)?
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, a)?, plan(&ra, &rb, b)?)
TAC # Ok((from_b.missing.len(), from_a.missing.len(), from_b.conflicts))
TTT # end