返回 CodeWhale
debug_diagnostics.rs
根目录 / crates / tui / src / commands / contract / debug_diagnostics.rs
1 //! Host-owned diagnostics projections for FEAT-029.
2 //!
3 //! Only this adapter reads App, pricing, request inspection and prepared-tool
4 //! evidence. No completed command message or rendered report crosses the facet.
5 //! The cache observation and final store are separate synchronous operations;
6 //! in particular observation never mutates the remembered inspection.
7
8 use std::collections::BTreeMap;
9 use std::time::Instant;
10
11 use codewhale_command_contract::facets::*;
12 use codewhale_models::{MessageRequest, SystemPrompt, Usage};
13
14 use super::SharedCommandHost;
15 use crate::context_report::project_source_map as source_map;
16 use crate::tui::app::App;
17 use codewhale_config::pricing::CostCurrency;
18 use codewhale_engine::client::{
19 CacheWarmupKey, PromptInspection, PromptLayerStability, inspect_prompt_for_request,
20 };
21 use codewhale_engine::pricing::token_usage_for_pricing;
22 use codewhale_engine::tool_inspection::project_snapshot as tool_snapshot;
23 use codewhale_runtime::config::provider_has_balance_api;
24
25 pub(super) struct DebugDiagnosticsAdapter<'a> {
26 pub(super) host: SharedCommandHost<'a>,
27 }
28
29 impl CommandDebugDiagnosticsContext for DebugDiagnosticsAdapter<'_> {
30 fn balance_projection(&self) -> DebugBalanceProjection {
31 let app = self.host.app.borrow();
32 DebugBalanceProjection {
33 provider_display_name: app
34 .admitted_provider_identity()
35 .map_or("unavailable", |identity| {
36 identity
37 .compatibility()
38 .map_or(identity.key.as_str(), |row| row.label)
39 })
40 .to_string(),
41 supports_balance_api: provider_has_balance_api(app.api_provider),
42 }
43 }
44
45 fn system_projection(&self) -> DebugSystemProjection {
46 let app = self.host.app.borrow();
47 let prompt = match app.system_prompt.as_ref() {
48 None => DebugSystemPrompt::None,
49 Some(SystemPrompt::Text(text)) => DebugSystemPrompt::Text(text.clone()),
50 Some(SystemPrompt::Blocks(blocks)) => {
51 DebugSystemPrompt::Blocks(blocks.iter().map(|block| block.text.clone()).collect())
52 }
53 };
54 DebugSystemProjection {
55 mode_label: app.mode.label().to_string(),
56 prompt,
57 }
58 }
59
60 fn token_projection(&self) -> DebugTokenProjection {
61 let app = self.host.app.borrow();
62 let window = app.effective_context_window();
63 let estimated = codewhale_engine::compaction::estimate_input_tokens_conservative(
64 &app.api_messages,
65 app.system_prompt.as_ref(),
66 );
67 DebugTokenProjection {
68 active_context_used: estimated.min(window as usize),
69 context_window: window,
70 last_input: app.session.last_prompt_tokens,
71 last_output: app.session.last_completion_tokens,
72 cache_hit: app.session.last_prompt_cache_hit_tokens,
73 cache_miss: app.session.last_prompt_cache_miss_tokens,
74 total_tokens: u64::from(app.session.displayed_total_tokens()),
75 cache_write_tokens: u64::from(app.session.displayed_total_cache_write_tokens()),
76 api_message_count: app.api_messages.len(),
77 chat_message_count: app.history.len(),
78 model: app.model.clone(),
79 cost: cost_projection(&app),
80 }
81 }
82
83 fn cost_projection(&self) -> DebugCostProjection {
84 cost_projection(&self.host.app.borrow())
85 }
86
87 fn cache_telemetry(&self) -> DebugCacheTelemetry {
88 let app = self.host.app.borrow();
89 let currency = app.cost_display_currency(app.cost_currency);
90 let now = Instant::now();
91 let history = app
92 .session
93 .turn_cache_history
94 .iter()
95 .map(|rec| {
96 let classes = token_usage_for_pricing(&Usage {
97 input_tokens: rec.input_tokens,
98 output_tokens: rec.output_tokens,
99 prompt_cache_hit_tokens: rec.cache_hit_tokens,
100 prompt_cache_miss_tokens: rec.cache_miss_tokens,
101 prompt_cache_write_tokens: rec.cache_write_tokens,
102 reasoning_tokens: rec.reasoning_tokens,
103 reasoning_replay_tokens: rec.reasoning_replay_tokens,
104 server_tool_use: None,
105
106 input_audio_tokens: None,
107 output_audio_tokens: None,
108
109 request_usages: Vec::new(),
110 safety_tokens: None,
111 });
112 DebugCacheTurn {
113 provider: rec.provider.map(|provider| provider.as_str().to_string()),
114 provider_identity: rec.provider_identity.clone(),
115 model: rec.model.clone(),
116 auto_model: rec.auto_model,
117 input_tokens: rec.input_tokens,
118 output_tokens: rec.output_tokens,
119 cache_hit_tokens: rec.cache_hit_tokens,
120 cache_miss_tokens: rec.cache_miss_tokens,
121 cache_write_tokens: rec.cache_write_tokens,
122 reasoning_tokens: rec.reasoning_tokens,
123 reasoning_replay_tokens: rec.reasoning_replay_tokens,
124 priced_amount: rec.cost_audit.as_ref().and_then(|audit| {
125 audit
126 .is_priced_in(currency)
127 .then(|| audit.estimate.map(|value| value.amount(currency)))
128 .flatten()
129 }),
130 unpriced_reason_key: rec.cost_audit.as_ref().and_then(|audit| {
131 audit
132 .unpriced_reason
133 .map(|reason| reason.label().to_string())
134 }),
135 unpriced_reason_sort_rank: rec
136 .cost_audit
137 .as_ref()
138 .and_then(|audit| audit.unpriced_reason.map(|reason| reason as u8)),
139 unpriced_classes: rec.cost_audit.as_ref().map_or_else(Vec::new, |audit| {
140 audit
141 .unpriced_classes
142 .iter()
143 .map(|class| class.label().to_string())
144 .collect()
145 }),
146 priced_cache_read: classes.cache_read,
147 priced_cache_miss: classes.input,
148 priced_cache_write: classes.cache_write,
149 age_seconds: now.saturating_duration_since(rec.recorded_at).as_secs(),
150 }
151 })
152 .collect();
153 let mut latest_calls = BTreeMap::new();
154 for (source, contribution) in &app.session.accounted_usage_sources {
155 latest_calls.insert(
156 (contribution.record.usage.route.dispatched_at, source),
157 contribution,
158 );
159 if latest_calls.len() > App::TURN_CACHE_HISTORY_CAP {
160 latest_calls.pop_first();
161 }
162 }
163 let wall_now = chrono::Utc::now();
164 let calls = latest_calls
165 .into_iter()
166 .map(|((quoted_at, source), contribution)| {
167 let record = &contribution.record;
168 let route = &record.usage.route;
169 let display_route = route.sanitized_for_persistence();
170 let valid = contribution.validate().is_ok()
171 && source.as_str()
172 == codewhale_engine::cost_status::usage_source_fingerprint(
173 &record.source_id,
174 );
175 let revision = record.settlement.as_ref().filter(|_| valid);
176 let coverage = revision.map_or(DebugCacheCallCoverage::Unknown, |revision| {
177 use codewhale_engine::llm_client::ProviderUsageCoverage;
178 match revision.coverage {
179 ProviderUsageCoverage::Reported => DebugCacheCallCoverage::Reported,
180 ProviderUsageCoverage::Incomplete => DebugCacheCallCoverage::Incomplete,
181 ProviderUsageCoverage::Missing => DebugCacheCallCoverage::Missing,
182 ProviderUsageCoverage::NotDispatched => {
183 DebugCacheCallCoverage::NotDispatched
184 }
185 ProviderUsageCoverage::Rejected => DebugCacheCallCoverage::Rejected,
186 }
187 });
188 let reported = matches!(
189 coverage,
190 DebugCacheCallCoverage::Reported | DebugCacheCallCoverage::Incomplete
191 );
192 let refused = matches!(
193 coverage,
194 DebugCacheCallCoverage::NotDispatched | DebugCacheCallCoverage::Rejected
195 );
196 let (amount, priced, unpriced) = match currency {
197 CostCurrency::Usd => {
198 (contribution.usd, contribution.priced, contribution.unpriced)
199 }
200 CostCurrency::Cny => (
201 contribution.cny,
202 contribution.cny_priced,
203 contribution.cny_unpriced,
204 ),
205 };
206 let known_amount = (revision.is_some()
207 && (refused || reported && (priced > 0 || amount > 0.0)))
208 .then_some(amount);
209 let usage = &record.usage.usage;
210 let cache_consistent =
211 codewhale_engine::pricing::usage_cache_partition_is_consistent(usage);
212 let classes = token_usage_for_pricing(usage);
213 let audit = route.audit_frozen(usage);
214 DebugCacheCall {
215 source_fingerprint: codewhale_engine::cost_status::usage_source_fingerprint(
216 &record.source_id,
217 ),
218 owner: revision.map(|revision| match revision.owner {
219 codewhale_engine::cost_status::UsageSpendOwner::Primary => {
220 DebugCacheCallOwner::Primary
221 }
222 codewhale_engine::cost_status::UsageSpendOwner::Auxiliary => {
223 DebugCacheCallOwner::Auxiliary
224 }
225 }),
226 coverage,
227 pricing_complete: revision.is_some()
228 && unpriced == 0
229 && (priced > 0 || refused),
230 row: DebugCacheTurn {
231 provider: Some(display_route.provider.as_str().to_string()),
232 provider_identity: Some(display_route.provider_identity.clone()),
233 model: Some(display_route.model.clone()),
234 auto_model: false,
235 input_tokens: if reported { usage.input_tokens } else { 0 },
236 output_tokens: if reported { usage.output_tokens } else { 0 },
237 cache_hit_tokens: (reported && cache_consistent)
238 .then_some(usage.prompt_cache_hit_tokens)
239 .flatten(),
240 cache_miss_tokens: (reported && cache_consistent)
241 .then_some(usage.prompt_cache_miss_tokens)
242 .flatten(),
243 cache_write_tokens: (reported && cache_consistent)
244 .then_some(usage.prompt_cache_write_tokens)
245 .flatten(),
246 reasoning_tokens: reported.then_some(usage.reasoning_tokens).flatten(),
247 reasoning_replay_tokens: reported
248 .then_some(usage.reasoning_replay_tokens)
249 .flatten(),
250 priced_amount: known_amount,
251 unpriced_reason_key: audit
252 .unpriced_reason
253 .map(|reason| reason.label().to_string()),
254 unpriced_reason_sort_rank: audit.unpriced_reason.map(|reason| reason as u8),
255 unpriced_classes: audit
256 .unpriced_classes
257 .iter()
258 .map(|class| class.label().to_string())
259 .collect(),
260 priced_cache_read: classes.cache_read,
261 priced_cache_miss: classes.input,
262 priced_cache_write: classes.cache_write,
263 age_seconds: u64::try_from(
264 wall_now.signed_duration_since(quoted_at).num_seconds(),
265 )
266 .unwrap_or(0),
267 },
268 }
269 })
270 .collect();
271 DebugCacheTelemetry {
272 model: app.model.clone(),
273 session_cache_rates: crate::tui::session_metrics::cache_rates(&app),
274 history,
275 calls,
276 calls_total: app.session.accounted_usage_sources.len(),
277 calls_currency: super::to_command_currency(currency),
278 calls_legacy_coverage_unknown: app.session.cost_coverage_unknown_legacy,
279 history_capacity: App::TURN_CACHE_HISTORY_CAP,
280 prefix_stability_pct: app.prefix_stability_pct,
281 prefix_checks_total: app.prefix_checks_total,
282 prefix_change_count: app.prefix_change_count,
283 prefix_drift_count: app.prefix_drift_count,
284 prefix_context_updates: app.prefix_context_updates,
285 prefix_pin_reason: app.prefix_pin_reason.clone(),
286 prefix_last_miss_reason: app.prefix_last_miss_reason.clone(),
287 last_prefix_change_desc: app.last_prefix_change_desc.clone(),
288 last_pinned_prefix_hash: app.last_pinned_prefix_hash.clone(),
289 api_message_count: app.api_messages.len(),
290 non_system_message_count: app
291 .api_messages
292 .iter()
293 .filter(|m| m.role != "system")
294 .count(),
295 }
296 }
297
298 fn context_source_map(&self) -> DebugPromptSourceMap {
299 source_map(crate::context_report::build_context_report(
300 &self.host.app.borrow(),
301 ))
302 }
303
304 fn prompt_context(&self) -> DebugPromptContext {
305 prompt_context(crate::context_report::build_prompt_context(
306 &self.host.app.borrow(),
307 ))
308 }
309
310 fn tool_snapshot(&self) -> Option<DebugToolSnapshot> {
311 self.host
312 .app
313 .borrow()
314 .session
315 .last_tool_request_snapshot
316 .as_ref()
317 .map(tool_snapshot)
318 }
319
320 fn inspect_cache(
321 &self,
322 ) -> Result<DebugCacheInspectionObservation, DebugCacheInspectionUnavailable> {
323 let app = self.host.app.borrow();
324 let (inspection, key) = observe_cache_for_app(&app)?;
325 let current_warmup_hash_short = key.hash_short();
326 let last_warmup_hash_short = app
327 .session
328 .last_warmup_key
329 .as_ref()
330 .map(CacheWarmupKey::hash_short);
331 Ok(DebugCacheInspectionObservation {
332 current: prompt_inspection(inspection),
333 previous: app
334 .session
335 .last_cache_inspection
336 .clone()
337 .map(prompt_inspection),
338 current_warmup_key: warmup_key(key),
339 last_warmup_key: app.session.last_warmup_key.clone().map(warmup_key),
340 current_warmup_hash_short,
341 last_warmup_hash_short,
342 })
343 }
344
345 fn remember_cache_inspection(&mut self, inspection: DebugPromptInspection) {
346 self.host.app.borrow_mut().session.last_cache_inspection =
347 Some(host_inspection(inspection));
348 }
349 }
350
351 /// Resolve the route and build the inspection exactly once using the existing
352 /// client authority. Both the original handler (until Phase 4 adoption) and
353 /// the diagnostics facet use this host-owned builder. This function is read-only;
354 /// the caller explicitly stores the inspected snapshot only after rendering.
355 pub(crate) fn observe_cache_for_app(
356 app: &App,
357 ) -> Result<(PromptInspection, CacheWarmupKey), DebugCacheInspectionUnavailable> {
358 let target = app
359 .cache_replay_target()
360 .ok_or(DebugCacheInspectionUnavailable::NoConcreteRoute)?;
361 let replay_base_url = target
362 .base_url
363 .as_deref()
364 .ok_or(DebugCacheInspectionUnavailable::MissingCapturedEndpoint)?;
365 let request = MessageRequest {
366 model: target.model.clone(),
367 messages: app.api_messages.as_ref().clone(),
368 max_tokens: 0,
369 system: app.system_prompt.clone(),
370 tools: app.session.last_tool_catalog.clone(),
371 tool_choice: None,
372 metadata: None,
373 thinking: None,
374 reasoning_effort: app
375 .reasoning_effort_api_value_for_replay(
376 target.provider,
377 &target.provider_identity,
378 replay_base_url,
379 &target.model,
380 )
381 .map(str::to_string),
382 stream: Some(true),
383 temperature: None,
384 top_p: None,
385 safety_check: None,
386 title: None,
387 };
388 let inspection = inspect_prompt_for_request(&request);
389 let key = CacheWarmupKey::from_inspection(
390 &target.provider_identity,
391 &target.model,
392 replay_base_url,
393 &inspection,
394 );
395 Ok((inspection, key))
396 }
397
398 /// Authoritative host cost components shared with the original `/cost`
399 /// command while its presentation moves to portable code in Phase 4.
400 /// The #244 high-water floor is not a separate billable amount.
401 pub(crate) struct CostComponents {
402 pub(crate) parent_turns: f64,
403 pub(crate) subagents: f64,
404 pub(crate) display_floor: f64,
405 }
406
407 impl CostComponents {
408 pub(crate) fn compute(app: &App) -> Self {
409 fn sanitize(amount: f64) -> f64 {
410 if amount.is_finite() && amount >= 0.0 {
411 amount
412 } else {
413 0.0
414 }
415 }
416 let currency = app.cost_display_currency(app.cost_currency);
417 let parent_turns = sanitize(app.session_cost_for_currency(currency));
418 let subagents = sanitize(app.subagent_cost_for_currency(currency));
419 let sum = parent_turns + subagents;
420 let current = if sum.is_finite() { sum } else { f64::MAX };
421 let total = app.displayed_session_cost_for_currency(app.cost_currency);
422 Self {
423 parent_turns,
424 subagents,
425 display_floor: (total - current).max(0.0),
426 }
427 }
428
429 #[cfg(test)]
430 pub(crate) fn sum(&self) -> f64 {
431 self.parent_turns + self.subagents + self.display_floor
432 }
433 }
434
435 pub(super) fn cost_projection(app: &App) -> DebugCostProjection {
436 let currency = app.cost_display_currency(app.cost_currency);
437 let total = app.displayed_session_cost_for_currency(app.cost_currency);
438 let components = CostComponents::compute(app);
439 let (priced_turns, unpriced_turns, reasons) = match currency {
440 CostCurrency::Usd => (
441 app.session.cost_priced_turns,
442 app.session.cost_unpriced_turns,
443 &app.session.cost_unpriced_reasons,
444 ),
445 CostCurrency::Cny => (
446 app.session.cost_cny_priced_turns,
447 app.session.cost_cny_unpriced_turns,
448 &app.session.cost_cny_unpriced_reasons,
449 ),
450 };
451 let mut by_route = BTreeMap::<String, f64>::new();
452 let mut itemized_turns = 0u32;
453 for rec in &app.session.turn_cache_history {
454 let Some(audit) = rec.cost_audit.as_ref() else {
455 continue;
456 };
457 if !audit.is_priced_in(currency) {
458 continue;
459 }
460 let Some(estimate) = audit.estimate else {
461 continue;
462 };
463 let provider = rec.provider_identity.clone().unwrap_or_else(|| {
464 rec.provider.map_or_else(
465 || "unknown-provider".to_string(),
466 |provider| provider.as_str().to_string(),
467 )
468 });
469 let route = format!(
470 "{provider}/{}",
471 rec.model.as_deref().unwrap_or("unknown-model")
472 );
473 *by_route.entry(route).or_default() += estimate.amount(currency);
474 itemized_turns = itemized_turns.saturating_add(1);
475 }
476 DebugCostProjection {
477 currency: super::to_command_currency(currency),
478 total,
479 parent_turns: components.parent_turns,
480 subagents: components.subagents,
481 display_floor: components.display_floor,
482 priced_turns,
483 unpriced_turns,
484 legacy_coverage_unknown: app.session.cost_coverage_unknown_legacy,
485 user_declared_estimates: app
486 .session
487 .cost_pricing_provenances
488 .contains("user_override"),
489 itemized_turns,
490 route_amounts: by_route
491 .into_iter()
492 .map(|(route, amount)| DebugRouteCost { route, amount })
493 .collect(),
494 turn_history_capacity: App::TURN_CACHE_HISTORY_CAP,
495 unpriced_reason_labels: reasons.iter().cloned().collect(),
496 unpriced_classes: app.session.cost_unpriced_classes.iter().cloned().collect(),
497 pricing_provenances: app
498 .session
499 .cost_pricing_provenances
500 .iter()
501 .cloned()
502 .collect(),
503 live_pricing_defects: app
504 .session
505 .cost_live_pricing_defects
506 .iter()
507 .cloned()
508 .collect(),
509 unusable_pricing_defects: app
510 .session
511 .cost_live_pricing_unusable_defects
512 .iter()
513 .cloned()
514 .collect(),
515 route_receipts: app.session.cost_route_receipts.iter().cloned().collect(),
516 }
517 }
518
519 pub(crate) fn prompt_context(context: crate::context_report::PromptContext) -> DebugPromptContext {
520 DebugPromptContext {
521 schema_version: context.schema_version,
522 provider: context.provider,
523 model: context.model,
524 system_prompt_state: context.system_prompt_state.to_string(),
525 tool_catalog_state: context.tool_catalog_state.to_string(),
526 sections: context
527 .sections
528 .into_iter()
529 .map(|section| DebugPromptContextSection {
530 index: section.index,
531 block_type: section.block_type,
532 cache_control: section.cache_control.map(|control| DebugCacheControl {
533 cache_type: control.cache_type,
534 }),
535 estimated_tokens: section.estimated_tokens,
536 text: section.text,
537 })
538 .collect(),
539 tools: context
540 .tools
541 .into_iter()
542 .map(|tool| DebugPromptTool {
543 tool_type: tool.tool_type,
544 name: tool.name,
545 description: tool.description,
546 input_schema: tool.input_schema,
547 allowed_callers: tool.allowed_callers,
548 defer_loading: tool.defer_loading,
549 input_examples: tool.input_examples,
550 strict: tool.strict,
551 cache_control: tool.cache_control.map(|control| DebugCacheControl {
552 cache_type: control.cache_type,
553 }),
554 })
555 .collect(),
556 source_map: source_map(context.source_map),
557 }
558 }
559
560 fn prompt_inspection(inspection: PromptInspection) -> DebugPromptInspection {
561 DebugPromptInspection {
562 base_static_prefix_hash: inspection.base_static_prefix_hash,
563 full_request_prefix_hash: inspection.full_request_prefix_hash,
564 tool_catalog_hash: inspection.tool_catalog_hash,
565 layers: inspection
566 .layers
567 .into_iter()
568 .map(|layer| DebugPromptLayer {
569 name: layer.name,
570 stability: match layer.stability {
571 PromptLayerStability::Static => DebugPromptLayerStability::Static,
572 PromptLayerStability::History => DebugPromptLayerStability::History,
573 PromptLayerStability::Dynamic => DebugPromptLayerStability::Dynamic,
574 },
575 char_len: layer.char_len,
576 byte_len: layer.byte_len,
577 token_estimate: layer.token_estimate,
578 sha256: layer.sha256,
579 tool_result: layer.tool_result.map(|result| DebugToolResultInspection {
580 original_chars: result.original_chars,
581 sent_chars: result.sent_chars,
582 truncated: result.truncated,
583 deduplicated: result.deduplicated,
584 }),
585 turn_meta: layer.turn_meta.map(|meta| DebugTurnMetaInspection {
586 original_chars: meta.original_chars,
587 sent_chars: meta.sent_chars,
588 deduplicated: meta.deduplicated,
589 sha256: meta.sha256,
590 }),
591 })
592 .collect(),
593 }
594 }
595
596 fn host_inspection(inspection: DebugPromptInspection) -> PromptInspection {
597 use codewhale_engine::client::{
598 PromptLayerInspection, ToolResultInspection, TurnMetaInspection,
599 };
600 PromptInspection {
601 base_static_prefix_hash: inspection.base_static_prefix_hash,
602 full_request_prefix_hash: inspection.full_request_prefix_hash,
603 tool_catalog_hash: inspection.tool_catalog_hash,
604 layers: inspection
605 .layers
606 .into_iter()
607 .map(|layer| PromptLayerInspection {
608 name: layer.name,
609 stability: match layer.stability {
610 DebugPromptLayerStability::Static => PromptLayerStability::Static,
611 DebugPromptLayerStability::History => PromptLayerStability::History,
612 DebugPromptLayerStability::Dynamic => PromptLayerStability::Dynamic,
613 },
614 char_len: layer.char_len,
615 byte_len: layer.byte_len,
616 token_estimate: layer.token_estimate,
617 sha256: layer.sha256,
618 tool_result: layer.tool_result.map(|result| ToolResultInspection {
619 original_chars: result.original_chars,
620 sent_chars: result.sent_chars,
621 truncated: result.truncated,
622 deduplicated: result.deduplicated,
623 }),
624 turn_meta: layer.turn_meta.map(|meta| TurnMetaInspection {
625 original_chars: meta.original_chars,
626 sent_chars: meta.sent_chars,
627 deduplicated: meta.deduplicated,
628 sha256: meta.sha256,
629 }),
630 })
631 .collect(),
632 }
633 }
634
635 pub(crate) fn warmup_key(key: CacheWarmupKey) -> DebugWarmupKey {
636 DebugWarmupKey {
637 provider: key.provider,
638 model: key.model,
639 base_url: key.base_url,
640 static_prefix_hash: key.static_prefix_hash,
641 tool_catalog_hash: key.tool_catalog_hash,
642 project_pack_hash: key.project_pack_hash,
643 skills_hash: key.skills_hash,
644 }
645 }
646
646 lines RUST