trusty-code 0.7.0

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
//! Core trait abstractions for tool execution, agent running, search, and skills.
//!
//! Why: DI through traits lets tcode swap concrete implementations (subprocess
//! runner vs. in-process mock; Brave vs. Tavily search; fs skill store vs.
//! embedded) without changing call sites. This is the SOA seam that keeps
//! the workflow engine and PM loop testable.
//! What: Defines `ToolExecutor`, `AgentRunner`, `SearchProvider`, and
//! `SkillResolver`. All are object-safe (`dyn`-able) and `Send + Sync`.
//!
//! `ServiceTier` and `RunContext`/`HistoryMessage` are byte-for-byte identical
//! to the canonical definitions in `trusty-agents-common` (the same crate
//! `trusty-agents` already re-exports these from — see
//! `crates/trusty-agents/src/tools/traits.rs`) and are re-exported here rather
//! than redeclared (#2893, epic #2892).
//!
//! `ToolExecutor`/`ToolResult` and `AgentRunner`/`AgentOutput` stay LOCAL,
//! deliberately NOT deduped against `trusty-agents-common`, because tcode's
//! versions carry fields the shared ones lack and that must not regress:
//! `ToolResult::Success.telemetry` (`Option<Box<ToolTelemetry>>`, #2862) and
//! `AgentOutput.finish_status` (`Option<FinishStatus>`, #2683; whose
//! `AgentOutput.usage: crate::perf::TokenUsage` also carries a `cost_usd`
//! field the shared `TokenUsage` lacks, #50). Unifying either would require
//! either type-erasing tcode's telemetry (`ToolTelemetry` depends on
//! `crate::events::{SearchHit, RecalledMemory}`, which are not portable to
//! the shared crate without a much larger events-module move) or extending
//! `trusty-agents-common`'s `TokenUsage`/`AgentOutput` and updating every
//! `trusty-agents`/`cto-assistant` call site that pattern-matches
//! `ToolResult::Success` — a real design decision outside this
//! behavior-preserving refactor's scope. See PR discussion for #2893.
//! Test: Mock impls of each trait are constructed in unit tests for
//! `ToolRegistry`, delegating commands, and related code.

use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;

// Why: `ServiceTier` and the `AgentRunner` DI seam types (`RunContext`,
//      `HistoryMessage`) are byte-identical (or a strict derive superset) of
//      trusty-agents-common's canonical definitions — re-exporting instead of
//      redeclaring eliminates ~40 duplicate lines without any behavior change
//      (#2893). `AgentOutput`/`AgentRunner` stay local (see module docs above)
//      so `HistoryMessage` here is the shared type used by the LOCAL
//      `AgentRunner` trait below, not `trusty_agents_common::runner::AgentRunner`.
// What: Re-exports the RBAC tier enum and the runner-context/history types.
// Test: All existing `ServiceTier`/`RunContext`/`HistoryMessage` references in
//       this crate resolve unchanged; `cargo test -p trusty-code` passes.
pub use trusty_agents_common::ServiceTier;
pub use trusty_agents_common::runner::{HistoryMessage, RunContext};

use crate::tools::telemetry::ToolTelemetry;

// ── ToolResult ──────────────────────────────────────────────────────────────

/// Structured result of a tool execution.
///
/// Why: Hard-failing the LLM loop on every tool error is brittle — the model
/// often can recover (retry with different args, fall back to another tool, or
/// explain the failure in its final answer). A structured error lets the caller
/// surface failure back to the LLM as a `tool_result` with `is_error: true`
/// while keeping the loop running.
/// What: `Success` carries a successful textual result plus (UI Phase 1) an
/// optional [`ToolTelemetry`] side-channel; `Error` carries a message plus a
/// `recoverable` flag.
/// Test: `ToolResult::err(...).is_error()` is true; `ok(...).content()` returns
/// the success string. Exercised in `tools::registry` and delegate tests.
#[derive(Debug)]
pub enum ToolResult {
    /// Tool executed successfully.
    ///
    /// `text` is the textual result fed back to the model. `telemetry`
    /// (UI Phase 1) is the structured account of what the tool actually did,
    /// which the agent loop forwards to its `ToolEventSink` — see
    /// `crate::tools::telemetry` for why this rides on the result rather than
    /// each tool holding a sink. `None` for every tool that has nothing
    /// structured to report, which is all but the retrieval tools.
    Success {
        text: String,
        telemetry: Option<Box<ToolTelemetry>>,
    },
    /// Tool failed; `message` describes why; `recoverable` advises the LLM loop.
    Error { message: String, recoverable: bool },
}

