garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /src/focus.rs

raw

//! Focus: how much deciding the person does, and the limits they set on it.
//!
//! Steering many sessions from a phone is mostly deciding: a question here, a
//! "Shall it land?" there, each arriving whenever its session gets to it. The
//! research on that kind of work points one way (BCG's "AI brain fry" survey of
//! 1,488 workers, HBR 2026-03: how much oversight the AI needs was the
//! strongest predictor of mental fatigue, and output fell from a fourth agent
//! on; Berkeley's study at a 200-person company, HBR 2026-02: the tools made
//! work denser, not lighter). So the hub counts what the person decides, and
//! lets them cap it themselves (the person's choice, 2026-11-04):
//!
//! - **The ledger** (`focus-ledger.jsonl`): one row per decision the person
//!   made — a question or permission answered, a board decision, a message to
//!   a session — with **points** for what it likely cost them ([`points`]):
//!   one for deciding, more for an interruption, a switch from another
//!   session, a long read, words of their own, a landing, a late hour. And a
//!   row per answer the autopilot gave in their place, with what it saved.
//!   Points are an estimate of effort, not a measure of how anyone feels:
//!   the end-of-day check-in (1 fresh … 5 fried) is kept beside them, and
//!   suggests a cap once there are days of both.
//! - **Settings**, per account (`focus.json`): a daily cap of points and of
//!   sessions at work, decision blocks (times of day when held questions are
//!   announced at once), quiet hours, and whether the person's rules apply in
//!   sessions without the autopilot. All of it off until they set it: a hub
//!   nobody configured behaves as before.
//! - **Rules**: what the person lets the autopilot decide without them, in
//!   their words ("take a free build node when one is needed"). The
//!   autopilot proposes them from the person's earlier answers; only an
//!   approved one is used.
//!
//! What the limits do, and only that: while the person holds questions
//! (outside a block, in quiet hours, or near their cap), a push goes out only
//! for what cannot wait (push.rs); at a block's start one push says how much
//! waits. Near the cap the autopilot is told to settle more itself; at the cap
//! a schedule's next run waits for the next day (templates.rs) and the page
//! asks before a new session. Nothing is hidden: every question still shows
//! on the page, and can be answered whenever the person likes.

use std::collections::BTreeMap;
use std::path::PathBuf;

use anyhow::{bail, Context, Result};
use serde_json::{json, Value};

use crate::registry::{self, now};
use crate::store::Store;

/// How long a decision block is open after its start, in minutes: questions
/// answered in it are no interruption, and the block's push goes at its start.
pub const BLOCK_MIN: i64 = 30;

/// An answer this soon after the question appeared, outside a block, was an
/// interruption: the push came, and the person stopped what they did.
const INTERRUPT_S: i64 = 180;

/// A decision for another session than the last one, within this long, was a switch.
const SWITCH_S: i64 = 600;

/// What the person read before deciding, past which it counts as a long read.
const LONG_READ: usize = 1500;

/// A message this long is their own words at some length.
const LONG_MESSAGE: usize = 280;

/// Near the cap: this share of it.
const NEAR: f64 = 0.8;

/// The earlier answers the autopilot reads as precedent.
const PRECEDENTS: usize = 25;

/// The rules that may wait for approval at once: more is noise.
const SUGGESTED_MAX: usize = 12;

/// The ledger read back for today and the week: enough for a heavy week.
const LEDGER_TAIL: u64 = 4 << 20;

fn path() -> PathBuf {
    registry::root().join("focus.json")
}

fn ledger() -> PathBuf {
    registry::root().join("focus-ledger.jsonl")
}

fn open() -> Result<Store<Value>> {
    let mut s = Store::<Value>::open(path())?;
    if !s.data.is_object() {
        s.data = json!({});
    }
    Ok(s)
}

fn read() -> Value {
    crate::store::read(&path()).unwrap_or_else(|| json!({}))
}

// ── Who ─────────────────────────────────────────────────────────────────────

/// The person behind a `by` (`web:<account>`, as the hub records a login's
/// changes), or none: agents, runners, keys and the autopilot are not people.
pub fn person_of(by: &str) -> Option<&str> {
    by.strip_prefix("web:").filter(|a| !a.is_empty() && !a.contains(':'))
}

/// The person a session answers to: who started it, or, from a template, who
/// scheduled it.
pub fn person_of_session(m: &Value) -> Option<String> {
    person_of(m["by"].as_str().unwrap_or("")).map(str::to_string)
}

/// Whose focus a reader without a login sees: the person who decided last, so
/// a page behind a proxy key still shows the one person most hubs have.
pub fn default_person() -> String {
    last_rows(64 << 10).iter().rev().find_map(|r| r["person"].as_str().map(str::to_string)).unwrap_or_else(|| "you".into())
}

// ── Settings ────────────────────────────────────────────────────────────────

