Skip to main content

base/context/
goal.rs

1//! Session goals: an objective the engine keeps working on across turns, one
2//! automatic round at a time, until the model marks it complete or blocked or
3//! its rounds or its token budget run out.
4//!
5//! A goal's rounds spend into a node of its own under the session's
6//! (`SessionLedger::goal_spent`); what that node has spent is passed in where
7//! a judgement needs it, as `spent`.
8//!
9//! This module is the state machine and its authority rules. The tools that
10//! drive it from the model live in `tools::goal`; whoever owns the turn loop
11//! (`runtime::Agent::run`, or the daemon's session pool) asks
12//! [`GoalSlot::next_round`] when a turn ends, and claims the round it returns
13//! with [`GoalSlot::claim_round`] when that round's turn starts.
14
15use serde::{Deserialize, Serialize};
16
17/// Log namespace and event under which a goal snapshot is recorded.
18pub const GOAL_NS: &str = "agix.goal";
19pub const GOAL_EVENT: &str = "change";
20
21pub const DEFAULT_MAX_ROUNDS: u32 = 256;
22pub const MAX_ROUNDS_LIMIT: u32 = 10_000;
23/// Automatic rounds that must have run since the goal was last armed before
24/// one of them may report the goal blocked.
25pub const BLOCKED_MIN_ROUNDS: u32 = 3;
26
27const GOAL_TURN_PREFIX: &str = "goal-";
28
29/// Goal snapshots to write to the session log, oldest first; `None` records
30/// a cleared goal. See `SessionState::unrecorded_goal_changes` in `session-state`.
31pub struct UnrecordedGoalChanges {
32    pub changes: Vec<Option<Goal>>,
33    _writing: tokio::sync::OwnedMutexGuard<()>,
34}
35
36impl UnrecordedGoalChanges {
37    pub fn new(changes: Vec<Option<Goal>>, writing: tokio::sync::OwnedMutexGuard<()>) -> Self {
38        Self {
39            changes,
40            _writing: writing,
41        }
42    }
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
46#[serde(rename_all = "snake_case")]
47#[non_exhaustive]
48pub enum GoalPhase {
49    Active,
50    Paused,
51    Blocked,
52    Complete,
53}
54
55#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
56pub struct Goal {
57    pub id: String,
58    pub revision: u64,
59    pub objective: String,
60    pub phase: GoalPhase,
61    pub max_rounds: u32,
62    /// The most tokens its rounds may spend, counted as every budget is,
63    /// their delegates and side calls included. `None`: no limit.
64    #[serde(default, skip_serializing_if = "Option::is_none")]
65    pub token_budget: Option<u64>,
66    pub rounds_started: u32,
67    /// Rounds started since the goal was last armed; what the blocked lower
68    /// bound counts.
69    #[serde(default)]
70    pub rounds_since_armed: u32,
71    #[serde(default, skip_serializing_if = "Option::is_none")]
72    pub blocked_reason: Option<String>,
73}
74
75/// Who started the turn a goal operation happens in.
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
77#[non_exhaustive]
78pub enum TurnOrigin {
79    /// A person, through a client or the host.
80    #[default]
81    Human,
82    /// An automatic goal round.
83    GoalRound { revision: u64, round: u32 },
84    /// Anything else that starts turns on its own, such as a scheduled job.
85    Automation,
86}
87
88impl TurnOrigin {
89    /// Read from the turn id the turn was started under.
90    pub fn from_turn_id(turn_id: &str) -> Self {
91        if let Some(rest) = turn_id.strip_prefix(GOAL_TURN_PREFIX) {
92            let mut parts = rest.splitn(3, '-');
93            if let (Some(revision), Some(round)) = (parts.next(), parts.next()) {
94                if let (Ok(revision), Ok(round)) = (revision.parse(), round.parse()) {
95                    return Self::GoalRound { revision, round };
96                }
97            }
98        }
99        if turn_id.starts_with("schedule-") || turn_id.starts_with("cron-") {
100            return Self::Automation;
101        }
102        Self::Human
103    }
104}
105
106#[derive(Debug, Clone, PartialEq, Eq)]
107#[non_exhaustive]
108pub enum GoalAction {
109    Edit {
110        objective: Option<String>,
111        max_rounds: Option<u32>,
112        token_budget: Option<u64>,
113    },
114    Pause,
115    Resume,
116    Complete,
117    Blocked {
118        reason: String,
119    },
120}
121
122#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
123#[non_exhaustive]
124pub enum GoalError {
125    #[error("this session has no goal")]
126    NoGoal,
127    #[error("the session already has an unfinished goal ({0}); complete or clear it first")]
128    AlreadyActive(String),
129    #[error("goal id {given} does not match the current goal {current}")]
130    WrongGoal { given: String, current: String },
131    #[error("revision {given} is stale; the goal is at revision {current} — read it again")]
132    StaleRevision { given: u64, current: u64 },
133    #[error("{0}")]
134    NotAllowed(String),
135    #[error("cannot {action} a goal that is {phase:?}")]
136    BadTransition {
137        action: &'static str,
138        phase: GoalPhase,
139    },
140    #[error("{0}")]
141    Invalid(String),
142}
143
144/// A session's goal together with whether automatic rounds are armed.
145/// Arming is never persisted: a goal read back from the log is disarmed until
146/// a person resumes it.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub struct GoalSlot {
149    pub goal: Option<Goal>,
150    pub armed: bool,
151    /// The turn id of the round handed out and not yet started. At most one
152    /// round is outstanding, so turns that end while it waits start no other.
153    pub pending_round: Option<String>,
154    /// The least revision the next goal may take, so a goal created after a
155    /// clear never repeats a revision an earlier round still carries.
156    pub next_revision: u64,
157}
158
159/// A goal as hosts and the model see it: the goal, whether automatic rounds
160/// are armed, and what its rounds have spent.
161#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
162pub struct GoalView {
163    #[serde(flatten)]
164    pub goal: Goal,
165    pub armed: bool,
166    pub tokens_used: u64,
167}
168
169/// How large a goal may be made, and by whom: `max_rounds` above
170/// `max_rounds_limit` is refused.
171#[derive(Debug, Clone, Copy, PartialEq, Eq)]
172pub struct GoalLimits {
173    pub max_rounds: Option<u32>,
174    pub token_budget: Option<u64>,
175    pub max_rounds_limit: u32,
176}
177
178impl GoalLimits {
179    /// What a host asks for, held to the format's limit.
180    pub fn asked(max_rounds: Option<u32>, token_budget: Option<u64>) -> Self {
181        Self {
182            max_rounds,
183            token_budget,
184            max_rounds_limit: MAX_ROUNDS_LIMIT,
185        }
186    }
187}
188
189/// The next automatic round to run.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct GoalRound {
192    pub turn_id: String,
193    pub message: String,
194}
195
196impl GoalSlot {
197    pub fn view(&self, spent: u64) -> Option<GoalView> {
198        self.goal.clone().map(|goal| GoalView {
199            goal,
200            armed: self.armed,
201            tokens_used: spent,
202        })
203    }
204
205    /// The goal as read back from a log: disarmed.
206    pub fn restored(goal: Option<Goal>) -> Self {
207        Self {
208            goal,
209            ..Self::default()
210        }
211    }
212
213    pub fn create(
214        &mut self,
215        objective: String,
216        limits: GoalLimits,
217        origin: TurnOrigin,
218    ) -> Result<Goal, GoalError> {
219        require_human(origin, "create a goal")?;
220        let objective = non_empty(objective)?;
221        let max_rounds = checked_max_rounds(
222            limits
223                .max_rounds
224                .unwrap_or(DEFAULT_MAX_ROUNDS.min(limits.max_rounds_limit)),
225            limits.max_rounds_limit,
226        )?;
227        let token_budget = checked_token_budget(limits.token_budget)?;
228        if let Some(goal) = &self.goal {
229            if goal.phase != GoalPhase::Complete {
230                return Err(GoalError::AlreadyActive(goal.id.clone()));
231            }
232        }
233        let revision = self
234            .goal
235            .as_ref()
236            .map_or(1, |g| g.revision + 1)
237            .max(self.next_revision);
238        let goal = Goal {
239            id: crate::id::Id::new().to_string(),
240            revision,
241            objective,
242            phase: GoalPhase::Active,
243            max_rounds,
244            token_budget,
245            rounds_started: 0,
246            rounds_since_armed: 0,
247            blocked_reason: None,
248        };
249        self.goal = Some(goal.clone());
250        self.armed = true;
251        self.pending_round = None;
252        Ok(goal)
253    }
254
255    /// `spent` is what the goal's rounds have spent; `max_rounds_limit` the
256    /// most rounds an edit may give it.
257    pub fn update(
258        &mut self,
259        goal_id: &str,
260        revision: u64,
261        action: GoalAction,
262        origin: TurnOrigin,
263        spent: u64,
264        max_rounds_limit: u32,
265    ) -> Result<Goal, GoalError> {
266        let goal = self.goal.as_mut().ok_or(GoalError::NoGoal)?;
267        if goal.id != goal_id {
268            return Err(GoalError::WrongGoal {
269                given: goal_id.to_string(),
270                current: goal.id.clone(),
271            });
272        }
273        if goal.revision != revision {
274            return Err(GoalError::StaleRevision {
275                given: revision,
276                current: goal.revision,
277            });
278        }
279        match action {
280            GoalAction::Edit {
281                objective,
282                max_rounds,
283                token_budget,
284            } => {
285                let max_rounds = max_rounds
286                    .map(|n| checked_max_rounds(n, max_rounds_limit))
287                    .transpose()?;
288                let token_budget = checked_token_budget(token_budget)?;
289                edit_goal(goal, origin, objective, max_rounds, token_budget)?
290            }
291            GoalAction::Pause => pause_goal(goal, &mut self.armed, origin)?,
292            GoalAction::Resume => resume_goal(goal, &mut self.armed, origin, spent)?,
293            GoalAction::Complete => complete_goal(goal, &mut self.armed, origin)?,
294            GoalAction::Blocked { reason } => block_goal(goal, &mut self.armed, origin, reason)?,
295        }
296        goal.revision += 1;
297        self.pending_round = None;
298        Ok(goal.clone())
299    }
300
301    pub fn clear(&mut self, origin: TurnOrigin) -> Result<(), GoalError> {
302        require_human(origin, "clear a goal")?;
303        let Some(goal) = self.goal.take() else {
304            return Err(GoalError::NoGoal);
305        };
306        self.next_revision = self.next_revision.max(goal.revision + 1);
307        self.armed = false;
308        self.pending_round = None;
309        Ok(())
310    }
311
312    /// Stop automatic rounds without changing the goal — a round that ended
313    /// abnormally (cancelled, errored, out of budget) leaves it for a person
314    /// to resume.
315    pub fn disarm(&mut self) -> bool {
316        self.pending_round = None;
317        std::mem::replace(&mut self.armed, false)
318    }
319
320    /// Mark an active goal blocked whose budget its rounds have spent, `next`
321    /// input included, as one whose rounds are all used is. Whether it changed.
322    pub fn block_if_spent(&mut self, spent: u64, next: u64) -> bool {
323        let Some(goal) = self.goal.as_mut() else {
324            return false;
325        };
326        let Some(budget) = goal.token_budget.filter(|&b| spent_out(b, spent + next)) else {
327            return false;
328        };
329        if goal.phase != GoalPhase::Active {
330            return false;
331        }
332        goal.phase = GoalPhase::Blocked;
333        goal.blocked_reason = Some(format!("token budget: {spent} of {budget} tokens used"));
334        goal.revision += 1;
335        self.armed = false;
336        self.pending_round = None;
337        true
338    }
339
340    /// The next automatic round, or `None` when the goal is not active and
341    /// armed or a round is already outstanding. A goal whose rounds or
342    /// token budget (against `spent`) are used up is marked blocked instead;
343    /// the second value says whether the goal changed. The round counts as
344    /// started only once it is claimed.
345    pub fn next_round(&mut self, spent: u64) -> (Option<GoalRound>, bool) {
346        let Some(goal) = self.goal.as_mut() else {
347            return (None, false);
348        };
349        if !self.armed || goal.phase != GoalPhase::Active || self.pending_round.is_some() {
350            return (None, false);
351        }
352        if goal.rounds_started >= goal.max_rounds {
353            goal.phase = GoalPhase::Blocked;
354            goal.blocked_reason = Some(format!("round limit: all {} rounds used", goal.max_rounds));
355            goal.revision += 1;
356            self.armed = false;
357            return (None, true);
358        }
359        if self.block_if_spent(spent, 0) {
360            return (None, true);
361        }
362        let Some(goal) = self.goal.as_mut() else {
363            return (None, false);
364        };
365        let number = goal.rounds_started + 1;
366        let round = GoalRound {
367            turn_id: format!(
368                "{GOAL_TURN_PREFIX}{}-{number}-{}",
369                goal.revision,
370                crate::id::Id::new()
371            ),
372            message: round_message(goal, number),
373        };
374        self.pending_round = Some(round.turn_id.clone());
375        (Some(round), false)
376    }
377
378    /// Start the outstanding round `turn_id`, counting it. `false` when it is
379    /// no longer wanted — the goal was paused, cleared, changed or disarmed
380    /// since it was handed out — and the turn must not run.
381    pub fn claim_round(&mut self, turn_id: &str) -> bool {
382        if self.pending_round.as_deref() != Some(turn_id) {
383            return false;
384        }
385        self.pending_round = None;
386        let Some(goal) = self.goal.as_mut() else {
387            return false;
388        };
389        if !self.armed || goal.phase != GoalPhase::Active {
390            return false;
391        }
392        goal.rounds_started += 1;
393        goal.rounds_since_armed += 1;
394        true
395    }
396
397    /// Give up the outstanding round `turn_id` without running it, so the
398    /// next turn to end may hand out another.
399    pub fn abandon_round(&mut self, turn_id: &str) {
400        if self.pending_round.as_deref() == Some(turn_id) {
401            self.pending_round = None;
402        }
403    }
404}
405
406fn round_message(goal: &Goal, round: u32) -> String {
407    let budget = goal
408        .token_budget
409        .map(|b| format!("Token budget: {b}\n"))
410        .unwrap_or_default();
411    format!(
412        "<goal_round>\nObjective: {}\nRound: {}/{}\n{budget}\nContinue working toward the objective in this \
413         session. Treat the workspace, tool results and session state as authoritative. Before \
414         claiming completion, gather evidence that the whole objective is met, then mark it \
415         complete with GoalUpdate (goal_id {}, read the current revision with GoalGet). If work \
416         remains, leave the goal active for the next round. Mark it blocked only when the same \
417         blocker has held for {BLOCKED_MIN_ROUNDS} consecutive rounds — difficulty or remaining \
418         work is not a blocker.\n</goal_round>",
419        goal.objective, round, goal.max_rounds, goal.id
420    )
421}
422
423fn require_human(origin: TurnOrigin, what: &str) -> Result<(), GoalError> {
424    match origin {
425        TurnOrigin::Human => Ok(()),
426        _ => Err(GoalError::NotAllowed(format!(
427            "only a direct request from the user can {what}"
428        ))),
429    }
430}
431
432fn require_human_or_this_round(
433    origin: TurnOrigin,
434    revision: u64,
435    what: &str,
436) -> Result<(), GoalError> {
437    match origin {
438        TurnOrigin::Human => Ok(()),
439        TurnOrigin::GoalRound { revision: r, .. } if r == revision => Ok(()),
440        TurnOrigin::GoalRound { .. } => Err(GoalError::NotAllowed(format!(
441            "this round belongs to an earlier revision of the goal; it cannot {what}"
442        ))),
443        TurnOrigin::Automation => Err(GoalError::NotAllowed(format!(
444            "only the user or a round of this goal can {what}"
445        ))),
446    }
447}
448
449fn non_empty(s: String) -> Result<String, GoalError> {
450    let s = s.trim().to_string();
451    if s.is_empty() {
452        Err(GoalError::Invalid("must not be empty".into()))
453    } else {
454        Ok(s)
455    }
456}
457
458fn checked_max_rounds(n: u32, limit: u32) -> Result<u32, GoalError> {
459    if (1..=limit).contains(&n) {
460        Ok(n)
461    } else {
462        Err(GoalError::Invalid(format!(
463            "max_rounds must be between 1 and {limit}"
464        )))
465    }
466}
467
468/// Whether `budget` leaves too little after `spent` for another model call.
469fn spent_out(budget: u64, spent: u64) -> bool {
470    budget.saturating_sub(spent) < crate::interface::budget_policy::MIN_CALL_TOKENS
471}
472
473fn checked_token_budget(budget: Option<u64>) -> Result<Option<u64>, GoalError> {
474    match budget {
475        Some(0) => Err(GoalError::Invalid("token_budget must be at least 1".into())),
476        budget => Ok(budget),
477    }
478}
479
480fn edit_goal(
481    goal: &mut Goal,
482    origin: TurnOrigin,
483    objective: Option<String>,
484    max_rounds: Option<u32>,
485    token_budget: Option<u64>,
486) -> Result<(), GoalError> {
487    require_human(origin, "edit a goal")?;
488    if goal.phase == GoalPhase::Complete {
489        return Err(GoalError::BadTransition {
490            action: "edit",
491            phase: goal.phase,
492        });
493    }
494    if let Some(objective) = objective {
495        goal.objective = non_empty(objective)?;
496    }
497    if let Some(max) = max_rounds {
498        goal.max_rounds = max;
499    }
500    if token_budget.is_some() {
501        goal.token_budget = token_budget;
502    }
503    goal.rounds_since_armed = 0;
504    Ok(())
505}
506
507fn pause_goal(goal: &mut Goal, armed: &mut bool, origin: TurnOrigin) -> Result<(), GoalError> {
508    require_human(origin, "pause a goal")?;
509    if goal.phase != GoalPhase::Active {
510        return Err(GoalError::BadTransition {
511            action: "pause",
512            phase: goal.phase,
513        });
514    }
515    goal.phase = GoalPhase::Paused;
516    *armed = false;
517    Ok(())
518}
519
520fn resume_goal(
521    goal: &mut Goal,
522    armed: &mut bool,
523    origin: TurnOrigin,
524    spent: u64,
525) -> Result<(), GoalError> {
526    require_human(origin, "resume a goal")?;
527    let resumable = matches!(goal.phase, GoalPhase::Paused | GoalPhase::Blocked)
528        || (goal.phase == GoalPhase::Active && !*armed);
529    if !resumable {
530        return Err(GoalError::BadTransition {
531            action: "resume",
532            phase: goal.phase,
533        });
534    }
535    if goal.rounds_started >= goal.max_rounds {
536        return Err(GoalError::NotAllowed(format!(
537            "all {} rounds are used; edit the goal to raise max_rounds before resuming",
538            goal.max_rounds
539        )));
540    }
541    if let Some(budget) = goal.token_budget.filter(|&b| spent_out(b, spent)) {
542        return Err(GoalError::NotAllowed(format!(
543            "{spent} of its {budget} tokens are used; edit the goal to raise token_budget \
544             before resuming"
545        )));
546    }
547    goal.phase = GoalPhase::Active;
548    goal.blocked_reason = None;
549    goal.rounds_since_armed = 0;
550    *armed = true;
551    Ok(())
552}
553
554fn complete_goal(goal: &mut Goal, armed: &mut bool, origin: TurnOrigin) -> Result<(), GoalError> {
555    require_human_or_this_round(origin, goal.revision, "complete a goal")?;
556    if goal.phase == GoalPhase::Complete {
557        return Err(GoalError::BadTransition {
558            action: "complete",
559            phase: goal.phase,
560        });
561    }
562    goal.phase = GoalPhase::Complete;
563    *armed = false;
564    Ok(())
565}
566
567fn block_goal(
568    goal: &mut Goal,
569    armed: &mut bool,
570    origin: TurnOrigin,
571    reason: String,
572) -> Result<(), GoalError> {
573    require_human_or_this_round(origin, goal.revision, "mark a goal blocked")?;
574    if goal.phase != GoalPhase::Active {
575        return Err(GoalError::BadTransition {
576            action: "block",
577            phase: goal.phase,
578        });
579    }
580    if matches!(origin, TurnOrigin::GoalRound { .. })
581        && goal.rounds_since_armed < BLOCKED_MIN_ROUNDS
582    {
583        return Err(GoalError::NotAllowed(format!(
584            "a goal can be marked blocked only after the same blocker has held for \
585             {BLOCKED_MIN_ROUNDS} consecutive rounds (this is round {}); keep \
586             working on it, or describe the blocker and let the next round retry",
587            goal.rounds_since_armed
588        )));
589    }
590    goal.phase = GoalPhase::Blocked;
591    goal.blocked_reason = Some(non_empty(reason)?);
592    *armed = false;
593    Ok(())
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    trait Up {
601        fn up(
602            &mut self,
603            id: &str,
604            rev: u64,
605            action: GoalAction,
606            origin: TurnOrigin,
607        ) -> Result<Goal, GoalError>;
608    }
609
610    impl Up for GoalSlot {
611        fn up(
612            &mut self,
613            id: &str,
614            rev: u64,
615            action: GoalAction,
616            origin: TurnOrigin,
617        ) -> Result<Goal, GoalError> {
618            self.update(id, rev, action, origin, 0, MAX_ROUNDS_LIMIT)
619        }
620    }
621
622    fn active() -> GoalSlot {
623        let mut slot = GoalSlot::default();
624        slot.create(
625            "ship it".into(),
626            GoalLimits::asked(Some(5), None),
627            TurnOrigin::Human,
628        )
629        .unwrap();
630        slot
631    }
632
633    fn ids(slot: &GoalSlot) -> (String, u64) {
634        let g = slot.goal.as_ref().unwrap();
635        (g.id.clone(), g.revision)
636    }
637
638    fn start_round(slot: &mut GoalSlot) -> Option<GoalRound> {
639        let round = slot.next_round(0).0?;
640        assert!(slot.claim_round(&round.turn_id));
641        Some(round)
642    }
643
644    fn round_origin(slot: &GoalSlot) -> TurnOrigin {
645        TurnOrigin::GoalRound {
646            revision: slot.goal.as_ref().unwrap().revision,
647            round: 1,
648        }
649    }
650
651    #[test]
652    fn a_round_turn_id_reads_back_as_its_origin() {
653        let mut slot = active();
654        let (round, changed) = slot.next_round(0);
655        let round = round.unwrap();
656        assert!(!changed);
657        assert_eq!(
658            TurnOrigin::from_turn_id(&round.turn_id),
659            TurnOrigin::GoalRound {
660                revision: 1,
661                round: 1
662            }
663        );
664        assert_eq!(TurnOrigin::from_turn_id("t-123"), TurnOrigin::Human);
665        assert_eq!(
666            TurnOrigin::from_turn_id("schedule-x-y"),
667            TurnOrigin::Automation
668        );
669        assert!(round.message.contains("Round: 1/5"));
670    }
671
672    #[test]
673    fn only_a_person_creates_edits_pauses_resumes_and_clears() {
674        let mut slot = GoalSlot::default();
675        for origin in [
676            TurnOrigin::Automation,
677            TurnOrigin::GoalRound {
678                revision: 1,
679                round: 1,
680            },
681        ] {
682            assert!(matches!(
683                slot.create("x".into(), GoalLimits::asked(None, None), origin),
684                Err(GoalError::NotAllowed(_))
685            ));
686        }
687        let mut slot = active();
688        let (id, rev) = ids(&slot);
689        let round = round_origin(&slot);
690        for action in [
691            GoalAction::Pause,
692            GoalAction::Resume,
693            GoalAction::Edit {
694                objective: Some("y".into()),
695                max_rounds: None,
696                token_budget: None,
697            },
698        ] {
699            assert!(matches!(
700                slot.up(&id, rev, action, round),
701                Err(GoalError::NotAllowed(_))
702            ));
703        }
704        assert!(matches!(slot.clear(round), Err(GoalError::NotAllowed(_))));
705    }
706
707    #[test]
708    fn a_round_may_complete_its_own_revision() {
709        let mut slot = active();
710        slot.next_round(0);
711        let (id, rev) = ids(&slot);
712        let stale = TurnOrigin::GoalRound {
713            revision: rev - 1,
714            round: 1,
715        };
716        assert!(slot.up(&id, rev, GoalAction::Complete, stale).is_err());
717        let goal = slot
718            .up(&id, rev, GoalAction::Complete, round_origin(&slot))
719            .unwrap();
720        assert_eq!(goal.phase, GoalPhase::Complete);
721        assert!(!slot.armed);
722        assert_eq!(slot.next_round(0), (None, false));
723    }
724
725    #[test]
726    fn a_round_may_block_only_after_the_lower_bound() {
727        let mut slot = active();
728        for round in 1..=BLOCKED_MIN_ROUNDS {
729            start_round(&mut slot);
730            let (id, rev) = ids(&slot);
731            let result = slot.up(
732                &id,
733                rev,
734                GoalAction::Blocked {
735                    reason: "no access".into(),
736                },
737                round_origin(&slot),
738            );
739            if round < BLOCKED_MIN_ROUNDS {
740                assert!(matches!(result, Err(GoalError::NotAllowed(_))), "{round}");
741            } else {
742                assert_eq!(result.unwrap().phase, GoalPhase::Blocked);
743            }
744        }
745    }
746
747    #[test]
748    fn a_person_may_block_at_once() {
749        let mut slot = active();
750        let (id, rev) = ids(&slot);
751        let goal = slot
752            .up(
753                &id,
754                rev,
755                GoalAction::Blocked {
756                    reason: "waiting on legal".into(),
757                },
758                TurnOrigin::Human,
759            )
760            .unwrap();
761        assert_eq!(goal.phase, GoalPhase::Blocked);
762    }
763
764    #[test]
765    fn a_stale_revision_or_another_goal_id_is_refused() {
766        let mut slot = active();
767        let (id, rev) = ids(&slot);
768        assert!(matches!(
769            slot.up(&id, rev + 1, GoalAction::Pause, TurnOrigin::Human),
770            Err(GoalError::StaleRevision { .. })
771        ));
772        assert!(matches!(
773            slot.up("other", rev, GoalAction::Pause, TurnOrigin::Human),
774            Err(GoalError::WrongGoal { .. })
775        ));
776    }
777
778    #[test]
779    fn rounds_run_out_into_blocked() {
780        let mut slot = GoalSlot::default();
781        slot.create(
782            "x".into(),
783            GoalLimits::asked(Some(2), None),
784            TurnOrigin::Human,
785        )
786        .unwrap();
787        assert!(start_round(&mut slot).is_some());
788        assert!(start_round(&mut slot).is_some());
789        let (round, changed) = slot.next_round(0);
790        assert!(round.is_none() && changed);
791        let goal = slot.goal.as_ref().unwrap();
792        assert_eq!(goal.phase, GoalPhase::Blocked);
793        assert!(goal
794            .blocked_reason
795            .as_deref()
796            .unwrap()
797            .contains("round limit"));
798        let (id, rev) = ids(&slot);
799        assert!(matches!(
800            slot.up(&id, rev, GoalAction::Resume, TurnOrigin::Human),
801            Err(GoalError::NotAllowed(_))
802        ));
803        slot.up(
804            &id,
805            rev,
806            GoalAction::Edit {
807                objective: None,
808                max_rounds: Some(4),
809                token_budget: None,
810            },
811            TurnOrigin::Human,
812        )
813        .unwrap();
814        let (id, rev) = ids(&slot);
815        slot.up(&id, rev, GoalAction::Resume, TurnOrigin::Human)
816            .unwrap();
817        assert!(slot.next_round(0).0.is_some());
818    }
819
820    #[test]
821    fn a_spent_token_budget_blocks_the_goal_until_it_is_raised() {
822        let mut slot = GoalSlot::default();
823        slot.create(
824            "x".into(),
825            GoalLimits::asked(None, Some(5_000)),
826            TurnOrigin::Human,
827        )
828        .unwrap();
829        assert!(start_round(&mut slot).is_some());
830        assert!(!slot.block_if_spent(3_976, 0), "1024 left pays for a call");
831        assert!(!slot.block_if_spent(3_000, 976), "nor with the input");
832        let (round, changed) = slot.next_round(4_000);
833        assert!(round.is_none() && changed);
834        let goal = slot.goal.as_ref().unwrap();
835        assert_eq!(goal.phase, GoalPhase::Blocked);
836        assert_eq!(
837            goal.blocked_reason.as_deref(),
838            Some("token budget: 4000 of 5000 tokens used")
839        );
840        let (id, rev) = ids(&slot);
841        assert!(matches!(
842            slot.update(&id, rev, GoalAction::Resume, TurnOrigin::Human, 4_000, 10),
843            Err(GoalError::NotAllowed(_))
844        ));
845        let edit = GoalAction::Edit {
846            objective: None,
847            max_rounds: None,
848            token_budget: Some(9_000),
849        };
850        slot.update(&id, rev, edit, TurnOrigin::Human, 4_000, 10)
851            .unwrap();
852        let (id, rev) = ids(&slot);
853        slot.update(&id, rev, GoalAction::Resume, TurnOrigin::Human, 4_000, 10)
854            .unwrap();
855        assert!(slot.next_round(4_000).0.is_some());
856    }
857
858    #[test]
859    fn a_goal_is_held_to_the_rounds_its_setter_may_give() {
860        let mut slot = GoalSlot::default();
861        let limits = GoalLimits {
862            max_rounds: Some(50),
863            token_budget: None,
864            max_rounds_limit: 10,
865        };
866        assert!(matches!(
867            slot.create("x".into(), limits, TurnOrigin::Human),
868            Err(GoalError::Invalid(_))
869        ));
870        let limits = GoalLimits {
871            max_rounds: None,
872            ..limits
873        };
874        let goal = slot.create("x".into(), limits, TurnOrigin::Human).unwrap();
875        assert_eq!(goal.max_rounds, 10, "the default is held to the limit too");
876        assert!(matches!(
877            slot.create(
878                "y".into(),
879                GoalLimits::asked(None, Some(0)),
880                TurnOrigin::Human
881            ),
882            Err(GoalError::AlreadyActive(_) | GoalError::Invalid(_))
883        ));
884    }
885
886    #[test]
887    fn a_restored_goal_waits_for_a_person() {
888        let mut slot = active();
889        let mut restored = GoalSlot::restored(slot.goal.take());
890        assert_eq!(restored.next_round(0), (None, false));
891        let (id, rev) = ids(&restored);
892        restored
893            .up(&id, rev, GoalAction::Resume, TurnOrigin::Human)
894            .unwrap();
895        assert!(restored.next_round(0).0.is_some());
896    }
897
898    #[test]
899    fn a_new_goal_waits_for_the_last_one_to_finish() {
900        let mut slot = active();
901        assert!(matches!(
902            slot.create(
903                "again".into(),
904                GoalLimits::asked(None, None),
905                TurnOrigin::Human
906            ),
907            Err(GoalError::AlreadyActive(_))
908        ));
909        let (id, rev) = ids(&slot);
910        slot.up(&id, rev, GoalAction::Complete, TurnOrigin::Human)
911            .unwrap();
912        let next = slot
913            .create(
914                "again".into(),
915                GoalLimits::asked(None, None),
916                TurnOrigin::Human,
917            )
918            .unwrap();
919        assert_eq!(next.max_rounds, DEFAULT_MAX_ROUNDS);
920        assert!(next.revision > rev);
921    }
922
923    #[test]
924    fn only_one_round_is_outstanding_at_a_time() {
925        let mut slot = active();
926        let first = slot.next_round(0).0.unwrap();
927        assert_eq!(slot.next_round(0), (None, false));
928        assert!(slot.claim_round(&first.turn_id));
929        assert!(!slot.claim_round(&first.turn_id));
930        let second = slot.next_round(0).0.unwrap();
931        assert!(second.message.contains("Round: 2/5"));
932        assert_ne!(first.turn_id, second.turn_id);
933    }
934
935    #[test]
936    fn rounds_count_only_once_claimed() {
937        let mut slot = active();
938        let round = slot.next_round(0).0.unwrap();
939        let goal = slot.goal.as_ref().unwrap();
940        assert_eq!((goal.rounds_started, goal.rounds_since_armed), (0, 0));
941        assert!(slot.claim_round(&round.turn_id));
942        let goal = slot.goal.as_ref().unwrap();
943        assert_eq!((goal.rounds_started, goal.rounds_since_armed), (1, 1));
944    }
945
946    #[test]
947    fn a_round_handed_out_before_a_pause_clear_or_change_cannot_start() {
948        let mut slot = active();
949        let round = slot.next_round(0).0.unwrap();
950        let (id, rev) = ids(&slot);
951        slot.up(&id, rev, GoalAction::Pause, TurnOrigin::Human)
952            .unwrap();
953        assert!(!slot.claim_round(&round.turn_id));
954
955        let mut slot = active();
956        let round = slot.next_round(0).0.unwrap();
957        slot.clear(TurnOrigin::Human).unwrap();
958        assert!(!slot.claim_round(&round.turn_id));
959
960        let mut slot = active();
961        let round = slot.next_round(0).0.unwrap();
962        let (id, rev) = ids(&slot);
963        slot.up(
964            &id,
965            rev,
966            GoalAction::Edit {
967                objective: Some("ship it twice".into()),
968                max_rounds: None,
969                token_budget: None,
970            },
971            TurnOrigin::Human,
972        )
973        .unwrap();
974        assert!(!slot.claim_round(&round.turn_id));
975        let next = slot.next_round(0).0.unwrap();
976        assert!(slot.claim_round(&next.turn_id));
977
978        let mut slot = active();
979        let round = slot.next_round(0).0.unwrap();
980        slot.disarm();
981        assert!(!slot.claim_round(&round.turn_id));
982        assert_eq!(slot.goal.as_ref().unwrap().rounds_started, 0);
983    }
984
985    #[test]
986    fn an_abandoned_round_lets_the_next_one_be_handed_out() {
987        let mut slot = active();
988        let round = slot.next_round(0).0.unwrap();
989        slot.abandon_round("goal-1-1-someone-else");
990        assert_eq!(slot.next_round(0), (None, false));
991        slot.abandon_round(&round.turn_id);
992        assert!(slot.next_round(0).0.is_some());
993    }
994
995    #[test]
996    fn a_goal_created_after_a_clear_never_reuses_a_revision() {
997        let mut slot = active();
998        let stale = round_origin(&slot);
999        slot.clear(TurnOrigin::Human).unwrap();
1000        slot.create(
1001            "another".into(),
1002            GoalLimits::asked(None, None),
1003            TurnOrigin::Human,
1004        )
1005        .unwrap();
1006        let (id, rev) = ids(&slot);
1007        assert!(matches!(
1008            slot.up(&id, rev, GoalAction::Complete, stale),
1009            Err(GoalError::NotAllowed(_))
1010        ));
1011    }
1012}