Skip to main content

adk_harness/
goal.rs

1//! The goal engine (spec 3.1 §7.11): loop-until goals, durable and ambient.
2//!
3//! A goal iterates the harness agent until the operator's `until` command exits 0 or the
4//! iteration cap is reached. Its state lives in a harness-owned [`GoalStore`], mirrored to
5//! `harness:goal` in session state for display (spec 3.1 §6 D-3, §9.2 I1).
6//!
7//! | Engine | Shape |
8//! |---|---|
9//! | `GoalEngine::Loop` | `LoopAgent` over the harness agent and an [`UntilCheckAgent`]; a held call resumes at the right sub-agent through `workflow_positions` |
10//! | `GoalEngine::Graph` (`graph`) | a checkpointed `StateGraph`: `iterate` → `check` → (`__end__` \| `iterate`) |
11//!
12//! While a session's goal runs and the session is in Ask or Auto, every turn of the harness
13//! runs the goal engine, so the same `Runner` serves `Harness::start_goal`, a resumed goal
14//! and a `DurableWorker` claiming target [`GOAL_TARGET`].
15
16use std::collections::{HashMap, VecDeque};
17use std::sync::{Arc, Mutex, RwLock as StdRwLock};
18use std::time::{Duration, Instant};
19
20use adk_core::audit_log::{AuditActor, AuditRecordDraft, AuditRecordKind};
21use adk_core::{
22    AdkError, Agent, Content, ErrorCategory, ErrorComponent, Event, EventStream, InvocationContext,
23    Llm, Result, Tool,
24};
25use adk_devtools::{BashTool, CommandLauncher, Workspace};
26use async_trait::async_trait;
27use chrono::{DateTime, Utc};
28use serde::{Deserialize, Serialize};
29use serde_json::{Value, json};
30use tokio::sync::RwLock;
31use tracing::Instrument;
32
33use crate::audit::{HARNESS_AUDIT_KIND, HarnessAudit};
34use crate::mode::HarnessMode;
35use crate::run_context::InvocationToolContext;
36
37/// Session-state key of the goal's display mirror (spec 3.1 §7.11).
38///
39/// # Example
40///
41/// ```rust
42/// assert_eq!(adk_harness::GOAL_STATE_KEY, "harness:goal");
43/// ```
44pub const GOAL_STATE_KEY: &str = "harness:goal";
45
46/// The durable-run target of goals, for `DurableWorker::with_agent` (spec 3.1 §7.11).
47///
48/// # Example
49///
50/// ```rust
51/// assert_eq!(adk_harness::GOAL_TARGET, "harness.goal");
52/// ```
53pub const GOAL_TARGET: &str = "harness.goal";
54
55/// A queue dedicated to durable goal runs, for [`Harness::with_goal_queue`](crate::Harness::with_goal_queue)
56/// and the `DurableWorker` that serves them (spec 3.1 §7.11).
57///
58/// # Example
59///
60/// ```rust
61/// assert_eq!(adk_harness::GOAL_QUEUE, "harness.goal");
62/// ```
63pub const GOAL_QUEUE: &str = "harness.goal";
64
65/// Name of the agent that runs a goal's `until` check.
66///
67/// # Example
68///
69/// ```rust
70/// assert_eq!(adk_harness::UNTIL_CHECK_AGENT, "until_check");
71/// ```
72pub const UNTIL_CHECK_AGENT: &str = "until_check";
73
74/// The `LoopAgent`'s own ceiling; the goal's `max_iterations` stops it first.
75const GOAL_LOOP_CEILING: u32 = 10_000;
76
77/// Most bytes of the check's output the next iteration reads.
78const CHECK_OUTPUT_TAIL: usize = 4 * 1024;
79
80/// How many iterations in a row a kernel-hosted goal may end with the same check result
81/// before it counts as stalled (spec 3.2 §7.3, §10 HK3); a `Graph` goal thread keeps the
82/// newest `2 * GOAL_STALL_WINDOW` checkpoints.
83///
84/// # Example
85///
86/// ```rust
87/// assert_eq!(adk_harness::GOAL_STALL_WINDOW, 3);
88/// ```
89pub const GOAL_STALL_WINDOW: u32 = 3;
90
91/// The `harness.goal.stalled` reason of a check that repeated the last
92/// [`GOAL_STALL_WINDOW`] results.
93pub(crate) const STALL_SAME_CHECK: &str = "same_check";
94/// The `harness.goal.stalled` reason of an iteration that made no tool call.
95pub(crate) const STALL_NO_TOOL_CALL: &str = "no_tool_call";
96
97/// Parks a stalled goal's run at its next model-call boundary: the kernel glue's handle on
98/// the kernel's processes (spec 3.2 §10 HK3).
99#[async_trait]
100pub(crate) trait GoalParker: Send + Sync {
101    /// Suspends the durable run `run_id`; `false` when the kernel is gone.
102    async fn park(&self, run_id: &str) -> Result<bool>;
103}
104
105/// What the harness knows about one start of a goal beyond its [`GoalState`]: when it
106/// started, the tail of its last check's output and its recent check results.
107#[derive(Clone, Debug)]
108pub(crate) struct GoalTrack {
109    // Read by the kernel glue's goal progress (feature `kernel`).
110    #[cfg_attr(not(feature = "kernel"), allow(dead_code))]
111    pub(crate) started_at: DateTime<Utc>,
112    pub(crate) last_tail: Option<String>,
113    digests: VecDeque<String>,
114}
115
116/// The goals this harness runs, by [`GoalRecord::run_id`], and the parker a kernel attached
117/// (spec 3.2 §7.3, §10 HK3). Stalls are watched only while a parker is attached, so a goal
118/// outside a kernel runs exactly as before.
119#[derive(Default)]
120pub(crate) struct GoalBook {
121    goals: Mutex<HashMap<String, GoalTrack>>,
122    parker: StdRwLock<Option<Arc<dyn GoalParker>>>,
123}
124
125impl std::fmt::Debug for GoalBook {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        f.debug_struct("GoalBook").finish_non_exhaustive()
128    }
129}
130
131impl GoalBook {
132    /// Notes that goal `run_id` is running, from now if it was not known.
133    pub(crate) fn started(&self, run_id: &str) {
134        let mut goals = self.goals.lock().unwrap_or_else(|e| e.into_inner());
135        if goals.len() > 4096 {
136            goals.clear();
137        }
138        goals.entry(run_id.to_string()).or_insert_with(|| GoalTrack {
139            started_at: Utc::now(),
140            last_tail: None,
141            digests: VecDeque::new(),
142        });
143    }
144
145    /// What is known about goal `run_id`.
146    #[cfg(feature = "kernel")]
147    pub(crate) fn track(&self, run_id: &str) -> Option<GoalTrack> {
148        self.goals.lock().unwrap_or_else(|e| e.into_inner()).get(run_id).cloned()
149    }
150
151    /// Attaches the kernel's parker, which also turns stall detection on.
152    #[cfg(feature = "kernel")]
153    pub(crate) fn set_parker(&self, parker: Arc<dyn GoalParker>) {
154        *self.parker.write().unwrap_or_else(|e| e.into_inner()) = Some(parker);
155    }
156
157    fn parker(&self) -> Option<Arc<dyn GoalParker>> {
158        self.parker.read().unwrap_or_else(|e| e.into_inner()).clone()
159    }
160
161    /// Records a check of goal `run_id` and returns the stall reason when, with a parker
162    /// attached and the goal still running, the iteration made no tool call or the last
163    /// [`GOAL_STALL_WINDOW`] checks gave the same result. A stall restarts the window.
164    fn record_check(
165        &self,
166        run_id: &str,
167        exit_code: Option<i32>,
168        output: &str,
169        tool_calls: Option<usize>,
170        running: bool,
171    ) -> Option<&'static str> {
172        let watching = self.parker().is_some();
173        let mut goals = self.goals.lock().unwrap_or_else(|e| e.into_inner());
174        let track = goals.entry(run_id.to_string()).or_insert_with(|| GoalTrack {
175            started_at: Utc::now(),
176            last_tail: None,
177            digests: VecDeque::new(),
178        });
179        track.last_tail = Some(tail(output, CHECK_OUTPUT_TAIL).to_string());
180        track.digests.push_back(crate::fsutil::sha256_hex(&format!("{exit_code:?}\n{output}")));
181        while track.digests.len() > GOAL_STALL_WINDOW as usize {
182            track.digests.pop_front();
183        }
184        if !(watching && running) {
185            return None;
186        }
187        let same = track.digests.len() == GOAL_STALL_WINDOW as usize
188            && track.digests.iter().all(|digest| *digest == track.digests[0]);
189        let reason = if tool_calls == Some(0) {
190            Some(STALL_NO_TOOL_CALL)
191        } else if same {
192            Some(STALL_SAME_CHECK)
193        } else {
194            None
195        };
196        if reason.is_some() {
197            track.digests.clear();
198        }
199        reason
200    }
201}
202
203/// The iterations a goal takes unless configured otherwise, as `adk-rust goal` defaults
204/// `--max-iters`.
205///
206/// # Example
207///
208/// ```rust
209/// assert_eq!(adk_harness::DEFAULT_GOAL_ITERATIONS, 8);
210/// ```
211pub const DEFAULT_GOAL_ITERATIONS: u32 = 8;
212
213/// How long one run of a goal's `until` command may take unless configured otherwise.
214///
215/// # Example
216///
217/// ```rust
218/// assert_eq!(adk_harness::DEFAULT_CHECK_TIMEOUT.as_secs(), 600);
219/// ```
220pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(600);
221
222/// The most bytes of one deliverable file the grader reads; the rest is cut.
223const DELIVERABLE_MAX_BYTES: usize = 64 * 1024;
224
225/// The most bytes of the iteration's final message the grader reads.
226const FINAL_MESSAGE_MAX_BYTES: usize = 16 * 1024;
227
228/// A loop-until goal (spec 3.1 §7.11): the harness iterates until the goal's checks pass —
229/// the `until` command exits 0, the rubric's grader passes every criterion, or both when
230/// both are set — or `max_iterations` is reached.
231///
232/// # Example
233///
234/// ```rust
235/// use adk_harness::{GoalRubric, GoalSpec};
236///
237/// let tests = GoalSpec::new("make the tests pass").with_until("cargo test").with_max_iterations(10);
238/// assert_eq!(tests.max_iterations, 10);
239///
240/// let blurb = GoalSpec::new("write the launch blurb to blurb.md").with_rubric(
241///     GoalRubric::new(["names the product", "states the price"]).with_deliverables(["blurb.md"]),
242/// );
243/// assert!(blurb.until.is_none());
244/// ```
245#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(rename_all = "camelCase")]
247#[non_exhaustive]
248pub struct GoalSpec {
249    /// What to achieve.
250    pub goal: String,
251    /// The operator's check command; exit 0 passes it.
252    #[serde(default, skip_serializing_if = "Option::is_none")]
253    pub until: Option<String>,
254    /// The rubric a grader checks each iteration's deliverable against.
255    #[serde(default, skip_serializing_if = "Option::is_none")]
256    pub rubric: Option<GoalRubric>,
257    /// Most iterations.
258    pub max_iterations: u32,
259    /// Timeout of one run of `until`.
260    pub check_timeout: Duration,
261}
262
263impl GoalSpec {
264    /// A goal with no check yet, [`DEFAULT_GOAL_ITERATIONS`] iterations and a
265    /// [`DEFAULT_CHECK_TIMEOUT`]; give it [`with_until`](Self::with_until),
266    /// [`with_rubric`](Self::with_rubric) or both.
267    pub fn new(goal: impl Into<String>) -> Self {
268        Self {
269            goal: goal.into(),
270            until: None,
271            rubric: None,
272            max_iterations: DEFAULT_GOAL_ITERATIONS,
273            check_timeout: DEFAULT_CHECK_TIMEOUT,
274        }
275    }
276
277    /// The check command: the goal needs it to exit 0.
278    #[must_use]
279    pub fn with_until(mut self, command: impl Into<String>) -> Self {
280        self.until = Some(command.into());
281        self
282    }
283
284    /// The rubric: the goal needs a grader to pass every criterion.
285    #[must_use]
286    pub fn with_rubric(mut self, rubric: GoalRubric) -> Self {
287        self.rubric = Some(rubric);
288        self
289    }
290
291    /// The most iterations.
292    #[must_use]
293    pub fn with_max_iterations(mut self, max: u32) -> Self {
294        self.max_iterations = max;
295        self
296    }
297
298    /// How long one run of `until` may take.
299    #[must_use]
300    pub fn with_check_timeout(mut self, timeout: Duration) -> Self {
301        self.check_timeout = timeout;
302        self
303    }
304
305    /// The goal's digest: SHA-256 of its canonical JSON, as the durable run's idempotency
306    /// key uses it (`goal:<session>:<digest>`).
307    ///
308    /// # Example
309    ///
310    /// ```rust
311    /// let goal = adk_harness::GoalSpec::new("g").with_until("true");
312    /// assert_eq!(goal.digest().len(), 64);
313    /// ```
314    pub fn digest(&self) -> String {
315        crate::fsutil::sha256_hex(&serde_json::to_string(self).unwrap_or_default())
316    }
317
318    /// The message that starts the goal's run.
319    pub fn prompt(&self) -> String {
320        let mut checks = Vec::new();
321        if let Some(until) = &self.until {
322            checks.push(format!("the harness runs `{until}`, which must exit 0"));
323        }
324        if let Some(rubric) = &self.rubric {
325            checks.push(rubric.prompt_line());
326        }
327        let mut prompt = format!(
328            "Goal: {goal}\n\nWork toward the goal. After each of your turns {checks}; the goal \
329             is reached when {all}, and you get at most {max} iterations. Read the feedback \
330             from the previous iteration before you continue.",
331            goal = self.goal,
332            checks = checks.join(", then "),
333            all = if checks.len() > 1 { "both pass" } else { "it passes" },
334            max = self.max_iterations,
335        );
336        if let Some(rubric) = self.rubric.as_ref().filter(|rubric| !rubric.hidden) {
337            prompt.push_str("\n\nThe grader's criteria:");
338            for (index, criterion) in rubric.criteria.iter().enumerate() {
339                prompt.push_str(&format!("\n{}. {criterion}", index + 1));
340            }
341        }
342        prompt
343    }
344
345    #[cfg(feature = "runner")]
346    fn validate(&self) -> Result<()> {
347        let invalid = |message: &str| {
348            AdkError::new(
349                ErrorComponent::Agent,
350                ErrorCategory::InvalidInput,
351                "harness.goal.invalid",
352                message.to_string(),
353            )
354        };
355        if self.goal.trim().is_empty() {
356            return Err(invalid("a goal needs a goal"));
357        }
358        if self.until.is_none() && self.rubric.is_none() {
359            return Err(invalid("a goal needs an until command, a rubric, or both"));
360        }
361        if self.until.as_deref().is_some_and(|until| until.trim().is_empty()) {
362            return Err(invalid("a goal's until command is empty"));
363        }
364        if let Some(rubric) = &self.rubric {
365            rubric.validate().map_err(|message| invalid(&message))?;
366        }
367        if self.max_iterations == 0 {
368            return Err(invalid("a goal needs at least one iteration"));
369        }
370        if self.check_timeout.is_zero() {
371            return Err(invalid("a goal's check needs a timeout"));
372        }
373        Ok(())
374    }
375}
376
377/// The rubric of a goal: independently gradeable criteria that a grader checks each
378/// iteration's deliverable against, in a context of its own.
379///
380/// The grader reads the goal, the criteria, the iteration's final message and the
381/// `deliverables` files of the workspace — never the conversation that produced them. It
382/// grades only once the goal's `until` command (if any) has passed, and at most
383/// `max_evaluations` times ([`adk_eval::DEFAULT_OUTCOME_ITERATIONS`] by default, at most
384/// [`adk_eval::MAX_OUTCOME_ITERATIONS`]); a goal that reaches the cap unsatisfied is
385/// `Exhausted`. A `hidden` rubric is shown only to the grader: the agent learns the failed
386/// criteria from the grader's feedback.
387///
388/// # Example
389///
390/// ```rust
391/// use adk_harness::GoalRubric;
392///
393/// let rubric = GoalRubric::from_markdown("- names the product\n- states the price")?
394///     .with_deliverables(["blurb.md"])
395///     .with_max_evaluations(5);
396/// assert_eq!(rubric.criteria, ["names the product", "states the price"]);
397/// # Ok::<(), adk_core::AdkError>(())
398/// ```
399#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401#[non_exhaustive]
402pub struct GoalRubric {
403    /// The criteria, each graded pass or fail on its own.
404    pub criteria: Vec<String>,
405    /// Workspace-relative files the grader reads besides the final message.
406    #[serde(default, skip_serializing_if = "Vec::is_empty")]
407    pub deliverables: Vec<String>,
408    /// The most grading rounds before the goal counts as exhausted.
409    pub max_evaluations: u32,
410    /// Shows the criteria to the grader only.
411    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
412    pub hidden: bool,
413}
414
415impl GoalRubric {
416    /// A rubric of `criteria`, graded at most [`adk_eval::DEFAULT_OUTCOME_ITERATIONS`]
417    /// times. Blank criteria are dropped.
418    pub fn new<I, S>(criteria: I) -> Self
419    where
420        I: IntoIterator<Item = S>,
421        S: Into<String>,
422    {
423        Self {
424            criteria: criteria
425                .into_iter()
426                .map(|criterion| criterion.into().trim().to_string())
427                .filter(|criterion| !criterion.is_empty())
428                .collect(),
429            deliverables: Vec::new(),
430            max_evaluations: adk_eval::DEFAULT_OUTCOME_ITERATIONS,
431            hidden: false,
432        }
433    }
434
435    /// Reads the criteria from Markdown, one per list item
436    /// ([`adk_eval::RubricConfig::from_markdown`]).
437    ///
438    /// # Errors
439    ///
440    /// Returns `harness.goal.invalid` when `text` holds no criterion.
441    pub fn from_markdown(text: &str) -> Result<Self> {
442        let rubric = adk_eval::RubricConfig::from_markdown(text);
443        if rubric.rubrics.is_empty() {
444            return Err(AdkError::new(
445                ErrorComponent::Agent,
446                ErrorCategory::InvalidInput,
447                "harness.goal.invalid",
448                "the rubric holds no criteria; write one list item per criterion",
449            ));
450        }
451        Ok(Self::new(rubric.rubrics.into_iter().map(|criterion| criterion.description)))
452    }
453
454    /// The criteria the goal text lists, one per list item; a goal that lists none is its
455    /// own single criterion.
456    ///
457    /// # Example
458    ///
459    /// ```rust
460    /// let rubric = adk_harness::GoalRubric::from_goal("Write blurb.md:\n- under 60 words\n- names the price");
461    /// assert_eq!(rubric.criteria, ["under 60 words", "names the price"]);
462    /// let whole = adk_harness::GoalRubric::from_goal("Write a haiku about Rust");
463    /// assert_eq!(whole.criteria, ["The deliverable achieves the goal: Write a haiku about Rust"]);
464    /// ```
465    pub fn from_goal(goal: &str) -> Self {
466        let listed = adk_eval::RubricConfig::from_markdown(goal);
467        let has_items = goal.lines().any(|line| {
468            let line = line.trim_start();
469            line.starts_with("- ")
470                || line.starts_with("* ")
471                || line.starts_with("+ ")
472                || line.split_once(['.', ')']).is_some_and(|(number, rest)| {
473                    !number.is_empty()
474                        && number.bytes().all(|byte| byte.is_ascii_digit())
475                        && rest.starts_with(' ')
476                })
477        });
478        if has_items && !listed.rubrics.is_empty() {
479            Self::new(listed.rubrics.into_iter().map(|criterion| criterion.description))
480        } else {
481            Self::new([format!("The deliverable achieves the goal: {}", goal.trim())])
482        }
483    }
484
485    /// The workspace files the grader reads.
486    #[must_use]
487    pub fn with_deliverables<I, S>(mut self, paths: I) -> Self
488    where
489        I: IntoIterator<Item = S>,
490        S: Into<String>,
491    {
492        self.deliverables = paths.into_iter().map(Into::into).collect();
493        self
494    }
495
496    /// The most grading rounds, from 1 to [`adk_eval::MAX_OUTCOME_ITERATIONS`].
497    #[must_use]
498    pub fn with_max_evaluations(mut self, max: u32) -> Self {
499        self.max_evaluations = max;
500        self
501    }
502
503    /// Shows the criteria to the grader only.
504    #[must_use]
505    pub fn hidden(mut self, yes: bool) -> Self {
506        self.hidden = yes;
507        self
508    }
509
510    /// The criteria as the grader takes them.
511    pub(crate) fn config(&self) -> adk_eval::RubricConfig {
512        adk_eval::RubricConfig::from_criteria(&self.criteria)
513    }
514
515    /// How the goal's prompt describes this rubric.
516    fn prompt_line(&self) -> String {
517        let reads = if self.deliverables.is_empty() {
518            "your final message".to_string()
519        } else {
520            format!("your final message and {}", self.deliverables.join(", "))
521        };
522        let what = if self.hidden {
523            "criteria you are not shown; its feedback names the ones that fail".to_string()
524        } else {
525            format!("the {} criteria below", self.criteria.len())
526        };
527        format!(
528            "a separate grader that reads only {reads} grades the result against {what} \
529             (at most {} grading rounds)",
530            self.max_evaluations
531        )
532    }
533
534    #[cfg(feature = "runner")]
535    fn validate(&self) -> std::result::Result<(), String> {
536        if self.criteria.is_empty() {
537            return Err("a goal's rubric needs at least one criterion".to_string());
538        }
539        let max = adk_eval::MAX_OUTCOME_ITERATIONS;
540        if !(1..=max).contains(&self.max_evaluations) {
541            return Err(format!(
542                "a goal's rubric allows {} grading rounds; set from 1 to {max}",
543                self.max_evaluations
544            ));
545        }
546        if let Some(path) = self.deliverables.iter().find(|path| path.trim().is_empty()) {
547            return Err(format!("a goal's rubric names an empty deliverable path `{path}`"));
548        }
549        Ok(())
550    }
551}
552
553/// Where a goal stands (spec 3.1 §7.11).
554///
555/// # Example
556///
557/// ```rust
558/// assert_eq!(serde_json::to_value(adk_harness::GoalStatus::Exhausted).unwrap(), "exhausted");
559/// ```
560#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
561#[serde(rename_all = "camelCase")]
562pub enum GoalStatus {
563    /// Iterating.
564    Running,
565    /// The check passed.
566    Done,
567    /// The iteration cap was reached.
568    Exhausted,
569    /// Cancelled.
570    Cancelled,
571}
572
573/// A goal's state, as mirrored to `harness:goal` (spec 3.1 §7.11).
574///
575/// # Example
576///
577/// ```rust,ignore
578/// if let Some(state) = harness.goal(&user, &session).await? {
579///     println!("{} of {}", state.iteration, state.max_iterations);
580/// }
581/// ```
582#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
583#[serde(rename_all = "camelCase")]
584#[non_exhaustive]
585pub struct GoalState {
586    /// What to achieve.
587    pub goal: String,
588    /// The check command, when the goal has one.
589    #[serde(default, skip_serializing_if = "Option::is_none")]
590    pub until: Option<String>,
591    /// The current iteration.
592    pub iteration: u32,
593    /// Most iterations.
594    pub max_iterations: u32,
595    /// Where it stands.
596    pub status: GoalStatus,
597    /// The last check's exit code.
598    pub last_check: Option<i32>,
599    /// Grading rounds so far, when the goal has a rubric.
600    #[serde(default, skip_serializing_if = "is_zero")]
601    pub evaluations: u32,
602    /// The grader's last verdict, when the goal has a rubric and was graded.
603    #[serde(default, skip_serializing_if = "Option::is_none")]
604    pub last_grade: Option<adk_eval::OutcomeGrade>,
605    /// When it last changed.
606    pub updated_at: DateTime<Utc>,
607}
608
609impl GoalState {
610    /// How the goal ended, in one line, or `None` while it runs.
611    ///
612    /// # Example
613    ///
614    /// ```rust
615    /// use adk_harness::{GoalRecord, GoalSpec};
616    ///
617    /// let record = GoalRecord::start(GoalSpec::new("g").with_until("true"));
618    /// assert_eq!(record.state.outcome(), None);
619    /// ```
620    pub fn outcome(&self) -> Option<String> {
621        let grade = self.last_grade.as_ref();
622        let checks = match (&self.until, grade) {
623            (Some(until), Some(_)) => format!("`{until}` and the rubric"),
624            (Some(until), None) => format!("`{until}`"),
625            (None, _) => "the rubric".to_string(),
626        };
627        match self.status {
628            GoalStatus::Running => None,
629            GoalStatus::Done => {
630                Some(format!("goal met after {} iteration(s): {checks} passed.", self.iteration))
631            }
632            GoalStatus::Exhausted => {
633                let failing = match (self.last_check, grade) {
634                    (Some(code), _) if code != 0 && self.until.is_some() => {
635                        format!(
636                            "`{}` still fails (exit {code})",
637                            self.until.as_deref().unwrap_or_default()
638                        )
639                    }
640                    (None, None) if self.until.is_some() => {
641                        format!("`{}` still fails", self.until.as_deref().unwrap_or_default())
642                    }
643                    (_, Some(grade)) => format!(
644                        "the rubric is not satisfied after {} grading round(s): {} of {} \
645                         criteria fail\n{}",
646                        self.evaluations,
647                        grade.criteria.len() - grade.passed(),
648                        grade.criteria.len(),
649                        grade.feedback()
650                    ),
651                    _ => "the checks still fail".to_string(),
652                };
653                Some(format!("budget exhausted after {} iteration(s); {failing}", self.iteration))
654            }
655            GoalStatus::Cancelled => {
656                Some(format!("the goal was cancelled at iteration {}.", self.iteration))
657            }
658        }
659    }
660}
661
662fn is_zero(value: &u32) -> bool {
663    *value == 0
664}
665
666/// The goal loop's engine (spec 3.1 §7.11, feature `graph`).
667///
668/// # Example
669///
670/// ```rust
671/// let engine = adk_harness::GoalEngine::Loop;
672/// # let _ = engine;
673/// ```
674#[cfg(feature = "graph")]
675#[derive(Clone, Copy, Debug, PartialEq, Eq)]
676pub enum GoalEngine {
677    /// A `LoopAgent` over the harness agent and an until-check agent.
678    Loop,
679    /// A checkpointed `StateGraph`: iterate → check → (done | iterate).
680    Graph,
681}
682
683/// A session's goal as the [`GoalStore`] keeps it: the spec and where it stands.
684///
685/// # Example
686///
687/// ```rust
688/// use adk_harness::{GoalRecord, GoalSpec, GoalStatus};
689///
690/// let spec = GoalSpec::new("g").with_until("true").with_max_iterations(3);
691/// let record = GoalRecord::start(spec);
692/// assert_eq!(record.state.status, GoalStatus::Running);
693/// assert_eq!(record.state.iteration, 0);
694/// ```
695#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
696#[serde(rename_all = "camelCase")]
697pub struct GoalRecord {
698    /// The goal.
699    pub spec: GoalSpec,
700    /// Where it stands.
701    pub state: GoalState,
702    /// Identifies this start of the goal; the `Graph` engine's thread is keyed by it.
703    pub run_id: String,
704}
705
706impl GoalRecord {
707    /// A goal that starts now, at iteration 0.
708    pub fn start(spec: GoalSpec) -> Self {
709        let state = GoalState {
710            goal: spec.goal.clone(),
711            until: spec.until.clone(),
712            iteration: 0,
713            max_iterations: spec.max_iterations,
714            status: GoalStatus::Running,
715            last_check: None,
716            evaluations: 0,
717            last_grade: None,
718            updated_at: Utc::now(),
719        };
720        Self { spec, state, run_id: uuid::Uuid::new_v4().to_string() }
721    }
722}
723
724/// Where a harness keeps each session's goal (spec 3.1 §7.11, §9.2 I1, I36).
725///
726/// Keyed by (`app`, `user`, `session`). Only the harness writes it: a session-state write,
727/// a client `stateDelta` or a delegate merge cannot change a goal.
728///
729/// # Example
730///
731/// ```rust
732/// use adk_harness::{GoalRecord, GoalSpec, GoalStore, InMemoryGoalStore};
733///
734/// # futures::executor::block_on(async {
735/// let store = InMemoryGoalStore::new();
736/// let spec = GoalSpec::new("g").with_until("true").with_max_iterations(3);
737/// store.set("app", "alice", "s1", GoalRecord::start(spec)).await?;
738/// assert!(store.get("app", "alice", "s1").await?.is_some());
739/// # Ok::<(), adk_core::AdkError>(())
740/// # }).unwrap();
741/// ```
742#[async_trait]
743pub trait GoalStore: Send + Sync {
744    /// The session's goal, if one was set.
745    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<GoalRecord>>;
746    /// Replaces the session's goal.
747    async fn set(&self, app: &str, user: &str, session: &str, record: GoalRecord) -> Result<()>;
748}
749
750type ScopeKey = (String, String, String);
751
752/// A [`GoalStore`] in process memory, the builder default.
753///
754/// # Example
755///
756/// ```rust
757/// let store = adk_harness::InMemoryGoalStore::new();
758/// # let _ = store;
759/// ```
760#[derive(Debug, Default)]
761pub struct InMemoryGoalStore {
762    records: RwLock<HashMap<ScopeKey, GoalRecord>>,
763}
764
765impl InMemoryGoalStore {
766    /// An empty store.
767    pub fn new() -> Self {
768        Self::default()
769    }
770}
771
772#[async_trait]
773impl GoalStore for InMemoryGoalStore {
774    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<GoalRecord>> {
775        let key = (app.to_string(), user.to_string(), session.to_string());
776        Ok(self.records.read().await.get(&key).cloned())
777    }
778
779    async fn set(&self, app: &str, user: &str, session: &str, record: GoalRecord) -> Result<()> {
780        let key = (app.to_string(), user.to_string(), session.to_string());
781        self.records.write().await.insert(key, record);
782        Ok(())
783    }
784}
785
786/// A [`GoalStore`] in SQLite (feature `sqlite`), beside the mode and rule stores.
787///
788/// Call [`migrate`](Self::migrate) once before use. The table is `adk_harness_goals`.
789///
790/// # Example
791///
792/// ```rust,ignore
793/// let pool = sqlx::SqlitePool::connect("sqlite::memory:").await?;
794/// let store = adk_harness::SqliteGoalStore::new(pool);
795/// store.migrate().await?;
796/// ```
797#[cfg(feature = "sqlite")]
798#[derive(Debug, Clone)]
799pub struct SqliteGoalStore {
800    pool: sqlx::SqlitePool,
801    #[cfg(feature = "encrypted")]
802    envelope: Option<crate::encrypted::StoreEnvelope>,
803}
804
805#[cfg(feature = "sqlite")]
806impl SqliteGoalStore {
807    /// A store over `pool`.
808    pub fn new(pool: sqlx::SqlitePool) -> Self {
809        Self {
810            pool,
811            #[cfg(feature = "encrypted")]
812            envelope: None,
813        }
814    }
815
816    /// Seals every record under `keyring` (spec 3.1 §7.12).
817    #[cfg(feature = "encrypted")]
818    #[must_use]
819    pub fn with_keyring(mut self, keyring: crate::encrypted::StoreKeyring) -> Self {
820        self.envelope = Some(crate::encrypted::StoreEnvelope::new(keyring, "goals"));
821        self
822    }
823
824    /// Re-seals every record a previous key sealed with the current key, seals records
825    /// written before a key was configured, and returns how many rows changed (spec 3.1
826    /// §7.12). Without a keyring, nothing changes.
827    ///
828    /// # Errors
829    ///
830    /// Returns `harness.store.decrypt_failed` when a row opens under no key the keyring
831    /// holds, or the database error.
832    #[cfg(feature = "encrypted")]
833    pub async fn rewrap(&self) -> Result<u64> {
834        let Some(envelope) = &self.envelope else {
835            return Ok(0);
836        };
837        let rows: Vec<(String, String, String, String)> =
838            sqlx::query_as("SELECT app_name, user_id, session_id, record FROM adk_harness_goals")
839                .fetch_all(&self.pool)
840                .await
841                .map_err(crate::fsutil::db_error)?;
842        let mut changed = 0;
843        for (app, user, session, text) in rows {
844            if let Some(resealed) = envelope.reseal_or_seal(&[&app, &user, &session], &text)? {
845                sqlx::query("UPDATE adk_harness_goals SET record = ? WHERE app_name = ? AND user_id = ? AND session_id = ?")
846                    .bind(resealed)
847                    .bind(&app)
848                    .bind(&user)
849                    .bind(&session)
850                    .execute(&self.pool)
851                    .await
852                    .map_err(crate::fsutil::db_error)?;
853                changed += 1;
854            }
855        }
856        Ok(changed)
857    }
858
859    #[cfg(feature = "encrypted")]
860    fn encode(&self, address: &[&str], text: String) -> Result<String> {
861        crate::encrypted::encode_row(self.envelope.as_ref(), address, text)
862    }
863
864    #[cfg(not(feature = "encrypted"))]
865    fn encode(&self, _address: &[&str], text: String) -> Result<String> {
866        Ok(text)
867    }
868
869    #[cfg(feature = "encrypted")]
870    fn decode(&self, address: &[&str], text: String) -> Result<String> {
871        crate::encrypted::decode_row(self.envelope.as_ref(), "goals", address, text)
872    }
873
874    #[cfg(not(feature = "encrypted"))]
875    fn decode(&self, _address: &[&str], text: String) -> Result<String> {
876        Ok(text)
877    }
878
879    /// Creates the store's table if it does not exist.
880    ///
881    /// # Errors
882    ///
883    /// Returns the database error when the statement fails.
884    pub async fn migrate(&self) -> Result<()> {
885        sqlx::query(
886            "CREATE TABLE IF NOT EXISTS adk_harness_goals (\
887                app_name TEXT NOT NULL, user_id TEXT NOT NULL, session_id TEXT NOT NULL, \
888                record TEXT NOT NULL, PRIMARY KEY (app_name, user_id, session_id))",
889        )
890        .execute(&self.pool)
891        .await
892        .map_err(crate::fsutil::db_error)?;
893        Ok(())
894    }
895}
896
897#[cfg(feature = "sqlite")]
898#[async_trait]
899impl GoalStore for SqliteGoalStore {
900    async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<GoalRecord>> {
901        let row: Option<(String,)> = sqlx::query_as(
902            "SELECT record FROM adk_harness_goals WHERE app_name = ? AND user_id = ? AND session_id = ?",
903        )
904        .bind(app)
905        .bind(user)
906        .bind(session)
907        .fetch_optional(&self.pool)
908        .await
909        .map_err(crate::fsutil::db_error)?;
910        let Some((text,)) = row else {
911            return Ok(None);
912        };
913        let text = self.decode(&[app, user, session], text)?;
914        // A record that does not parse is no goal: nothing runs on it.
915        Ok(serde_json::from_str(&text).ok())
916    }
917
918    async fn set(&self, app: &str, user: &str, session: &str, record: GoalRecord) -> Result<()> {
919        let text = serde_json::to_string(&record)
920            .map_err(|error| crate::fsutil::serialize_error("goal record", &error))?;
921        let text = self.encode(&[app, user, session], text)?;
922        sqlx::query(
923            "INSERT INTO adk_harness_goals (app_name, user_id, session_id, record) VALUES (?, ?, ?, ?) \
924             ON CONFLICT (app_name, user_id, session_id) DO UPDATE SET record = excluded.record",
925        )
926        .bind(app)
927        .bind(user)
928        .bind(session)
929        .bind(text)
930        .execute(&self.pool)
931        .await
932        .map_err(crate::fsutil::db_error)?;
933        Ok(())
934    }
935}
936
937/// Runs a goal's checks after each iteration (spec 3.1 §7.11): its `until` command, then,
938/// once that passes, its rubric's grader.
939///
940/// It checks the kill switch, runs `until` through the harness's command launcher with the
941/// goal's `check_timeout`, grades the iteration's deliverable when the goal has a
942/// [`GoalRubric`], updates the goal state, and sets `escalate` once every check passes
943/// (Done) or at a cap (Exhausted), which stops the `LoopAgent`. The command comes from the
944/// operator, not the model, so it is not a governed tool call; it is audited as
945/// `harness.bash.begin`/`.end` with `goalCheck: true`, each grading round as
946/// `harness.goal.grade`, and each iteration as `harness.goal.iteration` (spec 3.1 §9.3).
947///
948/// The check's result reaches the next iteration as a system notice
949/// ([`adk_core::history::system_notice`], authored `system`), so the agent reads the command's
950/// output and the grader's feedback as the harness's own notice rather than as another agent's
951/// output quoted to it as data.
952///
953/// The grader ([`with_grader`](Self::with_grader); the harness model by default) works in a
954/// context of its own: its request holds the goal, the criteria, the iteration's final
955/// message and the rubric's deliverable files, never the conversation. Its call counts
956/// against the run's budget and spend ledger, and its per-criterion feedback is what the
957/// next iteration reads.
958///
959/// # Example
960///
961/// ```rust
962/// use adk_harness::{InMemoryGoalStore, UntilCheckAgent};
963/// use std::sync::Arc;
964///
965/// let check = UntilCheckAgent::new(
966///     Arc::new(InMemoryGoalStore::new()),
967///     adk_devtools::Workspace::new("."),
968///     Arc::new(adk_devtools::HostLauncher),
969/// );
970/// assert_eq!(adk_core::Agent::name(&check), "until_check");
971/// ```
972pub struct UntilCheckAgent {
973    goals: Arc<dyn GoalStore>,
974    workspace: Workspace,
975    launcher: Arc<dyn CommandLauncher>,
976    book: Arc<GoalBook>,
977    grader: Option<Arc<dyn Llm>>,
978    worker: Option<String>,
979}
980
981impl std::fmt::Debug for UntilCheckAgent {
982    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
983        f.debug_struct("UntilCheckAgent")
984            .field("root", &self.workspace.root())
985            .field("launcher", &self.launcher.isolation())
986            .field("grader", &self.grader.as_ref().map(|model| model.name().to_string()))
987            .finish_non_exhaustive()
988    }
989}
990
991/// What one run of the `until` command found.
992struct CommandCheck {
993    exit_code: Option<i32>,
994    output: String,
995}
996
997impl UntilCheckAgent {
998    /// A check over the goals in `goals`, running commands in `workspace` through
999    /// `launcher`. The command is the operator's, so it runs whether or not the model may
1000    /// use `bash`.
1001    pub fn new(
1002        goals: Arc<dyn GoalStore>,
1003        workspace: Workspace,
1004        launcher: Arc<dyn CommandLauncher>,
1005    ) -> Self {
1006        Self {
1007            goals,
1008            workspace: workspace.allow_bash(true),
1009            launcher,
1010            book: Arc::new(GoalBook::default()),
1011            grader: None,
1012            worker: None,
1013        }
1014    }
1015
1016    /// The model that grades goals with a [`GoalRubric`]. Without one, a rubric goal's check
1017    /// fails with `harness.goal.no_grader`.
1018    #[must_use]
1019    pub fn with_grader(mut self, model: Arc<dyn Llm>) -> Self {
1020        self.grader = Some(model);
1021        self
1022    }
1023
1024    /// The agent whose final message of each iteration the grader reads; by default the
1025    /// agent the invocation runs.
1026    #[must_use]
1027    pub fn with_worker(mut self, name: impl Into<String>) -> Self {
1028        self.worker = Some(name.into());
1029        self
1030    }
1031
1032    /// The goals this check has seen, and the kernel's parker when one is attached.
1033    pub(crate) fn book(&self) -> &Arc<GoalBook> {
1034        &self.book
1035    }
1036
1037    fn audit(ctx: &dyn InvocationContext) -> Option<HarnessAudit> {
1038        let trail = ctx.run_config().audit.clone()?;
1039        Some(HarnessAudit::new(trail, AuditActor::for_context(ctx), ctx.session_id()))
1040    }
1041
1042    /// Runs one check and records it. The event mirrors the goal state while it runs on.
1043    async fn check(&self, ctx: Arc<dyn InvocationContext>) -> Result<Event> {
1044        self.check_with(ctx, None, None).await
1045    }
1046
1047    /// [`check`](Self::check) for an iteration that made `tool_calls` tool calls and ended
1048    /// with `final_message`, when the engine collected them.
1049    async fn check_with(
1050        &self,
1051        ctx: Arc<dyn InvocationContext>,
1052        tool_calls: Option<usize>,
1053        final_message: Option<String>,
1054    ) -> Result<Event> {
1055        ctx.run_config().check_governance()?;
1056        let (app, user, session) =
1057            (ctx.app_name().to_string(), ctx.user_id().to_string(), ctx.session_id().to_string());
1058        let mut record = self.goals.get(&app, &user, &session).await?.ok_or_else(|| {
1059            AdkError::new(
1060                ErrorComponent::Agent,
1061                ErrorCategory::NotFound,
1062                "harness.goal.missing",
1063                "the session has no goal to check",
1064            )
1065        })?;
1066        // The check speaks as the harness, in a system notice: the agent reads its result as
1067        // the runtime's own notice, not as another agent's output quoted for it as data.
1068        let mut event = Event::new(ctx.invocation_id());
1069        event.author = adk_core::history::SYSTEM_NOTICE_AUTHOR.to_string();
1070        event.branch = ctx.branch().to_string();
1071        if record.state.status != GoalStatus::Running {
1072            event.actions.escalate = true;
1073            event.set_content(adk_core::history::system_notice(&format!(
1074                "The goal is {:?}.",
1075                record.state.status
1076            )));
1077            return Ok(event);
1078        }
1079        record.state.iteration += 1;
1080        // The `harness.goal` span of spec 3.1 §7.13, around the check and its records.
1081        #[cfg(feature = "observe")]
1082        let span = crate::observe::goal_iteration_span(
1083            record.state.iteration,
1084            record.state.max_iterations,
1085        );
1086        #[cfg(not(feature = "observe"))]
1087        let span = tracing::Span::none();
1088        self.finish_check(ctx, record, event, tool_calls, final_message).instrument(span).await
1089    }
1090
1091    /// Runs the `until` command of `record`'s current iteration and records its run.
1092    async fn run_until(
1093        &self,
1094        ctx: &Arc<dyn InvocationContext>,
1095        record: &GoalRecord,
1096        until: &str,
1097        audit: Option<&HarnessAudit>,
1098    ) -> Result<CommandCheck> {
1099        let call_id = format!("goal-check-{}-{}", record.run_id, record.state.iteration);
1100        let args = json!({
1101            "command": until,
1102            "timeout_secs": record.spec.check_timeout.as_secs().max(1),
1103        });
1104        if let Some(audit) = audit {
1105            let draft = AuditRecordDraft::new(
1106                AuditRecordKind::Other(HARNESS_AUDIT_KIND.to_string()),
1107                "harness.bash.begin",
1108            )
1109            .args_digest(audit.trail().digest(&args));
1110            audit
1111                .record_draft(
1112                    draft,
1113                    json!({
1114                        "functionCallId": call_id,
1115                        "enforcer": self.launcher.isolation(),
1116                        "goalCheck": true,
1117                    }),
1118                )
1119                .await?;
1120        }
1121        // The goal's check_timeout bounds the check, not the shell's own limit for the model.
1122        let workspace = self.workspace.clone().bash_timeout(record.spec.check_timeout);
1123        let tool = BashTool::new(workspace).with_launcher(self.launcher.clone());
1124        let tool_ctx = Arc::new(InvocationToolContext::new(ctx.clone(), call_id.clone()));
1125        let started = Instant::now();
1126        let outcome = tool.execute(tool_ctx, args).await;
1127        let duration_ms = u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX);
1128        let (exit_code, output, timed_out) = match &outcome {
1129            Ok(value) => {
1130                let code = value.get("exit_code").and_then(Value::as_i64).map(|code| code as i32);
1131                let mut output = String::new();
1132                for stream in ["stdout", "stderr"] {
1133                    if let Some(text) = value.get(stream).and_then(Value::as_str) {
1134                        output.push_str(text);
1135                    }
1136                }
1137                (code, output, false)
1138            }
1139            Err(error) => (None, error.to_string(), error.code.contains("timeout")),
1140        };
1141        if let Some(audit) = audit {
1142            audit
1143                .record(
1144                    "harness.bash.end",
1145                    json!({
1146                        "functionCallId": call_id,
1147                        "exitCode": exit_code,
1148                        "durationMs": duration_ms,
1149                        "timedOut": timed_out,
1150                        "goalCheck": true,
1151                    }),
1152                )
1153                .await?;
1154        }
1155        Ok(CommandCheck { exit_code, output })
1156    }
1157
1158    /// Grades the iteration's deliverable against `rubric` in a context of its own, metered
1159    /// against the run's budget and spend ledger, and records the round.
1160    async fn grade(
1161        &self,
1162        ctx: &Arc<dyn InvocationContext>,
1163        record: &GoalRecord,
1164        rubric: &GoalRubric,
1165        final_message: Option<String>,
1166        audit: Option<&HarnessAudit>,
1167    ) -> Result<adk_eval::OutcomeGrade> {
1168        let grader = self.grader.clone().ok_or_else(|| {
1169            AdkError::new(
1170                ErrorComponent::Agent,
1171                ErrorCategory::InvalidInput,
1172                "harness.goal.no_grader",
1173                "the goal has a rubric but the check has no grader model; build the harness \
1174                 with a model or give UntilCheckAgent::with_grader one",
1175            )
1176        })?;
1177        let worker = self.worker.clone().unwrap_or_else(|| ctx.agent_name().to_string());
1178        let final_message = final_message
1179            .or_else(|| latest_text(&ctx.session().conversation_history_for_agent(&worker)));
1180        let mut deliverable = String::from("Final message of the iteration:\n");
1181        match final_message.as_deref().map(str::trim).filter(|text| !text.is_empty()) {
1182            Some(text) => deliverable.push_str(tail(text, FINAL_MESSAGE_MAX_BYTES)),
1183            None => deliverable.push_str("(none)"),
1184        }
1185        for path in &rubric.deliverables {
1186            deliverable.push_str(&format!("\n\nFile `{path}`:\n"));
1187            match self.workspace.read_for_review(path).await {
1188                Ok(Some(bytes)) => {
1189                    let text = String::from_utf8_lossy(&bytes);
1190                    if text.len() > DELIVERABLE_MAX_BYTES {
1191                        let mut end = DELIVERABLE_MAX_BYTES;
1192                        while !text.is_char_boundary(end) {
1193                            end -= 1;
1194                        }
1195                        deliverable.push_str(&text[..end]);
1196                        deliverable.push_str(&format!(
1197                            "\n(cut: the file has {} bytes; the grader read the first {end})",
1198                            text.len()
1199                        ));
1200                    } else {
1201                        deliverable.push_str(&text);
1202                    }
1203                }
1204                Ok(None) => deliverable.push_str("(the file does not exist)"),
1205                Err(error) => {
1206                    deliverable.push_str(&format!("(the file could not be read: {error})"))
1207                }
1208            }
1209        }
1210        let scope = adk_core::ModelCallScope::for_run(ctx.run_config(), ctx.app_name(), &worker);
1211        let metered: Arc<dyn Llm> = Arc::new(adk_core::MeteredLlm::new(grader).with_scope(scope));
1212        let model = metered.name().to_string();
1213        let grade = adk_eval::OutcomeGrader::new(metered)
1214            .grade(&record.spec.goal, &deliverable, &rubric.config())
1215            .await?;
1216        let failed: Vec<usize> = grade
1217            .criteria
1218            .iter()
1219            .enumerate()
1220            .filter(|(_, criterion)| !criterion.passed)
1221            .map(|(index, _)| index + 1)
1222            .collect();
1223        tracing::info!(
1224            harness.goal.iteration = record.state.iteration,
1225            goal.evaluation = record.state.evaluations,
1226            goal.criteria = grade.criteria.len(),
1227            goal.passed = grade.passed(),
1228            "goal graded"
1229        );
1230        if let Some(audit) = audit {
1231            audit
1232                .record(
1233                    "harness.goal.grade",
1234                    json!({
1235                        "goal": record.run_id,
1236                        "iteration": record.state.iteration,
1237                        "evaluation": record.state.evaluations,
1238                        "maxEvaluations": rubric.max_evaluations,
1239                        "model": model,
1240                        "criteria": grade.criteria.len(),
1241                        "failed": failed,
1242                        "satisfied": grade.satisfied(),
1243                    }),
1244                )
1245                .await?;
1246        }
1247        Ok(grade)
1248    }
1249
1250    /// Runs the checks of `record`'s current iteration and records them.
1251    async fn finish_check(
1252        &self,
1253        ctx: Arc<dyn InvocationContext>,
1254        mut record: GoalRecord,
1255        mut event: Event,
1256        tool_calls: Option<usize>,
1257        final_message: Option<String>,
1258    ) -> Result<Event> {
1259        let (app, user, session) =
1260            (ctx.app_name().to_string(), ctx.user_id().to_string(), ctx.session_id().to_string());
1261        let audit = Self::audit(ctx.as_ref());
1262        let command = match record.spec.until.clone() {
1263            Some(until) => Some(self.run_until(&ctx, &record, &until, audit.as_ref()).await?),
1264            None => None,
1265        };
1266        let command_passed = command.as_ref().is_none_or(|check| check.exit_code == Some(0));
1267        // The grader runs only once the command passes, so a failing command costs no
1268        // model call.
1269        let grade = match record.spec.rubric.clone() {
1270            Some(rubric) if command_passed => {
1271                record.state.evaluations += 1;
1272                Some(self.grade(&ctx, &record, &rubric, final_message, audit.as_ref()).await?)
1273            }
1274            _ => None,
1275        };
1276        let exit_code = command.as_ref().and_then(|check| check.exit_code);
1277        let graded_out = record
1278            .spec
1279            .rubric
1280            .as_ref()
1281            .is_some_and(|rubric| record.state.evaluations >= rubric.max_evaluations);
1282        record.state.last_check = exit_code;
1283        if grade.is_some() {
1284            record.state.last_grade = grade.clone();
1285        }
1286        record.state.updated_at = Utc::now();
1287        let satisfied = grade.as_ref().is_none_or(adk_eval::OutcomeGrade::satisfied);
1288        record.state.status = if command_passed && satisfied {
1289            GoalStatus::Done
1290        } else if record.state.iteration >= record.state.max_iterations || graded_out {
1291            GoalStatus::Exhausted
1292        } else {
1293            GoalStatus::Running
1294        };
1295        self.goals.set(&app, &user, &session, record.clone()).await?;
1296        if let Some(audit) = &audit {
1297            audit
1298                .record(
1299                    "harness.goal.iteration",
1300                    json!({
1301                        "iteration": record.state.iteration,
1302                        "max": record.state.max_iterations,
1303                        "checkExitCode": exit_code,
1304                        "rubricSatisfied": grade.as_ref().map(adk_eval::OutcomeGrade::satisfied),
1305                        "status": record.state.status,
1306                    }),
1307                )
1308                .await?;
1309        }
1310        tracing::info!(
1311            harness.goal.iteration = record.state.iteration,
1312            goal.status = ?record.state.status,
1313            check.exit_code = ?exit_code,
1314            "goal check finished"
1315        );
1316        // A rubric goal's progress is its grade, so a repeated verdict counts as a stall.
1317        let observed = match (&command, &grade) {
1318            (_, Some(grade)) => grade.feedback(),
1319            (Some(check), None) => check.output.clone(),
1320            (None, None) => String::new(),
1321        };
1322        let stalled = self.book.record_check(
1323            &record.run_id,
1324            exit_code,
1325            &observed,
1326            tool_calls,
1327            record.state.status == GoalStatus::Running,
1328        );
1329        let mut summary = check_summary(&record, command.as_ref(), grade.as_ref());
1330        if let Some(reason) = stalled {
1331            self.stall(ctx.as_ref(), &record, reason, audit.as_ref()).await?;
1332            summary.push_str(&format!(
1333                "\nThe goal made no progress ({reason}); it is parked until a person resumes it."
1334            ));
1335        }
1336        event.set_content(adk_core::history::system_notice(&summary));
1337        event.actions.state_delta.insert(
1338            GOAL_STATE_KEY.to_string(),
1339            serde_json::to_value(&record.state).unwrap_or(Value::Null),
1340        );
1341        event.actions.escalate = record.state.status != GoalStatus::Running;
1342        Ok(event)
1343    }
1344}
1345
1346/// What the next iteration reads about this iteration's checks.
1347fn check_summary(
1348    record: &GoalRecord,
1349    command: Option<&CommandCheck>,
1350    grade: Option<&adk_eval::OutcomeGrade>,
1351) -> String {
1352    let state = &record.state;
1353    let (iteration, max) = (state.iteration, state.max_iterations);
1354    let mut lines = Vec::new();
1355    if let (Some(until), Some(check)) = (&record.spec.until, command) {
1356        let exit = check.exit_code.map_or_else(|| "none".to_string(), |code| code.to_string());
1357        if check.exit_code == Some(0) {
1358            lines.push(format!("Goal check `{until}` passed on iteration {iteration}."));
1359        } else {
1360            lines.push(format!(
1361                "Goal check `{until}` failed (exit {exit}) on iteration {iteration} of {max}. \
1362                 Its output:\n{}",
1363                tail(&check.output, CHECK_OUTPUT_TAIL)
1364            ));
1365        }
1366    }
1367    if let (Some(rubric), Some(grade)) = (&record.spec.rubric, grade) {
1368        let total = grade.criteria.len();
1369        if grade.satisfied() {
1370            lines.push(format!(
1371                "The grader passed all {total} criteria on grading round {} of {}.",
1372                state.evaluations, rubric.max_evaluations
1373            ));
1374        } else {
1375            lines.push(format!(
1376                "The grader failed {} of {total} criteria on grading round {} of {}. Revise \
1377                 to address its feedback:\n{}",
1378                total - grade.passed(),
1379                state.evaluations,
1380                rubric.max_evaluations,
1381                grade.feedback()
1382            ));
1383        }
1384        if !grade.summary.is_empty() {
1385            lines.push(format!("Grader summary: {}", grade.summary));
1386        }
1387    }
1388    match state.status {
1389        GoalStatus::Done => lines.push("The goal is done.".to_string()),
1390        GoalStatus::Exhausted => {
1391            let cap = match &record.spec.rubric {
1392                Some(rubric) if state.evaluations >= rubric.max_evaluations => {
1393                    format!("the rubric's {} grading rounds are used up", rubric.max_evaluations)
1394                }
1395                _ => format!("no iterations are left ({iteration} of {max})"),
1396            };
1397            lines.push(format!("The goal is exhausted: {cap}."));
1398        }
1399        GoalStatus::Running | GoalStatus::Cancelled => {}
1400    }
1401    lines.join("\n")
1402}
1403
1404/// The text of the latest model turn in `history`.
1405fn latest_text(history: &[Content]) -> Option<String> {
1406    history.iter().rev().filter(|content| content.role == "model").find_map(|content| {
1407        let text: String = content.parts.iter().filter_map(adk_core::Part::text).collect();
1408        (!text.trim().is_empty()).then_some(text)
1409    })
1410}
1411
1412impl UntilCheckAgent {
1413    /// Records the stall of `record` and parks its durable run at its next model-call
1414    /// boundary, where the kernel shows it `Waiting`, suspended manually (spec 3.2 §7.3,
1415    /// §9.3 `harness.goal.stalled`).
1416    async fn stall(
1417        &self,
1418        ctx: &dyn InvocationContext,
1419        record: &GoalRecord,
1420        reason: &str,
1421        audit: Option<&HarnessAudit>,
1422    ) -> Result<()> {
1423        let pid = ctx.run_config().durable_run_id.clone();
1424        tracing::warn!(
1425            harness.goal.iteration = record.state.iteration,
1426            goal.stall = reason,
1427            run.id = ?pid,
1428            "goal made no progress; parking it"
1429        );
1430        if let Some(audit) = audit {
1431            audit
1432                .record(
1433                    "harness.goal.stalled",
1434                    json!({
1435                        "pid": pid,
1436                        "goal": record.run_id,
1437                        "iteration": record.state.iteration,
1438                        "reason": reason,
1439                    }),
1440                )
1441                .await?;
1442        }
1443        if let (Some(parker), Some(pid)) = (self.book.parker(), pid) {
1444            match parker.park(&pid).await {
1445                Ok(true) => {}
1446                Ok(false) => {
1447                    tracing::warn!(run.id = %pid, "the kernel is gone; the stalled goal runs on")
1448                }
1449                Err(error) => {
1450                    tracing::warn!(run.id = %pid, error = %error, "could not park the stalled goal")
1451                }
1452            }
1453        }
1454        Ok(())
1455    }
1456}
1457
1458/// The last `max` bytes of `text`, on a character boundary.
1459fn tail(text: &str, max: usize) -> &str {
1460    if text.len() <= max {
1461        return text;
1462    }
1463    let mut start = text.len() - max;
1464    while !text.is_char_boundary(start) {
1465        start += 1;
1466    }
1467    &text[start..]
1468}
1469
1470#[async_trait]
1471impl Agent for UntilCheckAgent {
1472    fn name(&self) -> &str {
1473        UNTIL_CHECK_AGENT
1474    }
1475
1476    fn description(&self) -> &str {
1477        "Runs the goal's until command and records the goal's progress."
1478    }
1479
1480    fn sub_agents(&self) -> &[Arc<dyn Agent>] {
1481        &[]
1482    }
1483
1484    async fn run(&self, ctx: Arc<dyn InvocationContext>) -> Result<EventStream> {
1485        let event = self.check(ctx).await?;
1486        Ok(Box::pin(futures::stream::iter(vec![Ok(event)])))
1487    }
1488}
1489
1490/// How a harness runs goals.
1491#[derive(Clone)]
1492pub(crate) struct GoalRuntime {
1493    pub(crate) store: Arc<dyn GoalStore>,
1494    pub(crate) until: Arc<UntilCheckAgent>,
1495    #[cfg(feature = "graph")]
1496    pub(crate) engine: GoalEngine,
1497    #[cfg(feature = "graph")]
1498    pub(crate) checkpointer: Arc<dyn adk_graph::Checkpointer>,
1499}
1500
1501impl GoalRuntime {
1502    /// Runs this turn as the session's goal, when one is running and the mode lets it.
1503    pub(crate) async fn route(
1504        &self,
1505        mode: HarnessMode,
1506        harness: &str,
1507        root: Arc<dyn Agent>,
1508        ctx: Arc<dyn InvocationContext>,
1509    ) -> Result<Option<EventStream>> {
1510        if !matches!(mode, HarnessMode::Ask | HarnessMode::Auto) {
1511            return Ok(None);
1512        }
1513        let Some(record) = self.store.get(ctx.app_name(), ctx.user_id(), ctx.session_id()).await?
1514        else {
1515            return Ok(None);
1516        };
1517        if record.state.status != GoalStatus::Running {
1518            return Ok(None);
1519        }
1520        self.until.book().started(&record.run_id);
1521        #[cfg(feature = "graph")]
1522        if self.engine == GoalEngine::Graph {
1523            return Ok(Some(self.run_graph(&record, harness, root, ctx)?));
1524        }
1525        // The loop is named like the harness, so a hold records its position under one name
1526        // every turn and the next turn resumes there.
1527        let engine = adk_agent::LoopAgent::new(harness, vec![root, self.until.clone()])
1528            .with_max_iterations(GOAL_LOOP_CEILING);
1529        Ok(Some(engine.run(ctx).await?))
1530    }
1531
1532    #[cfg(feature = "graph")]
1533    fn run_graph(
1534        &self,
1535        record: &GoalRecord,
1536        harness: &str,
1537        root: Arc<dyn Agent>,
1538        ctx: Arc<dyn InvocationContext>,
1539    ) -> Result<EventStream> {
1540        use adk_graph::{END, ExecutionConfig, START, State, StateGraph, StateSchema};
1541
1542        use crate::plan_graph::drive;
1543
1544        let (sink, forwarded) = tokio::sync::mpsc::unbounded_channel();
1545        let graph = StateGraph::new(StateSchema::simple(&["input"]))
1546            .add_node(IterateNode {
1547                root,
1548                harness: harness.to_string(),
1549                prompt: record.spec.prompt(),
1550                sink: sink.clone(),
1551            })
1552            .add_node(CheckNode { until: self.until.clone(), sink })
1553            .add_edge(START, "iterate")
1554            .add_edge("iterate", "check")
1555            .add_conditional_edges(
1556                "check",
1557                |state: &State| {
1558                    if state.get("goalStatus").and_then(Value::as_str) == Some("running") {
1559                        "iterate".to_string()
1560                    } else {
1561                        END.to_string()
1562                    }
1563                },
1564                [("iterate", "iterate"), (END, END)],
1565            )
1566            .compile()?
1567            .with_checkpointer_arc(self.checkpointer.clone())
1568            // Iterate and check checkpoint each iteration; the stall window and its
1569            // predecessor are all a resume needs (spec 3.2 §10 HK3).
1570            .with_checkpoint_retention(adk_graph::RetentionPolicy::keep_last(
1571                2 * GOAL_STALL_WINDOW as usize,
1572            ))
1573            .with_recursion_limit(2 * record.spec.max_iterations as usize + 2);
1574        let thread = format!(
1575            "{}:goal:{}",
1576            adk_graph::agent::session_thread_id(ctx.app_name(), ctx.user_id(), ctx.session_id()),
1577            record.run_id
1578        );
1579        let config = ExecutionConfig::new(&thread).with_parent_context(ctx);
1580        let run = async move { graph.invoke(State::new(), config).await };
1581        Ok(drive(run, forwarded, |outcome| {
1582            async_stream::stream! {
1583                match outcome {
1584                    Ok(_) | Err(adk_graph::GraphError::Interrupted(_)) => {}
1585                    Err(error) => yield Err(error.into()),
1586                }
1587            }
1588        }))
1589    }
1590}
1591
1592/// The graph state key of the tool calls the last iteration made.
1593#[cfg(feature = "graph")]
1594const ITERATION_TOOL_CALLS: &str = "iterationToolCalls";
1595
1596/// The graph state key of the last iteration's final message, which a rubric's grader reads.
1597#[cfg(feature = "graph")]
1598const ITERATION_OUTPUT: &str = "iterationOutput";
1599
1600/// One iteration of the `Graph` engine: the harness agent works on the goal.
1601#[cfg(feature = "graph")]
1602struct IterateNode {
1603    root: Arc<dyn Agent>,
1604    harness: String,
1605    prompt: String,
1606    sink: crate::plan_graph::Sink,
1607}
1608
1609#[cfg(feature = "graph")]
1610#[async_trait]
1611impl adk_graph::Node for IterateNode {
1612    fn name(&self) -> &str {
1613        "iterate"
1614    }
1615
1616    async fn execute(
1617        &self,
1618        ctx: &adk_graph::NodeContext,
1619    ) -> adk_graph::Result<adk_graph::NodeOutput> {
1620        let parent = ctx.config.parent_context.clone().ok_or_else(|| {
1621            adk_graph::GraphError::NodeExecutionFailed {
1622                node: "iterate".into(),
1623                message: "a goal iteration runs only inside a harness turn".into(),
1624            }
1625        })?;
1626        let (held, output, tool_calls) = crate::plan_graph::run_agent_node_counted(
1627            "iterate",
1628            &self.root,
1629            &self.harness,
1630            parent,
1631            Content::new("user").with_text(self.prompt.clone()),
1632            &self.sink,
1633        )
1634        .await?;
1635        if held {
1636            return Ok(adk_graph::NodeOutput::interrupt_with_data(
1637                "goal iteration holds a tool call",
1638                json!({}),
1639            ));
1640        }
1641        Ok(adk_graph::NodeOutput::new()
1642            .with_update(ITERATION_TOOL_CALLS, json!(tool_calls))
1643            .with_update(ITERATION_OUTPUT, json!(output)))
1644    }
1645}
1646
1647/// The `Graph` engine's check.
1648#[cfg(feature = "graph")]
1649struct CheckNode {
1650    until: Arc<UntilCheckAgent>,
1651    sink: crate::plan_graph::Sink,
1652}
1653
1654#[cfg(feature = "graph")]
1655#[async_trait]
1656impl adk_graph::Node for CheckNode {
1657    fn name(&self) -> &str {
1658        "check"
1659    }
1660
1661    async fn execute(
1662        &self,
1663        ctx: &adk_graph::NodeContext,
1664    ) -> adk_graph::Result<adk_graph::NodeOutput> {
1665        let parent = ctx.config.parent_context.clone().ok_or_else(|| {
1666            adk_graph::GraphError::NodeExecutionFailed {
1667                node: "check".into(),
1668                message: "a goal check runs only inside a harness turn".into(),
1669            }
1670        })?;
1671        let tool_calls = ctx
1672            .state
1673            .get(ITERATION_TOOL_CALLS)
1674            .and_then(Value::as_u64)
1675            .and_then(|calls| usize::try_from(calls).ok());
1676        let output = ctx.state.get(ITERATION_OUTPUT).and_then(Value::as_str).map(str::to_string);
1677        let event = self.until.check_with(parent, tool_calls, output).await.map_err(|error| {
1678            adk_graph::GraphError::AgentFailed { node: "check".into(), source: Box::new(error) }
1679        })?;
1680        // A check of a goal that no longer runs mirrors nothing, and ends the graph.
1681        let status = event
1682            .actions
1683            .state_delta
1684            .get(GOAL_STATE_KEY)
1685            .and_then(|state| state.get("status"))
1686            .cloned()
1687            .unwrap_or_else(|| json!("done"));
1688        let _ = self.sink.send(crate::plan_graph::Forward::Event(event));
1689        Ok(adk_graph::NodeOutput::new().with_update("goalStatus", status))
1690    }
1691}
1692
1693/// Starts `spec` for the session: validates it, requires Ask or Auto, and writes the goal
1694/// state (spec 3.1 §7.11).
1695#[cfg(feature = "runner")]
1696pub(crate) async fn begin(
1697    store: &dyn GoalStore,
1698    mode: HarnessMode,
1699    (app, user, session): (&str, &str, &str),
1700    spec: GoalSpec,
1701) -> Result<GoalRecord> {
1702    spec.validate()?;
1703    if !matches!(mode, HarnessMode::Ask | HarnessMode::Auto) {
1704        return Err(AdkError::new(
1705            ErrorComponent::Agent,
1706            ErrorCategory::Forbidden,
1707            "harness.goal.mode",
1708            format!("a goal runs only in ask or auto mode; the session is in {mode} mode"),
1709        ));
1710    }
1711    let record = GoalRecord::start(spec);
1712    store.set(app, user, session, record.clone()).await?;
1713    Ok(record)
1714}
1715
1716#[cfg(test)]
1717mod tests {
1718    use super::*;
1719
1720    #[test]
1721    fn tail_keeps_the_end_on_a_character_boundary() {
1722        assert_eq!(tail("abc", 10), "abc");
1723        assert_eq!(tail("abcdef", 3), "def");
1724        assert_eq!(tail("aé", 1), "");
1725    }
1726
1727    #[cfg(feature = "runner")]
1728    #[test]
1729    fn a_goal_spec_must_be_complete() {
1730        let spec = GoalSpec::new("g")
1731            .with_until("true")
1732            .with_max_iterations(1)
1733            .with_check_timeout(Duration::from_secs(1));
1734        assert!(spec.validate().is_ok());
1735        assert!(GoalSpec { max_iterations: 0, ..spec.clone() }.validate().is_err());
1736        assert!(GoalSpec { until: Some(" ".into()), ..spec.clone() }.validate().is_err());
1737        assert!(GoalSpec { until: None, ..spec.clone() }.validate().is_err());
1738        assert!(GoalSpec { check_timeout: Duration::ZERO, ..spec }.validate().is_err());
1739    }
1740
1741    #[cfg(feature = "runner")]
1742    #[test]
1743    fn a_rubric_goal_needs_criteria_and_a_cap_of_at_most_twenty() {
1744        let rubric = GoalRubric::new(["names the price"]);
1745        let spec = GoalSpec::new("write blurb.md").with_rubric(rubric.clone());
1746        assert!(spec.validate().is_ok(), "a rubric alone is a check");
1747        assert_eq!(rubric.max_evaluations, adk_eval::DEFAULT_OUTCOME_ITERATIONS);
1748        for (max, valid) in [(0, false), (1, true), (20, true), (21, false)] {
1749            let spec = spec.clone().with_rubric(rubric.clone().with_max_evaluations(max));
1750            assert_eq!(spec.validate().is_ok(), valid, "max_evaluations {max}");
1751        }
1752        let empty = spec.clone().with_rubric(GoalRubric::new(["  "]));
1753        assert!(empty.validate().is_err());
1754        let both = spec.with_until("test -f blurb.md");
1755        assert!(both.validate().is_ok());
1756    }
1757
1758    #[test]
1759    fn an_until_goal_keeps_its_digest() {
1760        // The digest names a goal's durable run, so adding the rubric must not move it.
1761        let spec = GoalSpec::new("make main green")
1762            .with_until("cargo test")
1763            .with_max_iterations(5)
1764            .with_check_timeout(Duration::from_secs(900));
1765        assert_eq!(
1766            serde_json::to_value(&spec).unwrap(),
1767            json!({
1768                "goal": "make main green",
1769                "until": "cargo test",
1770                "maxIterations": 5,
1771                "checkTimeout": {"secs": 900, "nanos": 0},
1772            })
1773        );
1774    }
1775
1776    #[test]
1777    fn the_prompt_shows_a_visible_rubric_and_hides_a_hidden_one() {
1778        let rubric = GoalRubric::new(["names the product", "states the price"])
1779            .with_deliverables(["blurb.md"]);
1780        let visible = GoalSpec::new("write blurb.md").with_rubric(rubric.clone()).prompt();
1781        assert!(visible.contains("reads only your final message and blurb.md"), "{visible}");
1782        assert!(visible.contains("1. names the product\n2. states the price"), "{visible}");
1783        let hidden = GoalSpec::new("write blurb.md").with_rubric(rubric.hidden(true)).prompt();
1784        assert!(hidden.contains("criteria you are not shown"), "{hidden}");
1785        assert!(!hidden.contains("states the price"), "{hidden}");
1786        let both = GoalSpec::new("g")
1787            .with_until("cargo test")
1788            .with_rubric(GoalRubric::new(["c"]))
1789            .prompt();
1790        assert!(both.contains("runs `cargo test`, which must exit 0, then a separate grader"));
1791        assert!(both.contains("the goal is reached when both pass"), "{both}");
1792    }
1793
1794    #[test]
1795    fn a_rubric_reads_from_markdown_and_from_the_goal_text() {
1796        let rubric = GoalRubric::from_markdown("# Rubric\n\n- one\n- two\n").unwrap();
1797        assert_eq!(rubric.criteria, ["one", "two"]);
1798        assert!(GoalRubric::from_markdown("# Only a heading\n").is_err());
1799        let listed = GoalRubric::from_goal("Ship it:\n1. tests pass\n2) docs updated");
1800        assert_eq!(listed.criteria, ["tests pass", "docs updated"]);
1801    }
1802}