git clone https://garage44.eu/jeroen/midas.git.. /src/templates.rs
//! Templates and schedules: sessions started from a brief kept for the
//! purpose, now or on a clock, with the autopilot driving them (autopilot.rs).
//!
//! A **template** is a brief with a name — "find one performance improvement,
//! measured" — written so that what counts as done is in it: measure first,
//! one change, land only with evidence, finish without landing when nothing
//! turns up. Started, it is one session per project chosen, each told which
//! template and project it is in. Every change to its brief is a **version**
//! saying who made it and why, and any version can be put back.
//!
//! A **schedule** starts a template on a clock (every night, on weekdays, once
//! a week, at a time kept in UTC; the page shows the person's own), but only
//! when the last sessions it started have finished: it never piles up. Its
//! runs' outcomes are kept, and **two runs in a row that land nothing pause
//! it**, said on the page, until the person resumes it. That is the answer to
//! what sank the earlier self-filing autopilot (cartopolis, retired
//! 2026-09-11): work nobody asked for, piling up unseen. Here a person chose
//! the template, the projects and the clock, and a schedule that stops paying
//! stops by itself.
//!
//! **Midas keeps a template up**, as the person allows per template (`editors`:
//! `me`, `propose` or `midas`): after each run of it finishes, a runner reads
//! that session's conversation and its outcome with Claude Code and says
//! whether the brief should change — a trap the run fell into, a clash with
//! other work, a measuring rule — as a whole new brief and why. With `midas` it
//! is a new version at once; with `propose` it waits on the page for the
//! person's yes; with `me` nothing is asked.
//!
//! All of it is one file beside the sessions, `hosted/templates.json`.
use std::path::PathBuf;
use std::sync::Mutex;
use anyhow::{bail, Context, Result};
use serde_json::{json, Value};
use crate::registry::now;
/// The longest brief, name and extra line.
const BRIEF_MAX: usize = 16 * 1024;
const NAME_MAX: usize = 60;
const EXTRA_MAX: usize = 2000;
/// Versions and runs kept per template.
const VERSIONS_KEPT: usize = 30;
const RUNS_KEPT: usize = 60;
/// Runs in a row that land nothing before a schedule pauses.
const PAUSE_AFTER: usize = 2;
/// A review a runner took and never answered is asked again after this long.
const REVIEW_RETRY_S: i64 = 3600;
/// How long a review may take.
const REVIEW_RUN_S: u64 = 420;
/// The model that reviews, unless `MIDAS_AUTOPILOT_MODEL` names another.
const MODEL: &str = "opus";
static LOCK: Mutex<()> = Mutex::new(());
fn path() -> PathBuf {
crate::registry::root().join("hosted").join("templates.json")
}
/// The templates a workshop starts with: what the person asked for first
/// (2026-10-29), each with its own definition of done.
fn defaults() -> Value {
let t = |id: &str, icon: &str, name: &str, brief: &str| json!({"id": id, "icon": icon, "name": name, "brief": brief, "editors": "midas",
"versions": [{"v": 1, "brief": brief, "by": "midas", "why": "the template midas starts with", "at": now()}], "runs": []});
json!({"seq": 4, "schedules": [], "templates": [
t("t1", "⚡", "Performance", "Find one performance improvement in this project and land it with numbers.\n\n\
1. Measure first, with the project's own tools (its CLAUDE.md and notes say how): find where the time or the memory goes.\n\
2. Choose the costliest place you can improve safely. One change.\n\
3. Measure again, the same way. Land it only when it is measurably better, with the numbers before and after in the commit body.\n\
4. If nothing worth changing turns up, say what you measured and finish without landing.\n\n\
Change no behaviour, and start nothing else."),
t("t2", "✂", "Code cleanup", "Make this project's code simpler without changing what it does.\n\n\
1. Start from what changed in the last two weeks (git log): dead code, duplicates, functions too long to read, names that say the wrong thing.\n\
2. Choose one coherent cleanup.\n\
3. The tests pass before and after; add one where the change is not covered.\n\
4. Land it when the gate passes. If nothing is worth it, finish without landing.\n\n\
Change no behaviour, and start nothing else."),
t("t3", "✓", "Tests", "Find code in this project that landed in the last week with no test that exercises it.\n\n\
1. Choose its most important path.\n\
2. Write tests that fail when that code is broken: break it, see them fail, put it back.\n\
3. Land the tests when the gate passes.\n\n\
Leave the code itself alone, unless a test finds a real bug: then fix that one bug and say so in the commit."),
t("t4", "🩹", "Red builds", "Find what fails in this project: its last CI runs and landing gates, and its test suite on main.\n\n\
1. Choose one failure and find its cause.\n\
2. Fix the cause, never the test.\n\
3. Land the fix when the gate passes.\n\n\
If everything is green, say so and finish without landing."),
]})
}
/// The file; the first time, the defaults, written down so they stay as they were made.
fn load() -> Value {
if let Some(v) = crate::store::read::<Value>(&path()).filter(|v| v["templates"].is_array()) {
return v;
}
let v = defaults();
if !path().exists() {
let _ = save(&v);
}
v
}
fn save(v: &Value) -> Result<()> {
let p = path();
if let Some(dir) = p.parent() {
std::fs::create_dir_all(dir)?;
}
crate::store::write_atomic(&p, serde_json::to_string_pretty(v)?.as_bytes(), crate::store::PUBLIC)?;
crate::ws::nudge();
Ok(())
}
/// Change the file under the lock: read, `f`, written when `f` succeeds.
fn change<R>(f: impl FnOnce(&mut Value) -> Result<R>) -> Result<R> {
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
let mut v = load();
let r = f(&mut v)?;
save(&v)?;
Ok(r)
}
/// As `change`, written only when `f` changed something: the hub's watch runs it twice a minute.
fn change_quiet<R>(f: impl FnOnce(&mut Value) -> Result<R>) -> Result<R> {
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
let mut v = load();
let before = v.clone();
let r = f(&mut v)?;
if v != before {
save(&v)?;
}
Ok(r)
}
/// Everything, for the page.
pub fn all() -> Value {
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
load()
}
fn next_id(v: &mut Value, prefix: &str) -> String {
let n = v["seq"].as_u64().unwrap_or(0) + 1;
v["seq"] = json!(n);
format!("{prefix}{n}")
}
fn find<'a>(list: &'a mut Value, id: &str) -> Result<&'a mut Value> {
list.as_array_mut().into_iter().flatten().find(|t| t["id"] == id).with_context(|| format!("no {id}"))
}
/// A new version of `t`'s brief, kept with who and why.
fn new_version(t: &mut Value, brief: &str, by: &str, why: &str, session: Option<&str>) {
let v = t["versions"].as_array().and_then(|a| a.last()).and_then(|l| l["v"].as_u64()).unwrap_or(0) + 1;
t["brief"] = json!(brief);
let versions = t["versions"].as_array_mut();
let entry = json!({"v": v, "brief": brief, "by": by, "why": why, "at": now(), "session": session});
match versions {
Some(list) => {
list.push(entry);
let extra = list.len().saturating_sub(VERSIONS_KEPT);
list.drain(..extra);
}
None => t["versions"] = json!([entry]),
}
t["proposal"] = Value::Null;
}
fn text(v: &Value, k: &str, max: usize, what: &str) -> Result<String> {
let s = v[k].as_str().unwrap_or("").trim().to_string();
if s.len() > max {
bail!("{what} of at most {max} bytes");
}
Ok(s)
}
fn editors_ok(e: &str) -> Result<&str> {
match e {
"me" | "propose" | "midas" => Ok(e),
_ => bail!("who may change a template: me, propose or midas"),
}
}
fn repeat_ok(r: &str) -> Result<&str> {
match r {
"daily" | "weekdays" | "weekly" => Ok(r),
_ => bail!("a schedule repeats daily, weekdays or weekly"),
}
}
/// The projects asked for, each one of the workspace's.
fn repos_ok(v: &Value) -> Result<Vec<String>> {
let known: Vec<String> = crate::sessions::projects().as_array().into_iter().flatten()
.filter_map(|p| p["repo"].as_str().map(str::to_string)).collect();
let repos: Vec<String> = v.as_array().into_iter().flatten().filter_map(|r| r.as_str().map(str::to_string)).collect();
if repos.is_empty() {
bail!("choose a project at least");
}
for r in &repos {
if !known.contains(r) {
bail!("{r} is not one of the workspace's projects");
}
}
Ok(repos)
}
/// The first time after `t` a schedule fires: `minute` past midnight UTC, on
/// the days its `repeat` says (weekly: `weekday`, Monday 0).
pub fn next_after(repeat: &str, minute: i64, weekday: i64, t: i64) -> i64 {
let day0 = t.div_euclid(86400);
for d in day0..day0 + 8 {
// 1970-01-01 was a Thursday: Monday is 0.
let wd = (d + 3).rem_euclid(7);
let fits = match repeat {
"weekdays" => wd < 5,
"weekly" => wd == weekday,
_ => true,
};
let at = d * 86400 + minute * 60;
if fits && at > t {
return at;
}
}
t + 86400
}
/// What the page asks (`POST /v1/hosted/templates`), by `op`; the whole state after.
pub fn op(body: &Value, by: &str) -> Result<Value> {
let id = body["id"].as_str().unwrap_or("").to_string();
match body["op"].as_str().unwrap_or("") {
"save" => change(|v| {
let name = text(body, "name", NAME_MAX, "a name")?;
let brief = text(body, "brief", BRIEF_MAX, "a brief")?;
let icon = crate::util::short(body["icon"].as_str().unwrap_or("").trim(), 8);
let editors = editors_ok(body["editors"].as_str().unwrap_or("propose"))?.to_string();
if name.is_empty() || brief.is_empty() {
bail!("a template has a name and a brief");
}
if id.is_empty() {
let tid = next_id(v, "t");
let mut t = json!({"id": tid, "name": name, "icon": icon, "editors": editors, "runs": [], "versions": []});
new_version(&mut t, &brief, by, "made", None);
v["templates"].as_array_mut().context("templates")?.push(t);
} else {
let t = find(&mut v["templates"], &id)?;
t["name"] = json!(name);
t["icon"] = json!(icon);
t["editors"] = json!(editors);
if t["brief"] != brief.as_str() {
let why = text(body, "why", 500, "a reason")?;
new_version(t, &brief, by, if why.is_empty() { "edited" } else { &why }, None);
}
}
Ok(())
})?,
"revert" => change(|v| {
let t = find(&mut v["templates"], &id)?;
let to = body["v"].as_u64().context("which version (v)?")?;
let brief = t["versions"].as_array().into_iter().flatten().find(|x| x["v"] == to)
.and_then(|x| x["brief"].as_str()).map(str::to_string).with_context(|| format!("no version {to}"))?;
new_version(t, &brief, by, &format!("back to version {to}"), None);
Ok(())
})?,
"accept" | "reject" => change(|v| {
let accept = body["op"] == "accept";
let t = find(&mut v["templates"], &id)?;
let p = t["proposal"].take();
let brief = p["brief"].as_str().context("nothing proposed")?;
if accept {
new_version(t, brief, "midas", p["why"].as_str().unwrap_or(""), p["session"].as_str());
t["versions"].as_array_mut().and_then(|l| l.last_mut()).map(|l| l["accepted_by"] = json!(by));
}
Ok(())
})?,
"delete" => change(|v| {
v["templates"].as_array_mut().context("templates")?.retain(|t| t["id"] != id.as_str());
v["schedules"].as_array_mut().into_iter().for_each(|s| s.retain(|s| s["template"] != id.as_str()));
Ok(())
})?,
"schedule" => change(|v| {
let s = schedule_of(v, body, by)?;
let list = v["schedules"].as_array_mut().context("schedules")?;
match list.iter_mut().find(|x| x["id"] == s["id"]) {
Some(x) => *x = s,
None => list.push(s),
}
Ok(())
})?,
"schedule_on" => change(|v| {
let s = find(&mut v["schedules"], &id)?;
let on = body["on"] == true;
s["on"] = json!(on);
if on {
// Resumed: what paused it is counted no more.
s["paused"] = Value::Null;
s["resumed_at"] = json!(now());
s["next"] = json!(next_after(s["repeat"].as_str().unwrap_or("daily"), s["minute"].as_i64().unwrap_or(0), s["weekday"].as_i64().unwrap_or(0), now()));
}
Ok(())
})?,
"schedule_delete" => change(|v| {
v["schedules"].as_array_mut().context("schedules")?.retain(|s| s["id"] != id.as_str());
Ok(())
})?,
// Started now: one session per project; with `repeat`, a schedule too, this its first run.
"start" => {
let sched = if body["repeat"].as_str().is_some_and(|r| !r.is_empty() && r != "once") {
Some(change(|v| {
let mut b = body.clone();
b["id"] = Value::Null;
b["on"] = json!(true);
let s = schedule_of(v, &b, by)?;
let sid = s["id"].as_str().unwrap_or("").to_string();
v["schedules"].as_array_mut().context("schedules")?.push(s);
Ok(sid)
})?)
} else {
None
};
let t = body["template"].as_str().unwrap_or("").to_string();
let started = start(&t, &repos_ok(&body["repos"])?, &text(body, "extra", EXTRA_MAX, "the extra line")?,
body["mode"].as_str(), body["model"].as_str(), body["autopilot"] != false, sched.as_deref(), by)?;
let mut all = all();
all["started"] = json!(started);
return Ok(all);
}
_ => bail!("a template op is save, revert, accept, reject, delete, schedule, schedule_on, schedule_delete or start"),
}
Ok(all())
}
/// A schedule as `body` describes it, checked; new ones get an id.
fn schedule_of(v: &mut Value, body: &Value, by: &str) -> Result<Value> {
let template = body["template"].as_str().unwrap_or("");
if !v["templates"].as_array().into_iter().flatten().any(|t| t["id"] == template) {
bail!("no template {template}");
}
let repeat = repeat_ok(body["repeat"].as_str().unwrap_or(""))?;
let minute = body["minute"].as_i64().filter(|m| (0..1440).contains(m)).context("a time of day (minute, 0–1439 UTC)")?;
let weekday = body["weekday"].as_i64().unwrap_or(0).rem_euclid(7);
let id = match body["id"].as_str().filter(|i| !i.is_empty()) {
Some(i) => i.to_string(),
None => next_id(v, "sch"),
};
let old = v["schedules"].as_array().into_iter().flatten().find(|s| s["id"] == id.as_str()).cloned().unwrap_or(Value::Null);
Ok(json!({
"id": id, "template": template, "repos": repos_ok(&body["repos"])?, "extra": text(body, "extra", EXTRA_MAX, "the extra line")?,
"repeat": repeat, "minute": minute, "weekday": weekday,
"mode": body["mode"].as_str().filter(|m| !m.is_empty()), "model": body["model"].as_str().filter(|m| !m.is_empty()),
"autopilot": body["autopilot"] != false, "on": body["on"] != false, "paused": old["paused"], "resumed_at": old["resumed_at"],
"by": old["by"].as_str().unwrap_or(by), "created": old["created"].as_i64().unwrap_or(now()),
"next": next_after(repeat, minute, weekday, now()),
}))
}
/// Start template `t` in each of `repos`: its brief, the extra line, and where
/// it comes from; titled by the template; its autopilot on when asked.
#[allow(clippy::too_many_arguments)]
fn start(t: &str, repos: &[String], extra: &str, mode: Option<&str>, model: Option<&str>, autopilot: bool, schedule: Option<&str>, by: &str) -> Result<Vec<String>> {
let tpl = all()["templates"].as_array().into_iter().flatten().find(|x| x["id"] == t).cloned().with_context(|| format!("no template {t}"))?;
let name = tpl["name"].as_str().unwrap_or("Template").to_string();
let version = tpl["versions"].as_array().and_then(|a| a.last()).map(|l| l["v"].clone()).unwrap_or(json!(1));
let mut ids = Vec::new();
for repo in repos {
let project = repo.rsplit('/').next().unwrap_or(repo);
let mut prompt = tpl["brief"].as_str().unwrap_or("").trim().to_string();
if !extra.is_empty() {
prompt.push_str(&format!("\n\nAlso: {extra}"));
}
prompt.push_str(&format!("\n\n(Started from the template \"{name}\"{}, in the project {repo}: work in that project only.)",
if schedule.is_some() { " on a schedule" } else { "" }));
let id = crate::sessions::start(by, &prompt, Some(repo), None, mode, model, None, &json!([]))?;
let _ = crate::sessions::set_title(&id, &format!("{name}: {project}"), by);
crate::sessions::set_template(&id, &json!({"id": t, "name": name, "v": version, "schedule": schedule}))?;
if autopilot {
crate::sessions::tell(&id, "autopilot", &json!({"on": true}), by)?;
}
ids.push(id.clone());
change(|v| {
let tp = find(&mut v["templates"], t)?;
if !tp["runs"].is_array() {
tp["runs"] = json!([]);
}
let list = tp["runs"].as_array_mut().context("runs")?;
list.push(json!({"session": id, "repo": repo, "at": now(), "schedule": schedule, "outcome": null, "review": null}));
let extra = list.len().saturating_sub(RUNS_KEPT);
list.drain(..extra);
Ok(())
})?;
}
crate::events::emit("template_started", json!({"actor": by, "template": t, "sessions": ids, "schedule": schedule}));
Ok(ids)
}
/// A run's outcome from its session: `landed`, `dropped`, `done` once it is
/// finished, `ended` when it stopped unfinished; none while it goes on.
fn outcome_of(session: &str) -> Option<String> {
let m = crate::sessions::meta(session).ok()?;
if let Some(o) = m["finished"]["outcome"].as_str() {
return Some(o.to_string());
}
matches!(m["status"].as_str(), Some("stopped" | "failed")).then(|| "ended".to_string())
}
/// The hub's watch (every half minute): runs' outcomes, schedules that pause,
/// and schedules due.
pub fn tick() {
let due: Vec<Value> = match change_quiet(|v| {
let t = now();
// Outcomes, as their sessions finish.
for tp in v["templates"].as_array_mut().into_iter().flatten() {
for run in tp["runs"].as_array_mut().into_iter().flatten().filter(|r| r["outcome"].is_null()) {
if let Some(o) = run["session"].as_str().and_then(outcome_of) {
run["outcome"] = json!(o);
run["ended"] = json!(t);
}
}
}
let runs_of = |v: &Value, sid: &str| -> Vec<Value> {
v["templates"].as_array().into_iter().flatten().flat_map(|tp| tp["runs"].as_array().cloned().unwrap_or_default())
.filter(|r| r["schedule"] == sid).collect()
};
let mut due = Vec::new();
let ids: Vec<String> = v["schedules"].as_array().into_iter().flatten().filter_map(|s| s["id"].as_str().map(str::to_string)).collect();
for sid in ids {
let runs = runs_of(v, &sid);
let s = find(&mut v["schedules"], &sid)?;
// Two runs in a row since it was last resumed, ended and landing nothing: paused.
let since = s["resumed_at"].as_i64().unwrap_or(0);
let mut ended: Vec<&Value> = runs.iter().filter(|r| r["at"].as_i64().unwrap_or(0) >= since && !r["outcome"].is_null()).collect();
ended.sort_by_key(|r| r["ended"].as_i64().unwrap_or(0));
let last: Vec<&&Value> = ended.iter().rev().take(PAUSE_AFTER).collect();
if s["paused"].is_null() && last.len() == PAUSE_AFTER && last.iter().all(|r| r["outcome"] != "landed") {
s["paused"] = json!(format!("{PAUSE_AFTER} runs in a row landed nothing"));
crate::events::emit("schedule_paused", json!({"actor": "midas", "schedule": sid}));
}
if s["on"] != true || !s["paused"].is_null() || s["next"].as_i64().unwrap_or(0) > t {
continue;
}
// Its person is at the daily cap they set on their decisions (focus.rs): it waits, still
// due, and starts once their day turns over.
if crate::focus::at_cap(s["by"].as_str().unwrap_or("")) {
if s["held"].is_null() {
s["held"] = json!("its person is at their daily cap");
crate::events::emit("schedule_held", json!({"actor": "midas", "schedule": sid}));
}
continue;
}
if s["held"].is_string() {
s["held"] = Value::Null;
}
let repeat = s["repeat"].as_str().unwrap_or("daily").to_string();
s["next"] = json!(next_after(&repeat, s["minute"].as_i64().unwrap_or(0), s["weekday"].as_i64().unwrap_or(0), t));
// Never piled up: the last run still goes on, so this one is skipped.
if runs.iter().any(|r| r["outcome"].is_null()) {
s["skipped"] = json!(t);
continue;
}
due.push(s.clone());
}
Ok(due)
}) {
Ok(d) => d,
Err(e) => {
crate::events::emit("error", json!({"what": format!("the schedules: {e:#}")}));
return;
}
};
for s in due {
let repos: Vec<String> = s["repos"].as_array().into_iter().flatten().filter_map(|r| r.as_str().map(str::to_string)).collect();
let by = s["by"].as_str().unwrap_or("midas").to_string();
if let Err(e) = start(s["template"].as_str().unwrap_or(""), &repos, s["extra"].as_str().unwrap_or(""), s["mode"].as_str(),
s["model"].as_str(), s["autopilot"] != false, s["id"].as_str(), &by) {
crate::events::emit("error", json!({"what": format!("schedule {}: {e:#}", s["id"].as_str().unwrap_or("?"))}));
}
}
}
// ── Midas keeping a template up ─────────────────────────────────────────────
/// For the runner's poll: runs that ended and whose template midas may change,
/// not reviewed yet (or asked long ago and never answered). Taken once.
pub fn reviews_take() -> Vec<Value> {
// Asked on every poll: written only when there is something to take.
let _l = LOCK.lock().unwrap_or_else(|p| p.into_inner());
let mut v = load();
let jobs = (|v: &mut Value| -> Result<Vec<Value>> {
let mut jobs = Vec::new();
for tp in v["templates"].as_array_mut().into_iter().flatten() {
if tp["editors"] == "me" {
continue;
}
let (tid, brief, name) = (tp["id"].clone(), tp["brief"].clone(), tp["name"].clone());
for run in tp["runs"].as_array_mut().into_iter().flatten() {
let stale = run["review"]["state"] == "asked" && run["review"]["at"].as_i64().unwrap_or(0) + REVIEW_RETRY_S <= now();
if run["outcome"].is_null() || !(run["review"].is_null() || stale) {
continue;
}
run["review"] = json!({"state": "asked", "at": now()});
jobs.push(json!({"template": tid, "name": name, "brief": brief, "session": run["session"], "outcome": run["outcome"]}));
}
}
Ok(jobs)
})(&mut v).unwrap_or_default();
if !jobs.is_empty() && save(&v).is_err() {
return Vec::new();
}
jobs
}
/// A runner's review of a run (`POST /v1/hosted/runner/review`): a new brief
/// and why, or none; kept as the template's editors allow.
pub fn reviewed(body: &Value) -> Result<()> {
let tid = body["template"].as_str().unwrap_or("");
let session = body["session"].as_str().unwrap_or("");
change(|v| {
let tp = find(&mut v["templates"], tid)?;
let brief = body["brief"].as_str().map(str::trim).filter(|b| !b.is_empty() && b.len() <= BRIEF_MAX && *b != tp["brief"].as_str().unwrap_or(""));
let why = crate::util::short(body["why"].as_str().unwrap_or("").trim(), 1000);
let state = if !body["error"].is_null() { "failed" } else if brief.is_some() { "changed" } else { "kept" };
if let Some(run) = tp["runs"].as_array_mut().into_iter().flatten().find(|r| r["session"] == session) {
run["review"] = json!({"state": state, "at": now(), "why": if state == "failed" { body["error"].clone() } else { json!(why) }});
}
if let Some(b) = brief {
match tp["editors"].as_str() {
Some("midas") => new_version(tp, b, "midas", &why, Some(session)),
Some("propose") => tp["proposal"] = json!({"brief": b, "why": why, "session": session, "at": now()}),
_ => {}
}
}
Ok(())
})
}
/// How a review is to be done: the system prompt.
const REVIEW_RULES: &str = "You keep a session template of midas, a build workshop, up to date. A template is the brief a session is \
started with; you are shown it and one session that ran from it, with how that session ended. Say whether the brief should change \
because of what this run showed: a trap it fell into that a line would have avoided, a clash with other work, a measuring rule, a \
step that wasted its time. Most runs need no change: then keep it. A change is small and to the point; keep the person's lines \
unless the run proved them wrong; never widen what the template asks for; keep it short. Answer with one JSON object and nothing \
else: {\"keep\": true, \"why\": \"…\"} or {\"brief\": \"<the whole new brief>\", \"why\": \"<one or two plain sentences: what in this \
run calls for it>\"}.";
/// Review a run the poll handed this runner, and tell the hub.
pub fn review(job: &Value) {
let session = job["session"].as_str().unwrap_or("").to_string();
let result = (|| -> Result<Value> {
let log = crate::client::get(&format!("/v1/hosted/{session}/log"))?;
let items = log["items"].as_array().cloned().unwrap_or_default();
let prompt = format!("## The template \"{}\"\n{}\n\n## How the session ended\n{}\n\n{}",
job["name"].as_str().unwrap_or(""), job["brief"].as_str().unwrap_or(""), job["outcome"].as_str().unwrap_or("?"),
crate::autopilot::digest(&items));
let home = crate::sessions::sessions_home().context("the runner has no sessions directory")?;
let dir = crate::sessions::worktree_of(&session).filter(|w| w.is_dir()).unwrap_or(home);
let model = crate::client::setting("MIDAS_AUTOPILOT_MODEL").unwrap_or_else(|| MODEL.into());
let said = crate::ask::read_only(&dir, &prompt, REVIEW_RULES, &model, REVIEW_RUN_S)?;
let start = said.find('{').context("no answer")?;
let end = said.rfind('}').filter(|e| *e >= start).context("no answer")?;
let v: Value = serde_json::from_str(&said[start..=end]).context("no answer it could read")?;
Ok(json!({"brief": if v["keep"] == true { Value::Null } else { v["brief"].clone() }, "why": v["why"]}))
})();
let mut body = match result {
Ok(v) => v,
Err(e) => json!({"error": format!("{e:#}")}),
};
body["template"] = job["template"].clone();
body["session"] = json!(session);
eprintln!("template {}: reviewed after {session}: {}", job["template"].as_str().unwrap_or("?"),
if !body["error"].is_null() { "failed" } else if body["brief"].is_string() { "a change" } else { "kept" });
if let Err(e) = crate::client::post("/v1/hosted/runner/review", &body) {
eprintln!("template review: could not tell the hub: {e:#}");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_schedule_fires_on_its_days_at_its_time() {
// 2026-10-29 was a Thursday; 12:00 UTC.
let thu_noon = 20755 * 86400 + 12 * 3600;
assert_eq!((20755 + 3) % 7, 3, "Thursday is 3, Monday 0");
// Daily at 02:00: tomorrow; at 13:00: today.
assert_eq!(next_after("daily", 120, 0, thu_noon), 20756 * 86400 + 7200);
assert_eq!(next_after("daily", 780, 0, thu_noon), 20755 * 86400 + 780 * 60);
// Weekdays at 02:00 from Friday noon: Monday.
assert_eq!(next_after("weekdays", 120, 0, thu_noon + 86400), (20756 + 3) * 86400 + 7200);
// Weekly on Monday (0) from Thursday: four days on.
assert_eq!(next_after("weekly", 360, 0, thu_noon), (20755 + 4) * 86400 + 360 * 60);
}
#[test]
fn a_new_version_keeps_who_and_why() {
let mut t = json!({"brief": "a", "versions": [{"v": 1, "brief": "a"}]});
new_version(&mut t, "b", "midas", "a run clashed", Some("s9"));
assert_eq!(t["brief"], "b");
assert_eq!(t["versions"][1]["v"], 2);
assert_eq!((t["versions"][1]["by"].as_str(), t["versions"][1]["session"].as_str()), (Some("midas"), Some("s9")));
}
#[test]
fn the_defaults_each_say_when_they_are_done() {
for t in defaults()["templates"].as_array().unwrap() {
let b = t["brief"].as_str().unwrap();
assert!(b.contains("Land") || b.contains("land"), "{} says when to land", t["name"]);
assert!(b.contains("finish without landing") || b.contains("Leave the code"), "{} says what to do with nothing to land", t["name"]);
}
}
}