/// An account's settings, every one off until set.
pub fn settings(person: &str) -> Value {
    let mut s = json!({
        "cap_points": null, "cap_sessions": null, "blocks": [], "hold": false,
        "quiet_from": null, "quiet_until": null, "tz_min": 0, "rules_everywhere": false, "undo_min": 30,
    });
    if let Some(saved) = read()["people"][person].as_object() {
        for (k, v) in saved {
            s[k] = v.clone();
        }
    }
    s
}

/// "HH:MM" as minutes past midnight.
fn minute_of(t: &str) -> Option<i64> {
    let (h, m) = t.trim().split_once(':')?;
    let (h, m): (i64, i64) = (h.parse().ok()?, m.parse().ok()?);
    ((0..24).contains(&h) && (0..60).contains(&m)).then_some(h * 60 + m)
}

/// The settings as the page sends them, checked; what is not sent stays.
pub fn set(person: &str, body: &Value) -> Result<Value> {
    let mut s = open()?;
    let mut mine = s.data["people"][person].clone();
    if !mine.is_object() {
        mine = json!({});
    }
    let cap = |k: &str, max: i64| -> Result<Value> {
        match &body[k] {
            Value::Null => Ok(Value::Null),
            v => match v.as_i64() {
                Some(n) if (1..=max).contains(&n) => Ok(json!(n)),
                _ => bail!("{k} is a number from 1 to {max}, or none"),
            },
        }
    };
    if body.get("cap_points").is_some() {
        mine["cap_points"] = cap("cap_points", 1000)?;
    }
    if body.get("cap_sessions").is_some() {
        mine["cap_sessions"] = cap("cap_sessions", 50)?;
    }
    if let Some(list) = body.get("blocks") {
        let list = list.as_array().context("blocks is a list of times, as [\"10:00\", \"15:00\"]")?;
        if list.len() > 8 {
            bail!("at most eight blocks a day");
        }
        let mut times: Vec<i64> = Vec::new();
        for t in list {
            times.push(t.as_str().and_then(minute_of).with_context(|| format!("{t} is no time of day (HH:MM)"))?);
        }
        times.sort_unstable();
        times.dedup();
        mine["blocks"] = json!(times.iter().map(|m| format!("{:02}:{:02}", m / 60, m % 60)).collect::<Vec<_>>());
    }
    for k in ["quiet_from", "quiet_until"] {
        if let Some(v) = body.get(k) {
            mine[k] = match v.as_str().filter(|t| !t.trim().is_empty()) {
                None => Value::Null,
                Some(t) => {
                    let m = minute_of(t).with_context(|| format!("{k} is a time of day (HH:MM)"))?;
                    json!(format!("{:02}:{:02}", m / 60, m % 60))
                }
            };
        }
    }
    for k in ["hold", "rules_everywhere"] {
        if let Some(v) = body.get(k) {
            mine[k] = json!(v.as_bool().with_context(|| format!("{k} is true or false"))?);
        }
    }
    if let Some(v) = body.get("undo_min") {
        match v.as_i64() {
            Some(n) if (0..=24 * 60).contains(&n) => mine["undo_min"] = json!(n),
            _ => bail!("undo_min is minutes, from 0 to a day"),
        }
    }
    if let Some(v) = body.get("tz_min") {
        mine["tz_min"] = json!(tz_ok(v)?);
    }
    if !s.data["people"].is_object() {
        s.data["people"] = json!({});
    }
    s.data["people"][person] = mine;
    s.save()?;
    Ok(settings(person))
}

fn tz_ok(v: &Value) -> Result<i64> {
    match v.as_i64() {
        Some(n) if (-14 * 60..=14 * 60).contains(&n) => Ok(n),
        _ => bail!("tz_min is the minutes east of UTC"),
    }
}

/// The page says where the person is each time it asks (its clock's offset):
/// kept only when it changed, so their days and blocks follow them.
pub fn seen_tz(person: &str, tz_min: i64) {
    if settings(person)["tz_min"].as_i64() == Some(tz_min) || tz_ok(&json!(tz_min)).is_err() {
        return;
    }
    let _ = set(person, &json!({"tz_min": tz_min}));
}

/// Minutes past the person's midnight at `t`, and their date then.
fn local(s: &Value, t: i64) -> (i64, String) {
    let shifted = t + s["tz_min"].as_i64().unwrap_or(0) * 60;
    let date = chrono::DateTime::from_timestamp(shifted, 0).map(|d| d.format("%Y-%m-%d").to_string()).unwrap_or_default();
    (shifted.rem_euclid(86400) / 60, date)
}

/// The person's midnight before `t`, as a unix time.
fn day_start(s: &Value, t: i64) -> i64 {
    let (m, _) = local(s, t);
    t - t.rem_euclid(60) - m * 60
}

