trusty_code/tools/traits.rs
1//! Core trait abstractions for tool execution, agent running, search, and skills.
2//!
3//! Why: DI through traits lets tcode swap concrete implementations (subprocess
4//! runner vs. in-process mock; Brave vs. Tavily search; fs skill store vs.
5//! embedded) without changing call sites. This is the SOA seam that keeps
6//! the workflow engine and PM loop testable.
7//! What: Defines `ToolExecutor`, `AgentRunner`, `SearchProvider`, and
8//! `SkillResolver`. All are object-safe (`dyn`-able) and `Send + Sync`.
9//!
10//! `ServiceTier` and `RunContext`/`HistoryMessage` are byte-for-byte identical
11//! to the canonical definitions in `trusty-agents-common` (the same crate
12//! `trusty-agents` already re-exports these from — see
13//! `crates/trusty-agents/src/tools/traits.rs`) and are re-exported here rather
14//! than redeclared (#2893, epic #2892).
15//!
16//! `ToolExecutor`/`ToolResult` and `AgentRunner`/`AgentOutput` stay LOCAL,
17//! deliberately NOT deduped against `trusty-agents-common`, because tcode's
18//! versions carry fields the shared ones lack and that must not regress:
19//! `ToolResult::Success.telemetry` (`Option<Box<ToolTelemetry>>`, #2862) and
20//! `AgentOutput.finish_status` (`Option<FinishStatus>`, #2683; whose
21//! `AgentOutput.usage: crate::perf::TokenUsage` also carries a `cost_usd`
22//! field the shared `TokenUsage` lacks, #50). Unifying either would require
23//! either type-erasing tcode's telemetry (`ToolTelemetry` depends on
24//! `crate::events::{SearchHit, RecalledMemory}`, which are not portable to
25//! the shared crate without a much larger events-module move) or extending
26//! `trusty-agents-common`'s `TokenUsage`/`AgentOutput` and updating every
27//! `trusty-agents`/`cto-assistant` call site that pattern-matches
28//! `ToolResult::Success` — a real design decision outside this
29//! behavior-preserving refactor's scope. See PR discussion for #2893.
30//! Test: Mock impls of each trait are constructed in unit tests for
31//! `ToolRegistry`, delegating commands, and related code.
32
33use anyhow::Result;
34use async_trait::async_trait;
35use serde::{Deserialize, Serialize};
36use serde_json::Value;
37
38// Why: `ServiceTier` and the `AgentRunner` DI seam types (`RunContext`,
39// `HistoryMessage`) are byte-identical (or a strict derive superset) of
40// trusty-agents-common's canonical definitions — re-exporting instead of
41// redeclaring eliminates ~40 duplicate lines without any behavior change
42// (#2893). `AgentOutput`/`AgentRunner` stay local (see module docs above)
43// so `HistoryMessage` here is the shared type used by the LOCAL
44// `AgentRunner` trait below, not `trusty_agents_common::runner::AgentRunner`.
45// What: Re-exports the RBAC tier enum and the runner-context/history types.
46// Test: All existing `ServiceTier`/`RunContext`/`HistoryMessage` references in
47// this crate resolve unchanged; `cargo test -p trusty-code` passes.
48pub use trusty_agents_common::ServiceTier;
49pub use trusty_agents_common::runner::{HistoryMessage, RunContext};
50
51use crate::tools::telemetry::ToolTelemetry;
52
53// ── ToolResult ──────────────────────────────────────────────────────────────
54
55/// Structured result of a tool execution.
56///
57/// Why: Hard-failing the LLM loop on every tool error is brittle — the model
58/// often can recover (retry with different args, fall back to another tool, or
59/// explain the failure in its final answer). A structured error lets the caller
60/// surface failure back to the LLM as a `tool_result` with `is_error: true`
61/// while keeping the loop running.
62/// What: `Success` carries a successful textual result plus (UI Phase 1) an
63/// optional [`ToolTelemetry`] side-channel; `Error` carries a message plus a
64/// `recoverable` flag.
65/// Test: `ToolResult::err(...).is_error()` is true; `ok(...).content()` returns
66/// the success string. Exercised in `tools::registry` and delegate tests.
67#[derive(Debug)]
68pub enum ToolResult {
69 /// Tool executed successfully.
70 ///
71 /// `text` is the textual result fed back to the model. `telemetry`
72 /// (UI Phase 1) is the structured account of what the tool actually did,
73 /// which the agent loop forwards to its `ToolEventSink` — see
74 /// `crate::tools::telemetry` for why this rides on the result rather than
75 /// each tool holding a sink. `None` for every tool that has nothing
76 /// structured to report, which is all but the retrieval tools.
77 Success {
78 text: String,
79 telemetry: Option<Box<ToolTelemetry>>,
80 },
81 /// Tool failed; `message` describes why; `recoverable` advises the LLM loop.
82 Error { message: String, recoverable: bool },
83}
84
85impl ToolResult {
86 /// Construct a successful result with no telemetry.
87 ///
88 /// Why: Single canonical happy-path constructor used by every tool. Tools
89 /// with structured telemetry chain [`Self::with_telemetry`] onto this
90 /// rather than needing a second constructor.
91 /// What: Wraps `s` in `Success` with `telemetry: None`.
92 /// Test: Trivially exercised by every successful tool execute().
93 pub fn ok(s: impl Into<String>) -> Self {
94 ToolResult::Success {
95 text: s.into(),
96 telemetry: None,
97 }
98 }
99
100 /// Attach structured telemetry to a successful result (UI Phase 1).
101 ///
102 /// Why: lets a tool report what it actually did (real search lane, which
103 /// memories entered context) without knowing which agent runs it or
104 /// owning an event sink — see `crate::tools::telemetry`'s module docs.
105 /// What: builder-style; a no-op on an `Error` result, because the event
106 /// shapes this feeds describe work that produced results, and an errored
107 /// tool has none to describe — its failure is already narrated by
108 /// `ToolFinished`/`ToolError`.
109 /// Test: `tests::tool_result_carries_optional_telemetry`,
110 /// `tests::with_telemetry_is_a_no_op_on_error`.
111 pub fn with_telemetry(self, telemetry: ToolTelemetry) -> Self {
112 match self {
113 ToolResult::Success { text, .. } => ToolResult::Success {
114 text,
115 telemetry: Some(Box::new(telemetry)),
116 },
117 error => error,
118 }
119 }
120
121 /// The structured telemetry this result carries, if any (UI Phase 1).
122 ///
123 /// Why: the agent loop reads this after every dispatch to decide whether
124 /// to emit a structured event alongside the generic tool events.
125 /// What: `None` for errors and for any tool that reported none.
126 /// Test: `tests::tool_result_carries_optional_telemetry`.
127 pub fn telemetry(&self) -> Option<&ToolTelemetry> {
128 match self {
129 ToolResult::Success { telemetry, .. } => telemetry.as_deref(),
130 ToolResult::Error { .. } => None,
131 }
132 }
133
134 /// Construct a recoverable error.
135 ///
136 /// Why: Most tool failures are non-fatal — wrong arg, transient network,
137 /// empty result. The LLM should see the error and decide.
138 /// What: Wraps `msg` with `recoverable = true`.
139 /// Test: Exercised by delegate and registry tests.
140 pub fn err(msg: impl Into<String>) -> Self {
141 ToolResult::Error {
142 message: msg.into(),
143 recoverable: true,
144 }
145 }
146
147 /// Construct a fatal (non-recoverable) error.
148 ///
149 /// Why: Some failures (invariant violations, credential rejection) should
150 /// not be retried; callers should bail.
151 /// What: Wraps `msg` with `recoverable = false`.
152 /// Test: Checked by `is_fatal` predicates in tests.
153 pub fn fatal(msg: impl Into<String>) -> Self {
154 ToolResult::Error {
155 message: msg.into(),
156 recoverable: false,
157 }
158 }
159
160 /// Whether this result is an error variant.
161 ///
162 /// Why: Dispatch paths need a cheap predicate to log/branch on failure.
163 /// What: Returns `true` for any `Error`, `false` for `Success`.
164 /// Test: `ToolResult::err("x").is_error()` is true.
165 pub fn is_error(&self) -> bool {
166 matches!(self, ToolResult::Error { .. })
167 }
168
169 /// Whether this error is fatal (not recoverable). `false` for Success.
170 ///
171 /// Why: Callers that distinguish fatal-vs-recoverable need this to decide
172 /// whether to retry or bail.
173 /// What: True only for `Error { recoverable: false, .. }`.
174 /// Test: `ToolResult::fatal("x").is_fatal()` is true.
175 pub fn is_fatal(&self) -> bool {
176 matches!(
177 self,
178 ToolResult::Error {
179 recoverable: false,
180 ..
181 }
182 )
183 }
184
185 /// Extract the message string for both variants.
186 ///
187 /// Why: Callers like the LLM loop need the raw string regardless of
188 /// success/failure to pass back as `tool_result` content.
189 /// What: Returns the payload string for both `Success` and `Error`.
190 /// Test: `ToolResult::ok("hi").content()` == "hi";
191 /// `ToolResult::err("oops").content()` == "oops".
192 pub fn content(&self) -> &str {
193 match self {
194 ToolResult::Success { text, .. } => text.as_str(),
195 ToolResult::Error { message, .. } => message.as_str(),
196 }
197 }
198}
199
200// ── ToolExecutor ─────────────────────────────────────────────────────────────
201//
202// `ServiceTier` (access tiers controlling which users/transports may invoke a
203// tool) is re-exported from `trusty-agents-common` above (#2893) rather than
204// redeclared here.
205
206/// Object-safe executor interface for a single named tool.
207///
208/// Why: Abstracts over all tool kinds (fs, shell, web search, delegate, MCP
209/// bridge) so the registry and dispatch loop are tool-agnostic. New tools drop
210/// in by implementing this trait without touching the PM loop.
211/// What: `name()` is the string key used in LLM function calls; `schema()`
212/// emits the JSON function descriptor; `execute(args)` performs the action.
213/// Test: `ToolRegistry` tests register a `MockTool` implementing this trait.
214#[async_trait]
215pub trait ToolExecutor: Send + Sync {
216 /// The tool's function name as exposed to the LLM.
217 fn name(&self) -> &str;
218
219 /// JSON schema describing the tool's parameters (OpenAI function format).
220 fn schema(&self) -> Value;
221
222 /// Execute the tool with the given JSON argument object.
223 async fn execute(&self, args: Value) -> ToolResult;
224
225 /// Access tiers that are **blocked** from calling this tool.
226 ///
227 /// Why: Tools declare which tiers they restrict; an empty list means
228 /// universally accessible. This inverted model means adding RBAC to
229 /// existing tools is a no-op by default.
230 /// What: Returns a slice of `ServiceTier` values that are NOT allowed.
231 /// Test: `rbac::tests::can_access_tier_*`.
232 fn restricted_tiers(&self) -> &[ServiceTier] {
233 &[]
234 }
235}
236
237// ── RunContext ───────────────────────────────────────────────────────────────
238//
239// `RunContext` (per-invocation context threaded from orchestrator to agent
240// runner) is re-exported from `trusty-agents-common::runner` above (#2893)
241// rather than redeclared here — the two definitions were byte-identical.
242
243// ── AgentOutput ──────────────────────────────────────────────────────────────
244
245/// Structured output returned by an `AgentRunner`.
246///
247/// Why: Downstream phases need a concise `summary` for template substitution
248/// while also needing the full `content` for file extraction. Bundling them
249/// avoids separate trait methods. (#2683) A delegated engineer's caller (the
250/// PM's `delegate_to_agent` tool) also needs to know whether the agent
251/// terminated by an EXPLICIT, successful `finish_task` completion — that is the
252/// authoritative "the task is genuinely done" signal used to prevent a
253/// gratuitous post-finish re-delegation from mislabeling a complete run.
254/// What: `content` is raw agent output; `summary` is the extracted `## Summary`
255/// section (or a prefix fallback); `finish_status` (#2683) is `Some` only when
256/// the loop ended via an accepted `finish_task` call, carrying that call's
257/// reported status.
258/// Test: Constructed from IPC result messages in integration paths;
259/// `finish_status` propagation is covered by
260/// `agent_loop::tests::explicit_finish_task_terminates_loop_with_structured_summary`
261/// and `tools::delegate::tests::completion_signal_latches_on_completed_finish`.
262#[derive(Debug, Clone)]
263pub struct AgentOutput {
264 /// Raw output from the agent.
265 pub content: String,
266 /// Extracted summary (e.g. `## Summary` section), if present.
267 pub summary: Option<String>,
268 /// Aggregated LLM token usage for this invocation.
269 pub usage: crate::perf::TokenUsage,
270 /// The status of an explicit `finish_task` completion, if the loop ended
271 /// via one (#2683). `None` when the run ended any other way (turn cap,
272 /// timeout, a plain no-tool-call stop, or an error).
273 pub finish_status: Option<crate::tools::finish_task::FinishStatus>,
274}
275
276impl AgentOutput {
277 /// Build from content alone; summary/usage will be defaults.
278 ///
279 /// Why: Convenience constructor for simple agent results.
280 /// What: Sets `content`, leaves `summary` None, `usage` zeroed, and
281 /// `finish_status` None (no explicit finish observed).
282 /// Test: Used in mock runners throughout this crate's tests.
283 pub fn from_content(content: impl Into<String>) -> Self {
284 Self {
285 content: content.into(),
286 summary: None,
287 usage: crate::perf::TokenUsage::default(),
288 finish_status: None,
289 }
290 }
291
292 /// Return summary if present, else fall back to content.
293 ///
294 /// Why: Callers that want a short form for template injection should not
295 /// have to branch on `Option`.
296 /// What: Returns `&summary` if `Some`, otherwise `&content`.
297 /// Test: `agent_output_summary_or_content_fallback`.
298 pub fn summary_or_content(&self) -> &str {
299 self.summary.as_deref().unwrap_or(&self.content)
300 }
301}
302
303// ── AgentRunner ──────────────────────────────────────────────────────────────
304
305/// Runs a task against a named agent.
306///
307/// Why: Abstracts over how an agent is executed — subprocess, in-process, or
308/// mock. Lets tests avoid spawning real processes.
309/// What: `run(agent_name, task)` returns the agent's `AgentOutput`.
310/// `run_with_context` extends this to pass per-invocation overrides; the
311/// default forwards to `run()` so existing mock runners keep working.
312/// Test: `MockAgentRunner` in tests implements this; `test_run_with_history_forwards_ctx`
313/// verifies the default delegation chain.
314#[async_trait]
315pub trait AgentRunner: Send + Sync {
316 /// Run a task against the named agent.
317 async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;
318
319 /// Run with per-invocation overrides in `ctx`.
320 ///
321 /// Why: Replaces `std::env::set_var` threading of per-call state. Default
322 /// impl ignores `ctx` and falls back to `run()` so legacy mock runners
323 /// keep working unchanged.
324 /// What: Concrete runners override this to scope env vars to the child.
325 /// Test: Wave-loop and runner tests prove context fields reach the child.
326 async fn run_with_context(
327 &self,
328 agent_name: &str,
329 task: &str,
330 _ctx: &RunContext,
331 ) -> Result<AgentOutput> {
332 self.run(agent_name, task).await
333 }
334
335 /// Run a task while forwarding prior session history.
336 ///
337 /// Why: Persistent-session agents need prior turns so the sub-agent can
338 /// rebuild context in a fresh subprocess.
339 /// What: Default delegates to `run_with_context(ctx)` so `working_dir`
340 /// and `model` are honoured even when the runner does not override this.
341 /// Test: `test_run_with_history_forwards_ctx`.
342 async fn run_with_history(
343 &self,
344 agent_name: &str,
345 task: &str,
346 _history: &[HistoryMessage],
347 ctx: &RunContext,
348 ) -> Result<AgentOutput> {
349 self.run_with_context(agent_name, task, ctx).await
350 }
351}
352
353// ── HistoryMessage ───────────────────────────────────────────────────────────
354//
355// `HistoryMessage` (a prior conversation turn forwarded to persistent-session
356// agents, used by `AgentRunner::run_with_history` below) is re-exported from
357// `trusty-agents-common::runner` above (#2893) rather than redeclared here —
358// tcode's fields (`role`, `content`) were a strict subset of the shared type
359// (which additionally derives `PartialEq`/`Eq` and adds `user()`/`assistant()`
360// constructors). Not to be confused with `crate::ipc::HistoryMessage`, a
361// separate NDJSON wire type for the PM<->sub-agent IPC protocol.
362
363// ── SearchProvider ───────────────────────────────────────────────────────────
364
365/// A search hit returned by a `SearchProvider`.
366///
367/// Why: Uniform result type for web/code search so callers are provider-agnostic.
368/// What: `title`, `url`, `snippet` — the minimal useful set.
369/// Test: Used in `SearchProvider` mock tests.
370#[derive(Debug, Clone, Serialize, Deserialize)]
371pub struct SearchResult {
372 pub title: String,
373 pub url: String,
374 pub snippet: String,
375}
376
377/// Web/code search backend abstraction.
378///
379/// Why: Swap Brave for Tavily / DuckDuckGo / a test stub by changing the
380/// registered impl — no callers change.
381/// What: `search(query, n)` returns up to `n` results.
382/// Test: A stub `SearchProvider` returns a fixed vector in mock tests.
383#[async_trait]
384pub trait SearchProvider: Send + Sync {
385 /// Run a search for `query` and return up to `n` results.
386 async fn search(&self, query: &str, n: usize) -> Result<Vec<SearchResult>>;
387}
388
389// ── SkillResolver ────────────────────────────────────────────────────────────
390
391/// Resolves named skills to their Markdown content.
392///
393/// Why: Skill sources vary (project `.claude/`, user `~/.claude/`, bundled
394/// config); callers should not care which. #2069 splits skills into cheap,
395/// always-cached metadata (name + description) and an on-demand-loaded body
396/// so the PM/agents can see the full catalog without paying every skill's
397/// token cost up front — `metadata()` is the cached catalog, `resolve()` is
398/// the lazy, per-invocation body load.
399/// What: `resolve(name)` returns `Some(content)` if found. `list()` returns
400/// all discoverable names. `metadata()` returns the full cached
401/// `SkillMetadata` catalog (name + description), the progressive-disclosure
402/// prompt injection uses.
403/// Test: `crate::skills::tests::fs_skill_resolver_*` construct an
404/// `FsSkillResolver` (this trait's concrete filesystem impl) over a tempdir
405/// and assert `resolve()`/`list()`/`metadata()` all agree.
406pub trait SkillResolver: Send + Sync {
407 /// Look up a skill by name and return its Markdown content, if found.
408 fn resolve(&self, name: &str) -> Option<String>;
409 /// List all discoverable skill names.
410 fn list(&self) -> Vec<String>;
411 /// Cached metadata (name + description) for every discoverable skill.
412 fn metadata(&self) -> Vec<crate::skills::SkillMetadata>;
413}
414
415// ── Tests ─────────────────────────────────────────────────────────────────────
416
417#[cfg(test)]
418mod tests {
419 use std::path::PathBuf;
420 use std::sync::{Arc, Mutex};
421
422 use anyhow::Result;
423 use async_trait::async_trait;
424
425 use super::*;
426 use crate::perf::TokenUsage;
427
428 /// Mock runner that records the `RunContext` received in `run_with_context`.
429 ///
430 /// Why: We need to assert that the default `run_with_history` impl actually
431 /// forwards `ctx` to `run_with_context` (regression guard).
432 /// What: Records each ctx snapshot; `run` is unused in this test.
433 /// Test: `test_run_with_history_forwards_ctx`.
434 struct CtxCapture {
435 captured: Arc<Mutex<Vec<RunContext>>>,
436 }
437
438 #[async_trait]
439 impl AgentRunner for CtxCapture {
440 async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
441 Ok(AgentOutput::from_content("run"))
442 }
443
444 async fn run_with_context(
445 &self,
446 _agent_name: &str,
447 _task: &str,
448 ctx: &RunContext,
449 ) -> Result<AgentOutput> {
450 self.captured
451 .lock()
452 .expect("lock poisoned")
453 .push(ctx.clone());
454 Ok(AgentOutput::from_content("run_with_context"))
455 }
456 // NOTE: run_with_history is intentionally NOT overridden — we test the
457 // default impl defined in the trait.
458 }
459
460 /// Verifies that the default `run_with_history` forwards `ctx` to
461 /// `run_with_context` rather than dropping it.
462 ///
463 /// Why: Without this, persistent-session agents lose `working_dir` and
464 /// `model` when the default implementation falls through.
465 /// What: Calls `run_with_history` with specific `working_dir` and `model`,
466 /// then asserts `run_with_context` received those values.
467 /// Test: This test itself.
468 #[tokio::test]
469 async fn test_run_with_history_forwards_ctx() {
470 let captured = Arc::new(Mutex::new(Vec::new()));
471 let runner = CtxCapture {
472 captured: captured.clone(),
473 };
474
475 let ctx = RunContext {
476 working_dir: Some(PathBuf::from("/tmp/test-wd")),
477 model: Some("anthropic/claude-opus-4-5".to_string()),
478 max_turns_override: Some(5),
479 assigned_file: None,
480 };
481
482 let out = runner
483 .run_with_history("test-agent", "do something", &[], &ctx)
484 .await
485 .expect("run_with_history should succeed");
486
487 assert_eq!(
488 out.content, "run_with_context",
489 "default run_with_history must call run_with_context, not run()"
490 );
491
492 let snaps = captured.lock().expect("lock poisoned");
493 assert_eq!(
494 snaps.len(),
495 1,
496 "run_with_context must be called exactly once"
497 );
498
499 let recorded = &snaps[0];
500 assert_eq!(
501 recorded.working_dir,
502 Some(PathBuf::from("/tmp/test-wd")),
503 "working_dir must be forwarded"
504 );
505 assert_eq!(
506 recorded.model,
507 Some("anthropic/claude-opus-4-5".to_string()),
508 "model must be forwarded"
509 );
510 assert_eq!(
511 recorded.max_turns_override,
512 Some(5),
513 "max_turns_override must be forwarded"
514 );
515 }
516
517 /// Verify `ToolResult` predicates and content accessor.
518 ///
519 /// Why: Guard the semantics of `is_error`, `is_fatal`, and `content`.
520 /// What: Constructs each variant and checks all three predicates.
521 /// Test: This test itself.
522 #[test]
523 fn tool_result_predicates() {
524 let ok = ToolResult::ok("hello");
525 assert!(!ok.is_error());
526 assert!(!ok.is_fatal());
527 assert_eq!(ok.content(), "hello");
528
529 let err = ToolResult::err("oops");
530 assert!(err.is_error());
531 assert!(!err.is_fatal());
532 assert_eq!(err.content(), "oops");
533
534 let fatal = ToolResult::fatal("crash");
535 assert!(fatal.is_error());
536 assert!(fatal.is_fatal());
537 assert_eq!(fatal.content(), "crash");
538 }
539
540 /// A successful result must carry telemetry when a tool attaches it, and
541 /// none by default (UI Phase 1).
542 ///
543 /// Why: `None` by default is what keeps every non-retrieval tool's
544 /// behaviour byte-identical to pre-ticket.
545 /// Test: this test.
546 #[test]
547 fn tool_result_carries_optional_telemetry() {
548 use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};
549
550 assert!(
551 ToolResult::ok("plain").telemetry().is_none(),
552 "tools that report nothing structured must stay unaffected"
553 );
554
555 let telemetry = ToolTelemetry::Search(SearchTelemetry {
556 lane: "semantic".to_string(),
557 query: "q".to_string(),
558 hit_count: Some(3),
559 hits: vec![],
560 latency_ms: 7,
561 });
562 let result = ToolResult::ok("hits").with_telemetry(telemetry.clone());
563 assert_eq!(result.telemetry(), Some(&telemetry));
564 assert_eq!(result.content(), "hits", "the text must be untouched");
565 }
566
567 /// Attaching telemetry to an error must be a no-op (UI Phase 1).
568 ///
569 /// Why: the structured events describe work that produced results; an
570 /// errored tool has none to describe, and its failure is already narrated
571 /// by `ToolFinished`/`ToolError`.
572 /// Test: this test.
573 #[test]
574 fn with_telemetry_is_a_no_op_on_error() {
575 use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};
576
577 let result =
578 ToolResult::err("boom").with_telemetry(ToolTelemetry::Search(SearchTelemetry {
579 lane: "semantic".to_string(),
580 query: "q".to_string(),
581 hit_count: None,
582 hits: vec![],
583 latency_ms: 1,
584 }));
585 assert!(result.is_error());
586 assert!(result.telemetry().is_none());
587 assert_eq!(result.content(), "boom");
588 }
589
590 /// Verify `AgentOutput::summary_or_content` fallback.
591 ///
592 /// Why: Callers rely on this to get a short form without branching.
593 /// What: `summary=Some` returns summary; `summary=None` returns content.
594 /// Test: This test itself.
595 #[test]
596 fn agent_output_summary_or_content_fallback() {
597 let with_summary = AgentOutput {
598 content: "full content".into(),
599 summary: Some("short summary".into()),
600 usage: TokenUsage::default(),
601 finish_status: None,
602 };
603 assert_eq!(with_summary.summary_or_content(), "short summary");
604
605 let no_summary = AgentOutput::from_content("just content");
606 assert_eq!(no_summary.summary_or_content(), "just content");
607 }
608}