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, and the
41/// `seen` lines their recipients write (msg.rs `Seen`, which pace the senders). That name is a claim,
42/// so a line travels only under an origin of the key it names (`travels`), and only while it is fresh:
43/// a line one node pruned would otherwise come back from every peer. Last in the list: a 0.3.0 peer
44/// (`borg/mesh/12`) never reconciles this one.
45///
46/// The removed playbooks' log is not listed: a session still steps through it after the outcomes
47/// and keeps nothing (sync.rs `PLAYBOOKS`).
48pub const SYNCED: [&str; 5] = ["lessons.jsonl", "stats.jsonl", borg::outcome::TEAM_FILE, borg::veto::FILE, borg::msg::FILE];
49
50/// Redacted reasoning excerpts behind git notes (`borg notes`): replicated by their author to
51/// `sync::REPLICAS` members, not reconciled with everyone (sync.rs, step 4).
52pub const REASONING: &str = "reasoning.jsonl";
53
54pub type Hash = [u8; 32];
55
56/// The logs whose lines carry origins, in `home`: the synced ones and reasoning. Stamping (origin.rs
57/// `stamp`), quarantine (`origin::apply`) and the daemon's change fingerprint all cover what this lists.
58pub fn logs(home: &Path) -> Vec<std::path::PathBuf> {
59    let mut out: Vec<std::path::PathBuf> = SYNCED.iter().map(|f| home.join(f)).collect();
60    out.push(home.join(REASONING));
61    out
62}
63
64/// Whether `line` of the log `file` may be offered or stored under an origin of `key`, at `now`. Any
65/// line but a message's. A message or a seen line must be one borg msg.rs could have written
66/// (`Line::parse`), name `key` as its node (the member key its sender or reader wrote, as `borg top`
67/// names a remote node), and be fresh (msg.rs `fresh_at`: neither past `TTL_MS` nor stamped further
68/// ahead of this clock than `SKEW_MS`): a member's forged node, or a far-future line that would outlive
69/// every prune, never reaches another member, and no node acknowledges for another's sessions. A
70/// message to the sessions of its own node (`local`, msg.rs `stays_here`) never travels: it is for
71/// that machine alone.
72pub fn travels(file: &str, line: &str, key: &str, now: i64) -> bool {
73    if file != borg::msg::FILE {
74        return true;
75    }
76    let Some(l) = borg::msg::Line::parse(line) else { return false };
77    l.node() == key && borg::msg::fresh_at(l.ms(), now) && l.message().is_none_or(|m| !m.stays_here())
78}
79
80pub fn hash(line: &str) -> Hash {
81    *blake3::hash(line.as_bytes()).as_bytes()
82}
83
84fn complete(line: &str) -> bool {
85    !line.trim().is_empty() && serde_json::from_str::<Value>(line).is_ok()
86}
87
88/// The distinct complete lines of `path` by hash (empty if the file does not exist).
89pub fn read(path: &Path) -> BTreeMap<Hash, String> {
90    let text = std::fs::read_to_string(path).unwrap_or_default();
91    text.lines().filter(|l| complete(l)).map(|l| (hash(l), l.to_string())).collect()
92}
93
94/// One hash for the whole set: equal digests mean there is nothing to exchange.
95pub fn digest(set: &BTreeMap<Hash, String>) -> Hash {
96    let mut h = blake3::Hasher::new();
97    for k in set.keys() {
98        h.update(k);
99    }
100    *h.finalize().as_bytes()
101}
102
103/// Appends the `incoming` lines `path` lacks, then settles lesson versions. Returns how many lines
104/// were new.
105pub fn merge(path: &Path, incoming: &[String]) -> Result<usize, String> {
106    let mut known = read(path);
107    let new: Vec<&String> = incoming.iter().filter(|l| complete(l) && known.insert(hash(l), (*l).clone()).is_none()).collect();
108    append(path, &new)?;
109    settle(path)?;
110    Ok(new.len())
111}
112
113fn append(path: &Path, lines: &[&String]) -> Result<(), String> {
114    if lines.is_empty() {
115        return Ok(());
116    }
117    if let Some(d) = path.parent() {
118        std::fs::create_dir_all(d).map_err(|e| e.to_string())?;
119    }
120    let ends_open = std::fs::read(path).map(|b| b.last().is_some_and(|c| *c != b'\n')).unwrap_or(false);
121    let mut out = String::from(if ends_open { "\n" } else { "" });
122    for l in lines {
123        out.push_str(l);
124        out.push('\n');
125    }
126    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(path).map_err(|e| format!("{}: {e}", path.display()))?;
127    f.write_all(out.as_bytes()).map_err(|e| format!("{}: {e}", path.display()))
128}
129
130/// Makes the winning version of every versioned record the last line for its id (module doc).
131/// Also after lines were removed (quarantine): the line that is now last may be an older version.
132pub fn settle(path: &Path) -> Result<(), String> {
133    let text = std::fs::read_to_string(path).unwrap_or_default();
134    let mut winner: HashMap<String, ((u64, Hash), &str)> = HashMap::new();
135    let mut last: HashMap<String, Hash> = HashMap::new();
136    for l in text.lines() {
137        let Ok(v) = serde_json::from_str::<Value>(l) else { continue };
138        let (Some(id), Some(version)) = (v["id"].as_str(), v["version"].as_u64()) else { continue };
139        let rank = (version, hash(l));
140        last.insert(id.to_string(), rank.1);
141        if winner.get(id).is_none_or(|(r, _)| rank > *r) {
142            winner.insert(id.to_string(), (rank, l));
143        }
144    }
145    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();
146    stale.sort();
147    append(path, &stale.iter().map(|(_, l)| l).collect::<Vec<_>>())
148}
149
150#[cfg(test)]
151mod tests {
152    use super::*;
153
154    fn lesson(id: &str, version: u32, q: &str) -> String {
155        serde_json::json!({"id": id, "origin_ms": 1, "question": q, "version": version}).to_string()
156    }
157
158    fn tmp(tag: &str) -> std::path::PathBuf {
159        let d = std::env::temp_dir().join(format!("borg-mesh-lines-{tag}-{}", std::process::id()));
160        let _ = std::fs::remove_dir_all(&d);
161        std::fs::create_dir_all(&d).unwrap();
162        d
163    }
164
165    /// `local` is this machine's sessions: its line never travels; `collective` (written `all`) does.
166    #[test]
167    fn a_local_broadcast_never_travels() {
168        let key = "ab".repeat(32);
169        let from = borg::msg::Sender { by: "s1".into(), name: "One of Two".into(), harness: "claude".into(), node: key.clone() };
170        let line = |to: &str| serde_json::to_string(&borg::msg::Message::new(borg::msg::TELL, &from, to, None, 1_000, "freeze merges")).unwrap();
171        assert!(!travels(borg::msg::FILE, &line(&format!("{}@{key}", borg::msg::LOCAL)), &key, 1_000));
172        assert!(travels(borg::msg::FILE, &line(borg::msg::ALL), &key, 1_000));
173        assert!(travels(borg::msg::FILE, &line(&format!("s2@{}", "cd".repeat(32))), &key, 1_000));
174    }
175
176    /// A seen line travels under its own node's key while fresh: no node acknowledges for another's
177    /// sessions, and a malformed one never travels.
178    #[test]
179    fn a_seen_line_travels_only_under_its_node() {
180        let (key, other) = ("ab".repeat(32), "cd".repeat(32));
181        let seen = |node: &str, ms: i64, ids: &[&str]| serde_json::to_string(&borg::msg::Seen::new("s2", node, ms, ids)).unwrap();
182        assert!(travels(borg::msg::FILE, &seen(&key, 1_000, &["m0123456789ab"]), &key, 1_000));
183        assert!(!travels(borg::msg::FILE, &seen(&key, 1_000, &["m0123456789ab"]), &other, 1_000), "signed by another node");
184        assert!(!travels(borg::msg::FILE, &seen(&key, 1_000, &["m0123456789ab"]), &key, 1_000 + borg::msg::TTL_MS + 1), "expired");
185        assert!(!travels(borg::msg::FILE, &seen(&key, 1_000, &["not an id"]), &key, 1_000), "malformed");
186    }
187
188    #[test]
189    fn union_skips_known_and_torn_lines() {
190        let d = tmp("union");
191        let p = d.join("lessons.jsonl");
192        std::fs::write(&p, format!("{}\n{{\"id\":\"L2\",\"ver", lesson("L1", 1, "a"))).unwrap();
193        assert_eq!(read(&p).len(), 1, "a half-written line does not count");
194        let n = merge(&p, &[lesson("L1", 1, "a"), lesson("L3", 1, "c"), "garbage".into()]).unwrap();
195        assert_eq!(n, 1, "only the unknown complete line is new");
196        assert_eq!(merge(&p, &[lesson("L3", 1, "c")]).unwrap(), 0, "idempotent");
197        let _ = std::fs::remove_dir_all(d);
198    }
199
200    #[test]
201    fn ratified_constraints_sync_and_load_as_the_same_standing_lesson_everywhere() {
202        let d = tmp("constraints");
203        assert!(logs(&d).contains(&d.join(borg::veto::FILE)), "stamped, signed and quarantined like the lessons");
204        let c = |by: &str, ms: i64| {
205            serde_json::json!({"id": "cabc", "text": "merge lookups go through the review API", "lesson": "L1", "by": by, "ms": ms, "source": "veto"})
206                .to_string()
207        };
208        let (a, b) = (d.join("a"), d.join("b"));
209        for (home, own) in [(&a, c("bob@x", 9)), (&b, c("ann@x", 5))] {
210            std::fs::create_dir_all(home).unwrap();
211            std::fs::write(home.join("lessons.jsonl"), format!("{}\n", lesson("L1", 1, "lookup?"))).unwrap();
212            merge(&home.join(borg::veto::FILE), &[own]).unwrap();
213        }
214        merge(&a.join(borg::veto::FILE), &read(&b.join(borg::veto::FILE)).into_values().collect::<Vec<_>>()).unwrap();
215        merge(&b.join(borg::veto::FILE), &read(&a.join(borg::veto::FILE)).into_values().collect::<Vec<_>>()).unwrap();
216        let standing = |h: &Path| {
217            let v: Vec<_> = borg::conscience::load(&h.join("lessons.jsonl"), None)
218                .into_iter()
219                .filter(|c| c.standing())
220                .map(|c| (c.id, c.engineers, c.consolidated))
221                .collect();
222            v
223        };
224        assert_eq!(standing(&a), [("cabc".to_string(), vec!["ann@x".to_string()], true)], "the earliest ratification, whatever the order");
225        assert_eq!(standing(&a), standing(&b));
226        let _ = std::fs::remove_dir_all(d);
227    }
228
229    #[test]
230    fn concurrent_versions_settle_on_the_same_winner_everywhere() {
231        let d = tmp("settle");
232        let (a, b) = (d.join("a/lessons.jsonl"), d.join("b/lessons.jsonl"));
233        let (v1, v2a, v2b) = (lesson("L1", 1, "orig"), lesson("L1", 2, "alice's merge"), lesson("L1", 2, "bob's merge"));
234        merge(&a, &[v1.clone(), v2a.clone()]).unwrap();
235        merge(&b, &[v1.clone(), v2b.clone()]).unwrap();
236        merge(&a, &read(&b).into_values().collect::<Vec<_>>()).unwrap();
237        merge(&b, &read(&a).into_values().collect::<Vec<_>>()).unwrap();
238        assert_eq!(digest(&read(&a)), digest(&read(&b)), "same set");
239        let q = |p: &Path| borg::conscience::load(p, None).into_iter().map(|c| c.question).collect::<Vec<_>>();
240        assert_eq!(q(&a), q(&b), "the conscience asks the same version on both nodes");
241        assert_ne!(q(&a), vec!["orig".to_string()], "an older version never wins");
242        // Arriving out of order (newest first) still leaves the newest last.
243        let c = d.join("c/lessons.jsonl");
244        merge(&c, &[v2a]).unwrap();
245        merge(&c, &[v1]).unwrap();
246        assert_eq!(q(&c), vec!["alice's merge".to_string()]);
247        let _ = std::fs::remove_dir_all(d);
248    }
249}