git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T12:14:52Z
feat(tree): a direction the person paces, that finds its own way on, and its history The person asked for more control over and insight into goals: how many sessions at once, how it went, letting it run by itself, and agents that keep building alike. - Limits: the hub took at_once (1-3) and per_day (1-12) already, but the page never sent them, so every direction ran one at a time, four a day. Heading this way and a new Limits button now set them, in place (`direction_limits`) without starting the direction over. - The way running out: a direction was "reached" as soon as the techs the scout had found were built, and nothing sent the scout further, so it stopped while the goal was far from done. It now sends a whole look on the goal when nothing is left to start (and after every N landings, three unless said), at most twice a day, starts nothing while it looks, and is reached only when a look finds nothing new. A way whose rest nobody can start pauses with why instead of waiting for ever. - Structure: a tech has "Done when" checks (written by the scout, editable by the person); a research brief carries them and the same How to work steps; the session gives evidence per check before asking to land, and the autopilot lands only once it has. - How it went: per goal, techs built a week beside those the scout merely found built (on the live Pinnacle goal 34 of 34 "built this week" were the latter, so one series alone said nothing), and every research session with its duration, outcome and cost. Cost is read once from the session's usage lines when it ends: each agent process counts up from zero, so a drop starts a new one and the session's is the sum. The shared confirm dialog keeps its text in reactive state inside a <p>, where form fields rendered empty, so these forms have a dialog of their own.
docs/hub.md | 42 +++++--
src/autopilot.rs | 4 +-
src/sessions.rs | 16 +++
src/tests.rs | 92 +++++++++++++-
src/tree.rs | 269 +++++++++++++++++++++++++++++++--------
web/src/app.css | 18 +++
web/src/components/research.tsx | 270 ++++++++++++++++++++++++++++++++++++----
web/src/lib/api.ts | 29 ++++-
web/src/lib/tree.test.ts | 23 +++-
web/src/lib/tree.ts | 52 ++++++++
web/src/lib/treetalk.test.ts | 2 +-
web/src/lib/treetalk.ts | 5 +-
12 files changed, 731 insertions(+), 91 deletions(-)
diff --git a/docs/hub.md b/docs/hub.md
index c757038..f0fa476 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -802,14 +802,40 @@ minute) researches the techs on the way by itself, one after another — the
next whose needs are built, what is known before a guess and the smallest
first, a guess kept when its turn comes, since choosing the way was the
person's decision — each a session on autopilot; a session that lands makes
-its tech built. At most one at a time and four started a day, held while its
-person is at their Focus cap, paused after two in a row that land nothing,
-and done once everything on the way is built; the page shows the way as stops — the tech
-landed last, what is at work now and for how long, what is NEXT and when it
-begins (`next` in the direction: after the tech it needs, after the one at
-work, tomorrow once today's four are used, when the Focus cap allows, or
-paused), and the goal — with Pause and Stop. Cost from finished
-sessions is the design's next step. It is one file, `hosted/tree.json`: `GET
+its tech built. Its **limits** are the person's, set when heading that way
+and changed in place with **Limits** (`direction_limits`): how many at once
+(1–3, one unless said) and started a day (1–12, four unless said). It is held
+while its person is at their Focus cap and paused after two in a row that land
+nothing. When the way **runs out** — everything known is built, or nothing is
+left to start and nothing goes on — it sends the **scout** along it by itself
+(a whole look on the goal, `via: direction`), and also after every few
+landings since its last look (three unless said; 0 only when it runs out), at
+most twice a day; nothing new starts while that look goes, and it carries on
+with what the look found. Only when a look finds nothing new is the goal
+**reached**; what is left that nobody can start pauses it with why (`the way is
+stuck`). The scout can be turned off, and the direction then is reached as
+soon as everything known is built. The page shows the way as stops — the tech
+landed last, what is at work now and for how long, the scout looking ahead,
+what is NEXT and when it begins (`next` in the direction: after the tech it
+needs, after the one at work, tomorrow once today's are used, when the Focus
+cap allows, after the scout's look, or paused), and the goal — with Limits,
+Pause and Stop, and its limits in a line under them.
+
+Each tech has a **Done when**: one to three checks a person could make in the
+product, written by the scout for what is missing or by the person in the tech's
+dialog (`tech_edit` `done`). A research's brief carries it, and the same
+**How to work** for every research (the project's CLAUDE.md, one tech, a test
+for what it does, the project's checks on a node); before asking to land, the
+session gives evidence for each check (a test, a picture, or why it cannot be
+checked), or says its own checks when the tech had none, and the autopilot
+lands a brief with Done when only once it has. **How it went**, under the tree,
+is the goal's history: techs built a week by a session beside those the scout
+found built already, and its research sessions newest first, with when each
+started, how long it took, how it ended and what it cost (`sessions` on each
+tech: `at`, `ended`, `cost`; the cost read once from the session's usage lines
+when it ends and kept in `costs`). The design for several directions at
+once, across projects, is `docs/screens/directions.html` (not built). It is
+one file, `hosted/tree.json`: `GET
/v1/hosted/tree`, `POST /v1/hosted/tree` (by `op`, role `steer`), and the
runner's `POST /v1/hosted/runner/scouted`. A round can carry a **focus**:
what the person asks it to look at, in their words, which the scout reads
diff --git a/src/autopilot.rs b/src/autopilot.rs
index cd48129..9050f64 100644
--- a/src/autopilot.rs
+++ b/src/autopilot.rs
@@ -324,7 +324,9 @@ Decide as the person would:\n\
when it offers more work than was asked, say no and have it finish what was asked.\n\
- A choice with a \"(Recommended)\" option: take it when it fits the brief, unless the conversation shows it is wrong.\n\
- Landing and deploying are yours to decide: say yes when the work is what was asked and the evidence is there (the gate or tests \
-passed, a visual change was shown); say what is missing when it is not.\n\
+passed, a visual change was shown); say what is missing when it is not. A brief with \"Done when\" checks lands only once the session \
+has given evidence for each check (the test that covers it, the picture that shows it, or why it cannot be checked from here): \
+ask for the ones it skipped.\n\
- Read the code when the answer depends on it; never guess.\n\
\n\
Leave it to the person (\"leave\") when it cannot be taken back and they did not ask for it — data destroyed (a database dropped, \
diff --git a/src/sessions.rs b/src/sessions.rs
index 70978d4..93d25a8 100644
--- a/src/sessions.rs
+++ b/src/sessions.rs
@@ -717,6 +717,22 @@ pub fn last_words(id: &str) -> Option<String> {
items.iter().rev().find(|i| i["kind"] == "agent").and_then(|i| i["text"].as_str()).map(str::to_string)
}
+/// What a session cost in dollars, from its usage lines: each agent process counts up from nothing, so a
+/// cost lower than the one before it starts a new one, and the session's is the sum of each one's last.
+pub fn cost_of(id: &str) -> Option<f64> {
+ let (items, _) = lines(id, "log.jsonl", 0);
+ let costs = items.iter().filter(|i| i["kind"] == "usage").filter_map(|i| i["cost"].as_f64());
+ let (mut total, mut last, mut any) = (0.0, 0.0, false);
+ for c in costs {
+ if c < last {
+ total += last;
+ }
+ last = c;
+ any = true;
+ }
+ any.then_some(total + last)
+}
+
pub fn log(id: &str, after: u64) -> Result<Value> {
meta(id)?;
let (items, next) = lines(id, "log.jsonl", after);
diff --git a/src/tests.rs b/src/tests.rs
index a58cb12..7ab4b27 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -2525,7 +2525,9 @@ fn a_direction_researches_the_techs_on_the_way_one_after_another() {
assert_eq!(meta["title"], "Tech k2");
assert_eq!(meta["research"]["tech"], "k2");
assert_eq!(meta["research"]["goal"], "communities");
- assert_eq!(k2["sessions"], json!([{"id": sid, "outcome": null}]));
+ assert_eq!(k2["sessions"][0]["id"], json!(sid));
+ assert_eq!(k2["sessions"][0]["outcome"], Value::Null);
+ assert!(k2["sessions"][0]["at"].as_i64().is_some(), "when it started, for the progress: {}", k2["sessions"]);
// k3 needs k2, which is at work: next, after it.
assert_eq!(all["direction"]["next"], json!({"tech": "k3", "why": "after", "after": "k2"}));
crate::tree::tick();
@@ -2558,6 +2560,94 @@ fn a_direction_researches_the_techs_on_the_way_one_after_another() {
assert_eq!(k3, ["dropped", "dropped"]);
}
+#[test]
+fn a_direction_sends_the_scout_when_its_way_runs_out_and_is_reached_when_it_finds_nothing() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("tree-direction-scout");
+ struct Conf;
+ impl Drop for Conf {
+ fn drop(&mut self) {
+ // SAFETY: tests hold SERIAL.
+ unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
+ }
+ }
+ let conf = std::env::temp_dir().join(format!("midas-test-tree-direction-scout-{}.conf", std::process::id()));
+ std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
+ // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
+ unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
+ let _conf = Conf;
+ // Everything known toward g1 is built: the old direction would have called it reached at once.
+ let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
+ "techs": [{"id": "k1", "key": "k1", "name": "Tech k1", "goals": ["g1"], "needs": [], "built": true, "by": "scout",
+ "moves": ["map"], "size": "S", "repos": ["acme/cartopolis"]}],
+ "insights": [], "rounds": []});
+ let path = crate::registry::root().join("hosted").join("tree.json");
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, tree.to_string()).unwrap();
+ crate::tree::op(&json!({"op": "direction_set", "target": "g1", "at_once": 9, "per_day": 0}), "ana").unwrap();
+ let d = crate::tree::all()["direction"].clone();
+ assert_eq!((d["at_once"].as_u64(), d["per_day"].as_u64(), d["scout"].as_bool()), (Some(3), Some(1), Some(true)), "limits within bounds: {d}");
+ crate::tree::op(&json!({"op": "direction_limits", "at_once": 2, "per_day": 6, "scout_every": 0}), "ana").unwrap();
+ let d = crate::tree::all()["direction"].clone();
+ assert_eq!((d["at_once"].as_u64(), d["per_day"].as_u64(), d["scout_every"].as_u64()), (Some(2), Some(6), Some(0)), "changed in place: {d}");
+ assert!(d["reached"].is_null() && d["runs"].as_array().unwrap().is_empty());
+ // The way has run out: the scout is sent along it, a whole look, and nothing is reached while it looks.
+ crate::tree::tick();
+ let all = crate::tree::all();
+ let rounds: Vec<&str> = all["rounds"].as_array().unwrap().iter().map(|r| r["move"].as_str().unwrap()).collect();
+ assert_eq!(rounds, ["map", "harvest", "group", "sketch"]);
+ assert!(all["rounds"].as_array().unwrap().iter().all(|r| r["via"] == "direction" && r["goal"] == "g1"));
+ assert_eq!(all["direction"]["scouted"]["why"], "out");
+ assert_eq!(all["direction"]["next"]["why"], "scouting");
+ assert!(all["direction"]["reached"].is_null());
+ crate::tree::tick();
+ assert_eq!(crate::tree::all()["rounds"].as_array().unwrap().len(), 4, "one look for one running out");
+ // The look comes back with nothing new: then, and only then, the goal is reached.
+ let mut v: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
+ for r in v["rounds"].as_array_mut().unwrap() {
+ r["state"] = json!("done");
+ }
+ std::fs::write(&path, v.to_string()).unwrap();
+ crate::tree::tick();
+ let d = crate::tree::all()["direction"].clone();
+ assert!(d["reached"].as_i64().is_some(), "{d}");
+ assert_eq!(crate::tree::all()["rounds"].as_array().unwrap().len(), 4, "no second look for the same running out");
+}
+
+#[test]
+fn a_research_brief_says_when_it_is_done_and_how_to_work() {
+ let _g = SERIAL.lock().unwrap();
+ scratch("tree-brief-done");
+ struct Conf;
+ impl Drop for Conf {
+ fn drop(&mut self) {
+ // SAFETY: tests hold SERIAL.
+ unsafe { std::env::remove_var("MIDAS_HUB_CONF") };
+ }
+ }
+ let conf = std::env::temp_dir().join(format!("midas-test-tree-brief-done-{}.conf", std::process::id()));
+ std::fs::write(&conf, serde_json::to_string(&crate::conf::HubConf {repos: vec!["acme/cartopolis".into()], ..Default::default()}).unwrap()).unwrap();
+ // SAFETY: tests hold SERIAL, so no other thread reads the environment meanwhile.
+ unsafe { std::env::set_var("MIDAS_HUB_CONF", &conf) };
+ let _conf = Conf;
+ let tree = json!({"seq": 9, "goals": [{"id": "g1", "name": "communities", "repos": ["acme/cartopolis"]}],
+ "techs": [{"id": "k1", "key": "k1", "name": "Invite by a link", "goals": ["g1"], "needs": [], "built": false, "by": "person",
+ "moves": ["map"], "size": "S", "repos": ["acme/cartopolis"], "done": "a link opens the community on the phone"}],
+ "insights": [], "rounds": []});
+ let path = crate::registry::root().join("hosted").join("tree.json");
+ std::fs::create_dir_all(path.parent().unwrap()).unwrap();
+ std::fs::write(&path, tree.to_string()).unwrap();
+ crate::tree::op(&json!({"op": "research", "id": "k1"}), "ana").unwrap();
+ let sid = crate::tree::all()["techs"][0]["research"]["session"].as_str().unwrap().to_string();
+ let brief = crate::sessions::meta(&sid).unwrap()["prompt"].as_str().unwrap().to_string();
+ assert!(brief.contains("Done when: a link opens the community on the phone"), "{brief}");
+ assert!(brief.contains("How to work:") && brief.contains("CLAUDE.md"), "{brief}");
+ assert!(brief.contains("one check at a time"), "{brief}");
+ // The person's words for it can be edited like the rest of the tech.
+ crate::tree::op(&json!({"op": "tech_edit", "id": "k1", "done": "the link works without an account"}), "ana").unwrap();
+ assert_eq!(crate::tree::all()["techs"][0]["done"], "the link works without an account");
+}
+
#[test]
fn a_research_started_by_hand_that_lands_builds_its_tech() {
use crate::sessions;
diff --git a/src/tree.rs b/src/tree.rs
index ed9f4bd..f0370d3 100644
--- a/src/tree.rs
+++ b/src/tree.rs
@@ -70,7 +70,7 @@ const MODEL: &str = "opus";
const MOVES: [&str; 4] = ["map", "harvest", "group", "sketch"];
/// A tech's description, as `tech_edit` changes it.
-const TECH_TEXT: [&str; 6] = ["name", "what", "who", "differently", "exists", "size"];
+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;
@@ -101,6 +101,10 @@ 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;
/// A direction's runs kept, newest last.
const DIRECTION_RUNS_KEPT: usize = 40;
/// The researches a tech keeps, newest last.
@@ -109,7 +113,7 @@ const RESEARCHES_KEPT: usize = 12;
const THEMES: usize = 5;
/// A research session's brief is at most this long.
-const BRIEF_MAX: usize = 6000;
+const BRIEF_MAX: usize = 8000;
static LOCK: Mutex<()> = Mutex::new(());
@@ -213,11 +217,12 @@ fn researching(t: &Value) -> bool {
fn all_unlocked(mut v: Value) -> Value {
let techs = v["techs"].as_array().cloned().unwrap_or_default();
let runs: Vec<Value> = v["direction"]["runs"].as_array().cloned().unwrap_or_default();
+ 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));
+ t["sessions"] = json!(sessions_of(t, &runs, &costs));
t["photographing"] = json!(photographing(t));
}
if v["direction"].is_object() {
@@ -482,15 +487,25 @@ pub fn op(body: &Value, by: &str) -> Result<Value> {
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}"))?;
- let at_once = body["at_once"].as_u64().unwrap_or(DIRECTION_AT_ONCE).clamp(1, 3);
- let per_day = body["per_day"].as_u64().unwrap_or(DIRECTION_PER_DAY).clamp(1, 12);
// A new direction keeps what the old one started, so a run going on is still read back when it ends.
let runs = v["direction"]["runs"].clone();
- v["direction"] = json!({"target": target, "name": name, "by": by, "at": now(), "at_once": at_once, "per_day": per_day,
+ v["direction"] = json!({"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": if runs.is_array() { runs } else { json!([]) }});
+ set_limits(&mut v["direction"], body);
crate::events::emit("tree_direction", json!({"actor": by, "target": target}));
Ok(())
})?,
+ // The 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| {
+ if !v["direction"].is_object() || v["direction"]["cleared"].is_object() {
+ bail!("no direction is set");
+ }
+ set_limits(&mut v["direction"], body);
+ crate::events::emit("tree_direction_limits", json!({"actor": by}));
+ Ok(())
+ })?,
"direction_pause" => change(|v| {
if !v["direction"].is_object() {
bail!("no direction is set");
@@ -553,15 +568,6 @@ pub fn op(body: &Value, by: &str) -> Result<Value> {
if repos_of(&v["goals"], goal).is_empty() {
bail!("say which projects the goal is about first");
}
- // 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.
- 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::<std::collections::BTreeSet<_>>().len();
- if waiting > LOOKS_WAITING {
- bail!("{LOOKS_WAITING} questions wait for the scout already: take one back first");
- }
- let behind = going.last().map(|r| r["id"].clone()).unwrap_or(Value::Null);
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}"))?),
@@ -577,26 +583,10 @@ pub fn op(body: &Value, by: &str) -> Result<Value> {
let steps: &[(&str, bool)] = match (&about, ask) {
(Some(_), "draw") => &[("sketch", false)],
(Some(_), _) => &[("map", false)],
- (None, _) => &[("map", false), ("harvest", false), ("group", true), ("sketch", true)],
+ (None, _) => LOOK_WHOLE,
};
let tid = about.as_ref().map(|t| t["id"].clone()).unwrap_or(Value::Null);
- let mut look = String::new();
- let mut after = behind;
- 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.clone()).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"}));
+ 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.
@@ -713,8 +703,18 @@ fn research_brief(v: &Value, id: &str) -> Result<(String, String)> {
if !caveats.is_empty() {
b.push_str(&format!("\n\nOn record about it:\n- {}", caveats.join("\n- ")));
}
- b.push_str("\n\nFirst check what already does this on main. Build the smallest version the person who notices would notice, \
-and say how it will be judged, naming what cannot be checked from here. When it is done, show it and ask whether it shall land.");
+ 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 <file> --caption \"…\" --tech {id}` (the caption one sentence in the tech's language)."));
Ok((crate::util::short(&b, BRIEF_MAX), repo))
@@ -778,6 +778,9 @@ 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) {
@@ -836,6 +839,7 @@ fn direction_step(v: &mut Value) -> Result<Option<(String, String)>> {
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["direction"].clone();
@@ -850,7 +854,7 @@ fn direction_step(v: &mut Value) -> Result<Option<(String, String)>> {
crate::events::emit("tree_direction_paused", json!({"actor": "midas"}));
return Ok(None);
}
- if !d["reached"].is_null() {
+ if !d["reached"].is_null() || !d["paused"].is_null() {
return Ok(None);
}
let target = d["target"].as_str().unwrap_or("").to_string();
@@ -858,25 +862,55 @@ fn direction_step(v: &mut Value) -> Result<Option<(String, String)>> {
let techs: Vec<Value> = 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<Value> = 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["direction"]["scouts"] = json!(scouts);
+ v["direction"]["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["direction"]["reached"] = json!(t0);
crate::events::emit("tree_direction_reached", json!({"actor": "midas", "target": target}));
return Ok(None);
}
- if !d["paused"].is_null() {
+ if out && !remaining.is_empty() {
+ // What is left needs something nobody can start: said, rather than waited on for ever.
+ v["direction"]["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"}));
return Ok(None);
}
- let running = 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 by = d["by"].as_str().unwrap_or("").to_string();
if 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 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 Some(next) = ready.first() 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.
@@ -886,6 +920,92 @@ fn direction_step(v: &mut Value) -> Result<Option<(String, String)>> {
Ok(Some((tid, by)))
}
+/// 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<String>, tid: Value, steps: &[(&str, bool)], focus: &str) -> Result<String> {
+ 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::<std::collections::BTreeSet<_>>().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<String> {
+ 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<i64> = 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 the direction starts: the tech's brief, its session on autopilot, noted on the tech and the direction.
fn start_research(tid: &str, by: &str) -> Result<()> {
let (brief, repo, toward) = {
@@ -1128,8 +1248,36 @@ fn origin_of(v: &Value, tid: &str) -> Value {
}
/// The sessions that researched a tech, oldest first, each with how it ended (`outcome_of`), none while
-/// it goes on: from its list, and before there was one, its last research and the direction's runs.
-fn sessions_of(t: &Value, runs: &[Value]) -> Vec<Value> {
+/// 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<Value> {
+ 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: Vec<Value> = v["direction"]["runs"].as_array().cloned().unwrap_or_default();
+ let ids: Vec<String> = 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<i64>| {
if let Some(sid) = sid.filter(|s| !s.is_empty()) {
@@ -1146,7 +1294,7 @@ fn sessions_of(t: &Value, runs: &[Value]) -> Vec<Value> {
}
add(t["research"]["session"].as_str(), t["research"]["at"].as_i64());
ids.sort();
- ids.into_iter().map(|(_, sid)| json!({"id": sid, "outcome": outcome_of(&sid)})).collect()
+ ids
}
/// The order the direction takes ready techs in: what is known before a guess, the smallest first, the oldest first.
@@ -1174,7 +1322,12 @@ fn next_of(v: &Value) -> Value {
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::<Vec<_>>();
let ready = waiting.iter().find(|t| unbuilt(t).is_empty());
- let Some(next) = ready.or_else(|| waiting.iter().find(|t| unbuilt(t).iter().all(|n| going(n)))).or(waiting.first()) else {
+ 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();
@@ -1396,6 +1549,15 @@ fn harvest_digest(g: &Value) -> String {
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 \
@@ -1413,7 +1575,9 @@ Answer with one JSON object and nothing else:\n\
{\"techs\": [{\"name\": \"<at most 40 characters, what someone can do>\", \"what\": \"<one sentence>\", \"who\": \"<who notices>\", \
\"differently\": \"<what they do differently once it exists>\", \"state\": \"built\" or \"missing\", \"needs\": [\"<names of other techs, \
in this answer or the known list>\"], \"evidence\": [\"<path, commit, session id with words, or URL>\"], \"exists\": \"<for a missing \
-one: what already exists toward it>\", \"size\": \"S\", \"M\" or \"L\", \"icon\": \"<svg …>\"}], \
+one: what already exists toward it>\", \"done\": \"<for a missing one: when it is done, one to three checks a person could make in the \
+product themselves, such as 'on the phone, an invite link opens the community for someone without an account'>\", \"size\": \"S\", \
+\"M\" or \"L\", \"icon\": \"<svg …>\"}], \
\"insights\": [{\"text\": \"<an observation that is not a capability yet, one or two sentences>\", \"evidence\": [\"…\"], \"about\": \
\"<a tech's name, or empty>\"}], \"summary\": \"<one plain sentence: what this round found>\"}\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 \
@@ -1723,6 +1887,12 @@ pub fn scouted(body: &Value) -> Result<()> {
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);
+ }
// 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) {
@@ -1760,6 +1930,7 @@ pub fn scouted(body: &Value) -> Result<()> {
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)) },
"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 },
diff --git a/web/src/app.css b/web/src/app.css
index e77f31c..d7cb440 100644
--- a/web/src/app.css
+++ b/web/src/app.css
@@ -9568,6 +9568,24 @@ button.tree-lane__name:hover {
flex: 1 1 320px;
min-width: 0;
}
+/* When a tech is done, with its edit button beside it. */
+.tree-done {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: var(--m-space-2);
+ margin: 0;
+}
+/* A small form of the Goals page (form dialog in research.tsx): its fields spaced as one column. */
+.tree-form {
+ display: flex;
+ flex-direction: column;
+ gap: var(--m-space-3);
+}
+.tree-direction__limits {
+ display: block;
+ margin-top: var(--m-space-2);
+}
.tree-fold-card--open {
flex-basis: 100%;
order: 2;
diff --git a/web/src/components/research.tsx b/web/src/components/research.tsx
index 67a56c2..76b7c1e 100644
--- a/web/src/components/research.tsx
+++ b/web/src/components/research.tsx
@@ -1,21 +1,22 @@
import m, {MithrilComponent} from '@garage44/mithril'
-import {Button, Card, Dialog, FieldTags, FieldText, FieldTextarea} from '@garage44/mithril/components'
+import {Button, Card, Dialog, Table, FieldNumber, FieldSwitch, FieldTags, FieldText, FieldTextarea} from '@garage44/mithril/components'
import {seg} from '@/components/autopilot'
+import {Bars, SERIES} from '@/components/charts'
import {openTreeTalk, talkAboutTree} from '@/components/discuss'
import {pipsView} from '@/components/pips'
import {askConfirm} from '@/components/confirm'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import type {Direction, DirectionNext, Goal, Insight, LiveLine, Round, Tech, TechState, TreeState} from '@/lib/api'
-import {age, ahead, shortName} from '@/lib/format'
+import {age, ahead, dur, shortName} from '@/lib/format'
import {hooks as talkHooks, talking} from '@/lib/discuss'
import {askProjects, projectName, projectSelect, projects, shown} from '@/lib/projects'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {$s, steers} from '@/lib/store'
-import {CARD_H, CARD_W, HEAD_H, LANE_HEAD, branches, curve, evidenceNames, frontier, goalsUnder, layout, leadsTo, lineOf, looksOf, moveTime, pathOf, pipOf, pips, progress, seenBy, techsOf, themes, wayOf} from '@/lib/tree'
-import type {Branch, Look, Step} from '@/lib/tree'
+import {CARD_H, CARD_W, HEAD_H, LANE_HEAD, branches, curve, evidenceNames, frontier, goalsUnder, layout, leadsTo, lineOf, looksOf, moveTime, pathOf, pipOf, pips, progress, history, seenBy, techsOf, themes, wayOf} from '@/lib/tree'
+import type {Branch, Look, Run, Step} from '@/lib/tree'
/**
* The research tree (tree.rs, docs/mockups/research-tree): the person's goals
@@ -38,7 +39,7 @@ const state = local({
allBuilt: false, notesBy: 'all' as 'all' | 'person' | 'scout', allNotes: false, openNote: '',
// The goal's menu open; what to send the scout to look at; the tech whose popover is open and the question typed in it;
// which of a look's finds is walked to (-1: none yet); the look whose finds the log lights; What next unfolded.
- menu: false, ask: '', pop: '', popAsk: '', walk: -1, lookShown: '', allLooks: false, nextOpen: false, notesOpen: false,
+ menu: false, ask: '', pop: '', popAsk: '', walk: -1, lookShown: '', allLooks: false, nextOpen: false, notesOpen: false, historyOpen: false,
// The height the screen has for the tree, so a short tree is spread over it (`fill`).
fill: 0,
// When the open tech's dialog opened, so what was changed since shows old beside new; and whether a voice conversation opened it.
@@ -1149,7 +1150,7 @@ function whatNext(d: TreeState, g: Goal, techs: Tech[]): m.Children {
<span>
<b>{toBuild} still to build</b> for this goal{ready.length ? `, ${ready.length} can start now` : ''}. Midas can build them one after another by itself, on autopilot.
</span>
- <Button variant="primary" disabled={!steers()} onclick={() => void headFor(d, g.id, g.name)}>
+ <Button variant="primary" disabled={!steers()} onclick={() => headFor(d, g.id, g.name)}>
Build it all by itself
</Button>
</div>
@@ -1171,7 +1172,7 @@ function whatNext(d: TreeState, g: Goal, techs: Tech[]): m.Children {
<b class="tree-board__title">What next</b>
<span class="hint">{empty ? 'Everything known is built: Research further, above, finds what comes next.' : summary || 'Nothing waits on you.'}</span>
{!open && head ? (
- <Button variant="primary" disabled={!steers()} onclick={() => void headFor(d, g.id, g.name)}>
+ <Button variant="primary" disabled={!steers()} onclick={() => headFor(d, g.id, g.name)}>
Build it all by itself
</Button>
) : null}
@@ -1186,26 +1187,216 @@ function whatNext(d: TreeState, g: Goal, techs: Tech[]): m.Children {
)
}
+/** Built by work, and found built already by a look: only the first is the week's work. */
+const SERIES_BUILT = [
+ {label: 'built by a session', color: SERIES[0]!},
+ {label: 'found built by the scout', color: SERIES[1]!},
+]
+
+/** Each outcome in a word, for the sessions' table. */
+const OUTCOME: Record<string, string> = {landed: 'landed', dropped: 'dropped', done: 'done, not landed', ended: 'stopped'}
+
+/**
+ * How the goal's work went, folded to one line: techs built a week, how many research sessions landed,
+ * how long one takes and what they cost; open, the sessions themselves (lib/tree.ts `history`).
+ */
+function historyCard(techs: Tech[]): m.Children {
+ const WEEKS = 8
+ const t0 = Date.now() / 1000
+ const x = history(techs, t0, WEEKS)
+ if (!x.runs.length && !x.built.some(Boolean)) return null
+ const month = x.built.slice(-4).reduce((s, n) => s + n, 0)
+ const dollars = (v: number) => `$${v.toFixed(v < 10 ? 2 : 0)}`
+ const summary = [
+ `${month} built in 4 weeks`,
+ x.ended ? `${x.landed} of ${x.ended} sessions landed` : '',
+ x.hours != null ? `about ${dur(x.hours * 3600)} each` : '',
+ x.costed ? `${dollars(x.cost)} in all` : '',
+ ].filter(Boolean).join(' · ')
+ const open = state.historyOpen
+ const weekOf = (i: number) => {
+ const start = new Date((t0 - (WEEKS - i) * 7 * 86400) * 1000)
+ return i === WEEKS - 1 ? 'this week' : `week of ${start.toLocaleDateString(undefined, {day: 'numeric', month: 'short'})}`
+ }
+ return (
+ <Card class={`tree-fold-card${open ? ' tree-fold-card--open' : ''}`}>
+ <div class="tree-next__fold">
+ <b class="tree-board__title">How it went</b>
+ <span class="hint">{summary}</span>
+ <Button variant="ghost" aria-expanded={open} onclick={() => (state.historyOpen = !state.historyOpen)}>
+ {open ? 'Fold ▴' : 'Open ▾'}
+ </Button>
+ </div>
+ {open
+ ? [
+ <h3 class="tree-detail__label">Techs built a week</h3>,
+ <Bars
+ days={x.built.map((_, i) => i)}
+ series={SERIES_BUILT}
+ value={(i) => [x.built[i]!, x.found[i]!]}
+ format={(v) => String(Math.round(v))}
+ label={weekOf}
+ />,
+ x.runs.length ? (
+ <Table
+ rowKey={(r: Run) => r.id}
+ rows={x.runs}
+ columns={[
+ {key: 'tech', label: 'tech', cell: (r: Run) => <a href="#" onclick={(e: Event) => { e.preventDefault(); pick(r.tech.id) }}>{shortName(r.tech.name, 40)}</a>},
+ {key: 'at', label: 'started', cell: (r: Run) => (r.at ? `${age(r.at)} ago` : '–')},
+ {key: 'took', label: 'took', align: 'end', cell: (r: Run) => (r.ended && r.at ? dur(r.ended - r.at) : r.outcome ? '–' : 'at work')},
+ {key: 'outcome', label: 'how', cell: (r: Run) => (r.outcome ? (OUTCOME[r.outcome] ?? r.outcome) : 'at work')},
+ {key: 'cost', label: 'cost', align: 'end', cell: (r: Run) => (r.cost != null ? dollars(r.cost) : '–')},
+ {key: 'id', label: 'session', cell: (r: Run) => <a href={`/sessions/${r.id}`} onclick={(e: Event) => { e.preventDefault(); go(`sessions/${r.id}`) }}>{r.id}</a>},
+ ]}
+ />
+ ) : null,
+ ]
+ : null}
+ </Card>
+ )
+}
+
/** The direction, live: true until it is cleared. */
function directionOf(d: TreeState): Direction | null {
return d.direction && !d.direction.cleared ? d.direction : null
}
+interface Limits {
+ at_once: number
+ per_day: number
+ scout: boolean
+ scout_every: number
+}
+
+/** A direction's limits as they stand, or the hub's defaults (tree.rs `DIRECTION_*`). */
+function limitsOf(dir: Direction | null): Limits {
+ return {at_once: dir?.at_once ?? 1, per_day: dir?.per_day ?? 4, scout: dir?.scout ?? true, scout_every: dir?.scout_every ?? 3}
+}
+
+/** The limits of the direction going, in one line. */
+function limitsLine(dir: Direction): string {
+ const l = limitsOf(dir)
+ const scout = !l.scout ? 'no scout' : l.scout_every ? `scout when the way runs out and every ${l.scout_every} landings` : 'scout when the way runs out'
+ return `${l.at_once} at once · ${l.per_day} a day · ${scout}`
+}
+
+/**
+ * The page's one small form at a time, in a dialog of its own (the shared confirm keeps its text in reactive
+ * state, where a form's fields do not survive): heading for a goal or a tech with the direction's limits, the
+ * limits of the direction going, or when a tech is done.
+ */
+const form = local({
+ open: '' as '' | 'head' | 'limits' | 'done',
+ target: '',
+ name: '',
+ replaces: '',
+ at_once: 1,
+ per_day: 4,
+ scout: true,
+ scout_every: 3,
+ done: '',
+})
+/** What to do once the form is sent (the tech's dialog closes): never in `form`, as reactive state calls a function put in it. */
+let afterForm: null | (() => void) = null
+
/** Head for a goal or a tech: from then on the techs on the way are researched one after another, on autopilot. */
-async function headFor(d: TreeState, id: string, name: string) {
+function headFor(d: TreeState, id: string, name: string, after?: () => void) {
const now = directionOf(d)
- const yes = await askConfirm({
- title: `Head for “${name}”?`,
- text: (
- <p>
- Midas then researches the techs on the way to it by itself, one after another: each a session on autopilot, landed when it is done, the tech
- built once it is on main. A guess on the way is kept when its turn comes. At most one at a time and four a day; it pauses after two that land
- nothing. You can pause or stop it here at any time.{now ? ` It replaces the way to “${now.name}”.` : ''}
- </p>
- ),
- yes: 'Head this way',
- })
- if (yes) await treeOp(`heading for ${name}`, 'direction_set', {target: id})
+ // A new direction starts from the limits of the one it replaces, so a choice made once is not made again.
+ Object.assign(form, limitsOf(now), {open: 'head', target: id, name, replaces: now?.name ?? ''})
+ afterForm = after ?? null
+}
+
+/** The direction's limits changed in place: what it started goes on. */
+function changeLimits(dir: Direction) {
+ Object.assign(form, limitsOf(dir), {open: 'limits', name: dir.name})
+ afterForm = null
+}
+
+/** When a tech is done, in the person's words: the checks its session gives evidence for before it lands. */
+function editDone(t: Tech) {
+ Object.assign(form, {open: 'done', target: t.id, name: t.name, done: t.done ?? ''})
+ afterForm = null
+}
+
+async function submitForm() {
+ const limits = {at_once: form.at_once, per_day: form.per_day, scout: form.scout, scout_every: form.scout_every}
+ const {open, target, name, done} = form
+ const after = afterForm
+ afterForm = null
+ form.open = ''
+ if (open === 'head') await treeOp(`heading for ${name}`, 'direction_set', {target, ...limits})
+ if (open === 'limits') await treeOp('limits saved', 'direction_limits', limits)
+ if (open === 'done') await treeOp('saved', 'tech_edit', {id: target, done})
+ after?.()
+}
+
+function formDialog(): m.Children {
+ const open = {
+ get value() {
+ return !!form.open
+ },
+ set value(v: boolean) {
+ if (!v) form.open = ''
+ },
+ }
+ const title = {'': '', head: `Head for “${form.name}”?`, limits: `How it heads for “${form.name}”`, done: `When is “${form.name}” done?`}[form.open]
+ const yes = form.open === 'head' ? 'Head this way' : 'Save'
+ const limits = [
+ <div class="focus-row">
+ <FieldNumber label="Sessions at once" model={bind(form, 'at_once')} min={1} max={3} help="More than one can collide in one project." />
+ <FieldNumber label="Started a day" model={bind(form, 'per_day')} min={1} max={12} />
+ </div>,
+ <FieldSwitch
+ model={bind(form, 'scout')}
+ label="Send the scout when the way runs out"
+ help="Rather than stop once everything known is built, it looks for what comes next, at most twice a day, and carries on with what it finds."
+ />,
+ <FieldNumber
+ label="And after every"
+ model={bind(form, 'scout_every')}
+ min={0}
+ max={10}
+ unit="landings"
+ disabled={!form.scout}
+ help="It looks again at what the landings left open. 0: only when the way runs out."
+ />,
+ ]
+ return (
+ <Dialog
+ model={open}
+ title={title}
+ size="sm"
+ footer={[
+ <Button variant="ghost" onclick={() => (form.open = '')}>
+ Cancel
+ </Button>,
+ <Button variant="primary" disabled={!steers()} onclick={() => void submitForm()}>
+ {yes}
+ </Button>,
+ ]}
+ >
+ <div class="tree-form">
+ {form.open === 'head' ? (
+ <p>
+ Midas then researches the techs on the way to it by itself, one after another: each a session on autopilot, landed when it is done, the
+ tech built once it is on main. A guess on the way is kept when its turn comes. It pauses after two that land nothing; you can pause or
+ stop it at any time.{form.replaces ? ` It replaces the way to “${form.replaces}”.` : ''}
+ </p>
+ ) : null}
+ {form.open === 'head' || form.open === 'limits' ? limits : null}
+ {form.open === 'done' ? (
+ <FieldTextarea
+ model={bind(form, 'done')}
+ label="Done when"
+ placeholder="on the phone, an invite link opens the community for someone without an account"
+ help="One to three checks you could make yourself. The session gives evidence for each before it asks to land."
+ />
+ ) : null}
+ </div>
+ </Dialog>
+ )
}
/** A tech's sessions as pips: what landed, what is at work, what its size still expects. */
@@ -1228,6 +1419,8 @@ function nextWord(d: TreeState, n: DirectionNext): string {
return 'when you have room'
case 'paused':
return 'paused'
+ case 'scouting':
+ return 'after the scout’s look'
}
}
@@ -1271,6 +1464,11 @@ function directionCard(d: TreeState): m.Children {
{built} / {on.length}
</span>
<span class="tree-direction__tools">
+ {dir.reached ? null : (
+ <Button variant="ghost" disabled={!steers()} onclick={() => changeLimits(dir)}>
+ Limits
+ </Button>
+ )}
{dir.reached ? null : (
<Button variant="ghost" disabled={!steers()} onclick={() => void treeOp(dir.paused ? 'resumed' : 'paused', 'direction_pause', {paused: !dir.paused})}>
{dir.paused ? 'Resume' : 'Pause'}
@@ -1291,6 +1489,13 @@ function directionCard(d: TreeState): m.Children {
() => openResearch(t),
),
)}
+ {dir.next?.why === 'scouting' ? (
+ <div class="way-stop way-stop--scout">
+ <span class="way-stop__node">{SCOUT_MARK}</span>
+ <span class="way-stop__name">The scout looks ahead</span>
+ <span class="way-stop__sub">{dir.scouted?.why === 'every' ? `after ${dir.scout_every} landings` : 'the way ran out'} · nothing starts meanwhile</span>
+ </div>
+ ) : null}
{next && dir.next ? stop('next', next, [<span class="way-tag way-tag--next">next</span>, nextWord(d, dir.next)], () => pick(next.id)) : null}
<div class={`way-stop way-stop--goal`}>
<span class="way-stop__node">{GOAL_FLAG}</span>
@@ -1299,10 +1504,18 @@ function directionCard(d: TreeState): m.Children {
</div>
</div>
{dir.paused ? <span class="tree-caveat">{dir.paused}</span> : null}
+ {dir.reached ? null : <span class="hint tree-direction__limits">{limitsLine(dir)}</span>}
</div>
)
}
+const SCOUT_MARK = (
+ <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
+ <circle cx="10.5" cy="10.5" r="6" />
+ <path d="M15 15l5 5" />
+ </svg>
+)
+
const CHECK = (
<svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
@@ -1632,7 +1845,7 @@ function techDialog(d: TreeState): m.Children {
</button>
)
// A field changed since the dialog opened: what it was, struck through, beside what it is, and Undo.
- const field = (k: 'name' | 'what' | 'who' | 'differently' | 'exists', now: string): m.Children => {
+ const field = (k: 'name' | 'what' | 'who' | 'differently' | 'exists' | 'done', now: string): m.Children => {
const e = t.edited?.[k]
if (!e || e.at < state.pickedAt || state.undone[`${t.id}:${k}`] === e.at) return now
return [
@@ -1748,7 +1961,7 @@ function techDialog(d: TreeState): m.Children {
// main, and a guess nobody starts fades by itself (tree.rs `guess_faded`). Saying so in a conversation still can.
if (going && directionOf(d)?.target !== t.id) {
buttons.push(
- <Button variant="secondary" disabled={!steers()} onclick={() => void headFor(d, t.id, t.name).then(close)}>
+ <Button variant="secondary" disabled={!steers()} onclick={() => headFor(d, t.id, t.name, close)}>
Head this way
</Button>,
)
@@ -1811,6 +2024,17 @@ function techDialog(d: TreeState): m.Children {
</dl>
</section>
) : null}
+ {t.built ? null : (
+ <section>
+ <h3 class="tree-detail__label">Done when</h3>
+ <p class="tree-done">
+ {t.done ? field('done', t.done) : <span class="hint">Not said yet: the session that builds it says it before it asks to land.</span>}{' '}
+ <Button variant="ghost" disabled={!steers()} onclick={() => editDone(t)}>
+ {t.done ? 'Change' : 'Say it'}
+ </Button>
+ </p>
+ </section>
+ )}
<section>
<h3 class="tree-detail__label">Where it sits</h3>
<div class="tree-chain">
@@ -2139,6 +2363,7 @@ export class ResearchPage extends MithrilComponent {
{treeView(d, g, techs)}
<div class="tree-folds">
{whatNext(d, g, techs)}
+ {historyCard(techs)}
{notesCard(d, g)}
</div>
{dropped ? (
@@ -2152,6 +2377,7 @@ export class ResearchPage extends MithrilComponent {
</p>
) : null}
{techDialog(d)}
+ {formDialog()}
</div>
)
}
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 90ad710..ec8c884 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -223,6 +223,15 @@ export interface Goal {
at: number
}
+/** A session that researched a tech: how it ended (none while it goes on), when it started and ended, what it cost in dollars once ended. */
+export interface TechSession {
+ id: string
+ outcome: string | null
+ at?: number
+ ended?: number | null
+ cost?: number | null
+}
+
/** Where a tech stands, worked out by the hub. */
export type TechState = 'built' | 'researching' | 'available' | 'locked' | 'fog' | 'dropped'
@@ -234,6 +243,8 @@ export interface Tech {
who: string
differently: string
exists: string
+ /** When it is done: one to three checks a person could make, written by the scout or the person; the research brief carries it. */
+ done?: string | null
size: 'S' | 'M' | 'L'
evidence: string[]
needs: string[]
@@ -264,11 +275,11 @@ export interface Tech {
/** The person's remarks on its mockup, waiting for its next drawing, which takes them away. */
remarks?: {id: string; text: string; by: string; at: number}[]
/** Fields changed on the person's word (`tech_edit`): each one's value before, by whom and when. */
- edited?: Partial<Record<'name' | 'what' | 'who' | 'differently' | 'exists' | 'size', {was: string; by: string; at: number}>>
+ edited?: Partial<Record<'name' | 'what' | 'who' | 'differently' | 'exists' | 'done' | 'size', {was: string; by: string; at: number}>>
/** The session researching it, started from the tree. */
research?: {session: string; by: string; at: number} | null
/** Every session that researched it, oldest first, and how each ended (`landed`, `dropped`, `done`, `ended`); none while it goes on. */
- sessions?: {id: string; outcome: string | null}[]
+ sessions?: TechSession[]
by: string
at: number
state: TechState
@@ -352,11 +363,17 @@ export interface Direction {
at: number
at_once: number
per_day: number
+ /** Whether it sends the scout by itself when the way runs out, and after how many landings since its last look (0: only when it runs out). */
+ scout?: boolean
+ scout_every?: number
+ /** When it sent the scout, and the last time why (`out`: nothing left to start; `every`: enough landed). */
+ scouts?: number[]
+ scouted?: {at: number; why: 'out' | 'every'; look: string} | null
/** Why it stopped starting researches, until resumed. */
paused: string | null
reached: number | null
cleared?: {by: string; at: number} | null
- runs: {tech: string; session: string; at: number; outcome: string | null; ended?: number}[]
+ runs: {tech: string; session: string; at: number; outcome: string | null; ended?: number; cost?: number | null}[]
/** What it starts next, and why not yet (tree.rs `next_of`). */
next?: DirectionNext | null
}
@@ -364,11 +381,11 @@ export interface Direction {
/**
* Why the next tech on the way has not started: `soon` at the hub's next look, `after` a tech it needs
* (or the one going, for `at_once`), `per_day` today's used until `at`, `focus` the person's attention at
- * its cap, `paused`.
+ * its cap, `paused`, `scouting` while the scout looks along the way (nothing starts meanwhile).
*/
export interface DirectionNext {
- tech: string
- why: 'soon' | 'after' | 'at_once' | 'per_day' | 'focus' | 'paused'
+ tech: string | null
+ why: 'soon' | 'after' | 'at_once' | 'per_day' | 'focus' | 'paused' | 'scouting'
after?: string | null
at?: number | null
}
diff --git a/web/src/lib/tree.test.ts b/web/src/lib/tree.test.ts
index 376f259..88bd5fb 100644
--- a/web/src/lib/tree.test.ts
+++ b/web/src/lib/tree.test.ts
@@ -1,7 +1,7 @@
import {describe, expect, test} from 'bun:test'
import type {Goal, Round, Tech, TreeState} from '@/lib/api'
-import {CARD_W, branches, GAP_X, depths, evidenceNames, goalsUnder, layout, frontier, lineOf, looksOf, moveTime, pathOf, progress, seenBy, techsOf, themes, wayOf} from '@/lib/tree'
+import {CARD_W, branches, GAP_X, depths, evidenceNames, goalsUnder, layout, frontier, lineOf, looksOf, moveTime, pathOf, progress, history, seenBy, techsOf, themes, wayOf} from '@/lib/tree'
const tech = (id: string, extra: Partial<Tech> = {}): Tech => ({
id, name: id, what: '', who: '', differently: '', exists: '', size: 'M', evidence: [], needs: [], goals: ['g1'], repos: [],
@@ -193,3 +193,24 @@ describe('the way to a goal', () => {
expect(way.map((s) => s.n)).toEqual([1, 2])
})
})
+
+describe('how a goal went', () => {
+ test('techs built a week, the sessions newest first, the median time and what they cost', () => {
+ const now = 100 * 7 * 86400
+ const h = 3600
+ const techs = [
+ tech('a', {state: 'built', built_at: now - 3600, sessions: [{id: 's1', outcome: 'landed', at: now - 10 * h, ended: now - 8 * h, cost: 2.5}]}),
+ tech('b', {state: 'built', built_by: 'research', built_at: now - 8 * 86400, sessions: [{id: 's2', outcome: 'dropped', at: now - 9 * 86400, ended: now - 9 * 86400 + 4 * h, cost: 1}]}),
+ tech('c', {sessions: [{id: 's3', outcome: null, at: now - h, ended: null, cost: null}]}),
+ tech('d', {state: 'built', built_at: now - 30 * 7 * 86400}),
+ tech('e', {state: 'built', built_by: 'scout', built_at: now - 3600}),
+ ]
+ const x = history(techs, now, 4)
+ expect(x.built).toEqual([0, 0, 1, 1])
+ expect(x.found).toEqual([0, 0, 0, 1])
+ expect(x.runs.map((r) => r.id)).toEqual(['s3', 's1', 's2'])
+ expect([x.landed, x.ended]).toEqual([1, 2])
+ expect(x.hours).toBe(2)
+ expect([x.cost, x.costed]).toEqual([3.5, 2])
+ })
+})
diff --git a/web/src/lib/tree.ts b/web/src/lib/tree.ts
index 9003e98..f2ca0dd 100644
--- a/web/src/lib/tree.ts
+++ b/web/src/lib/tree.ts
@@ -530,3 +530,55 @@ export function evidenceNames(t: Tech, file: string): boolean {
}),
)
}
+
+/** One research session in a goal's history: its tech, when it started and ended, how, and what it cost. */
+export interface Run {
+ tech: Tech
+ id: string
+ at: number
+ ended: number | null
+ outcome: string | null
+ cost: number | null
+}
+
+/**
+ * How a goal's work went: techs built a week by a session or the person (`built`) and found built already by the scout
+ * (`found`: what a first look over an old project finds is no work of that week), oldest first, the last `weeks` up to
+ * `now`; and its research sessions newest first, with what they add up to.
+ */
+export function history(techs: Tech[], now: number, weeks = 8): {
+ built: number[]
+ found: number[]
+ runs: Run[]
+ landed: number
+ ended: number
+ hours: number | null
+ cost: number
+ costed: number
+} {
+ const WEEK = 7 * 86400
+ const built = Array.from({length: weeks}, () => 0)
+ const found = Array.from({length: weeks}, () => 0)
+ for (const t of techs) {
+ if (t.state !== 'built' || !t.built_at) continue
+ const ago = Math.floor((now - t.built_at) / WEEK)
+ if (ago >= 0 && ago < weeks) (t.built_by === 'scout' ? found : built)[weeks - 1 - ago]! += 1
+ }
+ const runs: Run[] = techs
+ .flatMap((t) => (t.sessions ?? []).map((s) => ({tech: t, id: s.id, at: s.at ?? 0, ended: s.ended ?? null, outcome: s.outcome, cost: s.cost ?? null})))
+ .sort((a, b) => b.at - a.at)
+ const done = runs.filter((r) => r.outcome && r.ended && r.at)
+ const took = done.map((r) => (r.ended! - r.at) / 3600).sort((a, b) => a - b)
+ const costs = runs.filter((r) => r.cost != null)
+ return {
+ built,
+ found,
+ runs,
+ landed: runs.filter((r) => r.outcome === 'landed').length,
+ ended: runs.filter((r) => r.outcome).length,
+ // The median: one session left open over a weekend does not make every one look slow.
+ hours: took.length ? took[Math.floor((took.length - 1) / 2)]! : null,
+ cost: costs.reduce((s, r) => s + r.cost!, 0),
+ costed: costs.length,
+ }
+}
diff --git a/web/src/lib/treetalk.test.ts b/web/src/lib/treetalk.test.ts
index dfa8332..c30eb9b 100644
--- a/web/src/lib/treetalk.test.ts
+++ b/web/src/lib/treetalk.test.ts
@@ -28,7 +28,7 @@ test('the tree reads as its goal, its techs by state with ids, and where it head
expect(t).toContain('In the fog (a guess: Keep it or Not this) (1):\n- k3')
expect(t).toContain('Not this: not for us')
expect(t).toContain("- i1: organisers plan on phones (the person's own)")
- expect(t).toContain('heading to "goal g1" (g1), on; at most 4 a day. Next: k2 (soon).')
+ expect(t).toContain('heading to "goal g1" (g1), on; at most 1 at once and 4 a day, the scout sent when the way runs out. Next: k2 (soon).')
expect(t).toContain('(looking at: the phone)')
})
diff --git a/web/src/lib/treetalk.ts b/web/src/lib/treetalk.ts
index 3b0416d..2f4c3c0 100644
--- a/web/src/lib/treetalk.ts
+++ b/web/src/lib/treetalk.ts
@@ -86,12 +86,13 @@ export function techText(d: TreeState, id: string): string {
function directionText(d: TreeState): string {
const x = d.direction!
- const name = (id: string) => d.techs.find((t) => t.id === id)?.name ?? id
+ const name = (id: string | null) => (id ? (d.techs.find((t) => t.id === id)?.name ?? id) : 'nothing yet')
const state = x.reached ? 'reached' : x.paused ? `paused (${x.paused})` : 'on'
const next = x.next ? ` Next: ${name(x.next.tech)} (${x.next.why}${x.next.after ? `, after ${name(x.next.after)}` : ''}).` : ''
const last = x.runs.at(-1)
const ran = last ? ` Last started: ${name(last.tech)} in ${last.session}${last.outcome ? `, ${last.outcome}` : ', at work'}.` : ''
- return `heading to "${x.name}" (${x.target}), ${state}; at most ${x.per_day} a day.${next}${ran}`
+ const scout = x.scout === false ? 'no scout' : `the scout sent when the way runs out${x.scout_every ? ` and every ${x.scout_every} landings` : ''}`
+ return `heading to "${x.name}" (${x.target}), ${state}; at most ${x.at_once} at once and ${x.per_day} a day, ${scout}.${next}${ran}`
}
export function roundLine(r: Round): string {