//! Agent memory, kept by the hub so that every machine's sessions share it: //! Claude Code keeps a session's memory in its projects directory, named for //! the checkout's path (`~/.claude/projects//memory/`), so the container, //! a workstation and the deck each had their own, and what one learnt the //! others had to learn again. //! //! The hub keeps the notes per repository (`owner/name`, from the checkout's //! `origin`), and one set for the whole workspace: a note whose file is named //! `workspace--.md` (who the person is, how they like to work, the //! machines and deploys), which every repository's sessions get. Each note is //! a file of its own, with its line in the directory's index (`MEMORY.md`), //! kept as written; a note without a line stays out of the index, as Claude //! Code may leave one. //! //! `midas memory sync` (the hooks run it: before a prompt, at most every few //! minutes, and when a session writes a memory file) merges the checkout's //! memory directory with the hub's, against what the last sync left //! (`.midas-memory.json` beside the notes): a note changed on one side only //! goes to the other, one changed on both is the newer one's, and a removal //! travels like a change. Then it writes the index again: its lines in their //! order, new ones after them. use std::collections::{BTreeMap, BTreeSet}; use std::path::{Path, PathBuf}; use std::process::Command; use anyhow::{bail, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::store; /// A note's file name begins so when it holds for every repository. pub const WORKSPACE: &str = "workspace--"; /// The repository a session's folder syncs with before its agent has added a /// project (sessions.rs `folder`): none, so only the workspace's notes. pub const NO_PROJECT: &str = "-"; /// A note as large as a note gets, with room; well under the hub's request /// limit (hub.rs `MAX_BODY`), so one always fits in a request. const TEXT_MAX: usize = 32 * 1024; /// What a sync sends per request: a first sync sends a machine's every note. const BATCH: usize = 48 * 1024; /// What the last sync left in a memory directory: what it and the hub agreed on. const MANIFEST: &str = ".midas-memory.json"; #[derive(Serialize, Deserialize, Clone, Debug, Default, PartialEq)] #[serde(default)] pub struct Note { pub text: String, /// Its line in `MEMORY.md`; empty when it is not in the index. pub line: String, /// When it last changed (s), and who changed it. pub ts: i64, pub by: String, /// Removed: kept so the removal reaches the machines that have it. pub deleted: bool, } type Notes = BTreeMap; /// A note's file name: one plain `.md` file in the directory, never the index. pub fn file_ok(f: &str) -> bool { f.len() <= 128 && f.ends_with(".md") && f != "MEMORY.md" && !f.starts_with('.') && f.bytes().all(|b| b.is_ascii_alphanumeric() || b"-_.".contains(&b)) } // ─── the hub's side ────────────────────────────────────────────────────────── /// Where a set lives: the workspace's, or a repository's (`owner--name`). fn set_path(repo: Option<&str>) -> Result { let name = match repo { None => "workspace".to_string(), Some(r) => crate::mirror::repo_name(r)?.trim_end_matches(".git").replace('/', "--"), }; Ok(crate::registry::root().join("memory").join(format!("{name}.json"))) } /// A renamed project's notes, under its new name (hosted.rs `rename`). A set the /// new name has already (notes kept from a project once called so) stays, and the /// old one beside it. pub(crate) fn rename_set(from: &str, to: &str) -> Result<()> { let (old, new) = (set_path(Some(from))?, set_path(Some(to))?); if old.exists() && !new.exists() { std::fs::rename(&old, &new)?; } Ok(()) } fn read_set(repo: Option<&str>) -> Result { Ok(store::read(&set_path(repo)?).unwrap_or_default()) } /// The workspace's notes and `repo`'s, removals included (no repository's for `NO_PROJECT`). pub fn read(repo: &str) -> Result { let theirs = if repo == NO_PROJECT { Notes::new() } else { read_set(Some(repo))? }; Ok(json!({"workspace": read_set(None)?, "repo": theirs})) } /// Every set the hub keeps, by name (`workspace`, or `owner/name`), for the /// page's Memory: each note as it is, removals included — and `stale`, the /// files each note names that its repository no longer has ([`gone`]). pub fn read_all() -> Result { let dir = crate::registry::root().join("memory"); let mut sets = serde_json::Map::new(); let mut stale = serde_json::Map::new(); let mut trees: BTreeMap>> = BTreeMap::new(); let repos: Vec = crate::conf::hub().repos.iter().filter_map(|r| crate::mirror::repo_name(r).ok()).collect(); for e in std::fs::read_dir(&dir).into_iter().flatten().flatten() { let f = e.file_name().to_string_lossy().to_string(); let Some(stem) = f.strip_suffix(".json") else { continue }; let name = if stem == "workspace" { stem.to_string() } else { stem.replacen("--", "/", 1) }; let notes: Notes = store::read(&e.path()).unwrap_or_default(); // A repository's notes are checked against it; the workspace's against every repository. let against: Vec = if name == "workspace" { repos.clone() } else { repos.iter().filter(|r| r.trim_end_matches(".git") == name).cloned().collect() }; for r in &against { trees.entry(r.clone()).or_insert_with(|| tree(r)); } let files: Vec<&Vec> = against.iter().filter_map(|r| trees[r].as_ref()).collect(); // Not knowing the tree is not knowing the note is stale. if !files.is_empty() && files.len() == against.len() { let all: Vec<&str> = files.iter().flat_map(|v| v.iter().map(String::as_str)).collect(); for (file, n) in notes.iter().filter(|(_, n)| !n.deleted) { let missing = gone(&n.text, &all); if !missing.is_empty() { stale.insert(format!("{name}/{file}"), json!(missing)); } } } sets.insert(name, json!(notes)); } Ok(json!({"sets": sets, "stale": stale})) } /// Every file in a repository's mirror, at its default branch. fn tree(repo: &str) -> Option> { let out = crate::util::git(&crate::mirror::mirror_path(repo), &["ls-tree", "-r", "--name-only", "HEAD"]).ok()?; Some(out.lines().map(str::to_string).collect()) } /// The repository files a note names (in backticks: `src/hub.rs`, `web/src/app.css`, /// `docs/notes/`) that none of `files` is any more. Only what reads as a path /// inside a repository counts: a name with a directory or a known extension, /// never an absolute path, a home directory, a URL or a placeholder. pub fn gone(text: &str, files: &[&str]) -> Vec { const EXT: &[&str] = &[".rs", ".ts", ".tsx", ".js", ".md", ".toml", ".json", ".sh", ".css", ".wgsl", ".yml", ".yaml", ".py", ".html", ".lock"]; let mut out: Vec = Vec::new(); for (i, part) in text.split('`').enumerate() { if i % 2 == 0 { continue; } let p = part.trim().trim_end_matches([':', ',', '.']); let plain = !p.is_empty() && p.len() < 160 && !p.contains(char::is_whitespace) && !p.starts_with(['/', '~', '$', '-', '.']) && !p.contains("://") && !p.contains(['<', '>', '*', '{', '}', '|', '=', '(', '"', '\'']) && !p.contains("::"); let dir = p.ends_with('/') && p.matches('/').count() >= 1; let file = EXT.iter().any(|e| p.ends_with(e)); if !plain || !(dir || file) || out.iter().any(|o| o == p) { continue; } // A bare name (`hub.rs`) is any file of that name; a path, that path or one ending in it. let found = files.iter().any(|f| if dir { f.starts_with(p) || f.contains(&format!("/{p}")) } else { *f == p || f.ends_with(&format!("/{p}")) }); if !found { out.push(p.to_string()); } } out } /// One change a sync sends: a note's text and line, or its removal (`text` null). #[derive(Deserialize, Debug)] pub struct Change { pub file: String, pub text: Option, #[serde(default)] pub line: String, } /// The changes, each to the workspace's set or `repo`'s as its name says; /// answers as [`read`] does. pub fn change(repo: &str, changes: &[Change], by: &str) -> Result { for c in changes { if !file_ok(&c.file) { bail!("not a memory note's file name: {:?}", c.file); } if c.text.as_ref().is_some_and(|t| t.len() > TEXT_MAX) || c.line.len() > 1024 || c.line.contains('\n') { bail!("{}: a note of at most {} KB and an index line of one line", c.file, TEXT_MAX / 1024); } } if repo == NO_PROJECT && changes.iter().any(|c| !c.file.starts_with(WORKSPACE)) { bail!("a note of no project is the workspace's ({WORKSPACE}.md)"); } let now = crate::registry::now(); for repo in [None, Some(repo).filter(|r| *r != NO_PROJECT)] { let mine: Vec<&Change> = changes.iter().filter(|c| c.file.starts_with(WORKSPACE) == repo.is_none()).collect(); if mine.is_empty() { continue; } // The hub's user only: a note may say more about the machines than the page should. let mut s = store::Store::::open(set_path(repo)?)?.private(); for c in &mine { let note = match &c.text { Some(t) => Note { text: t.clone(), line: c.line.clone(), ts: now, by: by.into(), deleted: false }, None => Note { ts: now, by: by.into(), deleted: true, ..Default::default() }, }; s.data.insert(c.file.clone(), note); } s.save()?; } crate::events::emit("memory_changed", json!({ "actor": by, "repo": repo, "files": changes.iter().map(|c| json!({"file": c.file, "removed": c.text.is_none()})).collect::>(), })); read(repo) } // ─── a checkout's side ─────────────────────────────────────────────────────── /// A note as a memory directory has it: text and index line. #[derive(Serialize, Deserialize, Clone, Debug, PartialEq)] struct Local { text: String, line: String, } #[derive(Serialize, Deserialize, Default)] #[serde(default)] struct Manifest { repo: String, notes: BTreeMap, } fn git(dir: &Path, args: &[&str]) -> Option { let o = Command::new("git").arg("-C").arg(dir).args(args).output().ok()?; o.status.success().then(|| String::from_utf8_lossy(&o.stdout).trim().to_string()) } /// The checkout `cwd` is in, as Claude Code keys its memory: the main /// checkout's, which its worktrees share; and its repository, from `origin`. fn checkout(cwd: &Path) -> Result<(PathBuf, String)> { // A session's folder, a directory Claude Code keys its memory by as it is: // its first project's notes, or only the workspace's until it has one. if cwd.join(crate::sessions::SESSION_MARK).is_file() { let first = crate::sessions::folder_projects(cwd).into_iter().next(); return Ok((cwd.to_path_buf(), first.unwrap_or_else(|| NO_PROJECT.to_string()))); } let common = git(cwd, &["rev-parse", "--path-format=absolute", "--git-common-dir"]).context("not in a git checkout")?; let common = PathBuf::from(common); let main = if common.file_name().is_some_and(|n| n == ".git") { common.parent().unwrap_or(&common).to_path_buf() } else { common.clone() }; let url = git(cwd, &["remote", "get-url", "origin"]).context("the checkout has no origin, so no repository to share memory with")?; let repo = crate::flush::repo_of_url(&url).with_context(|| format!("no repository in origin {url}"))?; Ok((main, repo)) } /// The memory directory of the checkout `cwd` is in, and its repository. pub fn dir(cwd: &Path) -> Result<(PathBuf, String)> { let (main, repo) = checkout(cwd)?; Ok((crate::acp::project_dir(&main.to_string_lossy()).join("memory"), repo)) } /// The index's lines, and the note each names (`[…](file.md)`), if one. fn index_lines(text: &str) -> Vec<(String, Option)> { text.lines().map(|l| { let file = l.split("](").nth(1).and_then(|r| r.split(')').next()).map(str::trim).filter(|f| file_ok(f)).map(str::to_string); (l.to_string(), file) }).collect() } fn read_local(dir: &Path) -> Result<(BTreeMap, BTreeMap, Vec<(String, Option)>)> { let index = index_lines(&std::fs::read_to_string(dir.join("MEMORY.md")).unwrap_or_default()); let line_of: BTreeMap<&str, &str> = index.iter().filter_map(|(l, f)| f.as_deref().map(|f| (f, l.as_str()))).collect(); let (mut notes, mut mtimes) = (BTreeMap::new(), BTreeMap::new()); for e in std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?.flatten() { let f = e.file_name().to_string_lossy().to_string(); if !file_ok(&f) || !e.file_type().is_ok_and(|t| t.is_file()) { continue; } let text = std::fs::read_to_string(e.path()).unwrap_or_default(); let mtime = e.metadata().ok().and_then(|m| m.modified().ok()) .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_secs() as i64).unwrap_or(0); notes.insert(f.clone(), Local { text, line: line_of.get(f.as_str()).unwrap_or(&"").to_string() }); mtimes.insert(f, mtime); } Ok((notes, mtimes, index)) } /// What a sync decides for one note. #[derive(Debug, PartialEq)] enum Step { Same, Push(Option), Pull(Option), } /// Local, base (the last sync) and the hub's, each `None` when absent or /// removed; `local_newer` breaks a change on both sides. fn decide(local: Option<&Local>, base: Option<&Local>, hub: Option<&Local>, local_newer: bool) -> Step { if local == hub { Step::Same } else if local == base { Step::Pull(hub.cloned()) } else if hub == base || local_newer { Step::Push(local.cloned()) } else { Step::Pull(hub.cloned()) } } /// The index again: its lines in their order (a removed note's dropped, a /// changed one's replaced), then the new notes' lines. fn write_index(old: &[(String, Option)], notes: &BTreeMap) -> String { let mut seen = BTreeSet::new(); let mut out: Vec = Vec::new(); for (line, file) in old { match file { None => out.push(line.clone()), Some(f) => { if let Some(n) = notes.get(f).filter(|n| !n.line.is_empty()) { if seen.insert(f.clone()) { out.push(n.line.clone()); } } } } } // The workspace's first among the new: they hold everywhere. let mut new: Vec<(&String, &Local)> = notes.iter().filter(|(f, n)| !n.line.is_empty() && !seen.contains(*f)).collect(); new.sort_by_key(|(f, _)| (!f.starts_with(WORKSPACE), f.to_string())); out.extend(new.into_iter().map(|(_, n)| n.line.clone())); while out.last().is_some_and(|l| l.trim().is_empty()) { out.pop(); } if out.is_empty() { String::new() } else { format!("{}\n", out.join("\n")) } } fn hub_notes(v: &Value) -> (BTreeMap, BTreeMap) { let (mut notes, mut ts) = (BTreeMap::new(), BTreeMap::new()); for set in ["workspace", "repo"] { let parsed: Notes = serde_json::from_value(v[set].clone()).unwrap_or_default(); for (f, n) in parsed { if !file_ok(&f) { continue; } ts.insert(f.clone(), n.ts); if !n.deleted { notes.insert(f, Local { text: n.text, line: n.line }); } } } (notes, ts) } /// What a sync did. #[derive(Default, Debug)] pub struct Synced { pub repo: String, pub pulled: Vec, pub pushed: Vec, } /// Merge the memory directory of the checkout `cwd` is in with the hub's. /// `every`: not again within that many seconds of the last sync. pub fn sync(cwd: &Path, every: Option) -> Result> { let (dir, repo) = dir(cwd)?; std::fs::create_dir_all(&dir)?; let manifest_path = dir.join(MANIFEST); if let (Some(s), Ok(m)) = (every, std::fs::metadata(&manifest_path)) { if m.modified().ok().and_then(|t| t.elapsed().ok()).is_some_and(|e| e.as_secs() < s) { return Ok(None); } } let _lock = store::lock(&dir.join(".midas-memory.lock"))?; let base: Manifest = store::read(&manifest_path).filter(|m: &Manifest| m.repo == repo).unwrap_or_default(); let (local, mtimes, index) = read_local(&dir)?; let q = |s: &str| s.replace('%', "%25").replace('&', "%26").replace('/', "%2F"); let (hub, hub_ts) = hub_notes(&crate::client::get_auth(&format!("/v1/memory?repo={}", q(&repo)))?); let files: BTreeSet<&String> = local.keys().chain(base.notes.keys()).chain(hub.keys()).collect(); let (mut push, mut pull, mut waiting) = (Vec::new(), Vec::new(), Vec::new()); for f in files { let newer = mtimes.get(f).copied().unwrap_or(0) >= hub_ts.get(f).copied().unwrap_or(0); match decide(local.get(f), base.notes.get(f), hub.get(f), newer) { Step::Same => {} // Too large for the hub: stays here, said once a sync. Step::Push(Some(n)) if n.text.len() > TEXT_MAX => eprintln!("midas: memory note {f} is over {} KB; kept on this machine only", TEXT_MAX / 1024), // No project yet: a project's note waits here for the session's first, which takes it then. // Left out of what the hub agreed on, or the next sync would read it as removed there. Step::Push(_) if repo == NO_PROJECT && !f.starts_with(WORKSPACE) => waiting.push(f.clone()), Step::Push(n) => push.push((f.clone(), n)), Step::Pull(n) => pull.push((f.clone(), n)), } } let mut merged = local.clone(); if !push.is_empty() { let changes: Vec = push.iter().map(|(f, n)| match n { Some(n) => json!({"file": f, "text": n.text, "line": n.line}), None => json!({"file": f, "text": null}), }).collect(); let mut batch: Vec = Vec::new(); let mut size = 0; for c in changes { let n = c.to_string().len(); if !batch.is_empty() && size + n > BATCH { crate::client::post("/v1/memory", &json!({"repo": repo, "changes": std::mem::take(&mut batch)}))?; size = 0; } size += n; batch.push(c); } crate::client::post("/v1/memory", &json!({"repo": repo, "changes": batch}))?; } for (f, n) in &pull { let path = dir.join(f); match n { Some(n) => { store::write_atomic(&path, n.text.as_bytes(), store::PUBLIC)?; merged.insert(f.clone(), n.clone()); } None => { let _ = std::fs::remove_file(&path); merged.remove(f); } } } let index_text = write_index(&index, &merged); if index_text != std::fs::read_to_string(dir.join("MEMORY.md")).unwrap_or_default() { store::write_atomic(&dir.join("MEMORY.md"), index_text.as_bytes(), store::PUBLIC)?; } let mut agreed = merged; for f in &waiting { agreed.remove(f); } store::write_json(&manifest_path, &Manifest { repo: repo.clone(), notes: agreed }, store::PUBLIC)?; Ok(Some(Synced { repo, pulled: pull.into_iter().map(|(f, _)| f).collect(), pushed: push.into_iter().map(|(f, _)| f).collect() })) } /// `midas memory sync`. pub fn sync_cmd(every: Option, quiet: bool) -> Result { let cwd = std::env::current_dir()?; match sync(&cwd, every)? { Some(s) if !quiet => println!("memory of {} and the workspace: {} from the hub, {} to it{}", s.repo, s.pulled.len(), s.pushed.len(), { let all: Vec<&String> = s.pulled.iter().chain(&s.pushed).collect(); let shown: Vec<&str> = all.iter().take(8).map(|f| f.as_str()).collect(); match all.len() { 0 => String::new(), n if n > 8 => format!(" ({}, and {} more)", shown.join(", "), n - 8), _ => format!(" ({})", shown.join(", ")), } }), _ => {} } Ok(0) } /// `midas memory where`: the directory this checkout's sessions keep their memory in. pub fn where_cmd() -> Result { let (dir, repo) = dir(&std::env::current_dir()?)?; println!("{} ({repo})", dir.display()); Ok(0) } #[cfg(test)] mod tests { use super::*; fn n(text: &str) -> Local { Local { text: text.into(), line: format!("- [{text}](x.md)") } } #[test] fn a_change_on_one_side_goes_to_the_other_and_a_clash_to_the_newer() { let (a, b, c) = (n("a"), n("b"), n("c")); assert_eq!(decide(Some(&a), Some(&a), Some(&a), false), Step::Same); // Changed here: to the hub. assert_eq!(decide(Some(&b), Some(&a), Some(&a), false), Step::Push(Some(b.clone()))); // Changed on the hub: here. assert_eq!(decide(Some(&a), Some(&a), Some(&b), true), Step::Pull(Some(b.clone()))); // Removed here, or there: the removal travels. assert_eq!(decide(None, Some(&a), Some(&a), false), Step::Push(None)); assert_eq!(decide(Some(&a), Some(&a), None, true), Step::Pull(None)); // New on either side, never synced. assert_eq!(decide(Some(&a), None, None, false), Step::Push(Some(a.clone()))); assert_eq!(decide(None, None, Some(&a), false), Step::Pull(Some(a.clone()))); // Both changed: the newer. assert_eq!(decide(Some(&b), Some(&a), Some(&c), true), Step::Push(Some(b.clone()))); assert_eq!(decide(Some(&b), Some(&a), Some(&c), false), Step::Pull(Some(c.clone()))); // The first sync of a machine that had its own: the newer too. assert_eq!(decide(Some(&b), None, Some(&c), false), Step::Pull(Some(c))); } #[test] fn the_index_keeps_its_order_and_its_own_lines_and_adds_the_new() { let old = index_lines("# Memory\n- [A](a.md) — one\n- [Gone](gone.md) — x\n- [B](b.md) — two\n"); let mut notes = BTreeMap::new(); notes.insert("b.md".to_string(), Local { text: "b".into(), line: "- [B](b.md) — two, changed".into() }); notes.insert("a.md".to_string(), Local { text: "a".into(), line: "- [A](a.md) — one".into() }); notes.insert("new.md".to_string(), Local { text: "n".into(), line: "- [New](new.md) — n".into() }); notes.insert("workspace--who.md".to_string(), Local { text: "w".into(), line: "- [Who](workspace--who.md) — w".into() }); notes.insert("unlisted.md".to_string(), Local { text: "u".into(), line: String::new() }); assert_eq!(write_index(&old, ¬es), "# Memory\n- [A](a.md) — one\n- [B](b.md) — two, changed\n- [Who](workspace--who.md) — w\n- [New](new.md) — n\n"); } #[test] fn only_plain_note_files_are_notes() { assert!(file_ok("keep-answers-terse.md") && file_ok("workspace--machines.md")); for bad in ["MEMORY.md", ".midas-memory.json", "../x.md", "a/b.md", "notes.txt", ".hidden.md"] { assert!(!file_ok(bad), "{bad}"); } } #[test] fn the_hub_keeps_workspace_notes_apart_and_a_removal_as_a_removal() { let _g = crate::tests::SERIAL.lock().unwrap_or_else(|p| p.into_inner()); crate::tests::scratch("memory"); let ch = |file: &str, text: Option<&str>| Change { file: file.into(), text: text.map(str::to_string), line: format!("- [{file}]({file})") }; change("acme/cartopolis", &[ch("build-slots.md", Some("slots")), ch("workspace--who.md", Some("who"))], "t").unwrap(); // Another repository sees the workspace's note, not cartopolis's. let all = read_all().unwrap(); assert_eq!(all["sets"]["acme/cartopolis"]["build-slots.md"]["text"], "slots"); assert_eq!(all["sets"]["workspace"]["workspace--who.md"]["text"], "who"); let other = read("acme/midas").unwrap(); assert_eq!(other["workspace"]["workspace--who.md"]["text"], "who"); assert!(other["repo"].as_object().unwrap().is_empty()); let v = change("acme/cartopolis", &[ch("build-slots.md", None)], "t").unwrap(); assert_eq!(v["repo"]["build-slots.md"]["deleted"], true); assert!(change("acme/cartopolis", &[ch("../escape.md", Some("x"))], "t").is_err()); assert!(change("not a repo", &[ch("a.md", Some("x"))], "t").is_err()); // A session's folder before it has a project: the workspace's notes, and only those go up. let none = read(NO_PROJECT).unwrap(); assert_eq!(none["workspace"]["workspace--who.md"]["text"], "who"); assert!(none["repo"].as_object().unwrap().is_empty()); assert!(change(NO_PROJECT, &[ch("routing.md", Some("x"))], "t").is_err(), "a project's note waits for a project"); change(NO_PROJECT, &[ch("workspace--phone.md", Some("on a phone"))], "t").unwrap(); assert_eq!(read("acme/midas").unwrap()["workspace"]["workspace--phone.md"]["text"], "on a phone"); } } #[cfg(test)] mod gone_tests { use super::gone; #[test] fn a_note_naming_a_file_the_repository_lost_is_stale() { let files = ["src/hub.rs", "web/src/app.css", "docs/notes/terrain.md"]; let note = "See `src/hub.rs` and `web/src/components/board.tsx`, `hub.rs`, `app.css`, the `docs/notes/` dir, \ `/data/stack/Caddyfile`, `~/.claude/x.md`, `midas take`, `/x.rs`, `a::b`, `https://x.org/y.md`."; assert_eq!(gone(note, &files), vec!["web/src/components/board.tsx".to_string()]); assert!(gone("nothing named", &files).is_empty()); assert_eq!(gone("`docs/adr/`", &files), vec!["docs/adr/".to_string()]); } }