use crate::error::{Error, Result};
use crate::message::Message;
use serde::{Deserialize, Serialize};
pub const DEFAULT_BUDGET: u32 = 12;
pub const MAX_BUDGET: u32 = 100;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
Active,
Paused,
Done,
Blocked,
Stopped,
}
impl State {
pub fn as_str(self) -> &'static str {
match self {
State::Active => "active",
State::Paused => "paused",
State::Done => "done",
State::Blocked => "blocked",
State::Stopped => "stopped",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Goal {
pub session: String,
pub text: String,
pub gate: Option<String>,
pub budget: u32,
pub turns: u32,
pub state: State,
pub note: Option<String>,
pub garbage: bool,
pub created_ms: i64,
pub updated_ms: i64,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
Continue,
Done,
Blocked,
Unreadable,
}
impl Verdict {
pub fn as_str(self) -> &'static str {
match self {
Verdict::Continue => "continue",
Verdict::Done => "done",
Verdict::Blocked => "blocked",
Verdict::Unreadable => "unreadable",
}
}
pub fn parse(text: &str) -> Verdict {
let word = text
.trim()
.trim_start_matches(['"', '\'', '`', '*', ' '])
.split(|c: char| c.is_whitespace() || matches!(c, ',' | '.' | '!' | '?' | ';' | ':'))
.find(|w| !w.is_empty())
.unwrap_or("")
.trim_end_matches(['"', '\'', '`', '*'])
.to_ascii_lowercase();
match word.as_str() {
"continue" | "keep going" | "keep" | "going" | "more" => Verdict::Continue,
"done" | "complete" | "completed" | "finished" | "yes" => Verdict::Done,
"blocked" | "block" | "stuck" | "no" => Verdict::Blocked,
_ => Verdict::Unreadable,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Judgement {
pub turn: u32,
pub verdict: String,
pub why: Option<String>,
pub at_ms: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
Start {
text: String,
gate: Option<String>,
budget: Option<u32>,
},
Status,
Pause,
Resume,
Clear,
Gate(Option<String>),
}
pub fn parse(arg: &str) -> Result<Request> {
let text = arg.trim();
if text.is_empty() || text.eq_ignore_ascii_case("status") || text.eq_ignore_ascii_case("show") {
return Ok(Request::Status);
}
for (word, request) in [
("pause", Request::Pause),
("resume", Request::Resume),
("clear", Request::Clear),
] {
if text.eq_ignore_ascii_case(word) {
return Ok(request);
}
}
if let Some(rest) = text.strip_prefix("gate ") {
let rest = unquote(rest);
if rest.is_empty()
|| rest.eq_ignore_ascii_case("clear")
|| rest.eq_ignore_ascii_case("none")
{
return Ok(Request::Gate(None));
}
return Ok(Request::Gate(Some(rest)));
}
let rest = match text.strip_prefix("--") {
Some(after) if after.is_empty() || after.starts_with(char::is_whitespace) => after.trim(),
Some(_) => {
return Err(Error::Config(
"`/goal --gate …` is a flag with no goal sentence: write `/goal <what you want \
done> --gate <cmd>`, or `/goal -- --gate …` for a goal that starts with a flag"
.into(),
))
}
None => text,
};
let mut words: Vec<&str> = Vec::new();
let mut gate: Option<String> = None;
let mut budget: Option<u32> = None;
let mut iter = rest.split_whitespace().peekable();
while let Some(word) = iter.next() {
match word {
"--gate" => {
let mut command: Vec<&str> = Vec::new();
while let Some(next) = iter.peek() {
if *next == "--budget" || *next == "--turns" {
break;
}
command.push(iter.next().expect("peeked"));
}
let command = unquote(&command.join(" "));
if command.is_empty() {
return Err(Error::Config(
"`--gate` needs a command: `/goal finish the deploy --gate make smoke`"
.into(),
));
}
gate = Some(command);
}
"--budget" | "--turns" => {
let raw = iter.next().ok_or_else(|| {
Error::Config("`--budget` needs a number of turns".to_string())
})?;
let n: u32 = raw.parse().map_err(|_| {
Error::Config(format!("`--budget {raw}` is not a number of turns"))
})?;
if n == 0 {
return Err(Error::Config(
"`--budget 0` is a goal that may never take a turn".to_string(),
));
}
if n > MAX_BUDGET {
return Err(Error::Config(format!(
"`--budget {n}` is more than {MAX_BUDGET} turns"
)));
}
budget = Some(n);
}
other => words.push(other),
}
}
let text = unquote(&words.join(" "));
if text.is_empty() {
return Err(Error::Config(
"a goal needs a sentence: `/goal get the release out`".into(),
));
}
Ok(Request::Start { text, gate, budget })
}
fn unquote(text: &str) -> String {
let t = text.trim();
for q in ['"', '\''] {
if t.len() >= 2 && t.starts_with(q) && t.ends_with(q) {
return t[1..t.len() - 1].trim().to_string();
}
}
t.to_string()
}
impl Goal {
pub fn new(
session: &str,
text: &str,
gate: Option<String>,
budget: Option<u32>,
now_ms: i64,
) -> Goal {
Goal {
session: session.to_string(),
text: text.to_string(),
gate,
budget: budget.unwrap_or(DEFAULT_BUDGET),
turns: 0,
state: State::Active,
note: None,
garbage: false,
created_ms: now_ms,
updated_ms: now_ms,
}
}
pub fn remaining(&self) -> u32 {
self.budget.saturating_sub(self.turns)
}
pub fn wants_turn(&self) -> bool {
self.state == State::Active && self.turns < self.budget
}
pub fn continuation_prompt(&self) -> String {
let mut prompt = format!(
"Continue working on the goal you were given: {}\n\n\
That is the standing goal for this session. Pick up where the previous turn stopped — \
do not repeat work that is already done — and keep going until it is finished. If it \
cannot be finished, say what is blocking it.",
self.text
);
if let Some(gate) = &self.gate {
prompt.push_str(&format!(
"\n\nBefore you call it finished, this must pass: `{gate}`"
));
}
prompt
}
pub fn readout(&self) -> String {
let mut line = match self.state {
State::Active => format!(
"goal active · turn {}/{} · {}",
self.turns, self.budget, self.text
),
State::Paused => format!(
"goal paused · turn {}/{} · {}",
self.turns, self.budget, self.text
),
State::Done => format!("goal done · {} turn(s) · {}", self.turns, self.text),
State::Blocked => format!("goal blocked · {} turn(s) · {}", self.turns, self.text),
State::Stopped => format!("goal cleared · {} turn(s)", self.turns),
};
if let Some(gate) = &self.gate {
line.push_str(&format!(" · gate: {gate}"));
}
if let Some(note) = &self.note {
line.push_str(&format!(" · {note}"));
}
line
}
}
pub fn manage(
store: &crate::session::SessionStore,
session: &str,
arg: &str,
now_ms: i64,
) -> Result<String> {
match parse(arg)? {
Request::Start { text, gate, budget } => {
let goal = Goal::new(session, &text, gate, budget, now_ms);
let said = format!(
"goal set · {} · up to {} turn(s){} — it is worked on turn by turn until the judge \
says it is done, the budget runs out, or `/goal pause`",
goal.text,
goal.budget,
match &goal.gate {
Some(gate) => format!(" · gate: `{gate}`"),
None => String::new(),
}
);
store.set_goal(&goal)?;
Ok(said)
}
Request::Status => match store.goal(session)? {
Some(goal) => {
let mut said = goal.readout();
let turns = store.goal_turns(session)?;
if let Some(last) = turns.last() {
said.push_str(&format!(
" · last judgement: {} (turn {})",
last.verdict, last.turn
));
}
Ok(said)
}
None => Ok(
"no goal in this session. `/goal <what you want done>` sets one; a goal is worked \
on across turns until the judge says it is finished"
.to_string(),
),
},
Request::Pause => {
let Some(mut goal) = store.goal(session)? else {
return Err(Error::Config("no goal in this session to pause".into()));
};
if goal.state != State::Active {
return Ok(goal.readout());
}
goal.state = State::Paused;
goal.updated_ms = now_ms;
goal.note = Some("paused by the person".into());
store.set_goal(&goal)?;
Ok(format!(
"goal paused after {} turn(s) — `/goal resume` continues it",
goal.turns
))
}
Request::Resume => {
let Some(mut goal) = store.goal(session)? else {
return Err(Error::Config("no goal in this session to resume".into()));
};
if goal.state != State::Paused {
return Ok(goal.readout());
}
goal.state = State::Active;
goal.updated_ms = now_ms;
goal.note = None;
store.set_goal(&goal)?;
Ok(format!(
"goal resumed — turn {}/{}",
goal.turns + 1,
goal.budget
))
}
Request::Clear => {
if store.goal(session)?.is_none() {
return Ok("no goal in this session".to_string());
}
store.clear_goal(session)?;
Ok("goal cleared — no further turns will be started for it".to_string())
}
Request::Gate(gate) => {
let Some(mut goal) = store.goal(session)? else {
return Err(Error::Config(
"no goal in this session: set one first, then `/goal gate <cmd>`".into(),
));
};
goal.gate = gate.clone();
goal.updated_ms = now_ms;
store.set_goal(&goal)?;
Ok(match gate {
Some(gate) => format!(
"gate set to `{gate}` — the judge's \"done\" is not accepted until it exits 0"
),
None => "gate cleared".to_string(),
})
}
}
}
pub fn judge_prompt(goal: &Goal, last_reply: &str) -> [Message; 2] {
const SYSTEM: &str = "\
You judge whether a standing goal has been reached. You are given the goal, and the last thing the \
agent said. Answer with exactly one word:\n\
continue — the work is not finished and there is more to do\n\
done — the goal has been reached\n\
blocked — the work cannot proceed without a person\n\
No explanation, no punctuation, no other word.";
let mut user = format!("GOAL: {}", goal.text);
if let Some(gate) = &goal.gate {
user.push_str(&format!("\nTHE GOAL IS GATED ON: `{gate}` passing"));
}
user.push_str("\n\nTHE LAST THING THE AGENT SAID:\n");
let trimmed = last_reply.trim();
if trimmed.is_empty() {
user.push_str("(nothing — the turn produced no text)");
} else {
let budget = 4_000;
if trimmed.chars().count() > budget {
let head: String = trimmed.chars().take(budget / 2).collect();
let tail: String = trimmed
.chars()
.rev()
.take(budget / 2)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
user.push_str(&format!("{head}\n[…]\n{tail}"));
} else {
user.push_str(trimmed);
}
}
[Message::system(SYSTEM), Message::user(user)]
}
pub fn apply(goal: &mut Goal, verdict: Verdict, why: Option<String>, now_ms: i64) {
goal.turns = goal.turns.saturating_add(1);
goal.updated_ms = now_ms;
if verdict != Verdict::Unreadable {
goal.garbage = false;
}
let note = why.as_deref().map(str::trim).filter(|w| !w.is_empty());
match verdict {
Verdict::Done => {
goal.state = State::Done;
goal.note = Some(match note {
Some(why) => format!("the judge called it done: {why}"),
None => "the judge called it done".to_string(),
});
}
Verdict::Blocked => {
goal.state = State::Blocked;
goal.note = Some(match note {
Some(why) => format!("blocked: {why}"),
None => "the judge said it is blocked".to_string(),
});
}
Verdict::Continue => {
goal.note = note.map(|w| format!("continuing: {w}"));
if goal.turns >= goal.budget {
goal.state = State::Done;
goal.note = Some(format!(
"the turn budget ran out after {} turn(s); it did not finish",
goal.turns
));
}
}
Verdict::Unreadable => {
goal.note = Some(match note {
Some(why) => format!("the judge answered something else: {why}"),
None => "the judge answered something that was not continue, done or blocked"
.to_string(),
});
if goal.garbage {
goal.state = State::Blocked;
goal.note = Some(
"the judge answered twice with something that was not continue, done or \
blocked, so the goal stopped rather than loop on a guess"
.to_string(),
);
} else {
goal.garbage = true;
}
}
}
}
pub fn split_reply(answer: &str) -> (Verdict, Option<String>) {
let trimmed = answer.trim();
let verdict = Verdict::parse(trimmed);
let rest = trimmed
.split_once(char::is_whitespace)
.map(|(_, rest)| {
rest.trim()
.trim_start_matches(['—', '–', '-', ':', ',', ';'])
.trim()
.trim_start_matches(['"', '`', '*'])
.trim()
})
.filter(|rest| !rest.is_empty())
.map(str::to_string);
(verdict, rest)
}
#[cfg(test)]
mod tests {
use super::*;
fn goal(text: &str) -> Goal {
Goal::new("s1", text, None, None, 0)
}
#[test]
fn a_goal_line_is_a_sentence_with_optional_bounds() {
assert_eq!(
parse("get the release out").unwrap(),
Request::Start {
text: "get the release out".into(),
gate: None,
budget: None
}
);
assert_eq!(
parse("ship it --budget 4 --gate make smoke").unwrap(),
Request::Start {
text: "ship it".into(),
gate: Some("make smoke".into()),
budget: Some(4)
}
);
assert_eq!(
parse("-- pause the deploy").unwrap(),
Request::Start {
text: "pause the deploy".into(),
gate: None,
budget: None
}
);
}
#[test]
fn the_verbs_are_exact_and_the_escape_is_a_double_dash() {
assert_eq!(parse("").unwrap(), Request::Status);
assert_eq!(parse("status").unwrap(), Request::Status);
assert_eq!(parse("show").unwrap(), Request::Status);
assert_eq!(parse("PAUSE").unwrap(), Request::Pause);
assert_eq!(parse("resume").unwrap(), Request::Resume);
assert_eq!(parse("clear").unwrap(), Request::Clear);
assert_eq!(
parse("gate make smoke").unwrap(),
Request::Gate(Some("make smoke".into()))
);
assert_eq!(parse("gate clear").unwrap(), Request::Gate(None));
}
#[test]
fn a_bad_bound_is_refused_rather_than_clamped() {
assert!(parse("x --budget 0").is_err());
assert!(parse("x --budget many").is_err());
assert!(parse("x --budget 101").is_err());
assert!(parse("--gate make smoke").is_err(), "a gate is not a goal");
}
#[test]
fn only_the_three_words_are_an_answer() {
assert_eq!(Verdict::parse("continue"), Verdict::Continue);
assert_eq!(Verdict::parse("Done."), Verdict::Done);
assert_eq!(Verdict::parse("\"blocked\""), Verdict::Blocked);
for other in ["", "maybe", "it depends", "certainly"] {
assert_eq!(Verdict::parse(other), Verdict::Unreadable, "{other:?}");
}
let (verdict, note) = split_reply("continue — the tests are still red");
assert_eq!(verdict, Verdict::Continue);
assert_eq!(note.as_deref(), Some("the tests are still red"));
}
#[test]
fn a_continue_under_the_budget_leaves_the_goal_active() {
let mut g = goal("ship it");
apply(&mut g, Verdict::Continue, Some("one step left".into()), 10);
assert_eq!(g.state, State::Active);
assert_eq!(g.turns, 1);
assert_eq!(g.note.as_deref(), Some("continuing: one step left"));
assert!(g.wants_turn());
}
#[test]
fn done_and_blocked_end_it_and_keep_the_judges_line() {
let mut g = goal("ship it");
apply(&mut g, Verdict::Done, Some("the release is out".into()), 10);
assert_eq!(g.state, State::Done);
assert!(!g.wants_turn());
assert!(g.note.as_deref().unwrap().contains("the release is out"));
let mut g = goal("ship it");
apply(&mut g, Verdict::Blocked, Some("no credentials".into()), 10);
assert_eq!(g.state, State::Blocked);
assert!(g.note.as_deref().unwrap().contains("no credentials"));
}
#[test]
fn the_budget_ends_it_out_loud_rather_than_going_quiet() {
let mut g = Goal::new("s1", "ship it", None, Some(2), 0);
apply(&mut g, Verdict::Continue, None, 1);
assert!(g.wants_turn());
apply(&mut g, Verdict::Continue, None, 2);
assert_eq!(g.state, State::Done);
assert!(!g.wants_turn());
assert!(g.note.as_deref().unwrap().contains("budget ran out"));
}
#[test]
fn garbage_is_continue_once_and_then_a_stop_not_a_done() {
let mut g = goal("ship it");
apply(&mut g, Verdict::Unreadable, None, 1);
assert_eq!(g.state, State::Active, "one bad answer is tolerated");
assert!(g
.note
.as_deref()
.unwrap()
.contains("not continue, done or blocked"));
apply(&mut g, Verdict::Unreadable, None, 2);
assert_eq!(g.state, State::Blocked, "the second one stops it");
assert!(g.note.as_deref().unwrap().contains("twice"), "{:?}", g.note);
}
#[test]
fn a_judged_turn_clears_the_garbage_counter() {
let mut g = goal("ship it");
apply(&mut g, Verdict::Unreadable, None, 1);
apply(&mut g, Verdict::Continue, None, 2);
assert_eq!(g.state, State::Active);
apply(&mut g, Verdict::Unreadable, None, 3);
assert_eq!(g.state, State::Active);
}
#[test]
fn the_continuation_prompt_names_the_goal_the_gate_and_what_not_to_redo() {
let g = Goal::new("s1", "ship the release", Some("make smoke".into()), None, 0);
let prompt = g.continuation_prompt();
assert!(prompt.contains("ship the release"), "{prompt}");
assert!(prompt.contains("do not repeat work"), "{prompt}");
assert!(prompt.contains("make smoke"), "{prompt}");
}
#[test]
fn the_judge_question_carries_the_goal_and_the_reply_and_nothing_else() {
let g = goal("ship the release");
let request = judge_prompt(&g, "the tests are green");
assert!(request[0]
.content
.as_deref()
.unwrap()
.contains("exactly one word"));
let user = request[1].content.as_deref().unwrap();
assert!(user.contains("GOAL: ship the release"), "{user}");
assert!(user.contains("the tests are green"), "{user}");
let long = format!("{}{}", "a".repeat(5_000), "the end");
let request = judge_prompt(&g, &long);
let user = request[1].content.as_deref().unwrap();
assert!(user.len() < 5_000, "{} bytes", user.len());
assert!(
user.contains("the end"),
"the tail is the part that says done"
);
}
#[test]
fn the_readout_says_the_state_the_count_and_the_gate() {
let mut g = Goal::new("s1", "ship it", Some("make smoke".into()), Some(3), 0);
assert!(g.readout().starts_with("goal active · turn 0/3 · ship it"));
assert!(g.readout().contains("gate: make smoke"));
apply(&mut g, Verdict::Done, None, 1);
assert!(g.readout().starts_with("goal done"));
}
}