/// The block open at `t`, as its start ("15:00"), if one is.
pub fn block_at(s: &Value, t: i64) -> Option<String> {
    let (m, _) = local(s, t);
    s["blocks"].as_array().into_iter().flatten().filter_map(|b| b.as_str())
        .find(|b| minute_of(b).is_some_and(|start| (start..start + BLOCK_MIN).contains(&m)))
        .map(str::to_string)
}

/// The next block's start after `t`, as a unix time.
pub fn next_block(s: &Value, t: i64) -> Option<i64> {
    let (m, _) = local(s, t);
    let starts: Vec<i64> = s["blocks"].as_array().into_iter().flatten().filter_map(|b| b.as_str().and_then(minute_of)).collect();
    let base = day_start(s, t);
    starts.iter().filter(|&&b| b > m).min().map(|b| base + b * 60)
        .or_else(|| starts.iter().min().map(|b| base + 86400 + b * 60))
}

/// Within the person's quiet hours at `t`.
pub fn quiet_at(s: &Value, t: i64) -> bool {
    let (Some(from), Some(until)) = (s["quiet_from"].as_str().and_then(minute_of), s["quiet_until"].as_str().and_then(minute_of)) else {
        return false;
    };
    let (m, _) = local(s, t);
    if from <= until { (from..until).contains(&m) } else { m >= from || m < until }
}

// ── Points ──────────────────────────────────────────────────────────────────

/// What is known of one decision when it is made.
#[derive(Default)]
pub struct Facts {
    /// `question`, `permission`, `decision` or `message`.
    pub kind: String,
    pub at: i64,
    /// When it was put to the person, if it was put.
    pub asked_at: Option<i64>,
    /// How much they had to read for it: the question and the session's words before it.
    pub read: usize,
    /// They wrote an answer of their own rather than pick one.
    pub own_words: bool,
    /// The length of a message they wrote.
    pub words: usize,
    pub switched: bool,
    pub in_block: bool,
    pub late: bool,
    pub landing: bool,
}

/// The points a decision costs, and what each was for. One for deciding at
/// all; one each for an interruption, a switch, a long read, a landing and a
/// late hour; two for writing an answer of one's own (one for a long message,
/// which is words of one's own by nature).
pub fn points(f: &Facts) -> (u32, Value) {
    let mut parts = serde_json::Map::new();
    parts.insert("decision".into(), json!(1));
    let interrupted = !f.in_block && f.asked_at.is_some_and(|a| f.at - a <= INTERRUPT_S);
    if interrupted {
        parts.insert("interruption".into(), json!(1));
    }
    if f.switched {
        parts.insert("switch".into(), json!(1));
    }
    if f.read > LONG_READ {
        parts.insert("long_read".into(), json!(1));
    }
    if f.kind == "message" {
        if f.words > LONG_MESSAGE {
            parts.insert("own_words".into(), json!(1));
        }
    } else if f.own_words {
        parts.insert("own_words".into(), json!(2));
    }
    if f.landing {
        parts.insert("landing".into(), json!(1));
    }
    if f.late {
        parts.insert("late".into(), json!(1));
    }
    let total = parts.values().filter_map(Value::as_u64).sum::<u64>() as u32;
    (total, Value::Object(parts))
}

/// Whether a question is about landing: those weigh more.
fn about_landing(text: &str) -> bool {
    let t = text.to_lowercase();
    t.contains("shall it land") || t.contains("land it") || t.contains("should it land")
}

// ── The ledger ──────────────────────────────────────────────────────────────

fn last_rows(bytes: u64) -> Vec<Value> {
    crate::sessions::last_lines(&ledger(), bytes)
}

fn append(row: &Value) -> Result<()> {
    use std::io::Write;
    let _l = crate::store::lock(&crate::store::lock_path(&ledger()))?;
    let mut f = std::fs::OpenOptions::new().create(true).append(true).open(ledger())?;
    writeln!(f, "{row}")?;
    Ok(())
}

/// How many sessions are at work now: a turn, or a question waiting.
fn at_work() -> usize {
    crate::sessions::list().as_array().into_iter().flatten()
        .filter(|m| matches!(m["status"].as_str(), Some("working" | "needs_permission")) && m["archived"] != true)
        .count()
}

