git clone https://garage44.eu/jeroen/midas.gitcartopolis-agent · 2026-11-28T16:13:34Z
feat(tree): Goals ▸ Map, every project and the sessions between them The level above one goal's tree (docs/screens/graph.html). graph.rs reads what is recorded: each project's Cargo.toml and package.json for another hosted project's URL, with the pinned commit and how far behind main it is; sessions whose repos hold two projects; techs that need a tech elsewhere. It lays the projects out as the tree does, a column past the deepest one used, those sharing no code apart, and draws the map as SVG. The page shows it at research/map: tap a project for what it uses, what uses it and its stale pins, and open its sessions over time, one stream per related project, a bar per session tied to the other projects it worked in. The site's front page draws the public part for anyone: public projects only, techs built and built lately, no session counts, titles or costs. Which session started which is not recorded yet; the streams draw none.
docs/git-hosting.md | 2 +-
docs/hub.md | 24 ++-
docs/screens/graph.html | 2 +-
src/codeview.rs | 27 ++-
src/graph.rs | 392 ++++++++++++++++++++++++++++++++++++++
src/hub.rs | 6 +
src/main.rs | 1 +
src/tests.rs | 52 +++++
web/src/app.css | 227 ++++++++++++++++++++++
web/src/components/projectmap.tsx | 295 ++++++++++++++++++++++++++++
web/src/components/research.tsx | 11 +-
web/src/lib/api.ts | 14 ++
12 files changed, 1045 insertions(+), 8 deletions(-)
diff --git a/docs/git-hosting.md b/docs/git-hosting.md
index 8a0dd5e..ed8ff1e 100644
--- a/docs/git-hosting.md
+++ b/docs/git-hosting.md
@@ -5,7 +5,7 @@ the hub (`midas project create`, docs/hub.md "Projects the hub hosts"), with the
landing rule on main, LFS uploads, and public pages, clones and archives.
**Steps 2 to 4 done** (2026-11-28, s885): the public pages, clones, archives and
LFS are at Forgejo's own paths (`/<owner>/<name>`), with a front page of the
-public projects at `/`, served at garage44.eu. All twelve repositories were
+public projects at `/` (and since s887 their map, docs/hub.md **Map**), served at garage44.eu. All twelve repositories were
moved in one go with `midas hub import` (Forgejo stopped first, its copies read
from disk; every branch and tag checked identical, 639 LFS objects, none
missing). Port 2222 is the hub's sshd and code.garage44.eu its proxy, so no URL
diff --git a/docs/hub.md b/docs/hub.md
index fabdc8f..afb8d04 100644
--- a/docs/hub.md
+++ b/docs/hub.md
@@ -927,7 +927,29 @@ they land, the one depended on first; or the person's, `tech_edit`): it is
researched one session per project in that order, each landing on its own,
its brief naming its part (`landed_in` keeps what landed), and it is built
once the last lands. The goal's page shows the direction toward it, and the
-goal bar links to Directions with how many go. It is
+goal bar links to Directions with how many go.
+
+**Map** (Goals ▸ Map, `research/map`, designed in `docs/screens/graph.html`,
+`graph.rs`) is the level above one goal's tree: every hosted project at once,
+and only what is recorded between them. An **arrow** is code: a `Cargo.toml`
+or `package.json` on a project's main naming another hosted project by URL
+(`…/<owner>/<name>.git`, or `…/archive/<sha>`), drawn from the project used to
+the one using it, amber when the pin is more than five commits behind that
+project's main, with how far. A **band** is sessions that worked in both
+(their `repos`), a **dashed curve** techs of one that need a tech of another.
+Columns are the tree's: one past the deepest project a project uses; those
+that share no code stand apart. Tapping a project says what it uses and what
+uses it, its sessions and techs and its stale pins, and opens **its sessions
+over time** (`research/map/<owner>/<name>`): a stream for it, for each
+project it uses or that uses it and each other project three or more of
+those sessions also worked in, each session a bar from start to end coloured
+by how it ended, tied to the other projects it worked in, ◆ when it built a
+tech. The hub draws the map (`GET /v1/hosted/graph`: `graph` and `svg`, read
+at most once a minute); the site's **front page** draws its public part for
+anyone (`graph::public`): public projects and the lines between them, techs
+built and what was built lately, never a session's count, title or cost.
+Which session started which is not recorded yet, so the streams draw no such
+line. 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**:
diff --git a/docs/screens/graph.html b/docs/screens/graph.html
index d380cbe..f055be2 100644
--- a/docs/screens/graph.html
+++ b/docs/screens/graph.html
@@ -1,6 +1,6 @@
<!doctype html><meta charset="utf-8"><link rel="stylesheet" href="style.css">
<!-- A design for Goals ▸ Map: every project at once, how they depend on each other, and the sessions between them.
- Drawn before it exists. The numbers are the workspace's own on 2026-11-28 (hub /v1/hosted, /v1/hosted/tree,
+ Drawn before it was built (graph.rs, projectmap.tsx). The numbers are the workspace's own on 2026-11-28 (hub /v1/hosted, /v1/hosted/tree,
each project's Cargo.toml and package.json); the timeline is the real week of 21–28 November around Pinnacle. -->
<style>
body { width:1840px; }
diff --git a/src/codeview.rs b/src/codeview.rs
index dbbcca0..0b8710b 100644
--- a/src/codeview.rs
+++ b/src/codeview.rs
@@ -13,7 +13,8 @@
//! - Forgejo's `src/`, `raw/`, `media/` and `commits/` paths — sent to the above.
//!
//! [`front`] is the site's own front page: the public repositories, for a
-//! visitor who is not logged in to the hub.
+//! visitor who is not logged in to the hub, with the map of which uses which
+//! and what was built in them lately (graph.rs, its public part).
use anyhow::Result;
@@ -43,7 +44,7 @@ const STYLE: &str = "body{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-w
header h1{font-size:1.2rem;margin:.4rem 0}pre{background:#f6f6f6;padding:.8rem;overflow:auto;font-size:13px}\
table{border-collapse:collapse;width:100%}td{padding:.2rem .5rem;border-bottom:1px solid #eee}\
code{background:#f6f6f6;padding:0 .3rem;white-space:nowrap}header code{white-space:normal;overflow-wrap:anywhere}.muted{color:#777}td.muted{white-space:nowrap}\
- header .end{margin-left:auto}";
+ header .end{margin-left:auto}figure.map{margin:1rem 0}figure.map svg{width:100%;height:auto;max-height:70vh}h2{font-size:1rem;margin:1.2rem 0 .4rem}";
fn frame(repo: &str, host: &str, title: &str, body: &str) -> String {
let key = repo.trim_end_matches(".git");
@@ -76,6 +77,8 @@ pub fn front(host: &str) -> String {
body += "</table>";
if rows.is_empty() {
body = "<p class=\"muted\">No public projects yet.</p>".into();
+ } else {
+ body = map() + &body;
}
format!(
"<!doctype html><html lang=\"en\"><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\">\
@@ -85,6 +88,26 @@ pub fn front(host: &str) -> String {
)
}
+/// The public projects as a map, and the techs built in them lately.
+fn map() -> String {
+ let g = crate::graph::public(&crate::graph::all());
+ let mut s = format!("<figure class=\"map\">{}<figcaption class=\"muted\">An arrow runs from a project to one that uses its code, \
+ amber when that one uses an older commit. The ring is the share of its techs built.</figcaption></figure>",
+ crate::graph::svg(&g, Some("/")));
+ let landed = g["landed"].as_array().cloned().unwrap_or_default();
+ if !landed.is_empty() {
+ s += "<h2>Built lately</h2><table>";
+ for l in &landed {
+ let day = l["at"].as_i64().and_then(|t| chrono::DateTime::from_timestamp(t, 0)).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default();
+ let repo = l["repo"].as_str().unwrap_or("");
+ s += &format!("<tr><td class=\"muted\">{}</td><td><a href=\"/{r}\">{n}</a></td><td>{}</td></tr>",
+ esc(&day), esc(l["name"].as_str().unwrap_or("")), r = esc(repo), n = esc(repo.rsplit('/').next().unwrap_or(repo)));
+ }
+ s += "</table>";
+ }
+ s + "<h2>Repositories</h2>"
+}
+
fn query(q: &str, k: &str) -> Option<String> {
q.split('&').find_map(|p| p.strip_prefix(&format!("{k}="))).map(crate::hub::pct_decode)
}
diff --git a/src/graph.rs b/src/graph.rs
new file mode 100644
index 0000000..3b24271
--- /dev/null
+++ b/src/graph.rs
@@ -0,0 +1,392 @@
+//! Goals ▸ Map (docs/screens/graph.html): every project at once, which one's
+//! code another uses, the sessions that worked in two, and the techs in one that
+//! need a tech in another. The page draws it at `/v1/hosted/graph`, and the
+//! site's front page draws the public part of it for anyone ([`public`]).
+//!
+//! Every line is something recorded, never guessed:
+//! - **code**: a `Cargo.toml` or `package.json` on a project's main branch naming
+//! another hosted project by URL (`https://<host>/<owner>/<name>.git` or
+//! `…/<owner>/<name>/archive/<sha>.tar.gz`), with the pinned commit and how far
+//! behind its main that pin is;
+//! - **shared**: sessions whose `repos` hold both;
+//! - **needs**: a tech of one project's that needs a tech of another's.
+//!
+//! The layout is the tree's: a project's column is one past the deepest project
+//! whose code it uses, rows untangled by the mean row of what they use. Projects
+//! that share no code with any other stand apart, in a column of their own.
+
+use std::collections::{BTreeMap, BTreeSet};
+use std::process::Command;
+use std::sync::Mutex;
+use std::time::{Duration, Instant};
+
+use serde_json::{json, Value};
+
+use crate::hosted;
+
+/// How long one reading is served again: the front page is public, and every
+/// reading runs git over every repository.
+const FRESH: Duration = Duration::from_secs(60);
+
+/// The last reading, with when and of which hub (its registry root: tests run several).
+static CACHE: Mutex<Option<(Instant, std::path::PathBuf, Value)>> = Mutex::new(None);
+
+fn git(repo: &str, args: &[&str]) -> Option<String> {
+ let out = Command::new("git").arg("-C").arg(hosted::path(repo)).args(args).output().ok()?;
+ out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
+}
+
+/// One project's use of another's code, as its manifests say it.
+#[derive(Debug, Clone, PartialEq)]
+pub struct Use {
+ pub from: String,
+ pub rev: Option<String>,
+ pub file: String,
+}
+
+/// What `text` (a manifest at `file`) names of the projects in `known`: each
+/// URL `https://<host>/<owner>/<name>` followed by `.git` or `/archive/<sha>`,
+/// with the commit a `rev = "…"` on the same line, or the archive's, pins.
+pub fn uses(text: &str, file: &str, known: &BTreeSet<String>) -> Vec<Use> {
+ let mut out: Vec<Use> = Vec::new();
+ for line in text.lines() {
+ let mut rest = line;
+ while let Some(at) = rest.find("https://") {
+ rest = &rest[at + 8..];
+ let url: String = rest.chars().take_while(|c| !matches!(c, '"' | '\'' | ' ' | ',' | '}' | '#')).collect();
+ let mut parts = url.splitn(4, '/');
+ let (_, Some(owner), Some(name)) = (parts.next(), parts.next(), parts.next()) else { continue };
+ let after = parts.next().unwrap_or("");
+ let (name, rev) = if let Some(n) = name.strip_suffix(".git") {
+ let rev = ["rev = \"", "rev=\""].iter().find_map(|k| line.split_once(k)).and_then(|(_, r)| r.split('"').next()).map(str::to_string);
+ (n, rev)
+ } else if let Some(sha) = after.strip_prefix("archive/") {
+ (name, Some(sha.trim_end_matches(".tar.gz").to_string()))
+ } else {
+ continue;
+ };
+ let key = format!("{owner}/{name}");
+ if known.contains(&key) && !out.iter().any(|u| u.from == key && u.rev == rev) {
+ out.push(Use { from: key, rev, file: file.to_string() });
+ }
+ }
+ }
+ out
+}
+
+/// Every manifest of `repo`'s main branch, and what each names.
+fn uses_of(repo: &str, known: &BTreeSet<String>) -> Vec<Use> {
+ let Some(files) = git(repo, &["ls-tree", "-r", "--name-only", "HEAD"]) else { return vec![] };
+ let mut out: Vec<Use> = Vec::new();
+ for f in files.lines().filter(|f| f.ends_with("Cargo.toml") || f.ends_with("package.json")).filter(|f| !f.contains("node_modules/")) {
+ let Some(text) = git(repo, &["cat-file", "blob", &format!("HEAD:{f}")]) else { continue };
+ for u in uses(&text, f, known) {
+ if u.from != repo && !out.iter().any(|x| x.from == u.from && x.rev == u.rev) {
+ out.push(u);
+ }
+ }
+ }
+ out
+}
+
+/// How many commits of `repo`'s main are not in `rev`; none when the hub does not have `rev`.
+fn behind(repo: &str, rev: &str) -> Option<u64> {
+ if rev.starts_with('-') || !rev.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '_' | '/')) {
+ return None;
+ }
+ git(repo, &["rev-list", "--count", &format!("{rev}..HEAD")])?.parse().ok()
+}
+
+/// Columns and rows: a project's column is one past the deepest it uses; projects with no code line stand
+/// apart in the last column. Rows by the mean row of what a project uses, three passes, ties by size.
+pub fn layout(names: &[String], code: &[(String, String)], size: &BTreeMap<String, u64>) -> BTreeMap<String, (usize, usize)> {
+ let linked: BTreeSet<&String> = code.iter().flat_map(|(a, b)| [a, b]).collect();
+ let mut depth: BTreeMap<&String, usize> = names.iter().map(|n| (n, 0)).collect();
+ // Longest path, bounded by the number of projects so a cycle cannot loop for ever.
+ for _ in 0..names.len() {
+ let mut moved = false;
+ for (a, b) in code {
+ let d = depth.get(a).copied().unwrap_or(0) + 1;
+ if depth.get(b).is_some_and(|&x| x < d) && d < names.len() {
+ depth.insert(b, d);
+ moved = true;
+ }
+ }
+ if !moved {
+ break;
+ }
+ }
+ let apart = linked.iter().map(|n| depth[*n]).max().map(|d| d + 1).unwrap_or(0);
+ let col = |n: &String| if linked.contains(n) { depth[n] } else { apart };
+ let mut cols: BTreeMap<usize, Vec<String>> = BTreeMap::new();
+ for n in names {
+ cols.entry(col(n)).or_default().push(n.clone());
+ }
+ for c in cols.values_mut() {
+ c.sort_by(|a, b| size.get(b).cmp(&size.get(a)).then(a.cmp(b)));
+ }
+ let mut row: BTreeMap<String, f64> = BTreeMap::new();
+ for c in cols.values() {
+ for (i, n) in c.iter().enumerate() {
+ row.insert(n.clone(), i as f64);
+ }
+ }
+ for _ in 0..3 {
+ for (&k, c) in cols.iter_mut() {
+ if k == 0 || k == apart {
+ continue;
+ }
+ let mean = |n: &String| {
+ let up: Vec<f64> = code.iter().filter(|(_, b)| b == n).filter_map(|(a, _)| row.get(a).copied()).collect();
+ if up.is_empty() { row[n] } else { up.iter().sum::<f64>() / up.len() as f64 }
+ };
+ let mut keyed: Vec<(f64, String)> = c.iter().map(|n| (mean(n), n.clone())).collect();
+ keyed.sort_by(|a, b| a.0.total_cmp(&b.0).then(size.get(&b.1).cmp(&size.get(&a.1))));
+ *c = keyed.into_iter().map(|(_, n)| n).collect();
+ for (i, n) in c.iter().enumerate() {
+ row.insert(n.clone(), i as f64);
+ }
+ }
+ }
+ // The apart ones wrap into columns no taller than the tallest linked one (at least three), so the map
+ // stays as wide as it is tall rather than one long column.
+ let tall = cols.iter().filter(|(&k, _)| k != apart).map(|(_, c)| c.len()).max().unwrap_or(0).max(3);
+ let loners = cols.remove(&apart).unwrap_or_default();
+ let mut at: BTreeMap<String, (usize, usize)> =
+ cols.into_iter().flat_map(|(k, c)| c.into_iter().enumerate().map(move |(i, n)| (n, (k, i)))).collect();
+ for (i, n) in loners.into_iter().enumerate() {
+ at.insert(n, (apart + i / tall, i % tall));
+ }
+ at
+}
+
+/// The whole map, as recorded now.
+fn read() -> Value {
+ let repos = hosted::repos();
+ let known: BTreeSet<String> = repos.keys().cloned().collect();
+ let sessions = crate::sessions::list();
+ let mut count: BTreeMap<String, u64> = BTreeMap::new();
+ let mut shared: BTreeMap<(String, String), u64> = BTreeMap::new();
+ for s in sessions.as_array().into_iter().flatten() {
+ let mut rs: Vec<String> = s["repos"].as_array().into_iter().flatten().filter_map(|r| r.as_str()).map(str::to_string).collect();
+ if rs.is_empty() {
+ rs.extend(s["repo"].as_str().map(str::to_string));
+ }
+ rs.retain(|r| known.contains(r));
+ rs.sort();
+ rs.dedup();
+ for r in &rs {
+ *count.entry(r.clone()).or_default() += 1;
+ }
+ for (i, a) in rs.iter().enumerate() {
+ for b in &rs[i + 1..] {
+ *shared.entry((a.clone(), b.clone())).or_default() += 1;
+ }
+ }
+ }
+ // Techs: how many each project has and has built, which need another project's, and the last built.
+ let tree = crate::tree::all();
+ let techs = tree["techs"].as_array().cloned().unwrap_or_default();
+ let home = |t: &Value| t["repos"][0].as_str().map(str::to_string);
+ let mut built: BTreeMap<String, (u64, u64)> = BTreeMap::new();
+ let mut needs: BTreeMap<(String, String), u64> = BTreeMap::new();
+ let mut landed: Vec<Value> = Vec::new();
+ for t in techs.iter().filter(|t| t["state"] != "dropped") {
+ let Some(r) = home(t) else { continue };
+ let e = built.entry(r.clone()).or_default();
+ e.0 += 1;
+ if t["state"] == "built" {
+ e.1 += 1;
+ // What the scout found already there is built, but it did not land then.
+ if t["built_by"] != "scout" {
+ if let Some(at) = t["built_at"].as_i64() {
+ landed.push(json!({"name": t["name"], "repo": r, "at": at}));
+ }
+ }
+ }
+ for n in t["needs"].as_array().into_iter().flatten() {
+ if let Some(from) = techs.iter().find(|x| &x["id"] == n).and_then(home).filter(|f| *f != r) {
+ *needs.entry((from, r.clone())).or_default() += 1;
+ }
+ }
+ }
+ landed.sort_by_key(|l| std::cmp::Reverse(l["at"].as_i64().unwrap_or(0)));
+ let mut code: Vec<Value> = Vec::new();
+ for r in &known {
+ for u in uses_of(r, &known) {
+ let lag = u.rev.as_deref().and_then(|rev| behind(&u.from, rev));
+ code.push(json!({"from": u.from, "to": r, "rev": u.rev, "file": u.file, "behind": lag}));
+ }
+ }
+ let names: Vec<String> = known.iter().cloned().collect();
+ let pairs: Vec<(String, String)> = code.iter().map(|c| (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string())).collect();
+ let at = layout(&names, &pairs, &count);
+ let projects: Vec<Value> = names.iter().map(|n| {
+ let (techs, built) = built.get(n).copied().unwrap_or_default();
+ let (col, row) = at[n];
+ json!({"name": n, "public": repos[n]["visibility"] == "public", "description": repos[n]["description"],
+ "sessions": count.get(n).copied().unwrap_or(0), "techs": techs, "built": built, "col": col, "row": row})
+ }).collect();
+ json!({
+ "projects": projects,
+ "code": code,
+ "shared": shared.into_iter().map(|((a, b), n)| json!({"a": a, "b": b, "n": n})).collect::<Vec<_>>(),
+ "needs": needs.into_iter().map(|((from, to), n)| json!({"from": from, "to": to, "n": n})).collect::<Vec<_>>(),
+ "landed": landed.into_iter().take(40).collect::<Vec<_>>(),
+ })
+}
+
+/// The map, read at most once a minute.
+pub fn all() -> Value {
+ let mut c = CACHE.lock().unwrap_or_else(|p| p.into_inner());
+ let root = crate::registry::root();
+ if let Some((_, _, v)) = c.as_ref().filter(|(at, r, _)| at.elapsed() < FRESH && *r == root) {
+ return v.clone();
+ }
+ let v = read();
+ *c = Some((Instant::now(), root, v.clone()));
+ v
+}
+
+/// What anyone may see of `g`: public projects only, and only lines between two of them; no session
+/// counts (sessions are the workspace's), techs and what landed when.
+pub fn public(g: &Value) -> Value {
+ let open: BTreeSet<&str> = g["projects"].as_array().into_iter().flatten()
+ .filter(|p| p["public"] == true).filter_map(|p| p["name"].as_str()).collect();
+ let both = |a: &Value, b: &Value| a.as_str().is_some_and(|a| open.contains(a)) && b.as_str().is_some_and(|b| open.contains(b));
+ let names: Vec<String> = open.iter().map(|s| s.to_string()).collect();
+ let code: Vec<Value> = g["code"].as_array().into_iter().flatten().filter(|c| both(&c["from"], &c["to"])).cloned().collect();
+ let pairs: Vec<(String, String)> = code.iter().map(|c| (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string())).collect();
+ let size: BTreeMap<String, u64> = g["projects"].as_array().into_iter().flatten()
+ .filter_map(|p| Some((p["name"].as_str()?.to_string(), p["techs"].as_u64().unwrap_or(0)))).collect();
+ let at = layout(&names, &pairs, &size);
+ let projects: Vec<Value> = g["projects"].as_array().into_iter().flatten().filter(|p| p["name"].as_str().is_some_and(|n| open.contains(n)))
+ .map(|p| {
+ let (col, row) = at[p["name"].as_str().unwrap_or("")];
+ json!({"name": p["name"], "public": true, "description": p["description"], "techs": p["techs"], "built": p["built"], "col": col, "row": row})
+ }).collect();
+ json!({
+ "projects": projects,
+ "code": code,
+ "shared": [],
+ "needs": [],
+ "landed": g["landed"].as_array().into_iter().flatten().filter(|l| l["repo"].as_str().is_some_and(|r| open.contains(r))).take(12).cloned().collect::<Vec<_>>(),
+ })
+}
+
+fn esc(s: &str) -> String {
+ s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
+}
+
+/// Pins further behind than this are drawn amber.
+const STALE: u64 = 5;
+const COL_W: f64 = 230.0;
+const ROW_H: f64 = 150.0;
+
+/// The map as SVG, no script: each project a circle sized by its sessions (or, public, its techs), a ring
+/// for the share built, arrows from the project used to the one using it. With `link`, each project is a
+/// link to `link` + its name; else it carries `data-project` for the page to catch a tap.
+pub fn svg(g: &Value, link: Option<&str>) -> String {
+ let ps: Vec<&Value> = g["projects"].as_array().map(|a| a.iter().collect()).unwrap_or_default();
+ let cols = ps.iter().filter_map(|p| p["col"].as_u64()).max().map(|c| c + 1).unwrap_or(1) as f64;
+ let rows = ps.iter().filter_map(|p| p["row"].as_u64()).max().map(|r| r + 1).unwrap_or(1) as f64;
+ // Room below for the odd columns, set a quarter row lower, and a name under its circle.
+ let (w, h) = (cols * COL_W + 40.0, rows * ROW_H + ROW_H * 0.25 + 40.0);
+ let pos = |name: &str| ps.iter().find(|p| p["name"] == name).map(|p| {
+ let (c, r) = (p["col"].as_f64().unwrap_or(0.0), p["row"].as_f64().unwrap_or(0.0));
+ // Odd columns sit half a row lower, so a line across two columns passes between, not through.
+ (20.0 + COL_W * (c + 0.5), 20.0 + ROW_H * (r + 0.5) + if c as u64 % 2 == 1 { ROW_H * 0.25 } else { 0.0 })
+ });
+ let weight = |p: &Value| p["sessions"].as_f64().filter(|_| link.is_none()).unwrap_or(p["techs"].as_f64().unwrap_or(0.0) * 4.0);
+ let short = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string();
+ let radius = |name: &str| ps.iter().find(|p| p["name"] == name).map(|p| 16.0 + 5.0 * (1.0 + weight(p)).log2()).unwrap_or(20.0);
+ let col = |name: &str| ps.iter().find(|p| p["name"] == name).and_then(|p| p["col"].as_f64()).unwrap_or(0.0);
+ let mut s = format!(
+ "<svg class=\"pmap\" viewBox=\"0 0 {w} {h}\" xmlns=\"http://www.w3.org/2000/svg\" font-family=\"system-ui,sans-serif\" role=\"img\" aria-label=\"The projects and which uses which\">\
+ <defs><marker id=\"pm-a\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto\"><path d=\"M0,0L10,5L0,10z\" fill=\"#2f7f7a\"/></marker>\
+ <marker id=\"pm-o\" viewBox=\"0 0 10 10\" refX=\"9\" refY=\"5\" markerWidth=\"7\" markerHeight=\"7\" orient=\"auto\"><path d=\"M0,0L10,5L0,10z\" fill=\"#c79a3c\"/></marker></defs>");
+ for x in g["shared"].as_array().into_iter().flatten() {
+ let (Some(a), Some(b)) = (pos(x["a"].as_str().unwrap_or("")), pos(x["b"].as_str().unwrap_or(""))) else { continue };
+ let n = x["n"].as_f64().unwrap_or(1.0);
+ s += &format!("<line x1=\"{:.0}\" y1=\"{:.0}\" x2=\"{:.0}\" y2=\"{:.0}\" stroke=\"#cfe0df\" stroke-width=\"{:.1}\" stroke-linecap=\"round\" opacity=\".8\"><title>{} sessions in both</title></line>",
+ a.0, a.1, b.0, b.1, 2.0 + 2.0 * n.sqrt(), n);
+ }
+ for x in g["needs"].as_array().into_iter().flatten() {
+ let (Some(a), Some(b)) = (pos(x["from"].as_str().unwrap_or("")), pos(x["to"].as_str().unwrap_or(""))) else { continue };
+ // Bent to the left of its way, so the two ways between one pair are two curves.
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let d = (dx * dx + dy * dy).sqrt().max(1.0);
+ let (mx, my) = ((a.0 + b.0) / 2.0 + dy / d * 45.0, (a.1 + b.1) / 2.0 - dx / d * 45.0);
+ let to = short(x["to"].as_str().unwrap_or(""));
+ s += &format!("<path d=\"M{:.0},{:.0} Q{mx:.0},{my:.0} {:.0},{:.0}\" fill=\"none\" stroke=\"#8f6fc4\" stroke-width=\"1.6\" stroke-dasharray=\"5 4\" opacity=\".8\"><title>{n} techs of {} need one of {}</title></path>\
+ <text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11\" fill=\"#8f6fc4\">{n} techs</text>",
+ a.0, a.1, b.0, b.1, esc(&to), esc(&short(x["from"].as_str().unwrap_or(""))), (a.0 + b.0) / 4.0 + mx / 2.0, (a.1 + b.1) / 4.0 + my / 2.0 + 4.0, n = x["n"]);
+ }
+ // One arrow per pair: amber when its oldest pin is stale, labelled with how far.
+ let mut arrows: BTreeMap<(String, String), Option<u64>> = BTreeMap::new();
+ for c in g["code"].as_array().into_iter().flatten() {
+ let k = (c["from"].as_str().unwrap_or("").to_string(), c["to"].as_str().unwrap_or("").to_string());
+ let e = arrows.entry(k).or_default();
+ *e = (*e).max(c["behind"].as_u64());
+ }
+ for ((from, to), lag) in &arrows {
+ let (Some(a), Some(b)) = (pos(from), pos(to)) else { continue };
+ let (dx, dy) = (b.0 - a.0, b.1 - a.1);
+ let d = (dx * dx + dy * dy).sqrt().max(1.0);
+ // An arrow over a column bends round what stands in it.
+ let span = (col(to) - col(from)).abs();
+ let bend = if span > 1.0 { (span - 1.0) * ROW_H * 0.5 } else { 0.0 };
+ let c = ((a.0 + b.0) / 2.0 + dy / d * bend, (a.1 + b.1) / 2.0 - dx / d * bend);
+ let unit = |p: (f64, f64), q: (f64, f64)| {
+ let l = ((q.0 - p.0).powi(2) + (q.1 - p.1).powi(2)).sqrt().max(1.0);
+ ((q.0 - p.0) / l, (q.1 - p.1) / l)
+ };
+ let (ua, ub) = (unit(a, c), unit(c, b));
+ let (ra, rb) = (radius(from), radius(to) + 4.0);
+ let (x1, y1, x2, y2) = (a.0 + ua.0 * ra, a.1 + ua.1 * ra, b.0 - ub.0 * rb, b.1 - ub.1 * rb);
+ let stale = lag.is_some_and(|l| l > STALE);
+ s += &format!("<path d=\"M{x1:.0},{y1:.0} Q{:.0},{:.0} {x2:.0},{y2:.0}\" fill=\"none\" stroke=\"{}\" stroke-width=\"2.5\" marker-end=\"url(#pm-{})\"><title>{} uses {}'s code</title></path>",
+ c.0, c.1, if stale { "#c79a3c" } else { "#2f7f7a" }, if stale { "o" } else { "a" }, esc(&short(to)), esc(&short(from)));
+ if let Some(l) = lag.filter(|&l| l > 0) {
+ s += &format!("<text x=\"{:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11\" font-weight=\"600\" fill=\"{}\" stroke=\"#fff\" stroke-width=\"4\" stroke-linejoin=\"round\" paint-order=\"stroke\">{l} behind</text>",
+ (x1 + x2) / 4.0 + c.0 / 2.0, (y1 + y2) / 4.0 + c.1 / 2.0 - 5.0, if stale { "#8a6214" } else { "#6b8183" });
+ }
+ }
+ for p in &ps {
+ let name = p["name"].as_str().unwrap_or("");
+ let Some((x, y)) = pos(name) else { continue };
+ let r = radius(name);
+ let (techs, built) = (p["techs"].as_u64().unwrap_or(0), p["built"].as_u64().unwrap_or(0));
+ // A name wider than its circle goes under it.
+ let inside = short(name).len() as f64 * 7.4 < 2.0 * r - 8.0;
+ let open = match link {
+ Some(l) => format!("<a href=\"{}{}\">", esc(l), esc(name)),
+ None => format!("<g class=\"pmap__p\" data-project=\"{}\" tabindex=\"0\">", esc(name)),
+ };
+ s += &open;
+ s += &format!("<circle cx=\"{x:.0}\" cy=\"{y:.0}\" r=\"{r:.0}\" fill=\"#fff\" stroke=\"#dfe7e7\" stroke-width=\"2\"/>");
+ if techs > 0 {
+ let rr = r - 5.0;
+ let f = built as f64 / techs as f64;
+ let a = std::f64::consts::TAU * f.min(0.9999);
+ s += &format!("<circle cx=\"{x:.0}\" cy=\"{y:.0}\" r=\"{rr:.0}\" fill=\"none\" stroke=\"#e3eaea\" stroke-width=\"4\"/>");
+ if built > 0 {
+ s += &format!("<path d=\"M{x:.1},{:.1} A{rr:.1},{rr:.1} 0 {} 1 {:.1},{:.1}\" fill=\"none\" stroke=\"#2f8f5b\" stroke-width=\"4\" stroke-linecap=\"round\"/>",
+ y - rr, u8::from(f > 0.5), x + rr * a.sin(), y - rr * a.cos());
+ }
+ }
+ let under = if link.is_some() {
+ if techs > 0 { format!("{built} of {techs} techs built") } else { String::new() }
+ } else {
+ let n = p["sessions"].as_u64().unwrap_or(0);
+ format!("{n} session{}{}", if n == 1 { "" } else { "s" }, if techs > 0 { format!(" · {built}/{techs}") } else { String::new() })
+ };
+ s += &format!("<text x=\"{x:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"13.5\" font-weight=\"600\" fill=\"#1d2a2c\" stroke=\"#fff\" stroke-width=\"4\" stroke-linejoin=\"round\" paint-order=\"stroke\">{}</text>",
+ if inside { y + 4.5 } else { y + r + 16.0 }, esc(&short(name)));
+ s += &format!("<text x=\"{x:.0}\" y=\"{:.0}\" text-anchor=\"middle\" font-size=\"11.5\" fill=\"#6b8183\">{}</text>",
+ y + r + if inside { 15.0 } else { 30.0 }, esc(&under));
+ s += if link.is_some() { "</a>" } else { "</g>" };
+ }
+ s += "</svg>";
+ s
+}
diff --git a/src/hub.rs b/src/hub.rs
index ebf3004..4da0afe 100644
--- a/src/hub.rs
+++ b/src/hub.rs
@@ -632,6 +632,12 @@ fn api(method: &str, path: &str, query: &str, body: &Value, who: &Who, peer: &st
// What the autopilot reads of the person when it decides in a session: their rules, earlier answers, cap.
("GET", "focus/pilot") => return Ok((200, crate::focus::pilot_context(&q("session").unwrap_or_default())?)),
("GET", "hosted") => return Ok((200, crate::sessions::list())),
+ // Goals ▸ Map: every project, which uses which, and the sessions between them (graph.rs), drawn.
+ ("GET", "hosted/graph") => {
+ let g = crate::graph::all();
+ let svg = crate::graph::svg(&g, None);
+ return Ok((200, json!({"graph": g, "svg": svg})));
+ }
// The sessions runners: each now, and their starts, stops and absences (runners.rs).
("GET", "runners") => return Ok((200, crate::runners::read(since_q(q("since"))))),
("GET", "hosted/search") => {
diff --git a/src/main.rs b/src/main.rs
index 0dda97b..6f5ae5b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -35,6 +35,7 @@ mod hook;
mod host;
mod hub;
mod codeview;
+mod graph;
mod hosted;
mod hubsetup;
mod import;
diff --git a/src/tests.rs b/src/tests.rs
index bd22a51..cdfeb28 100644
--- a/src/tests.rs
+++ b/src/tests.rs
@@ -3005,6 +3005,58 @@ fn a_public_repository_has_pages_and_a_private_one_none() {
assert!(front.contains("href=\"/acme/open\"") && !front.contains("acme/shut") && front.contains("/login"), "{front}");
}
+#[test]
+fn a_manifest_names_the_projects_it_uses_and_the_commit_it_pins() {
+ let known: std::collections::BTreeSet<String> = ["acme/lib", "acme/app"].map(String::from).into();
+ let cargo = "[dependencies]\nlib = { git = \"https://code.example/acme/lib.git\", rev = \"c76404c7\", optional = true }\n\
+ lib_style = { git = \"https://code.example/acme/lib.git\", rev = \"c76404c7\" }\n\
+ other = { git = \"https://github.com/acme/other.git\" }\nrepository = \"https://code.example/acme/app\"\n";
+ let u = crate::graph::uses(cargo, "Cargo.toml", &known);
+ assert_eq!(u, vec![crate::graph::Use { from: "acme/lib".into(), rev: Some("c76404c7".into()), file: "Cargo.toml".into() }], "one pin, once");
+ let pkg = "{\"dependencies\": {\"@acme/lib\": \"https://code.example/acme/lib/archive/5ef10eb3.tar.gz\"}}";
+ assert_eq!(crate::graph::uses(pkg, "web/package.json", &known)[0].rev.as_deref(), Some("5ef10eb3"));
+ assert!(crate::graph::uses("lib = { git = \"https://code.example/acme/lib.git\", branch = \"main\" }", "Cargo.toml", &known)[0].rev.is_none());
+}
+
+#[test]
+fn the_map_puts_a_project_one_column_past_what_it_uses_and_the_loners_apart() {
+ let names: Vec<String> = ["a/ui", "a/lang", "a/editor", "a/os", "a/web", "a/alone"].map(String::from).into();
+ let code: Vec<(String, String)> = [("a/ui", "a/os"), ("a/ui", "a/editor"), ("a/lang", "a/os"), ("a/editor", "a/os"), ("a/ui", "a/web")]
+ .map(|(a, b)| (a.to_string(), b.to_string())).into();
+ let at = crate::graph::layout(&names, &code, &Default::default());
+ let col = |n: &str| at[n].0;
+ assert_eq!((col("a/ui"), col("a/lang"), col("a/editor"), col("a/web"), col("a/os")), (0, 0, 1, 1, 2));
+ assert_eq!(col("a/alone"), 3, "no code shared: a column of its own");
+ // Many such wrap into columns no taller than three, rather than one long one.
+ let more: Vec<String> = names.iter().cloned().chain(["a/b", "a/c", "a/d"].map(String::from)).collect();
+ let wrapped = crate::graph::layout(&more, &code, &Default::default());
+ assert_eq!(wrapped.values().filter(|(c, _)| *c == 3).count(), 3);
+ assert_eq!(wrapped.values().filter(|(c, _)| *c == 4).count(), 1);
+ // A cycle ends, wherever it puts them.
+ let ring: Vec<(String, String)> = [("a/ui", "a/os"), ("a/os", "a/ui")].map(|(a, b)| (a.to_string(), b.to_string())).into();
+ assert_eq!(crate::graph::layout(&names, &ring, &Default::default()).len(), names.len());
+}
+
+#[test]
+fn the_public_map_has_public_projects_only_and_no_sessions() {
+ let g = serde_json::json!({
+ "projects": [{"name": "a/os", "public": true, "sessions": 40, "techs": 10, "built": 4, "col": 1, "row": 0},
+ {"name": "a/ui", "public": true, "sessions": 9, "techs": 2, "built": 2, "col": 0, "row": 0},
+ {"name": "a/site", "public": false, "sessions": 4, "techs": 3, "built": 1, "col": 2, "row": 0}],
+ "code": [{"from": "a/ui", "to": "a/os", "behind": 30}, {"from": "a/os", "to": "a/site", "behind": 0}],
+ "shared": [{"a": "a/os", "b": "a/ui", "n": 7}],
+ "needs": [{"from": "a/os", "to": "a/site", "n": 3}],
+ "landed": [{"name": "Secret page", "repo": "a/site", "at": 2}, {"name": "Boot", "repo": "a/os", "at": 1}],
+ });
+ let p = crate::graph::public(&g);
+ let text = p.to_string();
+ assert!(!text.contains("a/site") && !text.contains("Secret") && !text.contains("\"sessions\""), "{text}");
+ assert_eq!(p["code"].as_array().unwrap().len(), 1);
+ let svg = crate::graph::svg(&p, Some("/"));
+ assert!(svg.contains("href=\"/a/os\"") && svg.contains("30 behind") && svg.contains("#c79a3c"), "a stale pin is amber: {svg}");
+ assert!(!crate::graph::svg(&g, None).contains("href="), "the page's map carries data-project, not links");
+}
+
#[test]
fn a_forgejo_project_is_imported_with_its_branches_and_its_landing_but_not_its_deploys() {
let _g = SERIAL.lock().unwrap();
diff --git a/web/src/app.css b/web/src/app.css
index c160410..0a04ba5 100644
--- a/web/src/app.css
+++ b/web/src/app.css
@@ -9620,3 +9620,230 @@ button.tree-lane__name:hover {
flex-basis: 100%;
order: 2;
}
+
+/* Goals ▸ Map (projectmap.tsx). The drawing is the hub's (graph.rs `svg`, also the public front page's), in
+ light colours as attributes; here the theme's colours override them, which CSS may over presentation attributes. */
+.pmap {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: var(--m-space-2);
+}
+.pmap__drawing {
+ overflow-x: auto;
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius);
+ background: var(--m-surface-sunken);
+}
+.pmap__drawing svg {
+ display: block;
+ min-width: 720px;
+ width: 100%;
+ height: auto;
+ max-height: 72vh;
+}
+.pmap__drawing circle[fill='#fff'] {
+ fill: var(--m-surface);
+ stroke: var(--m-border-strong);
+}
+.pmap__drawing text[fill='#1d2a2c'] {
+ fill: var(--m-text-strong);
+}
+.pmap__drawing text[fill='#6b8183'] {
+ fill: var(--m-text-dim);
+}
+.pmap__drawing line[stroke='#cfe0df'] {
+ stroke: var(--m-border-strong);
+ opacity: 0.45;
+}
+.pmap__p {
+ cursor: pointer;
+}
+.pmap__p:hover circle:first-child,
+.pmap__p:focus circle:first-child {
+ stroke: var(--m-accent);
+ stroke-width: 3;
+ outline: none;
+}
+.pmap-card {
+ position: absolute;
+ top: var(--m-space-2);
+ right: var(--m-space-2);
+ width: 320px;
+}
+.pmap-card__facts {
+ display: grid;
+ grid-template-columns: auto 1fr;
+ gap: 2px 12px;
+ margin: 0 0 var(--m-space-2);
+ font-size: var(--m-font-size-sm);
+}
+.pmap-card__facts dt {
+ color: var(--m-text-dim);
+}
+.pmap-card__facts dd {
+ margin: 0;
+}
+.pmap-card__warn {
+ margin: 0 0 var(--m-space-1);
+ color: var(--m-warning);
+ font-size: var(--m-font-size-sm);
+}
+.pmap-legend {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 6px 18px;
+ align-items: center;
+}
+.pmap-legend i {
+ display: inline-block;
+ width: 26px;
+ margin-right: 6px;
+ vertical-align: middle;
+}
+.pmap-legend__code {
+ border-top: 2.5px solid #2f7f7a;
+}
+.pmap-legend__stale {
+ border-top: 2.5px solid #c79a3c;
+}
+.pmap-legend__shared {
+ height: 6px;
+ border-radius: 3px;
+ background: var(--m-border-strong);
+}
+.pmap-legend__needs {
+ border-top: 2px dashed #8f6fc4;
+}
+/* A phone gets the map as a list, as the tree gets its outline. */
+.pmap-list {
+ display: none;
+}
+.pweek {
+ overflow-x: auto;
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius);
+ background: var(--m-surface-sunken);
+}
+.pweek__svg {
+ display: block;
+}
+.pweek__range {
+ display: inline-flex;
+ gap: 2px;
+ margin-left: auto;
+}
+.pweek__tick {
+ stroke: var(--m-border);
+}
+.pweek__date {
+ fill: var(--m-text-faint);
+ font-size: 11.5px;
+}
+.pweek__stream {
+ fill: var(--m-surface);
+ stroke: var(--m-border);
+}
+.pweek__stream.on {
+ fill: var(--m-accent-soft);
+}
+.pweek__name {
+ fill: var(--m-text-strong);
+ font-size: 13px;
+ font-weight: 600;
+}
+.pweek__name.dim {
+ fill: var(--m-text-faint);
+}
+.pweek__s {
+ cursor: pointer;
+}
+.pweek__s.landed {
+ --c: #2f8f8a;
+}
+.pweek__s.ended {
+ --c: var(--m-text-faint);
+}
+.pweek__s.working {
+ --c: #e6a93c;
+}
+.pweek__bar,
+.pweek__dot {
+ fill: var(--c);
+}
+.pweek__s:hover .pweek__bar {
+ stroke: var(--m-text-strong);
+ stroke-width: 1.5;
+}
+.pweek__tie {
+ stroke: var(--c);
+ stroke-width: 1;
+ opacity: 0.5;
+}
+.pweek__built {
+ fill: var(--m-accent);
+ font-size: 11px;
+}
+.pweek__key {
+ height: 8px;
+ border-radius: 4px;
+}
+.pweek__key.landed {
+ background: #2f8f8a;
+}
+.pweek__key.ended {
+ background: var(--m-text-faint);
+}
+.pweek__key.working {
+ background: #e6a93c;
+}
+@media (max-width: 760px) {
+ .pmap__drawing {
+ display: none;
+ }
+ .pmap-list {
+ display: flex;
+ flex-direction: column;
+ gap: var(--m-space-1);
+ }
+ .pmap-list__p {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ padding: var(--m-space-2);
+ border: 1px solid var(--m-border);
+ border-radius: var(--m-radius);
+ background: var(--m-surface);
+ color: var(--m-text);
+ font: inherit;
+ font-size: var(--m-font-size-sm);
+ text-align: left;
+ }
+ .pmap-list__p.on {
+ border-color: var(--m-accent);
+ }
+ .pmap-card {
+ position: static;
+ width: auto;
+ }
+}
+.pmap__drawing text[stroke='#fff'] {
+ stroke: var(--m-surface-sunken);
+}
+.pweek__svg {
+ width: 100%;
+ min-width: 900px;
+ height: auto;
+}
+.pmap {
+ min-width: 0;
+}
+@media (max-width: 760px) {
+ .pmap__beside {
+ display: none;
+ }
+ .pmap-list__p {
+ width: 100%;
+ box-sizing: border-box;
+ }
+}
diff --git a/web/src/components/projectmap.tsx b/web/src/components/projectmap.tsx
new file mode 100644
index 0000000..a97044c
--- /dev/null
+++ b/web/src/components/projectmap.tsx
@@ -0,0 +1,295 @@
+import m from '@garage44/mithril'
+import {Button, Card} from '@garage44/mithril/components'
+
+import {api} from '@/lib/api'
+import type {ProjectGraph, TreeState} from '@/lib/api'
+import {local} from '@/lib/reactive'
+import {go} from '@/lib/route'
+import {hosted, type Hosted} from '@/lib/stream'
+import {reposOf, show} from '@/lib/projects'
+
+/**
+ * Goals ▸ Map (docs/screens/graph.html): every project at once, which one's code another uses, the
+ * sessions between them; and, zoomed in, one project's sessions over time beside the projects it is
+ * built on. The map is drawn by the hub (graph.rs `svg`, the same drawing the public front page shows);
+ * the week is drawn here from the sessions the page already follows.
+ */
+
+const state = local({
+ graph: null as ProjectGraph | null,
+ svg: '',
+ error: '',
+ loading: false,
+ picked: '',
+ days: 7,
+})
+
+function load() {
+ if (state.loading) return
+ state.loading = true
+ api.graph()
+ .then((r) => {
+ state.graph = r.graph
+ state.svg = r.svg
+ state.error = ''
+ })
+ .catch((e: Error) => (state.error = e.message))
+ .finally(() => (state.loading = false))
+}
+
+const short = (repo: string) => repo.split('/').pop() ?? repo
+
+/** What `p` is built on, and what is built on it, by code. */
+const usesOf = (g: ProjectGraph, p: string) => [...new Set(g.code.filter((c) => c.to === p).map((c) => c.from))]
+const usedBy = (g: ProjectGraph, p: string) => [...new Set(g.code.filter((c) => c.from === p).map((c) => c.to))]
+
+/** Pins further behind than this are worth a word, as the map draws them amber. */
+const STALE = 5
+
+function pickedCard(g: ProjectGraph, name: string): m.Children {
+ const p = g.projects.find((x) => x.name === name)
+ if (!p) return null
+ const uses = usesOf(g, name)
+ const by = usedBy(g, name)
+ const stale = g.code.filter((c) => c.from === name && (c.behind ?? 0) > STALE)
+ const shared = g.shared
+ .filter((s) => s.a === name || s.b === name)
+ .map((s) => ({other: s.a === name ? s.b : s.a, n: s.n}))
+ .sort((a, b) => b.n - a.n)
+ return (
+ <Card class="pmap-card" title={short(name)} subtitle={[p.description, p.public ? 'public' : 'private'].filter(Boolean).join(' · ')}>
+ <dl class="pmap-card__facts">
+ {uses.length ? [<dt>uses</dt>, <dd>{uses.map(short).join(' · ')}</dd>] : null}
+ {by.length ? [<dt>used by</dt>, <dd>{by.map(short).join(' · ')}</dd>] : null}
+ <dt>sessions</dt>
+ <dd>
+ {p.sessions ?? 0}
+ {shared.length ? ` · most shared with ${shared.slice(0, 2).map((s) => `${short(s.other)} (${s.n})`).join(', ')}` : ''}
+ </dd>
+ {p.techs ? [<dt>techs</dt>, <dd>{p.built} of {p.techs} built</dd>] : null}
+ </dl>
+ {stale.map((c) => (
+ <p class="pmap-card__warn">
+ ⚑ {short(c.to)} uses a commit {c.behind} behind ({c.file})
+ </p>
+ ))}
+ <div class="tree-bar__row">
+ <Button variant="primary" onclick={() => go(`research/map/${name}`)}>
+ Its sessions over time
+ </Button>
+ {p.techs ? (
+ <Button variant="ghost" onclick={() => {
+ show(name)
+ go('research')
+ }}>
+ Its goals
+ </Button>
+ ) : null}
+ </div>
+ </Card>
+ )
+}
+
+/** On a phone: the projects as a list, in the map's columns, each saying what it uses and what uses it. */
+function mapList(g: ProjectGraph): m.Children {
+ const linked = new Set(g.code.flatMap((c) => [c.from, c.to]))
+ // The columns of the map, those that share no code (graph.rs wraps them over several) as one.
+ const apart = g.projects.filter((p) => !linked.has(p.name))
+ const cols = [...new Set(g.projects.filter((p) => linked.has(p.name)).map((p) => p.col))].sort((a, b) => a - b)
+ const groups: [string, typeof apart][] = [
+ ...cols.map((c): [string, typeof apart] => [c === cols[0] ? 'Built on no other project' : 'Built on the ones above', g.projects.filter((p) => p.col === c && linked.has(p.name))]),
+ ...(apart.length ? [['No code shared', apart] as [string, typeof apart]] : []),
+ ]
+ return (
+ <div class="pmap-list">
+ {groups.map(([title, list]) => [
+ <span class="hint">{title}</span>,
+ list
+ .slice()
+ .sort((a, b) => a.col - b.col || a.row - b.row)
+ .map((p) => [
+ <button class={`pmap-list__p${state.picked === p.name ? ' on' : ''}`} onclick={() => (state.picked = state.picked === p.name ? '' : p.name)}>
+ <b>{short(p.name)}</b>
+ <span class="hint">{p.techs ? `${p.built} / ${p.techs} built` : `${p.sessions ?? 0} session${p.sessions === 1 ? '' : 's'}`}</span>
+ {usesOf(g, p.name).length ? <span>uses {usesOf(g, p.name).map(short).join(', ')}</span> : null}
+ {usedBy(g, p.name).length ? <span>used by {usedBy(g, p.name).map(short).join(', ')}</span> : null}
+ </button>,
+ // On a phone the tapped one opens under itself, not past the end of the list.
+ state.picked === p.name ? pickedCard(g, p.name) : null,
+ ]),
+ ])}
+ </div>
+ )
+}
+
+function mapPage(): m.Children {
+ const g = state.graph!
+ return (
+ <div class="stack">
+ <div class="tree-bar__row">
+ <Button variant="ghost" onclick={() => go('research')}>
+ ← The tree
+ </Button>
+ <b class="tree-board__title">Map</b>
+ <span class="hint">{g.projects.length} projects · which uses which, and the sessions between them</span>
+ </div>
+ <div class="pmap">
+ <div
+ class="pmap__drawing"
+ onclick={(e: Event) => {
+ const p = (e.target as Element).closest('[data-project]')?.getAttribute('data-project') ?? ''
+ state.picked = state.picked === p ? '' : p
+ }}
+ onkeydown={(e: KeyboardEvent) => {
+ if (e.key !== 'Enter') return
+ state.picked = (e.target as Element).closest('[data-project]')?.getAttribute('data-project') ?? ''
+ }}
+ >
+ {m.trust(state.svg)}
+ </div>
+ {mapList(g)}
+ <div class="pmap__beside">{state.picked ? pickedCard(g, state.picked) : null}</div>
+ </div>
+ <div class="pmap-legend hint">
+ <span><i class="pmap-legend__code" />uses its code, arrow from the one used</span>
+ <span><i class="pmap-legend__stale" />uses an older commit</span>
+ <span><i class="pmap-legend__shared" />sessions in both, thicker for more</span>
+ <span><i class="pmap-legend__needs" />a tech there needs one here</span>
+ <span>size: sessions · ring: techs built</span>
+ </div>
+ </div>
+ )
+}
+
+type Outcome = 'landed' | 'ended' | 'working'
+
+function outcomeOf(h: Hosted): Outcome {
+ if (h.finished?.outcome === 'landed') return 'landed'
+ if (h.finished || h.status === 'stopped' || h.status === 'failed') return 'ended'
+ return 'working'
+}
+
+const X0 = 150
+const W = 1100
+const LANE = 13
+
+/**
+ * One project's sessions over time: a stream for it, then for each project it uses or that uses it, then
+ * for each other project three or more of these sessions also worked in, then one for everywhere else. A session is a bar from its start to its end in the
+ * first of its projects shown, with a tie to each other project it worked in. ◆: it built a tech.
+ */
+function weekPage(d: TreeState | null, name: string): m.Children {
+ const g = state.graph!
+ const near = [...usesOf(g, name), ...usedBy(g, name)].filter((p, i, a) => a.indexOf(p) === i && p !== name)
+ const now = Date.now() / 1000
+ const t0 = state.days ? now - state.days * 86400 : Math.min(now - 86400, ...hosted().map((h) => h.created))
+ const all = hosted().filter((h) => {
+ const rs = reposOf(h)
+ return rs.some((r) => r === name || near.includes(r)) && (h.finished?.at ?? h.updated ?? now) >= t0
+ })
+ const often: Record<string, number> = {}
+ for (const h of all) for (const r of reposOf(h)) if (r !== name && !near.includes(r)) often[r] = (often[r] ?? 0) + 1
+ const also = Object.keys(often)
+ .filter((r) => often[r]! >= 3)
+ .sort((a, b) => often[b]! - often[a]!)
+ const streams = [name, ...near, ...also].slice(0, 8)
+ const elsewhere = all.some((h) => reposOf(h).some((r) => !streams.includes(r)))
+ const rows = [...streams, ...(elsewhere ? ['elsewhere'] : [])]
+ const built = new Set((d?.techs ?? []).filter((t) => t.state === 'built').flatMap((t) => (t.sessions ?? []).filter((s) => s.outcome === 'landed').map((s) => s.id)))
+ // Lanes first, so each stream is as tall as its busiest moment.
+ const lanes: Record<string, number[]> = {}
+ const placed = all
+ .slice()
+ .sort((a, b) => a.created - b.created)
+ .map((h) => {
+ const home = reposOf(h).find((r) => streams.includes(r)) ?? 'elsewhere'
+ const ends = (lanes[home] ??= [])
+ const start = Math.max(h.created, t0)
+ const end = h.finished?.at ?? (outcomeOf(h) === 'working' ? now : h.updated)
+ let k = ends.findIndex((e) => e < start)
+ if (k < 0) k = ends.push(0) - 1
+ ends[k] = end + 1800
+ return {h, home, k, start, end}
+ })
+ const height = (s: string) => Math.max(34, 12 + (lanes[s]?.length ?? 1) * LANE)
+ const top: Record<string, number> = {}
+ let y = 30
+ for (const s of rows) {
+ top[s] = y
+ y += height(s) + 6
+ }
+ const x = (t: number) => X0 + ((t - t0) / Math.max(1, now - t0)) * W
+ const days = Math.round((now - t0) / 86400)
+ const ticks = Array.from({length: Math.min(days, 12) + 1}, (_, i) => t0 + (i * (now - t0)) / Math.min(days, 12))
+ const label = (t: number) => new Date(t * 1000).toLocaleDateString(undefined, {day: 'numeric', month: 'short'})
+ return (
+ <div class="stack">
+ <div class="tree-bar__row">
+ <Button variant="ghost" onclick={() => go('research/map')}>
+ ← All projects
+ </Button>
+ <b class="tree-board__title">{short(name)}</b>
+ <span class="hint">
+ {all.length} sessions · {all.filter((h) => outcomeOf(h) === 'landed').length} landed
+ </span>
+ <span class="pweek__range">
+ {[7, 30, 0].map((n) => (
+ <Button size="sm" variant={state.days === n ? 'secondary' : 'ghost'} onclick={() => (state.days = n)}>
+ {n ? `${n}D` : 'All'}
+ </Button>
+ ))}
+ </span>
+ </div>
+ <div class="pweek">
+ <svg class="pweek__svg" viewBox={`0 0 ${X0 + W + 20} ${y}`}>
+ {ticks.map((t) => [
+ <line x1={x(t)} y1={18} x2={x(t)} y2={y} class="pweek__tick" />,
+ <text x={x(t) + 4} y={14} class="pweek__date">{label(t)}</text>,
+ ])}
+ {rows.map((s) => [
+ <rect x={8} y={top[s]} width={X0 + W + 4} height={height(s)} rx={9} class={`pweek__stream${s === name ? ' on' : ''}`} />,
+ <text x={20} y={top[s]! + height(s) / 2 + 4} class={`pweek__name${s === 'elsewhere' ? ' dim' : ''}`}>{s === 'elsewhere' ? 'elsewhere' : short(s)}</text>,
+ ])}
+ {placed.map(({h, home, k, start, end}) => {
+ const by = top[home]! + 8 + k * LANE
+ const x1 = x(start)
+ const x2 = Math.max(x(end), x1 + 6)
+ const o = outcomeOf(h)
+ const ties = reposOf(h)
+ .map((r) => (streams.includes(r) ? r : 'elsewhere'))
+ .filter((r, i, a) => r !== home && a.indexOf(r) === i)
+ return (
+ <g class={`pweek__s ${o}`} onclick={() => go(`sessions/${h.id}`)}>
+ <title>{`${h.id} · ${h.title} · ${reposOf(h).map(short).join(', ')}`}</title>
+ {ties.map((r) => [
+ <line x1={x1 + 2} y1={by + 4} x2={x1 + 2} y2={top[r]! + height(r) / 2} class="pweek__tie" />,
+ <circle cx={x1 + 2} cy={top[r]! + height(r) / 2} r={3} class="pweek__dot" />,
+ ])}
+ <rect x={x1} y={by} width={x2 - x1} height={9} rx={4.5} class="pweek__bar" />
+ {built.has(h.id) ? <text x={x2 + 3} y={by + 9} class="pweek__built">◆</text> : null}
+ </g>
+ )
+ })}
+ </svg>
+ </div>
+ <div class="pmap-legend hint">
+ <span><i class="pweek__key landed" />landed</span>
+ <span><i class="pweek__key ended" />ended without landing</span>
+ <span><i class="pweek__key working" />at work</span>
+ <span>│ the same session in another project</span>
+ <span>◆ built a tech</span>
+ </div>
+ </div>
+ )
+}
+
+/** The Map's pages: `research/map`, and `research/map/<owner>/<name>` for one project over time. */
+export function mapView(d: TreeState | null, place: string): m.Children {
+ if (!state.graph) {
+ load()
+ return <p class="hint">{state.error || 'Reading every project…'}</p>
+ }
+ const name = place.replace(/^research\/map\/?/, '')
+ if (name && state.graph.projects.some((p) => p.name === name)) return weekPage(d, name)
+ return mapPage()
+}
diff --git a/web/src/components/research.tsx b/web/src/components/research.tsx
index 275394f..98e0d0a 100644
--- a/web/src/components/research.tsx
+++ b/web/src/components/research.tsx
@@ -5,6 +5,7 @@ import {seg} from '@/components/autopilot'
import {Bars, SERIES} from '@/components/charts'
import {openTreeTalk, talkAboutTree} from '@/components/discuss'
import {pipsView} from '@/components/pips'
+import {mapView} from '@/components/projectmap'
import {askConfirm} from '@/components/confirm'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
@@ -1261,11 +1262,14 @@ function historyCard(techs: Tech[]): m.Children {
/** To Directions, from the goal bar: how many go. */
function directionsLink(d: TreeState): m.Children {
const n = directionsOf(d).length
- return (
+ return [
<Button variant="ghost" onclick={() => go('research/directions')}>
{n ? `Directions · ${n}` : 'Directions'}
- </Button>
- )
+ </Button>,
+ <Button variant="ghost" onclick={() => go('research/map')}>
+ Map
+ </Button>,
+ ]
}
/**
@@ -2477,6 +2481,7 @@ export class ResearchPage extends MithrilComponent {
if (!d) return <p class="hint">{state.error || 'Loading the research tree…'}</p>
const h = here()
if (h === 'research/directions') return directionsPage(d)
+ if (h === 'research/map' || h.startsWith('research/map/')) return mapView(d, h)
const edit = h.match(/^research\/g\/(g\d+|new)(?:\/(g\d+))?$/)
if (edit) return editPage(d, edit[1] === 'new' ? '' : edit[1]!, edit[2] ?? '')
const g = pickedGoal(d)
diff --git a/web/src/lib/api.ts b/web/src/lib/api.ts
index 6a04a75..a0872c9 100644
--- a/web/src/lib/api.ts
+++ b/web/src/lib/api.ts
@@ -371,6 +371,18 @@ export interface TreeBudget {
week_cost: number
}
+/** Goals ▸ Map (graph.rs): every project with its place, and the lines between them, each one recorded. */
+export interface ProjectGraph {
+ projects: {name: string; public: boolean; description?: string; sessions?: number; techs: number; built: number; col: number; row: number}[]
+ /** `to`'s manifest `file` names `from`'s code at `rev`, `behind` commits short of its main. */
+ code: {from: string; to: string; rev?: string | null; file: string; behind?: number | null}[]
+ /** Sessions that worked in both. */
+ shared: {a: string; b: string; n: number}[]
+ /** Techs of `to` that need a tech of `from`. */
+ needs: {from: string; to: string; n: number}[]
+ landed: {name: string; repo: string; at: number}[]
+}
+
export interface Direction {
id: string
target: string
@@ -654,6 +666,8 @@ export const api = {
templateOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/templates', {op, ...fields}) as Promise<TemplatesState & {started?: string[]}>,
/** The research tree (tree.rs). */
tree: () => get<TreeState>('/v1/hosted/tree'),
+ /** Goals ▸ Map: every project, which uses which, the sessions between them, and the map drawn (graph.rs). */
+ graph: () => get<{graph: ProjectGraph; svg: string}>('/v1/hosted/graph'),
/** A change to it, by op (goal_save, goal_delete, idea, insight_drop, tech_confirm, tech_drop, tech_restore, tech_built, scout): the whole tree after. */
treeOp: (op: string, fields: Record<string, unknown>) => post('/v1/hosted/tree', {op, ...fields}) as Promise<TreeState>,
reopen: (id: string) => post(`/v1/hosted/${id}/reopen`, {}),