返回 CodeWhale
goal_loop.rs
根目录 / crates / runtime / src / goal_loop.rs
1 //! Goal loop orchestrator — the persistent-objective control layer (#3215, and
2 //! its lineage #891 / #1976 / #2058 / #2029).
3 //!
4 //! This is the **Workflow goal layer**: the decision core that turns a one-shot
5 //! `/goal` into a persistent work loop. Given the durable goal status, the
6 //! accumulated usage (from the per-goal accounting wired in `crates/state`
7 //! `record_thread_goal_usage`), and a budget, it decides whether to **continue**
8 //! (re-dispatch another worker turn toward the objective) or **stop** with a
9 //! terminal status. It is the orchestrator in the Workflow≈ultracode mapping —
10 //! the loop that fans work out to workers (`worker_profile`) and verifies before
11 //! committing.
12 //!
13 //! Scope: **decision logic + types**. The engine (`core/engine.rs`) reads the
14 //! `SharedGoalState` snapshot after each turn and calls `decide_continuation`
15 //! to decide whether to re-dispatch. For operate-mode goals the terminal stops
16 //! are a verified completion, a blocked report, the stall pause that fires
17 //! when a critical verifier reports the same gap set
18 //! [`MAX_REPEATED_GAP_PASSES`] times running (enforced in
19 //! `GoalState::record_not_achieved`), and the opt-in continuation backstop
20 //! (`[goal] max_continuations`); token accounting stays visible as telemetry
21 //! and gates continuation only under `[goal] enforce_token_budget` — spend is
22 //! bounded by stalling, not by a pass count, like grokbuild
23 //! (`DEFAULT_AGENT_BUDGET` as call cap) and kimicode swarm (`turnBudget`
24 //! per-task, resumable after budget-reached). Log when the backstop fires.
25
26 use std::time::Duration;
27
28 /// Default automatic cross-turn continuation policy for one goal run (#5052).
29 ///
30 /// Goals are unlimited by default: completion, blocked status, or explicit
31 /// user control ends the run. Operators who want a circuit breaker can opt in
32 /// with `[goal] max_continuations`; `0` keeps the default unlimited behavior.
33 pub const DEFAULT_MAX_GOAL_CONTINUATIONS: u32 = 0;
34
35 /// How many consecutive critical `not_achieved` reviews naming the *same*
36 /// normalized gap set a goal may accumulate before it pauses itself with
37 /// `GoalPauseReason::NoProgress`.
38 ///
39 /// This is the bound the continuation prompt promises the model, and it is the
40 /// only default stop on a goal run: `DEFAULT_MAX_GOAL_CONTINUATIONS` is `0`, so
41 /// without it the loop runs until the model volunteers a terminal status.
42 /// Enforcement lives in `GoalState::record_not_achieved`, and it reuses the
43 /// existing pause authority rather than adding a second one — both continuation
44 /// dispatchers already refuse to re-dispatch a non-active goal, and
45 /// `RuntimeThreadManager` already mirrors a non-limit pause into the durable
46 /// `ThreadGoalStatus::Paused`, so the stop survives a restart and needs an
47 /// explicit resume.
48 ///
49 /// The counter is `1` on the first report of a gap set, so `3` means the
50 /// verifier named identical remaining work three times running: two whole
51 /// continuation passes that moved nothing the verifier can see. Two is too
52 /// eager — one pass legitimately fails to land a fix and retries — and anything
53 /// larger just buys more identical passes.
54 pub const MAX_REPEATED_GAP_PASSES: u32 = 3;
55
56 /// Upper bound for one between-turn quiet period. A day is long enough for
57 /// coordinator cadences while preventing an accidental giant integer from
58 /// becoming a practically uninterruptible-looking schedule receipt.
59 pub const MAX_GOAL_CONTINUATION_DELAY_SECONDS: u64 = 24 * 60 * 60;
60
61 /// Terminal or active state of a persistent goal.
62 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
63 pub enum GoalRunStatus {
64 /// Still working toward the objective.
65 Active,
66 /// The objective was achieved (the model self-reported done and, ideally, a
67 /// verifier confirmed — see `GoalGate`).
68 Completed,
69 /// The model reported it is blocked and needs the user.
70 Blocked,
71 }
72
73 /// Why the loop stopped, for a terminal decision.
74 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75 pub enum StopReason {
76 /// Objective achieved.
77 Completed,
78 /// Model reported blocked.
79 Blocked,
80 /// Continuation circuit-breaker tripped (too many continuations without a
81 /// terminal signal).
82 ContinuationLimit,
83 /// The goal's token budget was reached while `[goal] enforce_token_budget`
84 /// opted the budget into a hard stop (#6013). Default-off: without the
85 /// opt-in the budget stays advisory telemetry and never produces this.
86 BudgetLimit,
87 }
88
89 /// Accumulated, durable progress for a goal run: the `tokens_used` wired by
90 /// `crates/state` `record_thread_goal_usage` plus a continuation counter the
91 /// loop maintains.
92 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
93 pub struct GoalProgress {
94 pub tokens_used: u64,
95 pub continuations: u32,
96 }
97
98 /// The optional token bound on a goal run. `None` means unbounded; the
99 /// continuation backstop (`max_continuations`) still applies unless
100 /// configured to `0`.
101 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
102 pub struct GoalBudget {
103 pub token_budget: Option<u64>,
104 /// Whether `token_budget` stops the run when reached (#6013). `false`
105 /// keeps the default advisory behavior: crossing the budget logs and
106 /// continues.
107 pub enforce_token_budget: bool,
108 /// Safety backstop on automatic continuation passes (#5052). `0` disables
109 /// the backstop: only terminal status stops the run.
110 pub max_continuations: u32,
111 }
112
113 /// The decision the loop makes after each worker turn.
114 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
115 pub enum ContinuationDecision {
116 /// Re-dispatch another turn toward the objective.
117 Continue,
118 /// Stop; the goal run is terminal.
119 Stop(StopReason),
120 }
121
122 /// Decide whether a persistent goal run should continue after a turn.
123 ///
124 /// Precedence (most authoritative first):
125 /// 1. A terminal model status (Completed / Blocked) ends the run.
126 /// 2. The configurable continuation backstop stops a pathological loop
127 /// (skipped entirely when configured to `0`).
128 /// 3. Otherwise continue — the loop runs to the completion gate, not to a
129 /// fixed pass count (#5052). A token budget without `enforce_token_budget`
130 /// is advisory telemetry; it is surfaced in the UI but does not stop the
131 /// run.
132 #[must_use]
133 pub fn decide_continuation(
134 status: GoalRunStatus,
135 progress: GoalProgress,
136 budget: GoalBudget,
137 ) -> ContinuationDecision {
138 // 1. Terminal model signal wins.
139 match status {
140 GoalRunStatus::Completed => return ContinuationDecision::Stop(StopReason::Completed),
141 GoalRunStatus::Blocked => return ContinuationDecision::Stop(StopReason::Blocked),
142 GoalRunStatus::Active => {}
143 }
144
145 // 2. Token budget: advisory telemetry by default, or a hard stop when
146 // `[goal] enforce_token_budget` opts in (#6013).
147 if budget
148 .token_budget
149 .is_some_and(|limit| progress.tokens_used >= limit)
150 {
151 if budget.enforce_token_budget {
152 tracing::info!(
153 tokens_used = progress.tokens_used,
154 token_budget = ?budget.token_budget,
155 "goal token budget reached; stopping ([goal] enforce_token_budget)"
156 );
157 return ContinuationDecision::Stop(StopReason::BudgetLimit);
158 }
159 tracing::debug!(
160 tokens_used = progress.tokens_used,
161 token_budget = ?budget.token_budget,
162 "goal over token budget but continuing (unbounded)"
163 );
164 }
165
166 // 3. Runaway-cost backstop. This deliberately uses the already-durable
167 // continuation counter instead of adding verifier fingerprints or another
168 // orchestration subsystem. `0` disables it — budget/terminal stops only.
169 if budget.max_continuations > 0 && progress.continuations >= budget.max_continuations {
170 tracing::warn!(
171 continuations = progress.continuations,
172 max_continuations = budget.max_continuations,
173 "goal continuation backstop fired: no terminal signal after the configured \
174 continuation limit ([goal] max_continuations)"
175 );
176 return ContinuationDecision::Stop(StopReason::ContinuationLimit);
177 }
178
179 // 4. Keep going.
180 ContinuationDecision::Continue
181 }
182
183 /// Outcome of waiting out the between-continuation quiet period.
184 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
185 pub enum ContinuationWaitOutcome {
186 /// The quiet period elapsed — dispatch the continuation.
187 Elapsed,
188 /// Cancelled during the quiet period — never dispatch.
189 Cancelled,
190 }
191
192 /// Compute the quiet-period wait for a configured between-continuation delay.
193 /// `None` continues immediately (unset or zero delay); a positive delay
194 /// returns the capped wait shared by every dispatch path so no caller can
195 /// construct an effectively uninterruptible schedule receipt.
196 #[must_use]
197 pub const fn continuation_wait(delay_seconds: u64) -> Option<Duration> {
198 if delay_seconds == 0 {
199 None
200 } else {
201 Some(Duration::from_secs(
202 if delay_seconds > MAX_GOAL_CONTINUATION_DELAY_SECONDS {
203 MAX_GOAL_CONTINUATION_DELAY_SECONDS
204 } else {
205 delay_seconds
206 },
207 ))
208 }
209 }
210
211 /// Wait out the between-continuation quiet period, honoring cancellation.
212 /// `None` resolves immediately so callers have a single dispatch gate: to
213 /// `Cancelled` when the token is already cancelled, otherwise `Elapsed`.
214 /// Cancellation is biased and always wins over a racing expiry — the same
215 /// semantics as the interactive cadence (#5508), including a zero delay. Two dispatchers await
216 /// this gate: the turn loop's intra-turn passes (every session), and the
217 /// runtime host's cross-turn re-arm for host-managed engines
218 /// (`RuntimeThreadManager::spawn_goal_continuation`), which never
219 /// self-continue.
220 pub async fn await_continuation_wait(
221 wait: Option<Duration>,
222 cancel_token: &tokio_util::sync::CancellationToken,
223 ) -> ContinuationWaitOutcome {
224 if cancel_token.is_cancelled() {
225 return ContinuationWaitOutcome::Cancelled;
226 }
227 let Some(wait) = wait else {
228 return ContinuationWaitOutcome::Elapsed;
229 };
230 tokio::select! {
231 biased;
232 () = cancel_token.cancelled() => ContinuationWaitOutcome::Cancelled,
233 () = tokio::time::sleep(wait) => ContinuationWaitOutcome::Elapsed,
234 }
235 }
236
237 /// Whether the durable token usage has reached an *enforced* token budget —
238 /// the same condition on which [`decide_continuation`] stops with
239 /// [`StopReason::BudgetLimit`]. Budgets are telemetry-only unless
240 /// `[goal] enforce_token_budget` opts in, so without it this stays false and
241 /// crossing a budget never closes the outbound gate. Preview and the live
242 /// continuation loop share this predicate so they cannot disagree about spend.
243 #[must_use]
244 pub const fn token_budget_exhausted(progress: GoalProgress, budget: GoalBudget) -> bool {
245 budget.enforce_token_budget
246 && match budget.token_budget {
247 Some(limit) => progress.tokens_used >= limit,
248 None => false,
249 }
250 }
251
252 #[cfg(test)]
253 mod tests {
254 use super::*;
255
256 const UNBOUNDED: GoalBudget = GoalBudget {
257 token_budget: None,
258 enforce_token_budget: false,
259 max_continuations: DEFAULT_MAX_GOAL_CONTINUATIONS,
260 };
261
262 #[test]
263 fn completed_status_stops_with_success() {
264 let d = decide_continuation(GoalRunStatus::Completed, GoalProgress::default(), UNBOUNDED);
265 assert_eq!(d, ContinuationDecision::Stop(StopReason::Completed));
266 }
267
268 #[test]
269 fn blocked_status_stops_without_success() {
270 let d = decide_continuation(GoalRunStatus::Blocked, GoalProgress::default(), UNBOUNDED);
271 assert_eq!(d, ContinuationDecision::Stop(StopReason::Blocked));
272 }
273
274 #[test]
275 fn active_under_budget_continues() {
276 let progress = GoalProgress {
277 tokens_used: 10,
278 continuations: 2,
279 };
280 let budget = GoalBudget {
281 token_budget: Some(1000),
282 ..UNBOUNDED
283 };
284 assert_eq!(
285 decide_continuation(GoalRunStatus::Active, progress, budget),
286 ContinuationDecision::Continue
287 );
288 }
289
290 #[test]
291 fn default_goal_has_no_continuation_limit() {
292 let progress = GoalProgress {
293 continuations: 10_000,
294 ..GoalProgress::default()
295 };
296 assert_eq!(
297 decide_continuation(GoalRunStatus::Active, progress, UNBOUNDED),
298 ContinuationDecision::Continue
299 );
300 }
301
302 #[test]
303 fn explicit_continuation_limit_stops_run() {
304 let configured_limit = 100;
305 let progress = GoalProgress {
306 continuations: configured_limit,
307 ..GoalProgress::default()
308 };
309 let budget = GoalBudget {
310 max_continuations: configured_limit,
311 ..UNBOUNDED
312 };
313 assert_eq!(
314 decide_continuation(GoalRunStatus::Active, progress, budget),
315 ContinuationDecision::Stop(StopReason::ContinuationLimit)
316 );
317 }
318
319 #[test]
320 fn operate_goal_continues_past_ten_when_budget_remains() {
321 // #5052 regression: the old hardcoded cap of 10 must not be a terminal
322 // stop. With no terminal signal, pass 10, 11, and far beyond keep
323 // continuing because the default has no hidden ceiling.
324 for continuations in [10, 11, 100, 10_000] {
325 let progress = GoalProgress {
326 tokens_used: 5_000,
327 continuations,
328 };
329 let budget = GoalBudget {
330 token_budget: Some(1_000_000),
331 ..UNBOUNDED
332 };
333 assert_eq!(
334 decide_continuation(GoalRunStatus::Active, progress, budget),
335 ContinuationDecision::Continue,
336 "pass {continuations} must continue toward the completion gate",
337 );
338 }
339 }
340
341 #[test]
342 fn configured_backstop_halts_pathological_loop() {
343 let backstop = 25;
344 let progress = GoalProgress {
345 continuations: backstop,
346 ..GoalProgress::default()
347 };
348 let budget = GoalBudget {
349 max_continuations: backstop,
350 ..UNBOUNDED
351 };
352 assert_eq!(
353 decide_continuation(GoalRunStatus::Active, progress, budget),
354 ContinuationDecision::Stop(StopReason::ContinuationLimit)
355 );
356 }
357
358 #[test]
359 fn zero_backstop_is_unlimited_and_budget_advisory() {
360 // 0 = unlimited-with-budget-stops: no continuation count ends the run…
361 let progress = GoalProgress {
362 continuations: 10_000,
363 ..GoalProgress::default()
364 };
365 let budget = GoalBudget {
366 max_continuations: 0,
367 ..UNBOUNDED
368 };
369 assert_eq!(
370 decide_continuation(GoalRunStatus::Active, progress, budget),
371 ContinuationDecision::Continue
372 );
373
374 // exceeded token budget is advisory — must still continue (unbounded)
375 let progress = GoalProgress {
376 tokens_used: 1_000,
377 continuations: 10_000,
378 };
379 let budget = GoalBudget {
380 token_budget: Some(1_000),
381 max_continuations: 0,
382 ..UNBOUNDED
383 };
384 assert_eq!(
385 decide_continuation(GoalRunStatus::Active, progress, budget),
386 ContinuationDecision::Continue,
387 "budget advisory — must continue even when over budget"
388 );
389 }
390
391 #[test]
392 fn enforced_token_budget_stops_the_run() {
393 let progress = GoalProgress {
394 tokens_used: 1000,
395 continuations: 1,
396 };
397 let budget = GoalBudget {
398 token_budget: Some(1000),
399 enforce_token_budget: true,
400 ..UNBOUNDED
401 };
402 assert_eq!(
403 decide_continuation(GoalRunStatus::Active, progress, budget),
404 ContinuationDecision::Stop(StopReason::BudgetLimit),
405 "enforce_token_budget makes an exhausted token budget terminal"
406 );
407 }
408
409 #[test]
410 fn enforce_flag_without_a_token_budget_cannot_stop() {
411 // A goal created without `token_budget` has no ceiling to reach — the
412 // flag must not invent one.
413 let progress = GoalProgress {
414 tokens_used: u64::MAX / 2,
415 continuations: 1,
416 };
417 let budget = GoalBudget {
418 enforce_token_budget: true,
419 ..UNBOUNDED
420 };
421 assert_eq!(
422 decide_continuation(GoalRunStatus::Active, progress, budget),
423 ContinuationDecision::Continue
424 );
425 }
426
427 #[test]
428 fn enforced_budget_still_yields_to_a_terminal_status() {
429 let budget = GoalBudget {
430 token_budget: Some(1000),
431 enforce_token_budget: true,
432 ..UNBOUNDED
433 };
434 assert_eq!(
435 decide_continuation(GoalRunStatus::Completed, GoalProgress::default(), budget),
436 ContinuationDecision::Stop(StopReason::Completed),
437 "a clean completion outranks the budget gate"
438 );
439 }
440
441 #[test]
442 fn token_budget_is_advisory_not_terminal() {
443 let progress = GoalProgress {
444 tokens_used: 1000,
445 continuations: 1,
446 };
447 let budget = GoalBudget {
448 token_budget: Some(1000),
449 ..UNBOUNDED
450 };
451 assert_eq!(
452 decide_continuation(GoalRunStatus::Active, progress, budget),
453 ContinuationDecision::Continue,
454 "token budget is advisory — unbounded run must continue"
455 );
456 }
457
458 #[test]
459 fn terminal_status_outranks_remaining_budget() {
460 // Completed wins even if there is plenty of budget left.
461 let progress = GoalProgress::default();
462 let budget = GoalBudget {
463 token_budget: Some(1_000_000),
464 ..UNBOUNDED
465 };
466 assert_eq!(
467 decide_continuation(GoalRunStatus::Completed, progress, budget),
468 ContinuationDecision::Stop(StopReason::Completed)
469 );
470 }
471
472 #[test]
473 fn continuation_wait_honors_configured_delay() {
474 assert_eq!(
475 continuation_wait(300),
476 Some(Duration::from_secs(300)),
477 "a positive configured delay must become the quiet-period wait"
478 );
479 assert_eq!(
480 continuation_wait(MAX_GOAL_CONTINUATION_DELAY_SECONDS + 1),
481 Some(Duration::from_secs(MAX_GOAL_CONTINUATION_DELAY_SECONDS)),
482 "the shared cap must bound an oversized configured delay"
483 );
484 }
485
486 #[test]
487 fn zero_delay_continues_immediately() {
488 assert_eq!(
489 continuation_wait(0),
490 None,
491 "an unset or zero delay must dispatch immediately"
492 );
493 }
494
495 #[tokio::test]
496 async fn cancellation_wins_over_pending_quiet_period() {
497 let cancel_token = tokio_util::sync::CancellationToken::new();
498 let canceller = cancel_token.clone();
499 tokio::spawn(async move {
500 tokio::time::sleep(Duration::from_millis(10)).await;
501 canceller.cancel();
502 });
503 assert_eq!(
504 await_continuation_wait(
505 continuation_wait(MAX_GOAL_CONTINUATION_DELAY_SECONDS),
506 &cancel_token,
507 )
508 .await,
509 ContinuationWaitOutcome::Cancelled,
510 "an explicit cancel during the quiet period must win and never dispatch"
511 );
512 }
513
514 #[test]
515 fn exhausted_budget_predicate_matches_the_live_stop() {
516 let progress = GoalProgress {
517 tokens_used: 1_000,
518 ..GoalProgress::default()
519 };
520 for enforce in [false, true] {
521 let budget = GoalBudget {
522 token_budget: Some(1_000),
523 enforce_token_budget: enforce,
524 max_continuations: 0,
525 };
526 assert_eq!(
527 token_budget_exhausted(progress, budget),
528 decide_continuation(GoalRunStatus::Active, progress, budget)
529 == ContinuationDecision::Stop(StopReason::BudgetLimit),
530 "preview must report exactly the budget stop the live loop takes (enforce={enforce})"
531 );
532 }
533 }
534
535 #[tokio::test]
536 async fn cancellation_wins_over_a_zero_delay() {
537 let cancel_token = tokio_util::sync::CancellationToken::new();
538 cancel_token.cancel();
539 assert_eq!(
540 await_continuation_wait(continuation_wait(0), &cancel_token).await,
541 ContinuationWaitOutcome::Cancelled,
542 "a cancelled goal with no quiet period must never dispatch"
543 );
544 }
545
546 #[tokio::test]
547 async fn elapsed_quiet_period_dispatches() {
548 let cancel_token = tokio_util::sync::CancellationToken::new();
549 assert_eq!(
550 await_continuation_wait(None, &cancel_token).await,
551 ContinuationWaitOutcome::Elapsed,
552 "an unset wait must gate the dispatch through immediately"
553 );
554 assert_eq!(
555 await_continuation_wait(Some(Duration::from_millis(1)), &cancel_token).await,
556 ContinuationWaitOutcome::Elapsed,
557 "an expired quiet period must dispatch"
558 );
559 }
560 }
561
561 lines RUST