/// A decision the person made, into the ledger with its points. `asked` is the
/// log item it answers (a question or permission), and `before` what the
/// session said leading up to it.
pub fn record(person: &str, session: &str, kind: &str, asked: Option<&Value>, before: &str, answer: &Value, own_words: bool, words: usize) {
    let s = settings(person);
    let t = now();
    let last = last_rows(64 << 10).into_iter().rev().find(|r| r["person"] == person && r["by"] == "person");
    let switched = last.is_some_and(|r| r["session"] != session && t - r["at"].as_i64().unwrap_or(0) <= SWITCH_S);
    let question = asked.map(|a| match a["kind"].as_str() {
        Some("permission") => a["title"].as_str().unwrap_or("").to_string(),
        _ => a["message"].as_str().or(a["question"].as_str()).unwrap_or("").to_string(),
    }).unwrap_or_default();
    let read = question.len() + asked.map_or(0, |a| a["schema"].to_string().len() / 2) + before.len();
    let facts = Facts {
        kind: kind.into(), at: t, asked_at: asked.and_then(|a| a["at"].as_i64()), read, own_words, words,
        switched, in_block: block_at(&s, t).is_some(), late: quiet_at(&s, t), landing: about_landing(&question),
    };
    let (pts, parts) = points(&facts);
    let row = json!({
        "at": t, "by": "person", "person": person, "session": session, "kind": kind, "points": pts, "parts": parts,
        "asked_at": facts.asked_at, "question": crate::util::short(&question, 400), "answer": answer,
        "recommended": recommended_picked(asked, answer), "running": at_work(),
    });
    if let Err(e) = append(&row) {
        crate::events::emit("error", json!({"what": format!("the focus ledger: {e:#}")}));
    }
}

/// Whether the answer took the option marked "(Recommended)", when there was one.
fn recommended_picked(asked: Option<&Value>, answer: &Value) -> Value {
    let Some(props) = asked.and_then(|a| a["schema"]["properties"].as_object()) else { return Value::Null };
    let mut any = false;
    for (k, f) in props.iter().filter(|(k, _)| !k.ends_with("_custom")) {
        let options = f["oneOf"].as_array().or(f["items"]["anyOf"].as_array());
        let rec: Vec<&Value> = options.into_iter().flatten().filter(|o| o["const"].as_str().is_some_and(|c| c.contains("(Recommended)"))).map(|o| &o["const"]).collect();
        if rec.is_empty() {
            continue;
        }
        any = true;
        let given = &answer[k];
        let took = given.as_array().map_or_else(|| rec.contains(&given), |list| rec.iter().all(|r| list.contains(r)));
        if !took {
            return json!(false);
        }
    }
    if any { json!(true) } else { Value::Null }
}

/// An answer the autopilot gave for the person, from what the runner reported:
/// `item` the log item (permission_answered, answered, or its message), `n` its
/// number in the session's log, `asked` what it answered.
pub fn record_pilot(m: &Value, item: &Value, n: u64, asked: Option<&Value>, before: &str) {
    let Some(person) = person_of_session(m) else { return };
    let session = m["id"].as_str().unwrap_or("");
    let question = asked.map(|a| a["message"].as_str().or(a["title"].as_str()).unwrap_or("").to_string()).unwrap_or_default();
    let (kind, answer) = match item["kind"].as_str() {
        Some("permission_answered") => ("permission", item["option"].clone()),
        Some("answered") => ("question", item["content"].clone()),
        _ => ("message", json!(crate::util::short(item["text"].as_str().unwrap_or(""), 400))),
    };
    // What it would have cost the person: deciding, and the read.
    let saved = 1 + u32::from(question.len() + before.len() > LONG_READ) + u32::from(about_landing(&question));
    let row = json!({
        "at": now(), "by": "autopilot", "person": person, "session": session, "n": n, "kind": kind,
        "question": crate::util::short(&question, 400), "answer": answer, "why": item["why"],
        "basis": item["basis"], "rule": item["rule"], "sure": item["sure"], "saved": saved,
    });
    if let Err(e) = append(&row) {
        crate::events::emit("error", json!({"what": format!("the focus ledger: {e:#}")}));
    }
    if let Some(rule) = item["rule"].as_str() {
        let _ = rule_used(rule);
    }
    if let Some(text) = item["propose"].as_str() {
        let _ = suggest(text, item["why"].as_str().unwrap_or(""), session);
    }
}

// ── Rules ───────────────────────────────────────────────────────────────────

pub fn rules() -> Vec<Value> {
    read()["rules"].as_array().cloned().unwrap_or_default()
}

/// The approved rules, as the autopilot reads them.
pub fn approved() -> Vec<Value> {
    rules().into_iter().filter(|r| r["state"] == "approved").collect()
}

fn rule_text(text: &str) -> Result<String> {
    let t = text.split_whitespace().collect::<Vec<_>>().join(" ");
    if t.is_empty() || t.len() > 400 {
        bail!("a rule is a sentence, at most 400 bytes");
    }
    Ok(t)
}

/// A rule the autopilot proposes from the person's answers: waits for their
/// word. One with the same words as any rule already there is not added again.
fn suggest(text: &str, evidence: &str, session: &str) -> Result<()> {
    let text = rule_text(text)?;
    let mut s = open()?;
    let list = s.data["rules"].as_array().cloned().unwrap_or_default();
    let same = |r: &Value| r["text"].as_str().is_some_and(|t| t.eq_ignore_ascii_case(&text));
    if list.iter().any(same) || list.iter().filter(|r| r["state"] == "suggested").count() >= SUGGESTED_MAX {
        return Ok(());
    }
    let id = next_rule(&mut s.data);
    let mut list = list;
    list.push(json!({"id": id, "text": text, "state": "suggested", "by": crate::autopilot::BY, "at": now(),
                     "evidence": crate::util::short(evidence, 400), "session": session, "uses": 0}));
    s.data["rules"] = json!(list);
    s.save()
}

