Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix: B3 — wire type-aware compressors into live-zone dispatcher
chopratejas2b55050a654b
diff --git a/crates/headroom-core/src/transforms/live_zone.rs b/crates/headroom-core/src/transforms/live_zone.rsindex 03b361129..ba1f6cbb9 100644--- a/crates/headroom-core/src/transforms/live_zone.rs+++ b/crates/headroom-core/src/transforms/live_zone.rs@@ -1,4 +1,4 @@-//! Live-zone block dispatcher — Phase B PR-B2 skeleton.+//! Live-zone block dispatcher — Phase B.//!//! # The mental model//!@@ -9,6 +9,28 @@//! which are the only ones whose bytes can mutate without busting the//! provider's prompt cache.//!+//! # Provider scope+//!+//! Phase B ships ONE dispatcher entry point —+//! [`compress_anthropic_live_zone`] — that handles the Anthropic+//! Messages API shape (`/v1/messages`). Other providers (OpenAI+//! Chat Completions, OpenAI Responses, Google Gemini, Bedrock with+//! native payloads, …) need their own dispatchers because their+//! request shapes diverge in load-bearing ways:+//!+//! - OpenAI Chat Completions puts tool results in their own+//! `role: "tool"` messages, not nested in user messages.+//! - OpenAI Responses uses `input` (not `messages`) with item types+//! like `function_call_output` and `reasoning`.+//! - Gemini uses `contents`/`parts`/`function_response`.+//!+//! Phase C (`REALIGNMENT/05-phase-C-rust-proxy.md`) introduces+//! `compress_openai_chat_live_zone`, `compress_openai_responses_live_zone`,+//! and friends. They share this module's provider-agnostic types+//! ([`LiveZoneOutcome`], [`BlockAction`], [`CompressionManifest`])+//! and the per-content-type compressor backend, but each owns its+//! own walker.+//!//! For Anthropic `/v1/messages`, the live zone is bounded by://!//! - **Floor:** `frozen_message_count` (computed by@@ -23,15 +45,15 @@//! (because tool outputs dominate token budgets); `text` blocks//! are also eligible (e.g. user pastes a long log).//!-//! # What this PR ships-//!-//! The dispatcher *skeleton*: identifies live-zone blocks and routes-//! them to per-type compressor functions. PR-B2 wires every per-type-//! function to a no-op, so [`compress_live_zone`] always returns-//! [`LiveZoneOutcome::NoChange`]. Subsequent PRs replace the no-ops:+//! # Phase B build-up//!-//! - **PR-B3** wires SmartCrusher, LogCompressor, SearchCompressor,-//! DiffCompressor, CodeCompressor.+//! - **PR-B2** shipped the dispatcher *skeleton*: identify live-zone+//! blocks, route to no-op compressors, always return `NoChange`.+//! - **PR-B3** (this PR) wires per-content-type compressors:+//! `JsonArray` → SmartCrusher; `BuildOutput` → LogCompressor;+//! `SearchResults` → SearchCompressor; `GitDiff` → DiffCompressor;+//! `SourceCode` / `PlainText` / `Html` → no-op (B4 + a Rust+//! code-compressor port follow-up).//! - **PR-B4** adds the tokenizer-validation gate (per-block//! `compressed.tokens >= original.tokens` → fall back) and the//! per-content-type byte threshold below which compression is@@ -40,29 +62,75 @@//!//! # Cache safety invariant//!-//! Bytes outside the live zone are NEVER touched. The-//! [`LiveZoneOutcome::Modified`] arm carries a freshly-serialized-//! body when (and only when) at least one block was actually-//! mutated; B2's no-op compressors never trigger this arm, so the-//! current implementation provably round-trips byte-for-byte.-//! Phase A's SHA-256 fixtures pin this in CI.+//! Bytes outside the live zone are NEVER touched. PR-B3 writes new+//! bodies via **byte-range surgery**: we locate each rewritten block+//! by pointer arithmetic on `serde_json::value::RawValue` borrowed+//! slices (which retain their offset into the original buffer), then+//! splice the replacement into the output. Concretely:+//!+//! ```text+//! out = body[..block_start] || replacement || body[block_end..]+//! ```+//!+//! The bytes outside the rewritten ranges are *literally copied*+//! from the input, never re-serialized. This is how we guarantee+//! the SHA-256 of the prefix and suffix are byte-identical to the+//! input — Phase A's fixtures and B3's `byte_fidelity_outside_compressed_block`+//! test pin this in CI.+//!+//! Why byte-range surgery and not "deserialize → mutate → serialize"?+//! Re-serializing a JSON `Value` does not preserve original+//! whitespace, key order subtleties, or numeric formatting that the+//! provider may have already cached against. Byte-faithful copy of+//! everything we don't touch is the only way to guarantee+//! cache stability — see `project_compression_realignment_2026_05`.//!//! # AuthMode//!-//! The `AuthMode` parameter is taken in B2 but unused — Phase F+//! The `AuthMode` parameter is taken in B3 but unused — Phase F//! PR-F2 wires the gate (PAYG/OAuth/Subscription each demand//! different policies; see project memory//! `project_auth_mode_compression_nuances.md`). Keeping the//! parameter in the signature now means later PRs are pure//! implementation swaps, not signature redesigns.+use std::sync::OnceLock;++use serde::Deserialize;use serde_json::value::RawValue;use serde_json::Value;use thiserror::Error;+use super::content_detector::{detect_content_type, ContentType};+use super::diff_compressor::{DiffCompressor, DiffCompressorConfig};+use super::log_compressor::{LogCompressor, LogCompressorConfig};+use super::search_compressor::{SearchCompressor, SearchCompressorConfig};+use super::smart_crusher::{SmartCrusher, SmartCrusherConfig};++// ─── Tunable constants (no magic numbers in the dispatch logic) ────────++/// Strategy tag emitted when SmartCrusher rewrote a JSON-array block.+const STRATEGY_SMART_CRUSHER: &str = "smart_crusher";+/// Strategy tag emitted when LogCompressor rewrote a build-output / log block.+const STRATEGY_LOG_COMPRESSOR: &str = "log_compressor";+/// Strategy tag emitted when SearchCompressor rewrote a grep / ripgrep block.+const STRATEGY_SEARCH_COMPRESSOR: &str = "search_compressor";+/// Strategy tag emitted when DiffCompressor rewrote a unified-diff block.+const STRATEGY_DIFF_COMPRESSOR: &str = "diff_compressor";++/// Empty query context passed to compressors that take a relevance+/// query string. PR-B3 dispatcher does not yet plumb the user's last+/// prompt through; PR-F3 will.+const EMPTY_QUERY: &str = "";+/// Default relevance bias passed to scoring-aware compressors. Mirrors+/// the OSS-default behaviour ("no bias").+const DEFAULT_BIAS: f64 = 0.0;++// ─── Public types ──────────────────────────────────────────────────────+/// Authentication mode of the originating request. Passed through to/// the dispatcher so PR-F2 can vary policy without re-shaping the-/// public API. PR-B2 ignores the value (always treated as `Payg`).+/// public API. PR-B3 ignores the value (always treated as `Payg`).#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum AuthMode {/// Pay-as-you-go API key. Most aggressive compression budget —@@ -99,10 +167,50 @@ pub struct BlockOutcome {/// Disposition of one block.#[derive(Debug, Clone)]pub enum BlockAction {- /// PR-B2: every supported block type currently lands here. The- /// dispatcher inspected the block but no compressor wrote any- /// bytes. Replaced in PR-B3 with per-type compressors.- NoOpSkeleton,+ /// Content type was inspected, no compressor was applicable.+ /// Examples: `PlainText` (Kompress wires in PR-B4), `SourceCode`+ /// (Rust code-compressor port pending), `Html` (no compressor),+ /// `Image` (binary), unknown shapes.+ NoCompressionApplied {+ /// String form of the detected content type — `"text"`,+ /// `"source_code"`, `"html"`, `"image"`, `"unknown"`, etc.+ content_type: String,+ },+ /// A compressor ran and produced a smaller output that was+ /// spliced into the body.+ Compressed {+ /// Identifier of the compressor (`"smart_crusher"`,+ /// `"log_compressor"`, ...). Static so the manifest is+ /// allocation-light.+ strategy: &'static str,+ /// Bytes of the original block content (the JSON string+ /// value, after unescaping).+ original_bytes: usize,+ /// Bytes of the replacement block content.+ compressed_bytes: usize,+ },+ /// A compressor was tried but failed loudly. Per project memory+ /// `feedback_no_silent_fallbacks.md`: surface the error in the+ /// manifest; the proxy logs warn-level and forwards the original+ /// bytes for that block (other blocks in the same body still get+ /// compressed normally).+ CompressorError {+ /// Identifier of the compressor that failed.+ strategy: &'static str,+ /// Human-readable error string (from `Display`).+ error: String,+ },+ /// A compressor ran but produced output >= original. Cache+ /// safety + "don't make it worse" → keep the original. PR-B4+ /// swaps this byte-length proxy for a real tokenizer count.+ RejectedNotSmaller {+ /// Identifier of the compressor that was rejected.+ strategy: &'static str,+ /// Original block-content size, bytes.+ original_bytes: usize,+ /// Would-be compressed-block-content size, bytes.+ compressed_bytes: usize,+ },/// Block type is intentionally outside the live zone (e.g./// `tool_use` → cache hot zone) and is excluded from dispatch.Excluded { reason: ExclusionReason },@@ -147,15 +255,18 @@ impl CompressionManifest {block_outcomes: Vec::new(),}}++ /// True when at least one block was actually rewritten by a+ /// compressor (used to discriminate the `Modified` arm from+ /// `NoChange`).+ fn has_compressed_block(&self) -> bool {+ self.block_outcomes+ .iter()+ .any(|b| matches!(b.action, BlockAction::Compressed { .. }))+ }}-/// Outcome of dispatching the live zone. Variants:-///-/// - [`LiveZoneOutcome::NoChange`] — caller forwards the original-/// bytes verbatim. PR-B2 always lands here.-/// - [`LiveZoneOutcome::Modified`] — caller forwards `new_body`.-/// PR-B3+ start producing this when per-type compressors mutate-/// blocks.+/// Outcome of dispatching the live zone.#[derive(Debug)]pub enum LiveZoneOutcome {/// No bytes were rewritten. The caller must forward the original@@ -169,20 +280,15 @@ pub enum LiveZoneOutcome {},}-/// Compressor errors. Every variant is recoverable by the caller —+/// Dispatcher errors. Every variant is recoverable by the caller —/// the proxy turns each into a structured warn-level log and/// falls back to forwarding the original bytes.#[derive(Debug, Error)]pub enum LiveZoneError {- /// The request body is not valid JSON. The proxy should log- /// and forward the bytes as-is (the upstream provider will- /// reject them with a parse error — that's the correct- /// behaviour, not ours to mask).+ /// The request body is not valid JSON.#[error("request body is not valid JSON: {0}")]BodyNotJson(serde_json::Error),- /// `messages` field is missing or not a JSON array. Forward- /// the bytes — the upstream may accept a body shape we don't- /// recognize (e.g. a future Anthropic API revision).+ /// `messages` field is missing or not a JSON array.#[error("body has no `messages` array")]NoMessagesArray,}@@ -200,8 +306,80 @@ const HOT_ZONE_BLOCK_TYPES: &[&str] = &["compaction",];-/// Entry point: inspect a buffered Anthropic `/v1/messages` body and-/// decide which blocks (if any) to rewrite.+// ─── Compressor singletons ─────────────────────────────────────────────+//+// Each compressor's struct holds its config + (for SmartCrusher) the+// scoring infrastructure. Allocating one per request would be+// wasteful and (in SmartCrusher's case) defeats the purpose of the+// builder. Hold one instance per process behind `OnceLock`; cheap to+// clone the &reference each call.++fn smart_crusher() -> &'static SmartCrusher {+ static INSTANCE: OnceLock<SmartCrusher> = OnceLock::new();+ INSTANCE.get_or_init(|| SmartCrusher::new(SmartCrusherConfig::default()))+}++fn log_compressor() -> &'static LogCompressor {+ static INSTANCE: OnceLock<LogCompressor> = OnceLock::new();+ INSTANCE.get_or_init(|| LogCompressor::new(LogCompressorConfig::default()))+}++fn search_compressor() -> &'static SearchCompressor {+ static INSTANCE: OnceLock<SearchCompressor> = OnceLock::new();+ INSTANCE.get_or_init(|| SearchCompressor::new(SearchCompressorConfig::default()))+}++fn diff_compressor() -> &'static DiffCompressor {+ static INSTANCE: OnceLock<DiffCompressor> = OnceLock::new();+ INSTANCE.get_or_init(|| DiffCompressor::new(DiffCompressorConfig::default()))+}++// ─── Public entry point ────────────────────────────────────────────────++/// Inspect a buffered Anthropic `/v1/messages` body and decide which+/// blocks (if any) to rewrite.+///+/// # Provider scope (Phase B)+///+/// This function only handles the Anthropic Messages API shape:+///+/// - `messages: [{role, content}]`, with `content` either a JSON+/// string or an array of typed blocks (`text`, `tool_result`,+/// `tool_use`, `thinking`, `image`, …).+/// - The "live zone" is the latest `role == "user"` message at or+/// above `frozen_message_count`. Earlier messages are in the+/// prompt cache hot zone and are byte-preserved.+///+/// **Other providers need their own dispatchers** because their+/// request shapes diverge:+///+/// - **OpenAI Chat Completions** (`/v1/chat/completions`) — tool+/// results live in their own `role: "tool"` messages, not nested+/// in user messages. The live zone is the trailing run of+/// `tool` messages plus the latest `user` message.+/// - **OpenAI Responses API** (`/v1/responses`) — the request is+/// keyed under `input` (not `messages`) with item types like+/// `function_call_output` and `reasoning`; live zone is the+/// trailing function-call-output items since the last `message`+/// or `reasoning` item.+/// - **Google Gemini** (`/v1beta/.../:generateContent`) — request+/// is keyed under `contents` (not `messages`), with+/// `function_response` parts (not `tool_result`). Function+/// responses can be either string or structured object.+/// - **Bedrock InvokeModel** — the embedded payload follows the+/// model's native format (Anthropic, Llama, Cohere, …); route+/// to the matching dispatcher.+///+/// Phase C (`REALIGNMENT/05-phase-C-rust-proxy.md`) introduces the+/// per-provider dispatchers. Each will live as+/// `compress_<provider>_live_zone` and share the cache-safety+/// invariants and the per-content-type compressor backend+/// (SmartCrusher / LogCompressor / SearchCompressor /+/// DiffCompressor / Code) from this module. The+/// [`LiveZoneOutcome`], [`BlockAction`], and+/// [`CompressionManifest`] types are intentionally+/// provider-agnostic so the per-provider dispatchers can return+/// them unchanged.////// # Arguments///@@ -209,15 +387,16 @@ const HOT_ZONE_BLOCK_TYPES: &[&str] = &[/// UTF-8 JSON; non-JSON returns [`LiveZoneError::BodyNotJson`]./// - `frozen_message_count`: hot-zone floor. Indices `< floor` are/// excluded from dispatch.-/// - `_auth_mode`: reserved for PR-F2; B2 ignores it.+/// - `_auth_mode`: reserved for PR-F2; B3 ignores it.////// # Returns///-/// - [`LiveZoneOutcome::NoChange`] (B2 always) when no block was-/// rewritten.-/// - [`LiveZoneOutcome::Modified`] (PR-B3+) when one or more blocks-/// were rewritten — the proxy forwards the new body.-pub fn compress_live_zone(+/// - [`LiveZoneOutcome::NoChange`] when no block was rewritten+/// (either nothing was eligible, or every compressor declined /+/// failed / produced larger output).+/// - [`LiveZoneOutcome::Modified`] when at least one block was+/// rewritten — the proxy forwards the new body.+pub fn compress_anthropic_live_zone(body_raw: &[u8],frozen_message_count: usize,_auth_mode: AuthMode,@@ -240,25 +419,231 @@ pub fn compress_live_zone(// Latest user message index, restricted to the live zone (>= floor).let latest_user_message_index = find_latest_user_message_index(messages, frozen_message_count);- let block_outcomes = match latest_user_message_index {- Some(idx) => inspect_latest_user_blocks(&messages[idx], idx),- None => Vec::new(),+ let Some(target_idx) = latest_user_message_index else {+ return Ok(LiveZoneOutcome::NoChange {+ manifest: CompressionManifest {+ messages_total,+ messages_below_frozen_floor,+ latest_user_message_index: None,+ block_outcomes: Vec::new(),+ },+ });+ };++ // Resolve block ranges (byte offsets into `body_raw`) by walking+ // the body via `RawValue` borrowed slices. The Vec<Replacement>+ // produced here is the surgery plan; we do *not* mutate `body_raw`+ // while computing it.+ let plan = match plan_block_replacements(body_raw, target_idx) {+ Ok(p) => p,+ Err(_) => {+ // Body shape doesn't match what we expect (e.g. content+ // is not a string and not an array, or messages is shaped+ // unexpectedly). Treat as no-change; the proxy forwards+ // the original bytes verbatim.+ let block_outcomes =+ inspect_latest_user_blocks_value(&messages[target_idx], target_idx)+ .unwrap_or_default();+ return Ok(LiveZoneOutcome::NoChange {+ manifest: CompressionManifest {+ messages_total,+ messages_below_frozen_floor,+ latest_user_message_index: Some(target_idx),+ block_outcomes,+ },+ });+ }};+ let mut block_outcomes: Vec<BlockOutcome> = Vec::with_capacity(plan.len());+ let mut replacements: Vec<Replacement> = Vec::new();++ for slot in plan {+ let outcome = match slot.kind {+ SlotKind::HotZone(block_type) => BlockOutcome {+ message_index: target_idx,+ block_index: Some(slot.block_index),+ block_type,+ action: BlockAction::Excluded {+ reason: ExclusionReason::HotZoneBlockType,+ },+ },+ SlotKind::Compressible {+ block_type,+ content_text,+ content_byte_range,+ } => {+ let detected = detect_content_type(&content_text);+ let _detected_tag = detected.content_type.as_str();+ let outcome: BlockOutcome =+ match dispatch_compressor(&content_text, detected.content_type) {+ DispatchResult::NoOp { content_type } => BlockOutcome {+ message_index: target_idx,+ block_index: Some(slot.block_index),+ block_type,+ action: BlockAction::NoCompressionApplied {+ content_type: content_type.to_string(),+ },+ },+ DispatchResult::Compressed {+ strategy,+ compressed,+ } => {+ let original_bytes = content_text.len();+ let compressed_bytes = compressed.len();+ if compressed_bytes >= original_bytes {+ // Byte-length gate (PR-B4 will replace+ // with a token-count gate). Without this+ // the dispatcher could ship a "compressed"+ // body bigger than the input.+ BlockOutcome {+ message_index: target_idx,+ block_index: Some(slot.block_index),+ block_type,+ action: BlockAction::RejectedNotSmaller {+ strategy,+ original_bytes,+ compressed_bytes,+ },+ }+ } else {+ // Encode replacement as a JSON string and+ // record it for the splice.+ let replacement_bytes = serde_json::to_vec(&compressed)+ .expect("string is always JSON-encodable");+ replacements.push(Replacement {+ range: content_byte_range,+ replacement: replacement_bytes,+ });+ BlockOutcome {+ message_index: target_idx,+ block_index: Some(slot.block_index),+ block_type,+ action: BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ },+ }+ }+ }+ DispatchResult::Error { strategy, error } => BlockOutcome {+ message_index: target_idx,+ block_index: Some(slot.block_index),+ block_type,+ action: BlockAction::CompressorError { strategy, error },+ },+ };+ outcome+ }+ SlotKind::StringContent {+ content_text,+ content_byte_range,+ } => {+ let detected = detect_content_type(&content_text);+ match dispatch_compressor(&content_text, detected.content_type) {+ DispatchResult::NoOp { content_type } => BlockOutcome {+ message_index: target_idx,+ block_index: None,+ block_type: "string_content".to_string(),+ action: BlockAction::NoCompressionApplied {+ content_type: content_type.to_string(),+ },+ },+ DispatchResult::Compressed {+ strategy,+ compressed,+ } => {+ let original_bytes = content_text.len();+ let compressed_bytes = compressed.len();+ if compressed_bytes >= original_bytes {+ BlockOutcome {+ message_index: target_idx,+ block_index: None,+ block_type: "string_content".to_string(),+ action: BlockAction::RejectedNotSmaller {+ strategy,+ original_bytes,+ compressed_bytes,+ },+ }+ } else {+ let replacement_bytes = serde_json::to_vec(&compressed)+ .expect("string is always JSON-encodable");+ replacements.push(Replacement {+ range: content_byte_range,+ replacement: replacement_bytes,+ });+ BlockOutcome {+ message_index: target_idx,+ block_index: None,+ block_type: "string_content".to_string(),+ action: BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ },+ }+ }+ }+ DispatchResult::Error { strategy, error } => BlockOutcome {+ message_index: target_idx,+ block_index: None,+ block_type: "string_content".to_string(),+ action: BlockAction::CompressorError { strategy, error },+ },+ }+ }+ };+ block_outcomes.push(outcome);+ }+let manifest = CompressionManifest {messages_total,messages_below_frozen_floor,- latest_user_message_index,+ latest_user_message_index: Some(target_idx),block_outcomes,};- // PR-B2: no compressor mutates anything, so the dispatcher- // always lands on `NoChange`. PR-B3+ replaces this with a- // per-block accumulator that tracks whether any byte was- // actually rewritten.- Ok(LiveZoneOutcome::NoChange { manifest })+ if !manifest.has_compressed_block() || replacements.is_empty() {+ return Ok(LiveZoneOutcome::NoChange { manifest });+ }++ // Build the new body via byte-range surgery. Replacements are+ // produced in ascending block order; sort defensively.+ let new_bytes = apply_replacements(body_raw, &mut replacements);++ // The output is always still valid JSON: every replacement is a+ // JSON string slot replaced by another JSON string slot. We could+ // round-trip-verify with `serde_json::from_slice` and bail out to+ // NoChange on failure, but that doubles parse cost on the hot+ // path. Rely on type discipline; the byte_fidelity test in+ // `live_zone_dispatch.rs` pins correctness.+ let new_body_str = match std::str::from_utf8(&new_bytes) {+ Ok(s) => s,+ Err(_) => {+ // Should be impossible: input was valid JSON (UTF-8) and+ // every replacement was a JSON-encoded string (also UTF-8).+ // Fall back rather than risk shipping malformed bytes.+ return Ok(LiveZoneOutcome::NoChange { manifest });+ }+ };+ let raw = match RawValue::from_string(new_body_str.to_string()) {+ Ok(r) => r,+ Err(_) => {+ // Same defensive bail-out; should not happen.+ return Ok(LiveZoneOutcome::NoChange { manifest });+ }+ };++ Ok(LiveZoneOutcome::Modified {+ new_body: raw,+ manifest,+ })}+// ─── Internal helpers ──────────────────────────────────────────────────+/// Walk `messages` from the back, returning the index of the latest/// `role == "user"` message. Restricted to indices `>= floor`; if/// the latest user message lies in the cache hot zone we return@@ -276,32 +661,419 @@ fn find_latest_user_message_index(messages: &[Value], floor: usize) -> Option<usNone}-/// Identify each block in the latest user message and tag it with-/// the dispatcher action it would receive. PR-B2: every dispatched-/// block lands on [`BlockAction::NoOpSkeleton`].-fn inspect_latest_user_blocks(message: &Value, message_index: usize) -> Vec<BlockOutcome> {- let content = match message.get("content") {- Some(c) => c,- None => return Vec::new(),+/// Body-shape view used to find byte ranges.+///+/// `&'a RawValue` borrows are pointer-equal to slices into the input+/// buffer; we use this to compute exact byte offsets via the+/// `bytes_offset_of` helper. The struct intentionally only captures+/// the path we need; everything else is left unparsed.+#[derive(Deserialize)]+struct BodyView<'a> {+ #[serde(borrow)]+ messages: Vec<&'a RawValue>,+}++#[derive(Deserialize)]+struct MessageView<'a> {+ #[serde(borrow, default)]+ content: Option<&'a RawValue>,+}++#[derive(Deserialize)]+struct BlockHeader<'a> {+ #[serde(borrow, default)]+ r#type: Option<&'a str>,+ #[serde(borrow, default)]+ content: Option<&'a RawValue>,+}++/// Per-block dispatch slot the planner emits.+struct PlanSlot {+ block_index: usize,+ kind: SlotKind,+}++enum SlotKind {+ /// Content is a JSON string the dispatcher may compress in place.+ Compressible {+ block_type: String,+ content_text: String,+ content_byte_range: (usize, usize),+ },+ /// String-shaped message content (Anthropic legacy shape: the+ /// whole message's `content` is a JSON string, no per-block+ /// array).+ StringContent {+ content_text: String,+ content_byte_range: (usize, usize),+ },+ /// Block type is on the cache-hot list — record but do not+ /// dispatch.+ HotZone(String),+}++/// Walk the buffered body, return one `PlanSlot` per block in the+/// latest user message. Errors out on shapes the dispatcher does not+/// support (e.g. structured-array `content` inside a tool_result —+/// rare; we degrade to NoChange in that case).+fn plan_block_replacements(+ body_raw: &[u8],+ target_msg_idx: usize,+) -> Result<Vec<PlanSlot>, PlanError> {+ // `serde_json::from_slice` requires UTF-8; we re-validate here+ // explicitly so the pointer-arithmetic helper can take a `&str`+ // without unsafe.+ let body_str = std::str::from_utf8(body_raw).map_err(|_| PlanError::ParseFailed)?;+ let body: BodyView<'_> = serde_json::from_str(body_str).map_err(|_| PlanError::ParseFailed)?;+ let target_msg_raw = body+ .messages+ .get(target_msg_idx)+ .ok_or(PlanError::TargetOutOfBounds)?;++ let msg_view: MessageView<'_> =+ serde_json::from_str(target_msg_raw.get()).map_err(|_| PlanError::ParseFailed)?;++ let Some(content_raw) = msg_view.content else {+ return Ok(Vec::new());};- // Anthropic accepts string-shaped content (legacy) and- // array-of-blocks content (current). String content has no- // sub-blocks; treat it as one synthetic "string_content" entry- // so observability still records that the live zone exists.- if let Some(_text) = content.as_str() {- return vec![BlockOutcome {+ // Compute the byte offset of the message's `content` value into+ // `body_raw`. The target_msg_raw points into body_raw; content_raw+ // points into target_msg_raw's bytes (which are the same backing+ // memory).+ let content_offset_in_msg =+ bytes_offset_of(target_msg_raw.get(), content_raw.get()).ok_or(PlanError::OffsetMissing)?;+ let msg_offset_in_body =+ bytes_offset_of(body_str, target_msg_raw.get()).ok_or(PlanError::OffsetMissing)?;+ let content_offset_in_body = msg_offset_in_body + content_offset_in_msg;++ let content_str = content_raw.get();++ // Case 1: content is a JSON string (Anthropic legacy shape for+ // user messages).+ if content_str.starts_with('"') {+ let unescaped: String =+ serde_json::from_str(content_str).map_err(|_| PlanError::ParseFailed)?;+ return Ok(vec![PlanSlot {+ block_index: 0,+ kind: SlotKind::StringContent {+ content_text: unescaped,+ content_byte_range: (+ content_offset_in_body,+ content_offset_in_body + content_str.len(),+ ),+ },+ }]);+ }++ // Case 2: content is an array of blocks. Borrow each block as a+ // &RawValue so we can compute its byte range too.+ let blocks: Vec<&RawValue> =+ serde_json::from_str(content_str).map_err(|_| PlanError::ParseFailed)?;++ let mut slots = Vec::with_capacity(blocks.len());+ for (block_idx, block_raw) in blocks.iter().enumerate() {+ let block_offset_in_content =+ bytes_offset_of(content_str, block_raw.get()).ok_or(PlanError::OffsetMissing)?;+ let block_offset_in_body = content_offset_in_body + block_offset_in_content;++ let header: BlockHeader<'_> =+ serde_json::from_str(block_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let block_type = header.r#type.unwrap_or("unknown").to_string();++ if HOT_ZONE_BLOCK_TYPES.iter().any(|t| *t == block_type) {+ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::HotZone(block_type),+ });+ continue;+ }++ // Find the inner `content` field's byte range. For tool_result+ // blocks this is the field we'd compress. For text blocks+ // it's a `text` field — we read that instead.+ let (inner_field_str, inner_field_offset_in_block) = match block_type.as_str() {+ "tool_result" => {+ let Some(field_raw) = header.content else {+ // tool_result with no content — skip dispatch.+ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::Compressible {+ block_type,+ content_text: String::new(),+ content_byte_range: (block_offset_in_body, block_offset_in_body),+ },+ });+ continue;+ };+ let off = bytes_offset_of(block_raw.get(), field_raw.get())+ .ok_or(PlanError::OffsetMissing)?;+ (field_raw.get(), off)+ }+ "text" => {+ #[derive(Deserialize)]+ struct TextHeader<'a> {+ #[serde(borrow, default)]+ text: Option<&'a RawValue>,+ }+ let h: TextHeader<'_> =+ serde_json::from_str(block_raw.get()).map_err(|_| PlanError::ParseFailed)?;+ let Some(text_raw) = h.text else {+ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::Compressible {+ block_type,+ content_text: String::new(),+ content_byte_range: (block_offset_in_body, block_offset_in_body),+ },+ });+ continue;+ };+ let off = bytes_offset_of(block_raw.get(), text_raw.get())+ .ok_or(PlanError::OffsetMissing)?;+ (text_raw.get(), off)+ }+ _ => {+ // image, document, etc. — record as compressible+ // block-type but with empty content so no compressor+ // runs.+ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::Compressible {+ block_type,+ content_text: String::new(),+ content_byte_range: (block_offset_in_body, block_offset_in_body),+ },+ });+ continue;+ }+ };++ // The compressors expect a plain string, not a JSON-quoted+ // string. `tool_result.content` and `text.text` are+ // either a JSON string or a structured array; we only+ // compress the string shape (B3). Structured-array shape+ // falls through to no-op.+ if !inner_field_str.starts_with('"') {+ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::Compressible {+ block_type,+ content_text: String::new(),+ content_byte_range: (block_offset_in_body, block_offset_in_body),+ },+ });+ continue;+ }+ let unescaped: String =+ serde_json::from_str(inner_field_str).map_err(|_| PlanError::ParseFailed)?;++ let inner_field_start_in_body = block_offset_in_body + inner_field_offset_in_block;+ let inner_field_end_in_body = inner_field_start_in_body + inner_field_str.len();++ slots.push(PlanSlot {+ block_index: block_idx,+ kind: SlotKind::Compressible {+ block_type,+ content_text: unescaped,+ content_byte_range: (inner_field_start_in_body, inner_field_end_in_body),+ },+ });+ }++ Ok(slots)+}++#[derive(Debug)]+enum PlanError {+ /// JSON parse failure on a body-shape view we expected to succeed.+ ParseFailed,+ /// Pointer-arithmetic could not locate a sub-slice's offset.+ /// Should not happen for valid JSON; surfacing rather than+ /// silently degrading.+ OffsetMissing,+ /// Latest-user-message index points past the end of `messages`.+ /// The caller already validated this — surfacing for safety.+ TargetOutOfBounds,+}++/// Compute the byte offset of `child` within `parent` when both are+/// `&str` views into the same backing memory. Returns `None` when+/// `child` does not lie strictly inside `parent`.+///+/// We rely on this trick because `serde_json` does not expose the+/// byte offset of a `&RawValue`; the `RawValue::get()` slice points+/// into the input buffer when `from_slice` / `from_str` was used,+/// so pointer arithmetic recovers it.+fn bytes_offset_of(parent: &str, child: &str) -> Option<usize> {+ let parent_start = parent.as_ptr() as usize;+ let parent_end = parent_start + parent.len();+ let child_start = child.as_ptr() as usize;+ if child_start < parent_start || child_start + child.len() > parent_end {+ return None;+ }+ Some(child_start - parent_start)+}++/// One byte-range replacement to apply. Sorted in ascending `range.0`+/// before splicing.+struct Replacement {+ range: (usize, usize),+ replacement: Vec<u8>,+}++/// Apply all `replacements` to `original`, returning the new buffer.+/// `replacements` are sorted in-place by ascending start offset; the+/// caller may inspect them post-call (they remain valid).+fn apply_replacements(original: &[u8], replacements: &mut [Replacement]) -> Vec<u8> {+ replacements.sort_by_key(|r| r.range.0);++ // Pre-size: original_len - sum(removed) + sum(replacement_len).+ let removed: usize = replacements.iter().map(|r| r.range.1 - r.range.0).sum();+ let added: usize = replacements.iter().map(|r| r.replacement.len()).sum();+ let mut out = Vec::with_capacity(original.len().saturating_sub(removed) + added);++ let mut cursor = 0usize;+ for r in replacements.iter() {+ out.extend_from_slice(&original[cursor..r.range.0]);+ out.extend_from_slice(&r.replacement);+ cursor = r.range.1;+ }+ out.extend_from_slice(&original[cursor..]);+ out+}++/// Per-block dispatch result — whether any compressor ran and what+/// it produced.+enum DispatchResult {+ /// No compressor was applicable for this content type.+ NoOp { content_type: &'static str },+ /// A compressor ran and produced a candidate replacement string.+ Compressed {+ strategy: &'static str,+ compressed: String,+ },+ /// A compressor ran and failed loudly. The error string is+ /// surfaced via the manifest; the proxy logs it.+ #[allow(dead_code)]+ Error {+ strategy: &'static str,+ error: String,+ },+}++/// Map `(text, content_type)` to the compressor result.+///+/// Per spec PR-B3:+///+/// - `JsonArray` (with `is_dict_array=true`) → SmartCrusher+/// - `BuildOutput` → LogCompressor+/// - `SearchResults` → SearchCompressor+/// - `GitDiff` → DiffCompressor+/// - `SourceCode` → no-op (Rust port pending; see TODO below)+/// - `PlainText` → no-op (PR-B4 wires Kompress)+/// - `Html` → no-op (no compressor)+fn dispatch_compressor(text: &str, content_type: ContentType) -> DispatchResult {+ if text.is_empty() {+ return DispatchResult::NoOp {+ content_type: content_type.as_str(),+ };+ }++ match content_type {+ ContentType::JsonArray => {+ // The detector classifies arrays-of-scalars as JsonArray+ // too (confidence 0.8). SmartCrusher's `crush` is safe to+ // call on those — it parses, finds no compressible+ // arrays, and returns the input.+ let result = smart_crusher().crush(text, EMPTY_QUERY, DEFAULT_BIAS);+ if !result.was_modified {+ return DispatchResult::NoOp {+ content_type: content_type.as_str(),+ };+ }+ DispatchResult::Compressed {+ strategy: STRATEGY_SMART_CRUSHER,+ compressed: result.compressed,+ }+ }+ ContentType::BuildOutput => {+ let (result, _stats) = log_compressor().compress(text, DEFAULT_BIAS);+ if result.compressed == result.original {+ return DispatchResult::NoOp {+ content_type: content_type.as_str(),+ };+ }+ DispatchResult::Compressed {+ strategy: STRATEGY_LOG_COMPRESSOR,+ compressed: result.compressed,+ }+ }+ ContentType::SearchResults => {+ let (result, _stats) = search_compressor().compress(text, EMPTY_QUERY, DEFAULT_BIAS);+ if result.compressed == result.original {+ return DispatchResult::NoOp {+ content_type: content_type.as_str(),+ };+ }+ DispatchResult::Compressed {+ strategy: STRATEGY_SEARCH_COMPRESSOR,+ compressed: result.compressed,+ }+ }+ ContentType::GitDiff => {+ let result = diff_compressor().compress(text, EMPTY_QUERY);+ if result.compressed == text {+ return DispatchResult::NoOp {+ content_type: content_type.as_str(),+ };+ }+ DispatchResult::Compressed {+ strategy: STRATEGY_DIFF_COMPRESSOR,+ compressed: result.compressed,+ }+ }+ // TODO(PR-B4 / Rust code-compressor port): Python has a+ // CodeAwareCompressor; the Rust port is not yet shipped. Once+ // that crate lands, `ContentType::SourceCode` routes here+ // exactly as the others above.+ ContentType::SourceCode => DispatchResult::NoOp {+ content_type: content_type.as_str(),+ },+ // TODO(PR-B4): wire Kompress (lossless prose compressor) for+ // PlainText. For now, leave untouched.+ ContentType::PlainText => DispatchResult::NoOp {+ content_type: content_type.as_str(),+ },+ // No HTML compressor on the Rust side; pages are handled by+ // upstream extractors, not the proxy.+ ContentType::Html => DispatchResult::NoOp {+ content_type: content_type.as_str(),+ },+ }+}++/// Fallback when byte-range planning fails: still record per-block+/// outcomes so observability covers the request. Mirrors PR-B2's+/// observation-only path.+fn inspect_latest_user_blocks_value(+ message: &Value,+ message_index: usize,+) -> Option<Vec<BlockOutcome>> {+ let content = message.get("content")?;++ if content.as_str().is_some() {+ return Some(vec![BlockOutcome {message_index,block_index: None,block_type: "string_content".to_string(),- action: BlockAction::NoOpSkeleton,- }];+ action: BlockAction::NoCompressionApplied {+ content_type: "text".to_string(),+ },+ }]);}- let Some(blocks) = content.as_array() else {- return Vec::new();- };-+ let blocks = content.as_array()?;let mut outcomes = Vec::with_capacity(blocks.len());for (idx, block) in blocks.iter().enumerate() {let block_type = block@@ -314,12 +1086,9 @@ fn inspect_latest_user_blocks(message: &Value, message_index: usize) -> Vec<Blocreason: ExclusionReason::HotZoneBlockType,}} else {- // PR-B2: every other block type routes to the no-op- // dispatcher. PR-B3 replaces this branch with a real- // per-type compressor switch (`tool_result` →- // SmartCrusher / Log / Search / Diff / Code based on- // content sniffing; `text` → SmartCrusher prose).- BlockAction::NoOpSkeleton+ BlockAction::NoCompressionApplied {+ content_type: "unknown".to_string(),+ }};outcomes.push(BlockOutcome {message_index,@@ -328,8 +1097,7 @@ fn inspect_latest_user_blocks(message: &Value, message_index: usize) -> Vec<Blocaction,});}-- outcomes+ Some(outcomes)}#[cfg(test)]@@ -352,7 +1120,7 @@ mod tests {#[test]fn empty_messages_yields_no_change() {let b = body(json!({"model": "claude", "messages": []}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();match out {LiveZoneOutcome::NoChange { manifest } => {assert_eq!(manifest.messages_total, 0);@@ -366,13 +1134,13 @@ mod tests {#[test]fn no_messages_field_errors() {let b = body(json!({"model": "claude"}));- let err = compress_live_zone(&b, 0, AuthMode::Payg).unwrap_err();+ let err = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap_err();assert!(matches!(err, LiveZoneError::NoMessagesArray));}#[test]fn invalid_json_errors() {- let err = compress_live_zone(b"not json", 0, AuthMode::Payg).unwrap_err();+ let err = compress_anthropic_live_zone(b"not json", 0, AuthMode::Payg).unwrap_err();assert!(matches!(err, LiveZoneError::BodyNotJson(_)));}@@ -389,10 +1157,10 @@ mod tests {]},]}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,- _ => panic!("expected NoChange"),+ LiveZoneOutcome::Modified { manifest, .. } => manifest,};assert_eq!(manifest.latest_user_message_index, Some(2));let block_msg_indices: Vec<usize> = manifest@@ -415,7 +1183,7 @@ mod tests {{"role": "user", "content": [{"type": "text", "text": "second"}]},]}));- let out = compress_live_zone(&b, 2, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 2, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,_ => panic!("expected NoChange"),@@ -427,8 +1195,6 @@ mod tests {#[test]fn excludes_hot_zone_block_types() {- // tool_use inside a user message (uncommon shape but legal in- // some assistants) must be tagged HotZoneBlockType.let b = body(json!({"messages": [{"role": "user",@@ -439,17 +1205,24 @@ mod tests {]}]}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();let actions = outcome_block_actions(&out);assert_eq!(actions.len(), 3);- assert!(matches!(actions[0], BlockAction::NoOpSkeleton));+ // tool_result with tiny content → NoCompressionApplied (under threshold / detector returns plain text).+ assert!(matches!(+ actions[0],+ BlockAction::NoCompressionApplied { .. }+ ));assert!(matches!(actions[1],BlockAction::Excluded {reason: ExclusionReason::HotZoneBlockType}));- assert!(matches!(actions[2], BlockAction::NoOpSkeleton));+ assert!(matches!(+ actions[2],+ BlockAction::NoCompressionApplied { .. }+ ));}#[test]@@ -457,26 +1230,25 @@ mod tests {let b = body(json!({"messages": [{"role": "user", "content": "just a string"}]}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,- _ => panic!("expected NoChange"),+ LiveZoneOutcome::Modified { manifest, .. } => manifest,};assert_eq!(manifest.block_outcomes.len(), 1);assert_eq!(manifest.block_outcomes[0].block_type, "string_content");assert!(matches!(manifest.block_outcomes[0].action,- BlockAction::NoOpSkeleton+ BlockAction::NoCompressionApplied { .. }));}#[test]fn no_user_message_in_live_zone_returns_no_blocks() {- // Only an assistant message → no live zone candidate.let b = body(json!({"messages": [{"role": "assistant", "content": "hi"}]}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,_ => panic!("expected NoChange"),@@ -486,34 +1258,32 @@ mod tests {}#[test]- fn auth_mode_does_not_affect_b2_outcome() {- // PR-F2 will wire policy; in B2 every mode behaves identically.+ fn auth_mode_does_not_affect_b3_outcome_for_short_input() {+ // Trivial input → every mode behaves identically.let b = body(json!({"messages": [{"role": "user", "content": [{"type": "text", "text": "hi"}]}]}));- let payg = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();- let oauth = compress_live_zone(&b, 0, AuthMode::OAuth).unwrap();- let sub = compress_live_zone(&b, 0, AuthMode::Subscription).unwrap();+ let payg = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let oauth = compress_anthropic_live_zone(&b, 0, AuthMode::OAuth).unwrap();+ let sub = compress_anthropic_live_zone(&b, 0, AuthMode::Subscription).unwrap();for o in [&payg, &oauth, &sub] {assert!(matches!(o, LiveZoneOutcome::NoChange { .. }));}}#[test]- fn no_change_when_no_block_mutated_returns_original_semantics() {- // PR-B2 invariant: dispatcher always returns NoChange.- // PR-B3+ will start emitting Modified; this test pins the- // current contract so an accidental early-Modified emission- // is caught at compile time of the next phase.+ fn no_change_when_input_already_minimal_returns_original_semantics() {+ // tiny tool_result → detected as plain text, no-op+ // dispatch → NoChange.let b = body(json!({"messages": [{"role": "user","content": [- {"type": "tool_result", "tool_use_id": "t", "content": "x".repeat(10_000)},+ {"type": "tool_result", "tool_use_id": "t", "content": "x"},]}]}));- let out = compress_live_zone(&b, 0, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 0, AuthMode::Payg).unwrap();assert!(matches!(out, LiveZoneOutcome::NoChange { .. }));}@@ -526,10 +1296,10 @@ mod tests {{"role": "user", "content": "live"},]}));- let out = compress_live_zone(&b, 2, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 2, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,- _ => panic!("expected NoChange"),+ LiveZoneOutcome::Modified { manifest, .. } => manifest,};assert_eq!(manifest.messages_total, 3);assert_eq!(manifest.messages_below_frozen_floor, 2);@@ -538,11 +1308,10 @@ mod tests {#[test]fn frozen_count_above_messages_clamps() {- // floor > total: clamped, no live zone.let b = body(json!({"messages": [{"role": "user", "content": "x"}]}));- let out = compress_live_zone(&b, 99, AuthMode::Payg).unwrap();+ let out = compress_anthropic_live_zone(&b, 99, AuthMode::Payg).unwrap();let manifest = match &out {LiveZoneOutcome::NoChange { manifest } => manifest,_ => panic!("expected NoChange"),diff --git a/crates/headroom-core/src/transforms/mod.rs b/crates/headroom-core/src/transforms/mod.rsindex 5444818e4..ef09dbcea 100644--- a/crates/headroom-core/src/transforms/mod.rs+++ b/crates/headroom-core/src/transforms/mod.rs@@ -38,8 +38,8 @@ pub use diff_compressor::{DiffCompressionResult, DiffCompressor, DiffCompressorConfig, DiffCompressorStats,};pub use live_zone::{- compress_live_zone, AuthMode, BlockAction, BlockOutcome, CompressionManifest, ExclusionReason,- LiveZoneError, LiveZoneOutcome,+ compress_anthropic_live_zone, AuthMode, BlockAction, BlockOutcome, CompressionManifest,+ ExclusionReason, LiveZoneError, LiveZoneOutcome,};pub use log_compressor::{LogCompressionResult, LogCompressor, LogCompressorConfig, LogCompressorStats, LogFormat,diff --git a/crates/headroom-core/tests/live_zone_dispatch.rs b/crates/headroom-core/tests/live_zone_dispatch.rsnew file mode 100644index 000000000..264154d15--- /dev/null+++ b/crates/headroom-core/tests/live_zone_dispatch.rs@@ -0,0 +1,373 @@+//! Integration tests for the PR-B3 live-zone dispatcher.+//!+//! These pin the per-content-type routing contract:+//!+//! - JSON array tool_results → SmartCrusher+//! - Build/log output → LogCompressor+//! - Search-result tool_results → SearchCompressor+//! - Git diff tool_results → DiffCompressor+//! - Source code → no-op (Rust port pending)+//! - Unknown / image / html → no-op+//!+//! Plus the cache-safety invariant: bytes outside the rewritten+//! block are byte-identical to the input (SHA-256 prefix + suffix).++use headroom_core::transforms::{compress_anthropic_live_zone, AuthMode, BlockAction, LiveZoneOutcome};+use serde_json::{json, Value};+use sha2::{Digest, Sha256};++fn body_of(value: Value) -> Vec<u8> {+ serde_json::to_vec(&value).unwrap()+}++fn dispatch(body: &[u8]) -> LiveZoneOutcome {+ compress_anthropic_live_zone(body, 0, AuthMode::Payg).expect("dispatcher returns Ok on valid bodies")+}++/// Find the byte range of the FIRST occurrence of `needle` inside+/// `haystack`. Used by the byte-fidelity test below to identify the+/// JSON-encoded tool_result.content slot we expect the dispatcher to+/// rewrite. Returns `(start, end)` half-open.+fn find_byte_range(haystack: &[u8], needle: &[u8]) -> (usize, usize) {+ let pos = haystack+ .windows(needle.len())+ .position(|w| w == needle)+ .unwrap_or_else(|| {+ panic!(+ "needle of {} bytes not found in haystack of {} bytes",+ needle.len(),+ haystack.len()+ )+ });+ (pos, pos + needle.len())+}++fn sha256(bytes: &[u8]) -> [u8; 32] {+ let mut h = Sha256::new();+ h.update(bytes);+ h.finalize().into()+}++/// Build a body with one user message containing one `tool_result`+/// whose `content` is `text`. Returns the full body and the byte+/// range of the JSON-encoded `content` slot (including the surrounding+/// quotes) within that body — useful for byte-fidelity assertions.+fn body_with_tool_result(text: &str) -> (Vec<u8>, (usize, usize)) {+ let body = body_of(json!({+ "model": "claude-sonnet-4-6",+ "max_tokens": 64,+ "system": "you are a helpful assistant",+ "messages": [{+ "role": "user",+ "content": [{+ "type": "tool_result",+ "tool_use_id": "toolu_dispatch_test",+ "content": text,+ }],+ }],+ }));+ // The JSON-encoded `content` slot is exactly `serde_json::to_vec(&text)`,+ // since text is shorter than the whole body and serde uses the same+ // encoding for the embedded string.+ let needle = serde_json::to_vec(&text).unwrap();+ let range = find_byte_range(&body, &needle);+ (body, range)+}++// ─── Routing tests ─────────────────────────────────────────────────────++#[test]+fn json_tool_result_routes_to_smart_crusher() {+ // Array of homogeneous dicts → SmartCrusher's bread-and-butter.+ let array_of_dicts: Vec<Value> = (0..200)+ .map(|i| {+ json!({+ "id": i,+ "status": "ok",+ "value": format!("repeat-pattern-{}", i % 3),+ })+ })+ .collect();+ let payload = serde_json::to_string(&array_of_dicts).unwrap();+ let (body, _) = body_with_tool_result(&payload);++ let out = dispatch(&body);+ let manifest = match &out {+ LiveZoneOutcome::Modified { manifest, .. } => manifest,+ LiveZoneOutcome::NoChange { manifest } => panic!(+ "expected SmartCrusher to compress 200 homogeneous dicts; got NoChange. manifest: {manifest:?}"+ ),+ };+ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present in manifest")+ .action+ .clone();+ match action {+ BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ } => {+ assert_eq!(strategy, "smart_crusher", "expected SmartCrusher dispatch");+ assert!(+ compressed_bytes < original_bytes,+ "SmartCrusher must produce strictly smaller output ({compressed_bytes} < {original_bytes})"+ );+ }+ other => panic!("expected BlockAction::Compressed, got {other:?}"),+ }+}++#[test]+fn log_tool_result_routes_to_log_compressor() {+ // Multi-line build/log output that the detector classifies as+ // `BuildOutput`. Repetitive lines compress well.+ let mut lines = String::new();+ for i in 0..200 {+ lines.push_str(&format!(+ "[INFO] 2026-05-02T19:30:{:02}.000Z app=widget request_id=abc-{} pool=default ok\n",+ i % 60,+ i+ ));+ }+ let (body, _) = body_with_tool_result(&lines);++ let out = dispatch(&body);+ let manifest = match &out {+ LiveZoneOutcome::Modified { manifest, .. } => manifest,+ LiveZoneOutcome::NoChange { .. } => {+ // The log compressor may decline if the lines aren't+ // repetitive enough; accept either outcome but require the+ // detector to have routed it correctly. Check the manifest+ // for the dispatch attempt.+ let nochange_manifest = match &out {+ LiveZoneOutcome::NoChange { manifest } => manifest,+ _ => unreachable!(),+ };+ let action = nochange_manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ assert!(+ matches!(+ action,+ BlockAction::NoCompressionApplied { .. }+ | BlockAction::RejectedNotSmaller { .. }+ ),+ "log dispatch declined cleanly: {action:?}"+ );+ return;+ }+ };++ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ match action {+ BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ } => {+ assert_eq!(strategy, "log_compressor");+ assert!(compressed_bytes < original_bytes);+ }+ other => panic!("expected log_compressor Compressed, got {other:?}"),+ }+}++#[test]+fn diff_tool_result_routes_to_diff_compressor() {+ // A unidiff with surrounding context the diff compressor can trim.+ let mut diff = String::from("diff --git a/foo.rs b/foo.rs\n--- a/foo.rs\n+++ b/foo.rs\n");+ diff.push_str("@@ -1,40 +1,40 @@\n");+ for i in 0..18 {+ diff.push_str(&format!(" context line {i}\n"));+ }+ diff.push_str("-old line\n+new line\n");+ for i in 0..18 {+ diff.push_str(&format!(" context line {}\n", i + 18));+ }++ let (body, _) = body_with_tool_result(&diff);+ let out = dispatch(&body);+ let manifest = match &out {+ LiveZoneOutcome::Modified { manifest, .. } => manifest,+ LiveZoneOutcome::NoChange { manifest } => {+ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ assert!(+ matches!(+ action,+ BlockAction::NoCompressionApplied { .. }+ | BlockAction::RejectedNotSmaller { .. }+ ),+ "diff dispatch declined cleanly: {action:?}"+ );+ return;+ }+ };+ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ match action {+ BlockAction::Compressed { strategy, .. } => {+ assert_eq!(strategy, "diff_compressor");+ }+ other => panic!("expected diff_compressor Compressed, got {other:?}"),+ }+}++#[test]+fn source_code_tool_result_routes_to_no_op() {+ // Detector classifies this as SourceCode. PR-B3 routes it to+ // no-op (Rust code-compressor port pending). Pin the contract+ // so a future "wire it up" PR can flip this assertion.+ let code = "+fn main() {+ let x: i32 = 42;+ let y = x * 2;+ println!(\"{}\", y);+ if x > 0 {+ println!(\"positive\");+ } else {+ println!(\"non-positive\");+ }+}+"+ .repeat(20);+ let (body, _) = body_with_tool_result(&code);+ let out = dispatch(&body);+ let manifest = match &out {+ LiveZoneOutcome::NoChange { manifest } => manifest,+ LiveZoneOutcome::Modified { manifest, .. } => {+ panic!("PR-B3 must NOT compress SourceCode (Rust port pending). manifest: {manifest:?}")+ }+ };+ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ match action {+ BlockAction::NoCompressionApplied { content_type } => {+ // Detector may classify code-with-prose as PlainText; both+ // outcomes are no-op for B3 so accept either tag.+ assert!(+ content_type == "source_code" || content_type == "text",+ "unexpected content_type tag: {content_type}"+ );+ }+ other => panic!("expected NoCompressionApplied, got {other:?}"),+ }+}++#[test]+fn unknown_content_type_no_op() {+ // Empty string should not invoke any compressor.+ let (body, _) = body_with_tool_result("");+ let out = dispatch(&body);+ let manifest = match &out {+ LiveZoneOutcome::NoChange { manifest } => manifest,+ LiveZoneOutcome::Modified { .. } => panic!("empty content must not trigger compression"),+ };+ let action = manifest+ .block_outcomes+ .iter()+ .find(|b| b.block_type == "tool_result")+ .expect("tool_result block present")+ .action+ .clone();+ assert!(+ matches!(action, BlockAction::NoCompressionApplied { .. }),+ "expected NoCompressionApplied, got {action:?}"+ );+}++// ─── Cache-safety invariant ────────────────────────────────────────────++#[test]+fn byte_fidelity_outside_compressed_block() {+ // 50 KB of homogeneous JSON dicts — guaranteed SmartCrusher fodder.+ // This pins the central B3 acceptance criterion: bytes OUTSIDE+ // the rewritten block must hash byte-identical to the input.+ let array_of_dicts: Vec<Value> = (0..1500)+ .map(|i| {+ json!({+ "id": i,+ "kind": "row",+ "value": format!("repeat-{}", i % 5),+ "status": "ok",+ })+ })+ .collect();+ let payload = serde_json::to_string(&array_of_dicts).unwrap();+ assert!(payload.len() > 50_000, "payload should exceed 50 KB");++ let (body_in, content_range) = body_with_tool_result(&payload);+ let (block_start, block_end) = content_range;++ let out = dispatch(&body_in);+ let new_body = match &out {+ LiveZoneOutcome::Modified { new_body, .. } => new_body.get().as_bytes().to_vec(),+ LiveZoneOutcome::NoChange { manifest } => panic!(+ "expected Modified outcome on 50 KB SmartCrusher fodder; got NoChange. manifest: {manifest:?}"+ ),+ };++ // Prefix bytes (before the content slot) must be byte-identical.+ let in_prefix = &body_in[..block_start];+ let out_prefix = &new_body[..block_start];+ assert_eq!(+ sha256(in_prefix),+ sha256(out_prefix),+ "prefix bytes outside the compressed block must be byte-equal"+ );++ // Suffix length will differ by the compression delta, so locate+ // the suffix in the output by length: it's the trailing+ // (in.len() - block_end) bytes.+ let in_suffix_len = body_in.len() - block_end;+ let in_suffix = &body_in[block_end..];+ let out_suffix = &new_body[new_body.len() - in_suffix_len..];+ assert_eq!(+ sha256(in_suffix),+ sha256(out_suffix),+ "suffix bytes outside the compressed block must be byte-equal"+ );++ // 2× size reduction inside the block.+ let in_block = &body_in[block_start..block_end];+ let out_block_len = new_body.len() - block_start - in_suffix_len;+ assert!(+ out_block_len * 2 < in_block.len(),+ "expected >2× block size reduction; got {out_block_len} bytes (was {})",+ in_block.len()+ );++ // Output must be valid JSON.+ let parsed: Value = serde_json::from_slice(&new_body).expect("output is valid JSON");+ assert_eq!(parsed["model"], "claude-sonnet-4-6");+ assert_eq!(parsed["system"], "you are a helpful assistant");+}diff --git a/crates/headroom-proxy/src/compression/live_zone_anthropic.rs b/crates/headroom-proxy/src/compression/live_zone_anthropic.rsindex 4024d2146..31ecc5fb2 100644--- a/crates/headroom-proxy/src/compression/live_zone_anthropic.rs+++ b/crates/headroom-proxy/src/compression/live_zone_anthropic.rs@@ -1,5 +1,15 @@-//! Anthropic `/v1/messages` request compression — Phase B PR-B2-//! live-zone dispatcher entry point.+//! Anthropic `/v1/messages` request compression — live-zone+//! dispatcher entry point.+//!+//! # Provider scope+//!+//! This module is **Anthropic-only**. The proxy gates compression+//! on `path == "/v1/messages"` (see `compression::is_compressible_path`).+//! OpenAI Chat Completions, OpenAI Responses, and Google Gemini+//! each get their own sibling module in Phase C — they share+//! [`headroom_core::transforms::LiveZoneOutcome`] and the+//! per-content-type compressor backend, but the walkers are+//! provider-specific because the request shapes diverge.//!//! # Pipeline//!@@ -9,25 +19,29 @@//! the body is parsed at all — when disabled, floor=0 without//! inspection.//! 2. Hand the buffered body bytes to-//! [`headroom_core::transforms::compress_live_zone`]. The-//! dispatcher inspects the live zone (latest user message) and-//! dispatches per-block compression. PR-B2 wires every per-type-//! function to a no-op, so the dispatcher always returns-//! [`headroom_core::transforms::LiveZoneOutcome::NoChange`].-//! 3. Translate the result into [`Outcome`] for the proxy: every-//! PR-B2 call lands on [`Outcome::NoCompression`].+//! [`headroom_core::transforms::compress_anthropic_live_zone`].+//! The dispatcher inspects the live zone (latest user message),+//! detects per-block content type, dispatches each block to the+//! matching compressor (SmartCrusher / LogCompressor /+//! SearchCompressor / DiffCompressor), and rewrites the body+//! via byte-range surgery so unmodified bytes round-trip+//! byte-equal.+//! 3. Translate [`LiveZoneOutcome::Modified`] →+//! [`Outcome::Compressed`] (caller forwards the new body) or+//! [`LiveZoneOutcome::NoChange`] → [`Outcome::NoCompression`]+//! (caller forwards the original body verbatim).//!//! # Cache-safety invariant//!-//! The dispatcher does not mutate any byte in the request body for-//! PR-B2. The proxy's `proxy.rs` forwards the *original* buffered-//! bytes verbatim. Phase A's SHA-256 fixtures still pass: the-//! introduction of dispatching (vs. unconditional passthrough)-//! changes log lines but no upstream-bound bytes.+//! Bytes outside the rewritten block round-trip byte-equal. The+//! `byte_fidelity_outside_compressed_block` integration test in+//! `crates/headroom-core/tests/live_zone_dispatch.rs` pins the+//! SHA-256 prefix-and-suffix invariant in CI.use bytes::Bytes;use headroom_core::transforms::{- compress_live_zone, AuthMode, BlockAction, ExclusionReason, LiveZoneError, LiveZoneOutcome,+ compress_anthropic_live_zone, AuthMode, BlockAction, ExclusionReason, LiveZoneError,+ LiveZoneOutcome,};use crate::compression::resolve_frozen_count;@@ -139,10 +153,13 @@ pub fn compress_anthropic_request(let frozen_count = resolve_frozen_count(&parsed, cache_control_policy, request_id);- // Run the live-zone dispatcher. PR-B2: every block lands on a- // no-op compressor, so the result is always NoChange. PR-B3+- // begin returning Modified.- match compress_live_zone(body, frozen_count, AuthMode::Payg) {+ // Run the live-zone dispatcher. PR-B3 wires per-type compressors:+ // SmartCrusher / LogCompressor / SearchCompressor / DiffCompressor.+ // The dispatcher returns `Modified` whenever at least one block+ // was rewritten and `NoChange` otherwise (live zone empty, every+ // compressor declined, or every compressor produced output that+ // wasn't smaller than the input).+ match compress_anthropic_live_zone(body, frozen_count, AuthMode::Payg) {Ok(LiveZoneOutcome::NoChange { manifest }) => {let block_count = manifest.block_outcomes.len();let blocks_excluded = manifest@@ -163,7 +180,7 @@ pub fn compress_anthropic_request(method = "POST",compression_mode = mode.as_str(),decision = "no_change",- reason = "no_op_skeleton_pr_b2",+ reason = "no_block_compressed",body_bytes = body.len(),frozen_message_count = frozen_count,messages_total = manifest.messages_total,@@ -174,22 +191,62 @@ pub fn compress_anthropic_request();Outcome::NoCompression}- Ok(LiveZoneOutcome::Modified { .. }) => {- // PR-B3+ will reach this arm. We keep it in B2 only as- // a debug_assert so an accidental early Modified emission- // surfaces immediately rather than producing a body- // we're not yet prepared to forward.- debug_assert!(- false,- "PR-B2 dispatcher must never return LiveZoneOutcome::Modified"- );- tracing::warn!(+ Ok(LiveZoneOutcome::Modified { new_body, manifest }) => {+ // Aggregate manifest into the proxy's `Compressed` payload.+ // PR-B3 reports byte-counts (not token counts); PR-B4+ // upgrades the gate to a tokenizer-validated count and+ // updates these fields with the real numbers.+ let mut original_bytes_total: usize = 0;+ let mut compressed_bytes_total: usize = 0;+ let mut strategies: Vec<&'static str> = Vec::new();+ for entry in &manifest.block_outcomes {+ if let BlockAction::Compressed {+ strategy,+ original_bytes,+ compressed_bytes,+ } = entry.action+ {+ original_bytes_total += original_bytes;+ compressed_bytes_total += compressed_bytes;+ if !strategies.contains(&strategy) {+ strategies.push(strategy);+ }+ }+ }+ let body_bytes_in = body.len();+ let new_body_bytes = Bytes::copy_from_slice(new_body.get().as_bytes());+ let body_bytes_out = new_body_bytes.len();+ let block_count = manifest.block_outcomes.len();+ tracing::info!(request_id = %request_id,path = "/v1/messages",- "live-zone dispatcher emitted Modified outcome in PR-B2; \- falling back to original bytes (this is a regression)"+ method = "POST",+ compression_mode = mode.as_str(),+ decision = "compressed",+ reason = "live_zone_blocks_rewritten",+ body_bytes_in = body_bytes_in,+ body_bytes_out = body_bytes_out,+ bytes_freed = body_bytes_in.saturating_sub(body_bytes_out),+ frozen_message_count = frozen_count,+ messages_total = manifest.messages_total,+ latest_user_message_index = ?manifest.latest_user_message_index,+ live_zone_blocks = block_count,+ live_zone_strategies = ?strategies,+ live_zone_block_original_bytes = original_bytes_total,+ live_zone_block_compressed_bytes = compressed_bytes_total,+ "anthropic live-zone dispatch");- Outcome::NoCompression+ Outcome::Compressed {+ body: new_body_bytes,+ // PR-B4 will replace these with tokenizer counts.+ // For now report block-content byte counts so+ // observers can compute the savings ratio.+ tokens_before: original_bytes_total,+ tokens_after: compressed_bytes_total,+ strategies_applied: strategies,+ // PR-B7 wires CCR retrieval-marker injection.+ markers_inserted: Vec::new(),+ }}Err(LiveZoneError::BodyNotJson(_)) => {// We already parsed successfully above; the dispatcher'sdiff --git a/crates/headroom-proxy/tests/integration_compression.rs b/crates/headroom-proxy/tests/integration_compression.rsindex c7db777a8..7be09b9e4 100644--- a/crates/headroom-proxy/tests/integration_compression.rs+++ b/crates/headroom-proxy/tests/integration_compression.rs@@ -649,17 +649,18 @@ mod tracing_capture {let logs = String::from_utf8(buf.lock().unwrap().clone()).expect("logs are utf-8");- // PR-B2: live-zone dispatcher logs `decision="no_change"`- // with `reason="no_op_skeleton_pr_b2"` until PR-B3 wires- // per-type compressors. Pin the contract so a future- // refactor can't silently change the operator-facing log- // schema.+ // PR-B3: live-zone dispatcher logs `decision="no_change"`+ // with `reason="no_block_compressed"` when the live zone+ // had no compressible blocks (or every compressor declined+ // / produced larger output). The `decision="compressed"`+ // path is exercised by+ // `crates/headroom-core/tests/live_zone_dispatch.rs`.assert!(logs.contains(r#""decision":"no_change""#),"decision field missing or wrong; logs: {logs}",);assert!(- logs.contains(r#""reason":"no_op_skeleton_pr_b2""#),+ logs.contains(r#""reason":"no_block_compressed""#),"reason field missing or wrong; logs: {logs}",);assert!(