impl ToolResult {
    /// Construct a successful result with no telemetry.
    ///
    /// Why: Single canonical happy-path constructor used by every tool. Tools
    /// with structured telemetry chain [`Self::with_telemetry`] onto this
    /// rather than needing a second constructor.
    /// What: Wraps `s` in `Success` with `telemetry: None`.
    /// Test: Trivially exercised by every successful tool execute().
    pub fn ok(s: impl Into<String>) -> Self {
        ToolResult::Success {
            text: s.into(),
            telemetry: None,
        }
    }

    /// Attach structured telemetry to a successful result (UI Phase 1).
    ///
    /// Why: lets a tool report what it actually did (real search lane, which
    /// memories entered context) without knowing which agent runs it or
    /// owning an event sink — see `crate::tools::telemetry`'s module docs.
    /// What: builder-style; a no-op on an `Error` result, because the event
    /// shapes this feeds describe work that produced results, and an errored
    /// tool has none to describe — its failure is already narrated by
    /// `ToolFinished`/`ToolError`.
    /// Test: `tests::tool_result_carries_optional_telemetry`,
    /// `tests::with_telemetry_is_a_no_op_on_error`.
    pub fn with_telemetry(self, telemetry: ToolTelemetry) -> Self {
        match self {
            ToolResult::Success { text, .. } => ToolResult::Success {
                text,
                telemetry: Some(Box::new(telemetry)),
            },
            error => error,
        }
    }

    /// The structured telemetry this result carries, if any (UI Phase 1).
    ///
    /// Why: the agent loop reads this after every dispatch to decide whether
    /// to emit a structured event alongside the generic tool events.
    /// What: `None` for errors and for any tool that reported none.
    /// Test: `tests::tool_result_carries_optional_telemetry`.
    pub fn telemetry(&self) -> Option<&ToolTelemetry> {
        match self {
            ToolResult::Success { telemetry, .. } => telemetry.as_deref(),
            ToolResult::Error { .. } => None,
        }
    }

    /// Construct a recoverable error.
    ///
    /// Why: Most tool failures are non-fatal — wrong arg, transient network,
    /// empty result. The LLM should see the error and decide.
    /// What: Wraps `msg` with `recoverable = true`.
    /// Test: Exercised by delegate and registry tests.
    pub fn err(msg: impl Into<String>) -> Self {
        ToolResult::Error {
            message: msg.into(),
            recoverable: true,
        }
    }

    /// Construct a fatal (non-recoverable) error.
    ///
    /// Why: Some failures (invariant violations, credential rejection) should
    /// not be retried; callers should bail.
    /// What: Wraps `msg` with `recoverable = false`.
    /// Test: Checked by `is_fatal` predicates in tests.
    pub fn fatal(msg: impl Into<String>) -> Self {
        ToolResult::Error {
            message: msg.into(),
            recoverable: false,
        }
    }

    /// Whether this result is an error variant.
    ///
    /// Why: Dispatch paths need a cheap predicate to log/branch on failure.
    /// What: Returns `true` for any `Error`, `false` for `Success`.
    /// Test: `ToolResult::err("x").is_error()` is true.
    pub fn is_error(&self) -> bool {
        matches!(self, ToolResult::Error { .. })
    }

    /// Whether this error is fatal (not recoverable). `false` for Success.
    ///
    /// Why: Callers that distinguish fatal-vs-recoverable need this to decide
    /// whether to retry or bail.
    /// What: True only for `Error { recoverable: false, .. }`.
    /// Test: `ToolResult::fatal("x").is_fatal()` is true.
    pub fn is_fatal(&self) -> bool {
        matches!(
            self,
            ToolResult::Error {
                recoverable: false,
                ..
            }
        )
    }