fn next_rule(data: &mut Value) -> String {
    let n = data["seq"].as_u64().unwrap_or(0) + 1;
    data["seq"] = json!(n);
    format!("r{n}")
}

fn rule_used(id: &str) -> Result<()> {
    let mut s = open()?;
    if let Some(r) = s.data["rules"].as_array_mut().into_iter().flatten().find(|r| r["id"] == id) {
        r["uses"] = json!(r["uses"].as_u64().unwrap_or(0) + 1);
        r["last_used"] = json!(now());
    }
    s.save()
}

/// The person's change to the rules: `add` (text; approved, theirs), `approve`,
/// `reject` (kept, so it is not proposed again), `edit` (text), `remove`.
pub fn rule_op(body: &Value, by: &str) -> Result<Vec<Value>> {
    let op = body["op"].as_str().unwrap_or("");
    let id = body["id"].as_str().unwrap_or("");
    let mut s = open()?;
    let mut list = s.data["rules"].as_array().cloned().unwrap_or_default();
    let find = |list: &mut Vec<Value>| -> Result<usize> { list.iter().position(|r| r["id"] == id).with_context(|| format!("no rule {id}")) };
    match op {
        "add" => {
            let text = rule_text(body["text"].as_str().unwrap_or(""))?;
            let id = next_rule(&mut s.data);
            list.push(json!({"id": id, "text": text, "state": "approved", "by": by, "at": now(), "uses": 0,
                             "session": body["session"].as_str()}));
        }
        "approve" | "reject" => {
            let i = find(&mut list)?;
            list[i]["state"] = json!(if op == "approve" { "approved" } else { "rejected" });
            list[i]["decided_by"] = json!(by);
            list[i]["decided_at"] = json!(now());
        }
        "edit" => {
            let i = find(&mut list)?;
            list[i]["text"] = json!(rule_text(body["text"].as_str().unwrap_or(""))?);
        }
        "remove" => {
            let i = find(&mut list)?;
            list.remove(i);
        }
        _ => bail!("a rule op is add, approve, reject, edit or remove"),
    }
    s.data["rules"] = json!(list);
    s.save()?;
    crate::events::emit("focus_rule", json!({"actor": by, "op": op, "id": id}));
    Ok(rules())
}

// ── What the autopilot is told ──────────────────────────────────────────────

/// For the autopilot deciding in `session`: the approved rules, the person's
/// earlier answers, whether they are near their cap, and whether their rules
/// apply where the autopilot is off.
pub fn pilot_context(session: &str) -> Result<Value> {
    let m = crate::sessions::meta(session)?;
    let Some(person) = person_of_session(&m) else {
        return Ok(json!({"rules": approved(), "precedents": [], "near_cap": false, "rules_everywhere": false}));
    };
    let s = settings(&person);
    let mut precedents: Vec<Value> = last_rows(LEDGER_TAIL).into_iter().rev()
        .filter(|r| r["person"] == person.as_str() && r["by"] == "person" && matches!(r["kind"].as_str(), Some("question" | "permission" | "decision")))
        .filter(|r| r["question"].as_str().is_some_and(|q| !q.is_empty()))
        .take(PRECEDENTS)
        .map(|r| json!({"question": r["question"], "answer": r["answer"], "recommended": r["recommended"]}))
        .collect();
    precedents.reverse();
    let today = today_of(&person, &s);
    Ok(json!({
        "rules": approved().iter().map(|r| json!({"id": r["id"], "text": r["text"]})).collect::<Vec<_>>(),
        "precedents": precedents, "near_cap": today["near_cap"], "at_cap": today["at_cap"],
        "rules_everywhere": s["rules_everywhere"] == true,
    }))
}

// ── Holding and caps ────────────────────────────────────────────────────────

/// Whether the person holds what can wait at `t`: they asked to between
/// blocks, it is their quiet time, or they are near their cap.
pub fn holding(person: &str, t: i64) -> bool {
    let s = settings(person);
    (s["hold"] == true && !s["blocks"].as_array().is_none_or(Vec::is_empty) && block_at(&s, t).is_none())
        || quiet_at(&s, t)
        || today_of(person, &s)["near_cap"] == true
}

/// The block that opened since the last look, once per block per day: its
/// push says how much waits. Marked as told when it answers.
pub fn block_opened(person: &str, t: i64) -> Option<String> {
    let s = settings(person);
    if s["hold"] != true {
        return None;
    }
    let b = block_at(&s, t)?;
    let key = format!("{} {b}", local(&s, t).1);
    let mut st = open().ok()?;
    if st.data["told"][person] == key.as_str() {
        return None;
    }
    if !st.data["told"].is_object() {
        st.data["told"] = json!({});
    }
    st.data["told"][person] = json!(key);
    st.save().ok()?;
    Some(b)
}

