| 1 | //! Per-scope instruction budgets, trim markers, and skip/trim notices (#6526). |
| 2 | //! |
| 3 | //! Standing instruction files are assembled into two independent scopes — |
| 4 | //! `global` (user-wide: the global `AGENTS.md` chain, `~/.claude/CLAUDE.md`, |
| 5 | //! and the configured `instructions = [...]` array) and `project` (the |
| 6 | //! repository-root → workspace chain, co-read foreign files, and the rules |
| 7 | //! block). Each scope has its own ceiling, expressed in **estimated tokens** |
| 8 | //! (`min(absolute_tokens, percent × usable_window)`), so a huge project can no |
| 9 | //! longer shrink the user's global preferences and vice versa. |
| 10 | //! |
| 11 | //! Every loss is reported. A scope that does not fit is trimmed from the |
| 12 | //! broadest end first — the root-most ancestor goes first, the workspace file |
| 13 | //! last — and a single file that alone exceeds its remaining budget keeps its |
| 14 | //! head and drops its tail with a marker carrying bytes and tokens. Skips are |
| 15 | //! not trims: an oversized file, an empty file, a rules-directory overflow, or |
| 16 | //! a symlinked duplicate is reported as `skipped` with the limit that produced |
| 17 | //! it, and never makes the workspace unopenable. |
| 18 | //! |
| 19 | //! Known limitations (deliberate, not bugs): |
| 20 | //! |
| 21 | //! - Token counts are *estimates* from |
| 22 | //! [`crate::compaction::estimate_text_tokens_conservative`], not a |
| 23 | //! provider tokenizer. The estimator reads multibyte text conservatively, |
| 24 | //! but a CJK- or emoji-heavy file can still be off by a comparable margin; |
| 25 | //! the notice says "estimated" for that reason. |
| 26 | //! - Opted-in foreign *fragments* (`.cursorrules`, `.clinerules`, …) are |
| 27 | //! loaded by `codewhale_core::fragments` into the world-state block with |
| 28 | //! their own cap. They are reported in `/context` but are not charged |
| 29 | //! against the project scope here; only the instruction chain and the rules |
| 30 | //! block are. |
| 31 | //! - The static-prefix guard measures every system block plus the tool |
| 32 | //! schemas the request carries, so memory, environment and goal blocks count |
| 33 | //! toward it even though only the two instruction scopes can be trimmed to |
| 34 | //! satisfy it. |
| 35 | //! - Trimming is one pass per scope. The guard then makes one bounded pass |
| 36 | //! over both scopes, largest first, with at most two attempts per scope. A |
| 37 | //! prefix that is still over the guard afterwards is reported, not looped |
| 38 | //! on, and host-owned prompts (child, isolated, RLM) are measured but never |
| 39 | //! trimmed. |
| 40 | |
| 41 | use std::path::PathBuf; |
| 42 | |
| 43 | use codewhale_config::instruction_budget::{ |
| 44 | DEFAULT_FILE_MAX_BYTES, DEFAULT_SCOPE_BUDGET_PERCENT, DEFAULT_SCOPE_BUDGET_TOKENS, |
| 45 | DEFAULT_STATIC_PREFIX_GUARD_PERCENT, |
| 46 | }; |
| 47 | pub use codewhale_config::instruction_budget::{InstructionBudgetConfig, InstructionBudgetPolicy}; |
| 48 | /// Share of the window kept free for the response and estimator drift. |
| 49 | const SAFETY_RESERVE_PERCENT: usize = 10; |
| 50 | /// Floor for [`SAFETY_RESERVE_PERCENT`] so small windows keep real headroom. |
| 51 | const SAFETY_RESERVE_MIN_TOKENS: usize = 2_048; |
| 52 | |
| 53 | /// Which scope an instruction source belongs to. |
| 54 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)] |
| 55 | pub enum InstructionScope { |
| 56 | /// User-wide authority: global files and configured `instructions` entries. |
| 57 | Global, |
| 58 | /// Workspace authority: the per-directory chain and the rules block. |
| 59 | Project, |
| 60 | } |
| 61 | |
| 62 | impl InstructionScope { |
| 63 | #[must_use] |
| 64 | pub fn as_str(self) -> &'static str { |
| 65 | match self { |
| 66 | Self::Global => "global", |
| 67 | Self::Project => "project", |
| 68 | } |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | /// Where an instruction source came from, for notices and `/context`. |
| 73 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] |
| 74 | pub enum InstructionOrigin { |
| 75 | /// An `AGENTS.md` (project chain or global chain). |
| 76 | Agents, |
| 77 | /// A `CLAUDE.md` / `.claude/CLAUDE.md` / `.claude/instructions.md`. |
| 78 | Claude, |
| 79 | /// Codewhale's own `.codewhale/instructions.md` or legacy |
| 80 | /// `.deepseek/instructions.md`. |
| 81 | Instructions, |
| 82 | /// The assembled rules block. |
| 83 | Rules, |
| 84 | /// The configured `instructions = [...]` array. |
| 85 | Configured, |
| 86 | WhaleSoul, |
| 87 | } |
| 88 | |
| 89 | impl InstructionOrigin { |
| 90 | #[must_use] |
| 91 | pub fn as_str(self) -> &'static str { |
| 92 | match self { |
| 93 | Self::Agents => "agents", |
| 94 | Self::Claude => "claude", |
| 95 | Self::Instructions => "instructions", |
| 96 | Self::Rules => "rules", |
| 97 | Self::Configured => "configured", |
| 98 | Self::WhaleSoul => "whale_soul", |
| 99 | } |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | /// What happened to one source. |
| 104 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] |
| 105 | pub enum InstructionAction { |
| 106 | Kept, |
| 107 | Trimmed, |
| 108 | Skipped, |
| 109 | Refused, |
| 110 | } |
| 111 | |
| 112 | impl InstructionAction { |
| 113 | #[must_use] |
| 114 | pub fn as_str(self) -> &'static str { |
| 115 | match self { |
| 116 | Self::Kept => "kept", |
| 117 | Self::Trimmed => "trimmed", |
| 118 | Self::Skipped => "skipped", |
| 119 | Self::Refused => "refused", |
| 120 | } |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | /// The limit that produced a loss. |
| 125 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] |
| 126 | pub enum InstructionLimit { |
| 127 | None, |
| 128 | /// The scope's own token budget. |
| 129 | ScopeBudget, |
| 130 | /// The static-prefix guard trimmed the largest scope by an overage. |
| 131 | StaticGuard, |
| 132 | /// `file_max_bytes`. |
| 133 | FileCeiling, |
| 134 | FileContent, |
| 135 | /// The file was whitespace-only. |
| 136 | EmptyFile, |
| 137 | /// `MAX_RULES_FILES` per directory. |
| 138 | RulesCap, |
| 139 | /// The project scope budget was exhausted before the rules block. |
| 140 | RulesBudget, |
| 141 | /// The same canonical file was already loaded in another scope. |
| 142 | DuplicatePath, |
| 143 | } |
| 144 | |
| 145 | impl InstructionLimit { |
| 146 | #[must_use] |
| 147 | pub fn as_str(self) -> &'static str { |
| 148 | match self { |
| 149 | Self::None => "none", |
| 150 | Self::ScopeBudget => "scope_budget", |
| 151 | Self::StaticGuard => "static_guard", |
| 152 | Self::FileCeiling => "file_ceiling", |
| 153 | Self::FileContent => "file_content", |
| 154 | Self::EmptyFile => "empty_file", |
| 155 | Self::RulesCap => "rules_cap", |
| 156 | Self::RulesBudget => "rules_budget", |
| 157 | Self::DuplicatePath => "duplicate_path", |
| 158 | } |
| 159 | } |
| 160 | } |
| 161 | |
| 162 | /// One instruction source that was kept, trimmed, skipped, or refused. |
| 163 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 164 | pub struct InstructionNotice { |
| 165 | pub path: Option<PathBuf>, |
| 166 | pub scope: InstructionScope, |
| 167 | pub origin: InstructionOrigin, |
| 168 | pub action: InstructionAction, |
| 169 | pub bytes_kept: u64, |
| 170 | pub bytes_dropped: u64, |
| 171 | pub tokens_kept: usize, |
| 172 | pub tokens_dropped: usize, |
| 173 | pub limit: InstructionLimit, |
| 174 | /// Lower-precedence file selected after the preferred one was skipped. |
| 175 | pub fallback_selected: Option<String>, |
| 176 | /// Typed reason for notices that are not a plain budget loss (a refused |
| 177 | /// symlinked rules directory, an unreadable file, a cap). |
| 178 | pub detail: Option<InstructionDetail>, |
| 179 | } |
| 180 | |
| 181 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 182 | #[serde(tag = "kind", rename_all = "snake_case")] |
| 183 | pub enum InstructionDetail { |
| 184 | DroppedBroadest, |
| 185 | NoRoomForContent { budget_tokens: usize }, |
| 186 | RulesBudgetExhausted { budget_tokens: usize }, |
| 187 | OverFileCeiling { max_bytes: u64 }, |
| 188 | Unreadable { reason: String }, |
| 189 | AlreadyLoaded, |
| 190 | RulesCap { max_files: usize }, |
| 191 | SymlinkedRulesDir, |
| 192 | } |
| 193 | |
| 194 | fn fill(template: &str, values: &[(&str, &str)]) -> String { |
| 195 | let mut out = String::with_capacity(template.len()); |
| 196 | let mut rest = template; |
| 197 | while let Some(start) = rest.find('{') { |
| 198 | out.push_str(&rest[..start]); |
| 199 | let tail = &rest[start + 1..]; |
| 200 | let replacement = tail.find('}').and_then(|end| { |
| 201 | values |
| 202 | .iter() |
| 203 | .find(|(key, _)| *key == &tail[..end]) |
| 204 | .map(|(_, value)| (*value, end)) |
| 205 | }); |
| 206 | match replacement { |
| 207 | Some((value, end)) => { |
| 208 | out.push_str(value); |
| 209 | rest = &tail[end + 1..]; |
| 210 | } |
| 211 | None => { |
| 212 | out.push('{'); |
| 213 | rest = tail; |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 | out.push_str(rest); |
| 218 | out |
| 219 | } |
| 220 | |
| 221 | impl InstructionDetail { |
| 222 | pub fn unreadable(error: &dyn std::fmt::Display) -> Self { |
| 223 | Self::Unreadable { |
| 224 | reason: codewhale_runtime::safe_label::safe_error_text(&error.to_string()), |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | fn render(&self, locale: codewhale_localization::Locale) -> String { |
| 229 | use codewhale_localization::{MessageId, tr}; |
| 230 | match self { |
| 231 | Self::DroppedBroadest => { |
| 232 | tr(locale, MessageId::InstructionDetailDroppedBroadest).into_owned() |
| 233 | } |
| 234 | Self::NoRoomForContent { budget_tokens } => fill( |
| 235 | &tr(locale, MessageId::InstructionDetailNoRoom), |
| 236 | &[("tokens", &budget_tokens.to_string())], |
| 237 | ), |
| 238 | Self::RulesBudgetExhausted { budget_tokens } => fill( |
| 239 | &tr(locale, MessageId::InstructionDetailRulesExhausted), |
| 240 | &[("tokens", &budget_tokens.to_string())], |
| 241 | ), |
| 242 | Self::OverFileCeiling { max_bytes } => fill( |
| 243 | &tr(locale, MessageId::InstructionDetailOverCeiling), |
| 244 | &[("bytes", &max_bytes.to_string())], |
| 245 | ), |
| 246 | Self::Unreadable { reason } => fill( |
| 247 | &tr(locale, MessageId::InstructionDetailUnreadable), |
| 248 | &[("reason", reason)], |
| 249 | ), |
| 250 | Self::AlreadyLoaded => { |
| 251 | tr(locale, MessageId::InstructionDetailAlreadyLoaded).into_owned() |
| 252 | } |
| 253 | Self::RulesCap { max_files } => fill( |
| 254 | &tr(locale, MessageId::InstructionDetailRulesCap), |
| 255 | &[("count", &max_files.to_string())], |
| 256 | ), |
| 257 | Self::SymlinkedRulesDir => { |
| 258 | tr(locale, MessageId::InstructionDetailSymlinkedRules).into_owned() |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | const NOTICE_LABEL_MAX_CHARS: usize = 80; |
| 265 | |
| 266 | fn inline_text(text: &str) -> String { |
| 267 | text.chars() |
| 268 | .map(|ch| if ch.is_control() { '?' } else { ch }) |
| 269 | .take(NOTICE_LABEL_MAX_CHARS) |
| 270 | .collect() |
| 271 | } |
| 272 | |
| 273 | impl InstructionNotice { |
| 274 | pub fn loss( |
| 275 | scope: InstructionScope, |
| 276 | origin: InstructionOrigin, |
| 277 | path: Option<PathBuf>, |
| 278 | limit: InstructionLimit, |
| 279 | action: InstructionAction, |
| 280 | ) -> Self { |
| 281 | Self { |
| 282 | path, |
| 283 | scope, |
| 284 | origin, |
| 285 | action, |
| 286 | bytes_kept: 0, |
| 287 | bytes_dropped: 0, |
| 288 | tokens_kept: 0, |
| 289 | tokens_dropped: 0, |
| 290 | limit, |
| 291 | fallback_selected: None, |
| 292 | detail: None, |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | /// Notice for the static-prefix guard: either the trim it performed or the |
| 297 | /// terminal state where the prefix is still over the guard. |
| 298 | pub fn static_guard( |
| 299 | scope: InstructionScope, |
| 300 | tokens_dropped: usize, |
| 301 | unsatisfiable: bool, |
| 302 | ) -> Self { |
| 303 | Self { |
| 304 | path: None, |
| 305 | scope, |
| 306 | origin: InstructionOrigin::Instructions, |
| 307 | action: if unsatisfiable { |
| 308 | InstructionAction::Skipped |
| 309 | } else { |
| 310 | InstructionAction::Trimmed |
| 311 | }, |
| 312 | bytes_kept: 0, |
| 313 | bytes_dropped: 0, |
| 314 | tokens_kept: 0, |
| 315 | tokens_dropped, |
| 316 | limit: InstructionLimit::StaticGuard, |
| 317 | fallback_selected: None, |
| 318 | detail: None, |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | /// Whether the notice describes a loss an operator must be told about. |
| 323 | #[must_use] |
| 324 | pub fn is_loss(&self) -> bool { |
| 325 | self.action != InstructionAction::Kept |
| 326 | } |
| 327 | |
| 328 | /// Display name of the source: the file name, or the scope name when the |
| 329 | /// loss covers a whole scope (for example the rules block). |
| 330 | #[must_use] |
| 331 | pub fn label(&self) -> String { |
| 332 | self.path |
| 333 | .as_ref() |
| 334 | .and_then(|path| path.file_name()) |
| 335 | .map(|name| inline_text(&name.to_string_lossy())) |
| 336 | .unwrap_or_else(|| format!("{} instructions", self.scope.as_str())) |
| 337 | } |
| 338 | |
| 339 | /// One line per loss, suitable for a system history cell or a synthetic |
| 340 | /// model message. The scope, origin, action and limit are machine keys and |
| 341 | /// stay as written; every sentence comes from the locale pack, and numbers |
| 342 | /// are always present with their unit so "trimmed" never hides how much |
| 343 | /// was dropped. |
| 344 | #[must_use] |
| 345 | pub fn render(&self, locale: codewhale_localization::Locale) -> String { |
| 346 | use codewhale_localization::{MessageId, tr}; |
| 347 | if self.limit == InstructionLimit::StaticGuard { |
| 348 | let tokens = self.tokens_dropped.to_string(); |
| 349 | return if self.action == InstructionAction::Skipped { |
| 350 | fill( |
| 351 | &tr(locale, MessageId::InstructionNoticeStaticGuardOver), |
| 352 | &[("tokens", &tokens)], |
| 353 | ) |
| 354 | } else { |
| 355 | fill( |
| 356 | &tr(locale, MessageId::InstructionNoticeStaticGuardTrimmed), |
| 357 | &[("scope", self.scope.as_str()), ("tokens", &tokens)], |
| 358 | ) |
| 359 | }; |
| 360 | } |
| 361 | let mut line = fill( |
| 362 | &tr(locale, MessageId::InstructionNoticeLine), |
| 363 | &[ |
| 364 | ("scope", self.scope.as_str()), |
| 365 | ("label", &self.label()), |
| 366 | ("origin", self.origin.as_str()), |
| 367 | ("action", self.action.as_str()), |
| 368 | ("limit", self.limit.as_str()), |
| 369 | ], |
| 370 | ); |
| 371 | let numbers = match self.action { |
| 372 | InstructionAction::Trimmed => true, |
| 373 | InstructionAction::Refused => self.bytes_kept > 0, |
| 374 | InstructionAction::Kept | InstructionAction::Skipped => false, |
| 375 | }; |
| 376 | if numbers { |
| 377 | line.push_str(&fill( |
| 378 | &tr(locale, MessageId::InstructionNoticeTrimmed), |
| 379 | &[ |
| 380 | ("kept_bytes", &self.bytes_kept.to_string()), |
| 381 | ( |
| 382 | "total_bytes", |
| 383 | &self |
| 384 | .bytes_kept |
| 385 | .saturating_add(self.bytes_dropped) |
| 386 | .to_string(), |
| 387 | ), |
| 388 | ("kept_tokens", &self.tokens_kept.to_string()), |
| 389 | ( |
| 390 | "total_tokens", |
| 391 | &self |
| 392 | .tokens_kept |
| 393 | .saturating_add(self.tokens_dropped) |
| 394 | .to_string(), |
| 395 | ), |
| 396 | ], |
| 397 | )); |
| 398 | } else if matches!( |
| 399 | self.action, |
| 400 | InstructionAction::Skipped | InstructionAction::Refused |
| 401 | ) && self.bytes_dropped > 0 |
| 402 | { |
| 403 | line.push_str(&fill( |
| 404 | &tr(locale, MessageId::InstructionNoticeDroppedBytes), |
| 405 | &[("bytes", &self.bytes_dropped.to_string())], |
| 406 | )); |
| 407 | } |
| 408 | if let Some(fallback) = self.fallback_selected.as_deref() { |
| 409 | line.push_str(&fill( |
| 410 | &tr(locale, MessageId::InstructionNoticeFallback), |
| 411 | &[("source", &inline_text(fallback))], |
| 412 | )); |
| 413 | } |
| 414 | if let Some(detail) = self.detail.as_ref() { |
| 415 | line.push_str("; "); |
| 416 | line.push_str(&detail.render(locale)); |
| 417 | } |
| 418 | line |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | impl std::fmt::Display for InstructionNotice { |
| 423 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 424 | f.write_str(&self.render(codewhale_localization::Locale::En)) |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 429 | pub enum InstructionRefusal { |
| 430 | Loss(InstructionNotice), |
| 431 | OverGuard { measured: usize, guard: usize }, |
| 432 | ReceiptMismatch, |
| 433 | } |
| 434 | |
| 435 | impl InstructionRefusal { |
| 436 | #[must_use] |
| 437 | pub fn render(&self, locale_tag: &str) -> String { |
| 438 | use codewhale_localization::{MessageId, resolve_locale, tr}; |
| 439 | let locale = resolve_locale(locale_tag); |
| 440 | let reason = match self { |
| 441 | Self::Loss(notice) => notice.render(locale), |
| 442 | Self::OverGuard { measured, guard } => fill( |
| 443 | &tr(locale, MessageId::InstructionBudgetOverGuard), |
| 444 | &[ |
| 445 | ("measured", &measured.to_string()), |
| 446 | ("guard", &guard.to_string()), |
| 447 | ], |
| 448 | ), |
| 449 | Self::ReceiptMismatch => { |
| 450 | return "instruction receipt does not match the installed prompt".to_string(); |
| 451 | } |
| 452 | }; |
| 453 | fill( |
| 454 | &tr(locale, MessageId::InstructionBudgetRefused), |
| 455 | &[("reason", &reason)], |
| 456 | ) |
| 457 | } |
| 458 | } |
| 459 | |
| 460 | /// Render the whole loss list as the body of the startup notice. |
| 461 | #[must_use] |
| 462 | pub fn render_notice_body(notices: &[InstructionNotice], locale_tag: &str) -> Option<String> { |
| 463 | use codewhale_localization::{MessageId, resolve_locale, tr}; |
| 464 | let losses: Vec<&InstructionNotice> = notices.iter().filter(|n| n.is_loss()).collect(); |
| 465 | if losses.is_empty() { |
| 466 | return None; |
| 467 | } |
| 468 | // Bounded on purpose: a rules directory beyond the cap yields one loss per |
| 469 | // extra file, and an unbounded summary would be a first-turn message larger |
| 470 | // than the budget it describes. |
| 471 | const MAX_LINES: usize = 12; |
| 472 | const MAX_BYTES: usize = 2_000; |
| 473 | let locale = resolve_locale(locale_tag); |
| 474 | let more = tr(locale, MessageId::InstructionNoticeMore); |
| 475 | let reserve = more.len() + 16; |
| 476 | let mut body = tr(locale, MessageId::InstructionNoticeHeader).into_owned(); |
| 477 | body.push('\n'); |
| 478 | let mut shown = 0usize; |
| 479 | for notice in &losses { |
| 480 | let line = format!("- {}\n", notice.render(locale)); |
| 481 | if shown >= MAX_LINES || body.len() + line.len() + reserve > MAX_BYTES { |
| 482 | break; |
| 483 | } |
| 484 | body.push_str(&line); |
| 485 | shown += 1; |
| 486 | } |
| 487 | if shown < losses.len() { |
| 488 | body.push_str("- "); |
| 489 | body.push_str(&fill( |
| 490 | &more, |
| 491 | &[("count", &(losses.len() - shown).to_string())], |
| 492 | )); |
| 493 | body.push('\n'); |
| 494 | } |
| 495 | Some(body.trim_end().to_string()) |
| 496 | } |
| 497 | |
| 498 | /// Raw instruction content, kept per source so a scope can be trimmed by |
| 499 | /// whole segments instead of by unmovable joined text. |
| 500 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 501 | pub struct InstructionSegment { |
| 502 | pub scope: InstructionScope, |
| 503 | pub origin: InstructionOrigin, |
| 504 | /// `None` for generated content that has no file behind it. |
| 505 | pub path: Option<PathBuf>, |
| 506 | /// Display label used in the rendered block: a stable relative path or |
| 507 | /// basename for file sources, or a synthetic name for inline sources. |
| 508 | pub label: Option<String>, |
| 509 | /// Canonical path, used to load one physical file once across scopes. |
| 510 | pub canonical_path: Option<PathBuf>, |
| 511 | pub text: String, |
| 512 | /// Lower-precedence file chosen after the preferred one was skipped. |
| 513 | pub fallback_selected: Option<String>, |
| 514 | } |
| 515 | |
| 516 | impl InstructionSegment { |
| 517 | pub fn new( |
| 518 | scope: InstructionScope, |
| 519 | origin: InstructionOrigin, |
| 520 | path: Option<PathBuf>, |
| 521 | text: String, |
| 522 | ) -> Self { |
| 523 | Self { |
| 524 | scope, |
| 525 | origin, |
| 526 | path, |
| 527 | label: None, |
| 528 | canonical_path: None, |
| 529 | text, |
| 530 | fallback_selected: None, |
| 531 | } |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | /// Resolved, per-route budgets. Percentages are of the *usable* window, never |
| 536 | /// the raw window: the response and the safety reserve are not available to |
| 537 | /// standing instructions. |
| 538 | #[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)] |
| 539 | pub struct InstructionBudgets { |
| 540 | pub global_tokens: usize, |
| 541 | pub project_tokens: usize, |
| 542 | pub static_guard_tokens: Option<usize>, |
| 543 | pub file_max_bytes: u64, |
| 544 | pub policy: InstructionBudgetPolicy, |
| 545 | pub claude_fallback: bool, |
| 546 | pub usable_window_tokens: Option<usize>, |
| 547 | } |
| 548 | |
| 549 | impl InstructionBudgets { |
| 550 | pub fn first_refused_loss<'a>( |
| 551 | &self, |
| 552 | notices: &'a [InstructionNotice], |
| 553 | ) -> Option<&'a InstructionNotice> { |
| 554 | if self.policy != InstructionBudgetPolicy::Refuse { |
| 555 | return None; |
| 556 | } |
| 557 | notices.iter().find(|notice| { |
| 558 | notice.is_loss() |
| 559 | && matches!( |
| 560 | notice.limit, |
| 561 | InstructionLimit::ScopeBudget |
| 562 | | InstructionLimit::RulesBudget |
| 563 | | InstructionLimit::FileContent |
| 564 | ) |
| 565 | }) |
| 566 | } |
| 567 | |
| 568 | /// Resolve config + route window into concrete token ceilings. |
| 569 | /// |
| 570 | /// `window` is the route's context window; `output` its resolved output |
| 571 | /// reservation when the caller has one. Unknown capacity leaves relative |
| 572 | /// ceilings unavailable and retains the absolute per-scope caps. |
| 573 | pub fn resolve( |
| 574 | config: Option<&InstructionBudgetConfig>, |
| 575 | window: Option<usize>, |
| 576 | output: Option<usize>, |
| 577 | ) -> Result<Self, String> { |
| 578 | if let Some(config) = config { |
| 579 | config.validate()?; |
| 580 | } |
| 581 | Ok(Self::resolve_unchecked(config, window, output)) |
| 582 | } |
| 583 | |
| 584 | #[must_use] |
| 585 | pub fn resolve_or_default( |
| 586 | config: &InstructionBudgetConfig, |
| 587 | window: Option<usize>, |
| 588 | output: Option<usize>, |
| 589 | ) -> Self { |
| 590 | Self::resolve(Some(config), window, output) |
| 591 | .unwrap_or_else(|_| Self::resolve_unchecked(None, window, output)) |
| 592 | } |
| 593 | |
| 594 | fn resolve_unchecked( |
| 595 | config: Option<&InstructionBudgetConfig>, |
| 596 | window: Option<usize>, |
| 597 | output: Option<usize>, |
| 598 | ) -> Self { |
| 599 | let usable = window |
| 600 | .zip(output) |
| 601 | .map(|(window, output)| usable_window_tokens(window, Some(output))); |
| 602 | let global_percent = config |
| 603 | .and_then(|c| c.global_budget_percent) |
| 604 | .unwrap_or(DEFAULT_SCOPE_BUDGET_PERCENT); |
| 605 | let project_percent = config |
| 606 | .and_then(|c| c.project_budget_percent) |
| 607 | .unwrap_or(DEFAULT_SCOPE_BUDGET_PERCENT); |
| 608 | let guard_percent = config |
| 609 | .and_then(|c| c.static_prefix_guard_percent) |
| 610 | .unwrap_or(DEFAULT_STATIC_PREFIX_GUARD_PERCENT); |
| 611 | let global_tokens = config |
| 612 | .and_then(|c| c.global_budget_tokens) |
| 613 | .unwrap_or(DEFAULT_SCOPE_BUDGET_TOKENS) |
| 614 | .min(usable.map_or(usize::MAX, |usable| share_of(usable, global_percent))); |
| 615 | let project_tokens = config |
| 616 | .and_then(|c| c.project_budget_tokens) |
| 617 | .unwrap_or(DEFAULT_SCOPE_BUDGET_TOKENS) |
| 618 | .min(usable.map_or(usize::MAX, |usable| share_of(usable, project_percent))); |
| 619 | Self { |
| 620 | global_tokens, |
| 621 | project_tokens, |
| 622 | static_guard_tokens: usable.map(|usable| share_of(usable, guard_percent)), |
| 623 | file_max_bytes: config |
| 624 | .and_then(|c| c.file_max_bytes) |
| 625 | .unwrap_or(DEFAULT_FILE_MAX_BYTES), |
| 626 | policy: config |
| 627 | .and_then(|c| c.policy) |
| 628 | .unwrap_or(InstructionBudgetPolicy::Trim), |
| 629 | claude_fallback: config.and_then(|c| c.claude_fallback).unwrap_or(false), |
| 630 | usable_window_tokens: usable, |
| 631 | } |
| 632 | } |
| 633 | |
| 634 | /// The shipped defaults for a route window, with no user table. |
| 635 | #[must_use] |
| 636 | pub fn defaults_for(window: Option<usize>) -> Self { |
| 637 | Self::resolve_unchecked(None, window, None) |
| 638 | } |
| 639 | |
| 640 | /// Set one scope's ceiling to an absolute value, for the static guard. |
| 641 | /// |
| 642 | /// Deliberately absolute rather than "ceiling minus the overage": a scope |
| 643 | /// that uses less than its ceiling would otherwise keep every byte and the |
| 644 | /// prefix would stay over the guard. The guard computes the new ceiling |
| 645 | /// from the scope's *retained* usage minus the overage. |
| 646 | pub fn with_scope_ceiling(mut self, scope: InstructionScope, tokens: usize) -> Self { |
| 647 | match scope { |
| 648 | InstructionScope::Global => self.global_tokens = self.global_tokens.min(tokens), |
| 649 | InstructionScope::Project => self.project_tokens = self.project_tokens.min(tokens), |
| 650 | } |
| 651 | self |
| 652 | } |
| 653 | } |
| 654 | |
| 655 | /// Usable window: the route window minus the response ceiling and a safety |
| 656 | /// reserve of 10% (minimum 2,048 tokens). |
| 657 | #[must_use] |
| 658 | pub fn usable_window_tokens(window: usize, output: Option<usize>) -> usize { |
| 659 | let output = output.unwrap_or(0); |
| 660 | let reserve = (window / 100 * SAFETY_RESERVE_PERCENT).max(SAFETY_RESERVE_MIN_TOKENS); |
| 661 | window.saturating_sub(output).saturating_sub(reserve) |
| 662 | } |
| 663 | |
| 664 | fn share_of(total: usize, percent: u8) -> usize { |
| 665 | total / 100 * usize::from(percent) + (total % 100) * usize::from(percent) / 100 |
| 666 | } |
| 667 | |
| 668 | /// Estimated tokens for instruction text. One estimator for budgets, |
| 669 | /// reports, and markers, so a number shown to the user is the number the |
| 670 | /// trim used. |
| 671 | #[must_use] |
| 672 | pub fn estimate_instruction_tokens(text: &str) -> usize { |
| 673 | crate::compaction::estimate_text_tokens_conservative(text) |
| 674 | } |
| 675 | |
| 676 | /// Result of trimming one piece of instruction text. |
| 677 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 678 | pub struct TrimmedText { |
| 679 | pub text: String, |
| 680 | pub bytes_kept: u64, |
| 681 | pub bytes_dropped: u64, |
| 682 | pub tokens_kept: usize, |
| 683 | pub tokens_dropped: usize, |
| 684 | /// True when the marker alone consumed the budget and no source text |
| 685 | /// survived. |
| 686 | pub empty: bool, |
| 687 | } |
| 688 | |
| 689 | impl TrimmedText { |
| 690 | fn whole(text: &str) -> Self { |
| 691 | let bytes = text.len() as u64; |
| 692 | Self { |
| 693 | text: text.to_string(), |
| 694 | bytes_kept: bytes, |
| 695 | bytes_dropped: 0, |
| 696 | tokens_kept: estimate_instruction_tokens(text), |
| 697 | tokens_dropped: 0, |
| 698 | empty: text.is_empty(), |
| 699 | } |
| 700 | } |
| 701 | } |
| 702 | |
| 703 | /// Marker inserted where a head-trim dropped the tail. |
| 704 | #[must_use] |
| 705 | pub fn instruction_trim_marker(scope: InstructionScope, kept: usize, dropped: usize) -> String { |
| 706 | format!( |
| 707 | "\n\n[…{} instructions trimmed: ~{kept} estimated tokens kept, ~{dropped} estimated tokens dropped at the {} scope budget…]", |
| 708 | scope.as_str(), |
| 709 | scope.as_str() |
| 710 | ) |
| 711 | } |
| 712 | |
| 713 | /// Marker inserted when the rules block was trimmed. |
| 714 | #[must_use] |
| 715 | pub fn rules_trim_marker(kept: usize, dropped: usize) -> String { |
| 716 | format!( |
| 717 | "\n\n[…rules block trimmed: ~{kept} estimated tokens kept, ~{dropped} estimated tokens dropped at the project scope budget…]" |
| 718 | ) |
| 719 | } |
| 720 | |
| 721 | /// Keep the longest UTF-8 prefix of `text` whose estimated token count, plus |
| 722 | /// the marker, fits `budget_tokens`. |
| 723 | /// |
| 724 | /// The cut point is found by binary search over character boundaries, so the |
| 725 | /// result is deterministic and never splits a character. |
| 726 | #[must_use] |
| 727 | pub fn keep_head_within_tokens( |
| 728 | text: &str, |
| 729 | budget_tokens: usize, |
| 730 | marker: impl Fn(usize, usize) -> String, |
| 731 | ) -> TrimmedText { |
| 732 | let total_tokens = estimate_instruction_tokens(text); |
| 733 | if total_tokens <= budget_tokens { |
| 734 | return TrimmedText::whole(text); |
| 735 | } |
| 736 | // Search over byte offsets, but only ever cut on a character boundary. |
| 737 | // Both bounds move every iteration (`low` up to a strictly larger |
| 738 | // boundary, `high` down past the probed one), so the loop terminates for |
| 739 | // multibyte text — where a naive midpoint search can settle on the same |
| 740 | // floored boundary forever. |
| 741 | let floor_boundary = |index: usize| { |
| 742 | let mut index = index.min(text.len()); |
| 743 | while index > 0 && !text.is_char_boundary(index) { |
| 744 | index -= 1; |
| 745 | } |
| 746 | index |
| 747 | }; |
| 748 | let next_boundary = |index: usize| { |
| 749 | let mut index = index.min(text.len()); |
| 750 | while index < text.len() && !text.is_char_boundary(index) { |
| 751 | index += 1; |
| 752 | } |
| 753 | index |
| 754 | }; |
| 755 | let mut best = 0usize; |
| 756 | let mut low = 0usize; |
| 757 | let mut high = text.len(); |
| 758 | while low < high { |
| 759 | let mut middle = floor_boundary(low + (high - low) / 2); |
| 760 | if middle <= low { |
| 761 | middle = next_boundary(middle + 1); |
| 762 | if middle > high { |
| 763 | break; |
| 764 | } |
| 765 | } |
| 766 | let head = text[..middle].trim_end(); |
| 767 | let kept = estimate_instruction_tokens(head); |
| 768 | let rendered = format!("{head}{}", marker(kept, total_tokens.saturating_sub(kept))); |
| 769 | if estimate_instruction_tokens(&rendered) <= budget_tokens { |
| 770 | best = middle; |
| 771 | low = middle; |
| 772 | } else { |
| 773 | if middle == 0 { |
| 774 | break; |
| 775 | } |
| 776 | high = middle - 1; |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | let head = text[..best].trim_end(); |
| 781 | let kept_tokens = estimate_instruction_tokens(head); |
| 782 | let dropped_tokens = total_tokens.saturating_sub(kept_tokens); |
| 783 | if head.is_empty() { |
| 784 | return TrimmedText { |
| 785 | text: String::new(), |
| 786 | bytes_kept: 0, |
| 787 | bytes_dropped: text.len() as u64, |
| 788 | tokens_kept: 0, |
| 789 | tokens_dropped: total_tokens, |
| 790 | empty: true, |
| 791 | }; |
| 792 | } |
| 793 | let marker = marker(kept_tokens, dropped_tokens); |
| 794 | TrimmedText { |
| 795 | text: format!("{head}{marker}"), |
| 796 | bytes_kept: head.len() as u64, |
| 797 | bytes_dropped: (text.len() - head.len()) as u64, |
| 798 | tokens_kept: kept_tokens, |
| 799 | tokens_dropped: dropped_tokens, |
| 800 | empty: false, |
| 801 | } |
| 802 | } |
| 803 | |
| 804 | /// Result of one budget pass over both scopes. |
| 805 | #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)] |
| 806 | pub struct InstructionAssembly { |
| 807 | /// The rendered `<project_instructions>` body, already trimmed. |
| 808 | pub block: Option<String>, |
| 809 | pub source_path: Option<PathBuf>, |
| 810 | pub constitution_source_path: Option<PathBuf>, |
| 811 | pub constitution_tokens: usize, |
| 812 | #[serde(skip_serializing_if = "Option::is_none")] |
| 813 | pub whale_soul_revision: Option<String>, |
| 814 | #[serde(skip_serializing_if = "Option::is_none")] |
| 815 | pub whale_soul_source_path: Option<PathBuf>, |
| 816 | pub warnings: Vec<String>, |
| 817 | #[serde(skip)] |
| 818 | pub prompt_range: Option<std::ops::Range<usize>>, |
| 819 | /// Losses from trimming, plus the loader's skip notices. |
| 820 | pub notices: Vec<InstructionNotice>, |
| 821 | /// Estimated tokens kept per scope after trimming. |
| 822 | pub global_tokens: usize, |
| 823 | pub project_tokens: usize, |
| 824 | /// The budgets this pass used. |
| 825 | pub budgets: InstructionBudgets, |
| 826 | } |
| 827 | |
| 828 | impl InstructionAssembly { |
| 829 | pub fn receipt_json(&self) -> serde_json::Value { |
| 830 | let mut receipt = serde_json::json!({ "global_tokens": self.global_tokens, "project_tokens": self.project_tokens, "budgets": self.budgets, "notices": self.notices, "source_path": self.source_path, "constitution_source_path": self.constitution_source_path, "constitution_tokens": self.constitution_tokens, "retained_block_tokens": self.block.as_deref().map_or(0, estimate_instruction_tokens), "warnings": self.warnings }); |
| 831 | if let Some(revision) = &self.whale_soul_revision { |
| 832 | receipt["whale_soul_revision"] = serde_json::Value::String(revision.clone()); |
| 833 | receipt["whale_soul_source_path"] = serde_json::json!(self.whale_soul_source_path); |
| 834 | } |
| 835 | receipt |
| 836 | } |
| 837 | } |
| 838 | |
| 839 | /// Apply each scope's ceiling to the raw segments, then charge the rules |
| 840 | /// block to what is left of the project scope. |
| 841 | /// |
| 842 | /// Segments are dropped whole from the broadest end of their scope first; a |
| 843 | /// single segment above its remaining budget keeps its head. Mutating the |
| 844 | /// segments in place is what lets the joined string be rebuilt from the |
| 845 | /// trimmed truth instead of being trimmed as an opaque blob. |
| 846 | pub fn apply_instruction_budgets( |
| 847 | segments: &mut Vec<InstructionSegment>, |
| 848 | rules_block: &mut Option<String>, |
| 849 | budgets: &InstructionBudgets, |
| 850 | ) -> Vec<InstructionNotice> { |
| 851 | let mut notices = Vec::new(); |
| 852 | trim_scope( |
| 853 | segments, |
| 854 | InstructionScope::Global, |
| 855 | budgets.global_tokens, |
| 856 | &mut notices, |
| 857 | ); |
| 858 | let project_kept = trim_scope( |
| 859 | segments, |
| 860 | InstructionScope::Project, |
| 861 | budgets.project_tokens, |
| 862 | &mut notices, |
| 863 | ); |
| 864 | |
| 865 | // Anything that survived without a loss notice is reported as `kept`, so |
| 866 | // `/context report` can list every source's action rather than only the |
| 867 | // ones that lost content. |
| 868 | for segment in segments.iter() { |
| 869 | if notices.iter().any(|notice| { |
| 870 | notice.is_loss() |
| 871 | && notice.scope == segment.scope |
| 872 | && notice.origin == segment.origin |
| 873 | && notice.path == segment.path |
| 874 | }) { |
| 875 | continue; |
| 876 | } |
| 877 | notices.push(InstructionNotice { |
| 878 | path: segment.path.clone(), |
| 879 | scope: segment.scope, |
| 880 | origin: segment.origin, |
| 881 | action: InstructionAction::Kept, |
| 882 | bytes_kept: segment.text.len() as u64, |
| 883 | bytes_dropped: 0, |
| 884 | tokens_kept: estimate_instruction_tokens(&segment.text), |
| 885 | tokens_dropped: 0, |
| 886 | limit: InstructionLimit::None, |
| 887 | fallback_selected: None, |
| 888 | detail: None, |
| 889 | }); |
| 890 | } |
| 891 | |
| 892 | // Rules are project-scope authority and read after the chain, so they get |
| 893 | // whatever the instruction chain could not spend. |
| 894 | if let Some(rules) = rules_block.as_mut() { |
| 895 | let total = estimate_instruction_tokens(rules); |
| 896 | let remaining = budgets |
| 897 | .project_tokens |
| 898 | .saturating_sub(project_kept) |
| 899 | .saturating_sub(usize::from(project_kept > 0) * 2); |
| 900 | if total > remaining { |
| 901 | if remaining == 0 { |
| 902 | notices.push(InstructionNotice { |
| 903 | path: None, |
| 904 | scope: InstructionScope::Project, |
| 905 | origin: InstructionOrigin::Rules, |
| 906 | action: InstructionAction::Skipped, |
| 907 | bytes_kept: 0, |
| 908 | bytes_dropped: rules.len() as u64, |
| 909 | tokens_kept: 0, |
| 910 | tokens_dropped: total, |
| 911 | limit: InstructionLimit::RulesBudget, |
| 912 | fallback_selected: None, |
| 913 | detail: Some(InstructionDetail::RulesBudgetExhausted { |
| 914 | budget_tokens: budgets.project_tokens, |
| 915 | }), |
| 916 | }); |
| 917 | *rules_block = None; |
| 918 | } else { |
| 919 | let trimmed = keep_head_within_tokens(rules, remaining, rules_trim_marker); |
| 920 | notices.push(InstructionNotice { |
| 921 | path: None, |
| 922 | scope: InstructionScope::Project, |
| 923 | origin: InstructionOrigin::Rules, |
| 924 | action: if trimmed.empty { |
| 925 | InstructionAction::Skipped |
| 926 | } else { |
| 927 | InstructionAction::Trimmed |
| 928 | }, |
| 929 | bytes_kept: trimmed.bytes_kept, |
| 930 | bytes_dropped: trimmed.bytes_dropped, |
| 931 | tokens_kept: trimmed.tokens_kept, |
| 932 | tokens_dropped: trimmed.tokens_dropped, |
| 933 | limit: InstructionLimit::RulesBudget, |
| 934 | fallback_selected: None, |
| 935 | detail: None, |
| 936 | }); |
| 937 | *rules_block = if trimmed.text.is_empty() { |
| 938 | None |
| 939 | } else { |
| 940 | Some(trimmed.text) |
| 941 | }; |
| 942 | } |
| 943 | } else { |
| 944 | notices.push(InstructionNotice { |
| 945 | path: None, |
| 946 | scope: InstructionScope::Project, |
| 947 | origin: InstructionOrigin::Rules, |
| 948 | action: InstructionAction::Kept, |
| 949 | bytes_kept: rules.len() as u64, |
| 950 | bytes_dropped: 0, |
| 951 | tokens_kept: estimate_instruction_tokens(rules), |
| 952 | tokens_dropped: 0, |
| 953 | limit: InstructionLimit::None, |
| 954 | fallback_selected: None, |
| 955 | detail: None, |
| 956 | }); |
| 957 | } |
| 958 | } |
| 959 | |
| 960 | notices |
| 961 | } |
| 962 | |
| 963 | fn trim_scope( |
| 964 | segments: &mut Vec<InstructionSegment>, |
| 965 | scope: InstructionScope, |
| 966 | budget_tokens: usize, |
| 967 | notices: &mut Vec<InstructionNotice>, |
| 968 | ) -> usize { |
| 969 | let mut order: Vec<usize> = segments |
| 970 | .iter() |
| 971 | .enumerate() |
| 972 | .filter(|(_, segment)| segment.scope == scope) |
| 973 | .map(|(index, _)| index) |
| 974 | .collect(); |
| 975 | if order.is_empty() { |
| 976 | return 0; |
| 977 | } |
| 978 | let scope_tokens = |segments: &[InstructionSegment]| { |
| 979 | super::render_instruction_scope(segments, scope) |
| 980 | .as_deref() |
| 981 | .map_or(0, estimate_instruction_tokens) |
| 982 | }; |
| 983 | let mut kept = scope_tokens(segments); |
| 984 | if kept <= budget_tokens { |
| 985 | return kept; |
| 986 | } |
| 987 | let mut dropped: Vec<usize> = Vec::new(); |
| 988 | while order.len() > 1 && kept > budget_tokens { |
| 989 | let index = order.remove(0); |
| 990 | dropped.push(index); |
| 991 | let retained: Vec<_> = order.iter().map(|&index| segments[index].clone()).collect(); |
| 992 | kept = scope_tokens(&retained); |
| 993 | } |
| 994 | |
| 995 | let dropped_count = dropped.len(); |
| 996 | for index in &dropped { |
| 997 | let segment = &segments[*index]; |
| 998 | let tokens = estimate_instruction_tokens(&segment.text); |
| 999 | notices.push(InstructionNotice { |
| 1000 | path: segment.path.clone(), |
| 1001 | scope, |
| 1002 | origin: segment.origin, |
| 1003 | action: InstructionAction::Trimmed, |
| 1004 | bytes_kept: 0, |
| 1005 | bytes_dropped: segment.text.len() as u64, |
| 1006 | tokens_kept: 0, |
| 1007 | tokens_dropped: tokens, |
| 1008 | limit: InstructionLimit::ScopeBudget, |
| 1009 | fallback_selected: None, |
| 1010 | detail: Some(InstructionDetail::DroppedBroadest), |
| 1011 | }); |
| 1012 | } |
| 1013 | // Remove them from the segment list: a notice that says content was |
| 1014 | // dropped while the content still renders is worse than no notice. Every |
| 1015 | // dropped index sits before `order[0]`, so removing in descending order |
| 1016 | // keeps the surviving index valid. |
| 1017 | for index in dropped.iter().rev() { |
| 1018 | segments.remove(*index); |
| 1019 | } |
| 1020 | |
| 1021 | // 2. A single segment above the remaining budget keeps its head. |
| 1022 | let last = order[0] - dropped_count; |
| 1023 | let overhead = scope_tokens(std::slice::from_ref(&segments[last])) |
| 1024 | .saturating_sub(estimate_instruction_tokens(&segments[last].text)); |
| 1025 | let mut content_budget = budget_tokens.saturating_sub(overhead.saturating_add(2)); |
| 1026 | let trimmed = loop { |
| 1027 | let trimmed = |
| 1028 | keep_head_within_tokens(&segments[last].text, content_budget, |kept, dropped| { |
| 1029 | instruction_trim_marker(scope, kept, dropped) |
| 1030 | }); |
| 1031 | let mut candidate = segments[last].clone(); |
| 1032 | candidate.text = trimmed.text.clone(); |
| 1033 | let measured = if trimmed.empty { |
| 1034 | 0 |
| 1035 | } else { |
| 1036 | scope_tokens(std::slice::from_ref(&candidate)) |
| 1037 | }; |
| 1038 | if measured <= budget_tokens || content_budget == 0 { |
| 1039 | break trimmed; |
| 1040 | } |
| 1041 | content_budget = content_budget.saturating_sub(measured - budget_tokens); |
| 1042 | }; |
| 1043 | if trimmed.empty { |
| 1044 | let segment = &segments[last]; |
| 1045 | notices.push(InstructionNotice { |
| 1046 | path: segment.path.clone(), |
| 1047 | scope, |
| 1048 | origin: segment.origin, |
| 1049 | action: InstructionAction::Skipped, |
| 1050 | bytes_kept: 0, |
| 1051 | bytes_dropped: segment.text.len() as u64, |
| 1052 | tokens_kept: 0, |
| 1053 | tokens_dropped: estimate_instruction_tokens(&segment.text), |
| 1054 | limit: InstructionLimit::ScopeBudget, |
| 1055 | fallback_selected: None, |
| 1056 | detail: Some(InstructionDetail::NoRoomForContent { budget_tokens }), |
| 1057 | }); |
| 1058 | segments.remove(last); |
| 1059 | } else if trimmed.bytes_dropped > 0 { |
| 1060 | notices.push(InstructionNotice { |
| 1061 | path: segments[last].path.clone(), |
| 1062 | scope, |
| 1063 | origin: segments[last].origin, |
| 1064 | action: InstructionAction::Trimmed, |
| 1065 | bytes_kept: trimmed.bytes_kept, |
| 1066 | bytes_dropped: trimmed.bytes_dropped, |
| 1067 | tokens_kept: trimmed.tokens_kept, |
| 1068 | tokens_dropped: trimmed.tokens_dropped, |
| 1069 | limit: InstructionLimit::ScopeBudget, |
| 1070 | fallback_selected: None, |
| 1071 | detail: None, |
| 1072 | }); |
| 1073 | segments[last].text = trimmed.text; |
| 1074 | } |
| 1075 | // When the surviving segment already fits, nothing is reported for it: a |
| 1076 | // "trimmed" notice on untouched text is exactly the kind of false receipt |
| 1077 | // this contract exists to prevent. The `kept` pass below covers it. |
| 1078 | |
| 1079 | scope_tokens(segments) |
| 1080 | } |
| 1081 | |
| 1082 | #[cfg(test)] |
| 1083 | mod tests { |
| 1084 | use super::*; |
| 1085 | |
| 1086 | #[test] |
| 1087 | fn usable_window_subtracts_output_and_ten_percent() { |
| 1088 | assert_eq!(usable_window_tokens(128_000, Some(2_100)), 113_100); |
| 1089 | assert_eq!(usable_window_tokens(32_000, Some(2_000)), 26_800); |
| 1090 | // The reserve never drops below its floor. |
| 1091 | assert_eq!(usable_window_tokens(10_000, Some(0)), 10_000 - 2_048); |
| 1092 | } |
| 1093 | |
| 1094 | #[test] |
| 1095 | fn per_scope_budget_takes_the_smaller_of_absolute_and_percent() { |
| 1096 | let budgets = |
| 1097 | InstructionBudgets::resolve(None, Some(128_000), Some(2_100)).expect("resolve"); |
| 1098 | // 25% of 113,100 is 28,275, below the 100k absolute cap; 80% is |
| 1099 | // 90,480. |
| 1100 | assert_eq!(budgets.global_tokens, 28_275); |
| 1101 | assert_eq!(budgets.project_tokens, 28_275); |
| 1102 | assert_eq!(budgets.static_guard_tokens, Some(90_480)); |
| 1103 | |
| 1104 | let budgets = |
| 1105 | InstructionBudgets::resolve(None, Some(1_000_000), Some(2_048)).expect("resolve"); |
| 1106 | // The absolute cap wins on a large window: 10% per scope, 20% total. |
| 1107 | assert_eq!(budgets.global_tokens, DEFAULT_SCOPE_BUDGET_TOKENS); |
| 1108 | assert_eq!(budgets.project_tokens, DEFAULT_SCOPE_BUDGET_TOKENS); |
| 1109 | } |
| 1110 | |
| 1111 | #[test] |
| 1112 | fn absolute_cap_is_independent_of_window() { |
| 1113 | let config = InstructionBudgetConfig { |
| 1114 | global_budget_tokens: Some(500), |
| 1115 | project_budget_tokens: Some(25_000), |
| 1116 | ..Default::default() |
| 1117 | }; |
| 1118 | let budgets = InstructionBudgets::resolve(Some(&config), Some(128_000), Some(2_100)) |
| 1119 | .expect("resolve"); |
| 1120 | assert_eq!(budgets.global_tokens, 500); |
| 1121 | assert_eq!(budgets.project_tokens, 25_000); |
| 1122 | } |
| 1123 | |
| 1124 | #[test] |
| 1125 | fn invalid_percentages_and_zero_budgets_are_rejected() { |
| 1126 | for config in [ |
| 1127 | InstructionBudgetConfig { |
| 1128 | global_budget_tokens: Some(0), |
| 1129 | ..Default::default() |
| 1130 | }, |
| 1131 | InstructionBudgetConfig { |
| 1132 | project_budget_tokens: Some(0), |
| 1133 | ..Default::default() |
| 1134 | }, |
| 1135 | InstructionBudgetConfig { |
| 1136 | file_max_bytes: Some(0), |
| 1137 | ..Default::default() |
| 1138 | }, |
| 1139 | InstructionBudgetConfig { |
| 1140 | global_budget_percent: Some(0), |
| 1141 | ..Default::default() |
| 1142 | }, |
| 1143 | InstructionBudgetConfig { |
| 1144 | project_budget_percent: Some(101), |
| 1145 | ..Default::default() |
| 1146 | }, |
| 1147 | InstructionBudgetConfig { |
| 1148 | static_prefix_guard_percent: Some(0), |
| 1149 | ..Default::default() |
| 1150 | }, |
| 1151 | ] { |
| 1152 | assert!(config.validate().is_err(), "{config:?} must be rejected"); |
| 1153 | } |
| 1154 | } |
| 1155 | |
| 1156 | #[test] |
| 1157 | fn guard_must_leave_room_for_other_static_content() { |
| 1158 | let too_tight = InstructionBudgetConfig { |
| 1159 | global_budget_percent: Some(25), |
| 1160 | project_budget_percent: Some(25), |
| 1161 | static_prefix_guard_percent: Some(55), |
| 1162 | ..Default::default() |
| 1163 | }; |
| 1164 | assert!(too_tight.validate().is_err()); |
| 1165 | |
| 1166 | let inverted = InstructionBudgetConfig { |
| 1167 | global_budget_percent: Some(60), |
| 1168 | project_budget_percent: Some(60), |
| 1169 | static_prefix_guard_percent: Some(80), |
| 1170 | ..Default::default() |
| 1171 | }; |
| 1172 | assert!(inverted.validate().is_err()); |
| 1173 | |
| 1174 | let ok = InstructionBudgetConfig { |
| 1175 | global_budget_percent: Some(25), |
| 1176 | project_budget_percent: Some(25), |
| 1177 | static_prefix_guard_percent: Some(70), |
| 1178 | ..Default::default() |
| 1179 | }; |
| 1180 | assert!(ok.validate().is_ok()); |
| 1181 | } |
| 1182 | |
| 1183 | #[test] |
| 1184 | fn percent_and_guard_bounds_are_validated() { |
| 1185 | for config in [ |
| 1186 | InstructionBudgetConfig { |
| 1187 | global_budget_percent: Some(0), |
| 1188 | ..Default::default() |
| 1189 | }, |
| 1190 | InstructionBudgetConfig { |
| 1191 | project_budget_percent: Some(101), |
| 1192 | ..Default::default() |
| 1193 | }, |
| 1194 | InstructionBudgetConfig { |
| 1195 | static_prefix_guard_percent: Some(101), |
| 1196 | ..Default::default() |
| 1197 | }, |
| 1198 | ] { |
| 1199 | assert!(config.validate().is_err(), "{config:?}"); |
| 1200 | } |
| 1201 | } |
| 1202 | |
| 1203 | #[test] |
| 1204 | fn unknown_window_reports_absolute_caps_and_unknown_relative_facts() { |
| 1205 | let budgets = InstructionBudgets::resolve(None, None, None).expect("resolve"); |
| 1206 | assert_eq!(budgets.global_tokens, DEFAULT_SCOPE_BUDGET_TOKENS); |
| 1207 | assert_eq!(budgets.project_tokens, DEFAULT_SCOPE_BUDGET_TOKENS); |
| 1208 | assert_eq!(budgets.usable_window_tokens, None); |
| 1209 | assert_eq!(budgets.static_guard_tokens, None); |
| 1210 | } |
| 1211 | |
| 1212 | #[test] |
| 1213 | fn head_trim_keeps_the_head_and_reports_numbers() { |
| 1214 | let text = "руководство ".repeat(20_000); |
| 1215 | let trimmed = keep_head_within_tokens(&text, 1_000, |kept, dropped| { |
| 1216 | instruction_trim_marker(InstructionScope::Project, kept, dropped) |
| 1217 | }); |
| 1218 | assert!(!trimmed.empty); |
| 1219 | assert!(trimmed.tokens_kept <= 1_000); |
| 1220 | assert!(trimmed.tokens_dropped > 0); |
| 1221 | assert!(trimmed.text.starts_with("руководство")); |
| 1222 | assert!(trimmed.text.contains("instructions trimmed")); |
| 1223 | assert_eq!( |
| 1224 | trimmed.bytes_kept as usize + trimmed.bytes_dropped as usize, |
| 1225 | text.len() |
| 1226 | ); |
| 1227 | } |
| 1228 | |
| 1229 | #[test] |
| 1230 | fn text_within_budget_is_returned_whole() { |
| 1231 | let text = "short instructions"; |
| 1232 | let trimmed = keep_head_within_tokens(text, 1_000, |kept, dropped| { |
| 1233 | instruction_trim_marker(InstructionScope::Global, kept, dropped) |
| 1234 | }); |
| 1235 | assert_eq!(trimmed.text, text); |
| 1236 | assert_eq!(trimmed.bytes_dropped, 0); |
| 1237 | } |
| 1238 | } |
| 1239 |