返回 CodeWhale
advisor.rs
根目录 / crates / engine / src / tools / subagent / advisor.rs
1 //! Background advisor watcher (#3982).
2 //!
3 //! When enabled, the advisor wakes on turn boundaries, reads a bounded slice
4 //! of recent tool calls from the session transcript, makes a concise LLM
5 //! advisory call on an exactly resolved provider/model client, and
6 //! emits an [`Event::AdvisoryNote`] fire-and-forget.
7 //!
8 //! Key design properties:
9 //! - **Off by default** — enabled via `[advisor] enabled = true` or `/advisor on`.
10 //! - **Bounded input** — at most `max_tool_calls` tool-call/result pairs are
11 //! included; the rest are dropped oldest-first.
12 //! - **Rate-limited** — at most one emission per `rate_limit_secs` seconds.
13 //! - **Deduplicated** — notes whose content hash matches the previous note
14 //! within `dedup_window_secs` are silently dropped.
15 //! - **Child-failure isolated** — advisor errors are logged but never surface
16 //! as parent turn failures.
17 //! - **Policy-bounded** — the advisor uses a read-only reviewer prompt and
18 //! no tool access; it cannot exceed the parent session policy.
19
20 use std::collections::hash_map::DefaultHasher;
21 use std::hash::{Hash, Hasher};
22 use std::time::{Duration, Instant};
23
24 use codewhale_config::AdvisorConfigToml;
25 use tokio::sync::mpsc;
26 use tracing::debug;
27
28 use crate::client::CodewhaleClient;
29 use crate::core::events::Event;
30 use crate::llm_client::LlmClient;
31 use codewhale_models::Role;
32 use codewhale_models::{ContentBlock, Message, MessageRequest, SystemPrompt};
33 use codewhale_runtime::config::Config;
34 use codewhale_util::utils::truncate_with_ellipsis;
35
36 /// Maximum tokens the advisor may generate. Kept short so the note stays
37 /// concise and does not compete with the parent turn's billing budget.
38 const ADVISOR_MAX_TOKENS: u32 = 256;
39
40 /// Maximum characters of tool input + result to include per tool-call pair.
41 const MAX_CHARS_PER_PAIR: usize = 800;
42
43 /// System prompt for the advisor LLM call. Read-only review posture — no
44 /// tool access, no code generation.
45 const ADVISOR_SYSTEM_PROMPT: &str = "You are a concise background advisor reviewing recent tool activity. \
46 Your role: identify one or two concrete concerns (correctness, risk, or \
47 missed alternatives) in the tool calls provided. \
48 If nothing notable stands out, respond with exactly the word \"ok\". \
49 Otherwise write one to three short sentences — no preamble, no markdown, \
50 no praise. Focus on signal; omit noise.";
51
52 /// A single tool-call/result pair extracted from the session transcript.
53 #[derive(Debug, Clone)]
54 pub struct ToolCallPair {
55 /// Tool name (e.g. `exec_shell`, `file_write`).
56 pub name: String,
57 /// Bounded serialization of the tool input.
58 pub input_preview: String,
59 /// Bounded serialization of the tool result.
60 pub result_preview: String,
61 }
62
63 /// Resolved advisor configuration derived from [`AdvisorConfigToml`].
64 #[derive(Debug, Clone)]
65 pub struct AdvisorConfig {
66 /// Whether the advisor is currently enabled (session-level toggle).
67 pub enabled: bool,
68 /// Max tool-call pairs to review per turn.
69 pub max_tool_calls: u32,
70 /// Min seconds between consecutive emissions.
71 pub rate_limit: Duration,
72 /// Window during which duplicate notes are suppressed.
73 pub dedup_window: Duration,
74 /// Optional model override (falls back to session model when `None`).
75 pub model: Option<String>,
76 }
77
78 impl AdvisorConfig {
79 /// Build a resolved config from the TOML schema.
80 #[must_use]
81 pub fn from_toml(toml: &AdvisorConfigToml) -> Self {
82 Self {
83 enabled: toml.enabled,
84 max_tool_calls: toml.max_tool_calls.clamp(1, 50),
85 rate_limit: Duration::from_secs(toml.rate_limit_secs.clamp(5, 3600)),
86 dedup_window: Duration::from_secs(toml.dedup_window_secs),
87 model: toml.model.clone(),
88 }
89 }
90
91 /// Default disabled config (matches `[advisor]` absent from config.toml).
92 #[must_use]
93 pub fn disabled() -> Self {
94 Self {
95 enabled: false,
96 max_tool_calls: 10,
97 rate_limit: Duration::from_secs(60),
98 dedup_window: Duration::from_secs(300),
99 model: None,
100 }
101 }
102 }
103
104 /// Runtime emission guard: tracks the last emission time and the hash of the
105 /// last advisory note to enforce rate limiting and deduplication.
106 #[derive(Debug)]
107 pub struct EmissionGuard {
108 last_emission: Option<Instant>,
109 last_note_hash: Option<u64>,
110 last_note_hash_at: Option<Instant>,
111 }
112
113 /// Accounting ownership captured while the originating turn is still live.
114 ///
115 #[derive(Debug)]
116 pub struct AdvisorUsageContext {
117 cost_scope: crate::cost_status::CostScopeToken,
118 source: crate::cost_status::NativeUsageSource,
119 }
120
121 impl AdvisorUsageContext {
122 #[must_use]
123 pub fn capture(accounting_origin: Option<crate::cost_status::NativeUsageOrigin>) -> Self {
124 let cost_scope = accounting_origin.as_ref().map_or_else(
125 crate::cost_status::scope_token,
126 crate::cost_status::NativeUsageOrigin::scope,
127 );
128 Self {
129 cost_scope,
130 source: crate::cost_status::NativeUsageSource::capture_with_origin(
131 format!("advisor:{}", uuid::Uuid::new_v4()),
132 crate::cost_status::UsageSpendOwner::Auxiliary,
133 accounting_origin,
134 ),
135 }
136 }
137 }
138
139 impl EmissionGuard {
140 /// Create a fresh guard with no emission history.
141 #[must_use]
142 pub fn new() -> Self {
143 Self {
144 last_emission: None,
145 last_note_hash: None,
146 last_note_hash_at: None,
147 }
148 }
149
150 /// Check whether emitting `note` is allowed under `config`'s rate-limit
151 /// and dedup policy. Returns `true` when the note may be emitted.
152 #[must_use]
153 pub fn may_emit(&self, note: &str, config: &AdvisorConfig) -> bool {
154 // Suppress trivial "ok" responses from the model.
155 if note.trim().eq_ignore_ascii_case("ok") {
156 return false;
157 }
158
159 let now = Instant::now();
160
161 // Rate limit: require at least `rate_limit` since last emission.
162 if let Some(last) = self.last_emission
163 && now.duration_since(last) < config.rate_limit
164 {
165 return false;
166 }
167
168 // Dedup: suppress if the note content hash matches the previous note
169 // within the dedup window.
170 let note_hash = hash_str(note);
171 if let (Some(prev_hash), Some(prev_at)) = (self.last_note_hash, self.last_note_hash_at)
172 && prev_hash == note_hash
173 && now.duration_since(prev_at) < config.dedup_window
174 {
175 return false;
176 }
177
178 true
179 }
180
181 /// Record that `note` was emitted now. Must be called immediately after
182 /// sending the `AdvisoryNote` event.
183 pub fn record_emission(&mut self, note: &str) {
184 let now = Instant::now();
185 self.last_emission = Some(now);
186 self.last_note_hash = Some(hash_str(note));
187 self.last_note_hash_at = Some(now);
188 }
189 }
190
191 impl Default for EmissionGuard {
192 fn default() -> Self {
193 Self::new()
194 }
195 }
196
197 /// Extract bounded tool-call/result pairs from a session message slice.
198 ///
199 /// Takes the newest `max_pairs` tool calls, then returns their unambiguous
200 /// pairs oldest-first. Missing results remain pending; corrupt or ambiguous
201 /// identities are omitted rather than borrowing another execution's output.
202 #[must_use]
203 pub fn extract_tool_call_pairs(messages: &[Message], max_pairs: usize) -> Vec<ToolCallPair> {
204 let mut uses = Vec::new();
205 let mut use_counts = std::collections::HashMap::new();
206 let mut results = std::collections::HashMap::new();
207
208 for msg in messages {
209 for block in &msg.content {
210 let Some(key) = block.tool_call_key() else {
211 continue;
212 };
213 match block {
214 ContentBlock::ToolUse {
215 id, name, input, ..
216 } => {
217 let input_str = truncate_with_ellipsis(
218 &serde_json::to_string(input).unwrap_or_default(),
219 MAX_CHARS_PER_PAIR / 2,
220 "…",
221 );
222 *use_counts.entry(key).or_insert(0usize) += 1;
223 uses.push((key, id.as_str(), name.as_str(), input_str));
224 }
225 ContentBlock::ToolResult {
226 tool_use_id,
227 content,
228 ..
229 } => {
230 results
231 .entry(key)
232 .and_modify(|result| *result = None)
233 .or_insert_with(|| {
234 Some((
235 tool_use_id.as_str(),
236 truncate_with_ellipsis(content, MAX_CHARS_PER_PAIR / 2, "…"),
237 ))
238 });
239 }
240 _ => {}
241 }
242 }
243 }
244
245 let start = uses.len().saturating_sub(max_pairs);
246 uses[start..]
247 .iter()
248 .filter_map(|(key, provider_id, name, input)| {
249 if key.as_str().trim().is_empty()
250 || provider_id.trim().is_empty()
251 || use_counts.get(key) != Some(&1)
252 {
253 return None;
254 }
255 let result = match results.get(key) {
256 Some(Some((result_provider, content))) if result_provider == provider_id => {
257 content.clone()
258 }
259 Some(_) => return None,
260 None => "(pending)".to_string(),
261 };
262 Some(ToolCallPair {
263 name: (*name).to_string(),
264 input_preview: input.clone(),
265 result_preview: result,
266 })
267 })
268 .collect()
269 }
270
271 /// Build the user prompt for the advisor from a slice of tool-call pairs.
272 #[must_use]
273 pub fn build_advisor_prompt(pairs: &[ToolCallPair]) -> String {
274 let mut out = String::from("Recent tool activity to review (oldest → newest):\n\n");
275 for (i, pair) in pairs.iter().enumerate() {
276 out.push_str(&format!(
277 "{}. tool={}\n input: {}\n result: {}\n\n",
278 i + 1,
279 pair.name,
280 pair.input_preview,
281 pair.result_preview
282 ));
283 }
284 out.push_str(
285 "Provide your advisory in one to three sentences, or respond with \"ok\" if nothing notable.",
286 );
287 out
288 }
289
290 /// Run one advisor review cycle for a completed turn.
291 ///
292 /// This is the async work dispatched by `spawn_supervised` in the engine. It:
293 /// 1. Checks whether emission is allowed by `guard`.
294 /// 2. Extracts bounded tool-call pairs from `messages`.
295 /// 3. Makes a non-streaming LLM call with a short read-only prompt.
296 /// 4. Checks emission again (the LLM call may have taken time).
297 /// 5. Sends `Event::AdvisoryNote` if the note passes the guard.
298 ///
299 /// All errors are logged and swallowed — the advisor must never fail the
300 /// parent turn.
301 pub async fn run_advisor_for_turn(
302 turn_id: String,
303 messages: Vec<Message>,
304 config: AdvisorConfig,
305 client: CodewhaleClient,
306 route_config: Config,
307 session_model: String,
308 usage_context: AdvisorUsageContext,
309 guard: std::sync::Arc<tokio::sync::Mutex<EmissionGuard>>,
310 tx_event: mpsc::Sender<Event>,
311 ) {
312 // Pre-flight: skip if the guard already blocks (avoids the LLM call when
313 // rate-limited, which is the common case for rapid turn sequences).
314 {
315 let g = guard.lock().await;
316 // We don't have the note content yet, so we only check the rate limit
317 // here by testing with a placeholder. The dedup check runs after the
318 // LLM call, when we have the actual content.
319 if let Some(last) = g.last_emission
320 && std::time::Instant::now().duration_since(last) < config.rate_limit
321 {
322 debug!(target: "advisor", "rate-limited, skipping advisor run for turn {turn_id}");
323 return;
324 }
325 }
326
327 // Extract a bounded slice of tool-call pairs.
328 let pairs = extract_tool_call_pairs(&messages, config.max_tool_calls as usize);
329 if pairs.is_empty() {
330 debug!(target: "advisor", "no tool calls found; skipping advisor for turn {turn_id}");
331 return;
332 }
333
334 let tool_call_count = pairs.len() as u32;
335 let prompt = build_advisor_prompt(&pairs);
336 let model = config
337 .model
338 .clone()
339 .unwrap_or_else(|| session_model.clone());
340
341 let (client, model) = match exact_advisor_client(&route_config, client, &session_model, &model)
342 {
343 Ok(route) => route,
344 Err(error) => {
345 tracing::warn!(target: "advisor", "advisor route resolution failed for turn {turn_id}: {error}");
346 return;
347 }
348 };
349 let route = client.effective_route_envelope(&model, chrono::Utc::now());
350 let request = MessageRequest {
351 model: model.clone(),
352 messages: vec![Message {
353 role: Role::User,
354 content: vec![ContentBlock::Text {
355 text: prompt,
356 cache_control: None,
357 }],
358 }],
359 max_tokens: ADVISOR_MAX_TOKENS,
360 system: Some(SystemPrompt::Text(ADVISOR_SYSTEM_PROMPT.to_string())),
361 tools: None,
362 tool_choice: None,
363 metadata: None,
364 thinking: None,
365 // The advisor has a deliberately tiny answer contract. Hidden
366 // reasoning would spend that allowance before the note is emitted.
367 reasoning_effort: Some("off".to_string()),
368 stream: Some(false),
369 temperature: None,
370 top_p: None,
371 safety_check: None,
372 title: None,
373 };
374
375 let observation = usage_context.source.observation();
376 let wire = observation.wire_observations.clone();
377 let response = crate::llm_client::observe_request_retries(
378 Some(observation),
379 client.create_message(request),
380 )
381 .await;
382 let wire = wire.drain();
383 let record = usage_context
384 .source
385 .response_record(&route, &response, &wire);
386 crate::cost_status::record_runtime_usage_async(
387 usage_context.cost_scope,
388 usage_context.source.origin(),
389 &record,
390 )
391 .await;
392 let response = match response {
393 Ok(response) => response,
394 Err(error) => {
395 tracing::warn!(%error, "advisor request failed");
396 return;
397 }
398 };
399
400 if codewhale_models::is_incomplete_stop_reason(response.stop_reason.as_deref()) {
401 tracing::warn!(
402 target: "advisor",
403 "advisor response incomplete for turn {turn_id} (stop reason `{}`); dropping partial note",
404 codewhale_models::stop_reason_detail(response.stop_reason.as_deref())
405 );
406 return;
407 }
408
409 // Extract the text from the response.
410 let note: String = response
411 .content
412 .iter()
413 .filter_map(|block| {
414 if let ContentBlock::Text { text, .. } = block {
415 Some(text.as_str())
416 } else {
417 None
418 }
419 })
420 .collect::<Vec<_>>()
421 .join("\n")
422 .trim()
423 .to_string();
424
425 if note.is_empty() {
426 debug!(target: "advisor", "empty advisor response for turn {turn_id}; skipping");
427 return;
428 }
429
430 // Post-flight emission check (rate limit + dedup).
431 let mut guard_lock = guard.lock().await;
432 if !guard_lock.may_emit(&note, &config) {
433 debug!(target: "advisor", "emission suppressed by guard for turn {turn_id}");
434 return;
435 }
436
437 guard_lock.record_emission(&note);
438 drop(guard_lock);
439
440 let _ = tx_event
441 .send(Event::AdvisoryNote {
442 turn_id: turn_id.clone(),
443 note: note.clone(),
444 tool_call_count,
445 })
446 .await;
447
448 debug!(target: "advisor", "advisory note emitted for turn {turn_id} ({tool_call_count} tool calls reviewed)");
449 }
450
451 fn exact_advisor_client(
452 config: &Config,
453 parent_client: CodewhaleClient,
454 session_model: &str,
455 requested_model: &str,
456 ) -> anyhow::Result<(CodewhaleClient, String)> {
457 if requested_model
458 .trim()
459 .eq_ignore_ascii_case(session_model.trim())
460 {
461 return Ok((parent_client, session_model.trim().to_string()));
462 }
463
464 if config.providers.as_ref().is_some_and(|providers| {
465 providers.custom.values().any(|provider| {
466 provider
467 .model
468 .as_deref()
469 .is_some_and(|model| model.trim().eq_ignore_ascii_case(requested_model.trim()))
470 })
471 }) {
472 anyhow::bail!(
473 "advisor model `{}` belongs to a custom provider but no exact provider identity is carried",
474 requested_model.trim()
475 );
476 }
477
478 let active = config
479 .active_provider_identity()
480 .map_err(anyhow::Error::msg)?;
481 let selection =
482 crate::model_routing::resolve_explicit_route_with_inventory(config, requested_model);
483 let (identity, model) = if let Some(selection) = selection {
484 (selection.provider, selection.model)
485 } else {
486 let candidates =
487 crate::model_routing::explicit_route_candidate_providers(config, requested_model);
488 if !candidates.is_empty() && !candidates.contains(&active) {
489 anyhow::bail!(
490 "advisor model `{}` is not owned by the originating provider and has no unique exact route",
491 requested_model.trim()
492 );
493 }
494 (active, requested_model.trim().to_string())
495 };
496 let client =
497 crate::route_runtime::resolve_runtime_route_for_identity(config, &identity, Some(&model))
498 .map_err(anyhow::Error::msg)?
499 .validate()
500 .map(|route| route.client)
501 .map_err(anyhow::Error::msg)?;
502 Ok((client, model))
503 }
504
505 fn hash_str(s: &str) -> u64 {
506 let mut h = DefaultHasher::new();
507 s.hash(&mut h);
508 h.finish()
509 }
510
511 // ── Tests ──────────────────────────────────────────────────────────────────
512
513 #[cfg(test)]
514 mod tests {
515 use super::*;
516 use codewhale_runtime::config::{ProviderConfig, ProvidersConfig};
517 use std::time::Duration;
518 use wiremock::matchers::{method, path};
519 use wiremock::{Mock, MockServer, ResponseTemplate};
520
521 fn test_config() -> AdvisorConfig {
522 AdvisorConfig {
523 enabled: true,
524 max_tool_calls: 5,
525 rate_limit: Duration::from_secs(1),
526 dedup_window: Duration::from_secs(10),
527 model: None,
528 }
529 }
530
531 // ── enable/disable ────────────────────────────────────────────────────
532
533 #[test]
534 fn disabled_config_has_enabled_false() {
535 let cfg = AdvisorConfig::disabled();
536 assert!(!cfg.enabled);
537 }
538
539 #[test]
540 fn from_toml_clamps_max_tool_calls() {
541 let toml = AdvisorConfigToml {
542 enabled: true,
543 max_tool_calls: 999,
544 rate_limit_secs: 60,
545 dedup_window_secs: 300,
546 model: None,
547 };
548 let cfg = AdvisorConfig::from_toml(&toml);
549 assert_eq!(
550 cfg.max_tool_calls, 50,
551 "max_tool_calls must be clamped to 50"
552 );
553 }
554
555 #[test]
556 fn from_toml_clamps_rate_limit() {
557 let toml = AdvisorConfigToml {
558 enabled: true,
559 max_tool_calls: 10,
560 rate_limit_secs: 0, // below minimum of 5
561 dedup_window_secs: 300,
562 model: None,
563 };
564 let cfg = AdvisorConfig::from_toml(&toml);
565 assert!(
566 cfg.rate_limit >= Duration::from_secs(5),
567 "rate_limit must be at least 5s"
568 );
569 }
570
571 // ── bounded input ─────────────────────────────────────────────────────
572
573 fn make_messages_with_n_tool_calls(n: usize) -> Vec<Message> {
574 let mut messages = Vec::new();
575 for i in 0..n {
576 let id = format!("tool_{i}");
577 // assistant message with ToolUse
578 messages.push(Message {
579 role: Role::Assistant,
580 content: vec![ContentBlock::ToolUse {
581 execution_id: None,
582 id: id.clone(),
583 name: "exec_shell".to_string(),
584 input: serde_json::json!({"command": format!("echo {i}")}),
585 caller: None,
586 thought_signature: None,
587 }],
588 });
589 // user message with ToolResult
590 messages.push(Message {
591 role: Role::User,
592 content: vec![ContentBlock::ToolResult {
593 execution_id: None,
594 tool_use_id: id,
595 content: format!("{i}"),
596 is_error: None,
597 content_blocks: None,
598 }],
599 });
600 }
601 messages
602 }
603
604 #[test]
605 fn extract_tool_call_pairs_bounded_by_max() {
606 let messages = make_messages_with_n_tool_calls(20);
607 let pairs = extract_tool_call_pairs(&messages, 5);
608 assert_eq!(pairs.len(), 5, "must return at most max_pairs");
609 // Should be the last 5 (newest).
610 assert_eq!(pairs[0].name, "exec_shell");
611 }
612
613 #[test]
614 fn extract_tool_call_pairs_empty_when_no_tool_calls() {
615 let messages = vec![Message {
616 role: Role::User,
617 content: vec![ContentBlock::Text {
618 text: "hello".to_string(),
619 cache_control: None,
620 }],
621 }];
622 let pairs = extract_tool_call_pairs(&messages, 5);
623 assert!(pairs.is_empty());
624 }
625
626 #[test]
627 fn extract_tool_call_pairs_fewer_than_max_returns_all() {
628 let messages = make_messages_with_n_tool_calls(3);
629 let pairs = extract_tool_call_pairs(&messages, 10);
630 assert_eq!(pairs.len(), 3);
631 }
632
633 #[test]
634 fn extract_tool_call_pairs_keep_execution_and_legacy_domains_distinct() {
635 let messages: Vec<Message> = serde_json::from_value(serde_json::json!([
636 {"role":"assistant", "content":[{"type":"tool_use", "id":"wire",
637 "execution_id":"first", "name":"read_file", "input":{"path":"first.txt"}}]},
638 {"role":"user", "content":[{"type":"tool_result", "tool_use_id":"wire",
639 "execution_id":"first", "content":"first output"}]},
640 {"role":"assistant", "content":[{"type":"tool_use", "id":"wire",
641 "execution_id":"second", "name":"read_file", "input":{"path":"second.txt"}}]},
642 {"role":"user", "content":[{"type":"tool_result", "tool_use_id":"wire",
643 "execution_id":"second", "content":"second output"}]},
644 {"role":"assistant", "content":[{"type":"tool_use", "id":"first",
645 "name":"read_file", "input":{"path":"legacy.txt"}}]},
646 {"role":"user", "content":[{"type":"tool_result", "tool_use_id":"first",
647 "content":"legacy output"}]}
648 ]))
649 .expect("transcript");
650 let pairs = extract_tool_call_pairs(&messages, 3);
651 assert_eq!(pairs.len(), 3);
652 for (pair, path, output) in [
653 (&pairs[0], "first.txt", "first output"),
654 (&pairs[1], "second.txt", "second output"),
655 (&pairs[2], "legacy.txt", "legacy output"),
656 ] {
657 assert!(pair.input_preview.contains(path));
658 assert_eq!(pair.result_preview, output);
659 }
660 let bounded = extract_tool_call_pairs(&messages, 2);
661 assert_eq!(bounded.len(), 2);
662 assert_eq!(bounded[0].result_preview, "second output");
663 assert_eq!(bounded[1].result_preview, "legacy output");
664 assert!(extract_tool_call_pairs(&messages, 0).is_empty());
665 }
666
667 #[test]
668 fn extract_tool_call_pairs_refuse_corrupt_identity_without_fallback() {
669 let call = |execution_id: Option<&str>| {
670 serde_json::json!({
671 "type":"tool_use", "id":"wire", "execution_id":execution_id,
672 "name":"read_file", "input":{"path":"selected.txt"}
673 })
674 };
675 let result = |execution_id: Option<&str>, provider: &str| {
676 serde_json::json!({
677 "type":"tool_result", "tool_use_id":provider, "execution_id":execution_id,
678 "content":"must not borrow this output"
679 })
680 };
681 for (label, calls, results, pending) in [
682 (
683 "duplicate local calls",
684 vec![call(Some("exec")), call(Some("exec"))],
685 vec![result(Some("exec"), "wire")],
686 false,
687 ),
688 (
689 "duplicate legacy calls",
690 vec![call(None), call(None)],
691 vec![result(None, "wire")],
692 false,
693 ),
694 (
695 "duplicate local results",
696 vec![call(Some("exec"))],
697 vec![result(Some("exec"), "wire"), result(Some("exec"), "wire")],
698 false,
699 ),
700 (
701 "duplicate legacy results",
702 vec![call(None)],
703 vec![result(None, "wire"), result(None, "wire")],
704 false,
705 ),
706 (
707 "wrong provider",
708 vec![call(Some("exec"))],
709 vec![result(Some("exec"), "other")],
710 false,
711 ),
712 (
713 "empty local identity",
714 vec![call(Some(""))],
715 vec![result(Some(""), "wire")],
716 false,
717 ),
718 (
719 "no local fallback",
720 vec![call(Some("exec"))],
721 vec![result(Some("wrong"), "wire"), result(None, "wire")],
722 true,
723 ),
724 (
725 "no legacy fallback",
726 vec![call(None)],
727 vec![result(Some("wire"), "wire")],
728 true,
729 ),
730 ("missing result", vec![call(Some("exec"))], vec![], true),
731 ] {
732 let messages: Vec<Message> = serde_json::from_value(serde_json::json!([
733 {"role":"assistant", "content":calls}, {"role":"user", "content":results}
734 ]))
735 .expect("transcript");
736 let pairs = extract_tool_call_pairs(&messages, 5);
737 assert_eq!(pairs.len(), usize::from(pending), "{label}");
738 if pending {
739 assert_eq!(pairs[0].result_preview, "(pending)", "{label}");
740 }
741 assert!(
742 !build_advisor_prompt(&pairs).contains("must not borrow"),
743 "{label}"
744 );
745 }
746 }
747
748 // ── rate limiting ─────────────────────────────────────────────────────
749
750 #[test]
751 fn emission_guard_allows_first_emission() {
752 let guard = EmissionGuard::new();
753 let config = test_config();
754 assert!(
755 guard.may_emit("something concerning here", &config),
756 "first emission must be allowed"
757 );
758 }
759
760 #[test]
761 fn emission_guard_blocks_immediately_after_emission() {
762 let mut guard = EmissionGuard::new();
763 let config = test_config();
764 let note = "something concerning";
765 guard.record_emission(note);
766 assert!(
767 !guard.may_emit("a completely different note", &config),
768 "emission must be blocked immediately after a prior emission (rate limit)"
769 );
770 }
771
772 #[test]
773 fn emission_guard_allows_after_rate_limit_expires() {
774 let mut guard = EmissionGuard::new();
775 // Rate limit of 0ms — always expired.
776 let config = AdvisorConfig {
777 rate_limit: Duration::ZERO,
778 dedup_window: Duration::from_secs(300),
779 ..AdvisorConfig::disabled()
780 };
781 let note = "first note";
782 guard.record_emission(note);
783 assert!(
784 guard.may_emit("second different note", &config),
785 "emission must be allowed when rate limit duration is zero"
786 );
787 }
788
789 // ── deduplication ─────────────────────────────────────────────────────
790
791 #[test]
792 fn emission_guard_suppresses_ok_response() {
793 let guard = EmissionGuard::new();
794 let config = test_config();
795 assert!(!guard.may_emit("ok", &config), "\"ok\" must be suppressed");
796 assert!(!guard.may_emit("OK", &config), "\"OK\" must be suppressed");
797 assert!(
798 !guard.may_emit(" ok ", &config),
799 "\" ok \" must be suppressed"
800 );
801 }
802
803 #[test]
804 fn emission_guard_dedup_blocks_identical_note_within_window() {
805 let mut guard = EmissionGuard::new();
806 // Use a zero rate limit so only dedup is tested.
807 let config = AdvisorConfig {
808 rate_limit: Duration::ZERO,
809 dedup_window: Duration::from_secs(300),
810 ..AdvisorConfig::disabled()
811 };
812 let note = "risky shell command with no error checking";
813 guard.record_emission(note);
814 assert!(
815 !guard.may_emit(note, &config),
816 "identical note must be suppressed within the dedup window"
817 );
818 }
819
820 #[test]
821 fn emission_guard_allows_different_note_within_dedup_window() {
822 let mut guard = EmissionGuard::new();
823 let config = AdvisorConfig {
824 rate_limit: Duration::ZERO,
825 dedup_window: Duration::from_secs(300),
826 ..AdvisorConfig::disabled()
827 };
828 guard.record_emission("first note");
829 assert!(
830 guard.may_emit("entirely different note", &config),
831 "a different note must be allowed even within the dedup window"
832 );
833 }
834
835 // ── child failure isolation ───────────────────────────────────────────
836
837 #[test]
838 fn advisor_prompt_is_non_empty_for_non_empty_pairs() {
839 let pairs = vec![ToolCallPair {
840 name: "exec_shell".to_string(),
841 input_preview: r#"{"command":"ls -la"}"#.to_string(),
842 result_preview: "total 4\ndrwxr-xr-x 2 user user 4096".to_string(),
843 }];
844 let prompt = build_advisor_prompt(&pairs);
845 assert!(
846 prompt.contains("exec_shell"),
847 "prompt must include the tool name"
848 );
849 assert!(
850 prompt.contains("ls -la"),
851 "prompt must include the tool input"
852 );
853 }
854
855 #[test]
856 fn advisor_model_override_builds_the_owning_provider_client() {
857 let config = {
858 let __cw_config_init_0_0 = Some("deepseek".to_string());
859 let __cw_config_init_0_1 = Some(ProvidersConfig {
860 deepseek: ProviderConfig {
861 api_key: Some("sk-deepseek-advisor-test".to_string()),
862 model: Some("deepseek-v4-pro".to_string()),
863 ..ProviderConfig::default()
864 },
865 zai: ProviderConfig {
866 api_key: Some("zai-advisor-test-key".to_string()),
867 model: Some(
868 codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL.to_string(),
869 ),
870 ..ProviderConfig::default()
871 },
872 ..ProvidersConfig::default()
873 });
874 let mut __cw_config_init_0_value: Config = Config::default();
875 __cw_config_init_0_value.provider = __cw_config_init_0_0;
876 __cw_config_init_0_value.providers = __cw_config_init_0_1;
877 __cw_config_init_0_value
878 };
879 let parent = CodewhaleClient::new(&config).expect("parent client");
880 let (advisor, resolved_model) = exact_advisor_client(
881 &config,
882 parent,
883 "deepseek-chat",
884 codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL,
885 )
886 .expect("cross-provider advisor route");
887 let route = advisor.effective_route_envelope(&resolved_model, chrono::Utc::now());
888
889 assert_eq!(route.provider, codewhale_config::ProviderKind::Zai);
890 assert_eq!(route.provider_identity, "zai");
891 assert_eq!(
892 route.model,
893 codewhale_config::descriptors::defaults::DEFAULT_ZAI_MODEL
894 );
895 }
896
897 #[test]
898 fn advisor_foreign_custom_override_fails_closed_without_exact_identity() {
899 let config = {
900 let __cw_config_init_1_0 = Some("deepseek".to_string());
901 let __cw_config_init_1_1 = Some(ProvidersConfig {
902 deepseek: ProviderConfig {
903 api_key: Some("sk-deepseek-advisor-test".to_string()),
904 model: Some("deepseek-v4-pro".to_string()),
905 ..ProviderConfig::default()
906 },
907 custom: [(
908 "private-route".to_string(),
909 ProviderConfig {
910 api_key: Some("custom-advisor-test-key".to_string()),
911 base_url: Some("https://custom.invalid/v1".to_string()),
912 model: Some("private-advisor-model".to_string()),
913 ..ProviderConfig::default()
914 },
915 )]
916 .into_iter()
917 .collect(),
918 ..ProvidersConfig::default()
919 });
920 let mut __cw_config_init_1_value: Config = Config::default();
921 __cw_config_init_1_value.provider = __cw_config_init_1_0;
922 __cw_config_init_1_value.providers = __cw_config_init_1_1;
923 __cw_config_init_1_value
924 };
925 let parent = CodewhaleClient::new(&config).expect("parent client");
926 let error =
927 match exact_advisor_client(&config, parent, "deepseek-chat", "private-advisor-model") {
928 Ok(_) => panic!("generic custom kind cannot identify the exact foreign route"),
929 Err(error) => error,
930 };
931 assert!(
932 error.to_string().contains("exact provider identity"),
933 "{error}"
934 );
935 }
936
937 #[test]
938 fn advisor_named_custom_a_cannot_route_model_owned_by_custom_b() {
939 let config = {
940 let __cw_config_init_2_0 = Some("custom-a".to_string());
941 let __cw_config_init_2_1 = Some(ProvidersConfig {
942 custom: [
943 (
944 "custom-a".to_string(),
945 ProviderConfig {
946 api_key: Some("custom-a-advisor-test-key".to_string()),
947 base_url: Some("https://custom-a.invalid/v1".to_string()),
948 model: Some("custom-a-model".to_string()),
949 kind: Some("openai-compatible".to_string()),
950 ..ProviderConfig::default()
951 },
952 ),
953 (
954 "custom-b".to_string(),
955 ProviderConfig {
956 api_key: Some("custom-b-advisor-test-key".to_string()),
957 base_url: Some("https://custom-b.invalid/v1".to_string()),
958 model: Some("custom-b-model".to_string()),
959 kind: Some("openai-compatible".to_string()),
960 ..ProviderConfig::default()
961 },
962 ),
963 ]
964 .into_iter()
965 .collect(),
966 ..ProvidersConfig::default()
967 });
968 let mut __cw_config_init_2_value: Config = Config::default();
969 __cw_config_init_2_value.provider = __cw_config_init_2_0;
970 __cw_config_init_2_value.providers = __cw_config_init_2_1;
971 __cw_config_init_2_value
972 };
973 let parent = CodewhaleClient::new(&config).expect("active custom-a client");
974 let error = match exact_advisor_client(&config, parent, "custom-a-model", "custom-b-model")
975 {
976 Ok(_) => panic!("custom-b must not reuse custom-a's endpoint or credential"),
977 Err(error) => error,
978 };
979 assert!(
980 error.to_string().contains("exact provider identity"),
981 "{error}"
982 );
983 }
984
985 async fn run_billed_advisor_fixture(
986 note: &str,
987 stop_reason: &str,
988 suppress_as_duplicate: bool,
989 include_usage: bool,
990 ) -> (crate::cost_status::PendingBackgroundCost, Option<Event>) {
991 let _scope = crate::cost_status::test_scope();
992 let server = MockServer::start().await;
993 let mut provider_response = serde_json::json!({
994 "id": "advisor-provider-response",
995 "model": "deepseek-v4-pro",
996 "choices": [{
997 "index": 0,
998 "message": {"role": "assistant", "content": note},
999 "finish_reason": stop_reason
1000 }]
1001 });
1002 if include_usage {
1003 provider_response["usage"] = serde_json::json!({
1004 "prompt_tokens": 9,
1005 "completion_tokens": 3,
1006 "total_tokens": 12
1007 });
1008 }
1009 Mock::given(method("POST"))
1010 .and(path("/v1/chat/completions"))
1011 .respond_with(ResponseTemplate::new(200).set_body_json(provider_response))
1012 .expect(1)
1013 .mount(&server)
1014 .await;
1015 let route_config = {
1016 let __cw_config_init_3_0 = Some("deepseek".to_string());
1017 let __cw_config_init_3_1 = Some(ProvidersConfig {
1018 deepseek: ProviderConfig {
1019 api_key: Some("sk-deepseek-advisor-test".to_string()),
1020 model: Some("deepseek-v4-pro".to_string()),
1021 ..ProviderConfig::default()
1022 },
1023 ..ProvidersConfig::default()
1024 });
1025 let mut __cw_config_init_3_value: Config = Config::default();
1026 __cw_config_init_3_value.provider = __cw_config_init_3_0;
1027 __cw_config_init_3_value.providers = __cw_config_init_3_1;
1028 __cw_config_init_3_value
1029 };
1030 let mut client = CodewhaleClient::new(&route_config).expect("advisor client");
1031 client.set_test_chat_transport_base_url(server.uri());
1032 let mut emission_guard = EmissionGuard::new();
1033 if suppress_as_duplicate {
1034 emission_guard.record_emission(note);
1035 }
1036 let guard = std::sync::Arc::new(tokio::sync::Mutex::new(emission_guard));
1037 let (tx, mut rx) = mpsc::channel(1);
1038 let directory = tempfile::tempdir().unwrap();
1039 let origin = crate::cost_status::NativeUsageOrigin::session(
1040 crate::cost_status::scope_token(),
1041 directory.path().to_path_buf(),
1042 "advisor-fixture".to_string(),
1043 );
1044 run_advisor_for_turn(
1045 "advisor-turn".to_string(),
1046 make_messages_with_n_tool_calls(1),
1047 AdvisorConfig {
1048 enabled: true,
1049 max_tool_calls: 5,
1050 rate_limit: Duration::ZERO,
1051 dedup_window: Duration::from_secs(60),
1052 model: None,
1053 },
1054 client,
1055 route_config,
1056 "deepseek-v4-pro".to_string(),
1057 AdvisorUsageContext::capture(Some(origin)),
1058 guard,
1059 tx,
1060 )
1061 .await;
1062 let mut pending = crate::cost_status::drain();
1063 let mut cost = crate::session_manager::SessionCostSnapshot::default();
1064 for record in &pending.source_records {
1065 cost.project_usage_record(record).unwrap();
1066 }
1067 pending.estimate = cost.total_estimate();
1068 pending.priced_turns = cost.priced_turns;
1069 pending.unpriced_turns = cost.unpriced_turns;
1070 pending.cny_priced_turns = cost.cny_priced_turns;
1071 pending.cny_unpriced_turns = cost.cny_unpriced_turns;
1072 if cost
1073 .unpriced_reasons
1074 .contains("provider_success_missing_usage")
1075 {
1076 pending
1077 .unpriced_reasons
1078 .insert("provider_success_missing_usage");
1079 }
1080 (pending, rx.try_recv().ok())
1081 }
1082
1083 #[tokio::test]
1084 async fn advisor_incomplete_and_dedup_suppressed_responses_are_each_billed_once() {
1085 let (incomplete, incomplete_event) =
1086 run_billed_advisor_fixture("partial note", "max_tokens", false, true).await;
1087 assert!(incomplete_event.is_none());
1088 assert_eq!(
1089 incomplete
1090 .priced_turns
1091 .saturating_add(incomplete.unpriced_turns),
1092 1
1093 );
1094
1095 let (dedup, dedup_event) =
1096 run_billed_advisor_fixture("same advisory", "stop", true, true).await;
1097 assert!(dedup_event.is_none());
1098 assert_eq!(dedup.priced_turns.saturating_add(dedup.unpriced_turns), 1);
1099 }
1100
1101 #[tokio::test]
1102 async fn advisor_provider_success_without_usage_marks_unknown_once() {
1103 let (pending, event) =
1104 run_billed_advisor_fixture("use a smaller focused slice", "stop", false, false).await;
1105
1106 assert!(
1107 event.is_some(),
1108 "the semantic advisor response remains usable"
1109 );
1110 assert_eq!(pending.priced_turns, 0);
1111 assert_eq!(pending.unpriced_turns, 1);
1112 assert_eq!(pending.cny_unpriced_turns, 1);
1113 assert!(
1114 pending
1115 .unpriced_reasons
1116 .contains("provider_success_missing_usage")
1117 );
1118 }
1119 }
1120
1120 lines RUST