| 1 | //! Prompt-bytes family: the model-visible prefix of a real first request. |
| 2 | //! |
| 3 | //! `docs/CACHE.md`: the system prompt and tool catalog are a session-pinned |
| 4 | //! KV-cache prefix, so a migration that moves any contributor (a tool adapter, |
| 5 | //! an MCP catalog, a slash command) must not change those bytes by accident. |
| 6 | //! Each case runs one real turn through the engine with the scripted provider |
| 7 | //! and captures the first `MessageRequest` — the exact prefix production would |
| 8 | //! send — then pins it three ways: |
| 9 | //! |
| 10 | //! - `<case>.golden.json`: sha256 of the system prompt, the tool catalog and |
| 11 | //! the combined prefix (bytes as serialized, key order included), sizes, and |
| 12 | //! the tool names in catalog order; |
| 13 | //! - `<case>.system.golden.txt`: the flat system prompt, readable in review; |
| 14 | //! - `<case>.tools.golden.json`: the tool catalog, readable in review. |
| 15 | //! |
| 16 | //! Masks are only the genuinely host-specific facts: temp paths, and the |
| 17 | //! environment block's platform and shell. The case pins the recorded host's |
| 18 | //! optional tools before the Engine projects its first request. |
| 19 | |
| 20 | use serde_json::{Value, json}; |
| 21 | |
| 22 | use super::events::run_scripted_turn; |
| 23 | use super::golden::{self, Failures, Sandbox}; |
| 24 | |
| 25 | const FAMILY: &str = "prompt"; |
| 26 | |
| 27 | fn default_script() -> Value { |
| 28 | json!([{ "events": [ |
| 29 | { "type": "message_start", "message": { |
| 30 | "id": "msg_prompt", "type": "message", "role": "assistant", "content": [], |
| 31 | "model": "conformance", "stop_reason": null, "stop_sequence": null, |
| 32 | "usage": { "input_tokens": 0, "output_tokens": 0 } } }, |
| 33 | { "type": "content_block_start", "index": 0, "content_block": { "type": "text", "text": "" } }, |
| 34 | { "type": "content_block_delta", "index": 0, "delta": { "type": "text_delta", "text": "ok" } }, |
| 35 | { "type": "content_block_stop", "index": 0 }, |
| 36 | { "type": "message_delta", "delta": { "stop_reason": "end_turn" } }, |
| 37 | { "type": "message_stop" } |
| 38 | ] }]) |
| 39 | } |
| 40 | |
| 41 | struct Prefix { |
| 42 | system_json: String, |
| 43 | system_flat: String, |
| 44 | system_blocks: usize, |
| 45 | tools: Vec<Value>, |
| 46 | } |
| 47 | |
| 48 | fn mask_host_lines(text: &str) -> String { |
| 49 | let platform = regex::Regex::new(r"(?m)^- platform: .*$").expect("platform regex"); |
| 50 | let shell = regex::Regex::new(r"(?m)^- shell: .*$").expect("shell regex"); |
| 51 | let text = platform.replace_all(text, "- platform: <PLATFORM>"); |
| 52 | shell.replace_all(&text, "- shell: <SHELL>").into_owned() |
| 53 | } |
| 54 | |
| 55 | /// Apply [`mask_host_lines`] inside every string of a JSON tree (the lines |
| 56 | /// live inside JSON strings, where serialization escapes their newlines). |
| 57 | fn mask_host_value(value: &mut Value) { |
| 58 | match value { |
| 59 | Value::String(text) => *text = mask_host_lines(text), |
| 60 | Value::Array(items) => items.iter_mut().for_each(mask_host_value), |
| 61 | Value::Object(map) => map.values_mut().for_each(mask_host_value), |
| 62 | _ => {} |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | fn capture_prefix(name: &str, case: &Value) -> Result<Prefix, String> { |
| 67 | let sandbox = Sandbox::new(case); |
| 68 | let script = case |
| 69 | .get("provider_script") |
| 70 | .cloned() |
| 71 | .unwrap_or_else(default_script); |
| 72 | let (record, provider) = run_scripted_turn(&sandbox, case, &script); |
| 73 | if let Some(error) = record.failure { |
| 74 | return Err(error); |
| 75 | } |
| 76 | let requests = provider.captured(); |
| 77 | let first = requests |
| 78 | .first() |
| 79 | .ok_or_else(|| format!("{name}: the engine sent no model request"))?; |
| 80 | let mut masker = sandbox.masker(&[]); |
| 81 | |
| 82 | let mut system = serde_json::to_value(&first.system).expect("system serializes"); |
| 83 | masker.value(&mut system); |
| 84 | mask_host_value(&mut system); |
| 85 | let system_json = serde_json::to_string(&system).expect("system json"); |
| 86 | let system_flat = first |
| 87 | .system |
| 88 | .as_ref() |
| 89 | .map(codewhale_engine::prompts::system_prompt_flat_text) |
| 90 | .unwrap_or_default(); |
| 91 | let system_flat = mask_host_lines(&masker.text(&system_flat)); |
| 92 | let system_blocks = match &first.system { |
| 93 | Some(codewhale_models::SystemPrompt::Blocks(blocks)) => blocks.len(), |
| 94 | Some(codewhale_models::SystemPrompt::Text(_)) => 1, |
| 95 | None => 0, |
| 96 | }; |
| 97 | if system_blocks == 0 { |
| 98 | return Err(format!("{name}: the captured system prefix is empty")); |
| 99 | } |
| 100 | |
| 101 | let mut tools = Vec::new(); |
| 102 | for tool in first.tools.iter().flatten() { |
| 103 | let mut value = serde_json::to_value(tool).expect("tool serializes"); |
| 104 | masker.value(&mut value); |
| 105 | mask_host_value(&mut value); |
| 106 | tools.push(value); |
| 107 | } |
| 108 | if tools.is_empty() { |
| 109 | return Err(format!("{name}: the captured tool catalog is empty")); |
| 110 | } |
| 111 | Ok(Prefix { |
| 112 | system_json, |
| 113 | system_flat, |
| 114 | system_blocks, |
| 115 | tools, |
| 116 | }) |
| 117 | } |
| 118 | |
| 119 | fn summary(prefix: &Prefix) -> Value { |
| 120 | let tools_json = serde_json::to_string(&prefix.tools).expect("tools json"); |
| 121 | let combined = format!("{}\n{}", prefix.system_json, tools_json); |
| 122 | json!({ |
| 123 | "system_sha256": codewhale_runtime::hashing::sha256_hex(prefix.system_json.as_bytes()), |
| 124 | "system_bytes": prefix.system_json.len(), |
| 125 | "system_blocks": prefix.system_blocks, |
| 126 | "tools_sha256": codewhale_runtime::hashing::sha256_hex(tools_json.as_bytes()), |
| 127 | "tools_bytes": tools_json.len(), |
| 128 | "tool_count": prefix.tools.len(), |
| 129 | "tool_names": prefix.tools.iter().map(|tool| tool["name"].clone()).collect::<Vec<_>>(), |
| 130 | "prefix_sha256": codewhale_runtime::hashing::sha256_hex(combined.as_bytes()), |
| 131 | "masks": ["<WORKSPACE>", "<HOME>", "<TMP>", "- platform: <PLATFORM>", "- shell: <SHELL>"], |
| 132 | }) |
| 133 | } |
| 134 | |
| 135 | #[test] |
| 136 | fn model_visible_prefix_bytes_match_goldens() { |
| 137 | let dir = golden::family_dir(FAMILY); |
| 138 | let names = golden::case_names(FAMILY); |
| 139 | let mut failures = Failures::default(); |
| 140 | for name in &names { |
| 141 | let case = golden::read_case(FAMILY, name); |
| 142 | let prefix = match capture_prefix(name, &case) { |
| 143 | Ok(prefix) => prefix, |
| 144 | Err(message) => { |
| 145 | failures.push(name, message); |
| 146 | continue; |
| 147 | } |
| 148 | }; |
| 149 | // A prefix that differs between two identical sessions is a cache |
| 150 | // bug in its own right (map iteration order, a clock, a counter). |
| 151 | match capture_prefix(name, &case) { |
| 152 | Ok(again) if again.system_json == prefix.system_json && again.tools == prefix.tools => { |
| 153 | } |
| 154 | Ok(_) => { |
| 155 | failures.push( |
| 156 | name, |
| 157 | "the prefix differs between two identical sessions in one process", |
| 158 | ); |
| 159 | continue; |
| 160 | } |
| 161 | Err(message) => { |
| 162 | failures.push(name, message); |
| 163 | continue; |
| 164 | } |
| 165 | } |
| 166 | failures.record( |
| 167 | name, |
| 168 | golden::check_golden( |
| 169 | &dir.join(format!("{name}.golden.json")), |
| 170 | &golden::pretty(&summary(&prefix)), |
| 171 | ), |
| 172 | ); |
| 173 | failures.record( |
| 174 | name, |
| 175 | golden::check_golden( |
| 176 | &dir.join(format!("{name}.system.golden.txt")), |
| 177 | &format!("{}\n", prefix.system_flat), |
| 178 | ), |
| 179 | ); |
| 180 | failures.record( |
| 181 | name, |
| 182 | golden::check_golden( |
| 183 | &dir.join(format!("{name}.tools.golden.json")), |
| 184 | &golden::pretty(&Value::Array(prefix.tools.clone())), |
| 185 | ), |
| 186 | ); |
| 187 | } |
| 188 | |
| 189 | failures.finish(FAMILY, names.len()); |
| 190 | } |
| 191 |