Skip to main content

borg_mesh/
lines.rs

1//! A collective's append-only logs as sets of content-addressed lines.
2//!
3//! Every line of `lessons.jsonl` is addressed by its blake3 hash, so two
4//! nodes compare what they hold without reading it, and a merge is a plain union: appending lines
5//! the store lacks never rewrites or loses a line. Only complete JSON lines count, so a line a
6//! hook is appending right now is picked up by the next sync rather than copied half-written.
7//!
8//! Lessons are versioned in place (a consolidation appends the same id with `version + 1`) and
9//! `conscience::load` keeps the *last* line per id. After a union the last line must therefore be
10//! the winning version on every node, whatever order the lines arrived in: highest version, ties
11//! (two nodes consolidated the same lesson concurrently) broken by the higher hash. `settle`
12//! re-appends a winner that is not last; that repeats an existing line, so the hash set (and what
13//! peers see) is unchanged.
14
15use std::collections::{BTreeMap, HashMap};
16use std::io::Write;
17use std::path::Path;
18
19use serde_json::Value;
20
21/// The logs a mesh syncs, relative to the collective's store.
22///
23/// Lessons, and the daily usage rollups (borg stats.rs): versioned records like lessons, one bucket per
24/// (node, engineer, day), counts only. Not episodes: a lesson already carries its `episodes` ids and `engineers`; the raw episodes stay
25/// on the node that captured them, so exactly one node learns each episode. Synced episodes were
26/// pending on every node (learn.rs skips only episodes cited by a lesson or rejected locally), so
27/// each member paid a model call per peer episode, and two members could learn the same correction
28/// into two lessons under different ids. Episodes also hold the engineer's raw words.
29///
30/// And the team's outcomes (borg outcome.rs `publish`): redacted lines, one per result, with the kind,
31/// lesson ids, time, asking propensity, hashed session and repo, and the node; never raw sessions,
32/// repos or text. Plain lines (no `id` + `version`), so `settle` leaves them alone; signed and
33/// quarantined like every synced log.
34///
35/// And the ratified constraints (borg veto.rs `ratify`): standing lessons every member's sessions get
36/// (conscience.rs `standing`), lines holding what a lesson does (the redacted invariant, its lesson,
37/// who ratified it). Plain lines (no `version`); the conscience keeps the earliest ratification per id,
38/// so arrival order does not matter.
39///
40/// And the messages between sessions (borg msg.rs): plain lines, each naming its author's node. That
41/// name is a claim, so a message travels only under an origin of the key it names (`travels`), and
42/// only while it is fresh: a line one node pruned would otherwise come back from every peer. Last in
43/// the list: a 0.3.0 peer (`borg/mesh/12`) never reconciles this one.
44///
45/// The removed playbooks' log is not listed: a session still steps through it after the outcomes
46/// and keeps nothing (sync.rs `PLAYBOOKS`).
47pub const SYNCED: [&str; 5] = ["lessons.jsonl", "stats.jsonl", borg::outcome::TEAM_FILE, borg::veto::FILE, borg::msg::FILE];
48
49/// Redacted reasoning excerpts behind git notes (`borg notes`): replicated by their author to
50/// `sync::REPLICAS` members, not reconciled with everyone (sync.rs, step 4).
51pub const REASONING: &str = "reasoning.jsonl";
52
53pub type Hash = [u8; 32];
54
55/// The logs whose lines carry origins, in `home`: the synced ones and reasoning. Stamping (origin.rs
56/// `stamp`), quarantine (`origin::apply`) and the daemon's change fingerprint all cover what this lists.
57pub fn logs(home: &Path) -> Vec<std::path::PathBuf> {
58    let mut out: Vec<std::path::PathBuf> = SYNCED.iter().map(|f| home.join(f)).collect();
59    out.push(home.join(REASONING));
60    out
61}
62
63/// Whether `line` of the log `file` may be offered or stored under an origin of `key`, at `now`. Any
64/// line but a message's. A message must be one borg msg.rs could have written (`well_formed`), name
65/// `key` as its node (the member key its sender wrote, as `borg top` names a remote node), and be
66/// fresh (msg.rs `fresh`: neither past `TTL_MS` nor stamped further ahead of this clock than
67/// `SKEW_MS`): a member's forged node, or a far-future line that would outlive every prune, never
68/// reaches another member. A message to the sessions of its own node (`local`, msg.rs `stays_here`)
69/// never travels: it is for that machine alone.
70pub fn travels(file: &str, line: &str, key: &str, now: i64) -> bool {
71    if file != borg::msg::FILE {
72        return true;
73    }
74    let Ok(m) = serde_json::from_str::<borg::msg::Message>(line) else { return false };
75    m.well_formed() && m.node == key && borg::msg::fresh(&m, now) && !m.stays_here()
76}
77
78pub fn hash(line: &str) -> Hash {
79    *blake3::hash(line.as_bytes()).as_bytes()
80}
81
82fn complete(line: &str) -> bool {
83    !line.trim().is_empty() && serde_json::from_str::<Value>(line).is_ok()
84}
85
86/// The distinct complete lines of `path` by hash (empty if the file does not exist).
87pub fn read(path: &Path) -> BTreeMap<Hash, String> {
88    let text = std::fs::read_to_string(path).unwrap_or_default();
89    text.lines().filter(|l| complete(l)).map(|l| (hash(l), l.to_string())).collect()
90}
91
92/// One hash for the whole set: equal digests mean there is nothing to exchange.
93pub fn digest(set: &BTreeMap<Hash, String>) -> Hash {
94    let mut h = blake3::Hasher::new();
95    for k in set.keys() {
96        h.update(k);
97    }
98    *h.finalize().as_bytes()
99}
100
101/// Appends the `incoming` lines `path` lacks, then settles lesson versions. Returns how many lines
102/// were new.
103pub fn merge(path: &Path, incoming: &[String]) -> Result<usize, String> {
104    let mut known = read(path);
105    let new: Vec<&String> = incoming.iter().filter(|l| complete(l) && known.insert(hash(l), (*l).clone()).is_none()).collect();
106    append(path, &new)?;
107    settle(path)?;
108    Ok(new.len())
109}
110
111fn append(path: &Path, lines: &[&String]) -> Result<(), String> {
112    if lines.is_empty() {
113        return Ok(());
114    }
115    if let Some(d) = path.parent() {
116        std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
117    }
118    let ends_open = std::fs::read(path).map(|b| b.last().is_some_and(|c| *c != b'\n')).unwrap_or(false);
119    let mut out = String::from(if ends_open { "\n" } else { "" });
120    for l in lines {
121        out.push_str(l);
122        out.push('\n');
123    }
124    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
125    f.write_all(out.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
126}
127
128/// Makes the winning version of every versioned record the last line for its id (module doc).
129/// Also after lines were removed (quarantine): the line that is now last may be an older version.
130pub fn settle(path: &Path) -> Result<(), String> {
131    let text = std::fs::read_to_string(path).unwrap_or_default();
132    let mut winner: HashMap<String, ((u64, Hash), &str)> = HashMap::new();
133    let mut last: HashMap<String, Hash> = HashMap::new();
134    for l in text.lines() {
135        let Ok(v) = serde_json::from_str::<Value>(l) else { continue };
136        let (Some(id), Some(version)) = (v["id"].as_str(), v["version"].as_u64()) else { continue };
137        let rank = (version, hash(l));
138        last.insert(id.to_string(), rank.1);
139        if winner.get(id).is_none_or(|(r, _)| rank > *r) {
140            winner.insert(id.to_string(), (rank, l));
141        }
142    }
143    let mut stale: Vec<(&String, String)> = winner.iter().filter(|(id, (r, _))| last.get(*id) != Some(&r.1)).map(|(id, (_, l))| (id, l.to_string())).collect();
144    stale.sort();
145    append(path, &stale.iter().map(|(_, l)| l).collect::<Vec<_>>())
146}
147
148#[cfg(test)]
149mod tests {
150    use super::*;
151
152    fn lesson(id: &str, version: u32, q: &str) -> String {
153        serde_json::json!({"id": id, "origin_ms": 1, "question": q, "version": version}).to_string()
154    }
155
156    fn tmp(tag: &str) -> std::path::PathBuf {
157        let d = std::env::temp_dir().join(format!("borg-mesh-lines-{tag}-{}", std::process::id()));
158        let _ = std::fs::remove_dir_all(&d);
159        std::fs::create_dir_all(&d).unwrap();
160        d
161    }
162
163    /// `local` is this machine's sessions: its line never travels; `collective` (written `all`) does.
164    #[test]
165    fn a_local_broadcast_never_travels() {
166        let key = "ab".repeat(32);
167        let from = borg::msg::Sender { by: "s1".into(), name: "One of Two".into(), harness: "claude".into(), node: key.clone() };
168        let line = |to: &str| serde_json::to_string(&borg::msg::Message::new(borg::msg::TELL, &from, to, None, 1_000, "freeze merges")).unwrap();
169        assert!(!travels(borg::msg::FILE, &line(&format!("{}@{key}", borg::msg::LOCAL)), &key, 1_000));
170        assert!(travels(borg::msg::FILE, &line(borg::msg::ALL), &key, 1_000));
171        assert!(travels(borg::msg::FILE, &line(&format!("s2@{}", "cd".repeat(32))), &key, 1_000));
172    }
173
174    #[test]
175    fn union_skips_known_and_torn_lines() {
176        let d = tmp("union");
177        let p = d.join("lessons.jsonl");
178        std::fs::write(&p, format!("{}\n{{\"id\":\"L2\",\"ver", lesson("L1", 1, "a"))).unwrap();
179        assert_eq!(read(&p).len(), 1, "a half-written line does not count");
180        let n = merge(&p, &[lesson("L1", 1, "a"), lesson("L3", 1, "c"), "garbage".into()]).unwrap();
181        assert_eq!(n, 1, "only the unknown complete line is new");
182        assert_eq!(merge(&p, &[lesson("L3", 1, "c")]).unwrap(), 0, "idempotent");
183        let _ = std::fs::remove_dir_all(d);
184    }
185
186    #[test]
187    fn ratified_constraints_sync_and_load_as_the_same_standing_lesson_everywhere() {
188        let d = tmp("constraints");
189        assert!(logs(&d).contains(&d.join(borg::veto::FILE)), "stamped, signed and quarantined like the lessons");
190        let c = |by: &str, ms: i64| {
191            serde_json::json!({"id": "cabc", "text": "merge lookups go through the review API", "lesson": "L1", "by": by, "ms": ms, "source": "veto"})
192                .to_string()
193        };
194        let (a, b) = (d.join("a"), d.join("b"));
195        for (home, own) in [(&a, c("bob@x", 9)), (&b, c("ann@x", 5))] {
196            std::fs::create_dir_all(home).unwrap();
197            std::fs::write(home.join("lessons.jsonl"), format!("{}\n", lesson("L1", 1, "lookup?"))).unwrap();
198            merge(&home.join(borg::veto::FILE), &[own]).unwrap();
199        }
200        merge(&a.join(borg::veto::FILE), &read(&b.join(borg::veto::FILE)).into_values().collect::<Vec<_>>()).unwrap();
201        merge(&b.join(borg::veto::FILE), &read(&a.join(borg::veto::FILE)).into_values().collect::<Vec<_>>()).unwrap();
202        let standing = |h: &Path| {
203            let v: Vec<_> = borg::conscience::load(&h.join("lessons.jsonl"), None)
204                .into_iter()
205                .filter(|c| c.standing())
206                .map(|c| (c.id, c.engineers, c.consolidated))
207                .collect();
208            v
209        };
210        assert_eq!(standing(&a), [("cabc".to_string(), vec!["ann@x".to_string()], true)], "the earliest ratification, whatever the order");
211        assert_eq!(standing(&a), standing(&b));
212        let _ = std::fs::remove_dir_all(d);
213    }
214
215    #[test]
216    fn concurrent_versions_settle_on_the_same_winner_everywhere() {
217        let d = tmp("settle");
218        let (a, b) = (d.join("a/lessons.jsonl"), d.join("b/lessons.jsonl"));
219        let (v1, v2a, v2b) = (lesson("L1", 1, "orig"), lesson("L1", 2, "alice's merge"), lesson("L1", 2, "bob's merge"));
220        merge(&a, &[v1.clone(), v2a.clone()]).unwrap();
221        merge(&b, &[v1.clone(), v2b.clone()]).unwrap();
222        merge(&a, &read(&b).into_values().collect::<Vec<_>>()).unwrap();
223        merge(&b, &read(&a).into_values().collect::<Vec<_>>()).unwrap();
224        assert_eq!(digest(&read(&a)), digest(&read(&b)), "same set");
225        let q = |p: &Path| borg::conscience::load(p, None).into_iter().map(|c| c.question).collect::<Vec<_>>();
226        assert_eq!(q(&a), q(&b), "the conscience asks the same version on both nodes");
227        assert_ne!(q(&a), vec!["orig".to_string()], "an older version never wins");
228        // Arriving out of order (newest first) still leaves the newest last.
229        let c = d.join("c/lessons.jsonl");
230        merge(&c, &[v2a]).unwrap();
231        merge(&c, &[v1]).unwrap();
232        assert_eq!(q(&c), vec!["alice's merge".to_string()]);
233        let _ = std::fs::remove_dir_all(d);
234    }
235}