//! The autopilot: a session's questions, permission requests and pauses //! answered by an agent standing in for the person, when they turn it on. //! //! It is the person's to turn on and off, per session (the page's Autopilot //! chip, or many at once: Take over), and it is kept in the session's meta //! (`autopilot`: on, who, until when, the goal) so a runner that starts again //! takes it back with the session. The runner does the deciding, where the //! agent's login and the session's worktrees are: each time the session asks //! — a permission request, a question form, or a turn that ends with nothing //! queued — it hands the question to Claude Code, read-only in the session's //! folder, with the conversation (the person's words in full, the rest from //! its end) and the goal, and Claude answers in one JSON object: an option, the //! form's answers, the next thing to say, "done", or "leave it to the person". //! //! What it may decide is everything the person may, landing and deploying //! included (the person's choice, 2026-10-29). What it leaves is what cannot //! be taken back and was not asked for (data destroyed, money spent, something //! published outside), and anything the conversation does not settle: that //! waits for the person as before, and their phone is told (push.rs). //! //! It reads the person's approved rules and earlier answers (focus.rs), says on //! what each answer rests (a rule, a precedent, its judgement) and whether it is //! sure, proposes a rule when their answers repeat, and marks what it leaves as //! needing them now or able to wait for their next decision block. A session //! without the autopilot asks it too, when the person applies their rules //! everywhere: then only a rule may answer (`decide_by_rules`). //! //! The person goes first: the page's buttons stay while it thinks, and //! whichever answer reaches the runner first is the one taken; a message they //! send stops its "what next" (sessions.rs drops a decision the session has //! moved past). Every decision is in the conversation, with its reason. //! //! Before this there was no autopilot of any kind: `docs/hub.md` said every //! permission waits for a person. An earlier autopilot (cartopolis, retired //! 2026-09-11) filed tickets by itself and was stopped for filing invented //! work; this one only answers sessions a person started or scheduled from a //! template (templates.rs), and stops itself after a run of its own messages. use std::collections::BTreeSet; use anyhow::{bail, Result}; use serde_json::{json, Value}; use crate::registry::now; /// The model that decides, unless the runner's `MIDAS_AUTOPILOT_MODEL` names /// another: it stands in for the person, so the best one. const MODEL: &str = "opus"; /// How long a decision may take before it is left to the person. const RUN_S: u64 = 420; /// Its own messages in a row, with nothing from the person between, before it /// stops: a session and its autopilot must not talk to each other for ever. pub const MAX_NUDGES: u32 = 8; /// The longest goal it is given. const GOAL_MAX: usize = 4000; /// How much of the conversation it reads: the person's words, and the rest. const ASKED_BUDGET: usize = 24_000; const RECENT_BUDGET: usize = 36_000; /// Who it is in the log, the inbox and the conversation. pub const BY: &str = "autopilot"; /// A change to a session's autopilot as the page asks it (`tell`, kind /// `autopilot`): on or off; until when (a unix time, or none: until turned /// off); and the goal, empty for "what the person asked in the session". pub fn change(fields: &Value) -> Result { let on = fields["on"] == true; let until = fields["until"].as_i64().filter(|_| on); if until.is_some_and(|u| u <= now()) { bail!("an autopilot until a time to come"); } let goal = if on { fields["goal"].as_str().unwrap_or("").trim().to_string() } else { String::new() }; if goal.len() > GOAL_MAX { bail!("a goal of at most {GOAL_MAX} bytes"); } Ok(json!({"on": on, "until": until, "goal": goal})) } /// The meta's `autopilot` after the person changed it. pub fn meta_of(change: &Value, by: &str) -> Value { if change["on"] != true { return json!({"on": false, "by": by, "at": now()}); } json!({"on": true, "by": by, "at": now(), "until": change["until"], "goal": change["goal"], "state": "idle"}) } /// The meta's `autopilot` after what a runner reported (`sessions::push`): /// whether it is deciding, left something to the person, or is idle; and off /// when it turned itself off (its time ran out, it said too much). pub fn follow(pilot: &mut Value, items: &[Value]) -> bool { if pilot["on"] != true { return false; } let mut changed = false; for it in items { let state = match it["kind"].as_str() { Some("autopilot") if it["on"] == false => { *pilot = json!({"on": false, "by": it["by"], "at": now(), "why": it["why"]}); return true; } Some("autopilot_deciding") => "deciding", Some("autopilot_left") => { // Whether it needs the person now or can wait for their next block (focus.rs); // a runner from before said nothing, and every leave needed them now. pilot["left_urgent"] = json!(it["urgent"] != false); changed = true; "left" } Some("autopilot_done" | "autopilot_idle") => "idle", Some("permission_answered" | "answered") => "idle", Some("user") => "idle", _ => continue, }; if pilot["state"] != state { pilot["state"] = json!(state); changed = true; } if state == "left" { pilot["left_why"] = it["why"].clone(); } } changed } /// The autopilot on for many sessions at once (the page's Take over): `ids`, /// with one goal and time for all. One that ended unfinished is reopened /// first; one finished, or in an editor, is passed over and said why. pub fn take_over(body: &Value, by: &str) -> Result { let c = change(body)?; let mut taken = Vec::new(); let mut passed = serde_json::Map::new(); for id in body["ids"].as_array().into_iter().flatten().filter_map(Value::as_str) { let done = (|| -> Result<()> { let m = crate::sessions::meta(id)?; if m["finished"].is_object() || m["imported"].is_object() { bail!("it is finished"); } if c["on"] == true && matches!(m["status"].as_str(), Some("stopped" | "failed")) { crate::sessions::reopen(id, by, "taken over by the autopilot")?; } crate::sessions::tell(id, "autopilot", &c, by) })(); match done { Ok(()) => taken.push(json!(id)), Err(e) => { passed.insert(id.to_string(), json!(format!("{e:#}"))); } } } Ok(json!({"taken": taken, "passed": passed})) } // ── The runner's side ─────────────────────────────────────────────────────── /// A session's autopilot, as its runner holds it. #[derive(Default)] pub struct Pilot { pub on: bool, pub until: Option, pub goal: String, /// Its own messages since the person last said something. pub nudges: u32, /// What it is deciding now: a request's id, or `next`. pub deciding: BTreeSet, } impl Pilot { /// As the session's meta has it, when its runner starts it. pub fn of_meta(m: &Value) -> Pilot { let a = &m["autopilot"]; let on = a["on"] == true && a["until"].as_i64().is_none_or(|u| u > now()); Pilot { on, until: a["until"].as_i64(), goal: a["goal"].as_str().unwrap_or("").to_string(), ..Pilot::default() } } /// Set as the person changed it (`change`). pub fn set(&mut self, c: &Value) { self.on = c["on"] == true; self.until = c["until"].as_i64(); self.goal = c["goal"].as_str().unwrap_or("").to_string(); self.nudges = 0; if !self.on { self.deciding.clear(); } } /// Its time has run out. pub fn expired(&self) -> bool { self.on && self.until.is_some_and(|u| u <= now()) } } /// What it is asked to decide. pub enum Ask { /// A permission request: its id (as the runner keys it) and its log item. Permission(String, Value), /// A question form: its id and its log item (message, schema). Question(String, Value), /// The session's turn ended and nothing waits for it: what next. Next, } impl Ask { /// The key it is decided under in `Pilot::deciding`. pub fn key(&self) -> String { match self { Ask::Permission(r, _) | Ask::Question(r, _) => r.clone(), Ask::Next => "next".into(), } } } /// Decide `ask` for session `id`, whose folder is `work`, in the background: /// `answer` is given what the runner should do with it, as an inbox item would /// say it (`permit`, `answer`, `message`, by the autopilot) or as the /// autopilot's own (`autopilot_left`, `autopilot_done`). pub fn decide(id: String, work: std::path::PathBuf, goal: String, nudges: u32, ask: Ask, answer: impl FnOnce(Value) + Send + 'static) { std::thread::spawn(move || { let key = ask.key(); let started = std::time::Instant::now(); let out = (|| -> Result { // The request it decides reaches the hub's log with the runner's next report, a moment from now. std::thread::sleep(std::time::Duration::from_secs(1)); let log = crate::client::get(&format!("/v1/hosted/{id}/log"))?; let items = log["items"].as_array().cloned().unwrap_or_default(); // The person's rules and earlier answers (focus.rs); without them it decides as before. let focus = crate::client::get(&format!("/v1/focus/pilot?session={id}")).unwrap_or(Value::Null); let mut prompt = prompt(&items, &goal, nudges, &ask); prompt.push_str(&person_context(&focus, false)); let model = crate::client::setting("MIDAS_AUTOPILOT_MODEL").unwrap_or_else(|| MODEL.into()); let said = crate::ask::read_only(&work, &prompt, RULES, &model, RUN_S)?; Ok(verdict(&said, &ask)) })(); let out = out.unwrap_or_else(|e| json!({"kind": "autopilot_left", "request": request_of(&ask), "why": format!("the autopilot could not decide ({})", crate::util::short(&format!("{e:#}"), 200))})); eprintln!("{id}: autopilot on {key}: {} after {:.0} s", out["kind"].as_str().unwrap_or("?"), started.elapsed().as_secs_f64()); answer(out); }); } /// The same for a session whose autopilot is off, when its person applies /// their rules everywhere (focus.rs): it answers only what an approved rule /// settles, and passes on everything else without a word (`autopilot_pass`). /// Nothing is asked of Claude when there are no rules, or they do not apply here. pub fn decide_by_rules(id: String, work: std::path::PathBuf, ask: Ask, answer: impl FnOnce(Value) + Send + 'static) { std::thread::spawn(move || { let pass = json!({"kind": "autopilot_pass", "request": request_of(&ask)}); let out = (|| -> Result { let focus = crate::client::get(&format!("/v1/focus/pilot?session={id}"))?; if focus["rules_everywhere"] != true || focus["rules"].as_array().is_none_or(Vec::is_empty) { return Ok(pass.clone()); } std::thread::sleep(std::time::Duration::from_secs(1)); let log = crate::client::get(&format!("/v1/hosted/{id}/log"))?; let items = log["items"].as_array().cloned().unwrap_or_default(); let mut prompt = prompt(&items, "", 0, &ask); prompt.push_str(&person_context(&focus, true)); let model = crate::client::setting("MIDAS_AUTOPILOT_MODEL").unwrap_or_else(|| MODEL.into()); let said = crate::ask::read_only(&work, &prompt, RULES, &model, RUN_S)?; let v = verdict(&said, &ask); // Only an answer a rule gave stands; anything else stays the person's. Ok(if v["basis"] == "rule" && v["rule"].is_string() { v } else { pass.clone() }) })(); let out = out.unwrap_or(pass); eprintln!("{id}: the person's rules on {}: {}", ask.key(), out["kind"].as_str().unwrap_or("?")); answer(out); }); } /// What it is told of the person (focus.rs): the rules they approved, how they /// answered before, and whether they are near their cap; with `only_rules`, that /// it may answer only by a rule. fn person_context(focus: &Value, only_rules: bool) -> String { let mut p = String::new(); let rules = focus["rules"].as_array().cloned().unwrap_or_default(); if !rules.is_empty() { p.push_str("\n## Rules the person approved (id: rule)\n"); for r in &rules { p.push_str(&format!("- {}: {}\n", r["id"].as_str().unwrap_or(""), r["text"].as_str().unwrap_or(""))); } } let precedents = focus["precedents"].as_array().cloned().unwrap_or_default(); if !precedents.is_empty() && !only_rules { p.push_str("\n## How the person answered before (oldest first)\n"); for r in &precedents { p.push_str(&format!("- Asked: {} → they answered: {}\n", crate::util::short(r["question"].as_str().unwrap_or(""), 300), crate::util::short(&r["answer"].to_string(), 200))); } } if only_rules { p.push_str("\nThe person has NOT handed this session to you: you may answer only when one of the rules above settles it \ beyond doubt, with \"basis\": \"rule\" and \"rule\": \"\". Anything else: {\"leave\": true, \"why\": \"no rule\"}.\n"); return p; } if focus["near_cap"] == true { p.push_str("\nThe person is near the daily limit they set on their own decisions: settle whatever the brief, the rules and \ their earlier answers reasonably settle, and leave only what cannot be taken back or truly needs them.\n"); } p.push_str("\nWith an answer, also say on what it rests: \"basis\": \"rule\" (with \"rule\": \"\"), \"precedent\" (they answered \ the same before), or \"judgement\"; and \"sure\": true or false. When their earlier answers show they answer this kind of \ question the same way every time (three times or more) and no rule says so yet, add \"propose\": \"\" for them to approve.\n\ When you leave it, say whether it needs them now: \"urgent\": true when it cannot be taken back or goes outside the workshop, \ false when it only needs their judgement and can wait for their next decision block.\n"); p } fn request_of(ask: &Ask) -> Value { match ask { Ask::Permission(r, _) | Ask::Question(r, _) => json!(r), Ask::Next => Value::Null, } } /// How it is to decide: the system prompt beside Claude Code's own. const RULES: &str = "You are the autopilot of a coding session run by midas, a build workshop. The person who started the session \ is away and has handed it to you: you answer what the session asks in their place, as they would, from what they asked for. \ You can read the session's code (its worktrees are in the current directory) but change nothing: the session does the work.\n\ \n\ Decide as the person would:\n\ - Their own messages are the brief. Hold the session to it: never widen the scope, never ask for something they did not; \ when it offers more work than was asked, say no and have it finish what was asked.\n\ - A choice with a \"(Recommended)\" option: take it when it fits the brief, unless the conversation shows it is wrong.\n\ - Landing and deploying are yours to decide: say yes when the work is what was asked and the evidence is there (the gate or tests \ passed, a visual change was shown); say what is missing when it is not. A brief with \"Done when\" checks lands only once the session \ has given evidence for each check (the test that covers it, the picture that shows it, or why it cannot be checked from here): \ ask for the ones it skipped.\n\ - Read the code when the answer depends on it; never guess.\n\ \n\ Leave it to the person (\"leave\") when it cannot be taken back and they did not ask for it — data destroyed (a database dropped, \ files deleted outside the session's worktrees, a force-push to main, other people's branches), money spent, something published \ or sent outside the workshop, access or secrets changed — and when the conversation does not settle it. Leaving is no failure: \ it is the right answer whenever you are not sure.\n\ \n\ Answer with one JSON object and nothing else, as the request below says. \"why\": one or two plain sentences, in the language of \ the person's messages, saying what in the conversation decided it."; /// The question put to it: the brief, the conversation, and what is asked. fn prompt(items: &[Value], goal: &str, nudges: u32, ask: &Ask) -> String { let mut p = String::new(); if !goal.trim().is_empty() { p.push_str(&format!("## The goal the person set for you\n{}\n\n", goal.trim())); } p.push_str(&digest(items)); p.push_str("\n## What the session asks now\n"); match ask { Ask::Permission(_, it) => { p.push_str(&format!("It asks permission: {}\n", it["title"].as_str().unwrap_or(""))); if !it["input"].is_null() { p.push_str(&format!("What it would run or change: {}\n", crate::util::short(&it["input"].to_string(), 4000))); } p.push_str("Options (optionId: name):\n"); for o in it["options"].as_array().into_iter().flatten() { p.push_str(&format!("- {}: {}\n", o["optionId"].as_str().unwrap_or(""), o["name"].as_str().unwrap_or(""))); } p.push_str("\nAnswer {\"option\": \"\", \"why\": \"…\"}, or {\"leave\": true, \"why\": \"…\"}. \ Never pick an option that allows always: allow once.\n"); } Ask::Question(_, it) => { p.push_str(&format!("It asks: {}\n", it["message"].as_str().unwrap_or(""))); p.push_str(&format!("The form (JSON schema): {}\n", it["schema"])); p.push_str("\nAnswer {\"answers\": {\"question_0\": \"\", …}, \"why\": \"…\"}, with every question \ answered: a single choice as one const, a multiple one as a list of consts, and question__custom only to add \ words of your own. Or {\"leave\": true, \"why\": \"…\"}.\n"); } Ask::Next => { p.push_str("Its turn has ended and nothing waits for it: no question, no request, no message.\n"); if nudges > 0 { p.push_str(&format!("You have said {nudges} things to it in a row without the person; it stops at {MAX_NUDGES}.\n")); } p.push_str("\nIf it stopped to ask something in its text, or stopped before the brief is done, say what it should do next: \ {\"say\": \"\", \"why\": \"…\"}. If the brief is done (landed and finished, or \ answered), or it waits on something that comes by itself: {\"done\": true, \"why\": \"…\"}. If only the person \ can say: {\"leave\": true, \"why\": \"…\"}.\n"); } } p } /// The conversation as it reads it: the person's messages, in full and in /// order (they are the brief), then the last of everything else, oldest first. pub fn digest(items: &[Value]) -> String { let mut asked = String::new(); for it in items.iter().filter(|i| i["kind"] == "user" && i["by"] != BY) { let line = format!("- {}\n", crate::util::short(it["text"].as_str().unwrap_or("").trim(), 8000)); if asked.len() + line.len() > ASKED_BUDGET { asked.push_str("- (later messages left out)\n"); break; } asked.push_str(&line); } let mut recent: Vec = Vec::new(); let mut size = 0; for it in items.iter().rev() { let s = |k: &str| it[k].as_str().unwrap_or("").trim().to_string(); let line = match it["kind"].as_str().unwrap_or("") { "user" if it["by"] == BY => format!("You (the autopilot) said: {}", crate::util::short(&s("text"), 2000)), "user" => format!("The person said: {}", crate::util::short(&s("text"), 2000)), "agent" => format!("The session: {}", crate::util::short(&s("text"), 3000)), "tool" => format!("[tool: {}]", crate::util::short(&s("title"), 200)), "permission" => format!("[asked permission: {}]", crate::util::short(&s("title"), 200)), "permission_answered" => format!("[answered by {}: {}]", s("by"), s("option")), "question" => format!("[asked: {}]", crate::util::short(&s("message"), 500)), "answered" => format!("[answered by {}: {}]", s("by"), crate::util::short(&it["content"].to_string(), 500)), "turn_end" => "[its turn ended]".into(), "status" | "error" => format!("[{}]", crate::util::short(&s("text"), 300)), "finishing" => "[landed; finishing once it is live]".into(), _ => continue, }; size += line.len() + 1; if size > RECENT_BUDGET { recent.push("(earlier conversation left out)".into()); break; } recent.push(line); } recent.reverse(); format!("## What the person asked (their messages, in order)\n{}\n## The conversation, to now\n{}\n", if asked.is_empty() { "(nothing yet)\n".to_string() } else { asked }, recent.join("\n")) } /// The first JSON object in what it said. fn object_in(said: &str) -> Option { let start = said.find('{')?; let end = said.rfind('}')?; serde_json::from_str(said.get(start..=end)?).ok().filter(Value::is_object) } /// What the runner does with what it said: checked against what was asked, /// and left to the person when it does not fit. pub fn verdict(said: &str, ask: &Ask) -> Value { let request = request_of(ask); // Left without its word on urgency: it needs the person now, as every leave did before (push.rs). let left = |why: &str| json!({"kind": "autopilot_left", "request": request, "why": why, "urgent": true}); let Some(v) = object_in(said) else { return left("the autopilot gave no answer it could act on") }; let why = v["why"].as_str().map(str::trim).filter(|w| !w.is_empty()).unwrap_or("(no reason given)"); let why = crate::util::short(why, 1000); if v["leave"] == true { let mut l = left(&why); l["urgent"] = json!(v["urgent"] != false); return l; } // On what it rests, and a rule it proposes (focus.rs): only what fits is passed on. let basis = v["basis"].as_str().filter(|b| matches!(*b, "rule" | "precedent" | "judgement")); let rule = v["rule"].as_str().filter(|_| basis == Some("rule")).filter(|r| r.len() <= 16); let propose = v["propose"].as_str().map(str::trim).filter(|p| !p.is_empty()).map(|p| crate::util::short(p, 400)); let mark = |mut out: Value| { out["basis"] = json!(basis); out["rule"] = json!(rule); out["sure"] = json!(v["sure"].as_bool()); out["propose"] = json!(propose); out }; match ask { Ask::Permission(r, it) => { let option = v["option"].as_str().unwrap_or(""); let found = it["options"].as_array().into_iter().flatten().find(|o| o["optionId"] == option); match found { // Never "always": the next request is decided again. Some(o) if o["kind"] == "allow_always" => left("it would allow this always; that is the person's to say"), Some(_) => mark(json!({"kind": "permit", "request": r, "option": option, "by": BY, "why": why})), None => left("the autopilot chose no option offered"), } } Ask::Question(r, it) => match answers_ok(&it["schema"], &v["answers"]) { Some(content) => mark(json!({"kind": "answer", "request": r, "action": "accept", "content": content, "by": BY, "why": why})), None => left("the autopilot's answers do not fit the question"), }, Ask::Next => { if v["done"] == true { return json!({"kind": "autopilot_done", "why": why}); } match v["say"].as_str().map(str::trim).filter(|s| !s.is_empty()) { Some(text) => json!({"kind": "message", "text": crate::util::short(text, 8000), "by": BY, "why": why}), None => left("the autopilot said neither what next nor that it is done"), } } } } /// The form's answers when every question is answered with one of its own /// options (or words in its "Other"); none otherwise. fn answers_ok(schema: &Value, answers: &Value) -> Option { let props = schema["properties"].as_object()?; let given = answers.as_object()?; let mut out = serde_json::Map::new(); for (k, field) in props { let v = given.get(k); if k.ends_with("_custom") { if let Some(t) = v.and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()) { out.insert(k.clone(), json!(t)); } continue; } let consts = |list: &Value| -> Vec { list.as_array().into_iter().flatten().map(|o| o["const"].clone()).collect() }; let custom = given.get(&format!("{k}_custom")).and_then(Value::as_str).is_some_and(|t| !t.trim().is_empty()); if field["type"] == "array" { let allowed = consts(&field["items"]["anyOf"]); let picked: Vec = v.and_then(Value::as_array).cloned().unwrap_or_default(); if picked.iter().any(|p| !allowed.contains(p)) || (picked.is_empty() && !custom) { return None; } out.insert(k.clone(), json!(picked)); } else { match v.filter(|x| consts(&field["oneOf"]).contains(x)) { Some(x) => { out.insert(k.clone(), x.clone()); } None if custom => {} None => return None, } } } Some(Value::Object(out)) } #[cfg(test)] mod tests { use super::*; fn permission() -> Ask { Ask::Permission("7".into(), json!({"title": "git push", "options": [ {"optionId": "allow", "name": "Allow", "kind": "allow_once"}, {"optionId": "always", "name": "Always", "kind": "allow_always"}, {"optionId": "reject", "name": "Reject", "kind": "reject_once"}]})) } fn question() -> Ask { let (_, schema) = crate::acp::question_form(&[json!({"question": "Shall it land?", "header": "Land", "options": [{"label": "Land it"}, {"label": "Not yet"}]})]); Ask::Question("9".into(), json!({"message": "Shall it land?", "schema": schema})) } #[test] fn a_permission_is_one_of_its_options_and_never_always() { let v = verdict("Sure. {\"option\": \"allow\", \"why\": \"asked for\"}", &permission()); assert_eq!((v["kind"].as_str(), v["option"].as_str(), v["by"].as_str()), (Some("permit"), Some("allow"), Some(BY))); assert_eq!(verdict("{\"option\": \"always\", \"why\": \"x\"}", &permission())["kind"], "autopilot_left"); assert_eq!(verdict("{\"option\": \"nope\", \"why\": \"x\"}", &permission())["kind"], "autopilot_left"); assert_eq!(verdict("no json here", &permission())["kind"], "autopilot_left"); let left = verdict("{\"leave\": true, \"why\": \"drops a table\"}", &permission()); assert_eq!((left["kind"].as_str(), left["why"].as_str(), left["request"].as_str()), (Some("autopilot_left"), Some("drops a table"), Some("7"))); assert_eq!(left["urgent"], true, "a leave that does not say needs the person now"); assert_eq!(verdict("{\"leave\": true, \"urgent\": false, \"why\": \"new kind\"}", &permission())["urgent"], false); } #[test] fn an_answer_says_on_what_it_rests() { let v = verdict("{\"option\": \"allow\", \"basis\": \"rule\", \"rule\": \"r3\", \"sure\": true, \"why\": \"rule 3\"}", &permission()); assert_eq!((v["basis"].as_str(), v["rule"].as_str(), v["sure"].as_bool()), (Some("rule"), Some("r3"), Some(true))); let v = verdict("{\"option\": \"allow\", \"basis\": \"vibes\", \"rule\": \"r3\", \"why\": \"x\"}", &permission()); assert_eq!((v["basis"].clone(), v["rule"].clone()), (Value::Null, Value::Null), "no basis it may give, so no rule either"); let v = verdict("{\"answers\": {\"question_0\": \"Land it\"}, \"basis\": \"precedent\", \"propose\": \" Land when the gate is green \", \"why\": \"x\"}", &question()); assert_eq!((v["basis"].as_str(), v["propose"].as_str()), (Some("precedent"), Some("Land when the gate is green"))); } #[test] fn a_question_is_answered_with_its_own_options() { let v = verdict("{\"answers\": {\"question_0\": \"Land it\"}, \"why\": \"gate green\"}", &question()); assert_eq!(v["kind"], "answer"); assert_eq!(v["content"], json!({"question_0": "Land it"})); assert_eq!(verdict("{\"answers\": {\"question_0\": \"Ship it\"}, \"why\": \"x\"}", &question())["kind"], "autopilot_left"); assert_eq!(verdict("{\"answers\": {}, \"why\": \"x\"}", &question())["kind"], "autopilot_left"); let other = verdict("{\"answers\": {\"question_0_custom\": \"after the docs\"}, \"why\": \"x\"}", &question()); assert_eq!(other["content"], json!({"question_0_custom": "after the docs"})); } #[test] fn what_next_is_a_message_done_or_left() { let v = verdict("{\"say\": \"Finish the note and stop.\", \"why\": \"brief\"}", &Ask::Next); assert_eq!((v["kind"].as_str(), v["text"].as_str(), v["by"].as_str()), (Some("message"), Some("Finish the note and stop."), Some(BY))); assert_eq!(verdict("{\"done\": true, \"why\": \"landed\"}", &Ask::Next)["kind"], "autopilot_done"); assert_eq!(verdict("{\"why\": \"hm\"}", &Ask::Next)["kind"], "autopilot_left"); } #[test] fn the_digest_keeps_the_persons_words_and_the_end() { let items = vec![ json!({"kind": "user", "by": "sam", "text": "Make the roads grey."}), json!({"kind": "agent", "text": "Done; shall it land?"}), json!({"kind": "user", "by": BY, "text": "Land it."}), ]; let d = digest(&items); assert!(d.contains("- Make the roads grey.")); assert!(d.contains("The session: Done; shall it land?")); assert!(d.contains("You (the autopilot) said: Land it.")); assert!(!d.split("## The conversation").next().unwrap().contains("Land it."), "its own words are not the brief"); } #[test] fn the_meta_follows_what_the_runner_reports() { let mut p = meta_of(&change(&json!({"on": true, "goal": "finish"})).unwrap(), "sam"); assert_eq!((p["on"].as_bool(), p["state"].as_str()), (Some(true), Some("idle"))); assert!(follow(&mut p, &[json!({"kind": "autopilot_deciding"})])); assert_eq!(p["state"], "deciding"); follow(&mut p, &[json!({"kind": "autopilot_left", "why": "drops data"})]); assert_eq!((p["state"].as_str(), p["left_why"].as_str()), (Some("left"), Some("drops data"))); follow(&mut p, &[json!({"kind": "permission_answered", "by": "sam"})]); assert_eq!(p["state"], "idle"); follow(&mut p, &[json!({"kind": "autopilot", "on": false, "by": BY, "why": "its time ran out"})]); assert_eq!(p["on"], false); assert!(change(&json!({"on": true, "until": 1})).is_err(), "until a time past"); } }