eclipse-core 0.15.1

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
//! `#172`: `/goal` — one standing goal, worked on across turns.
//!
//! A goal is not a loop and not a cron job. A loop re-sends the same prompt on a clock; a goal is
//! a sentence about what the work is *for*, and after each turn a small model reads the turn and
//! answers one of three words: keep going, it is done, or it is blocked. A "keep going" enqueues
//! the next turn — through the front's own run entry, like every other turn — and nothing else
//! about the agent changes.
//!
//! The behaviour is data: a `goals` row in the session store (`sessions.db`, foreign-keyed to the
//! session so deleting a session deletes its goal) and one row per judgement in `goal_turns`. The
//! runtime reads those rows; it does not grow a second loop. That is decision 11, and the reason
//! this module holds no timer, no agent and no provider — only the words, the verdict and the
//! arithmetic of a budget.
//!
//! Three rules are the whole safety of it:
//!
//! * **Garbage is not "done".** An answer that is not one of the three words is [`Verdict::Unreadable`];
//!   it counts as "continue" once and then ends the goal, because a judge that cannot answer must
//!   not be asked forever and must never be read as success.
//! * **A budget ends it out loud.** `turns` is capped, and reaching the cap writes a note rather
//!   than going quiet.
//! * **A gate is a command, not an opinion.** `--gate "<cmd>"` must exit 0 before "done" is
//!   accepted; a failing gate turns a "done" back into a "continue" and says so.

use crate::error::{Error, Result};
use crate::message::Message;
use serde::{Deserialize, Serialize};

/// How many turns a goal gets when nothing says otherwise. Twelve is enough for a job that takes a
/// handful of steps, and few enough that a goal with no ending in sight costs minutes, not an hour.
pub const DEFAULT_BUDGET: u32 = 12;

/// The most a goal may be given. A bound in the thousands is a way of writing "forever" with a
/// number that looks deliberate.
pub const MAX_BUDGET: u32 = 100;

/// Where a goal is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum State {
    /// Being worked on: the next turn is due whenever the last one finished.
    Active,
    /// Held by the person. `resume` puts it back.
    Paused,
    /// Finished, either because the judge said so or because the budget ran out.
    Done,
    /// The judge said the work cannot proceed. A person is the only way out of it.
    Blocked,
    /// `/goal clear`.
    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",
        }
    }
}

/// One session's goal, as the store keeps it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Goal {
    pub session: String,
    /// What the work is for, in the person's own words.
    pub text: String,
    /// A shell command that must exit 0 before "done" is accepted. Optional.
    pub gate: Option<String>,
    /// How many judged turns it may use.
    pub budget: u32,
    /// How many it has used.
    pub turns: u32,
    pub state: State,
    /// The one line the last judgement produced, or why the goal ended. Shown, not parsed.
    pub note: Option<String>,
    /// Set when the last judgement was unreadable. A run of two ends the goal; any real answer
    /// clears it, and it is stored so a restart does not reset the count.
    pub garbage: bool,
    pub created_ms: i64,
    pub updated_ms: i64,
}

/// What one judgement decided, as a row in `goal_turns`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Verdict {
    Continue,
    Done,
    Blocked,
    /// An answer that was not one of the three words. Continue once, then stop.
    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,
        }
    }
}

/// One recorded judgement.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Judgement {
    /// 1-based: the turn number this judgement is about.
    pub turn: u32,
    pub verdict: String,
    pub why: Option<String>,
    pub at_ms: i64,
}

/// Everything after the `/goal` word.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Request {
    /// `/goal <text>` — or `-- ` before it, for a sentence that starts with a flag-like word.
    Start {
        text: String,
        gate: Option<String>,
        budget: Option<u32>,
    },
    /// `/goal` or `/goal status` or `/goal show`.
    Status,
    Pause,
    Resume,
    Clear,
    /// `/goal gate <cmd>` sets one; `/goal gate clear` removes it.
    Gate(Option<String>),
}

/// Parse a `/goal` line.
///
/// The verbs are checked first and exactly, so a goal whose text happens to begin with "pause"
/// is written as `/goal -- pause the deploy` — the same escape every argument-taking command in
/// this build uses.
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)));
    }
    // `--` is the escape, and it has to stand alone: everything after it is the goal's own words,
    // flags and all. `--gate foo` with no sentence in front of it is a flag typed where the goal
    // goes — a mistake worth saying out loud rather than quietly turning into a goal called
    // "gate foo".
    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 {
    /// A fresh goal, active, with nothing used yet.
    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,
        }
    }

    /// Turns left before the budget ends it.
    pub fn remaining(&self) -> u32 {
        self.budget.saturating_sub(self.turns)
    }

    /// Whether another turn is owed: active, and under the budget.
    pub fn wants_turn(&self) -> bool {
        self.state == State::Active && self.turns < self.budget
    }

    /// The prompt the next turn is given. It is deliberately short: the work so far is in the
    /// transcript the run is continuing, and a second copy of it here would be a summary the model
    /// treats as authoritative.
    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
    }

    /// One line for a readout.
    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
    }
}

/// Answer one `/goal …` line. The one implementation all three fronts call, so a verb means the
/// same thing in the terminal and in the browser — including what it refuses.
///
/// `start` replaces whatever goal the session had, which is what "one standing goal" means; the
/// caller kicks off the first turn by asking
/// [`Agent::goal_continuation`](crate::runtime::Agent::goal_continuation).
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(),
            })
        }
    }
}

/// The exact question a judgement asks. One word back, and the three words are the whole answer.
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 {
        // Bounded: the tail is where a completion claim lives, and the head is where the
        // restatement of the task is. Enough of both to judge, not the whole transcript.
        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)]
}

/// What a judgement does to a goal. Pure, so the whole state machine is testable without a model.
///
/// * under the budget and "continue" → still active;
/// * "done" → done (a gate is checked by the caller before this is called);
/// * "blocked" → blocked;
/// * "unreadable" → continue once, and end the goal if the turn before it was also unreadable;
/// * the budget reached → done, with a note that says so.
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;
    // Any real answer ends a run of unreadable ones: the counter is about a run, not a lifetime.
    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;
            }
        }
    }
}

/// Split an answer into the word and the rest of the line, so a judge that adds a sentence still
/// has that sentence kept as the note.
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)| {
            // "continue — the tests are still red": the note is the sentence, not the dash that
            // introduced it. A leading separator is punctuation of the answer, not of the reason.
            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:?}");
        }
        // A sentence whose first word answers still answers; the rest becomes the note.
        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);
        // A later unreadable answer is tolerated again: the counter is about a run of failures,
        // not a lifetime tally.
        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}");
        // A long reply is bounded, keeping both ends.
        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"));
    }
}