返回 CodeWhale
portable_tests.rs
根目录 / crates / commands / src / debug / portable_tests.rs
1 //! Facet-only checks for the portable diagnostics leaf closure.
2 //! No App, provider, file system or request builder is used by these tests.
3
4 use std::cell::RefCell;
5 use std::rc::Rc;
6
7 use codewhale_command_contract::facets::{
8 CommandDebugDiagnosticsContext, CommandPresentationContext, DebugBalanceProjection,
9 DebugCacheInspectionObservation, DebugCacheInspectionUnavailable, DebugCacheTelemetry,
10 DebugCostProjection, DebugPromptContext, DebugPromptInspection, DebugPromptSourceMap,
11 DebugSystemProjection, DebugSystemPrompt, DebugTokenProjection, DebugToolSnapshot,
12 DebugWarmupKey,
13 };
14 use codewhale_command_contract::handler::CommandContexts;
15
16 use super::{balance, cache, preview_request, tokens, tool_inspection};
17
18 #[derive(Default)]
19 struct FakeDiagnostics {
20 events: Rc<RefCell<Vec<&'static str>>>,
21 observation: Option<Result<DebugCacheInspectionObservation, DebugCacheInspectionUnavailable>>,
22 remembered: Option<DebugPromptInspection>,
23 balance_supported: bool,
24 system_prompt: Option<DebugSystemProjection>,
25 }
26
27 impl CommandDebugDiagnosticsContext for FakeDiagnostics {
28 fn balance_projection(&self) -> DebugBalanceProjection {
29 self.events.borrow_mut().push("balance");
30 DebugBalanceProjection {
31 provider_display_name: "Example Provider".into(),
32 supports_balance_api: self.balance_supported,
33 }
34 }
35 fn system_projection(&self) -> DebugSystemProjection {
36 self.system_prompt
37 .clone()
38 .expect("system authority is unrelated to cache inspection")
39 }
40 fn token_projection(&self) -> DebugTokenProjection {
41 panic!("usage authority is unrelated to cache inspection")
42 }
43 fn cost_projection(&self) -> DebugCostProjection {
44 panic!("cost authority is unrelated to cache inspection")
45 }
46 fn cache_telemetry(&self) -> DebugCacheTelemetry {
47 panic!("telemetry authority is unrelated to cache inspection")
48 }
49 fn context_source_map(&self) -> DebugPromptSourceMap {
50 panic!("context authority is unrelated to cache inspection")
51 }
52 fn prompt_context(&self) -> DebugPromptContext {
53 panic!("prompt authority is unrelated to cache inspection")
54 }
55 fn tool_snapshot(&self) -> Option<DebugToolSnapshot> {
56 self.events.borrow_mut().push("tool_snapshot");
57 None
58 }
59 fn inspect_cache(
60 &self,
61 ) -> Result<DebugCacheInspectionObservation, DebugCacheInspectionUnavailable> {
62 self.events.borrow_mut().push("inspect");
63 self.observation.clone().expect("configured inspection")
64 }
65 fn remember_cache_inspection(&mut self, inspection: DebugPromptInspection) {
66 self.events.borrow_mut().push("remember");
67 assert!(
68 self.remembered.replace(inspection).is_none(),
69 "remember exactly once"
70 );
71 }
72 }
73
74 struct FakePresentation;
75 impl CommandPresentationContext for FakePresentation {
76 fn translate(&self, _key: &str, _replacements: &[(&str, &str)]) -> Result<String, String> {
77 panic!("inspection and warmup do not need translation")
78 }
79 }
80
81 fn inspection(hash: &str) -> DebugPromptInspection {
82 DebugPromptInspection {
83 base_static_prefix_hash: hash.into(),
84 full_request_prefix_hash: format!("full-{hash}"),
85 tool_catalog_hash: String::new(),
86 layers: Vec::new(),
87 }
88 }
89
90 fn observation() -> DebugCacheInspectionObservation {
91 DebugCacheInspectionObservation {
92 current: inspection("current"),
93 previous: Some(inspection("previous")),
94 current_warmup_key: DebugWarmupKey {
95 provider: "test".into(),
96 model: "test-model".into(),
97 base_url: "https://invalid.example/v1".into(),
98 static_prefix_hash: "current".into(),
99 tool_catalog_hash: String::new(),
100 project_pack_hash: String::new(),
101 skills_hash: String::new(),
102 },
103 last_warmup_key: None,
104 current_warmup_hash_short: "current-key".into(),
105 last_warmup_hash_short: None,
106 }
107 }
108
109 fn cache_with(fake: &mut FakeDiagnostics, arg: Option<&str>) -> super::CommandResult {
110 let mut presentation = FakePresentation;
111 cache::cache(
112 CommandContexts::empty()
113 .with_debug_diagnostics(fake)
114 .with_presentation(&mut presentation),
115 arg,
116 )
117 }
118
119 #[test]
120 fn missing_diagnostics_facet_fails_before_any_action() {
121 for result in [
122 balance::balance(CommandContexts::empty()),
123 tokens::system_prompt(CommandContexts::empty()),
124 tokens::context(CommandContexts::empty(), None),
125 tool_inspection::tools(CommandContexts::empty(), Some("invalid")),
126 tokens::tokens(CommandContexts::empty()),
127 tokens::cost(CommandContexts::empty(), None),
128 cache::cache(CommandContexts::empty(), Some("warmup")),
129 ] {
130 assert!(result.is_error, "missing authority must be an error");
131 assert_eq!(
132 result.message.as_deref(),
133 Some("Error: Command capability unavailable: debug_diagnostics")
134 );
135 assert!(result.action.is_none());
136 }
137 let result = preview_request::preview_request(Some("--json --prompt keep trailing "));
138 assert!(
139 !result.is_error,
140 "pure preview never constructs a host bundle"
141 );
142 assert!(result.action.is_some());
143 }
144
145 #[test]
146 fn missing_presentation_is_not_an_implicit_host_fallback() {
147 let mut fake = FakeDiagnostics::default();
148 for result in [
149 tokens::tokens(CommandContexts::empty().with_debug_diagnostics(&mut fake)),
150 tokens::cost(
151 CommandContexts::empty().with_debug_diagnostics(&mut fake),
152 None,
153 ),
154 cache::cache(
155 CommandContexts::empty().with_debug_diagnostics(&mut fake),
156 Some("warmup"),
157 ),
158 ] {
159 assert!(result.is_error);
160 assert_eq!(
161 result.message.as_deref(),
162 Some("Error: Command capability unavailable: presentation")
163 );
164 assert!(result.action.is_none());
165 }
166 assert!(fake.events.borrow().is_empty());
167 }
168
169 #[test]
170 fn cache_inspection_rejections_and_argument_only_warmup_never_store() {
171 let mut fake = FakeDiagnostics::default();
172 let conflict = cache_with(&mut fake, Some("inspect --json --verbose"));
173 assert_eq!(
174 conflict.message.as_deref(),
175 Some("cache inspect: --json and --verbose cannot be combined")
176 );
177 assert!(fake.events.borrow().is_empty());
178 let warmup = cache_with(&mut fake, Some("warmup"));
179 assert!(warmup.action.is_some());
180 assert!(fake.events.borrow().is_empty());
181
182 for (failure, expected) in [
183 (
184 DebugCacheInspectionUnavailable::NoConcreteRoute,
185 "cache inspect: Auto has no concrete route yet; send a turn first",
186 ),
187 (
188 DebugCacheInspectionUnavailable::MissingCapturedEndpoint,
189 "cache inspect: the restored Auto route has no captured endpoint; send a turn first",
190 ),
191 ] {
192 fake.observation = Some(Err(failure));
193 let result = cache_with(&mut fake, Some("inspect --json"));
194 assert_eq!(result.message.as_deref(), Some(expected));
195 assert_eq!(fake.events.borrow().last().unwrap(), &"inspect");
196 assert!(
197 fake.remembered.is_none(),
198 "failure must preserve previous state"
199 );
200 }
201 }
202
203 #[test]
204 fn cache_observes_then_renders_then_stores_the_same_snapshot_once() {
205 let mut fake = FakeDiagnostics {
206 observation: Some(Ok(observation())),
207 ..FakeDiagnostics::default()
208 };
209 let result = cache_with(&mut fake, Some("inspect --json"));
210 let rendered: serde_json::Value =
211 serde_json::from_str(result.message.as_deref().unwrap()).unwrap();
212 assert_eq!(rendered["base_static_prefix_hash"], "current");
213 assert_eq!(rendered["current_warmup_key"]["model"], "test-model");
214 assert_eq!(
215 rendered["warmup_status"],
216 "Warmup status: no previous warmup (current key: current-key)"
217 );
218 assert_eq!(&*fake.events.borrow(), &["inspect", "remember"]);
219 assert_eq!(fake.remembered.as_ref(), Some(&inspection("current")));
220 }
221
222 #[test]
223 fn balance_and_tool_snapshot_branches_observe_only_their_declared_facts() {
224 let mut fake = FakeDiagnostics::default();
225 let unsupported = balance::balance(CommandContexts::empty().with_debug_diagnostics(&mut fake));
226 assert_eq!(
227 unsupported.message.as_deref(),
228 Some(
229 "Balance check is not supported for Example Provider yet. Check the provider dashboard for account balance details."
230 )
231 );
232 assert!(unsupported.action.is_none());
233 fake.balance_supported = true;
234 let supported = balance::balance(CommandContexts::empty().with_debug_diagnostics(&mut fake));
235 assert!(supported.message.is_none());
236 assert!(matches!(
237 supported.action,
238 Some(super::DebugAction::FetchBalance)
239 ));
240 let unavailable = tool_inspection::tools(
241 CommandContexts::empty().with_debug_diagnostics(&mut fake),
242 Some("yaml"),
243 );
244 assert_eq!(
245 unavailable.message.as_deref(),
246 Some(
247 "Tool request snapshot unavailable — no model request has been captured for the latest turn."
248 )
249 );
250 assert!(
251 !unavailable.is_error,
252 "availability precedes format validation"
253 );
254 assert_eq!(
255 &*fake.events.borrow(),
256 &["balance", "balance", "tool_snapshot"]
257 );
258 }
259
260 #[test]
261 fn json_serialization_fallback_still_commits_the_observed_inspection_once() {
262 // Real semantic inspection data cannot make serde_json fail. Inject only
263 // the serializer result, not a production callback or host state, then
264 // exercise the same fallback/commit helpers as the live command.
265 let output = cache::json_or_fallback(Err(serde_json::Error::io(std::io::Error::other(
266 "forced serializer failure",
267 ))));
268 assert_eq!(
269 output,
270 "{\"error\":\"cache inspection serialization failed\"}"
271 );
272 let mut fake = FakeDiagnostics::default();
273 let delivered = cache::commit_rendered_inspection(&mut fake, observation(), output);
274 assert_eq!(
275 delivered,
276 "{\"error\":\"cache inspection serialization failed\"}"
277 );
278 assert_eq!(&*fake.events.borrow(), &["remember"]);
279 assert_eq!(fake.remembered.as_ref(), Some(&inspection("current")));
280 }
281
282 #[test]
283 fn system_prompt_truncation_reports_char_count_for_multibyte_text() {
284 let mut fake = FakeDiagnostics {
285 system_prompt: Some(DebugSystemProjection {
286 mode_label: "Agent".into(),
287 prompt: DebugSystemPrompt::Text("你".repeat(300)),
288 }),
289 ..FakeDiagnostics::default()
290 };
291 let result = tokens::system_prompt(CommandContexts::empty().with_debug_diagnostics(&mut fake));
292 assert!(!result.is_error);
293 let message = result.message.as_deref().unwrap();
294 assert!(
295 message.contains("(truncated, 300 chars total)"),
296 "expected char count 300 in: {message}"
297 );
298 assert!(
299 !message.contains("900 chars total"),
300 "must not report UTF-8 byte length as chars: {message}"
301 );
302 }
303
303 lines RUST