    /// Extract the message string for both variants.
    ///
    /// Why: Callers like the LLM loop need the raw string regardless of
    /// success/failure to pass back as `tool_result` content.
    /// What: Returns the payload string for both `Success` and `Error`.
    /// Test: `ToolResult::ok("hi").content()` == "hi";
    ///       `ToolResult::err("oops").content()` == "oops".
    pub fn content(&self) -> &str {
        match self {
            ToolResult::Success { text, .. } => text.as_str(),
            ToolResult::Error { message, .. } => message.as_str(),
        }
    }
}

// ── ToolExecutor ─────────────────────────────────────────────────────────────
//
// `ServiceTier` (access tiers controlling which users/transports may invoke a
// tool) is re-exported from `trusty-agents-common` above (#2893) rather than
// redeclared here.

/// Object-safe executor interface for a single named tool.
///
/// Why: Abstracts over all tool kinds (fs, shell, web search, delegate, MCP
/// bridge) so the registry and dispatch loop are tool-agnostic. New tools drop
/// in by implementing this trait without touching the PM loop.
/// What: `name()` is the string key used in LLM function calls; `schema()`
/// emits the JSON function descriptor; `execute(args)` performs the action.
/// Test: `ToolRegistry` tests register a `MockTool` implementing this trait.
#[async_trait]
pub trait ToolExecutor: Send + Sync {
    /// The tool's function name as exposed to the LLM.
    fn name(&self) -> &str;

    /// JSON schema describing the tool's parameters (OpenAI function format).
    fn schema(&self) -> Value;

    /// Execute the tool with the given JSON argument object.
    async fn execute(&self, args: Value) -> ToolResult;

    /// Access tiers that are **blocked** from calling this tool.
    ///
    /// Why: Tools declare which tiers they restrict; an empty list means
    /// universally accessible. This inverted model means adding RBAC to
    /// existing tools is a no-op by default.
    /// What: Returns a slice of `ServiceTier` values that are NOT allowed.
    /// Test: `rbac::tests::can_access_tier_*`.
    fn restricted_tiers(&self) -> &[ServiceTier] {
        &[]
    }
}

// ── RunContext ───────────────────────────────────────────────────────────────
//
// `RunContext` (per-invocation context threaded from orchestrator to agent
// runner) is re-exported from `trusty-agents-common::runner` above (#2893)
// rather than redeclared here — the two definitions were byte-identical.

// ── AgentOutput ──────────────────────────────────────────────────────────────

/// Structured output returned by an `AgentRunner`.
///
/// Why: Downstream phases need a concise `summary` for template substitution
/// while also needing the full `content` for file extraction. Bundling them
/// avoids separate trait methods. (#2683) A delegated engineer's caller (the
/// PM's `delegate_to_agent` tool) also needs to know whether the agent
/// terminated by an EXPLICIT, successful `finish_task` completion — that is the
/// authoritative "the task is genuinely done" signal used to prevent a
/// gratuitous post-finish re-delegation from mislabeling a complete run.
/// What: `content` is raw agent output; `summary` is the extracted `## Summary`
/// section (or a prefix fallback); `finish_status` (#2683) is `Some` only when
/// the loop ended via an accepted `finish_task` call, carrying that call's
/// reported status.
/// Test: Constructed from IPC result messages in integration paths;
/// `finish_status` propagation is covered by
/// `agent_loop::tests::explicit_finish_task_terminates_loop_with_structured_summary`
/// and `tools::delegate::tests::completion_signal_latches_on_completed_finish`.
#[derive(Debug, Clone)]
pub struct AgentOutput {
    /// Raw output from the agent.
    pub content: String,
    /// Extracted summary (e.g. `## Summary` section), if present.
    pub summary: Option<String>,
    /// Aggregated LLM token usage for this invocation.
    pub usage: crate::perf::TokenUsage,
    /// The status of an explicit `finish_task` completion, if the loop ended
    /// via one (#2683). `None` when the run ended any other way (turn cap,
    /// timeout, a plain no-tool-call stop, or an error).
    pub finish_status: Option<crate::tools::finish_task::FinishStatus>,
}

