//! A meeting's summary and actions made on this Mac by a local model (lane //! meetings-summaries; owner's decision, 17 Nov 2026: no cloud model is //! called by Cotton — a person who wants one asks their own assistant over //! Cotton MCP, which writes the same columns). //! //! The model is an open-weight GGUF from the summariser catalogue //! (`kits/shell/meetings/models.json`), fetched by name like the voice //! models, run by llama.cpp's `llama-server` (Metal) on a free local port for //! the length of one run; nothing leaves the Mac. The RULES — the parts, the //! questions, what of the model's answer is kept — are cotton-rules' //! ([`cotton_rules::meetings_summary`]); this file only asks and lands. //! //! [`drain`] walks the person's `meetings_meeting` rows that are ready and //! not summarised (or asked again), reads their lines and speakers, and //! writes `summary`, `actions` (one to do a line), `summarised_by`, //! `summarised_at` on the meeting and one `meetings_action` row per action; //! an action a person already added to their todos is kept as it was. use std::path::{Path, PathBuf}; use std::process::{Child, Command, Stdio}; use std::time::{Duration, Instant}; use chrono::NaiveDate; use cotton_rules::meetings::Line; use cotton_rules::meetings_summary::{self as rules, Action, Heard, Voice}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use crate::object::{Act, ObjectClient}; pub const ACTION: &str = "meetings_action"; /// The summariser catalogue, built into the binary as the core's kits are. pub const CATALOGUE: &str = include_str!("../../cotton-core/kits/shell/meetings/models.json"); #[derive(Debug, Clone, Deserialize)] pub struct Catalogue { pub default: String, pub models: std::collections::BTreeMap, } #[derive(Debug, Clone, Deserialize)] pub struct Entry { pub file: CatalogueFile, #[serde(default)] pub context: Option, #[serde(default)] pub think: Option, } #[derive(Debug, Clone, Deserialize)] pub struct CatalogueFile { pub name: String, pub bytes: u64, pub sha256: String, /// Where the coordinator put it; null until uploaded. #[serde(default)] pub url: Option, /// The publisher's own copy, fetched while `url` is null. #[serde(default)] pub source: Option, } pub fn catalogue() -> Catalogue { serde_json::from_str(CATALOGUE).expect("the summariser catalogue reads") } /// Where this Mac keeps models: `$MEETINGS_MODELS`, else `$VOICE_MODELS`, /// else `~/.cache/cotton-voice/models` (the voice models' own folder). pub fn models_dir() -> PathBuf { std::env::var_os("MEETINGS_MODELS") .or_else(|| std::env::var_os("VOICE_MODELS")) .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(std::env::var_os("HOME").unwrap_or_default()).join(".cache/cotton-voice/models")) } /// The model's file on this Mac when it has been fetched (right size). pub fn fetched(id: &str) -> Option { let entry = catalogue().models.get(id)?.clone(); let path = models_dir().join(id).join(&entry.file.name); let len = std::fs::metadata(&path).ok()?.len(); (len == entry.file.bytes).then_some(path) } /// Fetch a catalogue model by name into [`models_dir`], checked by sha256. pub fn fetch(id: &str) -> Result { use sha2::Digest; use std::io::{Read, Write}; let entry = catalogue().models.get(id).cloned().ok_or_else(|| format!("no model {id} in the summariser catalogue"))?; if let Some(path) = fetched(id) { return Ok(path); } let url = entry.file.url.clone().or(entry.file.source.clone()).ok_or_else(|| format!("{id} has nowhere to be fetched from yet"))?; let dir = models_dir().join(id); std::fs::create_dir_all(&dir).map_err(|e| e.to_string())?; let part = dir.join(format!("{}.part", entry.file.name)); let client = reqwest::blocking::Client::builder().timeout(None).build().map_err(|e| e.to_string())?; let mut body = client.get(&url).send().and_then(|r| r.error_for_status()).map_err(|e| format!("{id}: {e}"))?; let mut out = std::fs::File::create(&part).map_err(|e| e.to_string())?; let mut hash = sha2::Sha256::new(); let mut buf = vec![0u8; 1 << 20]; loop { let n = body.read(&mut buf).map_err(|e| e.to_string())?; if n == 0 { break; } hash.update(&buf[..n]); out.write_all(&buf[..n]).map_err(|e| e.to_string())?; } let got = hex::encode(hash.finalize()); if got != entry.file.sha256 { let _ = std::fs::remove_file(&part); return Err(format!("{id}: the file fetched is not the catalogue's (sha256 {got})")); } let path = dir.join(&entry.file.name); std::fs::rename(&part, &path).map_err(|e| e.to_string())?; Ok(path) } /// A model to ask: a running llama-server, and the name it signs with. pub struct Model { pub url: String, /// ``, signed `mac:llama:` in `summarised_by`. pub id: String, pub think: bool, pub part_chars: usize, server: Option, client: reqwest::blocking::Client, } impl Drop for Model { fn drop(&mut self) { if let Some(mut child) = self.server.take() { let _ = child.kill(); let _ = child.wait(); } } } fn client() -> reqwest::blocking::Client { reqwest::blocking::Client::builder().timeout(Duration::from_secs(900)).build().expect("an http client") } impl Model { /// A llama-server someone else runs (the bench). pub fn at(url: &str, id: &str) -> Model { let think = catalogue().models.get(id).and_then(|e| e.think).unwrap_or(false); Model { url: url.trim_end_matches('/').into(), id: id.into(), think, part_chars: rules::PART_CHARS, server: None, client: client() } } /// Start llama-server on this Mac on the fetched model, for this run. /// `$LLAMA_SERVER` names the binary, else `llama-server` on PATH, else /// Homebrew's. pub fn start(id: &str) -> Result { let entry = catalogue().models.get(id).cloned().ok_or_else(|| format!("no model {id} in the summariser catalogue"))?; let path = fetched(id).ok_or("model_missing")?; let bin = std::env::var_os("LLAMA_SERVER").map(PathBuf::from).unwrap_or_else(|| { let brew = PathBuf::from("/opt/homebrew/bin/llama-server"); if brew.exists() { brew } else { PathBuf::from("llama-server") } }); let port = std::net::TcpListener::bind("127.0.0.1:0").and_then(|l| l.local_addr()).map_err(|e| e.to_string())?.port(); let ctx = entry.context.unwrap_or(16_384).to_string(); let child = Command::new(&bin) .args(["-m"]) .arg(&path) .args(["--host", "127.0.0.1", "--port", &port.to_string(), "-c", &ctx, "-ngl", "99", "-fa", "on", "--no-webui"]) .stdin(Stdio::null()) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .map_err(|e| format!("no_server: {} did not start ({e})", bin.display()))?; let mut model = Model { url: format!("http://127.0.0.1:{port}"), id: id.into(), think: entry.think.unwrap_or(false), part_chars: rules::PART_CHARS, server: Some(child), client: client() }; let began = Instant::now(); loop { if model.client.get(format!("{}/health", model.url)).send().is_ok_and(|r| r.status().is_success()) { return Ok(model); } if let Some(child) = model.server.as_mut() { if let Ok(Some(status)) = child.try_wait() { return Err(format!("the model's server stopped ({status})")); } } if began.elapsed() > Duration::from_secs(180) { return Err("the model's server did not come up in three minutes".into()); } std::thread::sleep(Duration::from_millis(300)); } } pub fn by(&self) -> String { format!("mac:llama:{}", self.id) } fn ask(&self, prompt: &str, schema: Value) -> Result { let body = json!({ "messages": [ { "role": "system", "content": rules::SYSTEM }, { "role": "user", "content": prompt } ], "temperature": 0.2, "max_tokens": 2048, "response_format": { "type": "json_schema", "json_schema": { "name": "notes", "schema": schema } }, "chat_template_kwargs": { "enable_thinking": self.think }, }); let answer: Value = self.client.post(format!("{}/v1/chat/completions", self.url)).json(&body).send().and_then(|r| r.error_for_status()).and_then(|r| r.json()).map_err(|e| format!("the model did not answer: {e}"))?; let said = answer["choices"][0]["message"]["content"].as_str().unwrap_or_default(); let json = said.rsplit("").next().unwrap_or(said).trim(); serde_json::from_str(json).map_err(|e| format!("the model's answer did not read: {e}")) } } /// What one summary took. #[derive(Debug, Clone, Default, Serialize)] pub struct Took { pub parts: usize, pub seconds: f64, pub lines: usize, } /// A meeting's notes as made, before they land. #[derive(Debug, Clone, Serialize)] pub struct Made { pub by: String, pub summary: Vec, pub actions: Vec, pub summary_text: String, pub actions_text: String, pub took: Took, } /// Summarise one transcript: each part asked, the parts' points merged into /// one summary when there were several, the actions checked against the /// transcript and made one list. pub fn summarise(model: &Model, title: Option<&str>, voices: &[Voice], lines: &[Line], day: NaiveDate) -> Result { let started = Instant::now(); // A meeting landed before its language's script was set reads as written now. let written: Vec = lines.iter().map(|l| Line { text: cotton_rules::script::as_written(&l.text), ..l.clone() }).collect(); let lines = written.as_slice(); let parts = rules::parts(lines, voices, model.part_chars); let mut points: Vec> = Vec::new(); let mut actions: Vec = Vec::new(); for part in &parts { let heard: Heard = serde_json::from_value(model.ask(&rules::part_prompt(title, part, parts.len()), rules::part_schema())?).map_err(|e| e.to_string())?; points.push(heard.summary.clone()); actions.extend(rules::check(&heard.actions, lines, voices, day)); } let summary = match points.len() { 0 => Vec::new(), 1 => points.remove(0), _ => { let merged = model.ask(&rules::merge_prompt(title, &points), rules::merge_schema())?; merged["summary"].as_array().map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()).unwrap_or_else(|| points.concat()) } }; let actions = rules::one_list(actions); Ok(Made { by: model.by(), summary_text: rules::summary_text(&summary), actions_text: rules::actions_text(&actions, voices), summary, actions, took: Took { parts: parts.len(), seconds: started.elapsed().as_secs_f64(), lines: lines.len() }, }) } /// The meeting's own day, where it was held: the date of `started_at` in its /// own offset, and in the workspace's `zone` when it is written in UTC (UTC /// itself when the workspace names none). Never this Mac's zone: the Mac is /// somewhere, and the meeting is the workspace's (no_ambient_timezone). pub fn meeting_day(started_at: &str, zone: Option<&str>) -> Option { let at = chrono::DateTime::parse_from_rfc3339(started_at).ok()?; if at.offset().local_minus_utc() == 0 && started_at.ends_with('Z') { return Some(day_in(at.with_timezone(&chrono::Utc), zone)); } Some(at.date_naive()) } /// The date `at` falls on in `zone` (UTC when there is none or it is unknown). fn day_in(at: chrono::DateTime, zone: Option<&str>) -> NaiveDate { let offset = zone.map_or(0, |zone| cotton_core::rules::media::albums::zone_offset_seconds(zone, at.timestamp_millis())); (at + chrono::Duration::seconds(offset)).date_naive() } /// The workspace's zone (`cotton_news_settings.timezone`), when it names one. fn workspace_zone(object: &ObjectClient) -> Option { let rows = object.device_rows("cotton_news_settings")?.ok()?; rows.iter().map(|row| str_of(row, "timezone").trim()).find(|zone| !zone.is_empty()).map(str::to_string) } // ── the queue ─────────────────────────────────────────────────────────────── fn str_of<'a>(row: &'a Value, key: &str) -> &'a str { row["data"][key].as_str().unwrap_or_default() } /// The ready meetings with words that want a summary from the Mac: never /// summarised, or asked again since; not turned off. pub fn wanting(rows: &[Value]) -> Vec { let mut out: Vec = rows .iter() .filter(|r| str_of(r, "status") == "ready" && r["data"]["lines"].as_i64().unwrap_or(0) > 0 && str_of(r, "summarise_on") != "off") .filter(|r| { let at = str_of(r, "summarised_at"); at.is_empty() || str_of(r, "summary_asked_at") > at }) .cloned() .collect(); out.sort_by(|a, b| str_of(a, "started_at").cmp(str_of(b, "started_at"))); out } /// One meeting summarised, said for the run's summary. #[derive(Debug, Clone, Serialize)] pub struct Summarised { pub meeting: String, pub done: bool, pub why: Option, pub actions: usize, pub took: Option, } /// Summarise what wants it (at most `most`). With no model fetched, each /// such meeting is told why (`summary_why: model_missing`) and left. pub fn drain(object: &ObjectClient, model_id: &str, most: usize, each: &mut dyn FnMut(&Summarised)) -> Result, String> { let rows = object.device_rows(crate::meetings::MEETING).ok_or("this run holds no data key: sign this Mac in with seal-device")?.map_err(|e| e.to_string())?; let todo: Vec = wanting(&rows).into_iter().take(most).collect(); if todo.is_empty() { return Ok(Vec::new()); } let model = match Model::start(model_id) { Ok(m) => m, Err(why) => { let word = if why == "model_missing" { "model_missing" } else { "failed" }; eprintln!("meetings: summaries: {why}"); let mut out = Vec::new(); for row in &todo { let id = row["id"].as_str().unwrap_or_default().to_string(); if str_of(row, "summary_why") != word { let _ = object.act(Act::Update, crate::meetings::MEETING, &id, &json!({ "summary_why": word })); } let s = Summarised { meeting: id, done: false, why: Some(word.into()), actions: 0, took: None }; each(&s); out.push(s); } return Ok(out); } }; let mut out = Vec::new(); for row in todo { let s = one(object, &model, &row); each(&s); out.push(s); } Ok(out) } /// The meeting's speakers and lines from the object, in order. pub fn transcript_of(object: &ObjectClient, meeting: &str) -> Result<(Vec, Vec, Vec<(String, String)>), String> { let mine = |table: &str| -> Result, String> { let rows = object.device_rows(table).ok_or("no data key")?.map_err(|e| e.to_string())?; Ok(rows.into_iter().filter(|r| str_of(r, "meeting") == meeting).collect()) }; let speakers = mine(crate::meetings::SPEAKER)?; let mut lines = mine(crate::meetings::LINE)?; lines.sort_by_key(|l| (l["data"]["position"].as_i64().unwrap_or(0), l["data"]["start_ms"].as_i64().unwrap_or(0))); let ids: Vec<(String, String)> = speakers.iter().map(|s| (str_of(s, "label").to_string(), s["id"].as_str().unwrap_or_default().to_string())).collect(); let voices: Vec = speakers.iter().map(|s| Voice { label: str_of(s, "label").into(), name: Some(str_of(s, "name").to_string()).filter(|n| !n.trim().is_empty()) }).collect(); let label_of = |speaker: &str| ids.iter().find(|(_, id)| id == speaker).map(|(l, _)| l.clone()).unwrap_or_default(); let lines = lines .iter() .map(|l| Line { speaker: label_of(str_of(l, "speaker")), start_ms: l["data"]["start_ms"].as_i64().unwrap_or(0), end_ms: l["data"]["end_ms"].as_i64().unwrap_or(0), text: str_of(l, "text").into(), language: l["data"]["language"].as_str().map(str::to_string) }) .collect(); Ok((voices, lines, ids)) } fn one(object: &ObjectClient, model: &Model, row: &Value) -> Summarised { let id = row["id"].as_str().unwrap_or_default().to_string(); let failed = |why: &str| { let _ = object.act(Act::Update, crate::meetings::MEETING, &id, &json!({ "summary_why": "failed" })); Summarised { meeting: id.clone(), done: false, why: Some(why.into()), actions: 0, took: None } }; // The moment the words were read: what `summarised_at` says, so an ask again made while the model ran (a line // corrected, Summarise again) is later than it and the next pass takes it (STALE WRITES 2, 25 Nov 2026). let read_at = chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let (voices, lines, ids) = match transcript_of(object, &id) { Ok(t) => t, Err(why) => return failed(&why), }; let zone = workspace_zone(object); let day = meeting_day(str_of(row, "started_at"), zone.as_deref()).unwrap_or_else(|| day_in(chrono::Utc::now(), zone.as_deref())); let title = Some(str_of(row, "title")).filter(|t| !t.is_empty()); let made = match summarise(model, title, &voices, &lines, day) { Ok(m) => m, Err(why) => { eprintln!("meetings: {id}: summary: {why}"); return failed("failed"); } }; match land(object, &id, &made, &ids, &read_at) { Ok(()) => Summarised { meeting: id, done: true, why: None, actions: made.actions.len(), took: Some(made.took) }, Err(why) => { eprintln!("meetings: {id}: summary: {why}"); failed("failed") } } } /// The notes at the object: the old actions go except those a person added /// to their todos, the new ones come in order, and the meeting's columns are /// written last. pub fn land(object: &ObjectClient, meeting: &str, made: &Made, speaker_ids: &[(String, String)], read_at: &str) -> Result<(), String> { let e = |r: Result| r.map(|_| ()).map_err(|e| e.to_string()); let old: Vec = object.device_rows(ACTION).ok_or("no data key")?.map_err(|e| e.to_string())?.into_iter().filter(|r| str_of(r, "meeting") == meeting).collect(); let kept: Vec<&Value> = old.iter().filter(|r| !str_of(r, "todo").is_empty()).collect(); for gone in old.iter().filter(|r| str_of(r, "todo").is_empty()) { e(object.act(Act::Delete, ACTION, gone["id"].as_str().unwrap_or_default(), &json!({})))?; } let mut position = kept.len(); for a in &made.actions { let already = kept.iter().any(|k| { let was = Action { words: str_of(k, "words").into(), who: Some(str_of(k, "who").to_string()).filter(|w| !w.is_empty()), due: None, due_said: None, at_ms: None }; rules::same_task(&was, a) }); if already { continue; } position += 1; let speaker = a.who.as_deref().and_then(|w| speaker_ids.iter().find(|(l, _)| l == w)).map(|(_, id)| id.clone()); e(object.act( Act::Create, ACTION, &crate::meetings::new_id(), &json!({ "meeting": meeting, "position": position, "words": a.words, "who": a.who, "speaker": speaker, "due": a.due, "due_said": a.due_said, "at_ms": a.at_ms, "made_by": made.by }), ))?; } e(object.act( Act::Update, crate::meetings::MEETING, meeting, &json!({ "summary": made.summary_text, "actions": made.actions_text, "summarised_by": made.by, "summarised_at": read_at, "summary_why": null }), )) } /// A synthetic meeting (scripts/meetings/synthetic/transcript.py's JSON) put /// on the object as a ready, transcribed meeting, then summarised: the walk's /// way to a meeting with words on a Mac with no speech engine. Answers the /// meeting's id. pub fn land_synthetic(object: &ObjectClient, model: &Model, path: &Path) -> Result<(String, Summarised), String> { let v: Value = serde_json::from_slice(&std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?).map_err(|e| e.to_string())?; let lines: Vec = serde_json::from_value(v["lines"].clone()).map_err(|e| e.to_string())?; let mut speakers: Vec = Vec::new(); for l in &lines { if !speakers.iter().any(|s| s.label == l.speaker) { speakers.push(cotton_rules::meetings::Speaker { label: l.speaker.clone() }); } } let mut languages: Vec = Vec::new(); for l in &lines { if let Some(lang) = &l.language { if !languages.contains(lang) { languages.push(lang.clone()); } } } let transcript = cotton_rules::meetings::Transcript { by: "synthetic".into(), languages, speakers, lines }; let id = crate::meetings::new_id(); let meeting = &v["meeting"]; let e = |r: Result| r.map(|_| ()).map_err(|e| e.to_string()); e(object.act( Act::Create, crate::meetings::MEETING, &id, &json!({ "take": id, "kind": "meeting", "status": "transcribing", "title": meeting["title"], "started_at": meeting["started_at"], "duration_ms": meeting["duration_ms"], "transcribe_on": "mac", "summarise_on": "mac", "recorded_on": "a synthetic meeting" }), ))?; crate::meetings::land(object, &id, &transcript)?; // The speakers' names, as a person would have given them. let names: Vec<(String, String)> = v["speakers"].as_array().cloned().unwrap_or_default().iter().filter_map(|s| Some((s["label"].as_str()?.to_string(), s["name"].as_str()?.to_string()))).collect(); let (_, _, ids) = transcript_of(object, &id)?; for (label, name) in names { if let Some((_, speaker)) = ids.iter().find(|(l, _)| *l == label) { e(object.act(Act::Update, crate::meetings::SPEAKER, speaker, &json!({ "name": name })))?; } } let row = object.device_rows(crate::meetings::MEETING).ok_or("no data key")?.map_err(|e| e.to_string())?.into_iter().find(|r| r["id"].as_str() == Some(&id)).ok_or("the meeting did not land")?; let done = one(object, model, &row); Ok((id, done)) } /// A synthetic meeting file (scripts/meetings/synthetic/transcript.py's JSON). pub fn read_file(path: &Path) -> Result<(Option, Vec, Vec, NaiveDate), String> { let v: Value = serde_json::from_slice(&std::fs::read(path).map_err(|e| format!("{}: {e}", path.display()))?).map_err(|e| e.to_string())?; let voices: Vec = serde_json::from_value(v["speakers"].clone()).map_err(|e| e.to_string())?; let lines: Vec = serde_json::from_value(v["lines"].clone()).map_err(|e| e.to_string())?; let day = meeting_day(v["meeting"]["started_at"].as_str().unwrap_or_default(), None).ok_or("the meeting has no started_at")?; Ok((v["meeting"]["title"].as_str().map(str::to_string), voices, lines, day)) } #[cfg(test)] #[path = "summarise_tests.rs"] mod tests;