//! The research tree (docs/mockups/research-tree): a layer above sessions //! that thinks of them, as Civilization's tech tree does. //! //! At the far end stand **goals**, the person's own sentences, from abstract //! ("an open metaverse for communities") to concrete. Before them stand //! **techs**: capabilities someone would notice, each with the techs it //! **needs** first. A **scout** fills the tree in, one **round** at a time, each //! round one named **move** on one goal: **Map** (what on the way is built //! already) and **Harvest** (what earlier sessions left open). It runs on a //! runner, as template reviews do, with Claude Code read-only on each of the //! goal's projects' main, and changes the tree, never the code. //! //! What it finds and is not built is in the **fog** until a second, different //! move finds it too or the person confirms it; what it finds that is not a //! capability yet is an **insight**, and so is an idea the person writes in. //! Every tech has an icon of its own, drawn by the scout as SVG in one style //! and kept only after `icon` has rebuilt it from geometry alone: it is markup //! the page draws. //! //! The tree, Map, Harvest and Group (themes proposed as goals under a goal) are built, //! research by hand (a session started from a tech), and automatic research along a direction the person //! chooses (`tick`). Cost comes after. //! //! All of it is one file beside the sessions, `hosted/tree.json`. use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::sync::Mutex; use anyhow::{bail, Context, Result}; use serde_json::{json, Value}; use crate::registry::now; const NAME_MAX: usize = 80; const TEXT_MAX: usize = 2000; const NEVER_MAX: usize = 20; /// Kept at most: the tree stays a map, never a pile. const TECHS_KEPT: usize = 250; const INSIGHTS_KEPT: usize = 300; const ROUNDS_KEPT: usize = 60; const EVIDENCE_KEPT: usize = 8; /// What one round may add, so a talkative one cannot flood the tree. const ROUND_TECHS: usize = 15; const ROUND_INSIGHTS: usize = 8; /// An insight nothing confirmed for this long fades from the list. pub const FADE_S: i64 = 30 * 86400; /// A round a runner took and never answered is asked again after this long. const ROUND_RETRY_S: i64 = 3600; /// How long one project's round may take. const ROUND_RUN_S: u64 = 900; /// Projects one round reads, at most. const ROUND_REPOS: usize = 3; /// The finished sessions Harvest reads, and how much of each. const HARVEST_SESSIONS: usize = 30; const HARVEST_WORDS: usize = 700; const HARVEST_BUDGET: usize = 24 * 1024; /// The model that scouts, unless `MIDAS_AUTOPILOT_MODEL` names another. const MODEL: &str = "opus"; /// The moves this step has. const MOVES: [&str; 4] = ["map", "harvest", "group", "sketch"]; /// A tech's description, as `tech_edit` changes it. const TECH_TEXT: [&str; 7] = ["name", "what", "who", "differently", "exists", "done", "size"]; /// A remark on a mockup, and how many wait on one tech for its next drawing. const REMARK_MAX: usize = 500; const REMARKS_KEPT: usize = 12; /// How many looks may wait behind the one going on a goal. const LOOKS_WAITING: usize = 3; /// What a round shows of the scout at work: its last steps, and how often the runner says so. const LIVE_LINES: usize = 12; const LIVE_EVERY_S: u64 = 4; const LIVE_TEXT: usize = 300; /// What the scout says its mockup shows, for a voice talking it over. const SHOWS_MAX: usize = 1200; /// A Sketch round over the whole goal draws at most this many mockups: each is a few kilobytes of answer. const SKETCH_TECHS: usize = 6; /// A look sorts a goal into themes only once it has this many techs: fewer need no sorting. const GROUP_FROM: usize = 8; /// At most this many themes the scout proposes for one goal. const PROPOSALS_KEPT: usize = 8; /// A direction's limits unless said: one research at a time, at most four started a day. const DIRECTION_AT_ONCE: u64 = 1; const DIRECTION_PER_DAY: u64 = 4; /// Researches in a row that land nothing before a direction pauses, as a template's schedule does. const DIRECTION_PAUSE_AFTER: usize = 2; /// The scout is sent along the direction after this many landings since it last looked (0: only when the way runs out). const DIRECTION_SCOUT_EVERY: u64 = 3; /// At most this many looks the direction asks for itself in a day, however often the way runs out. const DIRECTION_SCOUTS_PER_DAY: usize = 2; /// At most this many directions go at once, and this many are kept, stopped ones included. const DIRECTIONS_LIVE: usize = 8; const DIRECTIONS_KEPT: usize = 20; /// What every direction together may start unless the person says: at once, a day, and at once in one project. const BUDGET_AT_ONCE: u64 = 3; const BUDGET_PER_DAY: u64 = 10; const BUDGET_PER_PROJECT: u64 = 1; /// A direction's runs kept, newest last. const DIRECTION_RUNS_KEPT: usize = 40; /// The researches a tech keeps, newest last. const RESEARCHES_KEPT: usize = 12; /// The themes under a goal that have a colour of their own on the tree page (tree.ts `THEMES`). const THEMES: usize = 5; /// A research session's brief is at most this long. const BRIEF_MAX: usize = 8000; static LOCK: Mutex<()> = Mutex::new(()); /// One round at a time on a runner: two goals on one project would check out /// its `ask-` worktree under each other. static SCOUTING: Mutex<()> = Mutex::new(()); fn path() -> PathBuf { crate::registry::root().join("hosted").join("tree.json") } fn load() -> Value { migrate(crate::store::read::(&path()).filter(|v| v["goals"].is_array()).unwrap_or_else(|| { json!({"seq": 0, "goals": [], "techs": [], "insights": [], "rounds": []}) })) } /// The one `direction` a tree had before there could be several becomes the first of `directions`, with /// the id `d0`; the next write keeps it so. fn migrate(mut v: Value) -> Value { if !v["directions"].is_array() { let old = v["direction"].take(); v["directions"] = json!([]); if old.is_object() { let mut d = old; d["id"] = json!("d0"); v["directions"].as_array_mut().expect("an array").push(d); } } if let Some(o) = v.as_object_mut() { o.remove("direction"); } v } /// Project `from` renamed to `to`, or deleted (`None`), in the goals and rounds that name it (hosted.rs). pub(crate) fn repo_renamed(from: &str, to: Option<&str>) -> Result<()> { if !path().exists() { return Ok(()); } change(|v| { crate::hosted::rename_in(v, from, to); Ok(()) }) } fn save(v: &Value) -> Result<()> { let p = path(); if let Some(dir) = p.parent() { std::fs::create_dir_all(dir)?; } crate::store::write_atomic(&p, serde_json::to_string_pretty(v)?.as_bytes(), crate::store::PUBLIC)?; crate::ws::nudge(); Ok(()) } /// Change the file under the lock: read, `f`, written when `f` succeeds. fn change(f: impl FnOnce(&mut Value) -> Result) -> Result { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); let mut v = load(); let r = f(&mut v)?; save(&v)?; Ok(r) } fn next_id(v: &mut Value, prefix: &str) -> String { let n = v["seq"].as_u64().unwrap_or(0) + 1; v["seq"] = json!(n); format!("{prefix}{n}") } fn find<'a>(list: &'a mut Value, id: &str) -> Result<&'a mut Value> { list.as_array_mut().into_iter().flatten().find(|t| t["id"] == id).with_context(|| format!("no {id}")) } fn text(v: &Value, k: &str, max: usize) -> String { crate::util::short(v[k].as_str().unwrap_or("").trim(), max) } fn strings(v: &Value, max_items: usize, max_len: usize) -> Vec { v.as_array().into_iter().flatten().filter_map(|s| s.as_str()).map(|s| crate::util::short(s.trim(), max_len)) .filter(|s| !s.is_empty()).take(max_items).collect() } /// A tech's name as the tree matches it: two rounds naming one capability /// "Invite by link" and "invite-by-link" find the same tech. pub fn key(name: &str) -> String { name.to_lowercase().split(|c: char| !c.is_alphanumeric()).filter(|w| !w.is_empty()).collect::>().join(" ") } /// Where a tech stands: `built`, `available` (its needs are built), `locked` /// (some are not), `fog` (only one move has found it, and the person has not /// confirmed it), or `dropped` (the person said not this). pub fn state_of(t: &Value, techs: &[Value]) -> &'static str { if t["dropped"].is_object() { return "dropped"; } if t["built"] == true { return "built"; } let moves = t["moves"].as_array().map(Vec::len).unwrap_or(0); if t["by"] == "scout" && moves < 2 && t["confirmed_by"].is_null() { // A guess nobody acted on and no look found again in a month fades, as a note does: nobody has to say // "not this" to it. A look that finds it again brings it back (`seen_at`). return if guess_faded(t) { "dropped" } else { "fog" }; } let built = |id: &Value| techs.iter().any(|x| &x["id"] == id && x["built"] == true); if t["needs"].as_array().into_iter().flatten().all(built) { "available" } else { "locked" } } /// Whether a guess faded: no look found it, nobody kept or started it, for `FADE_S`. fn guess_faded(t: &Value) -> bool { t["seen_at"].as_i64().or(t["at"].as_i64()).is_some_and(|seen| seen + FADE_S < now()) } /// Everything, for the page: each tech with its state, each insight with /// whether it faded. pub fn all() -> Value { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); all_unlocked(load()) } /// Whether a session researching a tech is still at it: not finished, stopped or failed. fn researching(t: &Value) -> bool { let Some(sid) = t["research"]["session"].as_str() else { return false }; crate::sessions::meta(sid).is_ok_and(|m| m["finished"].is_null() && !matches!(m["status"].as_str(), Some("stopped" | "failed"))) } /// `all` on a tree already read, under the lock. fn all_unlocked(mut v: Value) -> Value { let techs = v["techs"].as_array().cloned().unwrap_or_default(); let runs = all_runs(&v); let costs = v["costs"].take(); for t in v["techs"].as_array_mut().into_iter().flatten() { let s = state_of(t, &techs); t["state"] = json!(if matches!(s, "available" | "locked") && researching(t) { "researching" } else { s }); t["faded"] = json!(s == "dropped" && !t["dropped"].is_object()); t["sessions"] = json!(sessions_of(t, &runs, &costs)); t["photographing"] = json!(photographing(t)); } // Each direction going with what it starts next and in which project; the budget, with what it holds now. let nexts: Vec<(usize, Value)> = live(&v).into_iter().map(|i| (i, next_of(&v, i))).collect(); for (i, n) in nexts { v["directions"][i]["next"] = n; } let b = budget_of(&v); let t0 = now(); v["budget"] = json!({"at_once": b.at_once, "per_day": b.per_day, "per_project": b.per_project, "going": runs.iter().filter(|r| r["outcome"].is_null()).count(), "today": runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) > t0 - 86400).count(), "week_cost": (runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) > t0 - 7 * 86400).filter_map(|r| r["cost"].as_f64()).sum::() * 100.0).round() / 100.0}); if !v["proposals"].is_array() { v["proposals"] = json!([]); } let t0 = now(); for i in v["insights"].as_array_mut().into_iter().flatten() { let seen = i["seen_at"].as_i64().or(i["at"].as_i64()).unwrap_or(0); i["faded"] = json!(i["dropped"].is_object() || seen + FADE_S < t0); } v["moves"] = json!(MOVES); v } /// The projects a tech lands in, in order, as the scout or the person said: only the goal's own projects, each /// once, and only when there are two or more (one is the tech's own project, as before). fn lands_in(repos: &[String], said: &Value) -> Vec { let mut out: Vec = Vec::new(); for r in strings(said, 6, 200) { // The scout may name a project by its short name (`mithril` for `jeroen/mithril`). let full = repos.iter().find(|x| **x == r || x.rsplit('/').next() == Some(r.as_str())).cloned(); if let Some(full) = full.filter(|f| !out.contains(f)) { out.push(full); } } if out.len() > 1 { out } else { Vec::new() } } /// The projects asked for, each one of the workspace's. fn repos_ok(v: &Value) -> Result> { let known: Vec = crate::sessions::projects().as_array().into_iter().flatten() .filter_map(|p| p["repo"].as_str().map(str::to_string)).collect(); let repos: Vec = strings(v, 10, 200); for r in &repos { if !known.contains(r) { bail!("{r} is not one of the workspace's projects"); } } Ok(repos) } /// Whether `parent` stands above `id` already: a goal may not be its own ancestor. fn would_loop(goals: &Value, id: &str, parent: &str) -> bool { let mut at = parent.to_string(); for _ in 0..64 { if at == id { return true; } match goals.as_array().into_iter().flatten().find(|g| g["id"] == at.as_str()).and_then(|g| g["parent"].as_str()) { Some(p) => at = p.to_string(), None => return false, } } true } /// What the page asks (`POST /v1/hosted/tree`), by `op`; the whole tree after. pub fn op(body: &Value, by: &str) -> Result { let id = body["id"].as_str().unwrap_or("").to_string(); match body["op"].as_str().unwrap_or("") { "goal_save" => change(|v| { let name = text(body, "name", NAME_MAX); if name.is_empty() { bail!("a goal has a name"); } let parent = body["parent"].as_str().filter(|p| !p.is_empty()).map(str::to_string); if let Some(p) = &parent { if !v["goals"].as_array().into_iter().flatten().any(|g| g["id"] == p.as_str()) { bail!("no goal {p}"); } if !id.is_empty() && would_loop(&v["goals"], &id, p) { bail!("a goal cannot stand under itself"); } } let fields = json!({ "name": name, "statement": text(body, "statement", TEXT_MAX), "who": text(body, "who", TEXT_MAX), "signs": text(body, "signs", TEXT_MAX), "never": strings(&body["never"], NEVER_MAX, 300), "parent": parent, "repos": repos_ok(&body["repos"])?, }); let gid = if id.is_empty() { let gid = next_id(v, "g"); let mut g = fields; g["id"] = json!(gid); g["by"] = json!(by); g["at"] = json!(now()); v["goals"].as_array_mut().context("goals")?.push(g); gid } else { let g = find(&mut v["goals"], &id)?; for (k, x) in fields.as_object().into_iter().flatten() { g[k] = x.clone(); } g["changed_by"] = json!(by); g["changed_at"] = json!(now()); id.clone() }; v["last_goal"] = json!(gid); Ok(()) })?, "goal_delete" => change(|v| { if v["goals"].as_array().into_iter().flatten().any(|g| g["parent"] == id.as_str()) { bail!("move or delete the goals under it first"); } v["goals"].as_array_mut().context("goals")?.retain(|g| g["id"] != id.as_str()); for t in v["techs"].as_array_mut().into_iter().flatten() { if let Some(gs) = t["goals"].as_array_mut() { gs.retain(|g| g != id.as_str()); } } // A tech that led only to it, and that nobody built, goes with it. v["techs"].as_array_mut().context("techs")?.retain(|t| t["built"] == true || t["goals"].as_array().is_some_and(|g| !g.is_empty())); v["insights"].as_array_mut().context("insights")?.retain(|i| i["goal"] != id.as_str()); Ok(()) })?, // The person's own idea, in a line: an insight on the goal, or on one of its techs. "idea" => change(|v| { let goal = body["goal"].as_str().unwrap_or(""); if !v["goals"].as_array().into_iter().flatten().any(|g| g["id"] == goal) { bail!("which goal is it about?"); } let t = text(body, "text", TEXT_MAX); if t.is_empty() { bail!("say what the idea is"); } let iid = next_id(v, "i"); let about = body["about"].as_str().filter(|a| !a.is_empty()); push_insight(v, json!({"id": iid, "goal": goal, "text": t, "about": about, "evidence": [], "move": "person", "by": by, "at": now()})); Ok(()) })?, "insight_drop" => change(|v| { let i = find(&mut v["insights"], &id)?; i["dropped"] = json!({"by": by, "at": now(), "why": text(body, "why", 500)}); Ok(()) })?, // Out of the fog on the person's word. "tech_confirm" => change(|v| { let t = find(&mut v["techs"], &id)?; t["confirmed_by"] = json!(by); t["dropped"] = Value::Null; Ok(()) })?, // Not this, and why: kept, so a later round does not bring it back. "tech_drop" => change(|v| { let t = find(&mut v["techs"], &id)?; t["dropped"] = json!({"by": by, "at": now(), "why": text(body, "why", 500)}); Ok(()) })?, "tech_restore" => change(|v| { let t = find(&mut v["techs"], &id)?; t["dropped"] = Value::Null; // A guess that faded comes back seen now, or it would fade again at once. t["seen_at"] = json!(now()); Ok(()) })?, // Built, or not after all, on the person's word. "tech_built" => change(|v| { let t = find(&mut v["techs"], &id)?; let built = body["built"] != false; t["built"] = json!(built); t["built_at"] = if built { json!(now()) } else { Value::Null }; t["built_by"] = if built { json!(by) } else { Value::Null }; // Not built after all: a research that landed before this does not make it built again. if !built { t["unbuilt_at"] = json!(now()); } Ok(()) })?, // A tech's description, changed on the person's word (most often in a voice conversation): only the fields // given, each one's value before kept in `edited`, so the page can show what changed and undo it. "tech_edit" => change(|v| { let name = text(body, "name", NAME_MAX); if !name.is_empty() && v["techs"].as_array().into_iter().flatten().any(|t| t["id"] != id.as_str() && t["key"] == key(&name).as_str()) { bail!("another tech is called that already"); } let t = find(&mut v["techs"], &id)?; let mut changed = 0; for k in TECH_TEXT { if body[k].is_null() { continue; } let new = text(body, k, if k == "name" { NAME_MAX } else { TEXT_MAX }); if (k == "name" && new.is_empty()) || t[k].as_str().unwrap_or("") == new { continue; } if k == "size" && !matches!(new.as_str(), "S" | "M" | "L") { bail!("a size is S, M or L"); } t["edited"][k] = json!({"was": t[k].clone(), "by": by, "at": now()}); t[k] = json!(new); if k == "name" { t["key"] = json!(key(&new)); } changed += 1; } // The projects it lands in, in order: two or more of the workspace's, or none to make it one project's again. if body["lands_in"].is_array() { let said = repos_ok(&body["lands_in"])?; let spans = if said.len() > 1 { said } else { Vec::new() }; if t["lands_in"] != json!(spans) { t["edited"]["lands_in"] = json!({"was": t["lands_in"].clone(), "by": by, "at": now()}); t["lands_in"] = json!(spans); changed += 1; } } if changed == 0 { bail!("nothing to change: give a field with its new text"); } Ok(()) })?, // A remark on a tech's mockup, for the next time it is drawn; dropped by id, or by the drawing that handled it. "remark" => change(|v| { let said = text(body, "text", REMARK_MAX); if said.is_empty() { bail!("say what the remark is"); } let n = v["remark_seq"].as_u64().unwrap_or(0) + 1; v["remark_seq"] = json!(n); let t = find(&mut v["techs"], &id)?; let mut list = t["remarks"].as_array().cloned().unwrap_or_default(); if list.len() >= REMARKS_KEPT { bail!("{REMARKS_KEPT} remarks wait already: have it drawn again first"); } list.push(json!({"id": format!("m{n}"), "text": said, "by": by, "at": now()})); t["remarks"] = json!(list); Ok(()) })?, "remark_drop" => change(|v| { let rid = body["remark"].as_str().unwrap_or(""); let t = find(&mut v["techs"], &id)?; let list = t["remarks"].as_array_mut().with_context(|| format!("no remark {rid}"))?; let before = list.len(); list.retain(|m| m["id"] != rid); if list.len() == before { bail!("no remark {rid}"); } Ok(()) })?, // A theme the scout proposed, kept: a goal under its goal, with its techs leading to it too. "proposal_accept" => change(|v| { let p = v["proposals"].as_array().into_iter().flatten().find(|p| p["id"] == id.as_str()).cloned().with_context(|| format!("no {id}"))?; let parent = v["goals"].as_array().into_iter().flatten().find(|g| g["id"] == p["goal"]).cloned().context("its goal is gone")?; let name = Some(text(body, "name", NAME_MAX)).filter(|n| !n.is_empty()).unwrap_or_else(|| text(&p, "name", NAME_MAX)); let gid = next_id(v, "g"); v["goals"].as_array_mut().context("goals")?.push(json!({ "id": gid, "name": name, "statement": p["statement"], "who": "", "signs": "", "never": [], "parent": parent["id"], "repos": parent["repos"], "by": by, "at": now(), "proposal": id, })); let techs = strings(&p["techs"], TECHS_KEPT, 20); for t in v["techs"].as_array_mut().into_iter().flatten() { if techs.iter().any(|x| t["id"] == x.as_str()) { let mut gs = strings(&t["goals"], 20, 20); if !gs.contains(&gid) { gs.push(gid.clone()); } t["goals"] = json!(gs); } } v["proposals"].as_array_mut().context("proposals")?.retain(|p| p["id"] != id.as_str()); Ok(()) })?, "proposal_drop" => change(|v| { if let Some(l) = v["proposals"].as_array_mut() { l.retain(|p| p["id"] != id.as_str()); } Ok(()) })?, // A session researching a tech, its brief written from the tech: started outside the tree's lock, then noted on it. "research" => { let (brief, repo) = { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); research_brief(&all_unlocked(load()), &id)? }; let sid = crate::sessions::start(by, &brief, Some(&repo), None, None, None, None, &json!([]))?; change(|v| { mark_research(v, &id, &sid, by, false)?; Ok(()) })?; crate::events::emit("tree_research", json!({"actor": by, "tech": id, "session": sid})); } // A direction on the tree: a goal (a theme is one) or a far tech, the techs on the way to it // then researched one after another by `tick`, on autopilot, within its limits and the budget. // Several go at once; one to a target already headed for changes that one's limits instead. "direction_set" => change(|v| { let target = body["target"].as_str().unwrap_or(""); let name = v["goals"].as_array().into_iter().flatten().chain(v["techs"].as_array().into_iter().flatten()) .find(|x| x["id"] == target).and_then(|x| x["name"].as_str()).map(str::to_string).with_context(|| format!("no {target}"))?; if let Some(i) = live(v).into_iter().find(|&i| v["directions"][i]["target"] == target) { let d = &mut v["directions"][i]; set_limits(d, body); if d["paused"].is_string() { d["paused"] = Value::Null; d["resumed_at"] = json!(now()); } return Ok(()); } if live(v).len() >= DIRECTIONS_LIVE { bail!("{DIRECTIONS_LIVE} directions go already: stop one first"); } let id = next_id(v, "d"); let mut d = json!({"id": id, "target": target, "name": name, "by": by, "at": now(), "at_once": DIRECTION_AT_ONCE, "per_day": DIRECTION_PER_DAY, "scout": true, "scout_every": DIRECTION_SCOUT_EVERY, "paused": null, "reached": null, "resumed_at": now(), "runs": []}); set_limits(&mut d, body); let list = v["directions"].as_array_mut().context("directions")?; list.push(d); // Stopped ones beyond the cap go, the oldest first: their runs live on in their techs' researches. while list.len() > DIRECTIONS_KEPT { let Some(i) = list.iter().position(|d| d["cleared"].is_object()) else { break }; list.remove(i); } crate::events::emit("tree_direction", json!({"actor": by, "target": target, "direction": id})); Ok(()) })?, // A direction's limits changed, without starting it over: how many at once and a day, and whether the // scout is sent when the way runs out and after how many landings. "direction_limits" => change(|v| { let i = direction_at(v, body)?; set_limits(&mut v["directions"][i], body); crate::events::emit("tree_direction_limits", json!({"actor": by})); Ok(()) })?, "direction_pause" => change(|v| { let i = direction_at(v, body)?; let pause = body["paused"] != false; let d = &mut v["directions"][i]; d["paused"] = if pause { json!(format!("paused by {by}")) } else { Value::Null }; if !pause { d["resumed_at"] = json!(now()); } Ok(()) })?, "direction_clear" => change(|v| { let i = direction_at(v, body)?; v["directions"][i]["cleared"] = json!({"by": by, "at": now()}); Ok(()) })?, // The directions' order, the first first: when the budget is short, the higher one starts next. "direction_order" => change(|v| { let ids = strings(&body["ids"], 40, 20); let list = v["directions"].as_array_mut().context("directions")?; list.sort_by_key(|d| ids.iter().position(|x| d["id"] == x.as_str()).unwrap_or(usize::MAX)); Ok(()) })?, // What every direction together may start: at once, a day, and at once in one project. "budget_set" => change(|v| { let b = budget_of(v); let n = |k: &str, was: u64, max: u64| body[k].as_u64().map_or(was, |n| n.clamp(1, max)); v["budget"] = json!({"at_once": n("at_once", b.at_once, 6), "per_day": n("per_day", b.per_day, 30), "per_project": n("per_project", b.per_project, 3)}); crate::events::emit("tree_budget", json!({"actor": by})); Ok(()) })?, // A round of the scout: one move on one goal, for a runner to take. "scout" => change(|v| { let goal = body["goal"].as_str().unwrap_or(""); let mv = body["move"].as_str().unwrap_or(""); if !MOVES.contains(&mv) { bail!("a move is one of {}", MOVES.join(", ")); } let g = v["goals"].as_array().into_iter().flatten().find(|g| g["id"] == goal).cloned().with_context(|| format!("no goal {goal}"))?; if g["repos"].as_array().is_none_or(|r| r.is_empty()) { bail!("say which projects the goal is about first"); } if v["rounds"].as_array().into_iter().flatten().any(|r| r["goal"] == goal && matches!(r["state"].as_str(), Some("queued" | "asked"))) { bail!("a round on this goal is going already"); } // A Sketch may be for one tech: its mockup drawn again. let tech = body["tech"].as_str().filter(|t| mv == "sketch" && !t.is_empty()); if let Some(t) = tech { if !v["techs"].as_array().into_iter().flatten().any(|x| x["id"] == t) { bail!("no {t}"); } } let techs = v["techs"].as_array().cloned().unwrap_or_default(); if mv == "sketch" && tech.is_none() && to_sketch(&techs, &v["goals"], &json!({"goal": goal})).is_empty() { bail!("every tech still to build has a mockup: open one to have it drawn again"); } let rid = next_id(v, "r"); let list = v["rounds"].as_array_mut().context("rounds")?; // What the person asks this round to look at, in their words (said in a voice conversation, most often). let focus = Some(text(body, "focus", TEXT_MAX)).filter(|f| !f.is_empty()); list.push(json!({"id": rid, "goal": goal, "move": mv, "tech": tech, "focus": focus, "by": by, "at": now(), "state": "queued"})); let extra = list.len().saturating_sub(ROUNDS_KEPT); list.drain(..extra); crate::events::emit("tree_round", json!({"actor": by, "goal": goal, "move": mv})); Ok(()) })?, // The scout's one action on the page: a look, which is the moves that fit, one after another, as one // round each. On a tech it is one move about that tech: a question of the page's (`ask`), or a sketch. "look" => change(|v| { let goal = body["goal"].as_str().unwrap_or(""); if !v["goals"].as_array().into_iter().flatten().any(|g| g["id"] == goal) { bail!("no goal {goal}"); } if repos_of(&v["goals"], goal).is_empty() { bail!("say which projects the goal is about first"); } let via = Some(text(body, "via", 20)).filter(|v| v == "talk"); let about = match body["tech"].as_str().filter(|t| !t.is_empty()) { Some(t) => Some(v["techs"].as_array().into_iter().flatten().find(|x| x["id"] == t).cloned().with_context(|| format!("no {t}"))?), None => None, }; let ask = body["ask"].as_str().unwrap_or(""); let theirs = text(body, "focus", TEXT_MAX); let focus = match &about { Some(t) => [ask_focus(ask, t["name"].as_str().unwrap_or("")), theirs].into_iter().filter(|s| !s.is_empty()).collect::>().join(" "), None => theirs, }; // A move with `when` runs only if, when its turn comes, there is something for it (`wanted`). let steps: &[(&str, bool)] = match (&about, ask) { (Some(_), "draw") => &[("sketch", false)], (Some(_), _) => &[("map", false)], (None, _) => LOOK_WHOLE, }; let tid = about.as_ref().map(|t| t["id"].clone()).unwrap_or(Value::Null); push_look(v, goal, &by, via, tid, steps, &focus)?; Ok(()) })?, // A look stopped: what it has not done is not done, and an answer still on its way is not kept. "look_stop" => change(|v| { let look = body["look"].as_str().unwrap_or(""); let mut stopped = 0; for r in v["rounds"].as_array_mut().into_iter().flatten() { if (r["look"] == look || r["id"] == look) && matches!(r["state"].as_str(), Some("queued" | "asked")) { r["state"] = json!("stopped"); r["ended"] = json!(now()); r["error"] = json!(format!("stopped by {by}")); stopped += 1; } } if stopped == 0 { bail!("nothing of that look is going"); } Ok(()) })?, // What a look brought, seen by this person: it no longer glows on the tree for them. "look_seen" => change(|v| { let look = body["look"].as_str().unwrap_or(""); for r in v["rounds"].as_array_mut().into_iter().flatten() { if r["look"] == look || r["id"] == look { let mut seen = strings(&r["seen"], 20, 80); if !seen.iter().any(|s| s == by) { seen.push(by.to_string()); } r["seen"] = json!(seen); } } Ok(()) })?, // Pictures of a built tech as it works now: a session in its project takes them (`photo_brief`). "photograph" => start_photograph(&id, by, false)?, // Every built tech without pictures, photographed one after another by `tick`. "photograph_all" => change(|v| { let techs = v["techs"].as_array().cloned().unwrap_or_default(); let mut queue = strings(&v["photos"]["queue"], TECHS_KEPT, 20); for t in &techs { let tid = t["id"].as_str().unwrap_or(""); if state_of(t, &techs) == "built" && !has_shots(t) && !photographing(t) && !queue.iter().any(|q| q == tid) { queue.push(tid.to_string()); } } crate::events::emit("tree_photos", json!({"actor": by, "queued": queue.len()})); v["photos"] = json!({"queue": queue, "by": by, "at": now()}); Ok(()) })?, "photograph_stop" => change(|v| { v["photos"]["queue"] = json!([]); Ok(()) })?, // A picture taken off a tech's card. "shot_drop" => change(|v| { let n = body["n"].as_u64().context("which picture (n)")?; let t = find(&mut v["techs"], &id)?; if let Some(l) = t["shots"].as_array_mut() { l.retain(|s| s["n"] != n); } if let Some(p) = shot_path(&id, &n.to_string()) { let _ = std::fs::remove_file(p); } Ok(()) })?, _ => bail!("a tree op is goal_save, goal_delete, idea, insight_drop, tech_confirm, tech_drop, tech_restore, tech_built, tech_edit, remark, remark_drop, proposal_accept, proposal_drop, research, direction_set, direction_pause, direction_clear, scout, look, look_stop, look_seen, photograph, photograph_all, photograph_stop or shot_drop"), } Ok(all()) } /// A research session's brief, written from the tech as the design's checklist asks — who notices, what /// exists, what it needs, the evidence and what is on record against it — and the project it runs in. fn research_brief(v: &Value, id: &str) -> Result<(String, String)> { let techs = v["techs"].as_array().cloned().unwrap_or_default(); let t = techs.iter().find(|t| t["id"] == id).with_context(|| format!("no {id}"))?; match t["state"].as_str().unwrap_or("") { "built" => bail!("it is built already"), "dropped" => bail!("you said not this to it"), // Starting to build a guess is keeping it (`mark_research`): no separate Keep it first. "fog" => {} "researching" => bail!("a session is on it already ({})", t["research"]["session"].as_str().unwrap_or("?")), _ => {} } let goals: Vec<&Value> = v["goals"].as_array().into_iter().flatten().filter(|g| t["goals"].as_array().into_iter().flatten().any(|x| x == &g["id"])).collect(); let repo = next_repo(v, t).context("say which project the tech's goal is about first")?; let name = |nid: &str| techs.iter().find(|x| x["id"] == nid).map(|x| format!("{} ({})", x["name"].as_str().unwrap_or(""), x["state"].as_str().unwrap_or(""))).unwrap_or_default(); let mut b = format!("Research a tech of the research tree (More ▸ Research): \"{}\".\n\n{}\n", t["name"].as_str().unwrap_or(""), t["what"].as_str().unwrap_or("")); // A tech in several projects is one session each, the one the others depend on first, each landing on its own. let lands_in = strings(&t["lands_in"], 6, 200); if lands_in.len() > 1 { let done = strings(&t["landed_in"], 6, 200); b.push_str(&format!("\nIt lands in {} projects, in this order: {}. This session does its part in {repo} only{}; the part in each \ other project is a session of its own, after this one has landed, and what lands here must stand on its own on main.\n", lands_in.len(), lands_in.join(", then "), if done.is_empty() { String::new() } else { format!(" ({} has landed already)", done.join(", ")) })); } for (label, k) in [("Who notices", "who"), ("What they do differently once it exists", "differently"), ("What exists already toward it", "exists")] { if let Some(s) = t[k].as_str().filter(|s| !s.is_empty()) { b.push_str(&format!("\n{label}: {s}")); } } let needs: Vec = strings(&t["needs"], 20, 20).iter().map(|n| name(n)).filter(|n| !n.is_empty()).collect(); if !needs.is_empty() { b.push_str(&format!("\nIt builds on: {}", needs.join("; "))); } for g in &goals { b.push_str(&format!("\nIt serves the goal \"{}\": {}", g["name"].as_str().unwrap_or(""), g["statement"].as_str().unwrap_or(""))); let never = strings(&g["never"], NEVER_MAX, 300); if !never.is_empty() { b.push_str(&format!(" It must never: {}.", never.join("; "))); } } let evidence = strings(&t["evidence"], EVIDENCE_KEPT, 400); if !evidence.is_empty() { b.push_str(&format!("\n\nWhat the scout found it on:\n- {}", evidence.join("\n- "))); } let t0 = now(); let caveats: Vec = v["insights"].as_array().into_iter().flatten() .filter(|i| i["about"] == id && !i["dropped"].is_object() && i["seen_at"].as_i64().or(i["at"].as_i64()).unwrap_or(0) + FADE_S >= t0) .filter_map(|i| i["text"].as_str().map(str::to_string)).collect(); if !caveats.is_empty() { b.push_str(&format!("\n\nOn record about it:\n- {}", caveats.join("\n- "))); } let done = t["done"].as_str().map(str::trim).filter(|s| !s.is_empty()); if let Some(d) = done { b.push_str(&format!("\n\nDone when: {d}")); } b.push_str(&format!("\n\n{}", RESEARCH_RULES)); b.push_str(if done.is_some() { "\nBefore asking whether it shall land, go through \"Done when\" one check at a time and give for each the evidence: the test \ that covers it, the picture that shows it, or why it cannot be checked from here." } else { "\nBefore asking whether it shall land, say in one to three checks when this tech is done, and give for each the evidence: the \ test that covers it, the picture that shows it, or why it cannot be checked from here." }); b.push_str(&format!("\n\nIts card on the tree shows a sketch drawn before it existed: once it works, keep a picture or two of the real \ screens where someone uses it there, with `midas show --caption \"…\" --tech {id}` (the caption one sentence in the tech's language).")); Ok((crate::util::short(&b, BRIEF_MAX), repo)) } // ── Automatic research along a direction ──────────────────────────────────── /// The techs on the way to a target: a tech and all it needs, back to the start; or a goal's, the goals /// under it included, and all they need. What the person said not this to is off the way. fn path_of(v: &Value, target: &str) -> Vec { let techs = v["techs"].as_array().cloned().unwrap_or_default(); let mut under = vec![json!(target)]; let mut i = 0; while i < under.len() && i < 64 { let at = under[i].clone(); under.extend(v["goals"].as_array().into_iter().flatten().filter(|g| g["parent"] == at).map(|g| g["id"].clone())); i += 1; } let mut out: Vec = techs.iter() .filter(|t| t["id"] == target || t["goals"].as_array().into_iter().flatten().any(|g| under.contains(g))) .filter_map(|t| t["id"].as_str().map(str::to_string)).collect(); let mut i = 0; while i < out.len() && out.len() <= TECHS_KEPT { for n in techs.iter().find(|t| t["id"] == out[i].as_str()).map(|t| strings(&t["needs"], 20, 20)).unwrap_or_default() { if !out.contains(&n) && techs.iter().any(|t| t["id"] == n.as_str()) { out.push(n); } } i += 1; } out.retain(|id| techs.iter().any(|t| t["id"] == id.as_str() && !t["dropped"].is_object())); out } /// A research's outcome from its session: `landed`, `dropped`, `done` once finished, `ended` when it /// stopped unfinished; none while it goes on (as a template's run reads it). fn outcome_of(session: &str) -> Option { let m = crate::sessions::meta(session).ok()?; if let Some(o) = m["finished"]["outcome"].as_str() { return Some(o.to_string()); } matches!(m["status"].as_str(), Some("stopped" | "failed")).then(|| "ended".to_string()) } /// `change`, written only when `f` changed something: the watch runs every half minute. fn change_quiet(f: impl FnOnce(&mut Value) -> Result) -> Result { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); let mut v = load(); let before = v.clone(); let r = f(&mut v)?; if v != before { save(&v)?; } Ok(r) } /// The hub's watch (every half minute): a tech whose research landed is built, however the research was /// started; and for the direction, the researches it started read back as they end, and the next tech on /// the way started when its moment comes. pub fn tick() { if let Err(e) = change_quiet(built_by_landing) { crate::events::emit("error", json!({"what": format!("the research tree's landings: {e:#}")})); } if let Err(e) = change_quiet(fill_costs) { crate::events::emit("error", json!({"what": format!("the research tree's costs: {e:#}")})); } match change_quiet(photo_step) { Ok(Some((tid, by))) => { if let Err(e) = start_photograph(&tid, &by, true) { crate::events::emit("error", json!({"what": format!("photographing {tid}: {e:#}")})); } } Ok(None) => {} Err(e) => crate::events::emit("error", json!({"what": format!("the research tree's pictures: {e:#}")})), } let next = match change_quiet(directions_step) { Ok(n) => n, Err(e) => { crate::events::emit("error", json!({"what": format!("the research tree's directions: {e:#}")})); return; } }; let Some((did, tid, by)) = next else { return }; if let Err(e) = start_research(&did, &tid, &by) { // Paused with why, rather than tried again every half minute. let _ = change(|v| { if let Some(i) = index_of(v, &did) { v["directions"][i]["paused"] = json!(crate::util::short(&format!("could not start {tid}: {e:#}"), 300)); } Ok(()) }); } } /// A research landed is its tech built, whether a direction started it or the person did (Start now): /// read from the tech's own researches, so a research outside any direction is not left offered again. /// Only a landing after the person last said "not built" counts, or that word would be undone at the next look. /// A tech that lands in several projects (`lands_in`) is built once each of them has a landing (`landed_in`). fn built_by_landing(v: &mut Value) -> Result<()> { let t0 = now(); for t in v["techs"].as_array_mut().into_iter().flatten().filter(|t| t["built"] != true && !t["dropped"].is_object()) { let since = t["unbuilt_at"].as_i64().unwrap_or(0); let landed: Vec = t["researches"].as_array().into_iter().flatten().chain(t["research"].is_object().then_some(&t["research"])) .filter_map(|r| r["session"].as_str()) .filter_map(|sid| crate::sessions::meta(sid).ok()) .filter(|m| m["finished"]["outcome"] == "landed" && m["finished"]["at"].as_i64().unwrap_or(0) > since) .collect(); if landed.is_empty() { continue; } let lands_in = strings(&t["lands_in"], 6, 200); if lands_in.len() > 1 { let mut done = strings(&t["landed_in"], 6, 200); for r in landed.iter().filter_map(|m| m["repo"].as_str()) { if lands_in.iter().any(|x| x == r) && !done.iter().any(|x| x == r) { done.push(r.to_string()); } } if t["landed_in"] != json!(done) { t["landed_in"] = json!(done); } if !lands_in.iter().all(|x| done.contains(x)) { continue; } } t["built"] = json!(true); t["built_at"] = json!(t0); t["built_by"] = json!("research"); crate::events::emit("tree_built", json!({"actor": "midas", "tech": t["id"]})); } Ok(()) } /// What every direction together may start: at once, started a day, and at once in one project. #[derive(Clone, Copy)] struct Budget { at_once: u64, per_day: u64, per_project: u64, } fn budget_of(v: &Value) -> Budget { let b = &v["budget"]; Budget { at_once: b["at_once"].as_u64().unwrap_or(BUDGET_AT_ONCE), per_day: b["per_day"].as_u64().unwrap_or(BUDGET_PER_DAY), per_project: b["per_project"].as_u64().unwrap_or(BUDGET_PER_PROJECT), } } /// The directions going (not stopped), by index, in their order. fn live(v: &Value) -> Vec { v["directions"].as_array().into_iter().flatten().enumerate().filter(|(_, d)| !d["cleared"].is_object()).map(|(i, _)| i).collect() } fn index_of(v: &Value, id: &str) -> Option { v["directions"].as_array()?.iter().position(|d| d["id"] == id) } /// The direction a request names by `id`, or, naming none (a voice conversation from before there were /// several), the first going. fn direction_at(v: &Value, body: &Value) -> Result { match body["id"].as_str().filter(|s| !s.is_empty()) { Some(id) => index_of(v, id).filter(|&i| !v["directions"][i]["cleared"].is_object()).with_context(|| format!("no direction {id}")), None => live(v).first().copied().context("no direction is set"), } } /// Every direction's runs, of those going and stopped. fn all_runs(v: &Value) -> Vec { v["directions"].as_array().into_iter().flatten().flat_map(|d| d["runs"].as_array().cloned().unwrap_or_default()).collect() } /// The project a tech's next research works in: the first of `lands_in` without a landing yet, else its own /// project, else its goal's first. fn next_repo(v: &Value, t: &Value) -> Option { let done = strings(&t["landed_in"], 6, 200); if let Some(r) = strings(&t["lands_in"], 6, 200).into_iter().find(|r| !done.contains(r)) { return Some(r); } strings(&t["repos"], 1, 200).into_iter().next().or_else(|| { let goals = strings(&t["goals"], 20, 20); v["goals"].as_array().into_iter().flatten().filter(|g| goals.iter().any(|x| g["id"] == x.as_str())) .find_map(|g| strings(&g["repos"], 1, 200).into_iter().next()) }) } /// How many research sessions work in each project now, whoever started them. fn at_work_by_project(v: &Value) -> std::collections::HashMap { let mut n = std::collections::HashMap::new(); for t in v["techs"].as_array().into_iter().flatten().filter(|t| researching(t)) { let repo = t["research"]["session"].as_str().and_then(|s| crate::sessions::meta(s).ok()).and_then(|m| m["repo"].as_str().map(str::to_string)); if let Some(r) = repo { *n.entry(r).or_insert(0) += 1; } } n } /// One look at every direction, under the lock, in their order: each one's outcomes, pause, scout and whether /// it is reached; then the first that may start a research within its limits, the budget and its project's /// room, with the tech and whose direction it is. One start a look: the next goes half a minute later. fn directions_step(v: &mut Value) -> Result> { let t0 = now(); let b = budget_of(v); let runs = all_runs(v); let going = runs.iter().filter(|r| r["outcome"].is_null()).count() as u64; let today = runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) > t0 - 86400).count() as u64; let room = going < b.at_once && today < b.per_day; let mut busy = at_work_by_project(v); let mut start = None; for i in live(v) { let found = direction_step(v, i, room && start.is_none(), &|repo: &str| busy.get(repo).copied().unwrap_or(0) < b.per_project)?; if let Some((tid, repo)) = found { *busy.entry(repo).or_insert(0) += 1; start = Some((v["directions"][i]["id"].as_str().unwrap_or("").to_string(), tid, v["directions"][i]["by"].as_str().unwrap_or("").to_string())); } } Ok(start) } /// One look at direction `i`: outcomes, the pause, the scout, whether it is reached, and — when `may` and /// within its own limits — the tech to research next whose project has room, with that project. fn direction_step(v: &mut Value, i: usize, may: bool, room: &dyn Fn(&str) -> bool) -> Result> { let t0 = now(); // Outcomes, as their sessions finish (`built_by_landing` has made a landed one's tech built). for run in v["directions"][i]["runs"].as_array_mut().into_iter().flatten().filter(|r| r["outcome"].is_null()) { if let Some(o) = run["session"].as_str().and_then(outcome_of) { run["outcome"] = json!(o); run["ended"] = json!(t0); run["cost"] = run["session"].as_str().and_then(crate::sessions::cost_of).map_or(Value::Null, |c| json!((c * 100.0).round() / 100.0)); } } let d = v["directions"][i].clone(); let runs: Vec = d["runs"].as_array().cloned().unwrap_or_default(); // Researches in a row since it was last resumed, ended and landing nothing: paused. let since = d["resumed_at"].as_i64().unwrap_or(0); let mut ended: Vec<&Value> = runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) >= since && !r["outcome"].is_null()).collect(); ended.sort_by_key(|r| r["ended"].as_i64().unwrap_or(0)); let last: Vec<&&Value> = ended.iter().rev().take(DIRECTION_PAUSE_AFTER).collect(); if d["paused"].is_null() && last.len() == DIRECTION_PAUSE_AFTER && last.iter().all(|r| r["outcome"] != "landed") { v["directions"][i]["paused"] = json!(format!("{DIRECTION_PAUSE_AFTER} researches in a row landed nothing")); crate::events::emit("tree_direction_paused", json!({"actor": "midas", "direction": d["id"]})); return Ok(None); } if !d["reached"].is_null() || !d["paused"].is_null() { return Ok(None); } let target = d["target"].as_str().unwrap_or("").to_string(); let path = path_of(v, &target); let techs: Vec = v["techs"].as_array().cloned().unwrap_or_default(); let built = |id: &str| techs.iter().any(|t| t["id"] == id && t["built"] == true); let remaining: Vec<&Value> = techs.iter().filter(|t| path.iter().any(|p| t["id"] == p.as_str()) && t["built"] != true).collect(); // The next: all it needs built, nobody on it; what is known before a guess, the smallest first. let mut ready: Vec<&&Value> = remaining.iter() .filter(|t| strings(&t["needs"], 20, 20).iter().all(|n| built(n)) && !researching(t)) .collect(); ready.sort_by_key(|t| next_key(t, &techs)); let running = runs.iter().filter(|r| r["outcome"].is_null()).count() as u64; let busy = running > 0 || remaining.iter().any(|t| researching(t)); // The way has run out when nothing on it is left, or nothing is left to start and nothing goes on. let out = remaining.is_empty() || (ready.is_empty() && !busy); let goal = goal_of_target(v, &target); let by = d["by"].as_str().unwrap_or("").to_string(); // While the scout looks along the way nothing new starts: what it brings may change what comes next. if goal.as_deref().is_some_and(|g| looking(v, g)) { return Ok(None); } if let Some(g) = goal.as_deref().filter(|g| !repos_of(&v["goals"], g).is_empty()) { if let Some(why) = scout_due(&d, &runs, out, t0) { let focus = match why { "out" => format!("The direction toward \"{}\" has nothing left to start. What comes next on the way to it: what is missing, \ and what earlier sessions left open?", d["name"].as_str().unwrap_or("")), _ => format!("The direction toward \"{}\" landed more since the last look. What did those landings build, what did they \ leave open, and what comes next on the way?", d["name"].as_str().unwrap_or("")), }; let look = push_look(v, g, &by, Some("direction".into()), Value::Null, LOOK_WHOLE, &focus)?; let mut scouts: Vec = d["scouts"].as_array().cloned().unwrap_or_default(); scouts.push(json!(t0)); let extra = scouts.len().saturating_sub(DIRECTION_RUNS_KEPT); scouts.drain(..extra); v["directions"][i]["scouts"] = json!(scouts); v["directions"][i]["scouted"] = json!({"at": t0, "why": why, "look": look}); crate::events::emit("tree_direction_scout", json!({"actor": "midas", "goal": g, "why": why})); return Ok(None); } } if remaining.is_empty() && !path.is_empty() { v["directions"][i]["reached"] = json!(t0); crate::events::emit("tree_direction_reached", json!({"actor": "midas", "target": target})); return Ok(None); } if out && !remaining.is_empty() { // What is left needs something nobody can start: said, rather than waited on for ever. v["directions"][i]["paused"] = json!("the way is stuck: what is left needs something that is not on it, or was said not this to"); crate::events::emit("tree_direction_paused", json!({"actor": "midas", "direction": d["id"]})); return Ok(None); } let today = runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) > t0 - 86400).count() as u64; if !may || running >= d["at_once"].as_u64().unwrap_or(DIRECTION_AT_ONCE) || today >= d["per_day"].as_u64().unwrap_or(DIRECTION_PER_DAY) || crate::focus::at_cap(&by) { return Ok(None); } // The first ready one whose project has room: one waiting on a busy project does not hold up another's. let Some((next, repo)) = ready.iter().find_map(|t| next_repo(v, t).filter(|r| room(r)).map(|r| (*t, r))) else { return Ok(None) }; let tid = next["id"].as_str().unwrap_or("").to_string(); // A guess on the way is out of the fog by the direction chosen: that choice was the person's. if state_of(next, &techs) == "fog" { find(&mut v["techs"], &tid)?["confirmed_by"] = json!(format!("direction of {by}")); } Ok(Some((tid, repo))) } /// The moves of a look over a whole goal; one with `true` only runs when there is something for it (`wanted`). const LOOK_WHOLE: &[(&str, bool)] = &[("map", false), ("harvest", false), ("group", true), ("sketch", true)]; /// A look queued on a goal: its moves as rounds, one after another. A look asked while one goes waits for it, and /// starts by itself once it ends: a question is never refused for coming at the wrong moment, as one said in a voice /// conversation was. Its id, the first round's. fn push_look(v: &mut Value, goal: &str, by: &str, via: Option, tid: Value, steps: &[(&str, bool)], focus: &str) -> Result { let going: Vec<&Value> = v["rounds"].as_array().into_iter().flatten() .filter(|r| r["goal"] == goal && matches!(r["state"].as_str(), Some("queued" | "asked"))).collect(); let waiting = going.iter().map(|r| r["look"].as_str().or(r["id"].as_str()).unwrap_or("")).collect::>().len(); if waiting > LOOKS_WAITING { bail!("{LOOKS_WAITING} questions wait for the scout already: take one back first"); } let mut after = going.last().map(|r| r["id"].clone()).unwrap_or(Value::Null); let mut look = String::new(); for (mv, when) in steps { let rid = next_id(v, "r"); if look.is_empty() { look = rid.clone(); } let tech = if *mv == "sketch" { tid.clone() } else { Value::Null }; let focus = Some(focus.to_string()).filter(|f| !f.is_empty() && *mv != "sketch"); v["rounds"].as_array_mut().context("rounds")?.push(json!({"id": rid, "goal": goal, "move": mv, "tech": tech, "about": tid, "focus": focus, "by": by, "via": via, "at": now(), "state": "queued", "look": look, "after": after, "when": if *when { json!("wanted") } else { Value::Null }})); after = json!(rid); } let list = v["rounds"].as_array_mut().context("rounds")?; let extra = list.len().saturating_sub(ROUNDS_KEPT); list.drain(..extra); crate::events::emit("tree_round", json!({"actor": by, "goal": goal, "move": "look"})); Ok(look) } /// The goal a direction's scout looks at: the target itself when it is a goal, else the first goal of the tech. fn goal_of_target(v: &Value, target: &str) -> Option { let goals = v["goals"].as_array().into_iter().flatten(); if goals.clone().any(|g| g["id"] == target) { return Some(target.to_string()); } let t = v["techs"].as_array().into_iter().flatten().find(|t| t["id"] == target)?; strings(&t["goals"], 20, 20).into_iter().find(|g| goals.clone().any(|x| x["id"] == g.as_str())) } /// Whether a look on the goal is queued or going. fn looking(v: &Value, goal: &str) -> bool { v["rounds"].as_array().into_iter().flatten().any(|r| r["goal"] == goal && matches!(r["state"].as_str(), Some("queued" | "asked"))) } /// Whether the direction sends the scout now, and why (`out`: the way has nothing left to start; `every`: enough /// landed since it last looked). Never while a look on the goal goes, never twice for one running out (nothing /// ended since the last), and at most `DIRECTION_SCOUTS_PER_DAY` a day. fn scout_due(d: &Value, runs: &[Value], out: bool, t0: i64) -> Option<&'static str> { if d["scout"] == false { return None; } let scouts: Vec = d["scouts"].as_array().into_iter().flatten().filter_map(Value::as_i64).collect(); if scouts.iter().filter(|&&at| at > t0 - 86400).count() >= DIRECTION_SCOUTS_PER_DAY { return None; } let last = scouts.iter().copied().max().unwrap_or(0).max(d["at"].as_i64().unwrap_or(0) - 1); let ended_since = runs.iter().filter(|r| r["ended"].as_i64().unwrap_or(0) > last).count(); let landed_since = runs.iter().filter(|r| r["outcome"] == "landed" && r["ended"].as_i64().unwrap_or(0) > last).count() as u64; let never = scouts.is_empty(); if out && (never || ended_since > 0) { return Some("out"); } let every = d["scout_every"].as_u64().unwrap_or(DIRECTION_SCOUT_EVERY); (every > 0 && landed_since >= every).then_some("every") } /// The direction's limits from a request, each only when given and within its bounds. fn set_limits(d: &mut Value, body: &Value) { if let Some(n) = body["at_once"].as_u64() { d["at_once"] = json!(n.clamp(1, 3)); } if let Some(n) = body["per_day"].as_u64() { d["per_day"] = json!(n.clamp(1, 12)); } if let Some(b) = body["scout"].as_bool() { d["scout"] = json!(b); } if let Some(n) = body["scout_every"].as_u64() { d["scout_every"] = json!(n.min(10)); } } /// A research a direction starts: the tech's brief, its session on autopilot, noted on the tech and the direction. fn start_research(did: &str, tid: &str, by: &str) -> Result<()> { let (brief, repo, toward) = { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); let v = all_unlocked(load()); let (b, r) = research_brief(&v, tid)?; let name = index_of(&v, did).and_then(|i| v["directions"][i]["name"].as_str().map(str::to_string)).unwrap_or_default(); (b, r, name) }; let brief = format!("{brief}\n\nThe research tree's direction toward \"{toward}\" started this session, on autopilot: the person chose \ the direction and is not following along. Keep to this one tech."); let sid = crate::sessions::start(by, &brief, Some(&repo), None, None, None, None, &json!([]))?; crate::sessions::tell(&sid, "autopilot", &json!({"on": true}), by)?; change(|v| { mark_research(v, tid, &sid, by, true)?; if let Some(runs) = index_of(v, did).and_then(|i| v["directions"][i]["runs"].as_array_mut()) { runs.push(json!({"tech": tid, "session": sid, "repo": repo, "at": now(), "outcome": null})); let extra = runs.len().saturating_sub(DIRECTION_RUNS_KEPT); runs.drain(..extra); } Ok(()) })?; crate::events::emit("tree_research", json!({"actor": "midas", "tech": tid, "session": sid, "direction": did})); Ok(()) } // ── Pictures of a tech as it really works ──────────────────────────────────── /// The pictures a tech keeps, the newest last: one photographing's worth. const SHOTS_KEPT: usize = 6; /// The largest picture kept on a tech. const SHOT_MAX: usize = 8 << 20; fn has_shots(t: &Value) -> bool { t["shots"].as_array().is_some_and(|s| !s.is_empty()) } /// Whether a session photographing a tech is still at it. fn photographing(t: &Value) -> bool { let Some(sid) = t["photograph"]["session"].as_str() else { return false }; crate::sessions::meta(sid).is_ok_and(|m| m["finished"].is_null() && !matches!(m["status"].as_str(), Some("stopped" | "failed"))) } /// The queue `photograph_all` filled, one at a time: the next tech to photograph, with whose queue it is, /// when none is being photographed and its person is under their Focus cap. One built since, or given /// pictures by another session, or said not this to, leaves the queue. fn photo_step(v: &mut Value) -> Result> { let queue = strings(&v["photos"]["queue"], TECHS_KEPT, 20); if queue.is_empty() { return Ok(None); } let techs = v["techs"].as_array().cloned().unwrap_or_default(); if techs.iter().any(photographing) { return Ok(None); } let by = v["photos"]["by"].as_str().unwrap_or("").to_string(); if crate::focus::at_cap(&by) { return Ok(None); } let mut rest = queue.into_iter().filter(|id| techs.iter().any(|t| t["id"] == id.as_str() && state_of(t, &techs) == "built" && !has_shots(t))); let next = rest.next(); v["photos"]["queue"] = json!(rest.collect::>()); Ok(next.map(|tid| (tid, by))) } /// A session photographing a built tech in its project, on autopilot: it only looks, so there is nothing /// for the person to decide in it. Noted on the tech (`photograph`), not among its researches. fn start_photograph(tid: &str, by: &str, queued: bool) -> Result<()> { let (brief, repo, name) = { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); let v = all_unlocked(load()); let t = v["techs"].as_array().into_iter().flatten().find(|t| t["id"] == tid).cloned().with_context(|| format!("no {tid}"))?; if t["state"] != "built" { bail!("it is not built yet: the session building it keeps its pictures"); } if photographing(&t) { bail!("a session is photographing it already ({})", t["photograph"]["session"].as_str().unwrap_or("?")); } let (b, r) = photo_brief(&v, &t, queued)?; (b, r, t["name"].as_str().unwrap_or("").to_string()) }; let sid = crate::sessions::start(by, &brief, Some(&repo), None, None, None, None, &json!([]))?; crate::sessions::tell(&sid, "autopilot", &json!({"on": true}), by)?; let _ = crate::sessions::set_title(&sid, &crate::util::short(&format!("Photograph: {name}"), NAME_MAX), "midas"); change(|v| { find(&mut v["techs"], tid)?["photograph"] = json!({"session": sid, "by": by, "at": now()}); Ok(()) })?; crate::events::emit("tree_photograph", json!({"actor": by, "tech": tid, "session": sid})); Ok(()) } /// What a photographing session is asked: the real screens where the person who notices uses the tech, /// taken the project's own way, each kept on the tech with a caption; no code changed, nothing landed. fn photo_brief(v: &Value, t: &Value, queued: bool) -> Result<(String, String)> { let id = t["id"].as_str().unwrap_or(""); let repo = strings(&t["repos"], 1, 200).into_iter().next() .or_else(|| v["goals"].as_array().into_iter().flatten() .filter(|g| t["goals"].as_array().into_iter().flatten().any(|x| x == &g["id"])) .find_map(|g| strings(&g["repos"], 1, 200).into_iter().next())) .context("say which project the tech's goal is about first")?; let mut b = format!("Photograph a tech of the research tree as it works now on main: \"{}\" ({id}).\n\n{}\n", t["name"].as_str().unwrap_or(""), t["what"].as_str().unwrap_or("")); for (label, k) in [("Who notices", "who"), ("What they do differently now", "differently")] { if let Some(s) = t[k].as_str().filter(|s| !s.is_empty()) { b.push_str(&format!("\n{label}: {s}")); } } let evidence = strings(&t["evidence"], EVIDENCE_KEPT, 400); if !evidence.is_empty() { b.push_str(&format!("\n\nWhere the scout found it:\n- {}", evidence.join("\n- "))); } b.push_str(&format!("\n\nIts card on the tree (Goals) shows a sketch drawn before it existed, or nothing: give it pictures of the real \ thing. See it run the project's own way — its CLAUDE.md and skills say how (captures of the app, the web UI or its mock, a running client \ driven through its MCP server) — and take one to four pictures of the screens where the person who notices uses it, in the order they \ meet them, with real-looking content in them. Keep each with `midas show --caption \"…\" --tech {id}`, the caption one sentence in \ the tech's language saying what the picture shows. Change no code and land nothing: this session only looks. When it cannot be seen \ running here, keep a picture of the nearest screen that shows it and say in its caption what is missing. Then finish: \ `midas sessions finish --drop`.")); if queued { b.push_str("\n\nThe person asked for pictures of every built tech, one session after another, and is not following along."); } Ok((crate::util::short(&b, BRIEF_MAX), repo)) } /// What a picture is, by its first bytes: png, jpg or webp; nothing else is kept on a tech. fn picture_ext(bytes: &[u8]) -> Option<&'static str> { if bytes.starts_with(b"\x89PNG") { Some("png") } else if bytes.starts_with(&[0xff, 0xd8, 0xff]) { Some("jpg") } else if bytes.len() > 12 && &bytes[..4] == b"RIFF" && &bytes[8..12] == b"WEBP" { Some("webp") } else { None } } /// A picture of a tech as it really works, from a session (`midas show --tech`): kept on the tech. A /// session photographing it anew replaces what an earlier one kept; at most `SHOTS_KEPT`, the oldest go. pub fn add_shot(tid: &str, session: &str, file: &str, caption: Option<&str>, bytes: &[u8]) -> Result<()> { let ext = picture_ext(bytes).context("only a png, jpg or webp picture is kept on a tech")?; if bytes.len() > SHOT_MAX { bail!("a picture of at most {} MB is kept on a tech", SHOT_MAX >> 20); } let dir = shot_dir(tid).with_context(|| format!("not a tech: {tid}"))?; change(|v| { let t = find(&mut v["techs"], tid)?; let n = t["shot_seq"].as_u64().unwrap_or(0) + 1; let mut shots: Vec = t["shots"].as_array().cloned().unwrap_or_default(); let (keep, gone): (Vec, Vec) = shots.drain(..).partition(|s| s["session"] == session); shots = keep; shots.push(json!({"n": n, "caption": caption.map(|c| crate::util::short(c.trim(), TEXT_MAX)), "session": session, "file": file, "at": now()})); let extra = shots.len().saturating_sub(SHOTS_KEPT); let old: Vec = shots.drain(..extra).chain(gone).collect(); std::fs::create_dir_all(&dir)?; std::fs::write(dir.join(format!("{n}.{ext}")), bytes)?; for s in old { if let Some(p) = s["n"].as_u64().and_then(|o| shot_path(tid, &o.to_string())) { let _ = std::fs::remove_file(p); } } t["shot_seq"] = json!(n); t["shots"] = json!(shots); Ok(()) })?; crate::events::emit("tree_shot", json!({"actor": session, "tech": tid})); Ok(()) } fn shot_dir(tid: &str) -> Option { mockup_png_path(tid).map(|_| crate::registry::root().join("hosted").join("shots").join(tid)) } /// Where a tech's picture `n` is kept, whichever kind it is. pub fn shot_path(tid: &str, n: &str) -> Option { if n.is_empty() || n.len() > 6 || !n.chars().all(|c| c.is_ascii_digit()) { return None; } let dir = shot_dir(tid)?; let all = ["png", "jpg", "webp"].map(|e| dir.join(format!("{n}.{e}"))); all.iter().find(|p| p.exists()).cloned().or(Some(all[0].clone())) } /// A research started on a tech: noted on the tech (`research` the latest, `researches` all of them), and /// on the session, which takes the tech's name and says what it researches (`origin_of`) for the lists. fn mark_research(v: &mut Value, tid: &str, sid: &str, by: &str, direction: bool) -> Result<()> { let origin = origin_of(v, tid); let t = find(&mut v["techs"], tid)?; let at = now(); if !t["researches"].is_array() { // What came before the list: the one research the tech knew of. let had: Vec = t["research"].is_object().then(|| t["research"].clone()).into_iter().collect(); t["researches"] = json!(had); } t["research"] = json!({"session": sid, "by": by, "at": at, "direction": direction}); if t["confirmed_by"].is_null() { t["confirmed_by"] = json!(by); } if let Some(list) = t["researches"].as_array_mut() { list.push(json!({"session": sid, "by": by, "at": at})); let extra = list.len().saturating_sub(RESEARCHES_KEPT); list.drain(..extra); } let name = t["name"].as_str().unwrap_or("").to_string(); // A failed write to the session only loses how the lists show it. let _ = crate::sessions::set_research(sid, &origin); if !name.is_empty() { let _ = crate::sessions::set_title(sid, &name, "midas"); } Ok(()) } /// What a research session carries of its tech: the tech's name, icon and size, the goal it serves at /// the top, and the theme under that goal it falls in, with the colour the tree page gives that theme /// (tree.ts `themes`: the goals under the top one, oldest first, the first `THEMES` coloured). fn origin_of(v: &Value, tid: &str) -> Value { let goals: Vec = v["goals"].as_array().cloned().unwrap_or_default(); let Some(t) = v["techs"].as_array().into_iter().flatten().find(|t| t["id"] == tid) else { return Value::Null }; let goal = |id: &Value| goals.iter().find(|g| &g["id"] == id); // The tech's first goal, and the goals above it, up to the top. let mut line: Vec<&Value> = Vec::new(); let mut at = t["goals"].get(0).and_then(goal); while let Some(g) = at.filter(|_| line.len() < 16) { line.push(g); at = goal(&g["parent"]); } let top = line.last().copied(); let theme = (line.len() >= 2).then(|| line[line.len() - 2]); let num = |g: &Value| g["id"].as_str().and_then(|s| s.get(1..)).and_then(|s| s.parse::().ok()).unwrap_or(0); let slot = theme.and_then(|th| { let mut under: Vec<&Value> = goals.iter().filter(|g| top.is_some_and(|tp| g["parent"] == tp["id"])).collect(); under.sort_by_key(|g| (g["at"].as_i64().unwrap_or(0), num(g))); under.iter().position(|g| g["id"] == th["id"]).filter(|&i| i < THEMES) }); json!({ "tech": tid, "name": t["name"], "icon": t["icon"], "size": t["size"], "goal": top.map(|g| g["name"].clone()), "theme": theme.map(|g| g["name"].clone()), "slot": slot.map_or(json!(-1), |s| json!(s)), }) } /// The sessions that researched a tech, oldest first, each with how it ended (`outcome_of`), none while /// it goes on, when it started and ended, and what it cost once ended (`costs`, filled by `fill_costs`): /// from its list, and before there was one, its last research and the direction's runs. fn sessions_of(t: &Value, runs: &[Value], costs: &Value) -> Vec { session_ids(t, runs).into_iter().map(|(at, sid)| { let m = crate::sessions::meta(&sid).unwrap_or(Value::Null); let outcome = outcome_of(&sid); let ended = m["finished"]["at"].as_i64().or_else(|| outcome.is_some().then(|| m["updated"].as_i64()).flatten()); json!({"id": sid, "outcome": outcome, "at": m["created"].as_i64().unwrap_or(at), "ended": ended, "cost": costs[&sid]}) }).collect() } /// What each ended research session cost, kept once in `costs` by session id: a log is read only once. fn fill_costs(v: &mut Value) -> Result<()> { let runs = all_runs(v); let ids: Vec = v["techs"].as_array().into_iter().flatten().flat_map(|t| session_ids(t, &runs)).map(|(_, s)| s).collect(); if !v["costs"].is_object() { v["costs"] = json!({}); } for sid in ids { if v["costs"].get(&sid).is_some() || outcome_of(&sid).is_none() { continue; } let c = crate::sessions::cost_of(&sid).map_or(Value::Null, |c| json!((c * 100.0).round() / 100.0)); v["costs"][&sid] = c; } Ok(()) } /// The ids of the sessions that researched a tech, oldest first, with when each started as the tree has it. fn session_ids(t: &Value, runs: &[Value]) -> Vec<(i64, String)> { let mut ids: Vec<(i64, String)> = Vec::new(); let mut add = |sid: Option<&str>, at: Option| { if let Some(sid) = sid.filter(|s| !s.is_empty()) { if !ids.iter().any(|(_, x)| x == sid) { ids.push((at.unwrap_or(0), sid.to_string())); } } }; for r in t["researches"].as_array().into_iter().flatten() { add(r["session"].as_str(), r["at"].as_i64()); } for r in runs.iter().filter(|r| r["tech"] == t["id"]) { add(r["session"].as_str(), r["at"].as_i64()); } add(t["research"]["session"].as_str(), t["research"]["at"].as_i64()); ids.sort(); ids } /// The order the direction takes ready techs in: what is known before a guess, the smallest first, the oldest first. fn next_key(t: &Value, techs: &[Value]) -> (bool, u8, u64) { let size = match t["size"].as_str() { Some("S") => 0, Some("L") => 2, _ => 1 }; let num = t["id"].as_str().and_then(|s| s.get(1..)).and_then(|s| s.parse::().ok()).unwrap_or(0); (state_of(t, techs) == "fog", size, num) } /// What the direction starts next, and why it has not yet, for the page: `{tech, why}`, `why` one of /// `soon` (at its next look), `after` (a tech on the way it needs, named in `after`, is not built yet), /// `at_once` (as many go on as it may: `after` is the one going), `per_day` (today's are used, `at` when /// one frees), `focus` (the person's attention is at its cap), `paused`, `scouting` (the scout looks along the /// way), `budget` (every direction together has started all the budget allows) or `project` (its project, /// named in `project`, has as many at work as the budget allows). Each with the `project` it works in. /// None once there is nothing next. fn next_of(v: &Value, i: usize) -> Value { let n = next_why(v, i); if n.is_null() || n["tech"].is_null() { return n; } let mut n = n; let project = v["techs"].as_array().into_iter().flatten().find(|t| t["id"] == n["tech"]).and_then(|t| next_repo(v, t)); n["project"] = json!(project); if n["why"] == "soon" { let b = budget_of(v); let runs = all_runs(v); let t0 = now(); if runs.iter().filter(|r| r["outcome"].is_null()).count() as u64 >= b.at_once || runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) > t0 - 86400).count() as u64 >= b.per_day { n["why"] = json!("budget"); } else if let Some(p) = project.as_deref().filter(|p| at_work_by_project(v).get(*p).copied().unwrap_or(0) >= b.per_project) { n["why"] = json!("project"); n["project"] = json!(p); } } n } /// `next_of` within the direction alone, before the budget and the projects are asked. fn next_why(v: &Value, i: usize) -> Value { let d = &v["directions"][i]; if !d.is_object() || d["cleared"].is_object() || !d["reached"].is_null() { return Value::Null; } let techs: Vec = v["techs"].as_array().cloned().unwrap_or_default(); let path = path_of(v, d["target"].as_str().unwrap_or("")); let built = |id: &str| techs.iter().any(|t| t["id"] == id && t["built"] == true); let going = |id: &str| techs.iter().any(|t| t["id"] == id && researching(t)); let mut waiting: Vec<&Value> = techs.iter() .filter(|t| path.iter().any(|p| t["id"] == p.as_str()) && t["built"] != true && !researching(t)).collect(); waiting.sort_by_key(|t| next_key(t, &techs)); let unbuilt = |t: &Value| strings(&t["needs"], 20, 20).into_iter().filter(|n| !built(n)).collect::>(); let ready = waiting.iter().find(|t| unbuilt(t).is_empty()); let next = ready.or_else(|| waiting.iter().find(|t| unbuilt(t).iter().all(|n| going(n)))).or(waiting.first()); let target = d["target"].as_str().unwrap_or(""); if d["paused"].is_null() && goal_of_target(v, target).is_some_and(|g| looking(v, &g)) { return json!({"tech": next.map(|t| t["id"].clone()), "why": "scouting"}); } let Some(next) = next else { return Value::Null; }; let tid = next["id"].clone(); if !d["paused"].is_null() { return json!({"tech": tid, "why": "paused"}); } if ready.is_none() { let need = unbuilt(next); let after = need.iter().find(|n| going(n)).or(need.first()).cloned(); return json!({"tech": tid, "why": "after", "after": after}); } let runs: Vec = d["runs"].as_array().cloned().unwrap_or_default(); let t0 = now(); let running: Vec<&Value> = runs.iter().filter(|r| r["outcome"].is_null()).collect(); let today: Vec = runs.iter().filter_map(|r| r["at"].as_i64()).filter(|&at| at > t0 - 86400).collect(); if running.len() as u64 >= d["at_once"].as_u64().unwrap_or(DIRECTION_AT_ONCE) { return json!({"tech": tid, "why": "at_once", "after": running.first().map(|r| r["tech"].clone())}); } if today.len() as u64 >= d["per_day"].as_u64().unwrap_or(DIRECTION_PER_DAY) { return json!({"tech": tid, "why": "per_day", "at": today.iter().min().map(|at| at + 86400)}); } if crate::focus::at_cap(d["by"].as_str().unwrap_or("")) { return json!({"tech": tid, "why": "focus"}); } json!({"tech": tid, "why": "soon"}) } fn push_insight(v: &mut Value, i: Value) { if !v["insights"].is_array() { v["insights"] = json!([]); } let list = v["insights"].as_array_mut().expect("an array"); list.push(i); // Over the cap, the oldest faded or dropped ones go first, then the oldest. while list.len() > INSIGHTS_KEPT { let t0 = now(); let gone = list.iter().position(|i| i["dropped"].is_object() || i["seen_at"].as_i64().or(i["at"].as_i64()).unwrap_or(0) + FADE_S < t0).unwrap_or(0); list.remove(gone); } } // ── The scout, on a runner ────────────────────────────────────────────────── /// For the runner's poll: rounds queued (or taken long ago and never /// answered), each with its goal, what the tree knows already, and for /// Harvest what finished sessions in its projects said last. Taken once. pub fn rounds_take() -> Vec { let taken: Vec<(Value, Value, Vec)> = { let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner()); let mut v = load(); let goals = v["goals"].clone(); let known: Vec = v["techs"].as_array().into_iter().flatten() .map(|t| format!("{}{}", t["name"].as_str().unwrap_or(""), if t["built"] == true { " (built)" } else if t["dropped"].is_object() { " (dropped: do not propose again)" } else { "" })) .collect(); let techs = v["techs"].as_array().cloned().unwrap_or_default(); // A look's moves go one after another: each waits for the one before it, and one with nothing to do is skipped. let mut states: std::collections::HashMap = v["rounds"].as_array().into_iter().flatten() .map(|r| (r["id"].as_str().unwrap_or("").to_string(), r["state"].as_str().unwrap_or("").to_string())).collect(); let wants: Vec = v["rounds"].as_array().into_iter().flatten().map(|r| r["when"] != "wanted" || wanted(&v, r)).collect(); let mut changed = false; let mut taken = Vec::new(); for (r, want) in v["rounds"].as_array_mut().into_iter().flatten().zip(wants) { let stale = r["state"] == "asked" && r["taken_at"].as_i64().unwrap_or(0) + ROUND_RETRY_S <= now(); if r["state"] != "queued" && !stale { continue; } if r["after"].as_str().is_some_and(|a| matches!(states.get(a).map(String::as_str), Some("queued" | "asked"))) { continue; } let rid = r["id"].as_str().unwrap_or("").to_string(); if !want { r["state"] = json!("skipped"); r["ended"] = json!(now()); states.insert(rid, "skipped".into()); changed = true; continue; } let Some(mut g) = goals.as_array().into_iter().flatten().find(|g| g["id"] == r["goal"]).cloned() else { r["state"] = json!("failed"); r["error"] = json!("its goal is gone"); changed = true; continue; }; states.insert(rid, "asked".into()); // A theme reads the projects of the goal it is under. g["repos"] = json!(repos_of(&goals, g["id"].as_str().unwrap_or(""))); r["state"] = json!("asked"); r["taken_at"] = json!(now()); let mut job = r.clone(); if r["move"] == "sketch" { job["draw"] = json!(to_sketch(&techs, &goals, r)); // The remarks it was given, so the drawing that comes back takes away only those. if let Some(t) = r["tech"].as_str().and_then(|id| techs.iter().find(|t| t["id"] == id)) { r["remarks"] = json!(t["remarks"].as_array().into_iter().flatten().map(|m| m["id"].clone()).collect::>()); } } taken.push((job, g, known.clone())); } if (taken.is_empty() && !changed) || save(&v).is_err() { return Vec::new(); } taken }; taken.into_iter().map(|(r, g, known)| { let sessions = if r["move"] == "harvest" { harvest_digest(&g) } else { String::new() }; let lineage = lineage_of(&g); json!({"round": r["id"], "move": r["move"], "focus": r["focus"], "goal": g, "lineage": lineage, "known": known, "sessions": sessions, "draw": r["draw"]}) }).collect() } /// What a Sketch round draws: the one tech it names, or the goal's techs still to build that have no mockup yet, /// each as its name and what it is. fn to_sketch(techs: &[Value], goals: &Value, r: &Value) -> Vec { let line = |t: &Value| format!("{} {}: {}", t["id"].as_str().unwrap_or(""), t["name"].as_str().unwrap_or(""), t["what"].as_str().unwrap_or("")); // One tech drawn again: all of its description as it stands now, and the person's remarks on the last drawing. if let Some(id) = r["tech"].as_str() { return techs.iter().filter(|t| t["id"] == id).map(|t| { let mut s = line(t); for (label, k) in [("Who notices", "who"), ("What they do differently", "differently"), ("What exists already", "exists")] { if let Some(x) = t[k].as_str().filter(|x| !x.is_empty()) { s.push_str(&format!("\n {label}: {x}")); } } let remarks: Vec = t["remarks"].as_array().into_iter().flatten() .filter_map(|m| m["text"].as_str()).map(|m| format!("\n - {m}")).collect(); if !remarks.is_empty() { s.push_str(&format!("\n The person's remarks on its last mockup, each to be handled in this one:{}", remarks.concat())); } s }).collect(); } let mut under = vec![r["goal"].clone()]; for i in 0..64 { let Some(at) = under.get(i).cloned() else { break }; under.extend(goals.as_array().into_iter().flatten().filter(|g| g["parent"] == at).map(|g| g["id"].clone())); } techs.iter() .filter(|t| t["built"] != true && !t["dropped"].is_object() && t["mockup_png"].is_null()) .filter(|t| t["goals"].as_array().into_iter().flatten().any(|g| under.contains(g))) .take(SKETCH_TECHS).map(line).collect() } /// The goals above `g`, nearest first: a concrete goal is read in the light of the abstract one. fn lineage_of(g: &Value) -> Vec { let goals = all()["goals"].clone(); let mut out = Vec::new(); let mut at = g["parent"].clone(); while let Some(p) = at.as_str().and_then(|p| goals.as_array().into_iter().flatten().find(|x| x["id"] == p)) { if out.len() >= 8 { break; } out.push(json!({"name": p["name"], "statement": p["statement"]})); at = p["parent"].clone(); } out } /// The projects a goal is about: its own, else those of the nearest goal above it that names some. fn repos_of(goals: &Value, id: &str) -> Vec { let mut at = id.to_string(); for _ in 0..8 { let Some(g) = goals.as_array().into_iter().flatten().find(|g| g["id"] == at.as_str()) else { break }; let repos = strings(&g["repos"], ROUND_REPOS * 4, 200); if !repos.is_empty() { return repos; } let Some(p) = g["parent"].as_str() else { break }; at = p.to_string(); } Vec::new() } /// What the scout is asked about one tech, from the page's ready-made questions (`ask`). fn ask_focus(ask: &str, name: &str) -> String { match ask { "needs" => format!("Only about “{name}”: what does it need first that the tree does not have yet? Name those as techs, and say that “{name}” needs them."), "smaller" => format!("Only about “{name}”: it is too big for one session. Split it into smaller techs, each one session's worth, that together make it, each needing the one before where it does."), "exists" => format!("Only about “{name}”: is it built already, in whole or in part? Answer it as built when main has it, with the evidence; else what of it exists, as an insight about it."), _ => format!("Only about “{name}”: what comes after it, and what it still needs."), } } /// Whether a move a look runs only when wanted has anything to do now: Group while a goal has no themes, /// none proposed and enough techs to sort, Sketch while a tech still to build has no mockup. fn wanted(v: &Value, r: &Value) -> bool { let goal = r["goal"].as_str().unwrap_or(""); match r["move"].as_str().unwrap_or("") { "group" => { let themed = v["goals"].as_array().into_iter().flatten().any(|g| g["parent"] == goal); let proposed = v["proposals"].as_array().into_iter().flatten().any(|p| p["goal"] == goal); let on = v["techs"].as_array().into_iter().flatten().filter(|t| t["goals"].as_array().into_iter().flatten().any(|g| g == goal)).count(); !themed && !proposed && on >= GROUP_FROM } "sketch" => !to_sketch(v["techs"].as_array().map(Vec::as_slice).unwrap_or(&[]), &v["goals"], r).is_empty(), _ => true, } } /// What the latest finished sessions in the goal's projects said last. fn harvest_digest(g: &Value) -> String { let repos: Vec = strings(&g["repos"], 10, 200); let mut out = String::new(); let mut n = 0; for m in crate::sessions::list().as_array().into_iter().flatten() { if n >= HARVEST_SESSIONS || out.len() >= HARVEST_BUDGET { break; } let ended = m["finished"].is_object() || matches!(m["status"].as_str(), Some("stopped" | "failed")); if !ended || !crate::sessions::repos_of(m).iter().any(|r| repos.contains(r)) { continue; } let Some(id) = m["id"].as_str() else { continue }; let Some(words) = crate::sessions::last_words(id) else { continue }; let outcome = m["finished"]["outcome"].as_str().unwrap_or("ended unfinished"); out.push_str(&format!("- {id} \"{}\" ({outcome}): {}\n", m["title"].as_str().unwrap_or(""), crate::util::short(&words.split_whitespace().collect::>().join(" "), HARVEST_WORDS))); n += 1; } out } /// How a research session works, the same in every one, so sessions the direction starts one after another /// build alike: one tech, the project's own rules, evidence before the landing. const RESEARCH_RULES: &str = "How to work:\n\ 1. Read the project's CLAUDE.md (or README) and the notes it points to before changing anything, and keep to them.\n\ 2. First check what already does this on main; `midas who` shows who else changes the same files: agree with them first.\n\ 3. Keep to this one tech. Anything else you find goes in your last message as left open, not into this branch.\n\ 4. Build the smallest version the person who notices would notice, with a test for what it does, in commits of one change each.\n\ 5. Run the project's own checks on a build node; a red check is fixed, never worked around."; /// How a round is to be done: the system prompt. const SCOUT_RULES: &str = "You are the scout of a research tree, as in the game Civilization, kept by midas, a build workshop. At the far \ end of the tree stand the person's goals. Before them stand techs: capabilities that a person would notice in the product (\"invite \ someone by a link\", \"notices on the map\"), never modules, refactors, measurements or notes. A tech is small enough for one to three \ work sessions; a bigger one is split. Each tech says what it needs first.\n\n\ You read one project's code on its main branch, with read, search and list tools only. Start from its README, CLAUDE.md, docs/ \ (notes, direction, mockups, designs) and the commit subjects you are given; open code only to check a claim. Never guess: every built \ tech cites where it is (a path, or a commit), and every missing one cites why it is wanted (a session id and its words, a design \ file, a note) and says what already exists toward it, which you checked.\n\n\ Every tech has an icon: one SVG, 24 by 24 (viewBox \"0 0 24 24\"), drawn with lines only in one style: path, circle, rect, line, \ polyline, polygon, ellipse or g, stroke currentColor, no fill except one small accent with fill=\"currentColor\", no text, no \ colours, no style, no transform. One object or a small scene that says what changes for whom (a chain link for an invite link, a \ calendar with two people for a weekly meeting), recognisable at 20 pixels. Under 1500 bytes.\n\n\ Answer with one JSON object and nothing else:\n\ {\"techs\": [{\"name\": \"\", \"what\": \"\", \"who\": \"\", \ \"differently\": \"\", \"state\": \"built\" or \"missing\", \"needs\": [\"\"], \"evidence\": [\"\"], \"exists\": \"\", \"done\": \"\", \"size\": \"S\", \ \"M\" or \"L\", \"lands_in\": [\"\"], \"icon\": \"\"}], \ \"insights\": [{\"text\": \"\", \"evidence\": [\"…\"], \"about\": \ \"\"}], \"summary\": \"\"}\n\ At most 15 techs and 8 insights. Use a known tech's exact name when you mean it, to add evidence rather than a duplicate. Never \ propose one marked dropped. Fewer, well-sourced techs beat many: a round that finds nothing new says so.\n\n\ Write every new name, sentence, insight and summary in the language the goal is written in (a Dutch goal gets Dutch techs), \ except a known tech's exact name, which you keep as it is."; /// The question for one move. fn move_question(mv: &str) -> &'static str { match mv { "harvest" => "Harvest: what did earlier sessions leave open that serves this goal? Read what the finished sessions below said \ last: \"not built yet\", \"next\", \"untried\", \"designed, not built\", a step left to the person. Each such thing that serves the \ goal is a missing tech (with the session id and its words as evidence, and what exists toward it checked in the code), or an \ insight when it is not a capability yet. Name the built techs it builds on too, so the tree can draw what it needs.", "sketch" => "Sketch: make the mockup of each tech listed under \"Draw these\" below (each line starts with its id): the one \ screen where someone uses it once it exists, so it looks like the product itself, as the project's own design mockups do. First \ read how the product looks: its mockups (docs/mockups: their HTML, style.css and README) and its UI code's theme (colours, \ fonts, spacing, components). Then write the screen as one HTML page in that style: the product's real layout, panels, buttons \ and labels in its own words, with believable content (names, places, times) rather than placeholders, and what the tech adds \ marked as new the way the project's mockups mark it (a NEW badge, the accent outline). Show only the screen, no explanation \ around it.\n\ The page is opened from the project's root directory and photographed at a fixed size: \"phone\" is 390 by 844 pixels, \"wide\" \ is 1280 by 800; choose the one where it is used, and fit the screen in it. Link the project's own files by their path from the \ root (a style.css under docs/mockups, fonts under assets/fonts, an image the mockups use): nothing outside the project, no \ URL with a scheme (http:, data:, file:), no script, iframe, object or embed, no base tag. CSS in a style element is fine. At most \ 80000 characters.\n\ For this move answer with {\"techs\": [{\"id\": \"\", \"name\": \"\", \"frame\": \ \"phone\" or \"wide\", \"html\": \"…\", \"shows\": \"\"}], \"summary\": \"\"} and nothing else: no new techs, no insights. A tech listed with the person's remarks on its last mockup gets a \ drawing that handles each of them.", "group" => "Group:which themes does the work toward this goal fall into? Read the techs the tree knows (listed below) and \ the project's docs, and propose three to six concrete goals under this one, each a theme a person would recognise (\"a community \ holds its weekly meeting in the world\", \"run your own server\"), never a technical layer. Every known tech that is not dropped \ belongs to exactly one of them. For this move answer instead with one JSON object and nothing else: {\"goals\": [{\"name\": \"\", \"statement\": \"\", \"techs\": [\"\"]}], \"summary\": \"\"}", _ => "Map: what on the way to this goal is already built in this project? List the capabilities a person notices that serve \ the goal, each built one with where it is. Then the missing ones the goal clearly needs next (at most five), each with what already \ exists toward it. Say what each needs.", } } /// The scout at work, as the person sees it while a round goes on: its last steps in words, what it said last /// between them, and how much it read; told to the hub every few seconds (`POST /v1/hosted/runner/scouting`). #[derive(Default)] struct Live { repo: String, lines: std::collections::VecDeque, thought: String, reads: u64, searches: u64, told: Option, } impl Live { fn step(&mut self, round: &str, work: &std::path::Path, s: crate::ask::Step) { let short = |s: &str| crate::util::short(s.trim(), LIVE_TEXT); // A path as the project has it, not as the runner's worktree does. let path = |p: &str| short(std::path::Path::new(p).strip_prefix(work).map(|r| r.to_string_lossy().to_string()).unwrap_or_else(|_| p.to_string()).as_str()); let line = match s { crate::ask::Step::Tool("Read", i) => { self.reads += 1; json!({"kind": "read", "text": path(i["file_path"].as_str().unwrap_or(""))}) } crate::ask::Step::Tool("Grep", i) => { self.searches += 1; json!({"kind": "search", "text": short(i["pattern"].as_str().unwrap_or("")), "in": i["path"].as_str().map(path)}) } crate::ask::Step::Tool("Glob", i) => { self.searches += 1; json!({"kind": "list", "text": short(i["pattern"].as_str().unwrap_or(""))}) } crate::ask::Step::Tool(_, _) => return, // What it says between reads, its last paragraph: what it noticed, or what it looks at next. crate::ask::Step::Said(t) => { self.thought = short(t.rsplit("\n\n").next().unwrap_or(t)); Value::Null } }; if !line.is_null() { let mut line = line; line["at"] = json!(now()); line["repo"] = json!(self.repo); self.lines.push_front(line); self.lines.truncate(LIVE_LINES); } if self.told.is_some_and(|t| t.elapsed().as_secs() < LIVE_EVERY_S) { return; } self.told = Some(std::time::Instant::now()); let body = json!({"round": round, "lines": self.lines, "thought": self.thought, "reads": self.reads, "searches": self.searches}); if let Err(e) = crate::client::post("/v1/hosted/runner/scouting", &body) { eprintln!("tree round {round}: could not say how it goes: {e:#}"); } } } /// What a runner says of a round at work (`Live`), kept on the round while it goes on; a round that ended keeps /// only how much it read. pub fn scouting(body: &Value) -> Result<()> { let rid = body["round"].as_str().unwrap_or(""); change(|v| { let r = find(&mut v["rounds"], rid)?; if r["state"] != "asked" { return Ok(()); } let lines: Vec = body["lines"].as_array().into_iter().flatten().take(LIVE_LINES).map(|l| json!({ "kind": text(l, "kind", 10), "text": text(l, "text", LIVE_TEXT), "in": l["in"].as_str().map(|s| crate::util::short(s, LIVE_TEXT)), "repo": text(l, "repo", 80), "at": l["at"].as_i64().unwrap_or(0), })).collect(); r["live"] = json!({"lines": lines, "thought": text(body, "thought", LIVE_TEXT), "reads": body["reads"].as_u64().unwrap_or(0), "searches": body["searches"].as_u64().unwrap_or(0), "at": now()}); Ok(()) }) } /// A round the poll handed this runner: each of the goal's projects read in /// turn, and what was found told to the hub. pub fn scout(job: &Value) { let round = job["round"].as_str().unwrap_or("").to_string(); let goal = &job["goal"]; let mv = job["move"].as_str().unwrap_or("map"); let mut found = json!({"round": round, "techs": [], "insights": [], "goals": [], "summary": []}); let mut errors = Vec::new(); let _one = SCOUTING.lock().unwrap_or_else(|p| p.into_inner()); let mut live = Live::default(); let home = crate::sessions::sessions_home(); // Themes are one grouping of the whole tree: one project's reading of it is enough. let repos = if mv == "group" { 1 } else { ROUND_REPOS }; for repo in strings(&goal["repos"], repos, 200) { let result = (|| -> Result { let home = home.as_ref().context("the runner has no sessions directory (MIDAS_SESSIONS_DIR)")?; let work = crate::ask::worktree(home, &repo)?; let commits = git_log(&work); let prompt = round_prompt(job, &repo, &commits, mv); let model = crate::client::setting("MIDAS_AUTOPILOT_MODEL").unwrap_or_else(|| MODEL.into()); live.repo = repo.rsplit('/').next().unwrap_or(&repo).to_string(); let said = crate::ask::read_only_watched(&work, &prompt, SCOUT_RULES, &model, ROUND_RUN_S, &mut |s| live.step(&round, &work, s))?; let start = said.find('{').context("no answer")?; let end = said.rfind('}').context("no answer")?; let mut v: Value = serde_json::from_str(&said[start..=end]).context("no answer it could read")?; // A Sketch's pages are photographed here, in the project they link into; the hub gets the pictures. if mv == "sketch" { for t in v["techs"].as_array_mut().into_iter().flatten() { let frame = if t["frame"] == "wide" { "wide" } else { "phone" }; match photograph(&work, t["html"].as_str().unwrap_or(""), frame) { Ok(png) => { t["png"] = json!(data_encoding::BASE64.encode(&png)); t["frame"] = json!(frame); } Err(e) => errors.push(format!("{}: {e:#}", t["name"].as_str().unwrap_or("a mockup"))), } t["html"] = Value::Null; } } Ok(v) })(); match result { Ok(v) => { for k in ["techs", "insights", "goals"] { for mut x in v[k].as_array().cloned().unwrap_or_default() { x["repo"] = json!(repo); found[k].as_array_mut().expect("an array").push(x); } } if let Some(s) = v["summary"].as_str() { found["summary"].as_array_mut().expect("an array").push(json!(format!("{}: {s}", repo.rsplit('/').next().unwrap_or(&repo)))); } } Err(e) => errors.push(format!("{repo}: {e:#}")), } } if !errors.is_empty() { found["error"] = json!(errors.join("; ")); } eprintln!("tree round {round} ({mv}): {} techs, {} insights{}", found["techs"].as_array().map(Vec::len).unwrap_or(0), found["insights"].as_array().map(Vec::len).unwrap_or(0), if errors.is_empty() { String::new() } else { format!(", {} failed", errors.len()) }); if let Err(e) = crate::client::post("/v1/hosted/runner/scouted", &found) { eprintln!("tree round {round}: could not tell the hub: {e:#}"); } } /// The project's commit subjects of the last four months, newest first. fn git_log(work: &std::path::Path) -> String { let out = Command::new("git").arg("-C").arg(work) .args(["log", "--since=120.days", "--no-merges", "--date=short", "--format=%h %ad %s", "-n", "500"]) .stdin(Stdio::null()).output(); let s = out.map(|o| String::from_utf8_lossy(&o.stdout).to_string()).unwrap_or_default(); crate::util::short(&s, 30_000) } fn round_prompt(job: &Value, repo: &str, commits: &str, mv: &str) -> String { let g = &job["goal"]; let mut p = format!("## The goal\n{}\n{}\n", g["name"].as_str().unwrap_or(""), g["statement"].as_str().unwrap_or("")); for (label, k) in [("Who notices", "who"), ("Signs of progress", "signs")] { if let Some(s) = g[k].as_str().filter(|s| !s.is_empty()) { p.push_str(&format!("{label}: {s}\n")); } } let never = strings(&g["never"], NEVER_MAX, 300); if !never.is_empty() { p.push_str(&format!("Never: {}\n", never.join("; "))); } for above in job["lineage"].as_array().into_iter().flatten() { p.push_str(&format!("It stands under the goal \"{}\": {}\n", above["name"].as_str().unwrap_or(""), above["statement"].as_str().unwrap_or(""))); } p.push_str(&format!("\n## The project\nYou are reading {repo}, its main as it is now.\n\n## The move\n{}\n", move_question(mv))); if let Some(f) = job["focus"].as_str().filter(|f| !f.trim().is_empty()) { p.push_str(&format!("\n## What the person asks this round to look at\nIn their words: {}\nLook there first and answer \ it within the move: it narrows where you look, it does not change what a tech is or how you answer.\n", f.trim())); } let known: Vec<&str> = job["known"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); p.push_str(&format!("\n## Techs the tree knows already\n{}\n", if known.is_empty() { "(none yet)".to_string() } else { known.join("\n") })); let draw: Vec<&str> = job["draw"].as_array().into_iter().flatten().filter_map(Value::as_str).collect(); if !draw.is_empty() { p.push_str(&format!("\n## Draw these\n{}\n", draw.join("\n"))); } if let Some(s) = job["sessions"].as_str().filter(|s| !s.is_empty()) { p.push_str(&format!("\n## Finished sessions in the goal's projects, newest first: what each said last\n{s}")); } p.push_str(&format!("\n## Commits of the last four months\n{commits}")); p } /// A runner's round (`POST /v1/hosted/runner/scouted`): its techs merged into /// the tree — a known one gains evidence and the move, a new one comes in, in /// the fog unless built — and its insights kept. pub fn scouted(body: &Value) -> Result<()> { let rid = body["round"].as_str().unwrap_or(""); change(|v| { let r = find(&mut v["rounds"], rid)?.clone(); // A look stopped on the page: its answer is not kept. if r["state"] == "stopped" { return Ok(()); } let goal = r["goal"].as_str().unwrap_or("").to_string(); let mv = r["move"].as_str().unwrap_or("").to_string(); let found: Vec = body["techs"].as_array().cloned().unwrap_or_default().into_iter().take(ROUND_TECHS * ROUND_REPOS).collect(); let (mut added, mut confirmed, mut built, mut drawn) = (0, 0, 0, 0); // What it changed, by id, so the page can light it on the tree and walk through it. let mut changed = json!({"added": [], "confirmed": [], "built": [], "drawn": [], "insights": []}); let mut note = |kind: &str, id: &Value| { if let Some(l) = changed[kind].as_array_mut() { if !l.contains(id) { l.push(id.clone()); } } }; // First every tech, so the needs of one can name another of the same answer. let mut ids: Vec<(String, Vec)> = Vec::new(); let v_repos = repos_of(&v["goals"], &goal); for f in &found { // A Sketch's picture, kept beside the tree under the tech's id (by name when the id is missing). if let Some(png) = f["png"].as_str() { let by_name = key(&text(f, "name", NAME_MAX)); let Some(t) = v["techs"].as_array_mut().into_iter().flatten() .find(|t| (f["id"].is_string() && t["id"] == f["id"]) || (!by_name.is_empty() && t["key"] == by_name.as_str())) else { continue }; let Some(file) = t["id"].as_str().and_then(mockup_png_path) else { continue }; let Ok(bytes) = data_encoding::BASE64.decode(png.as_bytes()) else { continue }; if !bytes.starts_with(b"\x89PNG") || bytes.len() > SKETCH_PNG_MAX { continue; } if let Some(dir) = file.parent() { std::fs::create_dir_all(dir)?; } std::fs::write(&file, &bytes)?; t["mockup_png"] = json!(now()); t["mockup_frame"] = json!(if f["frame"] == "wide" { "wide" } else { "phone" }); t["mockup_shows"] = json!(Some(text(f, "shows", SHOWS_MAX)).filter(|s| !s.is_empty())); // The remarks this drawing was given are handled; one made while it was drawn waits for the next. let handled = r["remarks"].as_array().cloned().unwrap_or_default(); if let Some(l) = t["remarks"].as_array_mut() { l.retain(|m| !handled.contains(&m["id"])); } drawn += 1; note("drawn", &t["id"]); continue; } let name = text(f, "name", NAME_MAX); let k = key(&name); if k.is_empty() { continue; } let is_built = f["state"] == "built"; let evidence = strings(&f["evidence"], EVIDENCE_KEPT, 400); let repo = f["repo"].as_str().unwrap_or("").to_string(); let needs = strings(&f["needs"], 12, NAME_MAX); let existing = v["techs"].as_array_mut().into_iter().flatten().find(|t| t["key"] == k.as_str()); let tid = match existing { Some(t) => { if t["dropped"].is_object() { continue; } let mut ev = strings(&t["evidence"], EVIDENCE_KEPT, 400); for e in evidence { if !ev.contains(&e) && ev.len() < EVIDENCE_KEPT { ev.push(e); } } t["evidence"] = json!(ev); // Drawing a tech or sorting it into a theme is no second finding of it: the fog stays. let mut moves = strings(&t["moves"], 10, 20); if !moves.contains(&mv) && !matches!(mv.as_str(), "sketch" | "group") { moves.push(mv.clone()); confirmed += 1; note("confirmed", &t["id"]); } t["moves"] = json!(moves); // When it is done comes once too, for a tech that had none (one from before the scout asked for it): // the person's own words, once edited, are never written over. let done = text(f, "done", 600); if !done.is_empty() && t["built"] != true && t["done"].as_str().is_none_or(str::is_empty) { t["done"] = json!(done); } let spans = lands_in(&v_repos, &f["lands_in"]); if spans.len() > 1 && t["built"] != true && t["lands_in"].as_array().is_none_or(|l| l.is_empty()) { t["lands_in"] = json!(spans); } // A mockup comes once, for what is not built, unless a Sketch draws it again. if let Some(m) = f["mockup"].as_str().and_then(mockup) { if mv == "sketch" || (t["mockup"].is_null() && t["built"] != true) { t["mockup"] = json!(m); drawn += 1; note("drawn", &t["id"]); } } for (list, x) in [("goals", &goal), ("repos", &repo)] { let mut l = strings(&t[list], 20, 200); if !x.is_empty() && !l.contains(x) { l.push(x.clone()); } t[list] = json!(l); } if is_built && t["built"] != true { t["built"] = json!(true); t["built_at"] = json!(now()); t["built_by"] = json!("scout"); built += 1; note("built", &t["id"]); } if t["icon"].is_null() { t["icon"] = f["icon"].as_str().and_then(icon).map_or(Value::Null, |s| json!(s)); } t["seen_at"] = json!(now()); t["id"].as_str().unwrap_or("").to_string() } None => { if mv == "sketch" || added >= ROUND_TECHS || v["techs"].as_array().map(Vec::len).unwrap_or(0) >= TECHS_KEPT { continue; } let tid = next_id(v, "k"); let size = f["size"].as_str().filter(|s| matches!(*s, "S" | "M" | "L")).unwrap_or("M"); v["techs"].as_array_mut().context("techs")?.push(json!({ "id": tid, "key": k, "name": name, "what": text(f, "what", TEXT_MAX), "who": text(f, "who", 300), "differently": text(f, "differently", 600), "exists": text(f, "exists", 1000), "size": size, "done": if is_built { Value::Null } else { json!(text(f, "done", 600)) }, "lands_in": if is_built { json!([]) } else { json!(lands_in(&v_repos, &f["lands_in"])) }, "evidence": evidence, "needs": [], "goals": [goal], "repos": if repo.is_empty() { json!([]) } else { json!([repo]) }, "moves": [mv], "built": is_built, "built_at": if is_built { json!(now()) } else { Value::Null }, "built_by": if is_built { json!("scout") } else { Value::Null }, "icon": f["icon"].as_str().and_then(icon), "by": "scout", "round": rid, "at": now(), "seen_at": now(), "mockup": if is_built { None } else { f["mockup"].as_str().and_then(mockup) }, })); added += 1; note("added", &json!(tid)); if is_built { built += 1; note("built", &json!(tid)); } tid } }; ids.push((tid, needs)); } // Then the needs, by name, to techs the tree has: never to itself, never round in a circle. for (tid, needs) in ids { for n in needs { let nk = key(&n); let Some(nid) = v["techs"].as_array().into_iter().flatten().find(|t| t["key"] == nk.as_str()).and_then(|t| t["id"].as_str()).map(str::to_string) else { continue }; if nid == tid || needs_path(&v["techs"], &nid, &tid) { continue; } let t = find(&mut v["techs"], &tid)?; let mut l = strings(&t["needs"], 20, 20); if !l.contains(&nid) { l.push(nid); } t["needs"] = json!(l); } } let mut insights = 0; for f in body["insights"].as_array().cloned().unwrap_or_default().into_iter().take(ROUND_INSIGHTS * ROUND_REPOS) { let t = text(&f, "text", TEXT_MAX); if t.is_empty() { continue; } let ak = key(f["about"].as_str().unwrap_or("")); let about = v["techs"].as_array().into_iter().flatten().find(|x| !ak.is_empty() && x["key"] == ak.as_str()).map(|x| x["id"].clone()).unwrap_or(Value::Null); let iid = next_id(v, "i"); push_insight(v, json!({"id": iid, "goal": goal, "text": t, "about": about, "evidence": strings(&f["evidence"], EVIDENCE_KEPT, 400), "move": mv, "repo": f["repo"], "by": "scout", "round": rid, "at": now()})); insights += 1; note("insights", &json!(iid)); } // Group's themes: proposals of goals under this one, each with its techs, until the person keeps or drops one. // A new grouping replaces the last one not answered yet. let mut proposed = 0; let themes: Vec = body["goals"].as_array().cloned().unwrap_or_default(); if !themes.is_empty() { if !v["proposals"].is_array() { v["proposals"] = json!([]); } v["proposals"].as_array_mut().context("proposals")?.retain(|p| p["goal"] != goal.as_str()); let mut seen: Vec = Vec::new(); for f in themes.into_iter().take(PROPOSALS_KEPT) { let name = text(&f, "name", NAME_MAX); if key(&name).is_empty() || seen.contains(&key(&name)) { continue; } seen.push(key(&name)); // A known tech by its name as the round was given it, "(built)" and all. let techs: Vec = strings(&f["techs"], TECHS_KEPT, NAME_MAX * 2).iter() .map(|n| key(n.split(" (").next().unwrap_or(n))) .filter_map(|k| v["techs"].as_array().into_iter().flatten().find(|t| t["key"] == k.as_str()).map(|t| t["id"].clone())) .collect(); if techs.is_empty() { continue; } let pid = next_id(v, "p"); v["proposals"].as_array_mut().context("proposals")?.push(json!({"id": pid, "goal": goal, "name": name, "statement": text(&f, "statement", TEXT_MAX), "techs": techs, "round": rid, "at": now()})); proposed += 1; } } let r = find(&mut v["rounds"], rid)?; r["ended"] = json!(now()); r["counts"] = json!({"added": added, "confirmed": confirmed, "built": built, "insights": insights, "themes": proposed, "mockups": drawn}); r["changed"] = changed; r["summary"] = json!(strings(&body["summary"], ROUND_REPOS, 400).join(" ")); // Its steps were for watching it work; once back, how much it read is enough. if let Some(l) = r["live"].as_object_mut() { l.insert("lines".into(), json!([])); l.insert("thought".into(), json!("")); } match body["error"].as_str() { Some(e) if added + confirmed + insights + proposed + drawn == 0 => { r["state"] = json!("failed"); r["error"] = json!(crate::util::short(e, 600)); } e => { r["state"] = json!("done"); r["error"] = e.map_or(Value::Null, |e| json!(crate::util::short(e, 600))); } } crate::events::emit("tree_scouted", json!({"actor": "midas", "goal": goal, "move": mv, "added": added, "insights": insights})); Ok(()) }) } /// Whether `from` already needs `to`, through any chain: an edge `to → from` would close a circle. fn needs_path(techs: &Value, from: &str, to: &str) -> bool { let mut seen: Vec = Vec::new(); let mut stack = vec![from.to_string()]; while let Some(at) = stack.pop() { if at == to { return true; } if seen.contains(&at) || seen.len() > TECHS_KEPT { continue; } seen.push(at.clone()); if let Some(t) = techs.as_array().into_iter().flatten().find(|t| t["id"] == at.as_str()) { stack.extend(strings(&t["needs"], 20, 20)); } } false } // ── Icons ─────────────────────────────────────────────────────────────────── const ICON_MAX: usize = 2048; const ICON_ELEMENTS: usize = 60; const ICON_DEPTH: usize = 4; const ICON_TAGS: [&str; 8] = ["g", "path", "circle", "rect", "line", "polyline", "polygon", "ellipse"]; const ICON_ATTRS: [&str; 20] = ["d", "cx", "cy", "r", "rx", "ry", "x", "y", "width", "height", "x1", "y1", "x2", "y2", "points", "fill", "stroke", "stroke-width", "opacity", "stroke-dasharray"]; /// The root every icon is given, whatever it said: one style for the tree. const ICON_ROOT: &str = ""; const MOCKUP_MAX: usize = 16 * 1024; const MOCKUP_TAGS: [&str; 9] = ["g", "path", "circle", "rect", "line", "polyline", "polygon", "ellipse", "text"]; const MOCKUP_ATTRS: [&str; 26] = ["d", "cx", "cy", "r", "rx", "ry", "x", "y", "width", "height", "x1", "y1", "x2", "y2", "points", "fill", "stroke", "stroke-width", "opacity", "stroke-dasharray", "fill-opacity", "stroke-opacity", "font-size", "font-weight", "text-anchor", "dominant-baseline"]; /// A label in a mockup is a few words, not a page of text. const MOCKUP_LABEL: usize = 80; /// The two frames a mockup is drawn in: a phone's screen, or a wide one's. const MOCKUP_FRAMES: [&str; 2] = ["0 0 320 560", "0 0 640 400"]; /// What an SVG of the tree may hold: an icon's limits, or a mockup's, which may also hold short labels. struct Kind { max: usize, elements: usize, depth: usize, tags: &'static [&'static str], attrs: &'static [&'static str], } const ICON: Kind = Kind {max: ICON_MAX, elements: ICON_ELEMENTS, depth: ICON_DEPTH, tags: &ICON_TAGS, attrs: &ICON_ATTRS}; const MOCKUP: Kind = Kind {max: MOCKUP_MAX, elements: 400, depth: 6, tags: &MOCKUP_TAGS, attrs: &MOCKUP_ATTRS}; /// A tech's icon rebuilt from geometry alone, or none: an SVG is markup the /// page draws, so nothing passes but the allowed elements with the allowed /// attributes, whose values are numbers and path data (fill and stroke only /// `none` or `currentColor`). No script, `foreignObject`, link, style, event /// attribute, entity or text survives, because nothing is copied: it is /// written anew from what was read. pub fn icon(svg: &str) -> Option { rebuild(svg, &ICON, |_| ICON_ROOT.to_string()) } /// A tech's mockup, the scout's wireframe of the screen where someone uses it, rebuilt as an icon is /// and in one colour as icons are, with short labels as `text` (written anew, escaped) besides: in a /// phone's frame or a wide screen's, as its `viewBox` says, the phone's when it names neither. pub fn mockup(svg: &str) -> Option { rebuild(svg, &MOCKUP, |attrs| { let vb = attrs.iter().find(|(k, _)| k == "viewBox").map(|(_, v)| v.split_whitespace().collect::>().join(" ")); let frame = MOCKUP_FRAMES.iter().find(|f| vb.as_deref() == Some(**f)).unwrap_or(&MOCKUP_FRAMES[0]); format!("") }) } /// A Sketch page is at most this long; its picture at most this large. const SKETCH_HTML_MAX: usize = 80_000; pub const SKETCH_PNG_MAX: usize = 4 << 20; /// A Sketch round's answer to the hub: its pictures in base64, at most `SKETCH_TECHS` of them. pub const SCOUTED_BODY: usize = 36 << 20; /// The sizes a Sketch page is photographed at: a phone's screen, or a wide one. const SKETCH_FRAMES: [(&str, u32, u32); 2] = [("phone", 390, 844), ("wide", 1280, 800)]; /// How long a photograph may take before it is given up. const SKETCH_RENDER_S: u32 = 60; /// Why a Sketch page may not be photographed, or none. The page is the scout's own HTML, opened from /// the project's root as a file, so what it may reach is checked first: no script, frame or base, no /// URL with a scheme, and every path it names inside the project. Scripts are off in the browser too /// and the network unreachable, so what is left is the project's own files, which the scout read anyway. fn sketch_refused(work: &Path, html: &str) -> Option { if html.trim().is_empty() { return Some("no page".into()); } if html.len() > SKETCH_HTML_MAX { return Some(format!("a page of {} characters, more than {SKETCH_HTML_MAX}", html.len())); } let low = html.to_ascii_lowercase(); for tag in ["")); } } // Every place a path can stand: an attribute that loads, a CSS url(), an @import. let mut paths: Vec = Vec::new(); for attr in ["src=", "href=", "srcset=", "poster=", "data=", "xlink:href="] { let mut at = 0; while let Some(i) = low[at..].find(attr) { let s = at + i + attr.len(); let rest = &html[s..]; let v = match rest.chars().next() { Some(q @ ('"' | '\'')) => rest[1..].split(q).next().unwrap_or(""), _ => rest.split(|c: char| c.is_whitespace() || c == '>').next().unwrap_or(""), }; // A srcset is paths with sizes after them. paths.extend(v.split(',').map(|p| p.split_whitespace().next().unwrap_or("").to_string())); at = s; } } for (open, close) in [("url(", ')'), ("@import", ';')] { let mut at = 0; while let Some(i) = low[at..].find(open) { let s = at + i + open.len(); let v = html[s..].split(close).next().unwrap_or(""); let v = v.trim().trim_start_matches("url(").trim_end_matches(')').trim().trim_matches(|c| c == '"' || c == '\''); paths.push(v.to_string()); at = s; } } let root = work.canonicalize().ok()?; for p in paths.iter().map(|p| p.trim()).filter(|p| !p.is_empty() && !p.starts_with('#')) { if p.contains(':') || p.starts_with('/') || p.starts_with('\\') { return Some(format!("it links {}: only the project's own files, by their path", crate::util::short(p, 80))); } let file = p.split(['?', '#']).next().unwrap_or(p); // A path that does not exist loads nothing; one that does must stay inside the project. if let Ok(real) = root.join(file).canonicalize() { if !real.starts_with(&root) { return Some(format!("{} is outside the project", crate::util::short(p, 80))); } } else if file.split('/').filter(|s| *s == "..").count() > 0 { return Some(format!("{} leaves the project", crate::util::short(p, 80))); } } None } /// A Sketch page photographed headlessly at its frame's size (browser.rs), as the projects' own /// mockups are rendered: written into the project's root (the ask- worktree, the project's main), /// opened as a file with scripts off and the network pointed nowhere, and removed again. fn photograph(work: &Path, html: &str, frame: &str) -> Result> { if let Some(why) = sketch_refused(work, html) { bail!("not photographed: {why}"); } let (_, w, h) = SKETCH_FRAMES.iter().find(|(n, _, _)| *n == frame).copied().unwrap_or(SKETCH_FRAMES[0]); let tag = format!("{}-{}", std::process::id(), std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0)); let page = work.join(format!(".midas-sketch-{tag}.html")); std::fs::write(&page, html)?; let bytes = crate::browser::photograph(&format!("file://{}", page.display()), w, h, std::time::Duration::from_secs(SKETCH_RENDER_S.into())); let _ = std::fs::remove_file(&page); let bytes = bytes?; if !bytes.starts_with(b"\x89PNG") || bytes.len() > SKETCH_PNG_MAX { bail!("the browser's picture is no PNG of at most {} MB", SKETCH_PNG_MAX >> 20); } Ok(bytes) } /// `photograph` from the command line (`midas sketch-shot`): to try a page as the scout would make it. pub fn sketch_shot(root: &Path, html: &str, frame: &str) -> Result> { photograph(&root.canonicalize()?, html, frame) } /// Where a tech's photographed mockup is kept. pub fn mockup_png_path(id: &str) -> Option { let ok = id.len() < 16 && id.starts_with('k') && id[1..].chars().all(|c| c.is_ascii_digit()) && id.len() > 1; ok.then(|| crate::registry::root().join("hosted").join("mockups").join(format!("{id}.png"))) } fn rebuild(svg: &str, kind: &Kind, root_of: impl Fn(&[(String, String)]) -> String) -> Option { let s = svg.trim(); if s.len() > kind.max * 2 { return None; } let b = s.as_bytes(); let mut i = 0; let mut out = String::new(); let mut stack: Vec = Vec::new(); let mut root = false; let mut closed = false; let mut count = 0; let ws = |c: u8| c.is_ascii_whitespace(); while i < b.len() { if ws(b[i]) { i += 1; continue; } if closed || b[i] != b'<' { return None; } if s[i..].starts_with("")? + 3; continue; } if s[i..].starts_with("")? + 2; continue; } if s[i..].starts_with("')?; let name = s[i + 2..end].trim(); if stack.pop().as_deref() != Some(name) { return None; } if name == "svg" { closed = true; out.push_str(""); } else if name == "g" { out.push_str(""); } i = end + 1; continue; } // An element: its name, its attributes, and whether it closes itself. i += 1; let start = i; while i < b.len() && (b[i].is_ascii_alphanumeric()) { i += 1; } let name = &s[start..i]; let mut attrs: Vec<(String, String)> = Vec::new(); let self_closing; loop { while i < b.len() && ws(b[i]) { i += 1; } if i >= b.len() { return None; } if s[i..].starts_with("/>") { self_closing = true; i += 2; break; } if b[i] == b'>' { self_closing = false; i += 1; break; } let a0 = i; while i < b.len() && (b[i].is_ascii_alphanumeric() || b[i] == b'-' || b[i] == b':') { i += 1; } let an = s[a0..i].to_string(); if an.is_empty() || i >= b.len() || b[i] != b'=' { return None; } i += 1; let q = *b.get(i)?; if q != b'"' && q != b'\'' { return None; } let v0 = i + 1; let v1 = v0 + s[v0..].find(q as char)?; attrs.push((an, s[v0..v1].to_string())); i = v1 + 1; } if !root { if name != "svg" || self_closing { return None; } root = true; stack.push("svg".into()); out.push_str(&root_of(&attrs)); continue; } if !kind.tags.contains(&name) || stack.len() > kind.depth { return None; } count += 1; if count > kind.elements { return None; } out.push('<'); out.push_str(name); for (an, av) in attrs { if !kind.attrs.contains(&an.as_str()) || (name == "text" && matches!(an.as_str(), "fill" | "stroke")) { continue; } let ok = match an.as_str() { "fill" | "stroke" => matches!(av.as_str(), "none" | "currentColor"), "d" => av.chars().all(|c| c.is_ascii_digit() || " ,.-+eMmLlHhVvCcSsQqTtAaZz".contains(c)), "font-weight" => matches!(av.as_str(), "normal" | "bold") || av.chars().all(|c| c.is_ascii_digit()), "text-anchor" => matches!(av.as_str(), "start" | "middle" | "end"), "dominant-baseline" => matches!(av.as_str(), "middle" | "central" | "hanging" | "auto"), _ => av.chars().all(|c| c.is_ascii_digit() || " ,.-+e".contains(c)), }; if ok && av.len() <= 1500 { out.push_str(&format!(" {an}=\"{av}\"")); } } if name == "text" { // A label: its words up to the end tag, nothing nested, written anew and escaped. Drawn filled, never stroked. if self_closing { return None; } let end = i + s[i..].find('<')?; let words = s[i..end].split_whitespace().collect::>().join(" "); if !s[end..].starts_with("") || words.chars().count() > MOCKUP_LABEL { return None; } let words = words.replace('&', "&").replace('<', "<").replace('>', ">"); out.push_str(&format!(" fill=\"currentColor\" stroke=\"none\">{words}")); i = end + "".len(); continue; } if self_closing || name != "g" { out.push_str("/>"); if !self_closing { // An element other than a group holds nothing: its end tag must follow at once. while i < b.len() && ws(b[i]) { i += 1; } let close = format!(""); if !s[i..].starts_with(&close) { return None; } i += close.len(); } } else { out.push('>'); stack.push("g".into()); } } (closed && count > 0 && out.len() <= kind.max).then_some(out) } #[cfg(test)] mod tests { use super::*; #[test] fn a_round_carries_what_the_person_asked_it_to_look_at() { let job = json!({"move": "map", "goal": {"name": "Weekly meeting"}, "focus": "what an organiser misses on a phone"}); let p = round_prompt(&job, "acme/cartopolis", "", "map"); assert!(p.contains("## What the person asks this round to look at\nIn their words: what an organiser misses on a phone"), "{p}"); let none = round_prompt(&json!({"move": "map", "goal": {"name": "x"}, "focus": null}), "r", "", "map"); assert!(!none.contains("asks this round")); } #[test] fn an_icon_keeps_its_geometry_in_the_trees_style() { let got = icon(r#""#).unwrap(); assert!(got.starts_with(ICON_ROOT), "the tree's root, whatever was said: {got}"); assert!(got.contains(r#""#)); assert!(got.contains(r#""#)); assert!(got.contains(r#""#)); assert!(!got.contains("red") && !got.contains("style") && !got.contains("48")); } #[test] fn a_sketch_page_reaches_only_the_projects_own_files() { let root = std::env::temp_dir().join(format!("midas-sketch-test-{}", std::process::id())); std::fs::create_dir_all(root.join("docs/mockups/a")).unwrap(); std::fs::write(root.join("docs/mockups/a/style.css"), "").unwrap(); let ok = r#"
NEW
"#; assert_eq!(sketch_refused(&root, ok), None); for bad in [ r#""#, r#""#, r#""#, r#""#, r#""#, r#""#, r#""#, r#""#, r#""#, ] { assert!(sketch_refused(&root, bad).is_some(), "{bad}"); } assert!(sketch_refused(&root, &"x".repeat(SKETCH_HTML_MAX + 1)).is_some(), "too long"); assert_eq!(mockup_png_path("../x"), None); assert_eq!(mockup_png_path("k12").map(|p| p.ends_with("hosted/mockups/k12.png")), Some(true)); let _ = std::fs::remove_dir_all(&root); } #[test] fn a_mockup_keeps_its_frame_geometry_and_labels_written_anew() { let got = mockup(r#"Notices & "#); assert_eq!(got, None, "a label holding markup is refused"); let got = mockup(r#"Notices & alerts"#).unwrap(); assert!(got.contains(r#"viewBox="0 0 640 400""#), "{got}"); assert!(got.contains(r#"Notices & alerts"#), "{got}"); assert!(!got.contains("red")); let phone = mockup(r#""#).unwrap(); assert!(phone.contains(r#"viewBox="0 0 320 560""#), "a frame it does not know is the phone's: {phone}"); assert_eq!(mockup(&format!(r#"{}"#, "word ".repeat(30))), None, "a label is a few words"); assert_eq!(icon(r#"hi"#), None, "an icon still holds no text"); } #[test] fn an_icon_with_anything_but_geometry_is_refused_or_stripped() { for bad in [ r#""#, r#"
"#, r#""#, r#"text"#, r##""##, r#"]>"#, r#""#, r#""#, r#""#, r#""#, ] { assert_eq!(icon(bad), None, "refused: {bad}"); } let got = icon(r##""##).unwrap(); assert!(!got.contains("onload") && !got.contains("url") && !got.contains("transform"), "{got}"); assert!(got.contains(r#"stroke="currentColor""#)); assert_eq!(icon(r#""#).map(|s| s.contains("javascript")), Some(false)); } #[test] fn a_techs_state_follows_its_needs_and_the_fog() { let techs = vec![ json!({"id": "k1", "built": true}), json!({"id": "k2", "by": "scout", "moves": ["map"], "needs": ["k1"]}), json!({"id": "k3", "by": "scout", "moves": ["map", "harvest"], "needs": ["k1"]}), json!({"id": "k4", "by": "scout", "moves": ["map"], "confirmed_by": "sam", "needs": ["k3"]}), json!({"id": "k5", "by": "scout", "moves": ["map", "harvest"], "dropped": {"by": "sam"}}), ]; let st: Vec<&str> = techs.iter().map(|t| state_of(t, &techs)).collect(); assert_eq!(st, ["built", "fog", "available", "locked", "dropped"]); } #[test] fn names_match_however_they_are_written() { assert_eq!(key("Invite by link"), key("invite-by-link ")); assert_ne!(key("Invite by link"), key("Invite by mail")); } #[test] fn a_need_never_closes_a_circle() { let techs = json!([{"id": "a", "needs": ["b"]}, {"id": "b", "needs": ["c"]}, {"id": "c", "needs": []}]); assert!(needs_path(&techs, "a", "c"), "a needs c through b"); assert!(!needs_path(&techs, "c", "a")); } }