/// At or past the daily cap of points, for the person behind `by`.
pub fn at_cap(by: &str) -> bool {
    let Some(person) = person_of(by) else { return false };
    today_of(person, &settings(person))["at_cap"] == true
}

// ── Check-ins ───────────────────────────────────────────────────────────────

/// How the day felt, 1 (fresh) to 5 (fried), for the person's today.
pub fn checkin(person: &str, rating: i64) -> Result<()> {
    if !(1..=5).contains(&rating) {
        bail!("a check-in is 1 (fresh) to 5 (fried)");
    }
    let s = settings(person);
    let date = local(&s, now()).1;
    let mut st = open()?;
    if !st.data["checkins"].is_object() {
        st.data["checkins"] = json!({});
    }
    if !st.data["checkins"][person].is_object() {
        st.data["checkins"][person] = json!({});
    }
    st.data["checkins"][person][date] = json!(rating);
    st.save()
}

// ── The summary ─────────────────────────────────────────────────────────────

fn sum(rows: &[&Value], part: &str) -> u64 {
    rows.iter().filter_map(|r| r["parts"][part].as_u64()).sum()
}

/// One day's person rows, summed.
fn day_of(rows: &[&Value]) -> Value {
    json!({
        "points": rows.iter().filter_map(|r| r["points"].as_u64()).sum::<u64>(),
        "decisions": rows.len(),
        "switches": sum(rows, "switch"),
        "interruptions": sum(rows, "interruption"),
        "own_words": rows.iter().filter(|r| r["parts"]["own_words"].is_u64()).count(),
        "late": sum(rows, "late"),
        "landings": sum(rows, "landing"),
        "peak": rows.iter().filter_map(|r| r["running"].as_u64()).max().unwrap_or(0),
    })
}

/// Today's sums for the person, with where they stand against their cap.
fn today_of(person: &str, s: &Value) -> Value {
    let start = day_start(s, now());
    let rows = last_rows(LEDGER_TAIL);
    let mine: Vec<&Value> = rows.iter().filter(|r| r["person"] == person && r["by"] == "person" && r["at"].as_i64().unwrap_or(0) >= start).collect();
    let mut d = day_of(&mine);
    let pts = d["points"].as_u64().unwrap_or(0) as f64;
    let cap = s["cap_points"].as_u64().map(|c| c as f64);
    d["near_cap"] = json!(cap.is_some_and(|c| pts >= NEAR * c));
    d["at_cap"] = json!(cap.is_some_and(|c| pts >= c));
    d
}

/// A cap suggested from the check-ins: halfway between the points of days that
/// felt fresh (1–2) and of days that felt fried (4–5), once there are two of each.
fn suggested_cap(all_days: &BTreeMap<String, (u64, Option<i64>)>) -> Value {
    let avg = |want: &dyn Fn(i64) -> bool| -> Option<(f64, usize)> {
        let v: Vec<u64> = all_days.values().filter(|(_, r)| r.is_some_and(want)).map(|(p, _)| *p).collect();
        (v.len() >= 2).then(|| (v.iter().sum::<u64>() as f64 / v.len() as f64, v.len()))
    };
    match (avg(&|r| r <= 2), avg(&|r| r >= 4)) {
        (Some((fresh, nf)), Some((fried, nd))) if fried > fresh => json!({
            "cap": ((fresh + fried) / 2.0).round() as u64, "fresh": fresh.round() as u64, "fried": fried.round() as u64,
            "fresh_days": nf, "fried_days": nd,
        }),
        _ => Value::Null,
    }
}