impl AgentOutput {
    /// Build from content alone; summary/usage will be defaults.
    ///
    /// Why: Convenience constructor for simple agent results.
    /// What: Sets `content`, leaves `summary` None, `usage` zeroed, and
    /// `finish_status` None (no explicit finish observed).
    /// Test: Used in mock runners throughout this crate's tests.
    pub fn from_content(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            summary: None,
            usage: crate::perf::TokenUsage::default(),
            finish_status: None,
        }
    }

    /// Return summary if present, else fall back to content.
    ///
    /// Why: Callers that want a short form for template injection should not
    /// have to branch on `Option`.
    /// What: Returns `&summary` if `Some`, otherwise `&content`.
    /// Test: `agent_output_summary_or_content_fallback`.
    pub fn summary_or_content(&self) -> &str {
        self.summary.as_deref().unwrap_or(&self.content)
    }
}

// ── AgentRunner ──────────────────────────────────────────────────────────────

/// Runs a task against a named agent.
///
/// Why: Abstracts over how an agent is executed — subprocess, in-process, or
/// mock. Lets tests avoid spawning real processes.
/// What: `run(agent_name, task)` returns the agent's `AgentOutput`.
/// `run_with_context` extends this to pass per-invocation overrides; the
/// default forwards to `run()` so existing mock runners keep working.
/// Test: `MockAgentRunner` in tests implements this; `test_run_with_history_forwards_ctx`
/// verifies the default delegation chain.
#[async_trait]
pub trait AgentRunner: Send + Sync {
    /// Run a task against the named agent.
    async fn run(&self, agent_name: &str, task: &str) -> Result<AgentOutput>;

    /// Run with per-invocation overrides in `ctx`.
    ///
    /// Why: Replaces `std::env::set_var` threading of per-call state. Default
    /// impl ignores `ctx` and falls back to `run()` so legacy mock runners
    /// keep working unchanged.
    /// What: Concrete runners override this to scope env vars to the child.
    /// Test: Wave-loop and runner tests prove context fields reach the child.
    async fn run_with_context(
        &self,
        agent_name: &str,
        task: &str,
        _ctx: &RunContext,
    ) -> Result<AgentOutput> {
        self.run(agent_name, task).await
    }

    /// Run a task while forwarding prior session history.
    ///
    /// Why: Persistent-session agents need prior turns so the sub-agent can
    /// rebuild context in a fresh subprocess.
    /// What: Default delegates to `run_with_context(ctx)` so `working_dir`
    /// and `model` are honoured even when the runner does not override this.
    /// Test: `test_run_with_history_forwards_ctx`.
    async fn run_with_history(
        &self,
        agent_name: &str,
        task: &str,
        _history: &[HistoryMessage],
        ctx: &RunContext,
    ) -> Result<AgentOutput> {
        self.run_with_context(agent_name, task, ctx).await
    }
}

// ── HistoryMessage ───────────────────────────────────────────────────────────
//
// `HistoryMessage` (a prior conversation turn forwarded to persistent-session
// agents, used by `AgentRunner::run_with_history` below) is re-exported from
// `trusty-agents-common::runner` above (#2893) rather than redeclared here —
// tcode's fields (`role`, `content`) were a strict subset of the shared type
// (which additionally derives `PartialEq`/`Eq` and adds `user()`/`assistant()`
// constructors). Not to be confused with `crate::ipc::HistoryMessage`, a
// separate NDJSON wire type for the PM<->sub-agent IPC protocol.

// ── SearchProvider ───────────────────────────────────────────────────────────

/// A search hit returned by a `SearchProvider`.
///
/// Why: Uniform result type for web/code search so callers are provider-agnostic.
/// What: `title`, `url`, `snippet` — the minimal useful set.
/// Test: Used in `SearchProvider` mock tests.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SearchResult {
    pub title: String,
    pub url: String,
    pub snippet: String,
}

