1use 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
37pub const GOAL_STATE_KEY: &str = "harness:goal";
45
46pub const GOAL_TARGET: &str = "harness.goal";
54
55pub const GOAL_QUEUE: &str = "harness.goal";
64
65pub const UNTIL_CHECK_AGENT: &str = "until_check";
73
74const GOAL_LOOP_CEILING: u32 = 10_000;
76
77const CHECK_OUTPUT_TAIL: usize = 4 * 1024;
79
80pub const GOAL_STALL_WINDOW: u32 = 3;
90
91pub(crate) const STALL_SAME_CHECK: &str = "same_check";
94pub(crate) const STALL_NO_TOOL_CALL: &str = "no_tool_call";
96
97#[async_trait]
100pub(crate) trait GoalParker: Send + Sync {
101 async fn park(&self, run_id: &str) -> Result<bool>;
103}
104
105#[derive(Clone, Debug)]
108pub(crate) struct GoalTrack {
109 #[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#[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 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 #[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 #[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 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
203pub const DEFAULT_GOAL_ITERATIONS: u32 = 8;
212
213pub const DEFAULT_CHECK_TIMEOUT: Duration = Duration::from_secs(600);
221
222const DELIVERABLE_MAX_BYTES: usize = 64 * 1024;
224
225const FINAL_MESSAGE_MAX_BYTES: usize = 16 * 1024;
227
228#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
246#[serde(rename_all = "camelCase")]
247#[non_exhaustive]
248pub struct GoalSpec {
249 pub goal: String,
251 #[serde(default, skip_serializing_if = "Option::is_none")]
253 pub until: Option<String>,
254 #[serde(default, skip_serializing_if = "Option::is_none")]
256 pub rubric: Option<GoalRubric>,
257 pub max_iterations: u32,
259 pub check_timeout: Duration,
261}
262
263impl GoalSpec {
264 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 #[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 #[must_use]
286 pub fn with_rubric(mut self, rubric: GoalRubric) -> Self {
287 self.rubric = Some(rubric);
288 self
289 }
290
291 #[must_use]
293 pub fn with_max_iterations(mut self, max: u32) -> Self {
294 self.max_iterations = max;
295 self
296 }
297
298 #[must_use]
300 pub fn with_check_timeout(mut self, timeout: Duration) -> Self {
301 self.check_timeout = timeout;
302 self
303 }
304
305 pub fn digest(&self) -> String {
315 crate::fsutil::sha256_hex(&serde_json::to_string(self).unwrap_or_default())
316 }
317
318 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#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
400#[serde(rename_all = "camelCase")]
401#[non_exhaustive]
402pub struct GoalRubric {
403 pub criteria: Vec<String>,
405 #[serde(default, skip_serializing_if = "Vec::is_empty")]
407 pub deliverables: Vec<String>,
408 pub max_evaluations: u32,
410 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
412 pub hidden: bool,
413}
414
415impl GoalRubric {
416 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 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 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 #[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 #[must_use]
498 pub fn with_max_evaluations(mut self, max: u32) -> Self {
499 self.max_evaluations = max;
500 self
501 }
502
503 #[must_use]
505 pub fn hidden(mut self, yes: bool) -> Self {
506 self.hidden = yes;
507 self
508 }
509
510 pub(crate) fn config(&self) -> adk_eval::RubricConfig {
512 adk_eval::RubricConfig::from_criteria(&self.criteria)
513 }
514
515 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
561#[serde(rename_all = "camelCase")]
562pub enum GoalStatus {
563 Running,
565 Done,
567 Exhausted,
569 Cancelled,
571}
572
573#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
583#[serde(rename_all = "camelCase")]
584#[non_exhaustive]
585pub struct GoalState {
586 pub goal: String,
588 #[serde(default, skip_serializing_if = "Option::is_none")]
590 pub until: Option<String>,
591 pub iteration: u32,
593 pub max_iterations: u32,
595 pub status: GoalStatus,
597 pub last_check: Option<i32>,
599 #[serde(default, skip_serializing_if = "is_zero")]
601 pub evaluations: u32,
602 #[serde(default, skip_serializing_if = "Option::is_none")]
604 pub last_grade: Option<adk_eval::OutcomeGrade>,
605 pub updated_at: DateTime<Utc>,
607}
608
609impl GoalState {
610 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#[cfg(feature = "graph")]
675#[derive(Clone, Copy, Debug, PartialEq, Eq)]
676pub enum GoalEngine {
677 Loop,
679 Graph,
681}
682
683#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
696#[serde(rename_all = "camelCase")]
697pub struct GoalRecord {
698 pub spec: GoalSpec,
700 pub state: GoalState,
702 pub run_id: String,
704}
705
706impl GoalRecord {
707 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#[async_trait]
743pub trait GoalStore: Send + Sync {
744 async fn get(&self, app: &str, user: &str, session: &str) -> Result<Option<GoalRecord>>;
746 async fn set(&self, app: &str, user: &str, session: &str, record: GoalRecord) -> Result<()>;
748}
749
750type ScopeKey = (String, String, String);
751
752#[derive(Debug, Default)]
761pub struct InMemoryGoalStore {
762 records: RwLock<HashMap<ScopeKey, GoalRecord>>,
763}
764
765impl InMemoryGoalStore {
766 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#[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 pub fn new(pool: sqlx::SqlitePool) -> Self {
809 Self {
810 pool,
811 #[cfg(feature = "encrypted")]
812 envelope: None,
813 }
814 }
815
816 #[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 #[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 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 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
937pub 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
991struct CommandCheck {
993 exit_code: Option<i32>,
994 output: String,
995}
996
997impl UntilCheckAgent {
998 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 #[must_use]
1019 pub fn with_grader(mut self, model: Arc<dyn Llm>) -> Self {
1020 self.grader = Some(model);
1021 self
1022 }
1023
1024 #[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 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 async fn check(&self, ctx: Arc<dyn InvocationContext>) -> Result<Event> {
1044 self.check_with(ctx, None, None).await
1045 }
1046
1047 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 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 #[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 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 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 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 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 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 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
1346fn 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
1404fn 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 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
1458fn 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#[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 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 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 .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#[cfg(feature = "graph")]
1594const ITERATION_TOOL_CALLS: &str = "iterationToolCalls";
1595
1596#[cfg(feature = "graph")]
1598const ITERATION_OUTPUT: &str = "iterationOutput";
1599
1600#[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#[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 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#[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 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}