/// Everything the page's Focus shows for `person`: settings, today, the
/// autopilot's answers today (with which can still be taken back), the week,
/// the rules, and what waits now and until when.
pub fn overview(person: &str) -> Value {
    let s = settings(person);
    let t = now();
    let rows = last_rows(LEDGER_TAIL);
    let checkins = read()["checkins"][person].clone();
    let start = day_start(&s, t);

    // The days, by the person's date: points and check-in; the last seven in full.
    let mut by_day: BTreeMap<String, Vec<&Value>> = BTreeMap::new();
    for r in rows.iter().filter(|r| r["person"] == person && r["by"] == "person") {
        by_day.entry(local(&s, r["at"].as_i64().unwrap_or(0)).1).or_default().push(r);
    }
    let mut all_days: BTreeMap<String, (u64, Option<i64>)> = BTreeMap::new();
    for (date, list) in &by_day {
        all_days.insert(date.clone(), (list.iter().filter_map(|r| r["points"].as_u64()).sum(), checkins[date].as_i64()));
    }
    for (date, r) in checkins.as_object().into_iter().flatten() {
        all_days.entry(date.clone()).or_insert((0, r.as_i64())).1 = r.as_i64();
    }
    let week: Vec<Value> = (0..7).rev().map(|back| {
        let date = local(&s, start - back * 86400 + 3600).1;
        let list = by_day.get(&date).cloned().unwrap_or_default();
        let mut d = day_of(&list);
        d["date"] = json!(date);
        d["checkin"] = checkins[&date].clone();
        d
    }).collect();

    // The autopilot's answers today; undone ones say so.
    let undone: Vec<(String, u64)> = rows.iter().filter(|r| r["by"] == "undo" && r["person"] == person)
        .map(|r| (r["session"].as_str().unwrap_or("").to_string(), r["n"].as_u64().unwrap_or(0))).collect();
    let undo_s = s["undo_min"].as_i64().unwrap_or(30) * 60;
    let pilot: Vec<Value> = rows.iter().rev()
        .filter(|r| r["person"] == person && r["by"] == "autopilot" && r["at"].as_i64().unwrap_or(0) >= start)
        .take(100)
        .map(|r| {
            let mut v = r.clone();
            let key = (r["session"].as_str().unwrap_or("").to_string(), r["n"].as_u64().unwrap_or(0));
            v["undone"] = json!(undone.contains(&key));
            v["undo_until"] = json!(r["at"].as_i64().unwrap_or(0) + undo_s);
            v
        }).collect();
    let saved: u64 = pilot.iter().filter_map(|r| r["saved"].as_u64()).sum();

    let held = crate::push::needs().into_iter().filter(|n| n["urgent"] != true).count();
    let today = today_of(person, &s);
    json!({
        "person": person, "settings": s, "today": today, "now": t,
        "block": block_at(&s, t), "next_block": next_block(&s, t), "quiet": quiet_at(&s, t),
        "holding": holding(person, t), "held": held, "at_work": at_work(),
        "pilot": pilot, "saved": saved, "week": week, "rules": rules(),
        "checkin": checkins[local(&s, t).1.as_str()].clone(),
        "suggested_cap": suggested_cap(&all_days),
    })
}

