Skip to main content

eclipse_core/
goals.rs

1//! `#172`: `/goal` — one standing goal, worked on across turns.
2//!
3//! A goal is not a loop and not a cron job. A loop re-sends the same prompt on a clock; a goal is
4//! a sentence about what the work is *for*, and after each turn a small model reads the turn and
5//! answers one of three words: keep going, it is done, or it is blocked. A "keep going" enqueues
6//! the next turn — through the front's own run entry, like every other turn — and nothing else
7//! about the agent changes.
8//!
9//! The behaviour is data: a `goals` row in the session store (`sessions.db`, foreign-keyed to the
10//! session so deleting a session deletes its goal) and one row per judgement in `goal_turns`. The
11//! runtime reads those rows; it does not grow a second loop. That is decision 11, and the reason
12//! this module holds no timer, no agent and no provider — only the words, the verdict and the
13//! arithmetic of a budget.
14//!
15//! Three rules are the whole safety of it:
16//!
17//! * **Garbage is not "done".** An answer that is not one of the three words is [`Verdict::Unreadable`];
18//!   it counts as "continue" once and then ends the goal, because a judge that cannot answer must
19//!   not be asked forever and must never be read as success.
20//! * **A budget ends it out loud.** `turns` is capped, and reaching the cap writes a note rather
21//!   than going quiet.
22//! * **A gate is a command, not an opinion.** `--gate "<cmd>"` must exit 0 before "done" is
23//!   accepted; a failing gate turns a "done" back into a "continue" and says so.
24
25use crate::error::{Error, Result};
26use crate::message::Message;
27use serde::{Deserialize, Serialize};
28
29/// How many turns a goal gets when nothing says otherwise. Twelve is enough for a job that takes a
30/// handful of steps, and few enough that a goal with no ending in sight costs minutes, not an hour.
31pub const DEFAULT_BUDGET: u32 = 12;
32
33/// The most a goal may be given. A bound in the thousands is a way of writing "forever" with a
34/// number that looks deliberate.
35pub const MAX_BUDGET: u32 = 100;
36
37/// Where a goal is.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
39#[serde(rename_all = "lowercase")]
40pub enum State {
41    /// Being worked on: the next turn is due whenever the last one finished.
42    Active,
43    /// Held by the person. `resume` puts it back.
44    Paused,
45    /// Finished, either because the judge said so or because the budget ran out.
46    Done,
47    /// The judge said the work cannot proceed. A person is the only way out of it.
48    Blocked,
49    /// `/goal clear`.
50    Stopped,
51}
52
53impl State {
54    pub fn as_str(self) -> &'static str {
55        match self {
56            State::Active => "active",
57            State::Paused => "paused",
58            State::Done => "done",
59            State::Blocked => "blocked",
60            State::Stopped => "stopped",
61        }
62    }
63}
64
65/// One session's goal, as the store keeps it.
66#[derive(Debug, Clone, PartialEq, Eq)]
67pub struct Goal {
68    pub session: String,
69    /// What the work is for, in the person's own words.
70    pub text: String,
71    /// A shell command that must exit 0 before "done" is accepted. Optional.
72    pub gate: Option<String>,
73    /// How many judged turns it may use.
74    pub budget: u32,
75    /// How many it has used.
76    pub turns: u32,
77    pub state: State,
78    /// The one line the last judgement produced, or why the goal ended. Shown, not parsed.
79    pub note: Option<String>,
80    /// Set when the last judgement was unreadable. A run of two ends the goal; any real answer
81    /// clears it, and it is stored so a restart does not reset the count.
82    pub garbage: bool,
83    pub created_ms: i64,
84    pub updated_ms: i64,
85}
86
87/// What one judgement decided, as a row in `goal_turns`.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum Verdict {
90    Continue,
91    Done,
92    Blocked,
93    /// An answer that was not one of the three words. Continue once, then stop.
94    Unreadable,
95}
96
97impl Verdict {
98    pub fn as_str(self) -> &'static str {
99        match self {
100            Verdict::Continue => "continue",
101            Verdict::Done => "done",
102            Verdict::Blocked => "blocked",
103            Verdict::Unreadable => "unreadable",
104        }
105    }
106
107    pub fn parse(text: &str) -> Verdict {
108        let word = text
109            .trim()
110            .trim_start_matches(['"', '\'', '`', '*', ' '])
111            .split(|c: char| c.is_whitespace() || matches!(c, ',' | '.' | '!' | '?' | ';' | ':'))
112            .find(|w| !w.is_empty())
113            .unwrap_or("")
114            .trim_end_matches(['"', '\'', '`', '*'])
115            .to_ascii_lowercase();
116        match word.as_str() {
117            "continue" | "keep going" | "keep" | "going" | "more" => Verdict::Continue,
118            "done" | "complete" | "completed" | "finished" | "yes" => Verdict::Done,
119            "blocked" | "block" | "stuck" | "no" => Verdict::Blocked,
120            _ => Verdict::Unreadable,
121        }
122    }
123}
124
125/// One recorded judgement.
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct Judgement {
128    /// 1-based: the turn number this judgement is about.
129    pub turn: u32,
130    pub verdict: String,
131    pub why: Option<String>,
132    pub at_ms: i64,
133}
134
135/// Everything after the `/goal` word.
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum Request {
138    /// `/goal <text>` — or `-- ` before it, for a sentence that starts with a flag-like word.
139    Start {
140        text: String,
141        gate: Option<String>,
142        budget: Option<u32>,
143    },
144    /// `/goal` or `/goal status` or `/goal show`.
145    Status,
146    Pause,
147    Resume,
148    Clear,
149    /// `/goal gate <cmd>` sets one; `/goal gate clear` removes it.
150    Gate(Option<String>),
151}
152
153/// Parse a `/goal` line.
154///
155/// The verbs are checked first and exactly, so a goal whose text happens to begin with "pause"
156/// is written as `/goal -- pause the deploy` — the same escape every argument-taking command in
157/// this build uses.
158pub fn parse(arg: &str) -> Result<Request> {
159    let text = arg.trim();
160    if text.is_empty() || text.eq_ignore_ascii_case("status") || text.eq_ignore_ascii_case("show") {
161        return Ok(Request::Status);
162    }
163    for (word, request) in [
164        ("pause", Request::Pause),
165        ("resume", Request::Resume),
166        ("clear", Request::Clear),
167    ] {
168        if text.eq_ignore_ascii_case(word) {
169            return Ok(request);
170        }
171    }
172    if let Some(rest) = text.strip_prefix("gate ") {
173        let rest = unquote(rest);
174        if rest.is_empty()
175            || rest.eq_ignore_ascii_case("clear")
176            || rest.eq_ignore_ascii_case("none")
177        {
178            return Ok(Request::Gate(None));
179        }
180        return Ok(Request::Gate(Some(rest)));
181    }
182    // `--` is the escape, and it has to stand alone: everything after it is the goal's own words,
183    // flags and all. `--gate foo` with no sentence in front of it is a flag typed where the goal
184    // goes — a mistake worth saying out loud rather than quietly turning into a goal called
185    // "gate foo".
186    let rest = match text.strip_prefix("--") {
187        Some(after) if after.is_empty() || after.starts_with(char::is_whitespace) => after.trim(),
188        Some(_) => {
189            return Err(Error::Config(
190                "`/goal --gate …` is a flag with no goal sentence: write `/goal <what you want \
191                 done> --gate <cmd>`, or `/goal -- --gate …` for a goal that starts with a flag"
192                    .into(),
193            ))
194        }
195        None => text,
196    };
197    let mut words: Vec<&str> = Vec::new();
198    let mut gate: Option<String> = None;
199    let mut budget: Option<u32> = None;
200    let mut iter = rest.split_whitespace().peekable();
201    while let Some(word) = iter.next() {
202        match word {
203            "--gate" => {
204                let mut command: Vec<&str> = Vec::new();
205                while let Some(next) = iter.peek() {
206                    if *next == "--budget" || *next == "--turns" {
207                        break;
208                    }
209                    command.push(iter.next().expect("peeked"));
210                }
211                let command = unquote(&command.join(" "));
212                if command.is_empty() {
213                    return Err(Error::Config(
214                        "`--gate` needs a command: `/goal finish the deploy --gate make smoke`"
215                            .into(),
216                    ));
217                }
218                gate = Some(command);
219            }
220            "--budget" | "--turns" => {
221                let raw = iter.next().ok_or_else(|| {
222                    Error::Config("`--budget` needs a number of turns".to_string())
223                })?;
224                let n: u32 = raw.parse().map_err(|_| {
225                    Error::Config(format!("`--budget {raw}` is not a number of turns"))
226                })?;
227                if n == 0 {
228                    return Err(Error::Config(
229                        "`--budget 0` is a goal that may never take a turn".to_string(),
230                    ));
231                }
232                if n > MAX_BUDGET {
233                    return Err(Error::Config(format!(
234                        "`--budget {n}` is more than {MAX_BUDGET} turns"
235                    )));
236                }
237                budget = Some(n);
238            }
239            other => words.push(other),
240        }
241    }
242    let text = unquote(&words.join(" "));
243    if text.is_empty() {
244        return Err(Error::Config(
245            "a goal needs a sentence: `/goal get the release out`".into(),
246        ));
247    }
248    Ok(Request::Start { text, gate, budget })
249}
250
251fn unquote(text: &str) -> String {
252    let t = text.trim();
253    for q in ['"', '\''] {
254        if t.len() >= 2 && t.starts_with(q) && t.ends_with(q) {
255            return t[1..t.len() - 1].trim().to_string();
256        }
257    }
258    t.to_string()
259}
260
261impl Goal {
262    /// A fresh goal, active, with nothing used yet.
263    pub fn new(
264        session: &str,
265        text: &str,
266        gate: Option<String>,
267        budget: Option<u32>,
268        now_ms: i64,
269    ) -> Goal {
270        Goal {
271            session: session.to_string(),
272            text: text.to_string(),
273            gate,
274            budget: budget.unwrap_or(DEFAULT_BUDGET),
275            turns: 0,
276            state: State::Active,
277            note: None,
278            garbage: false,
279            created_ms: now_ms,
280            updated_ms: now_ms,
281        }
282    }
283
284    /// Turns left before the budget ends it.
285    pub fn remaining(&self) -> u32 {
286        self.budget.saturating_sub(self.turns)
287    }
288
289    /// Whether another turn is owed: active, and under the budget.
290    pub fn wants_turn(&self) -> bool {
291        self.state == State::Active && self.turns < self.budget
292    }
293
294    /// The prompt the next turn is given. It is deliberately short: the work so far is in the
295    /// transcript the run is continuing, and a second copy of it here would be a summary the model
296    /// treats as authoritative.
297    pub fn continuation_prompt(&self) -> String {
298        let mut prompt = format!(
299            "Continue working on the goal you were given: {}\n\n\
300             That is the standing goal for this session. Pick up where the previous turn stopped — \
301             do not repeat work that is already done — and keep going until it is finished. If it \
302             cannot be finished, say what is blocking it.",
303            self.text
304        );
305        if let Some(gate) = &self.gate {
306            prompt.push_str(&format!(
307                "\n\nBefore you call it finished, this must pass: `{gate}`"
308            ));
309        }
310        prompt
311    }
312
313    /// One line for a readout.
314    pub fn readout(&self) -> String {
315        let mut line = match self.state {
316            State::Active => format!(
317                "goal active · turn {}/{} · {}",
318                self.turns, self.budget, self.text
319            ),
320            State::Paused => format!(
321                "goal paused · turn {}/{} · {}",
322                self.turns, self.budget, self.text
323            ),
324            State::Done => format!("goal done · {} turn(s) · {}", self.turns, self.text),
325            State::Blocked => format!("goal blocked · {} turn(s) · {}", self.turns, self.text),
326            State::Stopped => format!("goal cleared · {} turn(s)", self.turns),
327        };
328        if let Some(gate) = &self.gate {
329            line.push_str(&format!(" · gate: {gate}"));
330        }
331        if let Some(note) = &self.note {
332            line.push_str(&format!(" · {note}"));
333        }
334        line
335    }
336}
337
338/// Answer one `/goal …` line. The one implementation all three fronts call, so a verb means the
339/// same thing in the terminal and in the browser — including what it refuses.
340///
341/// `start` replaces whatever goal the session had, which is what "one standing goal" means; the
342/// caller kicks off the first turn by asking
343/// [`Agent::goal_continuation`](crate::runtime::Agent::goal_continuation).
344pub fn manage(
345    store: &crate::session::SessionStore,
346    session: &str,
347    arg: &str,
348    now_ms: i64,
349) -> Result<String> {
350    match parse(arg)? {
351        Request::Start { text, gate, budget } => {
352            let goal = Goal::new(session, &text, gate, budget, now_ms);
353            let said = format!(
354                "goal set · {} · up to {} turn(s){} — it is worked on turn by turn until the judge \
355                 says it is done, the budget runs out, or `/goal pause`",
356                goal.text,
357                goal.budget,
358                match &goal.gate {
359                    Some(gate) => format!(" · gate: `{gate}`"),
360                    None => String::new(),
361                }
362            );
363            store.set_goal(&goal)?;
364            Ok(said)
365        }
366        Request::Status => match store.goal(session)? {
367            Some(goal) => {
368                let mut said = goal.readout();
369                let turns = store.goal_turns(session)?;
370                if let Some(last) = turns.last() {
371                    said.push_str(&format!(
372                        " · last judgement: {} (turn {})",
373                        last.verdict, last.turn
374                    ));
375                }
376                Ok(said)
377            }
378            None => Ok(
379                "no goal in this session. `/goal <what you want done>` sets one; a goal is worked \
380                 on across turns until the judge says it is finished"
381                    .to_string(),
382            ),
383        },
384        Request::Pause => {
385            let Some(mut goal) = store.goal(session)? else {
386                return Err(Error::Config("no goal in this session to pause".into()));
387            };
388            if goal.state != State::Active {
389                return Ok(goal.readout());
390            }
391            goal.state = State::Paused;
392            goal.updated_ms = now_ms;
393            goal.note = Some("paused by the person".into());
394            store.set_goal(&goal)?;
395            Ok(format!(
396                "goal paused after {} turn(s) — `/goal resume` continues it",
397                goal.turns
398            ))
399        }
400        Request::Resume => {
401            let Some(mut goal) = store.goal(session)? else {
402                return Err(Error::Config("no goal in this session to resume".into()));
403            };
404            if goal.state != State::Paused {
405                return Ok(goal.readout());
406            }
407            goal.state = State::Active;
408            goal.updated_ms = now_ms;
409            goal.note = None;
410            store.set_goal(&goal)?;
411            Ok(format!(
412                "goal resumed — turn {}/{}",
413                goal.turns + 1,
414                goal.budget
415            ))
416        }
417        Request::Clear => {
418            if store.goal(session)?.is_none() {
419                return Ok("no goal in this session".to_string());
420            }
421            store.clear_goal(session)?;
422            Ok("goal cleared — no further turns will be started for it".to_string())
423        }
424        Request::Gate(gate) => {
425            let Some(mut goal) = store.goal(session)? else {
426                return Err(Error::Config(
427                    "no goal in this session: set one first, then `/goal gate <cmd>`".into(),
428                ));
429            };
430            goal.gate = gate.clone();
431            goal.updated_ms = now_ms;
432            store.set_goal(&goal)?;
433            Ok(match gate {
434                Some(gate) => format!(
435                    "gate set to `{gate}` — the judge's \"done\" is not accepted until it exits 0"
436                ),
437                None => "gate cleared".to_string(),
438            })
439        }
440    }
441}
442
443/// The exact question a judgement asks. One word back, and the three words are the whole answer.
444pub fn judge_prompt(goal: &Goal, last_reply: &str) -> [Message; 2] {
445    const SYSTEM: &str = "\
446You judge whether a standing goal has been reached. You are given the goal, and the last thing the \
447agent said. Answer with exactly one word:\n\
448continue — the work is not finished and there is more to do\n\
449done — the goal has been reached\n\
450blocked — the work cannot proceed without a person\n\
451No explanation, no punctuation, no other word.";
452    let mut user = format!("GOAL: {}", goal.text);
453    if let Some(gate) = &goal.gate {
454        user.push_str(&format!("\nTHE GOAL IS GATED ON: `{gate}` passing"));
455    }
456    user.push_str("\n\nTHE LAST THING THE AGENT SAID:\n");
457    let trimmed = last_reply.trim();
458    if trimmed.is_empty() {
459        user.push_str("(nothing — the turn produced no text)");
460    } else {
461        // Bounded: the tail is where a completion claim lives, and the head is where the
462        // restatement of the task is. Enough of both to judge, not the whole transcript.
463        let budget = 4_000;
464        if trimmed.chars().count() > budget {
465            let head: String = trimmed.chars().take(budget / 2).collect();
466            let tail: String = trimmed
467                .chars()
468                .rev()
469                .take(budget / 2)
470                .collect::<Vec<_>>()
471                .into_iter()
472                .rev()
473                .collect();
474            user.push_str(&format!("{head}\n[…]\n{tail}"));
475        } else {
476            user.push_str(trimmed);
477        }
478    }
479    [Message::system(SYSTEM), Message::user(user)]
480}
481
482/// What a judgement does to a goal. Pure, so the whole state machine is testable without a model.
483///
484/// * under the budget and "continue" → still active;
485/// * "done" → done (a gate is checked by the caller before this is called);
486/// * "blocked" → blocked;
487/// * "unreadable" → continue once, and end the goal if the turn before it was also unreadable;
488/// * the budget reached → done, with a note that says so.
489pub fn apply(goal: &mut Goal, verdict: Verdict, why: Option<String>, now_ms: i64) {
490    goal.turns = goal.turns.saturating_add(1);
491    goal.updated_ms = now_ms;
492    // Any real answer ends a run of unreadable ones: the counter is about a run, not a lifetime.
493    if verdict != Verdict::Unreadable {
494        goal.garbage = false;
495    }
496    let note = why.as_deref().map(str::trim).filter(|w| !w.is_empty());
497    match verdict {
498        Verdict::Done => {
499            goal.state = State::Done;
500            goal.note = Some(match note {
501                Some(why) => format!("the judge called it done: {why}"),
502                None => "the judge called it done".to_string(),
503            });
504        }
505        Verdict::Blocked => {
506            goal.state = State::Blocked;
507            goal.note = Some(match note {
508                Some(why) => format!("blocked: {why}"),
509                None => "the judge said it is blocked".to_string(),
510            });
511        }
512        Verdict::Continue => {
513            goal.note = note.map(|w| format!("continuing: {w}"));
514            if goal.turns >= goal.budget {
515                goal.state = State::Done;
516                goal.note = Some(format!(
517                    "the turn budget ran out after {} turn(s); it did not finish",
518                    goal.turns
519                ));
520            }
521        }
522        Verdict::Unreadable => {
523            goal.note = Some(match note {
524                Some(why) => format!("the judge answered something else: {why}"),
525                None => "the judge answered something that was not continue, done or blocked"
526                    .to_string(),
527            });
528            if goal.garbage {
529                goal.state = State::Blocked;
530                goal.note = Some(
531                    "the judge answered twice with something that was not continue, done or \
532                     blocked, so the goal stopped rather than loop on a guess"
533                        .to_string(),
534                );
535            } else {
536                goal.garbage = true;
537            }
538        }
539    }
540}
541
542/// Split an answer into the word and the rest of the line, so a judge that adds a sentence still
543/// has that sentence kept as the note.
544pub fn split_reply(answer: &str) -> (Verdict, Option<String>) {
545    let trimmed = answer.trim();
546    let verdict = Verdict::parse(trimmed);
547    let rest = trimmed
548        .split_once(char::is_whitespace)
549        .map(|(_, rest)| {
550            // "continue — the tests are still red": the note is the sentence, not the dash that
551            // introduced it. A leading separator is punctuation of the answer, not of the reason.
552            rest.trim()
553                .trim_start_matches(['—', '–', '-', ':', ',', ';'])
554                .trim()
555                .trim_start_matches(['"', '`', '*'])
556                .trim()
557        })
558        .filter(|rest| !rest.is_empty())
559        .map(str::to_string);
560    (verdict, rest)
561}
562
563#[cfg(test)]
564mod tests {
565    use super::*;
566
567    fn goal(text: &str) -> Goal {
568        Goal::new("s1", text, None, None, 0)
569    }
570
571    #[test]
572    fn a_goal_line_is_a_sentence_with_optional_bounds() {
573        assert_eq!(
574            parse("get the release out").unwrap(),
575            Request::Start {
576                text: "get the release out".into(),
577                gate: None,
578                budget: None
579            }
580        );
581        assert_eq!(
582            parse("ship it --budget 4 --gate make smoke").unwrap(),
583            Request::Start {
584                text: "ship it".into(),
585                gate: Some("make smoke".into()),
586                budget: Some(4)
587            }
588        );
589        assert_eq!(
590            parse("-- pause the deploy").unwrap(),
591            Request::Start {
592                text: "pause the deploy".into(),
593                gate: None,
594                budget: None
595            }
596        );
597    }
598
599    #[test]
600    fn the_verbs_are_exact_and_the_escape_is_a_double_dash() {
601        assert_eq!(parse("").unwrap(), Request::Status);
602        assert_eq!(parse("status").unwrap(), Request::Status);
603        assert_eq!(parse("show").unwrap(), Request::Status);
604        assert_eq!(parse("PAUSE").unwrap(), Request::Pause);
605        assert_eq!(parse("resume").unwrap(), Request::Resume);
606        assert_eq!(parse("clear").unwrap(), Request::Clear);
607        assert_eq!(
608            parse("gate make smoke").unwrap(),
609            Request::Gate(Some("make smoke".into()))
610        );
611        assert_eq!(parse("gate clear").unwrap(), Request::Gate(None));
612    }
613
614    #[test]
615    fn a_bad_bound_is_refused_rather_than_clamped() {
616        assert!(parse("x --budget 0").is_err());
617        assert!(parse("x --budget many").is_err());
618        assert!(parse("x --budget 101").is_err());
619        assert!(parse("--gate make smoke").is_err(), "a gate is not a goal");
620    }
621
622    #[test]
623    fn only_the_three_words_are_an_answer() {
624        assert_eq!(Verdict::parse("continue"), Verdict::Continue);
625        assert_eq!(Verdict::parse("Done."), Verdict::Done);
626        assert_eq!(Verdict::parse("\"blocked\""), Verdict::Blocked);
627        for other in ["", "maybe", "it depends", "certainly"] {
628            assert_eq!(Verdict::parse(other), Verdict::Unreadable, "{other:?}");
629        }
630        // A sentence whose first word answers still answers; the rest becomes the note.
631        let (verdict, note) = split_reply("continue — the tests are still red");
632        assert_eq!(verdict, Verdict::Continue);
633        assert_eq!(note.as_deref(), Some("the tests are still red"));
634    }
635
636    #[test]
637    fn a_continue_under_the_budget_leaves_the_goal_active() {
638        let mut g = goal("ship it");
639        apply(&mut g, Verdict::Continue, Some("one step left".into()), 10);
640        assert_eq!(g.state, State::Active);
641        assert_eq!(g.turns, 1);
642        assert_eq!(g.note.as_deref(), Some("continuing: one step left"));
643        assert!(g.wants_turn());
644    }
645
646    #[test]
647    fn done_and_blocked_end_it_and_keep_the_judges_line() {
648        let mut g = goal("ship it");
649        apply(&mut g, Verdict::Done, Some("the release is out".into()), 10);
650        assert_eq!(g.state, State::Done);
651        assert!(!g.wants_turn());
652        assert!(g.note.as_deref().unwrap().contains("the release is out"));
653
654        let mut g = goal("ship it");
655        apply(&mut g, Verdict::Blocked, Some("no credentials".into()), 10);
656        assert_eq!(g.state, State::Blocked);
657        assert!(g.note.as_deref().unwrap().contains("no credentials"));
658    }
659
660    #[test]
661    fn the_budget_ends_it_out_loud_rather_than_going_quiet() {
662        let mut g = Goal::new("s1", "ship it", None, Some(2), 0);
663        apply(&mut g, Verdict::Continue, None, 1);
664        assert!(g.wants_turn());
665        apply(&mut g, Verdict::Continue, None, 2);
666        assert_eq!(g.state, State::Done);
667        assert!(!g.wants_turn());
668        assert!(g.note.as_deref().unwrap().contains("budget ran out"));
669    }
670
671    #[test]
672    fn garbage_is_continue_once_and_then_a_stop_not_a_done() {
673        let mut g = goal("ship it");
674        apply(&mut g, Verdict::Unreadable, None, 1);
675        assert_eq!(g.state, State::Active, "one bad answer is tolerated");
676        assert!(g
677            .note
678            .as_deref()
679            .unwrap()
680            .contains("not continue, done or blocked"));
681        apply(&mut g, Verdict::Unreadable, None, 2);
682        assert_eq!(g.state, State::Blocked, "the second one stops it");
683        assert!(g.note.as_deref().unwrap().contains("twice"), "{:?}", g.note);
684    }
685
686    #[test]
687    fn a_judged_turn_clears_the_garbage_counter() {
688        let mut g = goal("ship it");
689        apply(&mut g, Verdict::Unreadable, None, 1);
690        apply(&mut g, Verdict::Continue, None, 2);
691        assert_eq!(g.state, State::Active);
692        // A later unreadable answer is tolerated again: the counter is about a run of failures,
693        // not a lifetime tally.
694        apply(&mut g, Verdict::Unreadable, None, 3);
695        assert_eq!(g.state, State::Active);
696    }
697
698    #[test]
699    fn the_continuation_prompt_names_the_goal_the_gate_and_what_not_to_redo() {
700        let g = Goal::new("s1", "ship the release", Some("make smoke".into()), None, 0);
701        let prompt = g.continuation_prompt();
702        assert!(prompt.contains("ship the release"), "{prompt}");
703        assert!(prompt.contains("do not repeat work"), "{prompt}");
704        assert!(prompt.contains("make smoke"), "{prompt}");
705    }
706
707    #[test]
708    fn the_judge_question_carries_the_goal_and_the_reply_and_nothing_else() {
709        let g = goal("ship the release");
710        let request = judge_prompt(&g, "the tests are green");
711        assert!(request[0]
712            .content
713            .as_deref()
714            .unwrap()
715            .contains("exactly one word"));
716        let user = request[1].content.as_deref().unwrap();
717        assert!(user.contains("GOAL: ship the release"), "{user}");
718        assert!(user.contains("the tests are green"), "{user}");
719        // A long reply is bounded, keeping both ends.
720        let long = format!("{}{}", "a".repeat(5_000), "the end");
721        let request = judge_prompt(&g, &long);
722        let user = request[1].content.as_deref().unwrap();
723        assert!(user.len() < 5_000, "{} bytes", user.len());
724        assert!(
725            user.contains("the end"),
726            "the tail is the part that says done"
727        );
728    }
729
730    #[test]
731    fn the_readout_says_the_state_the_count_and_the_gate() {
732        let mut g = Goal::new("s1", "ship it", Some("make smoke".into()), Some(3), 0);
733        assert!(g.readout().starts_with("goal active · turn 0/3 · ship it"));
734        assert!(g.readout().contains("gate: make smoke"));
735        apply(&mut g, Verdict::Done, None, 1);
736        assert!(g.readout().starts_with("goal done"));
737    }
738}