/// Web/code search backend abstraction.
///
/// Why: Swap Brave for Tavily / DuckDuckGo / a test stub by changing the
/// registered impl — no callers change.
/// What: `search(query, n)` returns up to `n` results.
/// Test: A stub `SearchProvider` returns a fixed vector in mock tests.
#[async_trait]
pub trait SearchProvider: Send + Sync {
    /// Run a search for `query` and return up to `n` results.
    async fn search(&self, query: &str, n: usize) -> Result<Vec<SearchResult>>;
}

// ── SkillResolver ────────────────────────────────────────────────────────────

/// Resolves named skills to their Markdown content.
///
/// Why: Skill sources vary (project `.claude/`, user `~/.claude/`, bundled
/// config); callers should not care which. #2069 splits skills into cheap,
/// always-cached metadata (name + description) and an on-demand-loaded body
/// so the PM/agents can see the full catalog without paying every skill's
/// token cost up front — `metadata()` is the cached catalog, `resolve()` is
/// the lazy, per-invocation body load.
/// What: `resolve(name)` returns `Some(content)` if found. `list()` returns
/// all discoverable names. `metadata()` returns the full cached
/// `SkillMetadata` catalog (name + description), the progressive-disclosure
/// prompt injection uses.
/// Test: `crate::skills::tests::fs_skill_resolver_*` construct an
/// `FsSkillResolver` (this trait's concrete filesystem impl) over a tempdir
/// and assert `resolve()`/`list()`/`metadata()` all agree.
pub trait SkillResolver: Send + Sync {
    /// Look up a skill by name and return its Markdown content, if found.
    fn resolve(&self, name: &str) -> Option<String>;
    /// List all discoverable skill names.
    fn list(&self) -> Vec<String>;
    /// Cached metadata (name + description) for every discoverable skill.
    fn metadata(&self) -> Vec<crate::skills::SkillMetadata>;
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use std::path::PathBuf;
    use std::sync::{Arc, Mutex};

    use anyhow::Result;
    use async_trait::async_trait;

    use super::*;
    use crate::perf::TokenUsage;

    /// Mock runner that records the `RunContext` received in `run_with_context`.
    ///
    /// Why: We need to assert that the default `run_with_history` impl actually
    /// forwards `ctx` to `run_with_context` (regression guard).
    /// What: Records each ctx snapshot; `run` is unused in this test.
    /// Test: `test_run_with_history_forwards_ctx`.
    struct CtxCapture {
        captured: Arc<Mutex<Vec<RunContext>>>,
    }

    #[async_trait]
    impl AgentRunner for CtxCapture {
        async fn run(&self, _agent_name: &str, _task: &str) -> Result<AgentOutput> {
            Ok(AgentOutput::from_content("run"))
        }

        async fn run_with_context(
            &self,
            _agent_name: &str,
            _task: &str,
            ctx: &RunContext,
        ) -> Result<AgentOutput> {
            self.captured
                .lock()
                .expect("lock poisoned")
                .push(ctx.clone());
            Ok(AgentOutput::from_content("run_with_context"))
        }
        // NOTE: run_with_history is intentionally NOT overridden — we test the
        // default impl defined in the trait.
    }

    /// Verifies that the default `run_with_history` forwards `ctx` to
    /// `run_with_context` rather than dropping it.
    ///
    /// Why: Without this, persistent-session agents lose `working_dir` and
    /// `model` when the default implementation falls through.
    /// What: Calls `run_with_history` with specific `working_dir` and `model`,
    /// then asserts `run_with_context` received those values.
    /// Test: This test itself.
    #[tokio::test]
    async fn test_run_with_history_forwards_ctx() {
        let captured = Arc::new(Mutex::new(Vec::new()));
        let runner = CtxCapture {
            captured: captured.clone(),
        };

        let ctx = RunContext {
            working_dir: Some(PathBuf::from("/tmp/test-wd")),
            model: Some("anthropic/claude-opus-4-5".to_string()),
            max_turns_override: Some(5),
            assigned_file: None,
        };

        let out = runner
            .run_with_history("test-agent", "do something", &[], &ctx)
            .await
            .expect("run_with_history should succeed");

        assert_eq!(
            out.content, "run_with_context",
            "default run_with_history must call run_with_context, not run()"
        );

        let snaps = captured.lock().expect("lock poisoned");
        assert_eq!(
            snaps.len(),
            1,
            "run_with_context must be called exactly once"
        );

        let recorded = &snaps[0];
        assert_eq!(
            recorded.working_dir,
            Some(PathBuf::from("/tmp/test-wd")),
            "working_dir must be forwarded"
        );
        assert_eq!(
            recorded.model,
            Some("anthropic/claude-opus-4-5".to_string()),
            "model must be forwarded"
        );
        assert_eq!(
            recorded.max_turns_override,
            Some(5),
            "max_turns_override must be forwarded"
        );
    }

