//! Sessions working together through the hub, with no agent of its own in the //! middle: the hub keeps a mailbox per session, notices when two sessions //! change the same files, hands out numbers two branches must not both take, //! and knows what to call each session. The sessions decide; the hub passes //! notes and keeps the record. //! //! * **Notes.** `midas say …` from a session, or the hub's own //! rules (somebody is waiting for the node you are not using; your yield //! went through). A note can go to a role instead, resolved when it is //! sent: `@` its holder, `@waiting:` everyone in line //! for it, `@file:` every session changing that file (`dir/`: anything //! under it). A name the hub has not seen lately is refused, with the //! closest it knows (a branch name, or `worktree-`, is taken for its //! session). Every note has an id (`n12`): the sender sees whether it was //! read (`midas notes --sent`), the reader answers with `midas say --re n12`. //! Only the session hooks (`midas notes --hook`, `midas editing`) hand notes //! over — between tool calls and at each prompt, where the agent reads them — //! and never inside a subagent; the commands a session runs (every `ssh //! `, `take`, `wait`, `release`) only say how many wait. A hosted //! session that is idle gets the note as a message too, which wakes it. //! Notes are dropped unread when their session ends or after two days, and //! their sender is told. //! * **Work.** Each flush reports the files the worktree's branch changes //! (against the warm branch), what is uncommitted, and the functions its //! hunks touch; the tool hook adds each file as the session first edits it //! (`midas editing`), so an overlap is news before both sides have written //! it, not at the next flush. When two sessions' files meet, both get a note //! naming the other, the files and what each side changes in them: once per //! file in common, for as long as both sessions last and neither lands. //! * **Decisions.** What is the person's to decide — who gives way, whether //! one session carries on another's work — `midas ask` puts in front of //! them: mailed, and on the web page with a button per option. The answer //! goes to the asking session, and to those it named, as a note. //! * **Reservations.** `midas reserve --from N`: the next number //! after N and after every number already handed out in that namespace — a //! database migration, a wire message kind. Two sessions asking at once get //! different numbers. //! * **Open ends.** `midas todo add --for workstation "…"`: work left for the //! next session on another machine, shown to it when it starts. //! * **Names.** The session's label (the start of its first prompt, sent once //! by the prompt hook), its branch, and a link to it on claude.ai when the //! worktree name carries a Remote Control session id (`bridge-cse_…`); with //! the node it holds or waits for and when it was last seen (`midas who`). //! //! State in `collab.json` beside the registry, under its own lock: none of it //! decides who holds what, so it stays out of the registry and its snapshot. use std::collections::{BTreeMap, BTreeSet}; use std::fs; use std::path::PathBuf; use std::sync::Mutex; use anyhow::{bail, Context, Result}; use serde_json::{json, Map, Value}; use crate::events; use crate::registry::{self, now}; use crate::store; /// Notes kept per session at most: a session that never reads them should not /// grow the file forever. const MAX_NOTES: usize = 20; /// Work older than this is no longer anyone's: its session stopped syncing. const WORK_STALE_S: i64 = 3 * 86400; /// A session quiet for this long is told of no new overlaps, and nobody is /// told of its work, until it is active again. const PEER_QUIET_S: i64 = 2 * 3600; /// A session ending and starting again within this long is the same session /// carrying on: it is not told the overlaps it was told before. const RESTART_S: i64 = 10 * 60; /// Files every branch touches, which would make every pair "overlap". const COMMON: &[&str] = &["Cargo.lock", "bun.lock", "package-lock.json"]; /// A note nobody read in this long is dropped, and its sender told; a sent /// note's record (read or not) is kept as long. const NOTE_KEEP_S: i64 = 2 * 86400; /// A session not seen for this long is idle: it reads a note at its next /// prompt, not at its next tool call. const IDLE_S: i64 = 10 * 60; /// A session seen within this long may be written to by name. const KNOWN_S: i64 = 7 * 86400; /// Functions named per file in a session's work, at most. pub const MAX_FUNCTIONS: usize = 8; /// When each session last asked the hub anything (its hooks do, at every tool /// call and prompt). In memory: after a restart the session marks stand in. static SEEN: Mutex> = Mutex::new(BTreeMap::new()); /// A changed file as work keeps it: `:` when the session's /// midas says which project the worktree is (`repo`, `owner/name`), so a /// session spanning projects keeps each one's files, and two projects' same /// path is no overlap; bare from a midas from before it said. fn qualified(repo: Option<&str>, path: &str) -> String { match repo.and_then(|r| r.rsplit('/').next()).filter(|n| !n.is_empty()) { Some(name) => format!("{name}:{path}"), None => path.to_string(), } } /// A kept file's path in its worktree, and its project when said. fn split_file(f: &str) -> (Option<&str>, &str) { match f.split_once(':') { Some((p, path)) if !p.contains('/') => (Some(p), path), _ => (None, f), } } fn base(owner: &str) -> &str { owner.strip_prefix("gate-").unwrap_or(owner) } /// The session `owner` is here now. pub fn seen(owner: &str) { if let Ok(mut m) = SEEN.lock() { m.insert(base(owner).to_string(), now()); } } #[cfg(test)] pub fn forget_seen(owner: &str) { if let Ok(mut m) = SEEN.lock() { m.remove(base(owner)); } } fn last_seen(owner: &str) -> Option { SEEN.lock().ok().and_then(|m| m.get(base(owner)).copied()) } /// collab.json, locked while it is open (`store`; the lock is `.collab.lock`). struct Collab(store::Store); fn path() -> PathBuf { registry::root().join("collab.json") } impl Collab { fn open() -> Result { let mut s = store::Store::open(path())?; store::objects(&mut s.data, &["notes", "work", "reserved", "told", "ended", "todos", "decisions", "archived", "sent"]); Ok(Self(s)) } fn save(&self) -> Result<()> { self.0.save() } fn obj(&mut self, k: &str) -> &mut Map { self.0.data[k].as_object_mut().expect("normalised in open") } } // ── Notes ──────────────────────────────────────────────────────────────────── /// The start of a text, on one line, for quoting it. fn quote(text: &str, n: usize) -> String { let one = text.split_whitespace().collect::>().join(" "); if one.chars().count() > n { one.chars().take(n - 1).chain(['…']).collect() } else { one } } /// Leave a note for `to`, and wake it with the note if it is a session the hub /// runs or mirrors and idles (`wake`): the hub's own notes too — an overlap, /// somebody waiting for its node, a decision's answer — which until /// 2026-10-23 waited for a prompt that an idle session never gets. `from` is /// a session, or `hub` for the hub's rules. Returns its id (`n`). pub fn say(from: &str, to: &str, text: &str, kind: &str) -> Result { say_about(from, to, text, kind, Value::Null) } /// Leave a note for `to` that waits for its next prompt or tool call, waking /// nothing: news for a session at work that an idle one need not be woken for /// (a deploy about to restart what it uses, ship.rs). pub fn tell(from: &str, to: &str, text: &str, kind: &str) -> Result { store_note(from, to, text, kind, Value::Null) } /// `say`, with what the note is about as data (an overlap's session and /// files), which the page draws instead of the text. fn say_about(from: &str, to: &str, text: &str, kind: &str, about: Value) -> Result { let id = store_note(from, to, text, kind, about)?; if wakes(from, kind) { wake(to.trim(), &id); } Ok(id) } /// Whether a note may wake an idle session: one from a session, or the /// person's answer to a decision, which midas only carries. Midas's own news /// (a deploy that is live, an overlap, a node back in the pool) waits for the /// next prompt or tool call: woken by it, an agent answered midas in the /// person's conversation, with nobody there to talk to (session-s497, /// 2026-10-29). Its own command stopped for doing nothing (stall.rs) is not /// news but work left to it: s857 sat idle 19 hours on one, until the person /// asked. pub(crate) fn wakes(from: &str, kind: &str) -> bool { from != "hub" || matches!(kind, "decision" | "stalled" | "admin") } /// A note into `to`'s mailbox, waking nobody: its id. fn store_note(from: &str, to: &str, text: &str, kind: &str, about: Value) -> Result { let to = to.trim(); let text: String = text.trim().chars().take(1000).collect(); if to.is_empty() || text.is_empty() { bail!("a note needs somebody to go to and something to say"); } // What the reader is told about the sender: its label and branch. let sender = if from == "hub" { Value::Null } else { names_of()[base(from)].clone() }; let t = now(); let mut c = Collab::open()?; let n = c.0.data["note_seq"].as_u64().unwrap_or(0) + 1; c.0.data["note_seq"] = json!(n); let id = format!("n{n}"); let mut note = json!({"id": id, "ts": t, "from": from, "kind": kind, "text": text}); for (k, f) in [("label", "from_label"), ("branch", "from_branch")] { if sender[k].is_string() { note[f] = sender[k].clone(); } } if !about.is_null() { note["about"] = about; } let list = c.obj("notes").entry(to.to_string()).or_insert_with(|| json!([])); let arr = list.as_array_mut().context("notes are a list")?; arr.push(note); let excess = arr.len().saturating_sub(MAX_NOTES); let overflow: Vec = arr.drain(..excess).collect(); c.obj("sent").retain(|_, s| t - s["ts"].as_i64().unwrap_or(0) < NOTE_KEEP_S + 86400); c.obj("sent").insert(id.clone(), json!({"ts": t, "from": from, "to": to, "kind": kind, "text": quote(&text, 300)})); for o in &overflow { mark_dropped(&mut c, o, "mailbox_full", t); } c.save()?; drop(c); // `note_kind`: the event's own `kind` is "note". events::emit("note", json!({"actor": from, "to": to, "note_kind": kind, "text": text, "id": id})); for o in &overflow { events::emit("note_expired", json!({"actor": "hub", "id": o["id"], "to": to, "from": o["from"], "reason": "mailbox_full"})); } Ok(id) } fn mark_dropped(c: &mut Collab, note: &Value, reason: &str, t: i64) { if let Some(s) = note["id"].as_str().and_then(|id| c.obj("sent").get_mut(id)) { s["expired_at"] = json!(t); s["expired_reason"] = json!(reason); } } /// A name `say` was given that is no session the hub knows: refused, with /// the closest names it does know. #[derive(Debug)] pub struct Unknown { pub error: String, pub suggestions: Vec, } impl std::fmt::Display for Unknown { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { f.write_str(&self.error) } } impl std::error::Error for Unknown {} /// A note from a session, to a session or a role (`@`, `@waiting:`, `@file:`) resolved now, or — with `re` — to the sender of /// that note, quoting it. Returns, per recipient, `{to, id}`, and `woken` when /// an idle hosted session was sent it as a message, or `idle_since` and /// `session` for a Remote Control session that looks idle. A name the hub /// does not know fails with [`Unknown`]. pub fn say_to(from: &str, to: &str, text: &str, re: Option<&str>) -> Result> { let mut text = text.trim().to_string(); let mut to = to.trim().to_string(); if let Some(id) = re.map(str::trim).filter(|r| !r.is_empty()) { let orig = Collab::open()?.0.data["sent"][id].clone(); let Some(sender) = orig["from"].as_str() else { bail!("no note {id} in the last two days (`midas notes` shows each note's id)"); }; if sender == "hub" { bail!("{id} came from midas itself, which reads no replies: write to the session it names instead"); } to = base(sender).to_string(); text = format!("(re {id} \"{}\") {text}", quote(orig["text"].as_str().unwrap_or(""), 60)); } if text.is_empty() { bail!("a note needs something to say"); } let who: Vec = match to.strip_prefix('@') { Some(role) => { let me = base(from); let mut who: Vec = recipients(role)?.into_iter().filter(|o| base(o) != me).collect(); who.sort(); who.dedup(); if who.is_empty() { bail!("nobody is @{role} right now"); } text = format!("(to @{role}) {text}"); who } None => vec![resolve(&to)?], }; let mut out = Vec::new(); for o in &who { let id = store_note(from, o, &text, "say", Value::Null)?; out.push(wake(o, &id)); } Ok(out) } /// The session the hub runs or mirrors for `to`, if it waits for a prompt: a /// hub-run one by its name (`session-`), or an editor's thread mirrored /// to the page (`midas acp --mirror`, tap.rs), whose name is its checkout's — /// the one heard from last, when several threads share it. fn idle_hosted(to: &str) -> Option { if let Some(sid) = to.strip_prefix("session-") { return crate::sessions::meta(sid).is_ok_and(|m| m["status"] == "waiting").then(|| sid.to_string()); } crate::sessions::list().as_array()?.iter() .filter(|m| m["owner"] == to && m["status"] == "waiting" && m["runner"].is_string()) .max_by_key(|m| m["updated"].as_i64().unwrap_or(0)) .and_then(|m| m["id"].as_str().map(str::to_string)) } /// What else reaches `to` now that a note waits for it: an idle hosted session /// is sent it as a message, which wakes its agent (and the note counts as /// read); a Remote Control session that looks idle is named, for the sender to /// wake. Returns the `{to, id, …}` the sender is told. fn wake(to: &str, id: &str) -> Value { let mut r = json!({"to": to, "id": id}); if let Some(sid) = idle_hosted(to) { let note = Collab::open().ok().and_then(|c| c.0.data["notes"][to].as_array() .and_then(|a| a.iter().find(|n| n["id"] == id).cloned())); // The page draws `note` as a card of its own (who from, about what); // the agent reads the text. let told = note.as_ref().is_some_and(|n| crate::sessions::tell(&sid, "message", &json!({"text": note_line(n), "note": page_note(n)}), "midas").is_ok()); if told { let _ = take_one(to, id, "message"); r["woken"] = json!(true); } } else if let Some(link) = link(to) { if let Some(since) = idle_since(to) { r["idle_since"] = json!(since); r["session"] = json!(link.rsplit('/').next().unwrap_or("")); r["link"] = json!(link); } } r } /// One note out of a mailbox, as read: it reached its session another way. fn take_one(owner: &str, id: &str, via: &str) -> Result<()> { let t = now(); let mut c = Collab::open()?; if let Some(Value::Array(v)) = c.obj("notes").get_mut(owner) { v.retain(|n| n["id"] != id); } if let Some(s) = c.obj("sent").get_mut(id) { s["read_at"] = json!(t); s["read_via"] = json!(via); } c.save()?; drop(c); events::emit("notes_taken", json!({"actor": owner, "ids": [id], "via": via, "notes": [{"kind": "say", "age_s": 0}]})); Ok(()) } /// When `owner` was last active, if that was long enough ago to call it idle. fn idle_since(owner: &str) -> Option { let marks = names_of()[base(owner)]["last"].as_i64(); let last = [marks, last_seen(owner)].into_iter().flatten().max()?; (now() - last >= IDLE_S).then_some(last) } /// The session a name given to `say` means: itself if the hub has seen it in /// the last week (it holds or waits for a node, it has work, notes or marks); /// else the session whose worktree that is without `worktree-`, or whose /// branch it is. A session whose end hook ran is refused: nobody would read it. pub fn resolve(to: &str) -> Result { let to = to.trim(); if to.is_empty() { bail!("say who to: a session (`midas who` lists them) or a role"); } let known = known(); let ok = |o: &str| -> Result { match known[o]["ended"].as_i64() { Some(at) => bail!("{o} ended {} (its session-end hook ran), so nobody would read a note to it. \ A session resumed in that worktree can be written to again.", crate::cli::ago(at)), None => Ok(o.to_string()), } }; // `worktree-X` first: notes once left for such a name gave it a mailbox. if let Some(w) = to.strip_prefix("worktree-").filter(|w| known.get(*w).is_some()) { return ok(w); } if known.get(to).is_some() { return ok(to); } // A hosted session by its id, as notes name it (`short_name`). let hosted = format!("session-{to}"); if crate::sessions::id_ok(to) && known.get(&hosted).is_some() { return ok(&hosted); } let by_branch: Vec<&String> = known.as_object().into_iter().flatten() .filter(|(_, k)| k["branch"] == to).map(|(o, _)| o).collect(); if by_branch.len() == 1 { return ok(by_branch[0]); } let suggestions = closest(to, &known, 3); let did = if suggestions.is_empty() { String::new() } else { format!(" Closest: {}.", suggestions.iter().map(|s| match known[s.as_str()]["label"].as_str() { Some(l) => format!("{s} (\"{}\")", quote(l, 40)), None => s.clone(), }).collect::>().join(", ")) }; Err(Unknown { error: format!("no session called {to:?} is known to the hub (seen in the last week, or holding or waiting for a node).{did} \ `midas who` lists them; a role (@, @waiting:, @file:) reaches whoever it is now."), suggestions, }.into()) } /// Every session a note may go to by name: `{owner: {branch, label, ended}}`. fn known() -> Value { let t = now(); let mut out = json!({}); for (o, n) in names().as_object().into_iter().flatten() { let active = n["node"].is_string() || n["waiting_for"].is_string() || n["notes"].as_u64().unwrap_or(0) > 0; if active || n["last"].as_i64().is_some_and(|l| t - l < KNOWN_S) { // Holding a node, it is somebody's still: a hosted bot outlives its session. let ended = if n["node"].is_string() { Value::Null } else { n["ended"].clone() }; out[o] = json!({"branch": n["branch"], "label": n["label"], "ended": ended}); } } // Sessions midas runs, as long as they run, under their worktree's name. for m in crate::sessions::list().as_array().into_iter().flatten() { let live = !matches!(m["status"].as_str(), Some("stopped" | "failed")); if let (Some(o), true) = (m["owner"].as_str(), live) { if out[o].is_null() { out[o] = json!({"branch": m["branch"], "label": m["title"], "ended": null}); } } } out } /// Edit distance, in characters. fn distance(a: &str, b: &str) -> usize { let b: Vec = b.chars().collect(); let mut row: Vec = (0..=b.len()).collect(); for (i, ca) in a.chars().enumerate() { let mut prev = row[0]; row[0] = i + 1; for j in 0..b.len() { let cur = row[j + 1]; row[j + 1] = (prev + usize::from(ca != b[j])).min(row[j] + 1).min(cur + 1); prev = cur; } } row[b.len()] } /// Up to `n` known sessions whose name or branch is nearest `to`: one that /// either starts with comes first, then the fewest edits, within half its length. fn closest(to: &str, known: &Value, n: usize) -> Vec { let to = to.to_ascii_lowercase(); let score = |name: &str| -> Option { let name = name.to_ascii_lowercase(); if to.len() >= 3 && name.len() >= 3 && (name.starts_with(&to) || to.starts_with(&name)) { return Some(0); } let d = distance(&to, &name); (d <= (to.chars().count() / 2).max(2)).then_some(d) }; let mut ranked: Vec<(usize, String)> = known.as_object().into_iter().flatten().filter_map(|(o, k)| { let best = [Some(o.as_str()), k["branch"].as_str()].into_iter().flatten().filter_map(score).min()?; Some((best, o.clone())) }).collect(); ranked.sort(); ranked.into_iter().take(n).map(|(_, o)| o).collect() } /// The sessions a role names, now. fn recipients(role: &str) -> Result> { if let Some(path) = role.strip_prefix("file:") { let path = path.trim_start_matches("./"); let c = Collab::open()?; return Ok(c.0.data["work"].as_object().into_iter().flatten() .filter(|(_, w)| w["files"].as_array().into_iter().flatten().filter_map(Value::as_str) .flat_map(|f| [f, split_file(f).1]) .any(|f| if path.ends_with('/') { f.starts_with(path) } else { f == path })) .map(|(o, _)| o.clone()).collect()); } let mut reg = registry::Locked::open()?; reg.reap(); if let Some(what) = role.strip_prefix("waiting:") { let nodes: Vec = reg.nodes().iter() .filter(|n| n["id"] == what || n["machine"] == what).cloned().collect(); if nodes.is_empty() { bail!("no node or machine {what}"); } return Ok(reg.waiters().iter() .filter(|(_, w)| nodes.iter().any(|n| registry::wants(w, n))) .map(|(o, _)| o.clone()).collect()); } if reg.node(role).is_none() { bail!("@{role}: not a node; a role is @, @waiting: or @file:"); } Ok(reg.leases().get(role).and_then(|l| l["owner"].as_str()).map(str::to_string).into_iter().collect()) } /// A session's notes, handed over and forgotten. Its landing gate's /// (`gate-`) come with them: they are the same session's. What a /// hook from before `hold_notes` asks for. pub fn take_notes(owner: &str) -> Result> { seen(owner); let mut c = Collab::open()?; let mut out = Vec::new(); for who in [owner.to_string(), format!("gate-{owner}")] { if let Some(Value::Array(v)) = c.obj("notes").remove(&who) { out.extend(v); } } read(c, owner, &out)?; Ok(out) } /// A hook that asked for its notes and never said it printed them (`confirm_notes`) /// is handed them again this long after. const NOTE_HOLD_S: i64 = 60; /// A session's notes for its hook to print, left where they are until it /// says it did (`confirm_notes`). Taking them as they were handed over lost /// them whenever the hook gave up first: a hook ends after 3 s whatever it is /// doing, and a hub slow to answer had marked read notes nobody saw. Each is /// held for `NOTE_HOLD_S` meanwhile, so the hooks of tools run side by side /// do not print it twice. pub fn hold_notes(owner: &str) -> Result> { seen(owner); let t = now(); let mut c = Collab::open()?; let mut out = Vec::new(); for who in [owner.to_string(), format!("gate-{owner}")] { let Some(Value::Array(v)) = c.obj("notes").get_mut(&who) else { continue }; for n in v.iter_mut().filter(|n| t - n["held_at"].as_i64().unwrap_or(0) >= NOTE_HOLD_S) { n["held_at"] = json!(t); out.push(n.clone()); } } if !out.is_empty() { c.save()?; } Ok(out) } /// The notes a hook printed (`hold_notes`), out of the mailbox: read now. How many there were. pub fn confirm_notes(owner: &str, ids: &[String]) -> Result { let mut c = Collab::open()?; let mut out = Vec::new(); for who in [owner.to_string(), format!("gate-{owner}")] { let Some(Value::Array(v)) = c.obj("notes").get_mut(&who) else { continue }; let (gone, kept): (Vec, Vec) = std::mem::take(v).into_iter() .partition(|n| n["id"].as_str().is_some_and(|id| ids.iter().any(|i| i == id))); *v = kept; if v.is_empty() { c.obj("notes").remove(&who); } out.extend(gone); } read(c, owner, &out)?; Ok(out.len()) } /// Notes taken out of their mailbox, as read: their senders see so (`sent_by`). fn read(mut c: Collab, owner: &str, out: &[Value]) -> Result<()> { if out.is_empty() { return Ok(()); } let t = now(); for n in out { if let Some(s) = n["id"].as_str().and_then(|id| c.obj("sent").get_mut(id)) { s["read_at"] = json!(t); } } c.save()?; drop(c); // How long each waited to be read: what notes are worth depends on it. let ages: Vec = out.iter() .map(|n| json!({"kind": n["kind"], "age_s": t - n["ts"].as_i64().unwrap_or(t)})).collect(); let ids: Vec<&Value> = out.iter().map(|n| &n["id"]).filter(|i| i.is_string()).collect(); events::emit("notes_taken", json!({"actor": owner, "notes": ages, "ids": ids})); Ok(()) } /// A session's notes, shown and left where they are: what `midas notes` and /// the MCP `notes` tool read. A subagent runs them under its session's name /// (nothing in its environment tells them apart), and taking the notes there /// handed the session's mail to an agent that cannot act on it; only the /// session's own hooks take them (`take_notes`). pub fn peek_notes(owner: &str) -> Vec { let Ok(c) = Collab::open() else { return vec![] }; [owner.to_string(), format!("gate-{owner}")].iter() .flat_map(|who| c.0.data["notes"][who].as_array().cloned().unwrap_or_default()) .collect() } /// How many notes wait for a session (and its landing gate), unread. pub fn count_notes(owner: &str) -> usize { seen(owner); let Ok(c) = Collab::open() else { return 0 }; [owner.to_string(), format!("gate-{owner}")].iter() .map(|w| c.0.data["notes"][w].as_array().map_or(0, Vec::len)).sum() } /// The notes a session sent in the last two days, newest first, each with /// `state`: waiting, read (and `read_at`) or expired (and why). pub fn sent_by(owner: &str) -> Vec { let t = now(); let Ok(c) = Collab::open() else { return vec![] }; let mut v: Vec = c.0.data["sent"].as_object().into_iter().flatten() .filter(|(_, s)| s["from"].as_str().is_some_and(|f| base(f) == base(owner))) .filter(|(_, s)| t - s["ts"].as_i64().unwrap_or(0) < NOTE_KEEP_S) .map(|(id, s)| { let mut s = s.clone(); s["id"] = json!(id); s["state"] = json!(if s["read_at"].is_number() { "read" } else if s["expired_at"].is_number() { "expired" } else { "waiting" }); s }).collect(); v.sort_by_key(|s| std::cmp::Reverse(s["ts"].as_i64().unwrap_or(0))); v } /// Drop unread notes — every one of `owners`' (a session that ended), or /// every one older than two days (`owners` empty) — and tell each sender, /// once, what of theirs went unread. Returns how many were dropped. fn drop_unread(owners: &[String], reason: &str) -> Result { let t = now(); let mut c = Collab::open()?; let mut dropped: Vec<(String, Value)> = Vec::new(); let boxes: Vec = c.0.data["notes"].as_object().into_iter().flatten().map(|(k, _)| k.clone()).collect(); for to in boxes { let all = owners.is_empty(); if !all && !owners.contains(&to) { continue; } let Some(Value::Array(v)) = c.obj("notes").get_mut(&to) else { continue }; let (gone, kept): (Vec, Vec) = std::mem::take(v).into_iter() .partition(|n| !all || t - n["ts"].as_i64().unwrap_or(t) >= NOTE_KEEP_S); *v = kept; if v.is_empty() { c.obj("notes").remove(&to); } dropped.extend(gone.into_iter().map(|n| (to.clone(), n))); } if dropped.is_empty() { return Ok(0); } for (_, n) in &dropped { mark_dropped(&mut c, n, reason, t); } c.save()?; drop(c); let mut by_sender: BTreeMap> = BTreeMap::new(); for (to, n) in &dropped { events::emit("note_expired", json!({"actor": "hub", "id": n["id"], "to": to, "from": n["from"], "reason": reason})); let from = n["from"].as_str().unwrap_or("hub"); if from == "hub" || base(from) == base(to) { continue; } let q = quote(n["text"].as_str().unwrap_or(""), 80); let id = n["id"].as_str().map(|i| format!("{i} ")).unwrap_or_default(); by_sender.entry(from.to_string()).or_default().push(match reason { "session_ended" => format!("{} ended before reading your note {id}(\"{q}\")", base(to)), _ => format!("{} did not read your note {id}(\"{q}\") within two days, so it was dropped", base(to)), }); } for (from, lines) in by_sender { let _ = say("hub", &from, &format!("{}.", lines.join("; ")), "expired"); } Ok(dropped.len()) } /// Every few minutes from the hub: notes nobody read in two days go, and /// their senders hear so. pub fn expire_notes() { if let Err(e) = drop_unread(&[], "age") { events::emit("error", json!({"actor": "hub", "what": format!("expiring notes: {e:#}")})); } } /// A session ended (its session-end hook): its unread notes go, telling their /// senders, and so does its work; the record of which overlaps it was told /// about stays a while, in case it is back at once (`forget_work`). Not for `/clear` or `/resume`: the worktree's next session is the /// same one carrying on. pub fn session_ended(owner: &str, reason: Option<&str>) { if matches!(reason, Some("clear" | "resume")) || owner.is_empty() { return; } let owner = base(owner).to_string(); if let Ok(mut m) = SEEN.lock() { m.remove(&owner); } if let Err(e) = drop_unread(&[owner.clone(), format!("gate-{owner}")], "session_ended") { events::emit("error", json!({"actor": "hub", "what": format!("dropping {owner}'s notes: {e:#}")})); } forget_work(&owner); // Root it was granted goes with it. crate::admin::session_ended(&owner); } /// A session's work, gone: it ended. What it was told about overlaps stays for /// [`RESTART_S`]: a hosted session ends and starts again within seconds, and /// was told the same overlap again each time (s455, 2026-10-24). fn forget_work(owner: &str) { if let Ok(mut c) = Collab::open() { c.obj("work").remove(owner); c.obj("ended").insert(owner.to_string(), json!(now())); let _ = c.save(); } } /// A session's work and the overlaps it was told about, gone at once: it landed. fn forget_landed(owner: &str) { if let Ok(mut c) = Collab::open() { c.obj("work").remove(owner); c.obj("ended").remove(owner); c.obj("told").retain(|pair, _| !pair.split('|').any(|o| o == owner)); let _ = c.save(); } } /// Overlap records of sessions that ended more than [`RESTART_S`] ago go; one /// that is back (`owner`, reporting) keeps its record and is no longer ended. fn settle_ended(c: &mut Collab, owner: &str, t: i64) { c.obj("ended").remove(owner); let gone: Vec = c.obj("ended").iter() .filter(|(_, at)| t - at.as_i64().unwrap_or(0) > RESTART_S).map(|(o, _)| o.clone()).collect(); for o in &gone { c.obj("ended").remove(o); c.obj("told").retain(|pair, _| !pair.split('|').any(|p| p == o)); } } /// Whether `other`'s work is still somebody's: its session was active within /// [`PEER_QUIET_S`]. Work is kept for days ([`WORK_STALE_S`]) so a session /// coming back finds it, but in the three days to 2026-10-25, 43 overlap notes /// went unread to sessions last seen days before — each with a twin to a live /// session about work nobody was doing. fn active(other: &str, work: &Value, names: &Value, t: i64) -> bool { let last = [work["at"].as_i64(), names[other]["last"].as_i64(), last_seen(other)].into_iter().flatten().max(); last.is_some_and(|l| t - l <= PEER_QUIET_S) } /// How many notes are waiting for each session (for the page). fn pending(c: &Collab) -> BTreeMap { c.0.data["notes"].as_object().into_iter().flatten() .map(|(k, v)| (k.clone(), v.as_array().map_or(0, Vec::len))).collect() } // ── Work, and where it overlaps ────────────────────────────────────────────── /// Per changed file, the functions its hunks are in (the text git puts after /// a hunk header's second `@@`, shortened). pub type Functions = BTreeMap>; /// Functions from a request body's `functions` (`{file: [name, …]}`), capped; /// `None` when it sent none (a midas from before they were sent). pub fn functions_from(v: &Value) -> Option { let o = v.as_object()?; Some(o.iter().take(5000).map(|(f, names)| { let mut seen = BTreeSet::new(); let names: Vec = names.as_array().into_iter().flatten().filter_map(Value::as_str) .map(|n| quote(n, 60)).filter(|n| !n.is_empty() && seen.insert(n.clone())).take(MAX_FUNCTIONS).collect(); (f.clone(), names) }).filter(|(_, n)| !n.is_empty()).collect()) } /// A session's changed files, from its flush. Tells it, and whoever else is /// changing the same files, about every file they newly have in common. #[cfg(test)] pub fn report_work(owner: &str, branch: Option<&str>, files: &[String]) -> Result> { report_work_with(owner, branch, files, None, None) } /// `report_work`, with the functions each file's hunks are in, when the /// session's midas sends them; and the project the worktree is (`repo`), when /// it says: then these replace only that project's files, and a session's /// other projects' stay (`qualified`). pub fn report_work_with(owner: &str, branch: Option<&str>, files: &[String], functions: Option<&Functions>, repo: Option<&str>) -> Result> { report_work_in(owner, branch, files, functions, repo, None) } /// `report_work_with`, from a session folder that says which `projects` it /// spans now: another project's files are kept only while it is one of them. /// Without, a project's files stayed for days after the session stopped /// reporting it (the host checkout's loose files a midas before /// `folder_inside` sent), and every landing told the session of them again. pub fn report_work_in(owner: &str, branch: Option<&str>, files: &[String], functions: Option<&Functions>, repo: Option<&str>, projects: Option<&[String]>) -> Result> { let owner = base(owner); seen(owner); let mut files: BTreeSet = files.iter().filter(|f| !COMMON.contains(&split_file(f).1)).map(|f| qualified(repo, f)).collect(); let mut functions: Functions = functions.into_iter().flatten() .map(|(f, n)| (qualified(repo, f), n.clone())).filter(|(f, _)| files.contains(f)).collect(); let t = now(); let names = names_of(); let mut c = Collab::open()?; c.obj("work").retain(|_, w| t - w["at"].as_i64().unwrap_or(0) < WORK_STALE_S); settle_ended(&mut c, owner, t); if let Some(name) = repo.and_then(|r| r.rsplit('/').next()) { let w = &c.0.data["work"][owner]; let other = |f: &str| split_file(f).0.is_some_and(|p| p != name && projects.is_none_or(|ps| ps.iter().any(|q| q == p))); files.extend(w["files"].as_array().into_iter().flatten().filter_map(Value::as_str).filter(|f| other(f)).map(str::to_string)); for (f, n) in functions_from(&w["functions"]).unwrap_or_default() { if other(&f) { functions.insert(f, n); } } } c.obj("work").insert(owner.to_string(), json!({"branch": branch, "files": files, "functions": functions, "at": t})); let others: Vec<(String, Value)> = c.0.data["work"].as_object().into_iter().flatten() .filter(|(o, w)| o.as_str() != owner && active(o, w, &names, t)).map(|(o, w)| (o.clone(), w.clone())).collect(); let mut found = Vec::new(); let mut notes = Vec::new(); for (other, w) in others { let theirs: BTreeSet = w["files"].as_array().into_iter().flatten() .filter_map(|f| f.as_str().map(str::to_string)).collect(); let shared: Vec = files.intersection(&theirs).cloned().collect(); if shared.is_empty() { continue; } found.push(json!({"with": other, "files": shared})); // What the pair was told stays until one of them lands or ends: work // that shrinks and grows again is not news a second time. let pair = if owner < other.as_str() { format!("{owner}|{other}") } else { format!("{other}|{owner}") }; let mut told: BTreeSet = c.0.data["told"][&pair].as_array().into_iter().flatten() .filter_map(|f| f.as_str().map(str::to_string)).collect(); if shared.iter().all(|f| told.contains(f)) { continue; } told.extend(shared.iter().cloned()); c.obj("told").insert(pair, json!(told)); notes.push((other, w["branch"].clone(), w["functions"].clone(), shared)); } c.save()?; drop(c); let mine = json!(functions); for (other, their_branch, theirs, shared) in notes { let (text, about) = overlap_note(&other, &names[&other], &their_branch, &shared, &mine, &theirs); say_about("hub", owner, &text, "overlap", about)?; let (text, about) = overlap_note(owner, &names[owner], &json!(branch), &shared, &theirs, &mine); say_about("hub", &other, &text, "overlap", about)?; } Ok(found) } /// An overlap's files listed in a note; the rest are counted. const OVERLAP_FILES: usize = 6; /// The note telling a session that `other` changes files it changes, and the /// same as data for the page: a line per file, with where either side changes /// it and the places both do — /// /// ```text /// b ("routing", feat/b) also changes 2 files you change: /// src/a.rs — you: x, y; them: y, z (both: y) /// src/b.rs /// answer them: midas say b "…" /// ``` fn overlap_note(other: &str, name: &Value, branch: &Value, shared: &[String], you: &Value, them: &Value) -> (String, Value) { let label = name["label"].as_str().map(|l| quote(l, 60)); let short = short_name(other); let shown_branch = branch.as_str().filter(|b| !own_branch(other, b)); let about: Vec = label.iter().map(|l| format!("\"{l}\"")).chain(shown_branch.map(str::to_string)).collect(); let about = if about.is_empty() { String::new() } else { format!(" ({})", about.join(", ")) }; let n = shared.len(); let (lines, files) = file_lines(shared, you, them); let text = format!("{short}{about} also changes {n} file{} you change:{lines}\nanswer them: midas say {short} \"…\"", if n == 1 { "" } else { "s" }); let about = json!({"with": short, "label": label, "branch": shown_branch, "files": files, "more": n.saturating_sub(OVERLAP_FILES)}); (text, about) } /// A session as notes name it: a hosted one by its id (`s212`, not /// `session-s212`), which `resolve` takes back; any other by its name. fn short_name(owner: &str) -> &str { owner.strip_prefix("session-").filter(|id| crate::sessions::id_ok(id)).unwrap_or(owner) } /// Whether `branch` is the one a hosted session is given (`session/s212` for /// `session-s212`), which says nothing its name does not. fn own_branch(owner: &str, branch: &str) -> bool { owner.strip_prefix("session-").is_some_and(|id| branch.strip_prefix("session/") == Some(id)) } /// The files two sessions share, a line each (`\n file — you: …; them: …`) /// with the places both change, and the same as data. fn file_lines(shared: &[String], you: &Value, them: &Value) -> (String, Vec) { let names = |f: &Value, file: &str| -> Vec { f[file].as_array().into_iter().flatten().filter_map(Value::as_str).map(str::to_string).collect() }; let (mut text, mut files) = (String::new(), Vec::new()); for file in shared.iter().take(OVERLAP_FILES) { let (mine, theirs) = (names(you, file), names(them, file)); let both: Vec<&str> = mine.iter().filter(|m| theirs.contains(m)).map(String::as_str).collect(); let sides: Vec = [("you", &mine), ("them", &theirs)].into_iter() .filter(|(_, n)| !n.is_empty()).map(|(who, n)| format!("{who}: {}", n.join(", "))).collect(); text.push_str(&format!("\n {file}")); if !sides.is_empty() { text.push_str(&format!(" — {}", sides.join("; "))); } if !both.is_empty() { text.push_str(&format!(" (both: {})", both.join(", "))); } files.push(json!({"file": file, "you": mine, "them": theirs})); } if shared.len() > OVERLAP_FILES { text.push_str(&format!("\n and {} more", shared.len() - OVERLAP_FILES)); } (text, files) } /// Files a session has just started to change (the tool hook, on an edit): /// added to its work as it was at the last flush, which then decides the /// overlaps as the flush would. The next flush replaces the list whole. #[cfg(test)] pub fn editing(owner: &str, branch: Option<&str>, files: &[String]) -> Result> { editing_with(owner, branch, files, None, None) } /// `editing`, with the functions the edited files' hunks are in so far, and /// the project they are in (`qualified`). pub fn editing_with(owner: &str, branch: Option<&str>, files: &[String], functions: Option<&Functions>, repo: Option<&str>) -> Result> { let owner = base(owner); let (mut all, known_branch, mut fns) = { let c = Collab::open()?; let w = &c.0.data["work"][owner]; let all: BTreeSet = w["files"].as_array().into_iter().flatten() .filter_map(|f| f.as_str().map(str::to_string)).collect(); (all, w["branch"].as_str().map(str::to_string), functions_from(&w["functions"]).unwrap_or_default()) }; all.extend(files.iter().map(|f| qualified(repo, f))); for (f, n) in functions.into_iter().flatten() { fns.insert(qualified(repo, f), n.clone()); } let branch = branch.map(str::to_string).or(known_branch); report_work_with(owner, branch.as_deref(), &all.into_iter().collect::>(), Some(&fns), None) } /// A branch that landed is nobody's work in progress any more, and what its /// session was told about overlaps is history. Every active session changing /// the files it landed hears so now: otherwise it found out at its own landing, /// in the rebase or the gate. pub fn landed(owner: &str, branch: Option<&str>, sha: Option<&str>) { let owner = base(owner); let t = now(); let names = names_of(); let mut notes = Vec::new(); if let Ok(c) = Collab::open() { let work = &c.0.data["work"]; let mine = &work[owner]; let files: BTreeSet<&str> = mine["files"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); for (other, w) in work.as_object().into_iter().flatten() { if other == owner || !active(other, w, &names, t) { continue; } let shared: Vec = w["files"].as_array().into_iter().flatten().filter_map(Value::as_str) .filter(|f| files.contains(f)).map(str::to_string).collect(); if !shared.is_empty() { notes.push((other.clone(), shared.len(), file_lines(&shared, &w["functions"], &mine["functions"]).0)); } } } let what = match (branch, sha) { (Some(b), Some(s)) => format!("{b} ({})", crate::util::sha8(s)), (Some(b), None) => b.to_string(), (None, Some(s)) => crate::util::sha8(s).to_string(), (None, None) => "its branch".to_string(), }; for (other, n, lines) in notes { let _ = say("hub", &other, &format!( "{} landed {what} on main, changing {n} file{} you change too:{lines}\nRebase onto origin/main before you build on it.", short_name(owner), if n == 1 { "" } else { "s" }), "landed"); } forget_landed(owner); } // ── Reservations ───────────────────────────────────────────────────────────── fn namespace_ok(ns: &str) -> bool { !ns.is_empty() && ns.len() <= 40 && ns.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } /// The next number in `ns` after `from` and after everything handed out. pub fn reserve(ns: &str, owner: &str, from: i64, why: Option<&str>) -> Result { if !namespace_ok(ns) { bail!("a namespace is lowercase letters, digits and dashes: {ns:?}"); } let owner = owner.strip_prefix("gate-").unwrap_or(owner); let mut c = Collab::open()?; let entry = c.obj("reserved").entry(ns.to_string()).or_insert_with(|| json!({"last": 0, "by": {}})); let n = entry["last"].as_i64().unwrap_or(0).max(from) + 1; entry["last"] = json!(n); entry["by"][n.to_string()] = json!({"owner": owner, "at": now(), "why": why}); c.save()?; events::emit("reserved", json!({"actor": owner, "namespace": ns, "number": n, "why": why})); Ok(n) } pub fn reservations() -> Value { Collab::open().map(|c| c.0.data["reserved"].clone()).unwrap_or(json!({})) } // ── Open ends ──────────────────────────────────────────────────────────────── // // Work a session could not finish where it was, left for the next session on // the right machine: `midas todo add --for workstation "…"`. The first session // there to start is shown it (the project's session-start hook asks with // `/v1/todos/take`), does it first, and says `midas todo done `. One // shown but never done is offered again a day later. const TODO_RECLAIM_S: i64 = 86400; fn for_ok(f: &str) -> bool { !f.is_empty() && f.len() <= 40 && f.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') } /// Leave an open end for the next session of caller `for_` (`any` for every /// caller). Returns its id. pub fn todo_add(by: &str, for_: &str, text: &str) -> Result { let text: String = text.trim().chars().take(2000).collect(); if text.is_empty() { bail!("say what is left to do"); } if !for_ok(for_) { bail!("--for names a caller (workstation, agent, …) or any: {for_:?}"); } let mut c = Collab::open()?; let n = c.0.data["todo_seq"].as_u64().unwrap_or(0) + 1; c.0.data["todo_seq"] = json!(n); let id = format!("t{n}"); c.obj("todos").insert(id.clone(), json!({"text": text, "for": for_, "by": by, "at": now()})); c.save()?; events::emit("todo_added", json!({"actor": by, "id": id, "for": for_, "text": text})); Ok(id) } /// The open ends for a session of `caller` starting in `owner`: those meant /// for it, not yet done and not being done by another session. They are now /// this session's. pub fn todo_take(caller: &str, owner: &str) -> Result> { let t = now(); let mut c = Collab::open()?; let mut out = Vec::new(); for (id, todo) in c.obj("todos").iter_mut() { let mine = todo["claimed_by"] == owner; let free = todo["claimed_by"].is_null() || t - todo["claimed_at"].as_i64().unwrap_or(0) > TODO_RECLAIM_S; if todo["done_at"].is_null() && (todo["for"] == caller || todo["for"] == "any") && (mine || free) { if !mine { todo["claimed_by"] = json!(owner); todo["claimed_at"] = json!(t); } let mut v = todo.clone(); v["id"] = json!(id); out.push(v); } } if !out.is_empty() { c.save()?; for v in &out { events::emit("todo_shown", json!({"actor": owner, "id": v["id"], "for": v["for"]})); } } Ok(out) } /// Done: it stays in the record, out of everybody's way. pub fn todo_done(id: &str, by: &str, note: Option<&str>) -> Result<()> { let mut c = Collab::open()?; let Some(todo) = c.obj("todos").get_mut(id) else { bail!("no open end {id}") }; todo["done_at"] = json!(now()); todo["done_by"] = json!(by); if let Some(n) = note.map(str::trim).filter(|n| !n.is_empty()) { todo["done_note"] = json!(n); } c.save()?; events::emit("todo_done", json!({"actor": by, "id": id, "note": note})); Ok(()) } /// Every open end, and the ones done in the last week. pub fn todos() -> Value { let t = now(); let Ok(c) = Collab::open() else { return json!([]) }; let mut v: Vec = c.0.data["todos"].as_object().into_iter().flatten() .filter(|(_, d)| d["done_at"].as_i64().is_none_or(|at| t - at < 7 * 86400)) .map(|(id, d)| { let mut d = d.clone(); d["id"] = json!(id); d }) .collect(); v.sort_by_key(|d| d["at"].as_i64().unwrap_or(0)); json!(v) } // ── Decisions ──────────────────────────────────────────────────────────────── // // What only the person steering the sessions may decide. A session asks // (`midas ask "…" --option A --option B --with `); the web // page shows it with a button per option, and wakes a phone that asked to be // (`push.rs`); the // answer reaches the asker and every session it named, as a note. /// Ask the person. Returns its id (`d`). pub fn decision_add(by: &str, question: &str, options: &[String], with: &[String]) -> Result { let question: String = question.trim().chars().take(1000).collect(); let options: Vec = options.iter().map(|o| o.trim().chars().take(200).collect::()) .filter(|o| !o.is_empty()).take(6).collect(); if question.is_empty() { bail!("say what is to be decided"); } if options.len() == 1 { bail!("one option is not a choice: give two or more, or none for a free answer"); } let mut c = Collab::open()?; let n = c.0.data["decision_seq"].as_u64().unwrap_or(0) + 1; c.0.data["decision_seq"] = json!(n); let id = format!("d{n}"); c.obj("decisions").insert(id.clone(), json!({"question": question, "options": options, "by": by, "with": with, "at": now()})); c.save()?; events::emit("decision_asked", json!({"actor": by, "id": id, "question": question, "options": options, "with": with})); Ok(id) } /// The person's answer: an option's text or its number (1, 2, …), or free /// words when there were no options. Told to the asker and those it named. pub fn decision_answer(id: &str, choice: &str, by: &str, note: Option<&str>) -> Result { let mut c = Collab::open()?; let Some(d) = c.obj("decisions").get_mut(id) else { bail!("no decision {id}") }; if d["answer"].is_string() { bail!("{id} was decided already: {}", d["answer"].as_str().unwrap_or("")); } let options: Vec = d["options"].as_array().into_iter().flatten().filter_map(|o| o.as_str().map(str::to_string)).collect(); let choice = choice.trim(); let answer = match choice.parse::() { Ok(k) if (1..=options.len()).contains(&k) => options[k - 1].clone(), _ => match options.iter().find(|o| o.eq_ignore_ascii_case(choice)) { Some(o) => o.clone(), None if options.is_empty() && !choice.is_empty() => choice.to_string(), None => bail!("{id}: choose one of {}", options.iter().enumerate() .map(|(i, o)| format!("{} ({o})", i + 1)).collect::>().join(", ")), }, }; d["answer"] = json!(answer); d["answered_by"] = json!(by); d["answered_at"] = json!(now()); let note = note.map(str::trim).filter(|n| !n.is_empty()); if let Some(n) = note { d["note"] = json!(n); } let d = d.clone(); c.save()?; drop(c); events::emit("decision_answered", json!({"actor": by, "id": id, "answer": answer, "note": note})); // Into the person's focus ledger (focus.rs): words of their own when there were no options, or a note. if let Some(person) = crate::focus::person_of(by) { let asked = json!({"kind": "decision", "question": d["question"], "at": d["at"]}); crate::focus::record(person, d["by"].as_str().unwrap_or(""), "decision", Some(&asked), "", &json!(answer), options.is_empty() || note.is_some(), 0); } let text = format!("The person decided {id} (\"{}\"): {answer}{}", d["question"].as_str().unwrap_or(""), note.map(|n| format!(" — {n}")).unwrap_or_default()); let mut told = vec![d["by"].as_str().unwrap_or("").to_string()]; told.extend(d["with"].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(str::to_string))); told.retain(|o| !o.is_empty()); told.dedup(); for o in &told { say("hub", o, &text, "decision")?; } Ok(d) } /// Open decisions, and those answered in the last week. pub fn decisions() -> Value { let t = now(); let Ok(c) = Collab::open() else { return json!([]) }; let mut v: Vec = c.0.data["decisions"].as_object().into_iter().flatten() .filter(|(_, d)| d["answered_at"].as_i64().is_none_or(|at| t - at < 7 * 86400)) .map(|(id, d)| { let mut d = d.clone(); d["id"] = json!(id); d }) .collect(); v.sort_by_key(|d| d["at"].as_i64().unwrap_or(0)); json!(v) } // ── Archived cards ─────────────────────────────────────────────────────────── // // A person puts a session's card away (a landing they have seen, a session // they will not come back to): it leaves the board's working and landed lanes. // A session that moves on — takes a node, joins a line, lands again — shows // again, archived or not: what it does now is news. pub fn set_archived(owner: &str, on: bool, by: &str) -> Result<()> { let owner = owner.strip_prefix("gate-").unwrap_or(owner); if owner.is_empty() { bail!("which session?"); } let mut c = Collab::open()?; if on { c.obj("archived").insert(owner.to_string(), json!({"at": now(), "by": by})); } else { c.obj("archived").remove(owner); } c.save()?; events::emit(if on { "archived" } else { "unarchived" }, json!({"actor": by, "session": owner})); Ok(()) } pub fn archived() -> Value { Collab::open().map(|c| c.0.data["archived"].clone()).unwrap_or(json!({})) } // ── Names ──────────────────────────────────────────────────────────────────── /// `bridge-cse_01ABC…` is the worktree of Remote Control session `session_01ABC…`. pub fn link(owner: &str) -> Option { let id = owner.strip_prefix("gate-").unwrap_or(owner).strip_prefix("bridge-cse_")?; id.bytes().all(|b| b.is_ascii_alphanumeric()).then(|| format!("https://claude.ai/code/session_{id}")) } /// What to call every session seen lately: its label, branch and link, and /// for the page its work, overlaps and waiting notes; and for `midas who` the /// node it holds (`node`, `intent`) or waits for (`waiting_for`), when it was /// last seen (`seen`, `last`), and `ended` when its session-end hook ran. pub fn names() -> Value { let mut out = names_of(); // The registry first, and let go: it is never held while collab.json is // (a landing's event reaches `landed` with the registry locked). if let Ok(reg) = registry::Locked::open() { let t = now(); for (node, l) in reg.leases() { let Some(o) = l["owner"].as_str() else { continue }; let n = entry(&mut out, o); n["node"] = json!(node); n["mode"] = json!(registry::mode_of(l).as_str()); if l["intent"].is_string() && l["intent_until"].as_i64().is_none_or(|u| u > t) { n["intent"] = l["intent"].clone(); } n["last"] = json!(t); } for (o, w) in reg.waiters() { let n = entry(&mut out, o); n["waiting_for"] = w.get("node").filter(|v| v.is_string()).or(w.get("machine")).cloned().unwrap_or(json!("any")); n["last"] = json!(t); } } let seen: BTreeMap = SEEN.lock().map(|m| m.clone()).unwrap_or_default(); for (o, at) in seen { let n = entry(&mut out, &o); n["seen"] = json!(at); n["last"] = json!(n["last"].as_i64().unwrap_or(0).max(at)); // Seen since its end mark: the worktree has a session again. if n["ended"].as_i64().is_some_and(|e| at > e + 60) { n["ended"] = Value::Null; } } if let Ok(c) = Collab::open() { let work = c.0.data["work"].as_object().cloned().unwrap_or_default(); for (o, w) in &work { let mine: BTreeSet<&str> = w["files"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); let overlaps: Vec = work.iter().filter(|(x, _)| *x != o).filter_map(|(x, xw)| { let shared: Vec<&str> = xw["files"].as_array().into_iter().flatten() .filter_map(Value::as_str).filter(|f| mine.contains(f)).collect(); (!shared.is_empty()).then(|| json!({"with": x, "files": shared})) }).collect(); let n = entry(&mut out, o); n["files"] = json!(mine.len()); // Which ones: a session's page lists them under its header. n["changed"] = json!(mine); n["overlaps"] = json!(overlaps); if n["branch"].is_null() { n["branch"] = w["branch"].clone(); } if let Some(at) = w["at"].as_i64() { n["last"] = json!(n["last"].as_i64().unwrap_or(0).max(at)); } } for (o, k) in pending(&c) { entry(&mut out, &o)["notes"] = json!(k); } } out } fn entry<'a>(out: &'a mut Value, owner: &str) -> &'a mut Value { if out[owner].is_null() { out[owner] = json!({"label": null, "branch": null, "link": link(owner)}); } &mut out[owner] } /// Labels and branches from the session marks (the last thirty days), with /// the time of the latest (`last`) and of an end no start followed (`ended`; /// not `/clear` or `/resume`, after which the worktree carries on). fn names_of() -> Value { let mut out = json!({}); for m in crate::builds::marks(30 * 86400) { let Some(o) = m["actor"].as_str() else { continue }; let ts = m["ts"].as_str().and_then(|t| chrono::DateTime::parse_from_rfc3339(t).ok()).map(|t| t.timestamp()); let n = entry(&mut out, o); if m["event"] == "label" { n["label"] = m["label"].clone(); } if m["branch"].is_string() { n["branch"] = m["branch"].clone(); } if let Some(ts) = ts { n["last"] = json!(n["last"].as_i64().unwrap_or(0).max(ts)); match m["event"].as_str() { Some("end") if !matches!(m["reason"].as_str(), Some("clear" | "resume")) => n["ended"] = json!(ts), Some("start" | "label") => n["ended"] = Value::Null, _ => {} } } } out } // ── The hub's rules ────────────────────────────────────────────────────────── /// Every few minutes from the hub: a session holding a node somebody waits /// for, and not using it, hears so. Once a quarter of an hour at most. pub fn nudge_idle_holders() { const QUIET_S: i64 = 5 * 60; const AGAIN_S: i64 = 15 * 60; let Ok(mut reg) = registry::Locked::open() else { return }; let t = now(); let waiting: Vec<(String, Value)> = reg.waiters().iter().map(|(o, w)| (o.clone(), w.clone())).collect(); if waiting.is_empty() { return; } let mut nudges = Vec::new(); let leases: Vec<(String, Value)> = reg.leases().iter().map(|(k, v)| (k.clone(), v.clone())).collect(); for (node, l) in leases { if registry::mode_of(&l) != registry::Mode::Build { continue; } let Some(n) = reg.node(&node).cloned() else { continue }; let wanted = waiting.iter().filter(|(_, w)| registry::wants(w, &n)).count(); // A landing gate holds the turn to land every session shares: its // holder hears at once, busy or not, and gives the node over between // two builds (s530's gate waited 14 minutes, 2026-10-31). let gate = waiting.iter().find(|(o, w)| registry::is_gate(o) && registry::wants(w, &n)).map(|(o, _)| o.clone()); let reading = registry::reading(&node); let busy = reading.as_ref().is_some_and(|r| r["sessions"].as_u64().unwrap_or(0) > 0); let quiet = t - l["last_active"].as_i64().unwrap_or(t); let owner = l["owner"].as_str().unwrap_or("").to_string(); if wanted == 0 || t - l["nudged_at"].as_i64().unwrap_or(0) < AGAIN_S || gate.is_none() && (busy || quiet < QUIET_S) || gate.as_deref().is_some_and(|g| g.strip_prefix("gate-") == Some(owner.as_str())) { continue; } if let Some(lease) = reg.leases_mut().get_mut(&node) { lease["nudged_at"] = json!(t); } reg.mark(); let held = (t - l["claimed_at"].as_i64().unwrap_or(t)) / 60; if let Some(g) = gate { let who = g.strip_prefix("gate-").unwrap_or(&g); nudges.push((owner, format!( "{who}'s landing gate waits for {node}, which you hold: every landing waits behind it. \ `midas yield` now gives {node} over when your current command ends, and `midas take` \ puts you back in line; or `midas release` if you are done with it."))); continue; } nudges.push((owner, format!( "{wanted} waiting for {node}, which you have held {held}m without a command for {}m. \ Done with it: `midas release`. Need it again soon: `midas intent \"what, for how long\" --minutes N` \ tells them; or `midas yield` to let it go when your next build ends.", quiet / 60))); } let _ = reg.commit(); drop(reg); for (owner, text) in nudges { let _ = say("hub", &owner, &text, "nudge"); } } #[cfg(test)] mod tests { use super::*; #[test] fn a_remote_control_worktree_links_to_its_session() { assert_eq!(link("bridge-cse_01CNAdFmgksxaBPBR8ctWmbi").as_deref(), Some("https://claude.ai/code/session_01CNAdFmgksxaBPBR8ctWmbi")); assert_eq!(link("gate-bridge-cse_01AB").as_deref(), Some("https://claude.ai/code/session_01AB")); assert_eq!(link("readme-sheet"), None); assert_eq!(link("bridge-cse_../x"), None); } #[test] fn a_subagent_worktree_is_told_by_its_place_and_name() { use std::path::Path; assert!(subagent_worktree(Path::new("/home/a/work/.claude/worktrees/agent-a21506b8f3cdbcf06"))); assert!(!subagent_worktree(Path::new("/home/a/work/.claude/worktrees/bridge-cse_01JP")), "a session's own"); assert!(!subagent_worktree(Path::new("/home/a/midas-wt/agent-sheet")), "a worktree named so by a person"); } #[test] fn a_session_folder_inside_a_checkout_is_not_that_checkouts_work() { let repo = std::env::temp_dir().join(format!("midas-folder-inside-{}", std::process::id())); let folder = repo.join(".claude/worktrees/session-s1"); let project = folder.join("midas"); fs::create_dir_all(&project).unwrap(); fs::write(folder.join(crate::sessions::SESSION_MARK), "{}").unwrap(); assert_eq!(folder_inside(&repo, &folder).map(|f| fs::canonicalize(f).unwrap()), Some(fs::canonicalize(&folder).unwrap())); assert!(folder_inside(&repo, &project).is_some(), "below the folder, git answering the outer checkout"); assert_eq!(folder_inside(&project, &project), None, "the folder's own project worktree"); assert_eq!(folder_inside(&repo, &repo), None, "the checkout itself"); let _ = fs::remove_dir_all(&repo); } } // ── The session's side ─────────────────────────────────────────────────────── /// Say on stderr how many notes wait for this session, best effort: called by /// the commands a session runs anyway (every `ssh `, `take`, `wait`, /// `release`). They are not handed over here — stderr of a background command, /// or of `ssh … | tail`, is where notes went to be lost — but by the hooks, /// where the agent reads them. Never fails, never writes to stdout. pub fn mention_waiting(owner: &str) { let Ok(v) = crate::client::get(&format!("/v1/notes/count?owner={owner}")) else { return }; match v["count"].as_u64().unwrap_or(0) { 0 => {} n => eprintln!("midas: {n} note{} waiting — they reach you with your next prompt or tool call; \ `midas notes` reads them now", if n == 1 { "" } else { "s" }), } } /// A note as the one line its session reads: who sent it (with its label and /// branch) and how to answer. pub fn note_line(n: &Value) -> String { let from = n["from"].as_str().unwrap_or("?"); if from == "hub" { // The hub's own keep their lines: an overlap is a line per file. let text = n["text"].as_str().unwrap_or("").lines().map(str::trim_end).collect::>().join("\n"); return format!("midas: {text}"); } let text = n["text"].as_str().unwrap_or("").split('\n').map(str::trim).collect::>().join(" "); let Some(id) = n["id"].as_str() else { return format!("midas: note from {from}: {text}") }; let mut about = Vec::new(); if let Some(l) = n["from_label"].as_str() { about.push(format!("\"{}\"", quote(l, 40))); } if let Some(b) = n["from_branch"].as_str().filter(|b| !own_branch(from, b)) { about.push(b.to_string()); } let about = if about.is_empty() { String::new() } else { format!(" ({})", about.join(", ")) }; format!("midas: note {id} from {}{about}: {text} — reply: midas say --re {id} \"…\"", short_name(from)) } /// A note as the page draws it, beside the text its agent was sent: who it /// is from (a session, or `hub`), what kind it is, and for an overlap the /// session and files it is about (`overlap_note`). fn page_note(n: &Value) -> Value { let from = n["from"].as_str().unwrap_or("?"); let branch = n["from_branch"].as_str().filter(|b| !own_branch(from, b)); let mut out = json!({"id": n["id"], "from": short_name(from), "kind": n["kind"], "label": n["from_label"], "branch": branch, "text": n["text"]}); if n["about"].is_object() { out["about"] = n["about"].clone(); } out } /// A first prompt that is no name for its session: a note midas woke it with, /// or the end of a background task. Until 2026-10-27 such sessions were /// labelled "From the build workspace — midas: …" and " …". pub fn not_a_name(prompt: &str) -> bool { let p = prompt.trim_start(); ["From the build workspace", "midas: ", "", ""].iter().any(|s| p.starts_with(s)) } /// `midas notes`: this session's notes, on stdout; with `--hook `, as a /// Claude Code hook's added context, and nothing at all when there are none. /// `--sent`: the notes it sent in the last two days, and whether they were read. pub fn notes_cmd(owner: &str, hook: Option<&str>, sent: bool) -> Result { if sent { let v = crate::client::post("/v1/notes/sent", &json!({"owner": owner}))?; let all = v["sent"].as_array().cloned().unwrap_or_default(); if all.is_empty() { println!("no notes sent in the last two days"); } for s in &all { let state = match s["state"].as_str() { Some("read") => format!("read at {}", clock(s["read_at"].as_i64().unwrap_or(0))), Some("expired") => format!("expired unread ({})", s["expired_reason"].as_str().unwrap_or("?").replace('_', " ")), _ => "waiting".into(), }; println!("{:<5} {} to {} {state} \"{}\"", s["id"].as_str().unwrap_or("?"), clock(s["ts"].as_i64().unwrap_or(0)), s["to"].as_str().unwrap_or("?"), quote(s["text"].as_str().unwrap_or(""), 70)); } return Ok(0); } // Only a hook takes the notes; read by hand they stay for the hook to hand // over (`peek_notes`). A hub from before peeking takes them either way. A // hook's are held for it (`hold_notes`), and read only once it has printed // them; a hub from before holding takes them at once. let v = crate::client::post("/v1/notes/take", &json!({"owner": owner, "peek": hook.is_none(), "hold": hook.is_some()}))?; let notes = v["notes"].as_array().cloned().unwrap_or_default(); let lines: Vec = notes.iter().map(note_line).collect(); match hook { Some(event) if !lines.is_empty() => { use std::io::Write; println!("{}", json!({"hookSpecificOutput": { "hookEventName": event, "additionalContext": format!("Notes from the build workspace for this session:\n{}", lines.join("\n")), }})); std::io::stdout().flush()?; // Unconfirmed, they come again with a hook a minute from now. let ids: Vec<&Value> = notes.iter().map(|n| &n["id"]).filter(|i| i.is_string()).collect(); let _ = crate::client::post("/v1/notes/confirm", &json!({"owner": owner, "ids": ids})); } Some(_) => {} None if lines.is_empty() => println!("no notes"), None => println!("{}\n(left unread: they reach the session itself with its next prompt or tool call)", lines.join("\n")), } Ok(0) } /// A time today as HH:MM, here. fn clock(ts: i64) -> String { use chrono::TimeZone; chrono::Local.timestamp_opt(ts, 0).single().map(|t| t.format("%H:%M").to_string()).unwrap_or_else(|| "?".into()) } /// A Claude Code subagent's own worktree (`isolation: "worktree"`): /// `/.claude/worktrees/agent-`. No session hook runs for it — not /// at its start, not at its end — so it is no session of its own to the /// workspace: it takes no node and reports no work (which would read as an /// overlap with the session that started it). pub fn subagent_worktree(top: &std::path::Path) -> bool { let name = top.file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); name.starts_with("agent-") && top.parent().is_some_and(|p| p.ends_with(".claude/worktrees")) } /// The session folder between `at` and the checkout `top` it resolves to, if /// any. A session folder is no repository, but it can sit inside one (a /// project's own `.claude/worktrees/`), and git then answers that checkout for /// it: its loose files are nobody's work, and reported they read as every /// session changing them. pub fn folder_inside(top: &std::path::Path, at: &std::path::Path) -> Option { let top = std::fs::canonicalize(top).unwrap_or_else(|_| top.to_path_buf()); let at = std::fs::canonicalize(at).unwrap_or_else(|_| at.to_path_buf()); if !at.starts_with(&top) { return None; } at.ancestors().take_while(|d| *d != top).find(|d| d.join(crate::sessions::SESSION_MARK).is_file()).map(PathBuf::from) } /// `midas editing …`: tell the hub this session has started changing /// these files (and the functions changed in them so far), then hand over its /// notes — an overlap the files make among them — unless `no_notes` (a /// subagent's edit: its parent reads the notes). Paths are taken relative to /// the worktree, as the flush reports them; one outside it is no one else's /// business and is left out. pub fn editing_cmd(owner: &str, files: &[std::path::PathBuf], hook: Option<&str>, no_notes: bool) -> Result { let top_of = |dir: &std::path::Path| std::process::Command::new("git").arg("-C").arg(dir).args(["rev-parse", "--show-toplevel"]) .stderr(std::process::Stdio::null()).output().ok().filter(|o| o.status.success()) .map(|o| PathBuf::from(String::from_utf8_lossy(&o.stdout).trim())) .map(|t| std::fs::canonicalize(&t).unwrap_or(t)); let cwd = std::env::current_dir()?; if top_of(&cwd).is_some_and(|t| subagent_worktree(&t)) { return Ok(0); } // Each file in the worktree it is in: a session spanning projects edits in // several, from a folder that is none (sessions.rs `folder`). let mut by_top: BTreeMap> = BTreeMap::new(); for f in files { let abs = if f.is_absolute() { f.clone() } else { cwd.join(f) }; // The file may be new: resolve its directory, which exists. let Some(dir) = abs.parent().and_then(|d| std::fs::canonicalize(d).ok()) else { continue }; let (Some(name), Some(top)) = (abs.file_name(), top_of(&dir)) else { continue }; if folder_inside(&top, &dir).is_some() { continue; } if let Ok(r) = dir.join(name).strip_prefix(&top) { let r = r.to_string_lossy().to_string(); by_top.entry(top).or_default().push(r); } } if by_top.is_empty() && top_of(&cwd).is_none() && !cwd.join(crate::sessions::SESSION_MARK).is_file() { bail!("not in a git worktree"); } for (top, rel) in by_top { if subagent_worktree(&top) { continue; } let branch = crate::cli::branch_in(&top); let functions = changed_functions(&top, &rel); let repo = crate::cli::repo_in(&top); crate::client::post("/v1/editing", &json!({"owner": owner, "branch": branch, "files": rel, "functions": functions, "repo": repo}))?; } if no_notes { return Ok(0); } notes_cmd(owner, hook, false) } /// The files this worktree's branch changes against the warm branch, what is /// uncommitted, and the functions their hunks are in: what overlaps are /// measured on. Sent by the flush. pub fn send_work(top: &std::path::Path, owner: &str) { if subagent_worktree(top) { return; } let git = |args: &[&str]| std::process::Command::new("git").arg("-C").arg(top).args(args) .stderr(std::process::Stdio::null()).output().ok() .filter(|o| o.status.success()).map(|o| String::from_utf8_lossy(&o.stdout).to_string()); let Some(fork) = fork_point(top) else { return }; let mut files: BTreeSet = git(&["diff", "--name-only", &fork]).unwrap_or_default() .lines().map(str::to_string).collect(); files.extend(git(&["ls-files", "--others", "--exclude-standard"]).unwrap_or_default().lines().map(str::to_string)); let functions = changed_functions(top, &[]); let branch = crate::cli::branch_in(top); let repo = crate::cli::repo_in(top); let _ = crate::client::post("/v1/work", &json!({"owner": owner, "branch": branch, "files": files, "functions": functions, "repo": repo, "projects": folder_projects(top)})); } /// The projects of the session folder a project worktree `top` sits in (its /// own among them), by name; none for a checkout in no folder. fn folder_projects(top: &std::path::Path) -> Option> { let folder = top.parent().filter(|f| f.join(crate::sessions::SESSION_MARK).is_file())?; Some(crate::sessions::folder_worktrees(folder).into_iter() .map(|(r, _)| r.rsplit('/').next().unwrap_or(&r).to_string()).collect()) } /// A session folder with no project in it changes nothing: whatever it /// reported before goes. pub fn send_no_work(owner: &str) { let _ = crate::client::post("/v1/work", &json!({"owner": owner, "files": [], "projects": []})); } /// Where this worktree's branch left the warm branch. pub(crate) fn fork_point(top: &std::path::Path) -> Option { let warm = crate::client::setting("MIDAS_WARM_BRANCH").unwrap_or_else(|| "main".into()); std::process::Command::new("git").arg("-C").arg(top).args(["merge-base", "HEAD", &format!("origin/{warm}")]) .stderr(std::process::Stdio::null()).output().ok().filter(|o| o.status.success()) .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()).filter(|f| !f.is_empty()) } /// The functions the branch and the uncommitted edits change, per file (only /// `only`'s, unless empty), from `git diff -U0` against the fork point. Git's /// own language rules find the function a hunk is in — given through an /// attributes file of midas's own, below any the repository sets — so a /// method is named, not the `impl` around it. fn changed_functions(top: &std::path::Path, only: &[String]) -> Functions { let Some(fork) = fork_point(top) else { return Functions::new() }; let attrs = std::env::var("XDG_CACHE_HOME").map(PathBuf::from) .unwrap_or_else(|_| PathBuf::from(std::env::var("HOME").unwrap_or_else(|_| "/tmp".into())).join(".cache")) .join("midas").join("diff-attributes"); const DRIVERS: &str = "*.rs diff=rust\n*.py diff=python\n*.go diff=golang\n*.c diff=cpp\n*.h diff=cpp\n*.cc diff=cpp\n\ *.cpp diff=cpp\n*.hpp diff=cpp\n*.java diff=java\n*.kt diff=kotlin\n*.rb diff=ruby\n*.sh diff=bash\n\ *.md diff=markdown\n*.css diff=css\n*.html diff=html\n*.php diff=php\n"; if fs::read_to_string(&attrs).ok().as_deref() != Some(DRIVERS) { let _ = attrs.parent().map(fs::create_dir_all); let _ = fs::write(&attrs, DRIVERS); } let mut cmd = std::process::Command::new("git"); cmd.arg("-C").arg(top).arg("-c").arg(format!("core.attributesFile={}", attrs.display())) .args(["diff", "-U0", "--no-color", "--no-ext-diff", &fork, "--"]).args(only); let Some(out) = cmd.stderr(std::process::Stdio::null()).output().ok().filter(|o| o.status.success()) else { return Functions::new(); }; hunk_functions(&String::from_utf8_lossy(&out.stdout)) } /// Per file in a `git diff -U0`, the functions its hunk headers name (the /// text after the second `@@`), shortened, deduplicated, at most /// [`MAX_FUNCTIONS`] each. pub fn hunk_functions(diff: &str) -> Functions { let mut out = Functions::new(); let (mut old, mut file): (Option, Option) = (None, None); for line in diff.lines() { if line.starts_with("diff --git ") { (old, file) = (None, None); } else if let Some(p) = line.strip_prefix("--- ") { old = p.strip_prefix("a/").map(str::to_string); } else if let Some(p) = line.strip_prefix("+++ ") { file = p.strip_prefix("b/").map(str::to_string).or_else(|| old.clone()); } else if let (Some(f), Some(rest)) = (&file, line.strip_prefix("@@ ")) { let Some((_, ctx)) = rest.split_once(" @@") else { continue }; let Some(name) = short_function(ctx) else { continue }; let names = out.entry(f.clone()).or_default(); if !names.contains(&name) && names.len() < MAX_FUNCTIONS { names.push(name); } } } out } /// A hunk header's context as a name: `pub(crate) fn report_work(owner: …` /// → `report_work`, `class Main extends MithrilComponent<…` → `Main`, `## 7. /// The web page` → `7. The web page`. The keyword is left out: a note lists /// up to eight a side per file, and `fn`, `class` and `### ` were a third of /// it. A line that names nothing (`import {` above a file's first hunk) is /// no name. fn short_function(ctx: &str) -> Option { let ctx = ctx.trim(); if let Some(heading) = ctx.strip_prefix('#') { let heading = heading.trim_start_matches('#').trim(); return (!heading.is_empty()).then(|| quote(heading, 40)); } let mut s = ctx; const QUALIFIERS: &[&str] = &["pub", "pub(crate)", "pub(super)", "async", "unsafe", "const", "extern", "export", "default", "static", "public", "private", "protected", "abstract", "final", "fn", "function", "class", "struct", "enum", "trait", "mod", "def", "interface", "type", "let", "var", "impl", "func", "module"]; const NO_NAME: &[&str] = &["import", "use", "from", "#include", "package", "require"]; if ctx.split_whitespace().next().is_some_and(|w| NO_NAME.contains(&w.trim_end_matches(['{', '(', ';']))) { return None; } loop { let Some((first, rest)) = s.split_once(char::is_whitespace) else { break }; if QUALIFIERS.contains(&first) { s = rest.trim_start(); } else { break; } } // `impl Foo for Bar`: the generics go with the keyword. if let Some(rest) = s.strip_prefix("impl<").and_then(|r| r.split_once('>')) { s = rest.1.trim_start(); } let end = s.find(['(', '{', '<']).unwrap_or(s.len()); let s = [" where ", " extends ", " implements "].iter().fold(&s[..end], |s, w| s.split(w).next().unwrap_or("")); let s = s.trim().trim_end_matches(['=', ':', ' ']).trim(); (!s.is_empty()).then(|| quote(s, 60)) } /// `midas say`: a note to a session or a role, or with `--re` an answer to a /// note's sender. Says what became of it: waiting, sent on to an idle hosted /// session as a message, or waiting for a Remote Control session that looks /// idle (with how to wake it). pub fn say_cmd(owner: &str, words: &[String], re: Option<&str>) -> Result { let (to, text) = match re { Some(_) => (String::new(), words.join(" ")), None if words.len() >= 2 => (words[0].clone(), words[1..].join(" ")), None => bail!("say who to and what: midas say \"…\" (`midas who` lists sessions), or midas say --re \"…\""), }; let v = crate::client::post("/v1/say", &json!({"owner": owner, "to": to, "text": text, "re": re}))?; let Some(sent) = v["notes"].as_array() else { // A hub from before notes had ids. let got: Vec<&str> = v["to"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); eprintln!("left for {}; they get it with their next prompt or tool call", got.join(", ")); return Ok(0); }; for s in sent { let (to, id) = (s["to"].as_str().unwrap_or("?"), s["id"].as_str().unwrap_or("?")); if s["woken"] == true { eprintln!("{id} → {to}: it was idle, so it was sent to it as a message too, which wakes it"); } else if let Some(since) = s["idle_since"].as_i64() { eprintln!("{id} → {to}. {to} is idle since {}; it reads this at its next prompt. To wake it now, use the \ remote-session send_message tool with session_id {}.", clock(since), s["session"].as_str().unwrap_or("?")); } else { eprintln!("{id} → {to}; they get it with their next prompt or tool call (`midas notes --sent` shows when it is read)"); } } Ok(0) } /// `midas who`: every session seen lately, from the hub's names — what it is /// called, its branch, the node it holds or waits for and what it said it is /// doing there, how many files it changes and whose it shares, its unread /// notes, and when it was last seen. This session's row is marked. pub fn who_cmd(owner: &str, as_json: bool, all: bool) -> Result { let names = crate::client::get("/v1/names")?; let t = now(); let mut rows: Vec = names.as_object().into_iter().flatten().filter_map(|(o, n)| { let notes = n["notes"].as_u64().unwrap_or(0) + names[format!("gate-{o}")]["notes"].as_u64().unwrap_or(0); let active = n["node"].is_string() || n["waiting_for"].is_string(); let recent = n["last"].as_i64().is_some_and(|l| t - l < 86400) && n["ended"].is_null(); let gate = o.starts_with("gate-"); let keep = o == owner || active || (!gate && (all || recent || notes > 0)); keep.then(|| json!({ "owner": o, "you": o == owner, "label": n["label"], "branch": n["branch"], "link": n["link"], "node": n["node"], "intent": n["intent"], "waiting_for": n["waiting_for"], "files": n["files"].as_u64().unwrap_or(0), "overlaps": n["overlaps"].as_array().cloned().unwrap_or_default(), "notes": if gate { n["notes"].as_u64().unwrap_or(0) } else { notes }, "last": n["last"], "seen": n["seen"], "ended": n["ended"], })) }).collect(); rows.sort_by_key(|r| (r["you"] != true, std::cmp::Reverse(r["last"].as_i64().unwrap_or(0)))); if as_json { println!("{}", serde_json::to_string_pretty(&rows)?); return Ok(0); } if rows.is_empty() { println!("no sessions seen in the last day (--all for the last month)"); } for r in &rows { let you = if r["you"] == true { "* " } else { " " }; let label = r["label"].as_str().map(|l| format!(" \"{}\"", quote(l, 60))).unwrap_or_default(); let branch = r["branch"].as_str().map(|b| format!(" branch {b}")).unwrap_or_default(); println!("{you}{}{}{label}{branch}", r["owner"].as_str().unwrap_or("?"), if r["you"] == true { " (you)" } else { "" }); let mut parts = Vec::new(); if let Some(n) = r["node"].as_str() { parts.push(format!("holds {n}{}", r["intent"].as_str().map(|i| format!(" (\"{}\")", quote(i, 50))).unwrap_or_default())); } if let Some(w) = r["waiting_for"].as_str() { parts.push(format!("waits for {w}")); } if let Some(f) = r["files"].as_u64().filter(|f| *f > 0) { parts.push(format!("{f} file{} changed", if f == 1 { "" } else { "s" })); } for o in r["overlaps"].as_array().into_iter().flatten() { let files: Vec<&str> = o["files"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); let more = if files.len() > 3 { format!(" +{}", files.len() - 3) } else { String::new() }; parts.push(format!("shares {} with {}", files.iter().take(3).cloned().collect::>().join(", ") + &more, o["with"].as_str().unwrap_or("?"))); } if let Some(n) = r["notes"].as_u64().filter(|n| *n > 0) { parts.push(format!("{n} unread note{}", if n == 1 { "" } else { "s" })); } match (r["ended"].as_i64(), r["last"].as_i64()) { (Some(e), _) => parts.push(format!("ended {}", crate::cli::ago(e))), (None, Some(l)) => parts.push(format!("seen {}", crate::cli::ago(l))), _ => {} } if !parts.is_empty() { println!(" {}", parts.join(" · ")); } } Ok(0) } /// The words a starting session is given with its open ends (`/v1/todos/take` /// returns them, so a hook needs nothing but curl to pass them on). pub fn todo_context(todos: &[Value]) -> Option { if todos.is_empty() { return None; } let items: Vec = todos.iter().map(|t| format!( "- [{}] (left by {}) {}", t["id"].as_str().unwrap_or("?"), t["by"].as_str().unwrap_or("?"), t["text"].as_str().unwrap_or(""), )).collect(); Some(format!( "**Open ends left for the next session on this machine — do these first.** An earlier session \ could not finish them where it ran. Before starting on the person's request, do each (ask the \ person if one needs their decision), tell them in a line what you did, and mark it done with \ `midas todo done ` (or `--note \"…\"` for what came of it). If one no longer applies, say so \ and mark it done.\n\n{}", items.join("\n"))) } /// `midas todo take`: this session's open ends; with `--hook `, as a /// hook's added context (nothing when there are none). pub fn todo_take_cmd(owner: &str, hook: Option<&str>) -> Result { let v = crate::client::post("/v1/todos/take", &json!({"owner": owner}))?; let ctx = v["context"].as_str(); match (hook, ctx) { (Some(event), Some(c)) => println!("{}", json!({"hookSpecificOutput": {"hookEventName": event, "additionalContext": c}})), (Some(_), None) => {} (None, Some(c)) => println!("{c}"), (None, None) => println!("no open ends for this session"), } Ok(0) }