use std::time::Duration;
pub const DEFAULT_MAX_GOAL_CONTINUATIONS: u32 = 0;
pub const DEFAULT_GOAL_MAX_STEPS: u32 = u32::MAX;
pub const MAX_REPEATED_GAP_PASSES: u32 = 3;
pub const MAX_GOAL_CONTINUATION_DELAY_SECONDS: u64 = 24 * 60 * 60;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum GoalRunStatus {
Active,
Completed,
Blocked,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
Completed,
Blocked,
ContinuationLimit,
BudgetLimit,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct GoalProgress {
pub tokens_used: u64,
pub time_used_seconds: u64,
pub continuations: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GoalBudget {
pub token_budget: Option<u64>,
pub time_budget_seconds: Option<u64>,
pub enforce_token_budget: bool,
pub max_continuations: u32,
}
impl GoalBudget {
pub const fn unbounded() -> Self {
Self {
token_budget: None,
time_budget_seconds: None,
enforce_token_budget: false,
max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
}
}
pub const fn with_token_budget(token_budget: u64) -> Self {
Self {
token_budget: Some(token_budget),
time_budget_seconds: None,
enforce_token_budget: false,
max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
}
}
#[must_use]
pub const fn with_enforced_token_budget(mut self, enforce: bool) -> Self {
self.enforce_token_budget = enforce;
self
}
#[must_use]
pub const fn with_max_continuations(mut self, max_continuations: u32) -> Self {
self.max_continuations = max_continuations;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContinuationDecision {
Continue,
Stop(StopReason),
}
#[must_use]
pub fn decide_continuation(
status: GoalRunStatus,
progress: GoalProgress,
budget: GoalBudget,
) -> ContinuationDecision {
match status {
GoalRunStatus::Completed => return ContinuationDecision::Stop(StopReason::Completed),
GoalRunStatus::Blocked => return ContinuationDecision::Stop(StopReason::Blocked),
GoalRunStatus::Active => {}
}
if budget
.token_budget
.is_some_and(|limit| progress.tokens_used >= limit)
{
if budget.enforce_token_budget {
tracing::info!(
tokens_used = progress.tokens_used,
token_budget = ?budget.token_budget,
"goal token budget reached; stopping ([goal] enforce_token_budget)"
);
return ContinuationDecision::Stop(StopReason::BudgetLimit);
}
tracing::debug!(
tokens_used = progress.tokens_used,
token_budget = ?budget.token_budget,
"goal over token budget but continuing (unbounded)"
);
}
if let Some(secs) = budget.time_budget_seconds
&& progress.time_used_seconds >= secs
{
tracing::debug!(
time_used_seconds = progress.time_used_seconds,
time_budget_seconds = secs,
"goal over time budget but continuing (unbounded)"
);
}
if budget.max_continuations > 0 && progress.continuations >= budget.max_continuations {
tracing::warn!(
continuations = progress.continuations,
max_continuations = budget.max_continuations,
"goal continuation backstop fired: no terminal signal after the configured \
continuation limit ([goal] max_continuations)"
);
return ContinuationDecision::Stop(StopReason::ContinuationLimit);
}
ContinuationDecision::Continue
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ContinuationWaitOutcome {
Elapsed,
Cancelled,
}
#[must_use]
pub const fn continuation_wait(delay_seconds: u64) -> Option<Duration> {
if delay_seconds == 0 {
None
} else {
Some(Duration::from_secs(
if delay_seconds > MAX_GOAL_CONTINUATION_DELAY_SECONDS {
MAX_GOAL_CONTINUATION_DELAY_SECONDS
} else {
delay_seconds
},
))
}
}
pub async fn await_continuation_wait(
wait: Option<Duration>,
cancel_token: &tokio_util::sync::CancellationToken,
) -> ContinuationWaitOutcome {
if cancel_token.is_cancelled() {
return ContinuationWaitOutcome::Cancelled;
}
let Some(wait) = wait else {
return ContinuationWaitOutcome::Elapsed;
};
tokio::select! {
biased;
() = cancel_token.cancelled() => ContinuationWaitOutcome::Cancelled,
() = tokio::time::sleep(wait) => ContinuationWaitOutcome::Elapsed,
}
}
#[must_use]
pub const fn token_budget_exhausted(progress: GoalProgress, budget: GoalBudget) -> bool {
budget.enforce_token_budget
&& match budget.token_budget {
Some(limit) => progress.tokens_used >= limit,
None => false,
}
}
#[must_use]
pub fn is_success(reason: StopReason) -> bool {
matches!(reason, StopReason::Completed)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn completed_status_stops_with_success() {
let d = decide_continuation(
GoalRunStatus::Completed,
GoalProgress::default(),
GoalBudget::unbounded(),
);
assert_eq!(d, ContinuationDecision::Stop(StopReason::Completed));
assert!(is_success(StopReason::Completed));
}
#[test]
fn blocked_status_stops_without_success() {
let d = decide_continuation(
GoalRunStatus::Blocked,
GoalProgress::default(),
GoalBudget::unbounded(),
);
assert_eq!(d, ContinuationDecision::Stop(StopReason::Blocked));
assert!(!is_success(StopReason::Blocked));
}
#[test]
fn active_under_budget_continues() {
let progress = GoalProgress {
tokens_used: 10,
time_used_seconds: 5,
continuations: 2,
};
let budget = GoalBudget {
token_budget: Some(1000),
time_budget_seconds: Some(600),
enforce_token_budget: false,
max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
};
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue
);
}
#[test]
fn default_goal_has_no_continuation_limit() {
let progress = GoalProgress {
continuations: 10_000,
..GoalProgress::default()
};
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, GoalBudget::unbounded()),
ContinuationDecision::Continue
);
}
#[test]
fn explicit_continuation_limit_stops_run() {
let configured_limit = 100;
let progress = GoalProgress {
continuations: configured_limit,
..GoalProgress::default()
};
let budget = GoalBudget::unbounded().with_max_continuations(configured_limit);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Stop(StopReason::ContinuationLimit)
);
}
#[test]
fn operate_goal_continues_past_ten_when_budget_remains() {
for continuations in [10, 11, 100, 10_000] {
let progress = GoalProgress {
tokens_used: 5_000,
time_used_seconds: 300,
continuations,
};
let budget = GoalBudget::with_token_budget(1_000_000);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue,
"pass {continuations} must continue toward the completion gate",
);
}
}
#[test]
fn configured_backstop_halts_pathological_loop() {
let backstop = 25;
let progress = GoalProgress {
continuations: backstop,
..GoalProgress::default()
};
let budget = GoalBudget::unbounded().with_max_continuations(backstop);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Stop(StopReason::ContinuationLimit)
);
}
#[test]
fn zero_backstop_is_unlimited_and_budget_advisory() {
let progress = GoalProgress {
continuations: 10_000,
..GoalProgress::default()
};
let budget = GoalBudget::unbounded().with_max_continuations(0);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue
);
let progress = GoalProgress {
tokens_used: 1_000,
continuations: 10_000,
..GoalProgress::default()
};
let budget = GoalBudget::with_token_budget(1_000).with_max_continuations(0);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue,
"budget advisory — must continue even when over budget"
);
}
#[test]
fn enforced_token_budget_stops_the_run() {
let progress = GoalProgress {
tokens_used: 1000,
continuations: 1,
..GoalProgress::default()
};
let budget = GoalBudget::with_token_budget(1000).with_enforced_token_budget(true);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Stop(StopReason::BudgetLimit),
"enforce_token_budget makes an exhausted token budget terminal"
);
assert!(!is_success(StopReason::BudgetLimit));
}
#[test]
fn enforce_flag_without_a_token_budget_cannot_stop() {
let progress = GoalProgress {
tokens_used: u64::MAX / 2,
continuations: 1,
..GoalProgress::default()
};
let budget = GoalBudget::unbounded().with_enforced_token_budget(true);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue
);
}
#[test]
fn enforced_budget_still_yields_to_a_terminal_status() {
let budget = GoalBudget::with_token_budget(1000).with_enforced_token_budget(true);
assert_eq!(
decide_continuation(GoalRunStatus::Completed, GoalProgress::default(), budget),
ContinuationDecision::Stop(StopReason::Completed),
"a clean completion outranks the budget gate"
);
}
#[test]
fn token_budget_is_advisory_not_terminal() {
let progress = GoalProgress {
tokens_used: 1000,
continuations: 1,
..GoalProgress::default()
};
let budget = GoalBudget::with_token_budget(1000);
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue,
"token budget is advisory — unbounded run must continue"
);
}
#[test]
fn time_budget_is_advisory_not_terminal() {
let progress = GoalProgress {
time_used_seconds: 601,
continuations: 1,
..GoalProgress::default()
};
let budget = GoalBudget {
token_budget: None,
time_budget_seconds: Some(600),
enforce_token_budget: false,
max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
};
assert_eq!(
decide_continuation(GoalRunStatus::Active, progress, budget),
ContinuationDecision::Continue,
"time budget is advisory — unbounded run must continue"
);
}
#[test]
fn terminal_status_outranks_remaining_budget() {
let progress = GoalProgress::default();
let budget = GoalBudget {
token_budget: Some(1_000_000),
time_budget_seconds: Some(86_400),
enforce_token_budget: false,
max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
};
assert_eq!(
decide_continuation(GoalRunStatus::Completed, progress, budget),
ContinuationDecision::Stop(StopReason::Completed)
);
}
#[test]
fn continuation_wait_honors_configured_delay() {
assert_eq!(
continuation_wait(300),
Some(Duration::from_secs(300)),
"a positive configured delay must become the quiet-period wait"
);
assert_eq!(
continuation_wait(MAX_GOAL_CONTINUATION_DELAY_SECONDS + 1),
Some(Duration::from_secs(MAX_GOAL_CONTINUATION_DELAY_SECONDS)),
"the shared cap must bound an oversized configured delay"
);
}
#[test]
fn zero_delay_continues_immediately() {
assert_eq!(
continuation_wait(0),
None,
"an unset or zero delay must dispatch immediately"
);
}
#[tokio::test]
async fn cancellation_wins_over_pending_quiet_period() {
let cancel_token = tokio_util::sync::CancellationToken::new();
let canceller = cancel_token.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(10)).await;
canceller.cancel();
});
assert_eq!(
await_continuation_wait(
continuation_wait(MAX_GOAL_CONTINUATION_DELAY_SECONDS),
&cancel_token,
)
.await,
ContinuationWaitOutcome::Cancelled,
"an explicit cancel during the quiet period must win and never dispatch"
);
}
#[test]
fn exhausted_budget_predicate_matches_the_live_stop() {
let progress = GoalProgress {
tokens_used: 1_000,
..GoalProgress::default()
};
for enforce in [false, true] {
let budget = GoalBudget {
token_budget: Some(1_000),
time_budget_seconds: None,
enforce_token_budget: enforce,
max_continuations: 0,
};
assert_eq!(
token_budget_exhausted(progress, budget),
decide_continuation(GoalRunStatus::Active, progress, budget)
== ContinuationDecision::Stop(StopReason::BudgetLimit),
"preview must report exactly the budget stop the live loop takes (enforce={enforce})"
);
}
}
#[tokio::test]
async fn cancellation_wins_over_a_zero_delay() {
let cancel_token = tokio_util::sync::CancellationToken::new();
cancel_token.cancel();
assert_eq!(
await_continuation_wait(continuation_wait(0), &cancel_token).await,
ContinuationWaitOutcome::Cancelled,
"a cancelled goal with no quiet period must never dispatch"
);
}
#[tokio::test]
async fn elapsed_quiet_period_dispatches() {
let cancel_token = tokio_util::sync::CancellationToken::new();
assert_eq!(
await_continuation_wait(None, &cancel_token).await,
ContinuationWaitOutcome::Elapsed,
"an unset wait must gate the dispatch through immediately"
);
assert_eq!(
await_continuation_wait(Some(Duration::from_millis(1)), &cancel_token).await,
ContinuationWaitOutcome::Elapsed,
"an expired quiet period must dispatch"
);
}
}