| 1 | //! Diagnostic prompt source map for context pressure reports. |
| 2 | //! |
| 3 | //! The report is approximate and describes the runtime sources CodeWhale |
| 4 | //! already tracks, without claiming provider-tokenizer parity. Its headline |
| 5 | //! (`active_context_estimated_tokens`) is the pressure estimate the context |
| 6 | //! meter and the auto-compaction gate read |
| 7 | //! (`compaction::estimate_input_tokens_for_pressure`, lifted to the last |
| 8 | //! provider-billed prompt). The 1.5x-inflated conservative estimate that |
| 9 | //! request-overflow protection uses is reported separately as the overflow |
| 10 | //! guard, never as the headline. Per-source entries keep the conservative |
| 11 | //! per-text heuristic. |
| 12 | |
| 13 | mod portable_projection; |
| 14 | pub(crate) use portable_projection::source_map as project_source_map; |
| 15 | |
| 16 | use std::path::Path; |
| 17 | |
| 18 | use chrono::{SecondsFormat, Utc}; |
| 19 | use serde::Serialize; |
| 20 | |
| 21 | use crate::tui::app::App; |
| 22 | use codewhale_config::AppMode; |
| 23 | use codewhale_engine::compaction::{ |
| 24 | estimate_input_tokens_conservative, estimate_input_tokens_for_pressure, |
| 25 | estimate_text_tokens_conservative, |
| 26 | }; |
| 27 | use codewhale_engine::prompts::CORE_EXECUTION_PROFILE_PROMPT; |
| 28 | use codewhale_localization::{MessageId, resolve_locale, tr}; |
| 29 | use codewhale_models::{CacheControl, ContentBlock, Message, SystemPrompt, Tool}; |
| 30 | use codewhale_runtime::config::Config; |
| 31 | #[cfg(test)] |
| 32 | use codewhale_runtime::context_budget::PressureLevel; |
| 33 | |
| 34 | #[derive(Debug, Clone, Serialize)] |
| 35 | pub struct PromptSourceMap { |
| 36 | pub entries: Vec<SourceEntry>, |
| 37 | pub total_estimated_tokens: usize, |
| 38 | /// Headline: the same pressure estimate the context meter and the |
| 39 | /// auto-compaction gate read, so `/context` never disagrees with them. |
| 40 | pub active_context_estimated_tokens: usize, |
| 41 | /// Secondary: the 1.5x-inflated conservative estimate request-overflow |
| 42 | /// protection guards with. `None` when there is no live conversation to |
| 43 | /// measure (headless doctor reports). |
| 44 | pub overflow_guard_estimated_tokens: Option<usize>, |
| 45 | pub context_window_tokens: Option<u32>, |
| 46 | /// Non-secret receipt for the effective context-window value. |
| 47 | pub context_window_source: Option<String>, |
| 48 | pub budget_used_percent: Option<f64>, |
| 49 | pub generated_at: String, |
| 50 | pub note: String, |
| 51 | } |
| 52 | |
| 53 | /// Inspectable request-prefix context for the current session. |
| 54 | /// |
| 55 | /// `PromptSourceMap` explains provenance and estimated pressure. This sibling |
| 56 | /// type exposes the current assembled system-prompt sections and most recently |
| 57 | /// sent model tool catalog so users can audit the prompt plumbing as JSON. |
| 58 | #[derive(Debug, Clone, Serialize)] |
| 59 | pub struct PromptContext { |
| 60 | pub schema_version: u8, |
| 61 | pub provider: String, |
| 62 | pub model: String, |
| 63 | pub system_prompt_state: &'static str, |
| 64 | pub tool_catalog_state: &'static str, |
| 65 | pub sections: Vec<PromptContextSection>, |
| 66 | pub tools: Vec<Tool>, |
| 67 | pub source_map: PromptSourceMap, |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug, Clone, Serialize)] |
| 71 | pub struct PromptContextSection { |
| 72 | pub index: usize, |
| 73 | pub block_type: String, |
| 74 | pub cache_control: Option<CacheControl>, |
| 75 | pub estimated_tokens: usize, |
| 76 | pub text: String, |
| 77 | } |
| 78 | |
| 79 | #[derive(Debug, Clone, Serialize)] |
| 80 | pub struct SourceEntry { |
| 81 | pub source_kind: SourceKind, |
| 82 | pub label: String, |
| 83 | pub source_path: Option<String>, |
| 84 | pub activation_reason: ActivationReason, |
| 85 | pub estimated_tokens: usize, |
| 86 | pub counting_confidence: CountingConfidence, |
| 87 | pub authority_tier: Option<u8>, |
| 88 | pub truncation_reason: Option<String>, |
| 89 | } |
| 90 | |
| 91 | impl SourceEntry { |
| 92 | fn text( |
| 93 | source_kind: SourceKind, |
| 94 | label: impl Into<String>, |
| 95 | source_path: Option<String>, |
| 96 | activation_reason: ActivationReason, |
| 97 | text: &str, |
| 98 | counting_confidence: CountingConfidence, |
| 99 | authority_tier: Option<u8>, |
| 100 | ) -> Self { |
| 101 | Self::estimate( |
| 102 | source_kind, |
| 103 | label, |
| 104 | source_path, |
| 105 | activation_reason, |
| 106 | estimate_text_tokens_conservative(text), |
| 107 | counting_confidence, |
| 108 | authority_tier, |
| 109 | ) |
| 110 | } |
| 111 | |
| 112 | fn estimate( |
| 113 | source_kind: SourceKind, |
| 114 | label: impl Into<String>, |
| 115 | source_path: Option<String>, |
| 116 | activation_reason: ActivationReason, |
| 117 | estimated_tokens: usize, |
| 118 | counting_confidence: CountingConfidence, |
| 119 | authority_tier: Option<u8>, |
| 120 | ) -> Self { |
| 121 | Self { |
| 122 | source_kind, |
| 123 | label: label.into(), |
| 124 | source_path, |
| 125 | activation_reason, |
| 126 | estimated_tokens, |
| 127 | counting_confidence, |
| 128 | authority_tier, |
| 129 | truncation_reason: None, |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | fn omitted( |
| 134 | source_kind: SourceKind, |
| 135 | label: impl Into<String>, |
| 136 | source_path: Option<String>, |
| 137 | authority_tier: Option<u8>, |
| 138 | reason: impl Into<String>, |
| 139 | ) -> Self { |
| 140 | Self { |
| 141 | source_kind, |
| 142 | label: label.into(), |
| 143 | source_path, |
| 144 | activation_reason: ActivationReason::Omitted, |
| 145 | estimated_tokens: 0, |
| 146 | counting_confidence: CountingConfidence::High, |
| 147 | authority_tier, |
| 148 | truncation_reason: Some(reason.into()), |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | fn diagnostic( |
| 153 | source_kind: SourceKind, |
| 154 | label: impl Into<String>, |
| 155 | source_path: Option<String>, |
| 156 | activation_reason: ActivationReason, |
| 157 | detail: impl Into<String>, |
| 158 | estimated_tokens: usize, |
| 159 | authority_tier: Option<u8>, |
| 160 | ) -> Self { |
| 161 | Self { |
| 162 | source_kind, |
| 163 | label: label.into(), |
| 164 | source_path, |
| 165 | activation_reason, |
| 166 | estimated_tokens, |
| 167 | counting_confidence: CountingConfidence::High, |
| 168 | authority_tier, |
| 169 | truncation_reason: Some(detail.into()), |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 175 | #[serde(rename_all = "snake_case")] |
| 176 | pub enum SourceKind { |
| 177 | Constitution, |
| 178 | UserConstitution, |
| 179 | RepoConstitution, |
| 180 | ProjectContext, |
| 181 | ProjectContextWarning, |
| 182 | ProjectContextPack, |
| 183 | SkillsBlock, |
| 184 | ContextManagement, |
| 185 | CompactionRelayTemplate, |
| 186 | RuntimePolicy, |
| 187 | AuthorityRecap, |
| 188 | EnvironmentBlock, |
| 189 | UserMemory, |
| 190 | SessionGoal, |
| 191 | HandoffRelay, |
| 192 | ToolSchemas, |
| 193 | UserRequest, |
| 194 | ConversationHistory, |
| 195 | ToolResult, |
| 196 | ModelProviderFact, |
| 197 | } |
| 198 | |
| 199 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 200 | #[serde(rename_all = "snake_case")] |
| 201 | pub enum ActivationReason { |
| 202 | AlwaysOn, |
| 203 | FilePresent, |
| 204 | ConfigEnabled, |
| 205 | RuntimeState, |
| 206 | PerRequest, |
| 207 | Omitted, |
| 208 | } |
| 209 | |
| 210 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] |
| 211 | #[serde(rename_all = "snake_case")] |
| 212 | pub enum CountingConfidence { |
| 213 | High, |
| 214 | Approximate, |
| 215 | } |
| 216 | |
| 217 | struct ReportBuilder { |
| 218 | entries: Vec<SourceEntry>, |
| 219 | } |
| 220 | |
| 221 | impl ReportBuilder { |
| 222 | fn new() -> Self { |
| 223 | Self { |
| 224 | entries: Vec::new(), |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | fn push(&mut self, entry: SourceEntry) { |
| 229 | self.entries.push(entry); |
| 230 | } |
| 231 | |
| 232 | /// The window arrives as one resolution rather than a number plus a |
| 233 | /// separately chosen label, so the report can never attribute one rung's |
| 234 | /// tokens to another rung. |
| 235 | fn finish( |
| 236 | self, |
| 237 | context_window: codewhale_engine::route_runtime::ContextWindowResolution, |
| 238 | active_context_estimated_tokens: usize, |
| 239 | overflow_guard_estimated_tokens: Option<usize>, |
| 240 | note: impl Into<String>, |
| 241 | ) -> PromptSourceMap { |
| 242 | let total_estimated_tokens = self |
| 243 | .entries |
| 244 | .iter() |
| 245 | .map(|entry| entry.estimated_tokens) |
| 246 | .sum(); |
| 247 | let budget_used_percent = |
| 248 | ((active_context_estimated_tokens as f64 / f64::from(context_window.tokens)) * 100.0) |
| 249 | .clamp(0.0, 100.0); |
| 250 | PromptSourceMap { |
| 251 | entries: self.entries, |
| 252 | total_estimated_tokens, |
| 253 | active_context_estimated_tokens, |
| 254 | overflow_guard_estimated_tokens, |
| 255 | context_window_tokens: Some(context_window.tokens), |
| 256 | context_window_source: Some(context_window.source.label().to_string()), |
| 257 | budget_used_percent: Some(budget_used_percent), |
| 258 | generated_at: Utc::now().to_rfc3339_opts(SecondsFormat::Secs, true), |
| 259 | note: note.into(), |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | pub fn build_context_report(app: &App) -> PromptSourceMap { |
| 265 | let context_window = codewhale_engine::route_runtime::ContextWindowResolution { |
| 266 | tokens: app.effective_context_window(), |
| 267 | source: app.effective_context_window_source(), |
| 268 | }; |
| 269 | let mut builder = base_source_entries( |
| 270 | &app.model, |
| 271 | &app.workspace, |
| 272 | Some(&app.skills_dir), |
| 273 | app.project_context_pack_enabled, |
| 274 | &app.skills_config, |
| 275 | app.ui_locale.tag(), |
| 276 | app.mode, |
| 277 | Some(app.plugin_registry.as_ref()), |
| 278 | Some(context_window.tokens), |
| 279 | app.instruction_assembly.as_deref(), |
| 280 | false, |
| 281 | ); |
| 282 | add_app_runtime_entries(&mut builder, app); |
| 283 | builder.finish( |
| 284 | context_window, |
| 285 | pressure_estimated_tokens(app), |
| 286 | Some(estimate_input_tokens_conservative( |
| 287 | &app.api_messages, |
| 288 | app.system_prompt.as_ref(), |
| 289 | )), |
| 290 | "Diagnostic source map. The headline is the pressure estimate the context meter and auto-compaction gate use; per-source counts are conservative estimates. All counts may differ from provider billing.", |
| 291 | ) |
| 292 | } |
| 293 | |
| 294 | /// The one pressure number the context meter and the auto-compaction gate |
| 295 | /// decide on: the un-inflated estimate over the live request, lifted to the |
| 296 | /// provider's last billed prompt when that is higher (#5577). |
| 297 | fn pressure_estimated_tokens(app: &App) -> usize { |
| 298 | let estimated = |
| 299 | estimate_input_tokens_for_pressure(&app.api_messages, app.system_prompt.as_ref()); |
| 300 | let billed = app |
| 301 | .last_billed_input_tokens |
| 302 | .and_then(|tokens| usize::try_from(tokens).ok()) |
| 303 | .unwrap_or(0); |
| 304 | estimated.max(billed) |
| 305 | } |
| 306 | |
| 307 | #[must_use] |
| 308 | pub fn build_prompt_context(app: &App) -> PromptContext { |
| 309 | let tool_catalog_state = if app.session.last_tool_catalog.is_some() { |
| 310 | "last_sent" |
| 311 | } else { |
| 312 | "not_yet_sent" |
| 313 | }; |
| 314 | let sections = match app.system_prompt.as_ref() { |
| 315 | Some(SystemPrompt::Text(text)) => vec![PromptContextSection { |
| 316 | index: 0, |
| 317 | block_type: "text".to_string(), |
| 318 | cache_control: None, |
| 319 | estimated_tokens: estimate_text_tokens_conservative(text), |
| 320 | text: text.clone(), |
| 321 | }], |
| 322 | Some(SystemPrompt::Blocks(blocks)) => blocks |
| 323 | .iter() |
| 324 | .enumerate() |
| 325 | .map(|(index, block)| PromptContextSection { |
| 326 | index, |
| 327 | block_type: block.block_type.clone(), |
| 328 | cache_control: block.cache_control.clone(), |
| 329 | estimated_tokens: estimate_text_tokens_conservative(&block.text), |
| 330 | text: block.text.clone(), |
| 331 | }) |
| 332 | .collect(), |
| 333 | None => Vec::new(), |
| 334 | }; |
| 335 | PromptContext { |
| 336 | schema_version: 1, |
| 337 | provider: app.api_provider.as_str().to_string(), |
| 338 | model: app.model.clone(), |
| 339 | system_prompt_state: "current_session", |
| 340 | tool_catalog_state, |
| 341 | sections, |
| 342 | tools: app.session.last_tool_catalog.clone().unwrap_or_default(), |
| 343 | source_map: build_context_report(app), |
| 344 | } |
| 345 | } |
| 346 | |
| 347 | pub fn build_headless_context_report(config: &Config, workspace: &Path) -> PromptSourceMap { |
| 348 | let model = config.default_model(); |
| 349 | let identity = config.active_provider_identity().ok(); |
| 350 | let provider = identity |
| 351 | .as_ref() |
| 352 | .map_or(codewhale_config::ProviderKind::Custom, |identity| { |
| 353 | identity.provider |
| 354 | }); |
| 355 | let provider_identity = identity |
| 356 | .as_ref() |
| 357 | .map(|identity| identity.key.to_string()) |
| 358 | .unwrap_or_else(|| "unavailable".to_string()); |
| 359 | let route = identity.as_ref().and_then(|identity| { |
| 360 | codewhale_engine::route_runtime::resolve_runtime_route_for_identity( |
| 361 | config, |
| 362 | identity, |
| 363 | Some(&model), |
| 364 | ) |
| 365 | .ok() |
| 366 | }); |
| 367 | // A route we could not resolve does not erase an operator-configured |
| 368 | // window: doctor must report the same number the session would use. |
| 369 | let context_window = route.as_ref().map_or_else( |
| 370 | || { |
| 371 | codewhale_engine::route_runtime::resolve_context_window( |
| 372 | provider, |
| 373 | &model, |
| 374 | None, |
| 375 | identity |
| 376 | .as_ref() |
| 377 | .and_then(|identity| config.context_window_for_provider_config(identity)), |
| 378 | identity |
| 379 | .as_ref() |
| 380 | .and_then(|identity| config.model_context_windows_for(identity)), |
| 381 | ) |
| 382 | }, |
| 383 | |route| route.context_window, |
| 384 | ); |
| 385 | let global_skills_dir = config.skills_dir(); |
| 386 | let selected_skills_dir = |
| 387 | crate::tui::app::resolve_skills_dir(workspace, &global_skills_dir, config); |
| 388 | let settings = codewhale_engine::project_context::InstructionSettings::from_config(config); |
| 389 | let configured: Vec<_> = config |
| 390 | .instructions_paths() |
| 391 | .into_iter() |
| 392 | .map(Into::into) |
| 393 | .collect(); |
| 394 | let mut raw = codewhale_engine::project_context::capture_instruction_context( |
| 395 | workspace, |
| 396 | &configured, |
| 397 | &settings, |
| 398 | ); |
| 399 | let limits = route.as_ref().and_then(|route| { |
| 400 | codewhale_engine::route_budget::known_route_limits(route.candidate.limits()) |
| 401 | }); |
| 402 | let budgets = codewhale_engine::project_context::InstructionBudgets::resolve_or_default( |
| 403 | &settings.budget, |
| 404 | context_window.instruction_budget_tokens(), |
| 405 | Some( |
| 406 | codewhale_engine::route_budget::effective_max_output_tokens_for_turn_with_window( |
| 407 | provider, |
| 408 | &model, |
| 409 | limits, |
| 410 | Some(context_window.tokens), |
| 411 | None, |
| 412 | codewhale_engine::core::engine::turn_loop::resolve_auto_effort( |
| 413 | config.reasoning_effort(), |
| 414 | provider, |
| 415 | &config.active_route_base_url(), |
| 416 | &model, |
| 417 | ) |
| 418 | .as_deref(), |
| 419 | ) as usize, |
| 420 | ), |
| 421 | ); |
| 422 | let assembly = |
| 423 | codewhale_engine::project_context::assemble_instruction_block(&mut raw, &[], &budgets); |
| 424 | let mut builder = base_source_entries( |
| 425 | &model, |
| 426 | workspace, |
| 427 | Some(&selected_skills_dir), |
| 428 | config.project_context_pack_enabled(), |
| 429 | &config.skills_config(), |
| 430 | "en", |
| 431 | AppMode::Agent, |
| 432 | None, |
| 433 | Some(context_window.tokens), |
| 434 | Some(&assembly), |
| 435 | true, |
| 436 | ); |
| 437 | let memory_path = config.memory_path(); |
| 438 | let memory_enabled = config.memory_enabled(); |
| 439 | |
| 440 | if let Some(memory_block) = codewhale_runtime::native_memory::native_prompt_block( |
| 441 | memory_enabled, |
| 442 | &memory_path, |
| 443 | workspace, |
| 444 | ) { |
| 445 | builder.push(SourceEntry::text( |
| 446 | SourceKind::UserMemory, |
| 447 | "User memory", |
| 448 | Some(memory_path.display().to_string()), |
| 449 | ActivationReason::ConfigEnabled, |
| 450 | &memory_block, |
| 451 | CountingConfidence::High, |
| 452 | Some(6), |
| 453 | )); |
| 454 | } else { |
| 455 | builder.push(SourceEntry::omitted( |
| 456 | SourceKind::UserMemory, |
| 457 | "User memory", |
| 458 | Some(memory_path.display().to_string()), |
| 459 | Some(6), |
| 460 | "disabled, missing, or empty", |
| 461 | )); |
| 462 | } |
| 463 | |
| 464 | builder.push(SourceEntry::text( |
| 465 | SourceKind::ModelProviderFact, |
| 466 | format!("Provider facts ({provider_identity})"), |
| 467 | None, |
| 468 | ActivationReason::RuntimeState, |
| 469 | &format!( |
| 470 | "provider: {}\nmodel: {}\ncontext_window: {}\ncontext_window_source: {}", |
| 471 | provider_identity, |
| 472 | model, |
| 473 | context_window.tokens, |
| 474 | context_window.source.label() |
| 475 | ), |
| 476 | CountingConfidence::Approximate, |
| 477 | None, |
| 478 | )); |
| 479 | |
| 480 | let active_context_estimated_tokens = builder |
| 481 | .entries |
| 482 | .iter() |
| 483 | .map(|entry| entry.estimated_tokens) |
| 484 | .sum(); |
| 485 | builder.finish( |
| 486 | context_window, |
| 487 | active_context_estimated_tokens, |
| 488 | None, |
| 489 | "Headless diagnostic source map. Conversation, tool results, and live TUI state are unavailable in doctor mode.", |
| 490 | ) |
| 491 | } |
| 492 | |
| 493 | fn known_tokens(value: Option<usize>) -> String { |
| 494 | value.map_or_else( |
| 495 | || "unknown".to_string(), |
| 496 | |tokens| format!("{tokens} tokens"), |
| 497 | ) |
| 498 | } |
| 499 | |
| 500 | #[allow(clippy::too_many_arguments)] |
| 501 | fn base_source_entries( |
| 502 | model: &str, |
| 503 | workspace: &Path, |
| 504 | skills_dir: Option<&Path>, |
| 505 | project_pack_enabled: bool, |
| 506 | skills_config: &codewhale_runtime::config::SkillsConfig, |
| 507 | locale_tag: &str, |
| 508 | mode: AppMode, |
| 509 | plugin_registry: Option<&codewhale_plugins::PluginRegistry>, |
| 510 | context_window_tokens: Option<u32>, |
| 511 | instruction_assembly: Option<&codewhale_engine::project_context::InstructionAssembly>, |
| 512 | instruction_preview: bool, |
| 513 | ) -> ReportBuilder { |
| 514 | let mut builder = ReportBuilder::new(); |
| 515 | |
| 516 | let constitution = codewhale_engine::prompts::compose_default_static_layers(model); |
| 517 | builder.push(SourceEntry::text( |
| 518 | SourceKind::Constitution, |
| 519 | "Bundled constitution, language policy, and output policy", |
| 520 | Some( |
| 521 | codewhale_engine::prompts::base_prompt_origin() |
| 522 | .label() |
| 523 | .to_string(), |
| 524 | ), |
| 525 | ActivationReason::AlwaysOn, |
| 526 | &constitution, |
| 527 | CountingConfidence::High, |
| 528 | Some(1), |
| 529 | )); |
| 530 | |
| 531 | if let Some(block) = codewhale_engine::prompts::load_user_constitution_block() { |
| 532 | builder.push(SourceEntry::text( |
| 533 | SourceKind::UserConstitution, |
| 534 | "User-global constitution", |
| 535 | codewhale_config::UserConstitution::path() |
| 536 | .ok() |
| 537 | .map(|path| path.display().to_string()), |
| 538 | ActivationReason::FilePresent, |
| 539 | &block, |
| 540 | CountingConfidence::High, |
| 541 | Some(2), |
| 542 | )); |
| 543 | } |
| 544 | |
| 545 | match instruction_assembly { |
| 546 | Some(assembly) => { |
| 547 | if assembly.constitution_tokens > 0 { |
| 548 | let mut entry = SourceEntry::diagnostic( |
| 549 | SourceKind::RepoConstitution, |
| 550 | "Repository constitution", |
| 551 | assembly |
| 552 | .constitution_source_path |
| 553 | .as_ref() |
| 554 | .map(|path| path.display().to_string()), |
| 555 | ActivationReason::FilePresent, |
| 556 | "included in installed instruction block", |
| 557 | assembly.constitution_tokens, |
| 558 | Some(4), |
| 559 | ); |
| 560 | entry.truncation_reason = None; |
| 561 | builder.push(entry); |
| 562 | } |
| 563 | match assembly.block.as_deref() { |
| 564 | Some(block) => { |
| 565 | let mut entry = SourceEntry::text( |
| 566 | SourceKind::ProjectContext, |
| 567 | "Project instructions", |
| 568 | assembly |
| 569 | .source_path |
| 570 | .as_ref() |
| 571 | .map(|path| path.display().to_string()), |
| 572 | ActivationReason::FilePresent, |
| 573 | block, |
| 574 | CountingConfidence::High, |
| 575 | Some(5), |
| 576 | ); |
| 577 | entry.estimated_tokens = entry |
| 578 | .estimated_tokens |
| 579 | .saturating_sub(assembly.constitution_tokens); |
| 580 | builder.push(entry); |
| 581 | } |
| 582 | None => builder.push(SourceEntry::omitted( |
| 583 | SourceKind::ProjectContext, |
| 584 | "Project context and repository instructions", |
| 585 | Some(workspace.display().to_string()), |
| 586 | Some(5), |
| 587 | "no project context block available", |
| 588 | )), |
| 589 | } |
| 590 | let budget_label = if instruction_preview { |
| 591 | "Instruction budget (preview)" |
| 592 | } else { |
| 593 | "Instruction budget" |
| 594 | }; |
| 595 | let basis = if instruction_preview { |
| 596 | "preview from current files and config; no installed receipt and no tool schemas measured" |
| 597 | } else { |
| 598 | "installed receipt" |
| 599 | }; |
| 600 | builder.push(SourceEntry::diagnostic( |
| 601 | SourceKind::ProjectContext, |
| 602 | budget_label, |
| 603 | None::<String>, |
| 604 | ActivationReason::ConfigEnabled, |
| 605 | format!( |
| 606 | "{basis}; global {} / {} estimated tokens; project {} / {} estimated tokens; policy {}; usable window {}; static-prefix guard {}", |
| 607 | assembly.global_tokens, |
| 608 | assembly.budgets.global_tokens, |
| 609 | assembly.project_tokens, |
| 610 | assembly.budgets.project_tokens, |
| 611 | assembly.budgets.policy.as_str(), |
| 612 | known_tokens(assembly.budgets.usable_window_tokens), |
| 613 | known_tokens(assembly.budgets.static_guard_tokens), |
| 614 | ), |
| 615 | 0, |
| 616 | Some(5), |
| 617 | )); |
| 618 | let locale = codewhale_localization::resolve_locale(locale_tag); |
| 619 | for notice in assembly.notices.iter().filter(|notice| notice.is_loss()) { |
| 620 | builder.push(SourceEntry::diagnostic( |
| 621 | SourceKind::ProjectContextWarning, |
| 622 | format!("Instruction source: {}", notice.label()), |
| 623 | notice.path.as_ref().map(|path| path.display().to_string()), |
| 624 | ActivationReason::RuntimeState, |
| 625 | notice.render(locale), |
| 626 | 0, |
| 627 | Some(5), |
| 628 | )); |
| 629 | } |
| 630 | if !assembly.warnings.is_empty() { |
| 631 | builder.push(SourceEntry::diagnostic( |
| 632 | SourceKind::ProjectContextWarning, |
| 633 | "Project context warnings", |
| 634 | Some(workspace.display().to_string()), |
| 635 | ActivationReason::RuntimeState, |
| 636 | assembly.warnings.join("\n"), |
| 637 | 0, |
| 638 | Some(4), |
| 639 | )); |
| 640 | } |
| 641 | } |
| 642 | None => builder.push(SourceEntry::omitted( |
| 643 | SourceKind::ProjectContext, |
| 644 | "Project instructions", |
| 645 | None::<String>, |
| 646 | Some(5), |
| 647 | "installed instruction receipt unavailable", |
| 648 | )), |
| 649 | } |
| 650 | |
| 651 | if project_pack_enabled { |
| 652 | if let Some(pack) = |
| 653 | codewhale_engine::project_context::generate_project_context_pack(workspace) |
| 654 | { |
| 655 | builder.push(SourceEntry::text( |
| 656 | SourceKind::ProjectContextPack, |
| 657 | "Project context pack", |
| 658 | Some(workspace.display().to_string()), |
| 659 | ActivationReason::ConfigEnabled, |
| 660 | &pack, |
| 661 | CountingConfidence::Approximate, |
| 662 | Some(5), |
| 663 | )); |
| 664 | } |
| 665 | } else { |
| 666 | builder.push(SourceEntry::omitted( |
| 667 | SourceKind::ProjectContextPack, |
| 668 | "Project context pack", |
| 669 | Some(workspace.display().to_string()), |
| 670 | Some(5), |
| 671 | "disabled; project_map provides this information on demand", |
| 672 | )); |
| 673 | } |
| 674 | |
| 675 | let skills_block = codewhale_skills::render_index( |
| 676 | workspace, |
| 677 | skills_dir, |
| 678 | skills_config, |
| 679 | locale_tag, |
| 680 | plugin_registry, |
| 681 | context_window_tokens, |
| 682 | ); |
| 683 | let skills_detail = skills_block.map_or_else( |
| 684 | || "no skills discovered".to_string(), |
| 685 | |block| { |
| 686 | let label = tr(resolve_locale(locale_tag), MessageId::ConfigPreviewLabel); |
| 687 | let tokens = known_tokens(Some(estimate_text_tokens_conservative(&block))); |
| 688 | let mut detail = format!("{label}≈ {tokens} · load_skill"); |
| 689 | if let Some(note) = codewhale_skills::shortened_skills_note(&block) { |
| 690 | detail.push_str(". "); |
| 691 | detail.push_str(¬e); |
| 692 | } |
| 693 | detail |
| 694 | }, |
| 695 | ); |
| 696 | builder.push(SourceEntry::omitted( |
| 697 | SourceKind::SkillsBlock, |
| 698 | "Available skills", |
| 699 | skills_dir.map(|path| path.display().to_string()), |
| 700 | Some(5), |
| 701 | skills_detail, |
| 702 | )); |
| 703 | |
| 704 | builder.push(SourceEntry::omitted( |
| 705 | SourceKind::ContextManagement, |
| 706 | format!("{} runtime mode", mode.label()), |
| 707 | None, |
| 708 | Some(3), |
| 709 | "mode enforced by runtime policy and the live tool catalog; no prompt doctrine", |
| 710 | )); |
| 711 | builder.push(SourceEntry::omitted( |
| 712 | SourceKind::CompactionRelayTemplate, |
| 713 | "Session relay template", |
| 714 | Some("bundled in this codewhale-engine build (COMPACT_TEMPLATE, compiled in)".to_string()), |
| 715 | Some(3), |
| 716 | "loaded only when /relay is requested; automatic compaction owns its successor brief", |
| 717 | )); |
| 718 | builder.push(SourceEntry::text( |
| 719 | SourceKind::RuntimePolicy, |
| 720 | "Core execution discipline", |
| 721 | None, |
| 722 | ActivationReason::AlwaysOn, |
| 723 | CORE_EXECUTION_PROFILE_PROMPT, |
| 724 | CountingConfidence::High, |
| 725 | Some(3), |
| 726 | )); |
| 727 | builder.push(SourceEntry::text( |
| 728 | SourceKind::AuthorityRecap, |
| 729 | "Authority recap", |
| 730 | None, |
| 731 | ActivationReason::AlwaysOn, |
| 732 | codewhale_engine::prompts::effective_authority_recap(), |
| 733 | CountingConfidence::High, |
| 734 | Some(1), |
| 735 | )); |
| 736 | builder.push(SourceEntry::text( |
| 737 | SourceKind::EnvironmentBlock, |
| 738 | "Runtime environment", |
| 739 | Some(workspace.display().to_string()), |
| 740 | ActivationReason::AlwaysOn, |
| 741 | &codewhale_engine::prompts::render_environment_block(workspace, locale_tag), |
| 742 | CountingConfidence::High, |
| 743 | Some(4), |
| 744 | )); |
| 745 | |
| 746 | add_handoff_entry(&mut builder, workspace); |
| 747 | builder |
| 748 | } |
| 749 | |
| 750 | fn add_app_runtime_entries(builder: &mut ReportBuilder, app: &App) { |
| 751 | if let Some(memory_block) = codewhale_runtime::native_memory::native_prompt_block( |
| 752 | app.use_memory, |
| 753 | &app.memory_path, |
| 754 | &app.workspace, |
| 755 | ) { |
| 756 | builder.push(SourceEntry::text( |
| 757 | SourceKind::UserMemory, |
| 758 | "User memory", |
| 759 | Some(app.memory_path.display().to_string()), |
| 760 | ActivationReason::ConfigEnabled, |
| 761 | &memory_block, |
| 762 | CountingConfidence::High, |
| 763 | Some(6), |
| 764 | )); |
| 765 | } else { |
| 766 | builder.push(SourceEntry::omitted( |
| 767 | SourceKind::UserMemory, |
| 768 | "User memory", |
| 769 | Some(app.memory_path.display().to_string()), |
| 770 | Some(6), |
| 771 | "disabled, missing, or empty", |
| 772 | )); |
| 773 | } |
| 774 | |
| 775 | if let Some(goal) = app |
| 776 | .goal |
| 777 | .objective |
| 778 | .as_deref() |
| 779 | .filter(|goal| !goal.trim().is_empty()) |
| 780 | { |
| 781 | builder.push(SourceEntry::text( |
| 782 | SourceKind::SessionGoal, |
| 783 | "Session goal", |
| 784 | None, |
| 785 | ActivationReason::RuntimeState, |
| 786 | goal, |
| 787 | CountingConfidence::High, |
| 788 | Some(6), |
| 789 | )); |
| 790 | } else { |
| 791 | builder.push(SourceEntry::omitted( |
| 792 | SourceKind::SessionGoal, |
| 793 | "Session goal", |
| 794 | None, |
| 795 | Some(6), |
| 796 | "no active /goal objective", |
| 797 | )); |
| 798 | } |
| 799 | |
| 800 | if let Some(tools) = app.session.last_tool_catalog.as_ref() { |
| 801 | let rendered = serde_json::to_string(tools).unwrap_or_default(); |
| 802 | builder.push(SourceEntry::text( |
| 803 | SourceKind::ToolSchemas, |
| 804 | format!("Tool schemas ({} tools)", tools.len()), |
| 805 | None, |
| 806 | ActivationReason::PerRequest, |
| 807 | &rendered, |
| 808 | CountingConfidence::Approximate, |
| 809 | Some(3), |
| 810 | )); |
| 811 | } else { |
| 812 | builder.push(SourceEntry::omitted( |
| 813 | SourceKind::ToolSchemas, |
| 814 | "Tool schemas", |
| 815 | None, |
| 816 | Some(3), |
| 817 | "no tool catalog has been sent yet", |
| 818 | )); |
| 819 | } |
| 820 | |
| 821 | add_message_entries(builder, &app.api_messages); |
| 822 | } |
| 823 | |
| 824 | fn add_handoff_entry(builder: &mut ReportBuilder, workspace: &Path) { |
| 825 | let (path, _) = codewhale_engine::prompts::resolve_handoff_path(workspace); |
| 826 | let Some(raw) = std::fs::read_to_string(&path) |
| 827 | .ok() |
| 828 | .filter(|raw| !raw.trim().is_empty()) |
| 829 | else { |
| 830 | builder.push(SourceEntry::omitted( |
| 831 | SourceKind::HandoffRelay, |
| 832 | "Previous session relay", |
| 833 | Some( |
| 834 | workspace |
| 835 | .join(codewhale_engine::prompts::HANDOFF_RELATIVE_PATH) |
| 836 | .display() |
| 837 | .to_string(), |
| 838 | ), |
| 839 | Some(6), |
| 840 | "no relay artifact found", |
| 841 | )); |
| 842 | return; |
| 843 | }; |
| 844 | |
| 845 | builder.push(SourceEntry::text( |
| 846 | SourceKind::HandoffRelay, |
| 847 | "Previous session relay", |
| 848 | Some(path.display().to_string()), |
| 849 | ActivationReason::FilePresent, |
| 850 | &raw, |
| 851 | CountingConfidence::High, |
| 852 | Some(6), |
| 853 | )); |
| 854 | } |
| 855 | |
| 856 | fn add_message_entries(builder: &mut ReportBuilder, messages: &[Message]) { |
| 857 | if messages.is_empty() { |
| 858 | builder.push(SourceEntry::omitted( |
| 859 | SourceKind::ConversationHistory, |
| 860 | "Conversation history", |
| 861 | None, |
| 862 | None, |
| 863 | "no API messages yet", |
| 864 | )); |
| 865 | return; |
| 866 | } |
| 867 | |
| 868 | let latest_user = messages.iter().rposition(|message| message.role == "user"); |
| 869 | let mut latest_user_tokens = 0usize; |
| 870 | let mut conversation_tokens = 0usize; |
| 871 | let mut tool_result_tokens = 0usize; |
| 872 | let mut tool_result_count = 0usize; |
| 873 | |
| 874 | for (index, message) in messages.iter().enumerate() { |
| 875 | for block in &message.content { |
| 876 | let tokens = estimate_text_tokens_conservative(&content_block_text(block)); |
| 877 | match block { |
| 878 | ContentBlock::ToolResult { .. } |
| 879 | | ContentBlock::ToolSearchToolResult { .. } |
| 880 | | ContentBlock::CodeExecutionToolResult { .. } |
| 881 | | ContentBlock::WebSearchToolResult { .. } |
| 882 | | ContentBlock::WebFetchToolResult { .. } => { |
| 883 | tool_result_tokens += tokens; |
| 884 | tool_result_count += 1; |
| 885 | } |
| 886 | ContentBlock::Text { .. } if Some(index) == latest_user => { |
| 887 | latest_user_tokens += tokens; |
| 888 | } |
| 889 | _ => { |
| 890 | conversation_tokens += tokens; |
| 891 | } |
| 892 | } |
| 893 | } |
| 894 | } |
| 895 | |
| 896 | if latest_user_tokens > 0 { |
| 897 | builder.push(SourceEntry::estimate( |
| 898 | SourceKind::UserRequest, |
| 899 | "Latest user request", |
| 900 | None, |
| 901 | ActivationReason::PerRequest, |
| 902 | latest_user_tokens, |
| 903 | CountingConfidence::High, |
| 904 | Some(7), |
| 905 | )); |
| 906 | } |
| 907 | if conversation_tokens > 0 { |
| 908 | builder.push(SourceEntry::estimate( |
| 909 | SourceKind::ConversationHistory, |
| 910 | "Conversation history", |
| 911 | None, |
| 912 | ActivationReason::RuntimeState, |
| 913 | conversation_tokens, |
| 914 | CountingConfidence::High, |
| 915 | None, |
| 916 | )); |
| 917 | } |
| 918 | if tool_result_count > 0 { |
| 919 | builder.push(SourceEntry::estimate( |
| 920 | SourceKind::ToolResult, |
| 921 | format!("Tool results ({tool_result_count})"), |
| 922 | None, |
| 923 | ActivationReason::RuntimeState, |
| 924 | tool_result_tokens, |
| 925 | CountingConfidence::High, |
| 926 | None, |
| 927 | )); |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | fn content_block_text(block: &ContentBlock) -> String { |
| 932 | match block { |
| 933 | ContentBlock::Text { text, .. } => text.clone(), |
| 934 | ContentBlock::Thinking { thinking, .. } => thinking.clone(), |
| 935 | ContentBlock::ToolResult { content, .. } => content.clone(), |
| 936 | ContentBlock::ToolSearchToolResult { content, .. } |
| 937 | | ContentBlock::CodeExecutionToolResult { content, .. } |
| 938 | | ContentBlock::WebSearchToolResult { content, .. } |
| 939 | | ContentBlock::WebFetchToolResult { content, .. } => content.to_string(), |
| 940 | ContentBlock::ToolUse { input, .. } | ContentBlock::ServerToolUse { input, .. } => { |
| 941 | input.to_string() |
| 942 | } |
| 943 | ContentBlock::WebSearchCall { |
| 944 | action, |
| 945 | sources, |
| 946 | page, |
| 947 | .. |
| 948 | } => serde_json::json!({ "action": action, "sources": sources, "page": page }).to_string(), |
| 949 | ContentBlock::ServerToolCalls { steps } => { |
| 950 | serde_json::Value::Array(steps.clone()).to_string() |
| 951 | } |
| 952 | ContentBlock::File { file_id } => file_id.clone(), |
| 953 | ContentBlock::ImageUrl { image_url } => image_url.url.clone(), |
| 954 | } |
| 955 | } |
| 956 | |
| 957 | #[cfg(test)] |
| 958 | fn pressure_label(percent: Option<f64>) -> &'static str { |
| 959 | // Delegate to the unified pressure thresholds so this diagnostic label can't |
| 960 | // drift from `context_budget::PressureLevel`. `None` (unknown window) keeps |
| 961 | // its own sentinel since a level requires a usage percentage. |
| 962 | match percent { |
| 963 | Some(value) => PressureLevel::from_usage_percent(value).label(), |
| 964 | None => "unknown", |
| 965 | } |
| 966 | } |
| 967 | |
| 968 | #[cfg(test)] |
| 969 | pub fn format_context_report(report: &PromptSourceMap) -> String { |
| 970 | codewhale_commands::diagnostics_reports::format_context_report(&project_source_map( |
| 971 | report.clone(), |
| 972 | )) |
| 973 | } |
| 974 | |
| 975 | #[cfg(test)] |
| 976 | pub fn format_context_summary(report: &PromptSourceMap) -> String { |
| 977 | codewhale_commands::diagnostics_reports::format_context_summary(&project_source_map( |
| 978 | report.clone(), |
| 979 | )) |
| 980 | } |
| 981 | |
| 982 | pub fn context_report_json(report: &PromptSourceMap) -> String { |
| 983 | codewhale_commands::diagnostics_reports::context_report_json(&project_source_map( |
| 984 | report.clone(), |
| 985 | )) |
| 986 | } |
| 987 | |
| 988 | #[cfg(test)] |
| 989 | mod pressure_fixture_tests; |
| 990 | |
| 991 | #[cfg(test)] |
| 992 | mod tests { |
| 993 | use super::*; |
| 994 | use codewhale_config::ProviderKind; |
| 995 | use codewhale_config::route::RouteLimits; |
| 996 | use codewhale_engine::route_runtime::{ContextWindowResolution, ContextWindowSource}; |
| 997 | use codewhale_models::Role; |
| 998 | use codewhale_models::Tool; |
| 999 | use codewhale_runtime::config::Config; |
| 1000 | use std::fs; |
| 1001 | use tempfile::tempdir; |
| 1002 | |
| 1003 | #[test] |
| 1004 | fn context_report_json_contains_sources_and_tool_results() { |
| 1005 | let messages = vec![ |
| 1006 | Message { |
| 1007 | role: Role::User, |
| 1008 | content: vec![ContentBlock::Text { |
| 1009 | text: "read src/lib.rs".to_string(), |
| 1010 | cache_control: None, |
| 1011 | }], |
| 1012 | }, |
| 1013 | Message { |
| 1014 | role: Role::Assistant, |
| 1015 | content: vec![ContentBlock::ToolResult { |
| 1016 | execution_id: None, |
| 1017 | tool_use_id: "call_1".to_string(), |
| 1018 | content: "large tool output".repeat(40), |
| 1019 | is_error: None, |
| 1020 | content_blocks: None, |
| 1021 | }], |
| 1022 | }, |
| 1023 | ]; |
| 1024 | let mut builder = ReportBuilder::new(); |
| 1025 | builder.push(SourceEntry::text( |
| 1026 | SourceKind::Constitution, |
| 1027 | "Test static", |
| 1028 | None, |
| 1029 | ActivationReason::AlwaysOn, |
| 1030 | "static", |
| 1031 | CountingConfidence::High, |
| 1032 | Some(1), |
| 1033 | )); |
| 1034 | add_message_entries(&mut builder, &messages); |
| 1035 | let report = builder.finish( |
| 1036 | ContextWindowResolution { |
| 1037 | tokens: 128_000, |
| 1038 | source: ContextWindowSource::Fallback, |
| 1039 | }, |
| 1040 | 123, |
| 1041 | Some(185), |
| 1042 | "test", |
| 1043 | ); |
| 1044 | let json = context_report_json(&report); |
| 1045 | |
| 1046 | assert!(json.contains("\"source_kind\": \"tool_result\"")); |
| 1047 | assert!(json.contains("\"active_context_estimated_tokens\": 123")); |
| 1048 | assert!(json.contains("\"overflow_guard_estimated_tokens\": 185")); |
| 1049 | } |
| 1050 | |
| 1051 | #[test] |
| 1052 | fn headless_skill_catalog_preview_does_not_count_toward_prompt_tokens() { |
| 1053 | let workspace = tempdir().expect("workspace"); |
| 1054 | let skills = tempdir().expect("skills"); |
| 1055 | let skill_dir = skills.path().join("fixture-skill-preview"); |
| 1056 | fs::create_dir(&skill_dir).expect("create skill directory"); |
| 1057 | fs::write( |
| 1058 | skill_dir.join("SKILL.md"), |
| 1059 | "---\nname: fixture-skill-preview\ndescription: A long fixture description used to verify that catalog shortening stays visible.\n---\nInstructions.\n", |
| 1060 | ) |
| 1061 | .expect("write skill"); |
| 1062 | |
| 1063 | let config: Config = toml::from_str(&format!( |
| 1064 | "skills_dir = {}\n[skills]\nlisting_max_description_chars = 8", |
| 1065 | toml::Value::String(skills.path().to_string_lossy().into_owned()) |
| 1066 | )) |
| 1067 | .expect("read config"); |
| 1068 | let report = build_headless_context_report(&config, workspace.path()); |
| 1069 | let json: serde_json::Value = |
| 1070 | serde_json::from_str(&context_report_json(&report)).expect("read context report JSON"); |
| 1071 | let skills_entry = json["entries"] |
| 1072 | .as_array() |
| 1073 | .expect("source entries") |
| 1074 | .iter() |
| 1075 | .find(|entry| entry["source_kind"] == "skills_block") |
| 1076 | .expect("skills source"); |
| 1077 | |
| 1078 | assert_eq!(skills_entry["activation_reason"], "omitted"); |
| 1079 | assert_eq!(skills_entry["estimated_tokens"], 0); |
| 1080 | let detail = skills_entry["truncation_reason"] |
| 1081 | .as_str() |
| 1082 | .expect("catalog preview detail"); |
| 1083 | assert!(detail.starts_with("Preview: ≈ "), "{detail}"); |
| 1084 | assert!(detail.contains("tokens · load_skill"), "{detail}"); |
| 1085 | assert!(detail.contains("descriptions shortened"), "{detail}"); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn context_report_surfaces_repo_constitution_source_and_warnings() { |
| 1090 | let tmp = tempdir().expect("tempdir"); |
| 1091 | fs::create_dir(tmp.path().join(".git")).expect("mkdir .git"); |
| 1092 | fs::create_dir(tmp.path().join(".codewhale")).expect("mkdir .codewhale"); |
| 1093 | fs::write( |
| 1094 | tmp.path().join(".codewhale").join("constitution.json"), |
| 1095 | r#"{ |
| 1096 | "schema_version": 1, |
| 1097 | "authority": ["current user request"], |
| 1098 | "branch_policy": "v0.8.53 work targets the codex/v0.8.53 integration branch, not main" |
| 1099 | }"#, |
| 1100 | ) |
| 1101 | .expect("write constitution"); |
| 1102 | |
| 1103 | let report = build_headless_context_report(&Config::default(), tmp.path()); |
| 1104 | assert!( |
| 1105 | report.entries.iter().any(|entry| { |
| 1106 | entry.source_kind == SourceKind::RepoConstitution |
| 1107 | && entry.source_path.as_deref().is_some_and(|path| { |
| 1108 | path.replace('\\', "/") |
| 1109 | .ends_with(".codewhale/constitution.json") |
| 1110 | }) |
| 1111 | }), |
| 1112 | "repo constitution source should be an explicit source-map entry: {:?}", |
| 1113 | report.entries |
| 1114 | ); |
| 1115 | assert!( |
| 1116 | report.entries.iter().any(|entry| { |
| 1117 | entry.source_kind == SourceKind::ProjectContextWarning |
| 1118 | && entry |
| 1119 | .truncation_reason |
| 1120 | .as_deref() |
| 1121 | .is_some_and(|reason| reason.contains("branch_policy appears stale")) |
| 1122 | && entry.estimated_tokens == 0 |
| 1123 | }), |
| 1124 | "repo constitution warnings should be explicit source-map entries: {:?}", |
| 1125 | report.entries |
| 1126 | ); |
| 1127 | |
| 1128 | let formatted = format_context_report(&report); |
| 1129 | assert!(formatted.contains("Repository constitution")); |
| 1130 | assert!(formatted.contains("Project context warnings")); |
| 1131 | assert!(formatted.contains("/constitution")); |
| 1132 | assert!(formatted.contains("/setup report")); |
| 1133 | let json = context_report_json(&report); |
| 1134 | assert!(json.contains("\"repo_constitution\"")); |
| 1135 | assert!(json.contains("branch_policy appears stale")); |
| 1136 | } |
| 1137 | |
| 1138 | #[test] |
| 1139 | fn context_report_shows_actions_and_budgets() { |
| 1140 | let tmp = tempdir().expect("workspace"); |
| 1141 | std::fs::write(tmp.path().join("AGENTS.md"), "T".repeat(20_000)).expect("write agents"); |
| 1142 | let config = { |
| 1143 | let __cw_config_init_0_0 = |
| 1144 | Some(codewhale_engine::project_context::InstructionBudgetConfig { |
| 1145 | project_budget_tokens: Some(50), |
| 1146 | ..Default::default() |
| 1147 | }); |
| 1148 | let mut __cw_config_init_0_value: Config = Default::default(); |
| 1149 | __cw_config_init_0_value.instruction_budget = __cw_config_init_0_0; |
| 1150 | __cw_config_init_0_value |
| 1151 | }; |
| 1152 | let report = build_headless_context_report(&config, tmp.path()); |
| 1153 | assert!( |
| 1154 | report |
| 1155 | .entries |
| 1156 | .iter() |
| 1157 | .any(|entry| entry.label == "Instruction budget (preview)") |
| 1158 | ); |
| 1159 | assert!(report.entries.iter().any(|entry| { |
| 1160 | entry.label.starts_with("Instruction source:") |
| 1161 | && entry |
| 1162 | .truncation_reason |
| 1163 | .as_deref() |
| 1164 | .is_some_and(|reason| reason.contains("scope_budget")) |
| 1165 | })); |
| 1166 | } |
| 1167 | |
| 1168 | #[test] |
| 1169 | fn headless_context_report_uses_kimi_code_k3_route_context() { |
| 1170 | let tmp = tempdir().expect("workspace"); |
| 1171 | let config = { |
| 1172 | let __cw_config_init_1_0 = Some("moonshot".to_string()); |
| 1173 | let __cw_config_init_1_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1174 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 1175 | api_key: Some("test-kimi-key".to_string()), |
| 1176 | base_url: Some( |
| 1177 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL |
| 1178 | .to_string(), |
| 1179 | ), |
| 1180 | model: Some( |
| 1181 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL |
| 1182 | .to_string(), |
| 1183 | ), |
| 1184 | ..Default::default() |
| 1185 | }, |
| 1186 | ..Default::default() |
| 1187 | }); |
| 1188 | let mut __cw_config_init_1_value: Config = Default::default(); |
| 1189 | __cw_config_init_1_value.provider = __cw_config_init_1_0; |
| 1190 | __cw_config_init_1_value.providers = __cw_config_init_1_1; |
| 1191 | __cw_config_init_1_value |
| 1192 | }; |
| 1193 | |
| 1194 | let report = build_headless_context_report(&config, tmp.path()); |
| 1195 | |
| 1196 | assert_eq!(report.context_window_tokens, Some(262_144)); |
| 1197 | assert_eq!( |
| 1198 | report.context_window_source.as_deref(), |
| 1199 | Some("static Kimi Code safe floor") |
| 1200 | ); |
| 1201 | assert!(context_report_json(&report).contains("\"context_window_tokens\": 262144")); |
| 1202 | } |
| 1203 | |
| 1204 | #[test] |
| 1205 | fn headless_context_report_honors_kimi_code_k3_context_override() { |
| 1206 | let tmp = tempdir().expect("workspace"); |
| 1207 | let config = { |
| 1208 | let __cw_config_init_2_0 = Some("moonshot".to_string()); |
| 1209 | let __cw_config_init_2_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1210 | moonshot: codewhale_runtime::config::ProviderConfig { |
| 1211 | api_key: Some("test-kimi-key".to_string()), |
| 1212 | base_url: Some( |
| 1213 | codewhale_config::descriptors::defaults::DEFAULT_KIMI_CODE_BASE_URL |
| 1214 | .to_string(), |
| 1215 | ), |
| 1216 | model: Some( |
| 1217 | codewhale_config::catalog::reviewed::constants::KIMI_CODE_K3_MODEL |
| 1218 | .to_string(), |
| 1219 | ), |
| 1220 | context_window: Some(1_048_576), |
| 1221 | ..Default::default() |
| 1222 | }, |
| 1223 | ..Default::default() |
| 1224 | }); |
| 1225 | let mut __cw_config_init_2_value: Config = Default::default(); |
| 1226 | __cw_config_init_2_value.provider = __cw_config_init_2_0; |
| 1227 | __cw_config_init_2_value.providers = __cw_config_init_2_1; |
| 1228 | __cw_config_init_2_value |
| 1229 | }; |
| 1230 | |
| 1231 | let report = build_headless_context_report(&config, tmp.path()); |
| 1232 | |
| 1233 | assert_eq!(report.context_window_tokens, Some(1_048_576)); |
| 1234 | assert_eq!(report.context_window_source.as_deref(), Some("configured")); |
| 1235 | } |
| 1236 | |
| 1237 | fn private_deployment_config(context_window: Option<u32>) -> Config { |
| 1238 | { |
| 1239 | let __cw_config_init_3_0 = Some("custom".to_string()); |
| 1240 | let __cw_config_init_3_1 = Some(codewhale_runtime::config::ProvidersConfig { |
| 1241 | custom: std::collections::HashMap::from([( |
| 1242 | "custom".to_string(), |
| 1243 | codewhale_runtime::config::ProviderConfig { |
| 1244 | kind: Some("openai-compatible".to_string()), |
| 1245 | api_key: Some("test-private-key".to_string()), |
| 1246 | base_url: Some("https://private.test/v1".to_string()), |
| 1247 | model: Some("private-1m-deployment-v9".to_string()), |
| 1248 | context_window, |
| 1249 | ..Default::default() |
| 1250 | }, |
| 1251 | )]), |
| 1252 | ..Default::default() |
| 1253 | }); |
| 1254 | let mut __cw_config_init_3_value: Config = Default::default(); |
| 1255 | __cw_config_init_3_value.provider = __cw_config_init_3_0; |
| 1256 | __cw_config_init_3_value.providers = __cw_config_init_3_1; |
| 1257 | __cw_config_init_3_value |
| 1258 | } |
| 1259 | } |
| 1260 | |
| 1261 | /// #5239: a privately deployed id nobody catalogs, with an operator |
| 1262 | /// override, is a 1M route in the report — no route-resolution outcome may |
| 1263 | /// silently substitute the legacy window. |
| 1264 | #[test] |
| 1265 | fn headless_context_report_honors_a_private_model_context_override() { |
| 1266 | let tmp = tempdir().expect("workspace"); |
| 1267 | |
| 1268 | let report = |
| 1269 | build_headless_context_report(&private_deployment_config(Some(1_048_576)), tmp.path()); |
| 1270 | |
| 1271 | assert_eq!(report.context_window_tokens, Some(1_048_576)); |
| 1272 | assert_eq!(report.context_window_source.as_deref(), Some("configured")); |
| 1273 | } |
| 1274 | |
| 1275 | /// The same id without an override is a guess, and the report must say so |
| 1276 | /// against the window it actually used. |
| 1277 | #[test] |
| 1278 | fn headless_context_report_marks_an_unknown_private_model_unverified() { |
| 1279 | let tmp = tempdir().expect("workspace"); |
| 1280 | |
| 1281 | let report = build_headless_context_report(&private_deployment_config(None), tmp.path()); |
| 1282 | |
| 1283 | assert_eq!(report.context_window_source.as_deref(), Some("fallback")); |
| 1284 | let formatted = format_context_report(&report); |
| 1285 | assert!(formatted.contains("this window is a guess"), "{formatted}"); |
| 1286 | assert!( |
| 1287 | !formatted.contains("128K"), |
| 1288 | "the fallback rung must not assert a window it did not read: {formatted}" |
| 1289 | ); |
| 1290 | } |
| 1291 | |
| 1292 | #[test] |
| 1293 | fn context_report_marks_whale_md_ignored_without_loading_body() { |
| 1294 | let tmp = tempdir().expect("tempdir"); |
| 1295 | fs::write(tmp.path().join("WHALE.md"), "SECRET_LEGACY_WHALE_BODY").expect("write whale"); |
| 1296 | |
| 1297 | let report = build_headless_context_report(&Config::default(), tmp.path()); |
| 1298 | assert!( |
| 1299 | report.entries.iter().any(|entry| { |
| 1300 | entry.source_kind == SourceKind::ProjectContextWarning |
| 1301 | && entry |
| 1302 | .truncation_reason |
| 1303 | .as_deref() |
| 1304 | .is_some_and(|reason| reason.contains("WHALE.md is ignored")) |
| 1305 | }), |
| 1306 | "ignored WHALE.md should be visible as a migration warning: {:?}", |
| 1307 | report.entries |
| 1308 | ); |
| 1309 | assert!( |
| 1310 | !context_report_json(&report).contains("SECRET_LEGACY_WHALE_BODY"), |
| 1311 | "ignored WHALE.md body must not enter context report" |
| 1312 | ); |
| 1313 | } |
| 1314 | |
| 1315 | #[test] |
| 1316 | fn app_context_report_omits_legacy_plain_file_memory() { |
| 1317 | // The legacy single-file memory path (`~/.deepseek/memory.md` and |
| 1318 | // friends) was deleted for v0.9.4: only the native |
| 1319 | // `memory/global/MEMORY.md` store injects. |
| 1320 | let tmp = tempdir().expect("tempdir"); |
| 1321 | let memory_path = tmp.path().join("memory.md"); |
| 1322 | fs::write(&memory_path, "private legacy memory").expect("write memory"); |
| 1323 | let config: Config = toml::from_str( |
| 1324 | r#" |
| 1325 | [memory] |
| 1326 | enabled = true |
| 1327 | "#, |
| 1328 | ) |
| 1329 | .expect("parse config"); |
| 1330 | let app = App::new( |
| 1331 | crate::tui::app::TuiOptions { |
| 1332 | use_bracketed_paste: false, |
| 1333 | memory_path: memory_path.clone(), |
| 1334 | mcp_config_path: tmp.path().join("mcp.json"), |
| 1335 | use_memory: true, |
| 1336 | start_in_agent_mode: true, |
| 1337 | ..crate::tui::test_support::test_tui_options(tmp.path()) |
| 1338 | }, |
| 1339 | &config, |
| 1340 | ); |
| 1341 | |
| 1342 | let report = build_context_report(&app); |
| 1343 | let memory_entry = report |
| 1344 | .entries |
| 1345 | .iter() |
| 1346 | .find(|entry| entry.source_kind == SourceKind::UserMemory) |
| 1347 | .expect("user memory source entry"); |
| 1348 | |
| 1349 | assert_eq!(memory_entry.activation_reason, ActivationReason::Omitted); |
| 1350 | assert!(!context_report_json(&report).contains("private legacy memory")); |
| 1351 | } |
| 1352 | |
| 1353 | #[test] |
| 1354 | fn headless_report_counts_project_pack_only_when_configured() { |
| 1355 | let tmp = tempdir().expect("tempdir"); |
| 1356 | fs::create_dir(tmp.path().join(".git")).expect("mkdir .git"); |
| 1357 | fs::create_dir(tmp.path().join("src")).expect("mkdir src"); |
| 1358 | fs::write(tmp.path().join("src/lib.rs"), "pub fn fixture() {}\n").expect("write fixture"); |
| 1359 | |
| 1360 | let default_report = build_headless_context_report(&Config::default(), tmp.path()); |
| 1361 | let default_pack = default_report |
| 1362 | .entries |
| 1363 | .iter() |
| 1364 | .find(|entry| entry.source_kind == SourceKind::ProjectContextPack) |
| 1365 | .expect("project pack entry"); |
| 1366 | assert_eq!(default_pack.activation_reason, ActivationReason::Omitted); |
| 1367 | assert_eq!(default_pack.estimated_tokens, 0); |
| 1368 | assert_eq!( |
| 1369 | default_pack.truncation_reason.as_deref(), |
| 1370 | Some("disabled; project_map provides this information on demand") |
| 1371 | ); |
| 1372 | |
| 1373 | let relay = default_report |
| 1374 | .entries |
| 1375 | .iter() |
| 1376 | .find(|entry| entry.source_kind == SourceKind::CompactionRelayTemplate) |
| 1377 | .expect("relay template entry"); |
| 1378 | assert_eq!(relay.activation_reason, ActivationReason::Omitted); |
| 1379 | assert_eq!(relay.estimated_tokens, 0); |
| 1380 | |
| 1381 | let mut configured = Config::default(); |
| 1382 | configured.context.project_pack = Some(true); |
| 1383 | let configured_report = build_headless_context_report(&configured, tmp.path()); |
| 1384 | let configured_pack = configured_report |
| 1385 | .entries |
| 1386 | .iter() |
| 1387 | .find(|entry| entry.source_kind == SourceKind::ProjectContextPack) |
| 1388 | .expect("configured project pack entry"); |
| 1389 | assert_eq!( |
| 1390 | configured_pack.activation_reason, |
| 1391 | ActivationReason::ConfigEnabled |
| 1392 | ); |
| 1393 | assert!( |
| 1394 | configured_pack.estimated_tokens > 0, |
| 1395 | "configured project pack must be counted" |
| 1396 | ); |
| 1397 | |
| 1398 | let environment = configured_report |
| 1399 | .entries |
| 1400 | .iter() |
| 1401 | .find(|entry| entry.source_kind == SourceKind::EnvironmentBlock) |
| 1402 | .expect("runtime environment entry"); |
| 1403 | assert_eq!(environment.activation_reason, ActivationReason::AlwaysOn); |
| 1404 | } |
| 1405 | |
| 1406 | #[test] |
| 1407 | fn app_context_report_counts_configured_project_pack_before_first_turn() { |
| 1408 | let tmp = tempdir().expect("tempdir"); |
| 1409 | fs::create_dir(tmp.path().join(".git")).expect("mkdir .git"); |
| 1410 | fs::create_dir(tmp.path().join("src")).expect("mkdir src"); |
| 1411 | fs::write(tmp.path().join("src/lib.rs"), "pub fn fixture() {}\n").expect("write fixture"); |
| 1412 | let mut config = Config::default(); |
| 1413 | config.context.project_pack = Some(true); |
| 1414 | let app = App::new( |
| 1415 | crate::tui::app::TuiOptions { |
| 1416 | use_bracketed_paste: false, |
| 1417 | mcp_config_path: tmp.path().join("mcp.json"), |
| 1418 | start_in_agent_mode: true, |
| 1419 | ..crate::tui::test_support::test_tui_options(tmp.path()) |
| 1420 | }, |
| 1421 | &config, |
| 1422 | ); |
| 1423 | |
| 1424 | assert!( |
| 1425 | app.system_prompt.is_none(), |
| 1426 | "fixture must be pre-first-turn" |
| 1427 | ); |
| 1428 | let report = build_context_report(&app); |
| 1429 | let project_pack = report |
| 1430 | .entries |
| 1431 | .iter() |
| 1432 | .find(|entry| entry.source_kind == SourceKind::ProjectContextPack) |
| 1433 | .expect("project pack entry"); |
| 1434 | assert_eq!( |
| 1435 | project_pack.activation_reason, |
| 1436 | ActivationReason::ConfigEnabled |
| 1437 | ); |
| 1438 | assert!(project_pack.estimated_tokens > 0); |
| 1439 | } |
| 1440 | |
| 1441 | #[test] |
| 1442 | fn headless_context_report_omits_legacy_plain_file_memory() { |
| 1443 | let tmp = tempdir().expect("tempdir"); |
| 1444 | let memory_path = tmp.path().join("memory.md"); |
| 1445 | fs::write(&memory_path, "private legacy memory").expect("write memory"); |
| 1446 | let mut config: Config = toml::from_str( |
| 1447 | r#" |
| 1448 | [memory] |
| 1449 | enabled = true |
| 1450 | "#, |
| 1451 | ) |
| 1452 | .expect("parse config"); |
| 1453 | config.memory_path = Some(memory_path.to_string_lossy().into_owned()); |
| 1454 | |
| 1455 | let report = build_headless_context_report(&config, tmp.path()); |
| 1456 | let memory_entry = report |
| 1457 | .entries |
| 1458 | .iter() |
| 1459 | .find(|entry| entry.source_kind == SourceKind::UserMemory) |
| 1460 | .expect("user memory source entry"); |
| 1461 | |
| 1462 | assert_eq!(memory_entry.activation_reason, ActivationReason::Omitted); |
| 1463 | assert!(!context_report_json(&report).contains("private legacy memory")); |
| 1464 | } |
| 1465 | |
| 1466 | #[test] |
| 1467 | fn format_summary_lists_largest_sources() { |
| 1468 | let mut builder = ReportBuilder::new(); |
| 1469 | builder.push(SourceEntry::estimate( |
| 1470 | SourceKind::ToolSchemas, |
| 1471 | "Tool schemas", |
| 1472 | None, |
| 1473 | ActivationReason::PerRequest, |
| 1474 | 500, |
| 1475 | CountingConfidence::Approximate, |
| 1476 | Some(3), |
| 1477 | )); |
| 1478 | builder.push(SourceEntry::estimate( |
| 1479 | SourceKind::UserRequest, |
| 1480 | "Latest user request", |
| 1481 | None, |
| 1482 | ActivationReason::PerRequest, |
| 1483 | 25, |
| 1484 | CountingConfidence::High, |
| 1485 | Some(7), |
| 1486 | )); |
| 1487 | let report = builder.finish( |
| 1488 | ContextWindowResolution { |
| 1489 | tokens: 128_000, |
| 1490 | source: ContextWindowSource::Fallback, |
| 1491 | }, |
| 1492 | 525, |
| 1493 | Some(800), |
| 1494 | "test", |
| 1495 | ); |
| 1496 | let summary = format_context_summary(&report); |
| 1497 | |
| 1498 | assert!(summary.contains("Context Summary")); |
| 1499 | assert!(summary.contains("Tool schemas (500)")); |
| 1500 | // The headline is the pressure number; the inflated figure is only |
| 1501 | // ever the labeled secondary overflow-guard line. |
| 1502 | assert!(summary.contains("Estimated active context: 525 tokens")); |
| 1503 | assert!(summary.contains("Overflow guard: 800 tokens")); |
| 1504 | let full = format_context_report(&report); |
| 1505 | let headline = full |
| 1506 | .find("Estimated active context: 525 tokens") |
| 1507 | .expect("pressure headline"); |
| 1508 | let guard = full.find("Overflow guard: 800 tokens").expect("guard line"); |
| 1509 | assert!(headline < guard, "{full}"); |
| 1510 | } |
| 1511 | |
| 1512 | #[test] |
| 1513 | fn finish_reflects_route_context_window_over_model_default() { |
| 1514 | // deepseek-v4-pro defaults to a 1M window; a resolved route advertising a |
| 1515 | // smaller window must win in the report's context_window_tokens. |
| 1516 | let route_window = 128_000u64; |
| 1517 | let model_default = codewhale_models::context_window_for_model("deepseek-v4-pro") |
| 1518 | .expect("model has a default window"); |
| 1519 | assert_ne!( |
| 1520 | u64::from(model_default), |
| 1521 | route_window, |
| 1522 | "test fixture must differ from the model default to be meaningful" |
| 1523 | ); |
| 1524 | |
| 1525 | let limits = RouteLimits { |
| 1526 | context_tokens: Some(route_window), |
| 1527 | input_tokens: None, |
| 1528 | output_tokens: None, |
| 1529 | output_declared: false, |
| 1530 | }; |
| 1531 | let resolved = codewhale_engine::route_runtime::resolve_context_window( |
| 1532 | ProviderKind::Deepseek, |
| 1533 | "deepseek-v4-pro", |
| 1534 | Some(limits), |
| 1535 | None, |
| 1536 | None, |
| 1537 | ); |
| 1538 | assert_eq!(resolved.source, ContextWindowSource::Catalog); |
| 1539 | |
| 1540 | let builder = ReportBuilder::new(); |
| 1541 | let report = builder.finish(resolved, 10_000, None, "test"); |
| 1542 | |
| 1543 | assert_eq!(report.context_window_tokens, Some(route_window as u32)); |
| 1544 | assert_eq!(report.context_window_source.as_deref(), Some("catalog")); |
| 1545 | // Budget percent is computed against the route window, not the default. |
| 1546 | let expected = (10_000.0 / route_window as f64) * 100.0; |
| 1547 | let actual = report.budget_used_percent.expect("window known"); |
| 1548 | assert!( |
| 1549 | (actual - expected).abs() < 1e-6, |
| 1550 | "got {actual}, want {expected}" |
| 1551 | ); |
| 1552 | } |
| 1553 | |
| 1554 | #[test] |
| 1555 | fn pressure_label_matches_unified_pressure_levels() { |
| 1556 | // Boundaries mirror context_budget::PressureLevel. |
| 1557 | assert_eq!(pressure_label(None), "unknown"); |
| 1558 | assert_eq!(pressure_label(Some(0.0)), "low"); |
| 1559 | assert_eq!(pressure_label(Some(39.9)), "low"); |
| 1560 | assert_eq!(pressure_label(Some(40.0)), "moderate"); |
| 1561 | assert_eq!(pressure_label(Some(74.9)), "moderate"); |
| 1562 | assert_eq!(pressure_label(Some(75.0)), "high"); |
| 1563 | assert_eq!(pressure_label(Some(89.9)), "high"); |
| 1564 | assert_eq!(pressure_label(Some(90.0)), "critical"); |
| 1565 | assert_eq!(pressure_label(Some(100.0)), "critical"); |
| 1566 | } |
| 1567 | |
| 1568 | #[test] |
| 1569 | fn tool_schema_entry_serializes_like_runtime_catalog() { |
| 1570 | let tool = Tool { |
| 1571 | tool_type: Some("function".to_string()), |
| 1572 | name: "read_file".to_string(), |
| 1573 | description: "read a file".to_string(), |
| 1574 | input_schema: serde_json::json!({"type": "object"}), |
| 1575 | allowed_callers: None, |
| 1576 | defer_loading: None, |
| 1577 | input_examples: None, |
| 1578 | strict: Some(true), |
| 1579 | cache_control: None, |
| 1580 | }; |
| 1581 | let rendered = serde_json::to_string(&vec![tool]).expect("serialize tool"); |
| 1582 | |
| 1583 | assert!(rendered.contains("read_file")); |
| 1584 | } |
| 1585 | } |
| 1586 |