/// Take back an answer the autopilot gave (the digest's Undo): the session is
/// told at once, in the person's name, to stop acting on it and ask again. An
/// answer reached the agent the moment it was given, so this is all an undo
/// can be: a correction it hears next, never the answer unsaid.
pub fn undo(person: &str, session: &str, n: u64, by: &str) -> Result<()> {
    let rows = last_rows(LEDGER_TAIL);
    let row = rows.iter().rev().find(|r| r["by"] == "autopilot" && r["session"] == session && r["n"] == n)
        .with_context(|| format!("no answer of the autopilot's at {session} #{n}"))?;
    if row["person"] != person {
        bail!("that answer was given for someone else");
    }
    if rows.iter().any(|r| r["by"] == "undo" && r["session"] == session && r["n"] == n) {
        bail!("taken back already");
    }
    let answer = match &row["answer"] {
        Value::String(s) => s.clone(),
        v => v.to_string(),
    };
    let text = format!("I take back the autopilot's answer to \"{}\" (it answered {}). Stop acting on that answer, undo what you \
        did because of it if you can, and ask me again.", crate::util::short(row["question"].as_str().unwrap_or("its question"), 300),
        crate::util::short(&answer, 300));
    crate::sessions::tell(session, "message", &json!({"text": text, "now": true}), by)?;
    append(&json!({"at": now(), "by": "undo", "person": person, "session": session, "n": n}))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn s(blocks: &[&str], tz: i64) -> Value {
        json!({"blocks": blocks, "tz_min": tz, "quiet_from": "18:30", "quiet_until": "07:00"})
    }

    #[test]
    fn points_add_up_what_a_decision_cost() {
        let base = Facts { kind: "question".into(), at: 1000, asked_at: Some(100), ..Facts::default() };
        assert_eq!(points(&base).0, 1, "waited a while, short, nothing else: one");
        let heavy = Facts { asked_at: Some(950), switched: true, read: 4000, own_words: true, landing: true, late: true, ..base };
        let (p, parts) = points(&heavy);
        assert_eq!(p, 1 + 1 + 1 + 1 + 2 + 1 + 1);
        assert_eq!(parts["interruption"], 1);
        let in_block = Facts { kind: "question".into(), at: 1000, asked_at: Some(990), in_block: true, ..Facts::default() };
        assert_eq!(points(&in_block).0, 1, "answered in a block: no interruption");
        let msg = Facts { kind: "message".into(), at: 1, words: 500, own_words: true, ..Facts::default() };
        assert_eq!(points(&msg).0, 2, "a long message is one more, not two");
    }

    #[test]
    fn blocks_and_quiet_hours_follow_the_persons_clock() {
        // 2026-11-04 14:10 UTC is 15:10 at UTC+1.
        let t = 1_793_801_400;
        assert_eq!(local(&s(&[], 60), t).0, 15 * 60 + 10);
        assert_eq!(block_at(&s(&["10:00", "15:00"], 60), t).as_deref(), Some("15:00"));
        assert_eq!(block_at(&s(&["10:00", "15:00"], 0), t), None, "14:10 in UTC is in no block");
        assert_eq!(next_block(&s(&["10:00", "15:00"], 60), t), Some(t + 18 * 3600 + 50 * 60), "tomorrow 10:00");
        assert!(!quiet_at(&s(&[], 60), t));
        assert!(quiet_at(&s(&[], 60), t + 4 * 3600), "19:10 is past 18:30");
        assert!(quiet_at(&s(&[], 60), t + 15 * 3600), "06:10 is before 07:00");
        assert!(!quiet_at(&json!({"quiet_from": null}), t));
    }

    #[test]
    fn a_recommended_pick_is_seen_and_a_different_one_too() {
        let (_, schema) = crate::acp::question_form(&[json!({"question": "Which?", "header": "Pick",
            "options": [{"label": "A (Recommended)"}, {"label": "B"}]})]);
        let asked = json!({"kind": "question", "schema": schema});
        assert_eq!(recommended_picked(Some(&asked), &json!({"question_0": "A (Recommended)"})), json!(true));
        assert_eq!(recommended_picked(Some(&asked), &json!({"question_0": "B"})), json!(false));
        assert_eq!(recommended_picked(None, &json!({})), Value::Null);
    }

    #[test]
    fn people_are_logins_and_nothing_else() {
        assert_eq!(person_of("web:sam"), Some("sam"));
        for not in ["autopilot", "midas", "runner", "session-s3", "podium:sam", "web:", "web:a:b"] {
            assert_eq!(person_of(not), None, "{not}");
        }
    }

    #[test]
    fn settings_are_checked_and_rules_kept_with_their_state() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|e| e.into_inner());
        crate::tests::scratch("focus-settings");
        assert_eq!(settings("jo")["cap_points"], Value::Null, "off until set");
        let s = set("jo", &json!({"cap_points": 40, "blocks": ["15:00", "9:30", "15:00"], "hold": true, "quiet_from": "18:30"})).unwrap();
        assert_eq!((s["cap_points"].as_i64(), s["blocks"].clone(), s["hold"].as_bool()), (Some(40), json!(["09:30", "15:00"]), Some(true)));
        assert!(set("jo", &json!({"blocks": ["25:00"]})).is_err());
        assert!(set("jo", &json!({"cap_points": 0})).is_err());
        assert_eq!(set("jo", &json!({"cap_points": null})).unwrap()["cap_points"], Value::Null);

        suggest("Take a free build node when one is needed", "15 of 15", "s1").unwrap();
        suggest("take a free build node when one is needed", "again", "s2").unwrap();
        assert_eq!(rules().len(), 1, "the same words are not proposed twice");
        assert!(approved().is_empty(), "a proposal is not a rule until approved");
        let id = rules()[0]["id"].as_str().unwrap().to_string();
        rule_op(&json!({"op": "approve", "id": id}), "web:jo").unwrap();
        assert_eq!(approved().len(), 1);
        rule_op(&json!({"op": "add", "text": "Rebase onto main before building"}), "web:jo").unwrap();
        assert_eq!(approved().len(), 2);
        assert!(rule_op(&json!({"op": "add", "text": "  "}), "web:jo").is_err());
        rule_op(&json!({"op": "reject", "id": id}), "web:jo").unwrap();
        assert_eq!(approved().len(), 1);
        suggest("Take a free build node when one is needed", "", "s3").unwrap();
        assert_eq!(rules().len(), 2, "a rejected rule is not proposed again");
    }

    #[test]
    fn the_cap_and_a_block_hold_what_can_wait() {
        let _g = crate::tests::SERIAL.lock().unwrap_or_else(|e| e.into_inner());
        crate::tests::scratch("focus-cap");
        set("jo", &json!({"cap_points": 3})).unwrap();
        assert!(!holding("jo", now()));
        for i in 0..3 {
            record("jo", &format!("s{i}"), "question", None, "", &json!({}), false, 0);
        }
        assert!(at_cap("web:jo"), "three decisions at a cap of three");
        assert!(holding("jo", now()), "near the cap, what can wait is held");
        assert!(!at_cap("runner"));
        let o = overview("jo");
        assert_eq!(o["today"]["decisions"], 3);
        assert_eq!(o["today"]["switches"], 2, "each from another session than the last");
        assert_eq!(o["week"].as_array().unwrap().len(), 7);
        checkin("jo", 4).unwrap();
        assert!(checkin("jo", 9).is_err());
        assert_eq!(overview("jo")["checkin"], 4);
    }
}