    /// Verify `ToolResult` predicates and content accessor.
    ///
    /// Why: Guard the semantics of `is_error`, `is_fatal`, and `content`.
    /// What: Constructs each variant and checks all three predicates.
    /// Test: This test itself.
    #[test]
    fn tool_result_predicates() {
        let ok = ToolResult::ok("hello");
        assert!(!ok.is_error());
        assert!(!ok.is_fatal());
        assert_eq!(ok.content(), "hello");

        let err = ToolResult::err("oops");
        assert!(err.is_error());
        assert!(!err.is_fatal());
        assert_eq!(err.content(), "oops");

        let fatal = ToolResult::fatal("crash");
        assert!(fatal.is_error());
        assert!(fatal.is_fatal());
        assert_eq!(fatal.content(), "crash");
    }

    /// A successful result must carry telemetry when a tool attaches it, and
    /// none by default (UI Phase 1).
    ///
    /// Why: `None` by default is what keeps every non-retrieval tool's
    /// behaviour byte-identical to pre-ticket.
    /// Test: this test.
    #[test]
    fn tool_result_carries_optional_telemetry() {
        use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};

        assert!(
            ToolResult::ok("plain").telemetry().is_none(),
            "tools that report nothing structured must stay unaffected"
        );

        let telemetry = ToolTelemetry::Search(SearchTelemetry {
            lane: "semantic".to_string(),
            query: "q".to_string(),
            hit_count: Some(3),
            hits: vec![],
            latency_ms: 7,
        });
        let result = ToolResult::ok("hits").with_telemetry(telemetry.clone());
        assert_eq!(result.telemetry(), Some(&telemetry));
        assert_eq!(result.content(), "hits", "the text must be untouched");
    }

    /// Attaching telemetry to an error must be a no-op (UI Phase 1).
    ///
    /// Why: the structured events describe work that produced results; an
    /// errored tool has none to describe, and its failure is already narrated
    /// by `ToolFinished`/`ToolError`.
    /// Test: this test.
    #[test]
    fn with_telemetry_is_a_no_op_on_error() {
        use crate::tools::telemetry::{SearchTelemetry, ToolTelemetry};

        let result =
            ToolResult::err("boom").with_telemetry(ToolTelemetry::Search(SearchTelemetry {
                lane: "semantic".to_string(),
                query: "q".to_string(),
                hit_count: None,
                hits: vec![],
                latency_ms: 1,
            }));
        assert!(result.is_error());
        assert!(result.telemetry().is_none());
        assert_eq!(result.content(), "boom");
    }

    /// Verify `AgentOutput::summary_or_content` fallback.
    ///
    /// Why: Callers rely on this to get a short form without branching.
    /// What: `summary=Some` returns summary; `summary=None` returns content.
    /// Test: This test itself.
    #[test]
    fn agent_output_summary_or_content_fallback() {
        let with_summary = AgentOutput {
            content: "full content".into(),
            summary: Some("short summary".into()),
            usage: TokenUsage::default(),
            finish_status: None,
        };
        assert_eq!(with_summary.summary_or_content(), "short summary");

        let no_summary = AgentOutput::from_content("just content");
        assert_eq!(no_summary.summary_or_content(), "just content");
    }
}