| 1 | use std::cell::RefCell; |
| 2 | use std::path::{Path, PathBuf}; |
| 3 | |
| 4 | use codewhale_protocol::request::{ContentBlock, Message, SystemPrompt}; |
| 5 | use codewhale_protocol::role::Role; |
| 6 | |
| 7 | use crate::*; |
| 8 | |
| 9 | struct Session; |
| 10 | impl CommandSessionContext for Session { |
| 11 | fn session_id(&self) -> Option<String> { |
| 12 | Some("session".into()) |
| 13 | } |
| 14 | fn api_messages(&self) -> Vec<Message> { |
| 15 | vec![] |
| 16 | } |
| 17 | fn add_message(&mut self, _message: Message) {} |
| 18 | fn queued_message_count(&self) -> usize { |
| 19 | 0 |
| 20 | } |
| 21 | fn remove_queued_message(&mut self, _index: usize) -> Result<(), String> { |
| 22 | Ok(()) |
| 23 | } |
| 24 | fn total_tokens(&self) -> u64 { |
| 25 | 42 |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | struct Model; |
| 30 | impl CommandModelContext for Model { |
| 31 | fn current_model(&self) -> String { |
| 32 | "auto".into() |
| 33 | } |
| 34 | fn auto_model(&self) -> bool { |
| 35 | true |
| 36 | } |
| 37 | fn set_model_selection(&mut self, _model: String, _provider: Option<CommandProviderId>) {} |
| 38 | fn provider_identity(&self) -> Option<CommandProviderId> { |
| 39 | None |
| 40 | } |
| 41 | fn fallback_chain(&self) -> Vec<CommandProviderId> { |
| 42 | vec![] |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | struct Cost; |
| 47 | impl CommandCostContext for Cost { |
| 48 | fn display_currency(&self) -> CommandCurrency { |
| 49 | CommandCurrency::Usd |
| 50 | } |
| 51 | fn session_cost_for_currency(&self, _currency: CommandCurrency) -> f64 { |
| 52 | 1.0 |
| 53 | } |
| 54 | fn subagent_cost_for_currency(&self, _currency: CommandCurrency) -> f64 { |
| 55 | 0.5 |
| 56 | } |
| 57 | fn accrue_cost_estimate(&mut self, _amount: f64, _currency: CommandCurrency) {} |
| 58 | fn record_turn_cost( |
| 59 | &mut self, |
| 60 | _amount: f64, |
| 61 | _currency: CommandCurrency, |
| 62 | _receipt: Option<String>, |
| 63 | ) { |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | struct Policy; |
| 68 | impl CommandModePolicyContext for Policy { |
| 69 | fn mode(&self) -> CommandMode { |
| 70 | CommandMode::Plan |
| 71 | } |
| 72 | fn set_mode(&mut self, _mode: CommandMode) {} |
| 73 | fn approval_mode(&self) -> CommandApprovalMode { |
| 74 | CommandApprovalMode::Suggest |
| 75 | } |
| 76 | fn allow_shell(&self) -> bool { |
| 77 | false |
| 78 | } |
| 79 | fn set_shell_access(&mut self, _allow: bool) {} |
| 80 | fn policy_locked(&self) -> bool { |
| 81 | false |
| 82 | } |
| 83 | fn select_mode(&mut self, _mode: CommandMode) -> crate::facets::CommandModeSelection { |
| 84 | crate::facets::CommandModeSelection::Changed |
| 85 | } |
| 86 | fn mode_startup_default_receipt(&self, _mode: CommandMode) -> String { |
| 87 | String::new() |
| 88 | } |
| 89 | fn setting_locked_mode_message(&self) -> String { |
| 90 | String::new() |
| 91 | } |
| 92 | fn mode_label(&self, mode: CommandMode) -> String { |
| 93 | format!("{mode:?}") |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | struct Prompt; |
| 98 | impl CommandSystemPromptContext for Prompt { |
| 99 | fn system_prompt(&self) -> Option<SystemPrompt> { |
| 100 | None |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | struct Skills; |
| 105 | impl CommandSkillsContext for Skills { |
| 106 | fn active_skill(&self) -> Option<String> { |
| 107 | None |
| 108 | } |
| 109 | fn active_skill_provenance(&self) -> Option<String> { |
| 110 | None |
| 111 | } |
| 112 | fn refresh_skill_cache(&mut self) {} |
| 113 | } |
| 114 | |
| 115 | struct Workspace; |
| 116 | impl CommandWorkspaceContext for Workspace { |
| 117 | fn effective_home_dir(&self) -> Option<std::path::PathBuf> { |
| 118 | unreachable!("navigation is not used by this fixture") |
| 119 | } |
| 120 | fn inspect_workspace_target(&self, _: &std::path::Path) -> crate::navigation::WorkspaceTarget { |
| 121 | unreachable!("navigation is not used by this fixture") |
| 122 | } |
| 123 | fn read_anchor_document(&self) -> Result<Option<String>, String> { |
| 124 | unreachable!("anchors are not used by this fixture") |
| 125 | } |
| 126 | fn append_anchor_bytes( |
| 127 | &mut self, |
| 128 | _: &[&[u8]], |
| 129 | ) -> Result<std::path::PathBuf, crate::navigation::AnchorWriteError> { |
| 130 | unreachable!("anchors are not used by this fixture") |
| 131 | } |
| 132 | fn replace_anchor_document(&mut self, _: &[u8]) -> Result<(), String> { |
| 133 | unreachable!("anchors are not used by this fixture") |
| 134 | } |
| 135 | fn workspace(&self) -> PathBuf { |
| 136 | PathBuf::from(".") |
| 137 | } |
| 138 | fn work_state_snapshot(&self) -> Result<Option<String>, String> { |
| 139 | Ok(None) |
| 140 | } |
| 141 | fn operation_digest(&mut self) -> Result<String, String> { |
| 142 | Ok("No active operations or to-do items.".to_string()) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | #[test] |
| 147 | fn all_seven_shapes_are_object_safe() { |
| 148 | fn session(_: &dyn CommandSessionContext) {} |
| 149 | fn model(_: &dyn CommandModelContext) {} |
| 150 | fn cost(_: &dyn CommandCostContext) {} |
| 151 | fn policy(_: &dyn CommandModePolicyContext) {} |
| 152 | fn prompt(_: &dyn CommandSystemPromptContext) {} |
| 153 | fn skills(_: &dyn CommandSkillsContext) {} |
| 154 | fn workspace(_: &dyn CommandWorkspaceContext) {} |
| 155 | |
| 156 | session(&Session); |
| 157 | model(&Model); |
| 158 | cost(&Cost); |
| 159 | policy(&Policy); |
| 160 | prompt(&Prompt); |
| 161 | skills(&Skills); |
| 162 | workspace(&Workspace); |
| 163 | } |
| 164 | |
| 165 | #[test] |
| 166 | fn envelope_carries_independent_facets() { |
| 167 | let mut session = Session; |
| 168 | let mut model = Model; |
| 169 | let parts = CommandContexts::empty() |
| 170 | .with_session(&mut session) |
| 171 | .with_model(&mut model) |
| 172 | .into_parts(); |
| 173 | assert_eq!(parts.session.expect("session").total_tokens(), 42); |
| 174 | assert!(parts.model.expect("model").auto_model()); |
| 175 | assert!(parts.cost.is_none()); |
| 176 | } |
| 177 | |
| 178 | struct DebugDiagnostics; |
| 179 | impl CommandDebugDiagnosticsContext for DebugDiagnostics { |
| 180 | fn balance_projection(&self) -> DebugBalanceProjection { |
| 181 | DebugBalanceProjection { |
| 182 | provider_display_name: "Example".into(), |
| 183 | supports_balance_api: false, |
| 184 | } |
| 185 | } |
| 186 | fn system_projection(&self) -> DebugSystemProjection { |
| 187 | DebugSystemProjection { |
| 188 | mode_label: "plan".into(), |
| 189 | prompt: DebugSystemPrompt::Blocks(vec!["first".into(), "second".into()]), |
| 190 | } |
| 191 | } |
| 192 | fn token_projection(&self) -> DebugTokenProjection { |
| 193 | DebugTokenProjection { |
| 194 | active_context_used: 0, |
| 195 | context_window: 8192, |
| 196 | last_input: None, |
| 197 | last_output: Some(0), |
| 198 | cache_hit: None, |
| 199 | cache_miss: Some(0), |
| 200 | total_tokens: 0, |
| 201 | cache_write_tokens: 0, |
| 202 | api_message_count: 0, |
| 203 | chat_message_count: 0, |
| 204 | model: "example".into(), |
| 205 | cost: self.cost_projection(), |
| 206 | } |
| 207 | } |
| 208 | fn cost_projection(&self) -> DebugCostProjection { |
| 209 | DebugCostProjection { |
| 210 | currency: CommandCurrency::Usd, |
| 211 | total: 0.0, |
| 212 | parent_turns: 0.0, |
| 213 | subagents: 0.0, |
| 214 | display_floor: 0.0, |
| 215 | priced_turns: 0, |
| 216 | unpriced_turns: 0, |
| 217 | legacy_coverage_unknown: false, |
| 218 | user_declared_estimates: false, |
| 219 | itemized_turns: 0, |
| 220 | route_amounts: vec![], |
| 221 | turn_history_capacity: 10, |
| 222 | unpriced_reason_labels: vec![], |
| 223 | unpriced_classes: vec![], |
| 224 | pricing_provenances: vec![], |
| 225 | live_pricing_defects: vec![], |
| 226 | unusable_pricing_defects: vec![], |
| 227 | route_receipts: vec![], |
| 228 | } |
| 229 | } |
| 230 | fn cache_telemetry(&self) -> DebugCacheTelemetry { |
| 231 | DebugCacheTelemetry { |
| 232 | model: "example".into(), |
| 233 | session_cache_rates: DebugCacheRates::default(), |
| 234 | history: vec![], |
| 235 | calls: vec![], |
| 236 | calls_total: 0, |
| 237 | calls_currency: CommandCurrency::Usd, |
| 238 | calls_legacy_coverage_unknown: false, |
| 239 | history_capacity: 50, |
| 240 | prefix_stability_pct: None, |
| 241 | prefix_checks_total: 0, |
| 242 | prefix_change_count: 0, |
| 243 | prefix_drift_count: 0, |
| 244 | prefix_context_updates: 0, |
| 245 | prefix_pin_reason: None, |
| 246 | prefix_last_miss_reason: None, |
| 247 | last_prefix_change_desc: None, |
| 248 | last_pinned_prefix_hash: None, |
| 249 | api_message_count: 0, |
| 250 | non_system_message_count: 0, |
| 251 | } |
| 252 | } |
| 253 | fn context_source_map(&self) -> DebugPromptSourceMap { |
| 254 | DebugPromptSourceMap { |
| 255 | entries: vec![], |
| 256 | total_estimated_tokens: 0, |
| 257 | active_context_estimated_tokens: 0, |
| 258 | overflow_guard_estimated_tokens: None, |
| 259 | context_window_tokens: None, |
| 260 | context_window_source: None, |
| 261 | budget_used_percent: None, |
| 262 | pressure_label: "unknown".into(), |
| 263 | context_window_verified: false, |
| 264 | generated_at: "2026-01-01T00:00:00Z".into(), |
| 265 | note: String::new(), |
| 266 | } |
| 267 | } |
| 268 | fn prompt_context(&self) -> DebugPromptContext { |
| 269 | DebugPromptContext { |
| 270 | schema_version: 1, |
| 271 | provider: "example".into(), |
| 272 | model: "model".into(), |
| 273 | system_prompt_state: "unknown".into(), |
| 274 | tool_catalog_state: "absent".into(), |
| 275 | sections: vec![], |
| 276 | tools: vec![], |
| 277 | source_map: self.context_source_map(), |
| 278 | } |
| 279 | } |
| 280 | fn tool_snapshot(&self) -> Option<DebugToolSnapshot> { |
| 281 | None |
| 282 | } |
| 283 | fn inspect_cache( |
| 284 | &self, |
| 285 | ) -> Result<DebugCacheInspectionObservation, DebugCacheInspectionUnavailable> { |
| 286 | Err(DebugCacheInspectionUnavailable::NoConcreteRoute) |
| 287 | } |
| 288 | fn remember_cache_inspection(&mut self, _inspection: DebugPromptInspection) {} |
| 289 | } |
| 290 | |
| 291 | #[test] |
| 292 | fn debug_inspection_schema_preserves_order_and_absence() { |
| 293 | let inspection = DebugPromptInspection { |
| 294 | base_static_prefix_hash: "base".into(), |
| 295 | full_request_prefix_hash: "full".into(), |
| 296 | tool_catalog_hash: "".into(), |
| 297 | layers: vec![DebugPromptLayer { |
| 298 | name: "history".into(), |
| 299 | stability: DebugPromptLayerStability::History, |
| 300 | char_len: 0, |
| 301 | byte_len: 0, |
| 302 | token_estimate: 0, |
| 303 | sha256: "digest".into(), |
| 304 | tool_result: None, |
| 305 | turn_meta: None, |
| 306 | }], |
| 307 | }; |
| 308 | assert_eq!( |
| 309 | serde_json::to_string(&inspection).expect("structured inspection"), |
| 310 | r#"{"base_static_prefix_hash":"base","full_request_prefix_hash":"full","tool_catalog_hash":"","layers":[{"name":"history","stability":"History","char_len":0,"byte_len":0,"token_estimate":0,"sha256":"digest","tool_result":null,"turn_meta":null}]}"#, |
| 311 | ); |
| 312 | assert_eq!(DebugPromptLayerStability::Static.label(), "static"); |
| 313 | assert_eq!(DebugPromptLayerStability::Dynamic.label(), "dynamic"); |
| 314 | assert_ne!( |
| 315 | DebugCacheInspectionUnavailable::NoConcreteRoute, |
| 316 | DebugCacheInspectionUnavailable::MissingCapturedEndpoint, |
| 317 | ); |
| 318 | let key = DebugWarmupKey { |
| 319 | provider: "provider".into(), |
| 320 | model: "model".into(), |
| 321 | base_url: "local".into(), |
| 322 | static_prefix_hash: "static".into(), |
| 323 | tool_catalog_hash: "".into(), |
| 324 | project_pack_hash: "".into(), |
| 325 | skills_hash: "".into(), |
| 326 | }; |
| 327 | assert_eq!( |
| 328 | serde_json::to_string(&key).expect("structured key"), |
| 329 | r#"{"provider":"provider","model":"model","base_url":"local","static_prefix_hash":"static","tool_catalog_hash":"","project_pack_hash":"","skills_hash":""}"#, |
| 330 | ); |
| 331 | assert_eq!( |
| 332 | DebugDiagnostics.inspect_cache(), |
| 333 | Err(DebugCacheInspectionUnavailable::NoConcreteRoute) |
| 334 | ); |
| 335 | } |
| 336 | |
| 337 | #[test] |
| 338 | fn debug_context_schema_preserves_explicit_nulls_and_omits_optional_tool_fields() { |
| 339 | let mut context = DebugDiagnostics.prompt_context(); |
| 340 | context.tools.push(DebugPromptTool { |
| 341 | tool_type: None, |
| 342 | name: "search".into(), |
| 343 | description: "Search".into(), |
| 344 | input_schema: serde_json::json!({"type": "object"}), |
| 345 | allowed_callers: None, |
| 346 | defer_loading: Some(false), |
| 347 | input_examples: None, |
| 348 | strict: None, |
| 349 | cache_control: None, |
| 350 | }); |
| 351 | let value = serde_json::to_value(&context).expect("semantic prompt context"); |
| 352 | assert_eq!( |
| 353 | value["source_map"]["context_window_tokens"], |
| 354 | serde_json::Value::Null |
| 355 | ); |
| 356 | assert_eq!(value["system_prompt_state"], "unknown"); |
| 357 | assert_eq!(value["tool_catalog_state"], "absent"); |
| 358 | assert_eq!(value["tools"][0]["defer_loading"], false); |
| 359 | assert!(value["tools"][0].get("type").is_none()); |
| 360 | assert!(value["tools"][0].get("input_examples").is_none()); |
| 361 | assert_eq!( |
| 362 | serde_json::to_value(DebugSourceKind::ProjectContextWarning).unwrap(), |
| 363 | "project_context_warning" |
| 364 | ); |
| 365 | assert_eq!( |
| 366 | serde_json::to_value(DebugActivationReason::PerRequest).unwrap(), |
| 367 | "per_request" |
| 368 | ); |
| 369 | } |
| 370 | |
| 371 | #[test] |
| 372 | fn debug_tool_schema_keeps_unknown_distinct_from_known_empty() { |
| 373 | let unknown: DebugEvidence<DebugBoundedList> = DebugEvidence::Unknown { |
| 374 | reason: "no surface".into(), |
| 375 | }; |
| 376 | let empty = DebugEvidence::Known { |
| 377 | value: DebugBoundedList { |
| 378 | count: 0, |
| 379 | rendered: vec![], |
| 380 | omitted: 0, |
| 381 | }, |
| 382 | }; |
| 383 | assert_eq!( |
| 384 | serde_json::to_value(unknown).unwrap(), |
| 385 | serde_json::json!({"status":"unknown", "reason":"no surface"}), |
| 386 | ); |
| 387 | assert_eq!( |
| 388 | serde_json::to_value(empty).unwrap(), |
| 389 | serde_json::json!({"status":"known", "value":{"count":0,"rendered":[],"omitted":0}}), |
| 390 | ); |
| 391 | assert_eq!( |
| 392 | serde_json::to_value(DebugProviderAvailability::Unknown).unwrap(), |
| 393 | serde_json::json!({"status":"unknown"}), |
| 394 | ); |
| 395 | assert_eq!( |
| 396 | serde_json::to_value(DebugToolVisibility::InRequest).unwrap(), |
| 397 | "in_request" |
| 398 | ); |
| 399 | } |
| 400 | |
| 401 | #[test] |
| 402 | fn debug_tool_snapshot_schema_preserves_unobserved_and_absent_states() { |
| 403 | let snapshot = DebugToolSnapshot { |
| 404 | schema_version: 1, |
| 405 | capture_source: "prepared model-client request".into(), |
| 406 | delivery_status: "unknown (capture does not prove provider delivery)".into(), |
| 407 | turn_id: DebugBoundedString { |
| 408 | value: "turn".into(), |
| 409 | truncated: false, |
| 410 | }, |
| 411 | step: 0, |
| 412 | terminal: None, |
| 413 | tools_field_present: false, |
| 414 | tool_count: 0, |
| 415 | rendered_tool_count: 0, |
| 416 | omitted_tool_count: 0, |
| 417 | payload_json_bytes: None, |
| 418 | payload_measurement_status: "unavailable".into(), |
| 419 | active_tool_catalog_sha256: None, |
| 420 | unavailable_for_this_request: vec!["provider_wire_payload".into()], |
| 421 | provider: DebugProviderAvailability::Unknown, |
| 422 | registry_facts_present: false, |
| 423 | registry_tool_count: DebugEvidence::Unknown { |
| 424 | reason: "not captured".into(), |
| 425 | }, |
| 426 | registry_only_tools: DebugEvidence::Unknown { |
| 427 | reason: "not captured".into(), |
| 428 | }, |
| 429 | tools: vec![], |
| 430 | }; |
| 431 | let value = serde_json::to_value(&snapshot).expect("bounded snapshot"); |
| 432 | assert!( |
| 433 | value.get("terminal").is_none(), |
| 434 | "absent terminal is omitted" |
| 435 | ); |
| 436 | assert!( |
| 437 | value["payload_json_bytes"].is_null(), |
| 438 | "unmeasured is not zero" |
| 439 | ); |
| 440 | assert!(value["active_tool_catalog_sha256"].is_null()); |
| 441 | assert_eq!(value["registry_tool_count"]["status"], "unknown"); |
| 442 | assert_eq!(value["provider"]["status"], "unknown"); |
| 443 | assert_eq!( |
| 444 | value["unavailable_for_this_request"], |
| 445 | serde_json::json!(["provider_wire_payload"]) |
| 446 | ); |
| 447 | assert_eq!(snapshot.tools, vec![]); |
| 448 | } |
| 449 | |
| 450 | #[test] |
| 451 | fn debug_cache_observation_keeps_current_and_previous_distinct() { |
| 452 | let previous = DebugPromptInspection { |
| 453 | base_static_prefix_hash: "before".into(), |
| 454 | full_request_prefix_hash: "before".into(), |
| 455 | tool_catalog_hash: "".into(), |
| 456 | layers: vec![], |
| 457 | }; |
| 458 | let mut current = previous.clone(); |
| 459 | current.base_static_prefix_hash = "after".into(); |
| 460 | let observation = DebugCacheInspectionObservation { |
| 461 | current: current.clone(), |
| 462 | previous: Some(previous), |
| 463 | current_warmup_key: DebugWarmupKey { |
| 464 | provider: "provider".into(), |
| 465 | model: "model".into(), |
| 466 | base_url: "endpoint".into(), |
| 467 | static_prefix_hash: "after".into(), |
| 468 | tool_catalog_hash: "".into(), |
| 469 | project_pack_hash: "".into(), |
| 470 | skills_hash: "".into(), |
| 471 | }, |
| 472 | last_warmup_key: None, |
| 473 | current_warmup_hash_short: "digest".into(), |
| 474 | last_warmup_hash_short: None, |
| 475 | }; |
| 476 | assert_eq!( |
| 477 | observation |
| 478 | .previous |
| 479 | .as_ref() |
| 480 | .unwrap() |
| 481 | .base_static_prefix_hash, |
| 482 | "before" |
| 483 | ); |
| 484 | assert_eq!(observation.current.base_static_prefix_hash, "after"); |
| 485 | assert_ne!(observation.previous.as_ref(), Some(&observation.current)); |
| 486 | // Contract data alone cannot prove a host write; Phase 3 adapter tests |
| 487 | // must assert that the synchronous post-render commit stores `current`. |
| 488 | } |
| 489 | |
| 490 | #[test] |
| 491 | fn debug_diagnostics_facet_is_object_safe_and_independently_transportable() { |
| 492 | fn object_safe(_: &dyn CommandDebugDiagnosticsContext) {} |
| 493 | object_safe(&DebugDiagnostics); |
| 494 | |
| 495 | let mut diagnostics = DebugDiagnostics; |
| 496 | let parts = CommandContexts::empty() |
| 497 | .with_debug_diagnostics(&mut diagnostics) |
| 498 | .into_parts(); |
| 499 | assert_eq!( |
| 500 | parts |
| 501 | .debug_diagnostics |
| 502 | .expect("declared diagnostics facet") |
| 503 | .balance_projection(), |
| 504 | DebugBalanceProjection { |
| 505 | provider_display_name: "Example".into(), |
| 506 | supports_balance_api: false, |
| 507 | } |
| 508 | ); |
| 509 | assert_eq!( |
| 510 | DebugDiagnostics.system_projection(), |
| 511 | DebugSystemProjection { |
| 512 | mode_label: "plan".into(), |
| 513 | prompt: DebugSystemPrompt::Blocks(vec!["first".into(), "second".into()]), |
| 514 | } |
| 515 | ); |
| 516 | assert_ne!( |
| 517 | DebugSystemPrompt::None, |
| 518 | DebugSystemPrompt::Text(String::new()) |
| 519 | ); |
| 520 | assert_ne!(DebugSystemPrompt::Blocks(vec![]), DebugSystemPrompt::None); |
| 521 | let usage = DebugDiagnostics.token_projection(); |
| 522 | assert_eq!( |
| 523 | DebugDiagnostics.cache_telemetry().prefix_stability_pct, |
| 524 | None |
| 525 | ); |
| 526 | assert_eq!( |
| 527 | DebugDiagnostics.prompt_context().tool_catalog_state, |
| 528 | "absent" |
| 529 | ); |
| 530 | assert!(DebugDiagnostics.tool_snapshot().is_none()); |
| 531 | assert_eq!(usage.last_input, None); |
| 532 | assert_eq!(usage.last_output, Some(0)); |
| 533 | assert_eq!(usage.cache_miss, Some(0)); |
| 534 | assert_eq!(usage.cost, DebugDiagnostics.cost_projection()); |
| 535 | for absent in [ |
| 536 | parts.session.is_none(), |
| 537 | parts.model.is_none(), |
| 538 | parts.cost.is_none(), |
| 539 | parts.mode_policy.is_none(), |
| 540 | parts.system_prompt.is_none(), |
| 541 | parts.skills.is_none(), |
| 542 | parts.workspace.is_none(), |
| 543 | parts.presentation.is_none(), |
| 544 | parts.media.is_none(), |
| 545 | parts.memory.is_none(), |
| 546 | parts.project.is_none(), |
| 547 | parts.skill_group.is_none(), |
| 548 | parts.plugin.is_none(), |
| 549 | parts.lifecycle.is_none(), |
| 550 | parts.control.is_none(), |
| 551 | parts.export.is_none(), |
| 552 | ] { |
| 553 | assert!(absent, "diagnostics must not expose another facet"); |
| 554 | } |
| 555 | assert!( |
| 556 | CommandContexts::empty() |
| 557 | .into_parts() |
| 558 | .debug_diagnostics |
| 559 | .is_none() |
| 560 | ); |
| 561 | } |
| 562 | |
| 563 | #[test] |
| 564 | #[should_panic(expected = "debug diagnostics facet already set")] |
| 565 | fn debug_diagnostics_envelope_rejects_duplicate_authority() { |
| 566 | let mut first = DebugDiagnostics; |
| 567 | let mut second = DebugDiagnostics; |
| 568 | let _ = CommandContexts::empty() |
| 569 | .with_debug_diagnostics(&mut first) |
| 570 | .with_debug_diagnostics(&mut second); |
| 571 | } |
| 572 | |
| 573 | fn pure(value: Option<&str>) -> String { |
| 574 | value.unwrap_or_default().to_owned() |
| 575 | } |
| 576 | fn contextual(_contexts: CommandContexts<'_>, value: Option<&str>) -> String { |
| 577 | value.unwrap_or_default().to_owned() |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn handlers_are_plain_function_pointers() { |
| 582 | let pure_handler = CommandHandler::Pure(pure); |
| 583 | let contextual_handler = CommandHandler::Contextual { |
| 584 | capabilities: CommandCapabilities::NONE, |
| 585 | handler: contextual, |
| 586 | }; |
| 587 | match pure_handler { |
| 588 | CommandHandler::Pure(handler) => assert_eq!(handler(Some("x")), "x"), |
| 589 | _ => unreachable!(), |
| 590 | } |
| 591 | match contextual_handler { |
| 592 | CommandHandler::Contextual { |
| 593 | capabilities, |
| 594 | handler, |
| 595 | } => { |
| 596 | assert!(capabilities.is_empty()); |
| 597 | assert_eq!(handler(CommandContexts::empty(), Some("y")), "y") |
| 598 | } |
| 599 | _ => unreachable!(), |
| 600 | } |
| 601 | } |
| 602 | |
| 603 | struct Sample; |
| 604 | impl RegisterCommand<String> for Sample { |
| 605 | fn info() -> &'static CommandInfo { |
| 606 | static INFO: CommandInfo = CommandInfo { |
| 607 | name: "sample", |
| 608 | aliases: &["s"], |
| 609 | usage: "/sample", |
| 610 | description_key: "command.sample", |
| 611 | }; |
| 612 | &INFO |
| 613 | } |
| 614 | fn handler() -> CommandHandler<String> { |
| 615 | CommandHandler::Pure(pure) |
| 616 | } |
| 617 | } |
| 618 | |
| 619 | #[test] |
| 620 | fn registration_shape_has_no_app_dependency() { |
| 621 | assert_eq!(Sample::info().name, "sample"); |
| 622 | assert!(matches!(Sample::handler(), CommandHandler::Pure(_))); |
| 623 | } |
| 624 | |
| 625 | // --------------------------------------------------------------------------- |
| 626 | // FEAT-018: presentation, media, and digest capabilities (D2-D5) |
| 627 | // --------------------------------------------------------------------------- |
| 628 | |
| 629 | struct Presentation; |
| 630 | impl CommandPresentationContext for Presentation { |
| 631 | fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> { |
| 632 | if key == "automation_usage" { |
| 633 | return Ok("Usage: /automation [list|show <id>]".to_string()); |
| 634 | } |
| 635 | if key == "mcp_recommended_unknown_id" { |
| 636 | let command = replacements |
| 637 | .iter() |
| 638 | .find(|(name, _)| *name == "recommendations_command") |
| 639 | .map(|(_, value)| *value) |
| 640 | .unwrap_or("/mcp recommendations"); |
| 641 | return Ok(format!("Unknown recommended MCP ID (try {command})")); |
| 642 | } |
| 643 | // D3: unknown keys fail safely without echoing the raw lookup key. |
| 644 | Err("unknown translation key".to_string()) |
| 645 | } |
| 646 | } |
| 647 | |
| 648 | struct Media; |
| 649 | impl CommandMediaContext for Media { |
| 650 | fn attach_media(&mut self, path: &Path) -> Result<MediaAttachmentReceipt, String> { |
| 651 | if path.extension().and_then(|ext| ext.to_str()) == Some("png") { |
| 652 | Ok(MediaAttachmentReceipt { |
| 653 | kind: "image".to_string(), |
| 654 | path: path.to_path_buf(), |
| 655 | }) |
| 656 | } else { |
| 657 | Err("Unsupported attachment type".to_string()) |
| 658 | } |
| 659 | } |
| 660 | } |
| 661 | |
| 662 | struct DigestWorkspace; |
| 663 | impl CommandWorkspaceContext for DigestWorkspace { |
| 664 | fn effective_home_dir(&self) -> Option<std::path::PathBuf> { |
| 665 | unreachable!("navigation is not used by digest") |
| 666 | } |
| 667 | fn inspect_workspace_target(&self, _: &std::path::Path) -> crate::navigation::WorkspaceTarget { |
| 668 | unreachable!("navigation is not used by digest") |
| 669 | } |
| 670 | fn read_anchor_document(&self) -> Result<Option<String>, String> { |
| 671 | unreachable!("anchors are not used by digest") |
| 672 | } |
| 673 | fn append_anchor_bytes( |
| 674 | &mut self, |
| 675 | _: &[&[u8]], |
| 676 | ) -> Result<std::path::PathBuf, crate::navigation::AnchorWriteError> { |
| 677 | unreachable!("anchors are not used by digest") |
| 678 | } |
| 679 | fn replace_anchor_document(&mut self, _: &[u8]) -> Result<(), String> { |
| 680 | unreachable!("anchors are not used by digest") |
| 681 | } |
| 682 | fn workspace(&self) -> PathBuf { |
| 683 | PathBuf::from(".") |
| 684 | } |
| 685 | fn work_state_snapshot(&self) -> Result<Option<String>, String> { |
| 686 | Ok(None) |
| 687 | } |
| 688 | fn operation_digest(&mut self) -> Result<String, String> { |
| 689 | Ok("No active operations or to-do items.".to_string()) |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | #[test] |
| 694 | fn new_capabilities_are_object_safe_and_independently_transportable() { |
| 695 | fn presentation(_: &dyn CommandPresentationContext) {} |
| 696 | fn media(_: &dyn CommandMediaContext) {} |
| 697 | fn digest_workspace(_: &dyn CommandWorkspaceContext) {} |
| 698 | |
| 699 | presentation(&Presentation); |
| 700 | media(&Media); |
| 701 | digest_workspace(&DigestWorkspace); |
| 702 | fn export(_: &dyn CommandSessionExportContext) {} |
| 703 | export(&FakeExport::default()); |
| 704 | |
| 705 | let mut presentation = Presentation; |
| 706 | let mut media = Media; |
| 707 | let mut export = FakeExport::default(); |
| 708 | let parts = CommandContexts::empty() |
| 709 | .with_presentation(&mut presentation) |
| 710 | .with_media(&mut media) |
| 711 | .with_export(&mut export) |
| 712 | .into_parts(); |
| 713 | assert!(parts.presentation.is_some()); |
| 714 | assert!(parts.media.is_some()); |
| 715 | assert!(parts.export.is_some()); |
| 716 | assert!(parts.session.is_none()); |
| 717 | } |
| 718 | |
| 719 | #[test] |
| 720 | fn translation_contract_resolves_known_keys_and_fails_safely() { |
| 721 | let presentation = Presentation; |
| 722 | assert_eq!( |
| 723 | presentation |
| 724 | .translate("automation_usage", &[]) |
| 725 | .expect("known key"), |
| 726 | "Usage: /automation [list|show <id>]" |
| 727 | ); |
| 728 | assert_eq!( |
| 729 | presentation |
| 730 | .translate( |
| 731 | "mcp_recommended_unknown_id", |
| 732 | &[("recommendations_command", "/mcp recommendations")], |
| 733 | ) |
| 734 | .expect("known key with named replacement"), |
| 735 | "Unknown recommended MCP ID (try /mcp recommendations)" |
| 736 | ); |
| 737 | let unknown = presentation.translate("no_such_key", &[]); |
| 738 | assert!(unknown.is_err(), "unknown key must fail safely"); |
| 739 | let err = unknown.unwrap_err(); |
| 740 | assert!( |
| 741 | !err.contains("no_such_key"), |
| 742 | "no raw lookup key exposure (D3)" |
| 743 | ); |
| 744 | } |
| 745 | |
| 746 | #[test] |
| 747 | fn media_contract_is_atomic_and_returns_only_portable_data() { |
| 748 | let mut media = Media; |
| 749 | let ok = media |
| 750 | .attach_media(Path::new("/tmp/photo.png")) |
| 751 | .expect("png"); |
| 752 | assert_eq!(ok.kind, "image"); |
| 753 | assert_eq!(ok.path, PathBuf::from("/tmp/photo.png")); |
| 754 | |
| 755 | let err = media.attach_media(Path::new("/tmp/notes.txt")).unwrap_err(); |
| 756 | assert!(!err.is_empty(), "safe error string"); |
| 757 | } |
| 758 | |
| 759 | #[test] |
| 760 | fn digest_operation_returns_final_text_and_safe_errors() { |
| 761 | let mut workspace = DigestWorkspace; |
| 762 | assert_eq!( |
| 763 | workspace.operation_digest().expect("digest"), |
| 764 | "No active operations or to-do items." |
| 765 | ); |
| 766 | } |
| 767 | |
| 768 | #[test] |
| 769 | fn envelope_rejects_duplicate_new_slots_deterministically() { |
| 770 | struct SecondPresentation; |
| 771 | impl CommandPresentationContext for SecondPresentation { |
| 772 | fn translate(&self, _key: &str, _r: &[(&str, &str)]) -> Result<String, String> { |
| 773 | Ok(String::new()) |
| 774 | } |
| 775 | } |
| 776 | struct SecondMedia; |
| 777 | impl CommandMediaContext for SecondMedia { |
| 778 | fn attach_media(&mut self, _p: &Path) -> Result<MediaAttachmentReceipt, String> { |
| 779 | Err("unused".to_string()) |
| 780 | } |
| 781 | } |
| 782 | |
| 783 | let mut a = Presentation; |
| 784 | let mut b = SecondPresentation; |
| 785 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 786 | CommandContexts::empty() |
| 787 | .with_presentation(&mut a) |
| 788 | .with_presentation(&mut b); |
| 789 | })); |
| 790 | assert!(result.is_err(), "duplicate presentation slot must assert"); |
| 791 | |
| 792 | let mut a = Media; |
| 793 | let mut b = SecondMedia; |
| 794 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 795 | CommandContexts::empty() |
| 796 | .with_media(&mut a) |
| 797 | .with_media(&mut b); |
| 798 | })); |
| 799 | assert!(result.is_err(), "duplicate media slot must assert"); |
| 800 | } |
| 801 | |
| 802 | // --------------------------------------------------------------------------- |
| 803 | // Project facet (FEAT-021 D1/D4) |
| 804 | // --------------------------------------------------------------------------- |
| 805 | |
| 806 | /// Deterministic fake project facet over portable values only. |
| 807 | struct FakeProject { |
| 808 | approved: Vec<String>, |
| 809 | goal: ProjectGoalState, |
| 810 | } |
| 811 | |
| 812 | impl FakeProject { |
| 813 | fn new() -> Self { |
| 814 | Self { |
| 815 | approved: Vec::new(), |
| 816 | goal: ProjectGoalState { |
| 817 | objective: Some("Ship FEAT-021".to_string()), |
| 818 | status: ProjectGoalStatus::Active, |
| 819 | pause_reason: None, |
| 820 | started_at_elapsed_seconds: Some(42), |
| 821 | time_used_seconds: 42, |
| 822 | token_budget: Some(50_000), |
| 823 | tokens_used: 1_000, |
| 824 | session_total_tokens: 2_000, |
| 825 | continuation_count: 3, |
| 826 | pending_controls: false, |
| 827 | last_known_objective: None, |
| 828 | last_known_status: None, |
| 829 | conversation_present: true, |
| 830 | is_loading: false, |
| 831 | goal_continuation_waiting: false, |
| 832 | }, |
| 833 | } |
| 834 | } |
| 835 | } |
| 836 | |
| 837 | impl CommandProjectContext for FakeProject { |
| 838 | fn lsp_status(&self) -> String { |
| 839 | self.approved.join(",") |
| 840 | } |
| 841 | |
| 842 | fn lsp_approve(&mut self, names: &[&str]) -> Result<String, String> { |
| 843 | self.approved |
| 844 | .extend(names.iter().map(|name| (*name).to_owned())); |
| 845 | Ok(String::new()) |
| 846 | } |
| 847 | |
| 848 | fn lsp_revoke(&mut self, names: &[&str]) -> Result<String, String> { |
| 849 | self.approved |
| 850 | .retain(|approved| !names.contains(&approved.as_str())); |
| 851 | Ok(String::new()) |
| 852 | } |
| 853 | |
| 854 | fn goal_state(&self) -> ProjectGoalState { |
| 855 | self.goal.clone() |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | // --------------------------------------------------------------------------- |
| 860 | // FEAT-019: memory capability, typed outcomes, and workspace scoping (D1-D9) |
| 861 | // --------------------------------------------------------------------------- |
| 862 | |
| 863 | /// Deterministic fake memory facet over portable values only. Tracks the |
| 864 | /// workspace argument discipline (D8): only workspace-scoped methods receive |
| 865 | /// the workspace path. |
| 866 | struct FakeMemory { |
| 867 | hits: Vec<MemoryHit>, |
| 868 | remembered_result: Option<MemoryRemembered>, |
| 869 | workspace_id_result: Result<String, String>, |
| 870 | } |
| 871 | |
| 872 | impl FakeMemory { |
| 873 | fn new() -> Self { |
| 874 | Self { |
| 875 | hits: vec![MemoryHit { |
| 876 | source: PathBuf::from("/mem/source.md"), |
| 877 | line_start: 3, |
| 878 | line_end: 5, |
| 879 | text: "reviewed note".to_string(), |
| 880 | }], |
| 881 | remembered_result: Some(MemoryRemembered { |
| 882 | source: PathBuf::from("/mem/global.md"), |
| 883 | line_start: 7, |
| 884 | }), |
| 885 | workspace_id_result: Ok("owner/repo".to_string()), |
| 886 | } |
| 887 | } |
| 888 | } |
| 889 | |
| 890 | impl CommandMemoryContext for FakeMemory { |
| 891 | fn memory_path(&self) -> PathBuf { |
| 892 | PathBuf::from("/mem/user-memory.md") |
| 893 | } |
| 894 | |
| 895 | fn memory_enabled(&self) -> bool { |
| 896 | true |
| 897 | } |
| 898 | |
| 899 | fn status(&self) -> Result<MemoryStatus, String> { |
| 900 | Ok(MemoryStatus { |
| 901 | root: PathBuf::from("/mem/memory"), |
| 902 | source: PathBuf::from("/mem/memory/global/global.md"), |
| 903 | index: PathBuf::from("/mem/memory/index.db"), |
| 904 | }) |
| 905 | } |
| 906 | |
| 907 | fn path(&self) -> Result<PathBuf, String> { |
| 908 | Ok(PathBuf::from("/mem/memory")) |
| 909 | } |
| 910 | |
| 911 | fn workspace_id(&self, _workspace: &Path) -> Result<String, String> { |
| 912 | self.workspace_id_result.clone() |
| 913 | } |
| 914 | |
| 915 | fn search( |
| 916 | &self, |
| 917 | _workspace: &Path, |
| 918 | query: &str, |
| 919 | limit: usize, |
| 920 | ) -> Result<Vec<MemoryHit>, String> { |
| 921 | if query.is_empty() { |
| 922 | return Ok(Vec::new()); |
| 923 | } |
| 924 | Ok(self.hits.iter().take(limit).cloned().collect()) |
| 925 | } |
| 926 | |
| 927 | fn remember( |
| 928 | &self, |
| 929 | _target: MemoryRememberTarget, |
| 930 | note: &str, |
| 931 | ) -> Result<MemoryRemembered, String> { |
| 932 | if note.is_empty() { |
| 933 | return Err("empty note".to_string()); |
| 934 | } |
| 935 | Ok(self.remembered_result.clone().unwrap_or(MemoryRemembered { |
| 936 | source: PathBuf::from("/mem/global.md"), |
| 937 | line_start: 1, |
| 938 | })) |
| 939 | } |
| 940 | |
| 941 | fn import(&self) -> Result<MemoryImportOutcome, String> { |
| 942 | Ok(MemoryImportOutcome::Skipped) |
| 943 | } |
| 944 | |
| 945 | fn get(&self, _workspace: &Path, id: i64) -> Result<MemoryGetOutcome, String> { |
| 946 | if id == 42 { |
| 947 | Ok(MemoryGetOutcome::Found(self.hits[0].clone())) |
| 948 | } else { |
| 949 | Ok(MemoryGetOutcome::NotFound) |
| 950 | } |
| 951 | } |
| 952 | |
| 953 | fn export(&self) -> Result<MemoryExport, String> { |
| 954 | Ok(MemoryExport { |
| 955 | content: "# memory\n\n- bullet".to_string(), |
| 956 | }) |
| 957 | } |
| 958 | |
| 959 | fn reindex(&self) -> Result<MemoryReindex, String> { |
| 960 | Ok(MemoryReindex { entry_count: 3 }) |
| 961 | } |
| 962 | |
| 963 | fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String> { |
| 964 | match scope { |
| 965 | MemoryDeleteScope::All => Ok(MemoryDelete), |
| 966 | MemoryDeleteScope::Global => Ok(MemoryDelete), |
| 967 | } |
| 968 | } |
| 969 | |
| 970 | fn delete_workspace(&self, _workspace: &Path) -> Result<MemoryDelete, String> { |
| 971 | Ok(MemoryDelete) |
| 972 | } |
| 973 | } |
| 974 | |
| 975 | /// Recording fake that captures remember targets and delete scopes to prove |
| 976 | /// the typed target/scope discipline (D2/D8/D9). Interior mutability lets the |
| 977 | /// contract-level test assert exactly which operations the handler drives. |
| 978 | #[derive(Default)] |
| 979 | struct RecordingMemory { |
| 980 | remembered_targets: std::cell::RefCell<Vec<MemoryRememberTarget>>, |
| 981 | delete_scopes: std::cell::RefCell<Vec<String>>, |
| 982 | workspace_deletes: std::cell::Cell<usize>, |
| 983 | } |
| 984 | |
| 985 | impl RecordingMemory { |
| 986 | fn new() -> Self { |
| 987 | Self::default() |
| 988 | } |
| 989 | |
| 990 | fn recorded_targets(&self) -> Vec<MemoryRememberTarget> { |
| 991 | self.remembered_targets.borrow().clone() |
| 992 | } |
| 993 | |
| 994 | fn recorded_delete_scopes(&self) -> Vec<String> { |
| 995 | self.delete_scopes.borrow().clone() |
| 996 | } |
| 997 | |
| 998 | fn recorded_workspace_deletes(&self) -> usize { |
| 999 | self.workspace_deletes.get() |
| 1000 | } |
| 1001 | } |
| 1002 | |
| 1003 | impl CommandMemoryContext for RecordingMemory { |
| 1004 | fn memory_path(&self) -> PathBuf { |
| 1005 | PathBuf::from("/mem/user-memory.md") |
| 1006 | } |
| 1007 | |
| 1008 | fn memory_enabled(&self) -> bool { |
| 1009 | true |
| 1010 | } |
| 1011 | |
| 1012 | fn status(&self) -> Result<MemoryStatus, String> { |
| 1013 | unreachable!("recording fake") |
| 1014 | } |
| 1015 | |
| 1016 | fn path(&self) -> Result<PathBuf, String> { |
| 1017 | unreachable!("recording fake") |
| 1018 | } |
| 1019 | |
| 1020 | fn workspace_id(&self, _workspace: &Path) -> Result<String, String> { |
| 1021 | Ok("owner/repo".to_string()) |
| 1022 | } |
| 1023 | |
| 1024 | fn search( |
| 1025 | &self, |
| 1026 | _workspace: &Path, |
| 1027 | _query: &str, |
| 1028 | _limit: usize, |
| 1029 | ) -> Result<Vec<MemoryHit>, String> { |
| 1030 | unreachable!("recording fake") |
| 1031 | } |
| 1032 | |
| 1033 | fn remember( |
| 1034 | &self, |
| 1035 | target: MemoryRememberTarget, |
| 1036 | _note: &str, |
| 1037 | ) -> Result<MemoryRemembered, String> { |
| 1038 | self.remembered_targets.borrow_mut().push(target); |
| 1039 | Ok(MemoryRemembered { |
| 1040 | source: PathBuf::from("/mem/global.md"), |
| 1041 | line_start: 1, |
| 1042 | }) |
| 1043 | } |
| 1044 | |
| 1045 | fn import(&self) -> Result<MemoryImportOutcome, String> { |
| 1046 | unreachable!("recording fake") |
| 1047 | } |
| 1048 | |
| 1049 | fn get(&self, _workspace: &Path, _id: i64) -> Result<MemoryGetOutcome, String> { |
| 1050 | unreachable!("recording fake") |
| 1051 | } |
| 1052 | |
| 1053 | fn export(&self) -> Result<MemoryExport, String> { |
| 1054 | unreachable!("recording fake") |
| 1055 | } |
| 1056 | |
| 1057 | fn reindex(&self) -> Result<MemoryReindex, String> { |
| 1058 | unreachable!("recording fake") |
| 1059 | } |
| 1060 | |
| 1061 | fn delete(&self, scope: MemoryDeleteScope) -> Result<MemoryDelete, String> { |
| 1062 | self.delete_scopes.borrow_mut().push(match scope { |
| 1063 | MemoryDeleteScope::All => "all".to_string(), |
| 1064 | MemoryDeleteScope::Global => "global".to_string(), |
| 1065 | }); |
| 1066 | Ok(MemoryDelete) |
| 1067 | } |
| 1068 | |
| 1069 | fn delete_workspace(&self, _workspace: &Path) -> Result<MemoryDelete, String> { |
| 1070 | self.workspace_deletes.set(self.workspace_deletes.get() + 1); |
| 1071 | Ok(MemoryDelete) |
| 1072 | } |
| 1073 | } |
| 1074 | |
| 1075 | #[test] |
| 1076 | fn project_facet_is_object_safe_and_typed() { |
| 1077 | fn project(_: &dyn CommandProjectContext) {} |
| 1078 | project(&FakeProject::new()); |
| 1079 | |
| 1080 | let mut project = FakeProject::new(); |
| 1081 | assert_eq!(project.lsp_status(), ""); |
| 1082 | project.lsp_approve(&["rust"]).unwrap(); |
| 1083 | assert_eq!(project.lsp_status(), "rust"); |
| 1084 | project.lsp_revoke(&["rust"]).unwrap(); |
| 1085 | assert_eq!(project.lsp_status(), ""); |
| 1086 | } |
| 1087 | |
| 1088 | #[test] |
| 1089 | fn project_goal_state_preserves_semantic_values() { |
| 1090 | let project = FakeProject::new(); |
| 1091 | let goal = project.goal_state(); |
| 1092 | assert_eq!(goal.objective.as_deref(), Some("Ship FEAT-021")); |
| 1093 | assert_eq!(goal.status, ProjectGoalStatus::Active); |
| 1094 | assert_eq!(goal.pause_reason, None); |
| 1095 | assert_eq!(goal.started_at_elapsed_seconds, Some(42)); |
| 1096 | assert_eq!(goal.time_used_seconds, 42); |
| 1097 | assert_eq!(goal.token_budget, Some(50_000)); |
| 1098 | assert_eq!(goal.tokens_used, 1_000); |
| 1099 | assert_eq!(goal.session_total_tokens, 2_000); |
| 1100 | assert_eq!(goal.continuation_count, 3); |
| 1101 | assert!(!goal.pending_controls); |
| 1102 | assert_eq!(goal.last_known_objective, None); |
| 1103 | assert_eq!(goal.last_known_status, None); |
| 1104 | assert!(goal.conversation_present); |
| 1105 | assert!(!goal.is_loading); |
| 1106 | assert!(!goal.goal_continuation_waiting); |
| 1107 | } |
| 1108 | |
| 1109 | #[test] |
| 1110 | fn project_goal_status_variants_are_distinguishable() { |
| 1111 | let paused = ProjectGoalState { |
| 1112 | status: ProjectGoalStatus::Paused, |
| 1113 | pause_reason: Some("user".to_string()), |
| 1114 | ..FakeProject::new().goal |
| 1115 | }; |
| 1116 | assert_eq!(paused.status, ProjectGoalStatus::Paused); |
| 1117 | assert_eq!(paused.pause_reason.as_deref(), Some("user")); |
| 1118 | |
| 1119 | let complete = ProjectGoalState { |
| 1120 | status: ProjectGoalStatus::Complete, |
| 1121 | ..paused |
| 1122 | }; |
| 1123 | assert_eq!(complete.status, ProjectGoalStatus::Complete); |
| 1124 | assert_ne!(complete.status, ProjectGoalStatus::Blocked); |
| 1125 | } |
| 1126 | |
| 1127 | #[test] |
| 1128 | fn project_facet_transports_through_envelope_when_declared() { |
| 1129 | let mut project = FakeProject::new(); |
| 1130 | let parts = CommandContexts::empty() |
| 1131 | .with_project(&mut project) |
| 1132 | .into_parts(); |
| 1133 | assert!(parts.project.is_some()); |
| 1134 | assert!(parts.session.is_none()); |
| 1135 | |
| 1136 | // PROJECT combined with WORKSPACE (init) and PRESENTATION (goal). |
| 1137 | let mut workspace = Workspace; |
| 1138 | let parts = CommandContexts::empty() |
| 1139 | .with_project(&mut project) |
| 1140 | .with_workspace(&mut workspace) |
| 1141 | .into_parts(); |
| 1142 | assert!(parts.project.is_some()); |
| 1143 | assert!(parts.workspace.is_some()); |
| 1144 | assert!(parts.presentation.is_none()); |
| 1145 | } |
| 1146 | |
| 1147 | #[test] |
| 1148 | fn envelope_rejects_duplicate_project_slot_deterministically() { |
| 1149 | let mut a = FakeProject::new(); |
| 1150 | let mut b = FakeProject::new(); |
| 1151 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1152 | CommandContexts::empty() |
| 1153 | .with_project(&mut a) |
| 1154 | .with_project(&mut b); |
| 1155 | })); |
| 1156 | assert!(result.is_err(), "duplicate project slot must assert"); |
| 1157 | } |
| 1158 | |
| 1159 | #[test] |
| 1160 | fn memory_facet_is_object_safe_and_typed() { |
| 1161 | fn memory(_: &dyn CommandMemoryContext) {} |
| 1162 | let fake = FakeMemory::new(); |
| 1163 | memory(&fake); |
| 1164 | |
| 1165 | assert_eq!(fake.memory_path(), PathBuf::from("/mem/user-memory.md")); |
| 1166 | assert!(fake.memory_enabled()); |
| 1167 | let status = fake.status().expect("status"); |
| 1168 | assert_eq!(status.root, PathBuf::from("/mem/memory")); |
| 1169 | assert_eq!(status.source, PathBuf::from("/mem/memory/global/global.md")); |
| 1170 | assert_eq!(status.index, PathBuf::from("/mem/memory/index.db")); |
| 1171 | } |
| 1172 | |
| 1173 | #[test] |
| 1174 | fn memory_typed_results_preserve_semantic_distinctions() { |
| 1175 | let fake = FakeMemory::new(); |
| 1176 | |
| 1177 | // Search returns semantic hits, never preformatted messages. |
| 1178 | let hits = fake.search(Path::new("/ws"), "note", 10).expect("search"); |
| 1179 | assert_eq!(hits.len(), 1); |
| 1180 | assert_eq!(hits[0].source, PathBuf::from("/mem/source.md")); |
| 1181 | assert_eq!(hits[0].line_start, 3); |
| 1182 | assert_eq!(hits[0].line_end, 5); |
| 1183 | assert_eq!(hits[0].text, "reviewed note"); |
| 1184 | assert!( |
| 1185 | fake.search(Path::new("/ws"), "", 10) |
| 1186 | .expect("empty") |
| 1187 | .is_empty() |
| 1188 | ); |
| 1189 | |
| 1190 | // Get distinguishes found from not-found without an error string. |
| 1191 | assert!(matches!( |
| 1192 | fake.get(Path::new("/ws"), 42), |
| 1193 | Ok(MemoryGetOutcome::Found(_)) |
| 1194 | )); |
| 1195 | assert_eq!( |
| 1196 | fake.get(Path::new("/ws"), 1).expect("get"), |
| 1197 | MemoryGetOutcome::NotFound |
| 1198 | ); |
| 1199 | |
| 1200 | // Export carries the raw document, not a command response. |
| 1201 | let exported = fake.export().expect("export"); |
| 1202 | assert_eq!(exported.content, "# memory\n\n- bullet"); |
| 1203 | |
| 1204 | // Reindex carries the typed count. |
| 1205 | assert_eq!(fake.reindex().expect("reindex").entry_count, 3); |
| 1206 | |
| 1207 | // Remember distinguishes global from workspace via the typed target. |
| 1208 | let global = fake |
| 1209 | .remember(MemoryRememberTarget::Global, "note") |
| 1210 | .expect("global remember"); |
| 1211 | assert_eq!(global.source, PathBuf::from("/mem/global.md")); |
| 1212 | assert_eq!(global.line_start, 7); |
| 1213 | let workspace = fake |
| 1214 | .remember( |
| 1215 | MemoryRememberTarget::Workspace { |
| 1216 | workspace_id: "owner/repo".to_string(), |
| 1217 | }, |
| 1218 | "note", |
| 1219 | ) |
| 1220 | .expect("workspace remember"); |
| 1221 | assert_eq!(workspace.source, PathBuf::from("/mem/global.md")); |
| 1222 | |
| 1223 | // Import distinguishes imported from skipped. |
| 1224 | assert_eq!(fake.import().expect("import"), MemoryImportOutcome::Skipped); |
| 1225 | assert_eq!( |
| 1226 | MemoryImportOutcome::Imported { |
| 1227 | destination: PathBuf::from("/mem/global.md") |
| 1228 | }, |
| 1229 | MemoryImportOutcome::Imported { |
| 1230 | destination: PathBuf::from("/mem/global.md") |
| 1231 | } |
| 1232 | ); |
| 1233 | |
| 1234 | // Remember rejects empty notes with a safe error, never a panic. |
| 1235 | assert!(fake.remember(MemoryRememberTarget::Global, "").is_err()); |
| 1236 | |
| 1237 | // Zero-field delete outcome stays distinguishable. |
| 1238 | assert_eq!(fake.delete(MemoryDeleteScope::All), Ok(MemoryDelete)); |
| 1239 | } |
| 1240 | |
| 1241 | #[test] |
| 1242 | fn memory_delete_and_remember_targets_are_typed_and_scoped() { |
| 1243 | let memory = RecordingMemory::new(); |
| 1244 | let _ = memory.delete(MemoryDeleteScope::All); |
| 1245 | let _ = memory.delete(MemoryDeleteScope::Global); |
| 1246 | let _ = memory.delete_workspace(Path::new("/ws")); |
| 1247 | let _ = memory.remember(MemoryRememberTarget::Global, "a"); |
| 1248 | let _ = memory.remember( |
| 1249 | MemoryRememberTarget::Workspace { |
| 1250 | workspace_id: "owner/repo".to_string(), |
| 1251 | }, |
| 1252 | "b", |
| 1253 | ); |
| 1254 | |
| 1255 | // The non-workspace delete method receives exactly the all/global scopes; |
| 1256 | // workspace deletion goes through the distinct typed method (D8/D9). |
| 1257 | assert_eq!(memory.recorded_delete_scopes(), vec!["all", "global"]); |
| 1258 | assert_eq!(memory.recorded_workspace_deletes(), 1); |
| 1259 | |
| 1260 | // Remember targets preserve the typed global/workspace distinction. |
| 1261 | assert_eq!( |
| 1262 | memory.recorded_targets(), |
| 1263 | vec![ |
| 1264 | MemoryRememberTarget::Global, |
| 1265 | MemoryRememberTarget::Workspace { |
| 1266 | workspace_id: "owner/repo".to_string(), |
| 1267 | }, |
| 1268 | ] |
| 1269 | ); |
| 1270 | } |
| 1271 | |
| 1272 | #[test] |
| 1273 | fn capabilities_declare_exact_memory_authority() { |
| 1274 | let workspace = CommandCapabilities::WORKSPACE; |
| 1275 | let memory = CommandCapabilities::MEMORY; |
| 1276 | let workspace_memory = workspace.union(memory); |
| 1277 | |
| 1278 | assert_eq!( |
| 1279 | workspace_memory, |
| 1280 | CommandCapabilities::WORKSPACE | CommandCapabilities::MEMORY |
| 1281 | ); |
| 1282 | assert_ne!(workspace_memory, workspace); |
| 1283 | assert_ne!(workspace_memory, memory); |
| 1284 | assert!(workspace_memory.contains(CommandCapabilities::WORKSPACE)); |
| 1285 | assert!(workspace_memory.contains(CommandCapabilities::MEMORY)); |
| 1286 | assert!(!workspace.contains(CommandCapabilities::MEMORY)); |
| 1287 | assert!(!memory.contains(CommandCapabilities::WORKSPACE)); |
| 1288 | assert!(CommandCapabilities::NONE.is_empty()); |
| 1289 | assert!(!workspace_memory.contains(CommandCapabilities::NONE)); |
| 1290 | assert!(!CommandCapabilities::NONE.contains(CommandCapabilities::NONE)); |
| 1291 | // No presentation or media authority is declared for the memory group. |
| 1292 | assert!(!workspace_memory.contains(CommandCapabilities::PRESENTATION)); |
| 1293 | assert!(!workspace_memory.contains(CommandCapabilities::MEDIA)); |
| 1294 | // Existing capability identities stay stable. |
| 1295 | assert_ne!(CommandCapabilities::SESSION, CommandCapabilities::MODEL); |
| 1296 | } |
| 1297 | |
| 1298 | #[test] |
| 1299 | fn memory_facet_transports_through_envelope_when_declared() { |
| 1300 | let mut memory = FakeMemory::new(); |
| 1301 | let parts = CommandContexts::empty() |
| 1302 | .with_memory(&mut memory) |
| 1303 | .into_parts(); |
| 1304 | assert!(parts.memory.is_some()); |
| 1305 | assert!(parts.session.is_none()); |
| 1306 | assert!(parts.workspace.is_none()); |
| 1307 | |
| 1308 | // Undeclared slots stay absent when the memory facet is carried alone. |
| 1309 | let mut workspace = Workspace; |
| 1310 | let parts = CommandContexts::empty() |
| 1311 | .with_memory(&mut memory) |
| 1312 | .with_workspace(&mut workspace) |
| 1313 | .into_parts(); |
| 1314 | assert!(parts.memory.is_some()); |
| 1315 | assert!(parts.workspace.is_some()); |
| 1316 | assert!(parts.presentation.is_none()); |
| 1317 | assert!(parts.media.is_none()); |
| 1318 | } |
| 1319 | |
| 1320 | #[test] |
| 1321 | fn envelope_rejects_duplicate_memory_slot_deterministically() { |
| 1322 | let mut a = FakeMemory::new(); |
| 1323 | let mut b = FakeMemory::new(); |
| 1324 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1325 | CommandContexts::empty() |
| 1326 | .with_memory(&mut a) |
| 1327 | .with_memory(&mut b); |
| 1328 | })); |
| 1329 | assert!(result.is_err(), "duplicate memory slot must assert"); |
| 1330 | } |
| 1331 | |
| 1332 | // --------------------------------------------------------------------------- |
| 1333 | // FEAT-020: plugin capability, portable DTOs, and envelope slot (D1-D11) |
| 1334 | // --------------------------------------------------------------------------- |
| 1335 | |
| 1336 | /// Deterministic fake plugin facet over portable values only. |
| 1337 | struct FakePlugin { |
| 1338 | summaries: Vec<PluginSummary>, |
| 1339 | detail: Option<PluginDetail>, |
| 1340 | installed: bool, |
| 1341 | managed_candidates: Vec<PluginManagedCandidate>, |
| 1342 | } |
| 1343 | |
| 1344 | impl FakePlugin { |
| 1345 | fn new() -> Self { |
| 1346 | Self { |
| 1347 | summaries: vec![PluginSummary { |
| 1348 | name: "demo".to_string(), |
| 1349 | id: "demo@1.0.0".to_string(), |
| 1350 | state_label: "active".to_string(), |
| 1351 | scope: "user".to_string(), |
| 1352 | trust_status: "trusted".to_string(), |
| 1353 | review_display: None, |
| 1354 | approver: None, |
| 1355 | reviewed_date: None, |
| 1356 | enabled_by: None, |
| 1357 | reach_folder: None, |
| 1358 | outside_reach: false, |
| 1359 | process_note: None, |
| 1360 | compatibility: "full".to_string(), |
| 1361 | inventory: "skills=1 mcp=0".to_string(), |
| 1362 | active: true, |
| 1363 | trusted: true, |
| 1364 | enabled: true, |
| 1365 | }], |
| 1366 | detail: Some(PluginDetail { |
| 1367 | name: "demo".to_string(), |
| 1368 | id: "demo@1.0.0".to_string(), |
| 1369 | inventory_summary: "skills=1 mcp=0".to_string(), |
| 1370 | version: "1.0.0".to_string(), |
| 1371 | origin: "local".to_string(), |
| 1372 | scope: "user".to_string(), |
| 1373 | state_label: "active".to_string(), |
| 1374 | trust_status: "trusted".to_string(), |
| 1375 | trust_display: None, |
| 1376 | approver: None, |
| 1377 | reviewed_date: None, |
| 1378 | enabled_by: None, |
| 1379 | agent_thread_id: None, |
| 1380 | agent_workspace_path: None, |
| 1381 | reach_folder: None, |
| 1382 | outside_reach: false, |
| 1383 | process_note: None, |
| 1384 | host_services: Vec::new(), |
| 1385 | earlier_reviews: Vec::new(), |
| 1386 | compatibility: "full".to_string(), |
| 1387 | content_hash: "abc".to_string(), |
| 1388 | capability_hash: "def".to_string(), |
| 1389 | canonical_root: PathBuf::from("/plugins/demo"), |
| 1390 | active: true, |
| 1391 | trusted: true, |
| 1392 | enabled: true, |
| 1393 | unsupported_labels: Vec::new(), |
| 1394 | supported_labels: vec!["skills".to_string()], |
| 1395 | skills: vec!["demo:demo-skill".to_string()], |
| 1396 | commands: Vec::new(), |
| 1397 | profiles: Vec::new(), |
| 1398 | filesystem_roots: Vec::new(), |
| 1399 | network_hosts: Vec::new(), |
| 1400 | stdio_mcp_servers: 0, |
| 1401 | lifecycle_mutation: false, |
| 1402 | mcp_servers: Vec::new(), |
| 1403 | diagnostics: Vec::new(), |
| 1404 | }), |
| 1405 | installed: false, |
| 1406 | managed_candidates: Vec::new(), |
| 1407 | } |
| 1408 | } |
| 1409 | } |
| 1410 | |
| 1411 | impl CommandPluginContext for FakePlugin { |
| 1412 | fn summaries(&self) -> Result<Vec<PluginSummary>, String> { |
| 1413 | Ok(self.summaries.clone()) |
| 1414 | } |
| 1415 | |
| 1416 | fn detail(&self, selector: &str) -> Result<PluginDetail, String> { |
| 1417 | if selector == "demo" { |
| 1418 | self.detail |
| 1419 | .clone() |
| 1420 | .ok_or_else(|| "missing detail".to_string()) |
| 1421 | } else { |
| 1422 | Err(format!("no plugin named {selector}")) |
| 1423 | } |
| 1424 | } |
| 1425 | |
| 1426 | fn registry_diagnostics(&self) -> Vec<PluginDiagnostic> { |
| 1427 | Vec::new() |
| 1428 | } |
| 1429 | |
| 1430 | fn validation_is_clean(&self) -> bool { |
| 1431 | true |
| 1432 | } |
| 1433 | |
| 1434 | fn len(&self) -> usize { |
| 1435 | self.summaries.len() |
| 1436 | } |
| 1437 | |
| 1438 | fn reload(&mut self) -> Result<usize, String> { |
| 1439 | Ok(self.summaries.len()) |
| 1440 | } |
| 1441 | |
| 1442 | fn is_empty(&self) -> bool { |
| 1443 | self.summaries.is_empty() |
| 1444 | } |
| 1445 | |
| 1446 | fn reload_nudge(&mut self) -> Option<String> { |
| 1447 | None |
| 1448 | } |
| 1449 | |
| 1450 | fn state_path(&self) -> Option<PathBuf> { |
| 1451 | Some(PathBuf::from("/plugins/state.json")) |
| 1452 | } |
| 1453 | |
| 1454 | fn suggest(&self, task: &str) -> Result<Vec<PluginSuggestion>, String> { |
| 1455 | if task.len() < 3 { |
| 1456 | return Err("task too short".to_string()); |
| 1457 | } |
| 1458 | Ok(vec![PluginSuggestion { |
| 1459 | name: "demo".to_string(), |
| 1460 | state_label: "active".to_string(), |
| 1461 | description: "Demo bundle".to_string(), |
| 1462 | why: vec![task.to_string()], |
| 1463 | next_step: "Already active: /plugin show demo".to_string(), |
| 1464 | }]) |
| 1465 | } |
| 1466 | |
| 1467 | fn trust(&mut self, _selector: &str, token: &str) -> Result<(), String> { |
| 1468 | if token == "abc.def" { |
| 1469 | Ok(()) |
| 1470 | } else { |
| 1471 | Err("Review token does not match this bundle content and capability set".to_string()) |
| 1472 | } |
| 1473 | } |
| 1474 | |
| 1475 | fn enable(&mut self, _selector: &str) -> Result<(), String> { |
| 1476 | Ok(()) |
| 1477 | } |
| 1478 | |
| 1479 | fn disable(&mut self, _selector: &str) -> Result<(), String> { |
| 1480 | Ok(()) |
| 1481 | } |
| 1482 | |
| 1483 | fn revoke_trust(&mut self, _selector: &str) -> Result<(), String> { |
| 1484 | Ok(()) |
| 1485 | } |
| 1486 | |
| 1487 | fn install( |
| 1488 | &mut self, |
| 1489 | _source: &str, |
| 1490 | expected_content_hash: Option<&str>, |
| 1491 | ) -> Result<PluginMutationReceipt, String> { |
| 1492 | if let Some(expected) = expected_content_hash |
| 1493 | && expected != "abc" |
| 1494 | { |
| 1495 | return Err("content hash mismatch".to_string()); |
| 1496 | } |
| 1497 | self.installed = true; |
| 1498 | Ok(PluginMutationReceipt { |
| 1499 | name: "demo".to_string(), |
| 1500 | path: Some(PathBuf::from("/plugins/demo")), |
| 1501 | content_hash: Some("abc".to_string()), |
| 1502 | installed_content_hash: Some("abc".to_string()), |
| 1503 | outcome: PluginMutationOutcome::Installed, |
| 1504 | }) |
| 1505 | } |
| 1506 | |
| 1507 | fn update(&mut self, _selector: &str) -> Result<PluginMutationReceipt, String> { |
| 1508 | Ok(PluginMutationReceipt { |
| 1509 | name: "demo".to_string(), |
| 1510 | path: None, |
| 1511 | content_hash: None, |
| 1512 | installed_content_hash: None, |
| 1513 | outcome: PluginMutationOutcome::NoChange, |
| 1514 | }) |
| 1515 | } |
| 1516 | |
| 1517 | fn uninstall(&mut self, _selector: &str) -> Result<PluginMutationReceipt, String> { |
| 1518 | Ok(PluginMutationReceipt { |
| 1519 | name: "demo".to_string(), |
| 1520 | path: None, |
| 1521 | content_hash: None, |
| 1522 | installed_content_hash: None, |
| 1523 | outcome: PluginMutationOutcome::Uninstalled, |
| 1524 | }) |
| 1525 | } |
| 1526 | |
| 1527 | fn uninstall_path(&mut self, _name: &str, _plugins_dir: &Path) -> Result<(), String> { |
| 1528 | Ok(()) |
| 1529 | } |
| 1530 | |
| 1531 | fn export(&self, _selector: &str, target: &Path) -> Result<PluginExportReceipt, String> { |
| 1532 | Ok(PluginExportReceipt { |
| 1533 | exported_name: "demo".to_string(), |
| 1534 | target: target.to_path_buf(), |
| 1535 | display_name: Some("Demo Bundle".to_string()), |
| 1536 | wrote_mcp_json: false, |
| 1537 | files_copied: 2, |
| 1538 | skills_normalized: false, |
| 1539 | }) |
| 1540 | } |
| 1541 | |
| 1542 | fn legacy_scan(&self) -> Result<Option<PluginLegacyScan>, String> { |
| 1543 | Ok(None) |
| 1544 | } |
| 1545 | |
| 1546 | fn managed_scan(&self, _home_override: Option<&Path>) -> Result<PluginManagedScan, String> { |
| 1547 | Ok(PluginManagedScan { |
| 1548 | root: PathBuf::from("/kimi/managed"), |
| 1549 | candidates: self.managed_candidates.clone(), |
| 1550 | rejected: Vec::new(), |
| 1551 | }) |
| 1552 | } |
| 1553 | |
| 1554 | fn managed_install( |
| 1555 | &mut self, |
| 1556 | canonical_path: &Path, |
| 1557 | expected_content_hash: &str, |
| 1558 | ) -> Result<PluginMutationReceipt, String> { |
| 1559 | if expected_content_hash != "abc" { |
| 1560 | return Err("Kimi candidate changed".to_string()); |
| 1561 | } |
| 1562 | Ok(PluginMutationReceipt { |
| 1563 | name: "kimi-demo".to_string(), |
| 1564 | path: Some(canonical_path.to_path_buf()), |
| 1565 | content_hash: Some("abc".to_string()), |
| 1566 | installed_content_hash: Some("abc".to_string()), |
| 1567 | outcome: PluginMutationOutcome::Installed, |
| 1568 | }) |
| 1569 | } |
| 1570 | |
| 1571 | fn marketplace_state(&self) -> Result<PluginMarketplaceState, String> { |
| 1572 | Ok(PluginMarketplaceState { |
| 1573 | official: Some(PluginMarketplaceCatalog { |
| 1574 | id: "official".to_string(), |
| 1575 | source_path: None, |
| 1576 | display_name: None, |
| 1577 | description: Some("Built into this release".to_string()), |
| 1578 | format: "codewhale".to_string(), |
| 1579 | tier: "official".to_string(), |
| 1580 | publisher: Some("Codewhale".to_string()), |
| 1581 | total_candidates: 1, |
| 1582 | warning_count: 0, |
| 1583 | candidates: Vec::new(), |
| 1584 | diagnostics: Vec::new(), |
| 1585 | }), |
| 1586 | stored: Vec::new(), |
| 1587 | }) |
| 1588 | } |
| 1589 | |
| 1590 | fn marketplace_add( |
| 1591 | &mut self, |
| 1592 | name: &str, |
| 1593 | _path: &Path, |
| 1594 | ) -> Result<PluginMarketplaceAddReceipt, String> { |
| 1595 | if name == "official" { |
| 1596 | return Err( |
| 1597 | "`official` is the catalog built into Codewhale; pick another name.".to_string(), |
| 1598 | ); |
| 1599 | } |
| 1600 | Ok(PluginMarketplaceAddReceipt { |
| 1601 | name: name.to_string(), |
| 1602 | candidate_count: 0, |
| 1603 | warning_count: 0, |
| 1604 | catalog: PluginMarketplaceCatalog { |
| 1605 | id: name.to_string(), |
| 1606 | source_path: None, |
| 1607 | display_name: None, |
| 1608 | description: None, |
| 1609 | format: "kimi".to_string(), |
| 1610 | tier: "community".to_string(), |
| 1611 | publisher: None, |
| 1612 | total_candidates: 0, |
| 1613 | warning_count: 0, |
| 1614 | candidates: Vec::new(), |
| 1615 | diagnostics: Vec::new(), |
| 1616 | }, |
| 1617 | }) |
| 1618 | } |
| 1619 | |
| 1620 | fn marketplace_remove(&mut self, _name: &str) -> Result<bool, String> { |
| 1621 | Ok(true) |
| 1622 | } |
| 1623 | |
| 1624 | fn marketplace_install( |
| 1625 | &mut self, |
| 1626 | _catalog: &str, |
| 1627 | _candidate: &str, |
| 1628 | ) -> Result<PluginMutationReceipt, String> { |
| 1629 | Ok(PluginMutationReceipt { |
| 1630 | name: "market-demo".to_string(), |
| 1631 | path: None, |
| 1632 | content_hash: None, |
| 1633 | installed_content_hash: None, |
| 1634 | outcome: PluginMutationOutcome::Installed, |
| 1635 | }) |
| 1636 | } |
| 1637 | |
| 1638 | fn suggestion_dismissals(&self) -> Result<PluginSuggestionDismissals, String> { |
| 1639 | Ok(PluginSuggestionDismissals::default()) |
| 1640 | } |
| 1641 | |
| 1642 | fn reset_suggestion_dismissals(&mut self, _name: Option<&str>) -> Result<Vec<String>, String> { |
| 1643 | Ok(Vec::new()) |
| 1644 | } |
| 1645 | } |
| 1646 | |
| 1647 | #[test] |
| 1648 | fn plugin_facet_is_object_safe_and_typed() { |
| 1649 | fn plugin(_: &dyn CommandPluginContext) {} |
| 1650 | plugin(&FakePlugin::new()); |
| 1651 | |
| 1652 | let plugin = FakePlugin::new(); |
| 1653 | assert_eq!(plugin.len(), 1); |
| 1654 | assert!(!plugin.is_empty()); |
| 1655 | assert!(plugin.validation_is_clean()); |
| 1656 | let summaries = plugin.summaries().unwrap(); |
| 1657 | assert_eq!(summaries[0].name, "demo"); |
| 1658 | assert_eq!(summaries[0].state_label, "active"); |
| 1659 | } |
| 1660 | |
| 1661 | #[test] |
| 1662 | fn plugin_detail_preserves_semantic_values() { |
| 1663 | let plugin = FakePlugin::new(); |
| 1664 | let detail = plugin.detail("demo").unwrap(); |
| 1665 | assert_eq!(detail.content_hash, "abc"); |
| 1666 | assert_eq!(detail.capability_hash, "def"); |
| 1667 | assert_eq!(detail.compatibility, "full"); |
| 1668 | assert!(detail.active); |
| 1669 | assert_eq!(detail.skills, vec!["demo:demo-skill"]); |
| 1670 | // Unknown selector fails safely. |
| 1671 | assert!(plugin.detail("nope").is_err()); |
| 1672 | } |
| 1673 | |
| 1674 | #[test] |
| 1675 | fn plugin_mutation_receipts_distinguish_outcomes() { |
| 1676 | let mut plugin = FakePlugin::new(); |
| 1677 | let installed = plugin.install("path:/demo", Some("abc")).unwrap(); |
| 1678 | assert_eq!(installed.outcome, PluginMutationOutcome::Installed); |
| 1679 | assert_eq!(installed.installed_content_hash.as_deref(), Some("abc")); |
| 1680 | |
| 1681 | // Exact-hash mismatch fails before any install side effect. |
| 1682 | let err = plugin.install("path:/demo", Some("wrong")).unwrap_err(); |
| 1683 | assert!(err.contains("content hash mismatch")); |
| 1684 | |
| 1685 | let uninstalled = plugin.uninstall("demo").unwrap(); |
| 1686 | assert_eq!(uninstalled.outcome, PluginMutationOutcome::Uninstalled); |
| 1687 | |
| 1688 | plugin.trust("demo", "abc.def").unwrap(); |
| 1689 | let trust_err = plugin.trust("demo", "bad.token").unwrap_err(); |
| 1690 | assert!(trust_err.contains("Review token does not match")); |
| 1691 | } |
| 1692 | |
| 1693 | #[test] |
| 1694 | fn plugin_managed_and_marketplace_values_are_portable() { |
| 1695 | let mut plugin = FakePlugin::new(); |
| 1696 | let scan = plugin.managed_scan(None).unwrap(); |
| 1697 | assert_eq!(scan.root, PathBuf::from("/kimi/managed")); |
| 1698 | assert!(scan.candidates.is_empty()); |
| 1699 | |
| 1700 | plugin.managed_candidates.push(PluginManagedCandidate { |
| 1701 | name: "kimi-demo".to_string(), |
| 1702 | version: "1.0.0".to_string(), |
| 1703 | license: Some("MIT".to_string()), |
| 1704 | canonical_path: PathBuf::from("/kimi/managed/kimi-demo"), |
| 1705 | content_hash: "abc".to_string(), |
| 1706 | capability_hash: "def".to_string(), |
| 1707 | inventory: "skills=1".to_string(), |
| 1708 | applicable: true, |
| 1709 | }); |
| 1710 | let scan = plugin.managed_scan(None).unwrap(); |
| 1711 | assert_eq!(scan.candidates[0].name, "kimi-demo"); |
| 1712 | assert_eq!(scan.candidates[0].license.as_deref(), Some("MIT")); |
| 1713 | |
| 1714 | let state = plugin.marketplace_state().unwrap(); |
| 1715 | let official = state.official.as_ref().expect("fake official catalog"); |
| 1716 | assert_eq!(official.id, "official"); |
| 1717 | assert_eq!(official.tier, "official"); |
| 1718 | assert!(state.stored.is_empty()); |
| 1719 | |
| 1720 | let add = plugin |
| 1721 | .marketplace_add("custom", Path::new("/catalog.json")) |
| 1722 | .unwrap(); |
| 1723 | assert_eq!(add.name, "custom"); |
| 1724 | assert_eq!(add.catalog.format, "kimi"); |
| 1725 | |
| 1726 | let err = plugin |
| 1727 | .marketplace_add("official", Path::new("/x.json")) |
| 1728 | .unwrap_err(); |
| 1729 | assert!(err.contains("built into Codewhale")); |
| 1730 | } |
| 1731 | |
| 1732 | #[test] |
| 1733 | fn plugin_suggest_is_read_only_and_safe() { |
| 1734 | let plugin = FakePlugin::new(); |
| 1735 | let err = plugin.suggest("ab").unwrap_err(); |
| 1736 | assert!(err.contains("too short")); |
| 1737 | let suggestions = plugin.suggest("translate").unwrap(); |
| 1738 | assert_eq!(suggestions[0].name, "demo"); |
| 1739 | assert_eq!( |
| 1740 | suggestions[0].next_step, |
| 1741 | "Already active: /plugin show demo" |
| 1742 | ); |
| 1743 | } |
| 1744 | |
| 1745 | #[test] |
| 1746 | fn plugin_facet_transports_through_envelope_when_declared() { |
| 1747 | let mut plugin = FakePlugin::new(); |
| 1748 | let parts = CommandContexts::empty() |
| 1749 | .with_plugin(&mut plugin) |
| 1750 | .into_parts(); |
| 1751 | assert!(parts.plugin.is_some()); |
| 1752 | assert!(parts.session.is_none()); |
| 1753 | assert!(parts.memory.is_none()); |
| 1754 | |
| 1755 | // Undeclared slots stay absent when the plugin facet is carried alone. |
| 1756 | let mut workspace = Workspace; |
| 1757 | let parts = CommandContexts::empty() |
| 1758 | .with_plugin(&mut plugin) |
| 1759 | .with_workspace(&mut workspace) |
| 1760 | .into_parts(); |
| 1761 | assert!(parts.plugin.is_some()); |
| 1762 | assert!(parts.workspace.is_some()); |
| 1763 | assert!(parts.presentation.is_none()); |
| 1764 | } |
| 1765 | |
| 1766 | #[test] |
| 1767 | fn envelope_rejects_duplicate_plugin_slot_deterministically() { |
| 1768 | let mut a = FakePlugin::new(); |
| 1769 | let mut b = FakePlugin::new(); |
| 1770 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1771 | CommandContexts::empty() |
| 1772 | .with_plugin(&mut a) |
| 1773 | .with_plugin(&mut b); |
| 1774 | })); |
| 1775 | assert!(result.is_err(), "duplicate plugin slot must assert"); |
| 1776 | } |
| 1777 | |
| 1778 | #[test] |
| 1779 | fn plugin_capability_bit_is_stable_and_distinct() { |
| 1780 | let plugin = CommandCapabilities::PLUGIN; |
| 1781 | assert_eq!(plugin, CommandCapabilities::PLUGIN); |
| 1782 | assert!(plugin.contains(CommandCapabilities::PLUGIN)); |
| 1783 | assert!(!plugin.contains(CommandCapabilities::MEMORY)); |
| 1784 | assert!(!plugin.contains(CommandCapabilities::PROJECT)); |
| 1785 | assert!(!plugin.contains(CommandCapabilities::SKILL_GROUP)); |
| 1786 | assert!(!plugin.contains(CommandCapabilities::WORKSPACE)); |
| 1787 | |
| 1788 | let plugin_workspace = CommandCapabilities::PLUGIN.union(CommandCapabilities::WORKSPACE); |
| 1789 | assert!(plugin_workspace.contains(CommandCapabilities::PLUGIN)); |
| 1790 | assert!(plugin_workspace.contains(CommandCapabilities::WORKSPACE)); |
| 1791 | assert!(!plugin_workspace.contains(CommandCapabilities::MEMORY)); |
| 1792 | |
| 1793 | // The plugin group declares exactly WORKSPACE | PRESENTATION | PLUGIN. |
| 1794 | let exact = CommandCapabilities::WORKSPACE |
| 1795 | .union(CommandCapabilities::PRESENTATION) |
| 1796 | .union(CommandCapabilities::PLUGIN); |
| 1797 | assert!(exact.contains(CommandCapabilities::PLUGIN)); |
| 1798 | assert!(exact.contains(CommandCapabilities::PRESENTATION)); |
| 1799 | assert!(!exact.contains(CommandCapabilities::MEDIA)); |
| 1800 | assert!(!exact.contains(CommandCapabilities::MEMORY)); |
| 1801 | assert!(!exact.contains(CommandCapabilities::PROJECT)); |
| 1802 | assert!(!exact.contains(CommandCapabilities::SKILL_GROUP)); |
| 1803 | assert!(!exact.contains(CommandCapabilities::SKILLS)); |
| 1804 | } |
| 1805 | |
| 1806 | // FEAT-022: skill-group facet (CommandSkillGroupContext) |
| 1807 | // --------------------------------------------------------------------------- |
| 1808 | |
| 1809 | struct FakeSkillGroup { |
| 1810 | projection: SkillRegistryProjection, |
| 1811 | activation_result: Result<SkillActivationOutcome, SkillActivationError>, |
| 1812 | receipt: SkillMutationReceipt, |
| 1813 | remote: Result<RemoteRegistryOutcome, String>, |
| 1814 | sync: Result<SkillSyncOutcome, String>, |
| 1815 | review: Result<ReviewOutcome, String>, |
| 1816 | snapshots: Vec<SnapshotEntry>, |
| 1817 | restore_ok: bool, |
| 1818 | approval: CommandApprovalState, |
| 1819 | } |
| 1820 | |
| 1821 | impl FakeSkillGroup { |
| 1822 | fn new() -> Self { |
| 1823 | Self { |
| 1824 | projection: SkillRegistryProjection { |
| 1825 | workspace: "/ws".into(), |
| 1826 | skills_dir: "/ws/.codewhale/skills".into(), |
| 1827 | mode_label: "compatible".into(), |
| 1828 | bundled_status: vec![], |
| 1829 | dirs: vec!["/ws/.codewhale/skills".into()], |
| 1830 | entries: vec![SkillEntry { |
| 1831 | index_note: None, |
| 1832 | name: "demo".into(), |
| 1833 | description: "Demo skill".into(), |
| 1834 | source: SkillSourceKind::Native, |
| 1835 | path: Some("/ws/.codewhale/skills/demo/SKILL.md".into()), |
| 1836 | bundled_tier: None, |
| 1837 | }], |
| 1838 | warnings: vec!["one warning".into()], |
| 1839 | total: 1, |
| 1840 | }, |
| 1841 | activation_result: Ok(SkillActivationOutcome { |
| 1842 | name: "demo".into(), |
| 1843 | description: "Demo skill".into(), |
| 1844 | }), |
| 1845 | receipt: SkillMutationReceipt { |
| 1846 | name: "demo".into(), |
| 1847 | safe_target_path: "/ws/.codewhale/skills/demo".into(), |
| 1848 | outcome: SkillMutationOutcome::Installed, |
| 1849 | }, |
| 1850 | remote: Ok(RemoteRegistryOutcome::Loaded { |
| 1851 | entries: vec![RemoteSkillEntry { |
| 1852 | name: "demo".into(), |
| 1853 | description: Some("Remote demo".into()), |
| 1854 | source: "github.com/acme/skills".into(), |
| 1855 | }], |
| 1856 | }), |
| 1857 | sync: Ok(SkillSyncOutcome::Done { |
| 1858 | total: 1, |
| 1859 | downloaded: 1, |
| 1860 | fresh: 0, |
| 1861 | failed: 0, |
| 1862 | entries: vec![SkillSyncEntry::Downloaded { |
| 1863 | name: "demo".into(), |
| 1864 | path: "/cache/demo".into(), |
| 1865 | }], |
| 1866 | }), |
| 1867 | review: Ok(ReviewOutcome::Ready), |
| 1868 | snapshots: vec![SnapshotEntry { |
| 1869 | id: "abcdef123456".into(), |
| 1870 | label: "pre-turn:1".into(), |
| 1871 | timestamp: 1_700_000_000, |
| 1872 | }], |
| 1873 | restore_ok: true, |
| 1874 | approval: CommandApprovalState { |
| 1875 | yolo: true, |
| 1876 | trust_mode: false, |
| 1877 | }, |
| 1878 | } |
| 1879 | } |
| 1880 | } |
| 1881 | |
| 1882 | impl CommandSkillGroupContext for FakeSkillGroup { |
| 1883 | fn skill_registry_projection(&self) -> SkillRegistryProjection { |
| 1884 | self.projection.clone() |
| 1885 | } |
| 1886 | |
| 1887 | fn activate_skill( |
| 1888 | &mut self, |
| 1889 | _name: &str, |
| 1890 | ) -> Result<SkillActivationOutcome, SkillActivationError> { |
| 1891 | self.activation_result.clone() |
| 1892 | } |
| 1893 | |
| 1894 | fn install_skill( |
| 1895 | &mut self, |
| 1896 | _scope: Option<SkillTargetScope>, |
| 1897 | _spec: &str, |
| 1898 | ) -> Result<SkillMutationReceipt, String> { |
| 1899 | Ok(self.receipt.clone()) |
| 1900 | } |
| 1901 | |
| 1902 | fn update_skill( |
| 1903 | &mut self, |
| 1904 | _scope: Option<SkillTargetScope>, |
| 1905 | _name: &str, |
| 1906 | ) -> Result<SkillMutationReceipt, String> { |
| 1907 | Ok(self.receipt.clone()) |
| 1908 | } |
| 1909 | |
| 1910 | fn uninstall_skill( |
| 1911 | &mut self, |
| 1912 | _scope: Option<SkillTargetScope>, |
| 1913 | _name: &str, |
| 1914 | ) -> Result<SkillMutationReceipt, String> { |
| 1915 | Ok(self.receipt.clone()) |
| 1916 | } |
| 1917 | |
| 1918 | fn trust_skill( |
| 1919 | &mut self, |
| 1920 | _scope: Option<SkillTargetScope>, |
| 1921 | _name: &str, |
| 1922 | ) -> Result<SkillMutationReceipt, String> { |
| 1923 | Ok(self.receipt.clone()) |
| 1924 | } |
| 1925 | |
| 1926 | fn fetch_remote_registry(&mut self) -> Result<RemoteRegistryOutcome, String> { |
| 1927 | self.remote.clone() |
| 1928 | } |
| 1929 | |
| 1930 | fn recommend_skills(&mut self, task: &str) -> Result<Vec<SkillRecommendation>, String> { |
| 1931 | Ok(vec![SkillRecommendation { |
| 1932 | name: format!("rec-{task}"), |
| 1933 | description: Some("Recommended".into()), |
| 1934 | matched_terms: vec!["term".into()], |
| 1935 | }]) |
| 1936 | } |
| 1937 | |
| 1938 | fn sync_registry(&mut self) -> Result<SkillSyncOutcome, String> { |
| 1939 | self.sync.clone() |
| 1940 | } |
| 1941 | |
| 1942 | fn run_review(&mut self) -> Result<ReviewOutcome, String> { |
| 1943 | self.review.clone() |
| 1944 | } |
| 1945 | |
| 1946 | fn snapshot_list(&mut self, _limit: usize) -> Result<Vec<SnapshotEntry>, String> { |
| 1947 | Ok(self.snapshots.clone()) |
| 1948 | } |
| 1949 | |
| 1950 | fn restore_snapshot(&mut self, _id: &str) -> Result<(), String> { |
| 1951 | if self.restore_ok { |
| 1952 | Ok(()) |
| 1953 | } else { |
| 1954 | Err("Restore failed: boom".into()) |
| 1955 | } |
| 1956 | } |
| 1957 | |
| 1958 | fn approval_state(&self) -> CommandApprovalState { |
| 1959 | self.approval |
| 1960 | } |
| 1961 | } |
| 1962 | |
| 1963 | #[test] |
| 1964 | fn skill_group_facet_is_object_safe_and_typed() { |
| 1965 | fn project(_: &dyn CommandSkillGroupContext) {} |
| 1966 | project(&FakeSkillGroup::new()); |
| 1967 | |
| 1968 | let group = FakeSkillGroup::new(); |
| 1969 | let projection = group.skill_registry_projection(); |
| 1970 | assert_eq!(projection.total, 1); |
| 1971 | assert_eq!(projection.entries[0].name, "demo"); |
| 1972 | assert!(group.approval_state().yolo); |
| 1973 | } |
| 1974 | |
| 1975 | #[test] |
| 1976 | fn skill_registry_projection_preserves_semantic_values() { |
| 1977 | let group = FakeSkillGroup::new(); |
| 1978 | let projection = group.skill_registry_projection(); |
| 1979 | assert_eq!(projection.workspace, "/ws"); |
| 1980 | assert_eq!(projection.skills_dir, "/ws/.codewhale/skills"); |
| 1981 | assert_eq!(projection.mode_label, "compatible"); |
| 1982 | assert_eq!(projection.dirs, vec!["/ws/.codewhale/skills"]); |
| 1983 | assert_eq!(projection.warnings, vec!["one warning"]); |
| 1984 | assert_eq!(projection.entries.len(), 1); |
| 1985 | let entry = &projection.entries[0]; |
| 1986 | assert_eq!(entry.name, "demo"); |
| 1987 | assert_eq!(entry.description, "Demo skill"); |
| 1988 | assert_eq!(entry.source, SkillSourceKind::Native); |
| 1989 | assert_eq!( |
| 1990 | entry.path.as_deref(), |
| 1991 | Some("/ws/.codewhale/skills/demo/SKILL.md") |
| 1992 | ); |
| 1993 | assert_eq!(entry.bundled_tier, None); |
| 1994 | } |
| 1995 | |
| 1996 | #[test] |
| 1997 | fn skill_bundled_tier_headings_are_stable() { |
| 1998 | assert_eq!(SkillBundledTier::CoreAgentic.heading(), "Core agentic"); |
| 1999 | assert_eq!( |
| 2000 | SkillBundledTier::FormatTooling.heading(), |
| 2001 | "Format & tooling" |
| 2002 | ); |
| 2003 | } |
| 2004 | |
| 2005 | #[test] |
| 2006 | fn skill_mutation_receipt_preserves_outcome_variants() { |
| 2007 | let installed = FakeSkillGroup::new().receipt; |
| 2008 | assert_eq!(installed.name, "demo"); |
| 2009 | assert_eq!(installed.outcome, SkillMutationOutcome::Installed); |
| 2010 | |
| 2011 | let denied = SkillMutationReceipt { |
| 2012 | outcome: SkillMutationOutcome::NetworkDenied("acme.com".into()), |
| 2013 | ..installed.clone() |
| 2014 | }; |
| 2015 | assert_eq!( |
| 2016 | denied.outcome, |
| 2017 | SkillMutationOutcome::NetworkDenied("acme.com".into()) |
| 2018 | ); |
| 2019 | |
| 2020 | let approval = SkillMutationReceipt { |
| 2021 | outcome: SkillMutationOutcome::NeedsApproval("acme.com".into()), |
| 2022 | ..installed.clone() |
| 2023 | }; |
| 2024 | assert_eq!( |
| 2025 | approval.outcome, |
| 2026 | SkillMutationOutcome::NeedsApproval("acme.com".into()) |
| 2027 | ); |
| 2028 | |
| 2029 | assert_ne!(installed.outcome, denied.outcome); |
| 2030 | assert_ne!(installed.outcome, approval.outcome); |
| 2031 | assert_ne!(denied.outcome, approval.outcome); |
| 2032 | } |
| 2033 | |
| 2034 | #[test] |
| 2035 | fn skill_source_kind_variants_are_distinguishable() { |
| 2036 | let native = SkillSourceKind::Native; |
| 2037 | let plugin = SkillSourceKind::Plugin { |
| 2038 | plugin_name: "acme".into(), |
| 2039 | plugin_id: "acme-1".into(), |
| 2040 | }; |
| 2041 | assert_ne!(native, plugin); |
| 2042 | assert_eq!( |
| 2043 | plugin, |
| 2044 | SkillSourceKind::Plugin { |
| 2045 | plugin_name: "acme".into(), |
| 2046 | plugin_id: "acme-1".into(), |
| 2047 | } |
| 2048 | ); |
| 2049 | } |
| 2050 | |
| 2051 | #[test] |
| 2052 | fn remote_registry_outcome_variants_are_distinguishable() { |
| 2053 | let loaded = RemoteRegistryOutcome::Loaded { |
| 2054 | entries: vec![RemoteSkillEntry { |
| 2055 | name: "demo".into(), |
| 2056 | description: None, |
| 2057 | source: "acme".into(), |
| 2058 | }], |
| 2059 | }; |
| 2060 | let approval = RemoteRegistryOutcome::NeedsApproval("acme.com".into()); |
| 2061 | let denied = RemoteRegistryOutcome::Denied("acme.com".into()); |
| 2062 | assert_ne!(loaded, approval); |
| 2063 | assert_ne!(loaded, denied); |
| 2064 | assert_ne!(approval, denied); |
| 2065 | } |
| 2066 | |
| 2067 | #[test] |
| 2068 | fn skill_sync_outcome_preserves_all_entry_variants() { |
| 2069 | let outcome = SkillSyncOutcome::Done { |
| 2070 | total: 4, |
| 2071 | downloaded: 1, |
| 2072 | fresh: 1, |
| 2073 | failed: 2, |
| 2074 | entries: vec![ |
| 2075 | SkillSyncEntry::Downloaded { |
| 2076 | name: "a".into(), |
| 2077 | path: "/cache/a".into(), |
| 2078 | }, |
| 2079 | SkillSyncEntry::Fresh { name: "b".into() }, |
| 2080 | SkillSyncEntry::Failed { |
| 2081 | name: "c".into(), |
| 2082 | reason: "boom".into(), |
| 2083 | }, |
| 2084 | SkillSyncEntry::Denied { |
| 2085 | name: "d".into(), |
| 2086 | host: "acme.com".into(), |
| 2087 | }, |
| 2088 | SkillSyncEntry::NeedsApproval { |
| 2089 | name: "e".into(), |
| 2090 | host: "acme.com".into(), |
| 2091 | }, |
| 2092 | ], |
| 2093 | }; |
| 2094 | let SkillSyncOutcome::Done { |
| 2095 | total, |
| 2096 | downloaded, |
| 2097 | fresh, |
| 2098 | failed, |
| 2099 | entries, |
| 2100 | } = &outcome |
| 2101 | else { |
| 2102 | panic!("expected Done"); |
| 2103 | }; |
| 2104 | assert_eq!(*total, 4); |
| 2105 | assert_eq!(*downloaded, 1); |
| 2106 | assert_eq!(*fresh, 1); |
| 2107 | assert_eq!(*failed, 2); |
| 2108 | assert_eq!(entries.len(), 5); |
| 2109 | assert!(matches!(entries[0], SkillSyncEntry::Downloaded { .. })); |
| 2110 | assert!(matches!(entries[1], SkillSyncEntry::Fresh { .. })); |
| 2111 | assert!(matches!(entries[2], SkillSyncEntry::Failed { .. })); |
| 2112 | assert!(matches!(entries[3], SkillSyncEntry::Denied { .. })); |
| 2113 | assert!(matches!(entries[4], SkillSyncEntry::NeedsApproval { .. })); |
| 2114 | } |
| 2115 | |
| 2116 | #[test] |
| 2117 | fn skill_sync_registry_policy_variants_are_distinguishable() { |
| 2118 | let approval = SkillSyncOutcome::RegistryNeedsApproval("acme.com".into()); |
| 2119 | let denied = SkillSyncOutcome::RegistryDenied("acme.com".into()); |
| 2120 | assert_ne!(approval, denied); |
| 2121 | assert!(matches!( |
| 2122 | approval, |
| 2123 | SkillSyncOutcome::RegistryNeedsApproval(host) if host == "acme.com" |
| 2124 | )); |
| 2125 | assert!(matches!( |
| 2126 | denied, |
| 2127 | SkillSyncOutcome::RegistryDenied(host) if host == "acme.com" |
| 2128 | )); |
| 2129 | } |
| 2130 | |
| 2131 | #[test] |
| 2132 | fn skill_activation_error_variants_are_distinguishable() { |
| 2133 | let mut group = FakeSkillGroup::new(); |
| 2134 | group.activation_result = Err(SkillActivationError::NotFound { |
| 2135 | requested: "missing".into(), |
| 2136 | available: vec!["demo".into()], |
| 2137 | warnings: vec![], |
| 2138 | }); |
| 2139 | let not_found = group.activate_skill("missing").unwrap_err(); |
| 2140 | match ¬_found { |
| 2141 | SkillActivationError::NotFound { |
| 2142 | requested, |
| 2143 | available, |
| 2144 | .. |
| 2145 | } => { |
| 2146 | assert_eq!(requested, "missing"); |
| 2147 | assert_eq!(available, &vec!["demo".to_string()]); |
| 2148 | } |
| 2149 | _ => panic!("expected NotFound"), |
| 2150 | } |
| 2151 | |
| 2152 | let mut group = FakeSkillGroup::new(); |
| 2153 | group.activation_result = Err(SkillActivationError::PluginRejected { |
| 2154 | name: "plug".into(), |
| 2155 | reason: "authority revoked".into(), |
| 2156 | }); |
| 2157 | let rejected = group.activate_skill("plug").unwrap_err(); |
| 2158 | match rejected { |
| 2159 | SkillActivationError::PluginRejected { name, reason } => { |
| 2160 | assert_eq!(name, "plug"); |
| 2161 | assert_eq!(reason, "authority revoked"); |
| 2162 | } |
| 2163 | _ => panic!("expected PluginRejected"), |
| 2164 | } |
| 2165 | } |
| 2166 | |
| 2167 | #[test] |
| 2168 | fn review_outcome_variants_are_distinguishable() { |
| 2169 | let mut group = FakeSkillGroup::new(); |
| 2170 | group.review = Ok(ReviewOutcome::NotFound { |
| 2171 | skills_dir: "/ws/skills".into(), |
| 2172 | global_dir: "/home/u/.codewhale/skills".into(), |
| 2173 | warnings: vec!["w".into()], |
| 2174 | }); |
| 2175 | let outcome = group.run_review().unwrap(); |
| 2176 | match outcome { |
| 2177 | ReviewOutcome::NotFound { |
| 2178 | skills_dir, |
| 2179 | global_dir, |
| 2180 | warnings, |
| 2181 | } => { |
| 2182 | assert_eq!(skills_dir, "/ws/skills"); |
| 2183 | assert_eq!(global_dir, "/home/u/.codewhale/skills"); |
| 2184 | assert_eq!(warnings, vec!["w".to_string()]); |
| 2185 | } |
| 2186 | _ => panic!("expected NotFound"), |
| 2187 | } |
| 2188 | } |
| 2189 | |
| 2190 | #[test] |
| 2191 | fn snapshot_and_approval_values_preserve_semantics() { |
| 2192 | let mut group = FakeSkillGroup::new(); |
| 2193 | let snapshots = group.snapshot_list(20).unwrap(); |
| 2194 | assert_eq!(snapshots.len(), 1); |
| 2195 | assert_eq!(snapshots[0].id, "abcdef123456"); |
| 2196 | assert_eq!(snapshots[0].label, "pre-turn:1"); |
| 2197 | assert_eq!(snapshots[0].timestamp, 1_700_000_000); |
| 2198 | |
| 2199 | let approval = group.approval_state(); |
| 2200 | assert!(approval.yolo); |
| 2201 | assert!(!approval.trust_mode); |
| 2202 | } |
| 2203 | |
| 2204 | #[test] |
| 2205 | fn skill_group_facet_transports_through_envelope_when_declared() { |
| 2206 | let mut group = FakeSkillGroup::new(); |
| 2207 | let parts = CommandContexts::empty() |
| 2208 | .with_skill_group(&mut group) |
| 2209 | .into_parts(); |
| 2210 | assert!(parts.skill_group.is_some()); |
| 2211 | assert!(parts.session.is_none()); |
| 2212 | assert!(parts.project.is_none()); |
| 2213 | |
| 2214 | // /skill combines skill_group with SKILLS for baseline cache refreshes. |
| 2215 | let mut skills = Skills; |
| 2216 | let parts = CommandContexts::empty() |
| 2217 | .with_skill_group(&mut group) |
| 2218 | .with_skills(&mut skills) |
| 2219 | .into_parts(); |
| 2220 | assert!(parts.skill_group.is_some()); |
| 2221 | assert!(parts.skills.is_some()); |
| 2222 | assert!(parts.workspace.is_none()); |
| 2223 | } |
| 2224 | |
| 2225 | #[test] |
| 2226 | fn envelope_rejects_duplicate_skill_group_slot_deterministically() { |
| 2227 | let mut a = FakeSkillGroup::new(); |
| 2228 | let mut b = FakeSkillGroup::new(); |
| 2229 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 2230 | CommandContexts::empty() |
| 2231 | .with_skill_group(&mut a) |
| 2232 | .with_skill_group(&mut b); |
| 2233 | })); |
| 2234 | assert!(result.is_err(), "duplicate skill_group slot must assert"); |
| 2235 | } |
| 2236 | |
| 2237 | /// Regression: the shared FEAT-015 `CommandSkillsContext` surface is unchanged |
| 2238 | /// (getters + cache refresh only, no setter) and still transports through the |
| 2239 | /// envelope alongside the new skill-group facet (D2). |
| 2240 | #[test] |
| 2241 | fn shared_skills_facet_surface_remains_read_only_and_transportable() { |
| 2242 | let mut skills = Skills; |
| 2243 | let active = skills.active_skill(); |
| 2244 | assert_eq!(active, None); |
| 2245 | assert_eq!(skills.active_skill_provenance(), None); |
| 2246 | skills.refresh_skill_cache(); |
| 2247 | |
| 2248 | let mut group = FakeSkillGroup::new(); |
| 2249 | let parts = CommandContexts::empty() |
| 2250 | .with_skills(&mut skills) |
| 2251 | .with_skill_group(&mut group) |
| 2252 | .into_parts(); |
| 2253 | assert!(parts.skills.is_some()); |
| 2254 | assert!(parts.skill_group.is_some()); |
| 2255 | } |
| 2256 | |
| 2257 | // --------------------------------------------------------------------------- |
| 2258 | // FEAT-023: session lifecycle contract (D2/D3/D6). |
| 2259 | // --------------------------------------------------------------------------- |
| 2260 | |
| 2261 | #[test] |
| 2262 | fn lifecycle_capability_is_stable_distinct_and_non_conflicting() { |
| 2263 | let lifecycle = CommandCapabilities::SESSION_LIFECYCLE; |
| 2264 | for existing in [ |
| 2265 | CommandCapabilities::NONE, |
| 2266 | CommandCapabilities::SESSION, |
| 2267 | CommandCapabilities::MODEL, |
| 2268 | CommandCapabilities::COST, |
| 2269 | CommandCapabilities::MODE_POLICY, |
| 2270 | CommandCapabilities::SYSTEM_PROMPT, |
| 2271 | CommandCapabilities::SKILLS, |
| 2272 | CommandCapabilities::WORKSPACE, |
| 2273 | CommandCapabilities::PRESENTATION, |
| 2274 | CommandCapabilities::MEDIA, |
| 2275 | CommandCapabilities::MEMORY, |
| 2276 | CommandCapabilities::PROJECT, |
| 2277 | CommandCapabilities::SKILL_GROUP, |
| 2278 | CommandCapabilities::PLUGIN, |
| 2279 | ] { |
| 2280 | assert_ne!(lifecycle, existing, "SESSION_LIFECYCLE must not collide"); |
| 2281 | } |
| 2282 | assert!(!CommandCapabilities::NONE.contains(lifecycle)); |
| 2283 | assert!(lifecycle.contains(lifecycle)); |
| 2284 | assert!( |
| 2285 | lifecycle |
| 2286 | .union(CommandCapabilities::SESSION) |
| 2287 | .contains(lifecycle) |
| 2288 | ); |
| 2289 | assert!( |
| 2290 | lifecycle |
| 2291 | .union(CommandCapabilities::SESSION) |
| 2292 | .contains(CommandCapabilities::SESSION) |
| 2293 | ); |
| 2294 | } |
| 2295 | |
| 2296 | /// Deterministic fake lifecycle facet: every delegate returns canned portable |
| 2297 | /// values or error text so the contract transport is exercised exactly. |
| 2298 | #[derive(Default)] |
| 2299 | struct FakeLifecycle { |
| 2300 | blocked: bool, |
| 2301 | leaf_hint: Option<String>, |
| 2302 | branch_outcome: Option<SessionBranchOutcome>, |
| 2303 | branch_error: Option<String>, |
| 2304 | tree: Option<Result<TreeBodyProjection, String>>, |
| 2305 | save: Option<Result<SessionSaveReceipt, String>>, |
| 2306 | fork_active: Option<Result<SessionForkReceipt, String>>, |
| 2307 | fork_from: Option<Result<SessionForkFromReceipt, String>>, |
| 2308 | fresh: Option<Result<SessionNewReceipt, String>>, |
| 2309 | load: Option<Result<PathBuf, String>>, |
| 2310 | picker: Option<String>, |
| 2311 | archived: Option<Result<SessionArchiveReceipt, String>>, |
| 2312 | prune: Option<Result<usize, String>>, |
| 2313 | } |
| 2314 | |
| 2315 | impl CommandSessionLifecycleContext for FakeLifecycle { |
| 2316 | fn transition_blocked(&self) -> bool { |
| 2317 | self.blocked |
| 2318 | } |
| 2319 | fn transition_blockers(&self) -> Vec<String> { |
| 2320 | Vec::new() |
| 2321 | } |
| 2322 | fn branch_current_leaf_hint(&self) -> Option<String> { |
| 2323 | self.leaf_hint.clone() |
| 2324 | } |
| 2325 | fn branch_to(&mut self, entry_id: &str) -> Result<SessionBranchOutcome, String> { |
| 2326 | if let Some(err) = &self.branch_error { |
| 2327 | return Err(err.clone()); |
| 2328 | } |
| 2329 | self.branch_outcome |
| 2330 | .clone() |
| 2331 | .ok_or_else(|| format!("unexpected branch_to({entry_id}) on empty fake")) |
| 2332 | } |
| 2333 | fn tree_body(&self) -> Result<TreeBodyProjection, String> { |
| 2334 | self.tree |
| 2335 | .clone() |
| 2336 | .unwrap_or(Ok(TreeBodyProjection::NoSession)) |
| 2337 | } |
| 2338 | fn save_session( |
| 2339 | &mut self, |
| 2340 | explicit_path: Option<String>, |
| 2341 | ) -> Result<SessionSaveReceipt, String> { |
| 2342 | self.save |
| 2343 | .clone() |
| 2344 | .ok_or_else(|| format!("unexpected save_session({explicit_path:?}) on empty fake"))? |
| 2345 | } |
| 2346 | fn fork_active(&mut self) -> Result<SessionForkReceipt, String> { |
| 2347 | self.fork_active |
| 2348 | .clone() |
| 2349 | .ok_or_else(|| "unexpected fork_active() on empty fake".to_string())? |
| 2350 | } |
| 2351 | fn fork_from(&mut self, id: &str) -> Result<SessionForkFromReceipt, String> { |
| 2352 | self.fork_from |
| 2353 | .clone() |
| 2354 | .ok_or_else(|| format!("unexpected fork_from({id}) on empty fake"))? |
| 2355 | } |
| 2356 | fn fresh_session( |
| 2357 | &mut self, |
| 2358 | force: bool, |
| 2359 | conversation_mode: Option<&str>, |
| 2360 | ) -> Result<SessionNewReceipt, String> { |
| 2361 | self.fresh.clone().ok_or_else(|| { |
| 2362 | format!("unexpected fresh_session({force}, {conversation_mode:?}) on empty fake") |
| 2363 | })? |
| 2364 | } |
| 2365 | fn load_session(&mut self, path: &str) -> Result<PathBuf, String> { |
| 2366 | self.load |
| 2367 | .clone() |
| 2368 | .ok_or_else(|| format!("unexpected load_session({path}) on empty fake"))? |
| 2369 | } |
| 2370 | fn open_picker(&mut self, preselected: Option<String>) { |
| 2371 | self.picker = preselected; |
| 2372 | } |
| 2373 | fn set_archived( |
| 2374 | &mut self, |
| 2375 | session_id: &str, |
| 2376 | archived: bool, |
| 2377 | ) -> Result<SessionArchiveReceipt, String> { |
| 2378 | self.archived.clone().ok_or_else(|| { |
| 2379 | format!("unexpected set_archived({session_id}, {archived}) on empty fake") |
| 2380 | })? |
| 2381 | } |
| 2382 | fn prune_sessions(&mut self, days: u64) -> Result<usize, String> { |
| 2383 | self.prune |
| 2384 | .clone() |
| 2385 | .ok_or_else(|| format!("unexpected prune_sessions({days}) on empty fake"))? |
| 2386 | } |
| 2387 | } |
| 2388 | |
| 2389 | fn lifecycle_sync_payload(session_id: Option<&str>) -> SessionSyncPayload { |
| 2390 | SessionSyncPayload { |
| 2391 | session_id: session_id.map(str::to_string), |
| 2392 | messages: vec![Message { |
| 2393 | role: Role::User, |
| 2394 | content: vec![ContentBlock::Text { |
| 2395 | text: "hello lifecycle".to_string(), |
| 2396 | cache_control: None, |
| 2397 | }], |
| 2398 | }], |
| 2399 | system_prompt: Some(SystemPrompt::Text("prompt".to_string())), |
| 2400 | model: "lifecycle-model".to_string(), |
| 2401 | workspace: PathBuf::from("/workspace/lifecycle"), |
| 2402 | mode: CommandMode::Plan, |
| 2403 | agent_preset: None, |
| 2404 | } |
| 2405 | } |
| 2406 | |
| 2407 | #[test] |
| 2408 | fn lifecycle_facet_is_object_safe_and_transports_every_outcome() { |
| 2409 | // Object safety: usable behind a single `dyn` reference. |
| 2410 | fn accepts_dyn(_: &dyn CommandSessionLifecycleContext) {} |
| 2411 | fn accepts_dyn_mut(_: &mut dyn CommandSessionLifecycleContext) {} |
| 2412 | |
| 2413 | let mut fake = FakeLifecycle { |
| 2414 | blocked: true, |
| 2415 | leaf_hint: Some("entry-42".to_string()), |
| 2416 | branch_outcome: Some(SessionBranchOutcome { |
| 2417 | leaf_display: "entry-43".to_string(), |
| 2418 | journal_entries_before: 7, |
| 2419 | sync: lifecycle_sync_payload(Some("branched-session")), |
| 2420 | }), |
| 2421 | tree: Some(Ok(TreeBodyProjection::Journal { |
| 2422 | rendered: "rendered journal".to_string(), |
| 2423 | })), |
| 2424 | save: Some(Ok(SessionSaveReceipt { |
| 2425 | display_path: "/tmp/session.json".to_string(), |
| 2426 | truncated_id: "abc123".to_string(), |
| 2427 | })), |
| 2428 | fork_active: Some(Ok(SessionForkReceipt { |
| 2429 | parent_label: "parent".to_string(), |
| 2430 | fork_label: "child".to_string(), |
| 2431 | sync: lifecycle_sync_payload(Some("child")), |
| 2432 | })), |
| 2433 | fork_from: Some(Ok(SessionForkFromReceipt { |
| 2434 | parent_label: "source".to_string(), |
| 2435 | fork_label: "sibling".to_string(), |
| 2436 | spawn_depth: 3, |
| 2437 | sync: lifecycle_sync_payload(Some("sibling")), |
| 2438 | })), |
| 2439 | fresh: Some(Ok(SessionNewReceipt { |
| 2440 | truncated_id: "new-id".to_string(), |
| 2441 | sync: lifecycle_sync_payload(Some("new-id")), |
| 2442 | })), |
| 2443 | load: Some(Ok(PathBuf::from("/tmp/loaded.json"))), |
| 2444 | archived: Some(Ok(SessionArchiveReceipt { |
| 2445 | truncated_id: "arch-1".to_string(), |
| 2446 | title: "Archive Title".to_string(), |
| 2447 | })), |
| 2448 | prune: Some(Ok(3)), |
| 2449 | ..FakeLifecycle::default() |
| 2450 | }; |
| 2451 | accepts_dyn(&fake); |
| 2452 | accepts_dyn_mut(&mut fake); |
| 2453 | |
| 2454 | assert!(fake.transition_blocked()); |
| 2455 | assert_eq!(fake.branch_current_leaf_hint().as_deref(), Some("entry-42")); |
| 2456 | let branch = fake.branch_to("entry-43").expect("branch ok"); |
| 2457 | assert_eq!(branch.leaf_display, "entry-43"); |
| 2458 | assert_eq!(branch.journal_entries_before, 7); |
| 2459 | assert_eq!(branch.sync.session_id.as_deref(), Some("branched-session")); |
| 2460 | assert_eq!(branch.sync.messages.len(), 1); |
| 2461 | assert_eq!(branch.sync.mode, CommandMode::Plan); |
| 2462 | match fake.tree_body().expect("tree ok") { |
| 2463 | TreeBodyProjection::Journal { rendered } => assert_eq!(rendered, "rendered journal"), |
| 2464 | other => panic!("expected Journal projection, got {other:?}"), |
| 2465 | } |
| 2466 | let save = fake |
| 2467 | .save_session(Some("/tmp/session.json".to_string())) |
| 2468 | .expect("save ok"); |
| 2469 | assert_eq!(save.display_path, "/tmp/session.json"); |
| 2470 | assert_eq!(save.truncated_id, "abc123"); |
| 2471 | let active = fake.fork_active().expect("active fork ok"); |
| 2472 | assert_eq!(active.parent_label, "parent"); |
| 2473 | assert_eq!(active.fork_label, "child"); |
| 2474 | assert_eq!(active.sync.session_id.as_deref(), Some("child")); |
| 2475 | assert_eq!(active.sync.messages.len(), 1); |
| 2476 | assert_eq!(active.sync.mode, CommandMode::Plan); |
| 2477 | let explicit = fake.fork_from("source").expect("explicit fork ok"); |
| 2478 | assert_eq!(explicit.spawn_depth, 3); |
| 2479 | assert_eq!( |
| 2480 | explicit.sync.workspace, |
| 2481 | PathBuf::from("/workspace/lifecycle") |
| 2482 | ); |
| 2483 | let fresh = fake.fresh_session(true, None).expect("fresh ok"); |
| 2484 | assert_eq!(fresh.truncated_id, "new-id"); |
| 2485 | assert_eq!(fresh.sync.messages.len(), 1); |
| 2486 | let loaded = fake.load_session("loaded.json").expect("load ok"); |
| 2487 | assert_eq!(loaded, PathBuf::from("/tmp/loaded.json")); |
| 2488 | fake.open_picker(Some("arch-1".to_string())); |
| 2489 | assert_eq!(fake.picker.as_deref(), Some("arch-1")); |
| 2490 | let archived = fake.set_archived("arch-1", true).expect("archive ok"); |
| 2491 | assert_eq!(archived.truncated_id, "arch-1"); |
| 2492 | assert_eq!(archived.title, "Archive Title"); |
| 2493 | assert_eq!(fake.prune_sessions(30).expect("prune ok"), 3); |
| 2494 | } |
| 2495 | |
| 2496 | #[test] |
| 2497 | fn lifecycle_error_text_and_empty_states_transport_exactly() { |
| 2498 | let mut fake = FakeLifecycle { |
| 2499 | branch_error: Some("could not load session x: boom".to_string()), |
| 2500 | tree: Some(Err("could not open sessions directory: boom".to_string())), |
| 2501 | save: Some(Err("Failed to save session: boom".to_string())), |
| 2502 | load: Some(Err("Failed to read session file: boom".to_string())), |
| 2503 | archived: Some(Err("archive failed: boom".to_string())), |
| 2504 | prune: Some(Err("prune failed: boom".to_string())), |
| 2505 | ..FakeLifecycle::default() |
| 2506 | }; |
| 2507 | assert_eq!( |
| 2508 | fake.branch_to("x").unwrap_err(), |
| 2509 | "could not load session x: boom" |
| 2510 | ); |
| 2511 | assert_eq!( |
| 2512 | fake.tree_body().unwrap_err(), |
| 2513 | "could not open sessions directory: boom" |
| 2514 | ); |
| 2515 | assert_eq!( |
| 2516 | fake.save_session(None).unwrap_err(), |
| 2517 | "Failed to save session: boom" |
| 2518 | ); |
| 2519 | assert_eq!( |
| 2520 | fake.load_session("missing.json").unwrap_err(), |
| 2521 | "Failed to read session file: boom" |
| 2522 | ); |
| 2523 | assert_eq!( |
| 2524 | fake.set_archived("a", false).unwrap_err(), |
| 2525 | "archive failed: boom" |
| 2526 | ); |
| 2527 | assert_eq!(fake.prune_sessions(7).unwrap_err(), "prune failed: boom"); |
| 2528 | |
| 2529 | let mut empty = FakeLifecycle::default(); |
| 2530 | assert!(!empty.transition_blocked()); |
| 2531 | assert_eq!(empty.branch_current_leaf_hint(), None); |
| 2532 | assert!(matches!( |
| 2533 | empty.tree_body().expect("default tree"), |
| 2534 | TreeBodyProjection::NoSession |
| 2535 | )); |
| 2536 | empty.open_picker(None); |
| 2537 | assert_eq!(empty.picker, None); |
| 2538 | } |
| 2539 | |
| 2540 | #[test] |
| 2541 | fn envelope_lifecycle_slot_is_independent_and_rejects_duplicates() { |
| 2542 | let mut first = FakeLifecycle::default(); |
| 2543 | let mut second = FakeLifecycle::default(); |
| 2544 | |
| 2545 | let parts = CommandContexts::empty() |
| 2546 | .with_lifecycle(&mut first) |
| 2547 | .into_parts(); |
| 2548 | assert!( |
| 2549 | parts.lifecycle.is_some(), |
| 2550 | "lifecycle slot must be present when declared" |
| 2551 | ); |
| 2552 | assert!( |
| 2553 | parts.session.is_none() && parts.plugin.is_none() && parts.skill_group.is_none(), |
| 2554 | "unrelated slots must stay absent (exact exposure)" |
| 2555 | ); |
| 2556 | |
| 2557 | let bare = CommandContexts::empty().into_parts(); |
| 2558 | assert!( |
| 2559 | bare.lifecycle.is_none(), |
| 2560 | "undeclared lifecycle stays absent" |
| 2561 | ); |
| 2562 | |
| 2563 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 2564 | CommandContexts::empty() |
| 2565 | .with_lifecycle(&mut first) |
| 2566 | .with_lifecycle(&mut second); |
| 2567 | })); |
| 2568 | assert!( |
| 2569 | result.is_err(), |
| 2570 | "duplicate lifecycle slot must assert deterministically" |
| 2571 | ); |
| 2572 | |
| 2573 | // Reading through the dyn facet works after insertion. |
| 2574 | first.blocked = true; |
| 2575 | let inserted = CommandContexts::empty().with_lifecycle(&mut first); |
| 2576 | let lifecycle = inserted.into_parts().lifecycle.expect("inserted lifecycle"); |
| 2577 | assert!(lifecycle.transition_blocked()); |
| 2578 | } |
| 2579 | |
| 2580 | // --------------------------------------------------------------------------- |
| 2581 | // FEAT-024: session control contract (D2/D3/D6/D7). |
| 2582 | // --------------------------------------------------------------------------- |
| 2583 | |
| 2584 | #[test] |
| 2585 | fn control_capability_is_stable_distinct_and_non_conflicting() { |
| 2586 | let control = CommandCapabilities::SESSION_CONTROL; |
| 2587 | for existing in [ |
| 2588 | CommandCapabilities::NONE, |
| 2589 | CommandCapabilities::SESSION, |
| 2590 | CommandCapabilities::MODEL, |
| 2591 | CommandCapabilities::COST, |
| 2592 | CommandCapabilities::MODE_POLICY, |
| 2593 | CommandCapabilities::SYSTEM_PROMPT, |
| 2594 | CommandCapabilities::SKILLS, |
| 2595 | CommandCapabilities::WORKSPACE, |
| 2596 | CommandCapabilities::PRESENTATION, |
| 2597 | CommandCapabilities::MEDIA, |
| 2598 | CommandCapabilities::MEMORY, |
| 2599 | CommandCapabilities::PROJECT, |
| 2600 | CommandCapabilities::SKILL_GROUP, |
| 2601 | CommandCapabilities::PLUGIN, |
| 2602 | CommandCapabilities::SESSION_LIFECYCLE, |
| 2603 | ] { |
| 2604 | assert_ne!(control, existing, "SESSION_CONTROL must not collide"); |
| 2605 | } |
| 2606 | assert!(!CommandCapabilities::NONE.contains(control)); |
| 2607 | assert!(control.contains(control)); |
| 2608 | assert!( |
| 2609 | control |
| 2610 | .union(CommandCapabilities::PRESENTATION) |
| 2611 | .contains(control) |
| 2612 | ); |
| 2613 | assert!( |
| 2614 | control |
| 2615 | .union(CommandCapabilities::PRESENTATION) |
| 2616 | .contains(CommandCapabilities::PRESENTATION) |
| 2617 | ); |
| 2618 | assert!(!CommandCapabilities::SESSION_LIFECYCLE.contains(control)); |
| 2619 | assert!(!control.contains(CommandCapabilities::SESSION_LIFECYCLE)); |
| 2620 | // Storage remains u16-backed by construction: bit 14 (1 << 14 = 16384) |
| 2621 | // fits the backing `u16` without the speculative widening FEAT-023's |
| 2622 | // maintainer review ruled out. |
| 2623 | } |
| 2624 | |
| 2625 | /// Deterministic fake control facet: every delegate returns canned portable |
| 2626 | /// values or error text so the contract transport is exercised exactly. |
| 2627 | #[derive(Default)] |
| 2628 | struct FakeControl { |
| 2629 | blocked: bool, |
| 2630 | relay: Option<RelayProjection>, |
| 2631 | resume: Option<Result<ResumeSource, String>>, |
| 2632 | import: Option<Result<ResumeImportReceipt, String>>, |
| 2633 | sanitized_title: Option<String>, |
| 2634 | rename: Option<Result<SessionTitleReceipt, String>>, |
| 2635 | title_report: Option<TitleReport>, |
| 2636 | set_title: Option<Result<(), String>>, |
| 2637 | clear_title: Option<Result<(), String>>, |
| 2638 | remote_status: Option<String>, |
| 2639 | remote_link: Option<Option<RemoteLink>>, |
| 2640 | browser_open: Option<RemoteOpenOutcome>, |
| 2641 | start_info: Option<RemoteStartInfo>, |
| 2642 | stop_refusal: Option<Option<String>>, |
| 2643 | hosted: Option<Option<HostedWorkTarget>>, |
| 2644 | } |
| 2645 | |
| 2646 | impl CommandSessionControlContext for FakeControl { |
| 2647 | fn transition_blocked(&self) -> bool { |
| 2648 | self.blocked |
| 2649 | } |
| 2650 | fn transition_blockers(&self) -> Vec<String> { |
| 2651 | Vec::new() |
| 2652 | } |
| 2653 | fn relay_projection(&self) -> RelayProjection { |
| 2654 | self.relay |
| 2655 | .clone() |
| 2656 | .expect("unexpected relay_projection() on empty fake") |
| 2657 | } |
| 2658 | fn open_resume_picker(&mut self) {} |
| 2659 | fn resolve_resume_source(&mut self, raw: &str) -> Result<ResumeSource, String> { |
| 2660 | self.resume.clone().unwrap_or_else(|| { |
| 2661 | Err(format!( |
| 2662 | "unexpected resolve_resume_source({raw}) on empty fake" |
| 2663 | )) |
| 2664 | }) |
| 2665 | } |
| 2666 | fn import_session_file(&mut self, path: PathBuf) -> Result<ResumeImportReceipt, String> { |
| 2667 | self.import.clone().unwrap_or_else(|| { |
| 2668 | Err(format!( |
| 2669 | "unexpected import_session_file({path:?}) on empty fake" |
| 2670 | )) |
| 2671 | }) |
| 2672 | } |
| 2673 | fn sanitize_session_title(&self, raw: &str) -> String { |
| 2674 | self.sanitized_title |
| 2675 | .clone() |
| 2676 | .unwrap_or_else(|| raw.to_string()) |
| 2677 | } |
| 2678 | fn rename_session(&mut self, title: &str) -> Result<SessionTitleReceipt, String> { |
| 2679 | self.rename |
| 2680 | .clone() |
| 2681 | .unwrap_or_else(|| Err(format!("unexpected rename_session({title}) on empty fake"))) |
| 2682 | } |
| 2683 | fn title_report(&self) -> TitleReport { |
| 2684 | self.title_report |
| 2685 | .clone() |
| 2686 | .expect("unexpected title_report() on empty fake") |
| 2687 | } |
| 2688 | fn set_window_title(&mut self, title: String) -> Result<(), String> { |
| 2689 | self.set_title.clone().unwrap_or_else(|| { |
| 2690 | Err(format!( |
| 2691 | "unexpected set_window_title({title}) on empty fake" |
| 2692 | )) |
| 2693 | }) |
| 2694 | } |
| 2695 | fn clear_window_title(&mut self) -> Result<(), String> { |
| 2696 | self.clear_title |
| 2697 | .clone() |
| 2698 | .unwrap_or_else(|| Err("unexpected clear_window_title() on empty fake".to_string())) |
| 2699 | } |
| 2700 | fn composer_color(&self) -> Option<String> { |
| 2701 | None |
| 2702 | } |
| 2703 | fn set_composer_color(&mut self, color: Option<String>) -> Result<(), String> { |
| 2704 | Err(format!( |
| 2705 | "unexpected set_composer_color({color:?}) on empty fake" |
| 2706 | )) |
| 2707 | } |
| 2708 | fn remote_status(&self) -> String { |
| 2709 | self.remote_status |
| 2710 | .clone() |
| 2711 | .expect("unexpected remote_status() on empty fake") |
| 2712 | } |
| 2713 | fn remote_link(&self) -> Option<RemoteLink> { |
| 2714 | self.remote_link |
| 2715 | .clone() |
| 2716 | .expect("unexpected remote_link() on empty fake") |
| 2717 | } |
| 2718 | fn remote_browser_open(&self) -> RemoteOpenOutcome { |
| 2719 | self.browser_open |
| 2720 | .clone() |
| 2721 | .expect("unexpected remote_browser_open() on empty fake") |
| 2722 | } |
| 2723 | fn remote_start_info(&self) -> RemoteStartInfo { |
| 2724 | self.start_info |
| 2725 | .clone() |
| 2726 | .expect("unexpected remote_start_info() on empty fake") |
| 2727 | } |
| 2728 | fn remote_stop_refusal(&self) -> Option<String> { |
| 2729 | self.stop_refusal |
| 2730 | .clone() |
| 2731 | .expect("unexpected remote_stop_refusal() on empty fake") |
| 2732 | } |
| 2733 | fn resolve_hosted_work_target(&self) -> Option<HostedWorkTarget> { |
| 2734 | self.hosted |
| 2735 | .clone() |
| 2736 | .expect("unexpected resolve_hosted_work_target() on empty fake") |
| 2737 | } |
| 2738 | } |
| 2739 | |
| 2740 | fn control_relay_projection() -> RelayProjection { |
| 2741 | RelayProjection { |
| 2742 | compact_template: "# Session relay".to_string(), |
| 2743 | handoff_path: ".codewhale/handoff.md".to_string(), |
| 2744 | workspace: "/workspace/control".to_string(), |
| 2745 | mode: "operate".to_string(), |
| 2746 | model: "control-model".to_string(), |
| 2747 | goal_objective: Some("ship the slice".to_string()), |
| 2748 | goal_token_budget: Some(42_000), |
| 2749 | todos: TodoProjection::Body("- [ ] port relay".to_string()), |
| 2750 | plan: PlanProjection::Sections(PlanSections { |
| 2751 | title: Some("Plan title".to_string()), |
| 2752 | items: vec![PlanStep { |
| 2753 | status: PlanStepStatus::InProgress, |
| 2754 | text: "port the control slice".to_string(), |
| 2755 | }], |
| 2756 | ..PlanSections::default() |
| 2757 | }), |
| 2758 | } |
| 2759 | } |
| 2760 | |
| 2761 | #[test] |
| 2762 | fn control_facet_is_object_safe_and_transports_every_outcome() { |
| 2763 | // Object safety: usable behind a single `dyn` reference. |
| 2764 | fn accepts_dyn(_: &dyn CommandSessionControlContext) {} |
| 2765 | fn accepts_dyn_mut(_: &mut dyn CommandSessionControlContext) {} |
| 2766 | |
| 2767 | let mut fake = FakeControl { |
| 2768 | blocked: true, |
| 2769 | relay: Some(control_relay_projection()), |
| 2770 | resume: Some(Ok(ResumeSource::Session { |
| 2771 | load_path: Some(PathBuf::from("/tmp/sessions/abc123.json")), |
| 2772 | truncated_id: "abc123".to_string(), |
| 2773 | title: "Control Session".to_string(), |
| 2774 | })), |
| 2775 | import: Some(Ok(ResumeImportReceipt { |
| 2776 | truncated_id: "imp-9".to_string(), |
| 2777 | entry_count: 12, |
| 2778 | leaf_display: "leaf-3".to_string(), |
| 2779 | sync: lifecycle_sync_payload(Some("imp-9")), |
| 2780 | })), |
| 2781 | sanitized_title: Some("Renamed".to_string()), |
| 2782 | rename: Some(Ok(SessionTitleReceipt { |
| 2783 | title: "Renamed".to_string(), |
| 2784 | })), |
| 2785 | title_report: Some(TitleReport { |
| 2786 | effective: "task-7".to_string(), |
| 2787 | source: TitleSource::Session, |
| 2788 | }), |
| 2789 | set_title: Some(Ok(())), |
| 2790 | clear_title: Some(Ok(())), |
| 2791 | remote_status: Some("live".to_string()), |
| 2792 | remote_link: Some(Some(RemoteLink { |
| 2793 | url: "https://remote.example/s".to_string(), |
| 2794 | computer_url: Some("https://remote.example/c".to_string()), |
| 2795 | })), |
| 2796 | browser_open: Some(RemoteOpenOutcome::Opened { |
| 2797 | url: "https://remote.example/s".to_string(), |
| 2798 | }), |
| 2799 | start_info: Some(RemoteStartInfo { connecting: true }), |
| 2800 | stop_refusal: Some(None), |
| 2801 | hosted: Some(Some(HostedWorkTarget { |
| 2802 | url: "https://app.codewhale.net/work?repo=A%2FB".to_string(), |
| 2803 | repo: "A/B".to_string(), |
| 2804 | branch: "main".to_string(), |
| 2805 | })), |
| 2806 | }; |
| 2807 | accepts_dyn(&fake); |
| 2808 | accepts_dyn_mut(&mut fake); |
| 2809 | |
| 2810 | assert!(fake.transition_blocked()); |
| 2811 | let relay = fake.relay_projection(); |
| 2812 | assert_eq!(relay.model, "control-model"); |
| 2813 | assert_eq!(relay.goal_token_budget, Some(42_000)); |
| 2814 | assert!(matches!(relay.todos, TodoProjection::Body(_))); |
| 2815 | match relay.plan { |
| 2816 | PlanProjection::Sections(sections) => { |
| 2817 | assert_eq!(sections.title.as_deref(), Some("Plan title")); |
| 2818 | assert_eq!(sections.items.len(), 1); |
| 2819 | assert_eq!(sections.items[0].status, PlanStepStatus::InProgress); |
| 2820 | } |
| 2821 | other => panic!("expected Sections plan, got {other:?}"), |
| 2822 | } |
| 2823 | let resolved = fake |
| 2824 | .resolve_resume_source("abc123") |
| 2825 | .expect("resume resolution ok"); |
| 2826 | match resolved { |
| 2827 | ResumeSource::Session { |
| 2828 | load_path, title, .. |
| 2829 | } => { |
| 2830 | assert_eq!(load_path, Some(PathBuf::from("/tmp/sessions/abc123.json"))); |
| 2831 | assert_eq!(title, "Control Session"); |
| 2832 | } |
| 2833 | other => panic!("expected Session resolution, got {other:?}"), |
| 2834 | } |
| 2835 | let imported = fake |
| 2836 | .import_session_file(PathBuf::from("/tmp/import.json")) |
| 2837 | .expect("import ok"); |
| 2838 | assert_eq!(imported.truncated_id, "imp-9"); |
| 2839 | assert_eq!(imported.entry_count, 12); |
| 2840 | assert_eq!(imported.leaf_display, "leaf-3"); |
| 2841 | assert_eq!(fake.sanitize_session_title("raw"), "Renamed"); |
| 2842 | let renamed = fake.rename_session("Renamed").expect("rename ok"); |
| 2843 | assert_eq!(renamed.title, "Renamed"); |
| 2844 | let report = fake.title_report(); |
| 2845 | assert_eq!(report.effective, "task-7"); |
| 2846 | assert!(matches!(report.source, TitleSource::Session)); |
| 2847 | fake.set_window_title("task-7".to_string()).expect("set ok"); |
| 2848 | fake.clear_window_title().expect("clear ok"); |
| 2849 | assert_eq!(fake.remote_status(), "live"); |
| 2850 | let link = fake.remote_link().expect("link present"); |
| 2851 | assert_eq!(link.url, "https://remote.example/s"); |
| 2852 | assert!(matches!( |
| 2853 | fake.remote_browser_open(), |
| 2854 | RemoteOpenOutcome::Opened { .. } |
| 2855 | )); |
| 2856 | assert!(fake.remote_start_info().connecting); |
| 2857 | assert_eq!(fake.remote_stop_refusal(), None); |
| 2858 | let hosted = fake.resolve_hosted_work_target().expect("target present"); |
| 2859 | assert_eq!(hosted.repo, "A/B"); |
| 2860 | assert_eq!(hosted.branch, "main"); |
| 2861 | } |
| 2862 | |
| 2863 | #[test] |
| 2864 | fn control_error_and_empty_states_transport_exactly() { |
| 2865 | let mut fake = FakeControl { |
| 2866 | blocked: false, |
| 2867 | resume: Some(Err("could not open sessions directory: boom".to_string())), |
| 2868 | import: Some(Err( |
| 2869 | "File x.json is not a recognized session export".to_string() |
| 2870 | )), |
| 2871 | rename: Some(Err("Could not save session: boom".to_string())), |
| 2872 | set_title: Some(Err("Could not save session: boom".to_string())), |
| 2873 | clear_title: Some(Err("Could not save session: boom".to_string())), |
| 2874 | remote_link: Some(None), |
| 2875 | browser_open: Some(RemoteOpenOutcome::NoLink), |
| 2876 | stop_refusal: Some(Some( |
| 2877 | "stop refused while a remote turn is active".to_string(), |
| 2878 | )), |
| 2879 | hosted: Some(None), |
| 2880 | ..FakeControl::default() |
| 2881 | }; |
| 2882 | assert!(!fake.transition_blocked()); |
| 2883 | assert_eq!( |
| 2884 | fake.resolve_resume_source("x").unwrap_err(), |
| 2885 | "could not open sessions directory: boom" |
| 2886 | ); |
| 2887 | assert_eq!( |
| 2888 | fake.import_session_file(PathBuf::from("x.json")) |
| 2889 | .unwrap_err(), |
| 2890 | "File x.json is not a recognized session export" |
| 2891 | ); |
| 2892 | assert_eq!( |
| 2893 | fake.rename_session("t").unwrap_err(), |
| 2894 | "Could not save session: boom" |
| 2895 | ); |
| 2896 | assert_eq!( |
| 2897 | fake.set_window_title("task".to_string()).unwrap_err(), |
| 2898 | "Could not save session: boom" |
| 2899 | ); |
| 2900 | assert_eq!( |
| 2901 | fake.clear_window_title().unwrap_err(), |
| 2902 | "Could not save session: boom" |
| 2903 | ); |
| 2904 | assert_eq!(fake.remote_link(), None); |
| 2905 | assert!(matches!( |
| 2906 | fake.remote_browser_open(), |
| 2907 | RemoteOpenOutcome::NoLink |
| 2908 | )); |
| 2909 | assert_eq!( |
| 2910 | fake.remote_stop_refusal().as_deref(), |
| 2911 | Some("stop refused while a remote turn is active") |
| 2912 | ); |
| 2913 | assert_eq!(fake.resolve_hosted_work_target(), None); |
| 2914 | |
| 2915 | // Empty-state variants: absent to-do/plan and no effective title transport. |
| 2916 | fake.relay = Some(RelayProjection { |
| 2917 | todos: TodoProjection::Absent, |
| 2918 | plan: PlanProjection::Absent, |
| 2919 | ..control_relay_projection() |
| 2920 | }); |
| 2921 | let relay = fake.relay_projection(); |
| 2922 | assert!(matches!(relay.todos, TodoProjection::Absent)); |
| 2923 | assert!(matches!(relay.plan, PlanProjection::Absent)); |
| 2924 | fake.title_report = Some(TitleReport { |
| 2925 | effective: "unset".to_string(), |
| 2926 | source: TitleSource::None, |
| 2927 | }); |
| 2928 | assert!(matches!(fake.title_report().source, TitleSource::None)); |
| 2929 | fake.clear_title = Some(Ok(())); |
| 2930 | fake.clear_window_title().expect("cleared"); |
| 2931 | } |
| 2932 | |
| 2933 | #[test] |
| 2934 | fn envelope_control_slot_is_independent_and_rejects_duplicates() { |
| 2935 | let mut first = FakeControl::default(); |
| 2936 | let mut second = FakeControl::default(); |
| 2937 | let mut lifecycle = FakeLifecycle::default(); |
| 2938 | |
| 2939 | let parts = CommandContexts::empty() |
| 2940 | .with_control(&mut first) |
| 2941 | .with_lifecycle(&mut lifecycle) |
| 2942 | .into_parts(); |
| 2943 | assert!( |
| 2944 | parts.control.is_some(), |
| 2945 | "control slot must be present when declared" |
| 2946 | ); |
| 2947 | assert!( |
| 2948 | parts.lifecycle.is_some(), |
| 2949 | "lifecycle slot may coexist with control" |
| 2950 | ); |
| 2951 | assert!( |
| 2952 | parts.session.is_none() |
| 2953 | && parts.plugin.is_none() |
| 2954 | && parts.skill_group.is_none() |
| 2955 | && parts.presentation.is_none(), |
| 2956 | "unrelated slots must stay absent (exact exposure)" |
| 2957 | ); |
| 2958 | |
| 2959 | let bare = CommandContexts::empty().into_parts(); |
| 2960 | assert!(bare.control.is_none(), "undeclared control stays absent"); |
| 2961 | |
| 2962 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 2963 | CommandContexts::empty() |
| 2964 | .with_control(&mut first) |
| 2965 | .with_control(&mut second); |
| 2966 | })); |
| 2967 | assert!( |
| 2968 | result.is_err(), |
| 2969 | "duplicate control slot must assert deterministically" |
| 2970 | ); |
| 2971 | |
| 2972 | // Reading through the dyn facet works after insertion. |
| 2973 | first.blocked = true; |
| 2974 | let inserted = CommandContexts::empty().with_control(&mut first); |
| 2975 | let control = inserted.into_parts().control.expect("inserted control"); |
| 2976 | assert!(control.transition_blocked()); |
| 2977 | } |
| 2978 | |
| 2979 | #[test] |
| 2980 | fn control_surface_does_not_widen_session_or_lifecycle_facets() { |
| 2981 | // The basic session and lifecycle facets still expose exactly their own |
| 2982 | // method surface alongside the new control slot: all three may populate an |
| 2983 | // envelope at once without colliding, and control does not add behavior to |
| 2984 | // the existing facets. |
| 2985 | let mut session = Session; |
| 2986 | let mut lifecycle = FakeLifecycle::default(); |
| 2987 | let mut control = FakeControl { |
| 2988 | blocked: true, |
| 2989 | ..FakeControl::default() |
| 2990 | }; |
| 2991 | |
| 2992 | let mut parts = CommandContexts::empty() |
| 2993 | .with_session(&mut session) |
| 2994 | .with_lifecycle(&mut lifecycle) |
| 2995 | .with_control(&mut control) |
| 2996 | .into_parts(); |
| 2997 | assert_eq!( |
| 2998 | parts.session.as_deref().unwrap().session_id().as_deref(), |
| 2999 | Some("session") |
| 3000 | ); |
| 3001 | assert!(!parts.lifecycle.as_deref_mut().unwrap().transition_blocked()); |
| 3002 | assert!(parts.control.as_deref_mut().unwrap().transition_blocked()); |
| 3003 | } |
| 3004 | |
| 3005 | // --------------------------------------------------------------------------- |
| 3006 | // FEAT-025: session export contract (D1/D3/D5/D6/D7/D8/D9). |
| 3007 | // --------------------------------------------------------------------------- |
| 3008 | |
| 3009 | #[test] |
| 3010 | fn export_capability_is_stable_distinct_and_non_conflicting() { |
| 3011 | let export = CommandCapabilities::SESSION_EXPORT; |
| 3012 | let existing = [ |
| 3013 | CommandCapabilities::SESSION, |
| 3014 | CommandCapabilities::MODEL, |
| 3015 | CommandCapabilities::COST, |
| 3016 | CommandCapabilities::MODE_POLICY, |
| 3017 | CommandCapabilities::SYSTEM_PROMPT, |
| 3018 | CommandCapabilities::SKILLS, |
| 3019 | CommandCapabilities::WORKSPACE, |
| 3020 | CommandCapabilities::PRESENTATION, |
| 3021 | CommandCapabilities::MEDIA, |
| 3022 | CommandCapabilities::MEMORY, |
| 3023 | CommandCapabilities::PROJECT, |
| 3024 | CommandCapabilities::SKILL_GROUP, |
| 3025 | CommandCapabilities::PLUGIN, |
| 3026 | CommandCapabilities::SESSION_LIFECYCLE, |
| 3027 | CommandCapabilities::SESSION_CONTROL, |
| 3028 | ]; |
| 3029 | let mut union = CommandCapabilities::NONE; |
| 3030 | for capability in existing { |
| 3031 | assert_ne!( |
| 3032 | export, capability, |
| 3033 | "SESSION_EXPORT must not collide with an existing capability" |
| 3034 | ); |
| 3035 | union = union.union(capability); |
| 3036 | } |
| 3037 | assert!( |
| 3038 | !union.contains(export), |
| 3039 | "SESSION_EXPORT must be a bit outside every existing capability (bits 0-14)" |
| 3040 | ); |
| 3041 | assert!(!CommandCapabilities::NONE.contains(export)); |
| 3042 | assert!(!CommandCapabilities::NONE.contains(CommandCapabilities::NONE)); |
| 3043 | assert!(export.contains(export)); |
| 3044 | assert!( |
| 3045 | export |
| 3046 | .union(CommandCapabilities::SESSION_CONTROL) |
| 3047 | .contains(export) |
| 3048 | ); |
| 3049 | assert!( |
| 3050 | export |
| 3051 | .union(CommandCapabilities::SESSION_CONTROL) |
| 3052 | .contains(CommandCapabilities::SESSION_CONTROL) |
| 3053 | ); |
| 3054 | assert!(!CommandCapabilities::SESSION_CONTROL.contains(export)); |
| 3055 | assert!(!export.contains(CommandCapabilities::SESSION_CONTROL)); |
| 3056 | // FEAT-029 widened storage after bit 15 filled the original space; export |
| 3057 | // retains its exact published identity. |
| 3058 | assert_eq!( |
| 3059 | std::mem::size_of::<CommandCapabilities>(), |
| 3060 | std::mem::size_of::<u64>(), |
| 3061 | "CommandCapabilities storage must be widened for diagnostics" |
| 3062 | ); |
| 3063 | } |
| 3064 | |
| 3065 | /// Canary: FEAT-029 widened the previously full 16-bit capability space. |
| 3066 | /// |
| 3067 | /// The first sixteen identities stay published as before; diagnostics takes |
| 3068 | /// bit 16 and later slices can allocate independently without renumbering. |
| 3069 | #[test] |
| 3070 | fn debug_diagnostics_capability_preserves_published_bits() { |
| 3071 | let all = [ |
| 3072 | CommandCapabilities::SESSION, |
| 3073 | CommandCapabilities::MODEL, |
| 3074 | CommandCapabilities::COST, |
| 3075 | CommandCapabilities::MODE_POLICY, |
| 3076 | CommandCapabilities::SYSTEM_PROMPT, |
| 3077 | CommandCapabilities::SKILLS, |
| 3078 | CommandCapabilities::WORKSPACE, |
| 3079 | CommandCapabilities::PRESENTATION, |
| 3080 | CommandCapabilities::MEDIA, |
| 3081 | CommandCapabilities::MEMORY, |
| 3082 | CommandCapabilities::PROJECT, |
| 3083 | CommandCapabilities::SKILL_GROUP, |
| 3084 | CommandCapabilities::PLUGIN, |
| 3085 | CommandCapabilities::SESSION_LIFECYCLE, |
| 3086 | CommandCapabilities::SESSION_CONTROL, |
| 3087 | CommandCapabilities::SESSION_EXPORT, |
| 3088 | CommandCapabilities::DEBUG_DIAGNOSTICS, |
| 3089 | ]; |
| 3090 | |
| 3091 | let mut union = CommandCapabilities::NONE; |
| 3092 | for (index, capability) in all.iter().enumerate() { |
| 3093 | assert_eq!( |
| 3094 | capability.bits_for_test(), |
| 3095 | 1u64 << index, |
| 3096 | "capability {index} must occupy exactly bit {index}" |
| 3097 | ); |
| 3098 | union = union.union(*capability); |
| 3099 | } |
| 3100 | |
| 3101 | assert_eq!( |
| 3102 | all.len(), |
| 3103 | u16::BITS as usize + 1, |
| 3104 | "diagnostics is the first bit after the original u16 space" |
| 3105 | ); |
| 3106 | assert_eq!( |
| 3107 | union.bits_for_test(), |
| 3108 | u64::from(u16::MAX) | (1u64 << 16), |
| 3109 | "bits 0-15 retain their published values and diagnostics occupies bit 16" |
| 3110 | ); |
| 3111 | assert!(union.contains(CommandCapabilities::DEBUG_DIAGNOSTICS)); |
| 3112 | assert!(!CommandCapabilities::SESSION_EXPORT.contains(CommandCapabilities::DEBUG_DIAGNOSTICS)); |
| 3113 | assert!(!CommandCapabilities::DEBUG_DIAGNOSTICS.contains(CommandCapabilities::SESSION_EXPORT)); |
| 3114 | assert!(CommandCapabilities::NONE.is_empty()); |
| 3115 | assert!(!CommandCapabilities::NONE.contains(CommandCapabilities::DEBUG_DIAGNOSTICS)); |
| 3116 | assert!(!CommandCapabilities::DEBUG_DIAGNOSTICS.contains(CommandCapabilities::NONE)); |
| 3117 | } |
| 3118 | |
| 3119 | /// Deterministic fake export facet: every delegate returns canned portable |
| 3120 | /// values or host error text, and effectful delegates record their calls so a |
| 3121 | /// later phase can assert sequencing without a real host. |
| 3122 | #[derive(Default)] |
| 3123 | struct FakeExport { |
| 3124 | projection: Option<ConversationExportProjection>, |
| 3125 | turn: Option<TurnHandoffProjection>, |
| 3126 | terminal_paste: bool, |
| 3127 | recovery: Option<Option<PathBuf>>, |
| 3128 | clipboard: Option<Result<(), String>>, |
| 3129 | resolved: Option<Result<PathBuf, String>>, |
| 3130 | write: Option<Result<(), String>>, |
| 3131 | calls: RefCell<Vec<String>>, |
| 3132 | } |
| 3133 | |
| 3134 | impl CommandSessionExportContext for FakeExport { |
| 3135 | fn conversation_projection(&self) -> ConversationExportProjection { |
| 3136 | self.calls |
| 3137 | .borrow_mut() |
| 3138 | .push("conversation_projection".to_string()); |
| 3139 | self.projection |
| 3140 | .clone() |
| 3141 | .expect("unexpected conversation_projection() on empty fake") |
| 3142 | } |
| 3143 | fn turn_handoff_projection(&self) -> TurnHandoffProjection { |
| 3144 | self.calls |
| 3145 | .borrow_mut() |
| 3146 | .push("turn_handoff_projection".to_string()); |
| 3147 | self.turn |
| 3148 | .clone() |
| 3149 | .expect("unexpected turn_handoff_projection() on empty fake") |
| 3150 | } |
| 3151 | fn clipboard_requires_terminal_paste(&self) -> bool { |
| 3152 | self.calls |
| 3153 | .borrow_mut() |
| 3154 | .push("clipboard_requires_terminal_paste".to_string()); |
| 3155 | self.terminal_paste |
| 3156 | } |
| 3157 | fn write_recovery_copy(&self, markdown: &str) -> Option<PathBuf> { |
| 3158 | self.calls |
| 3159 | .borrow_mut() |
| 3160 | .push(format!("write_recovery_copy:{markdown}")); |
| 3161 | self.recovery |
| 3162 | .clone() |
| 3163 | .expect("unexpected write_recovery_copy() on empty fake") |
| 3164 | } |
| 3165 | fn write_clipboard(&self, markdown: &str) -> Result<(), String> { |
| 3166 | self.calls |
| 3167 | .borrow_mut() |
| 3168 | .push(format!("write_clipboard:{markdown}")); |
| 3169 | self.clipboard |
| 3170 | .clone() |
| 3171 | .unwrap_or_else(|| Err("unexpected write_clipboard() on empty fake".to_string())) |
| 3172 | } |
| 3173 | fn resolve_export_path(&self, raw: &str) -> Result<PathBuf, String> { |
| 3174 | self.calls |
| 3175 | .borrow_mut() |
| 3176 | .push(format!("resolve_export_path:{raw}")); |
| 3177 | self.resolved.clone().unwrap_or_else(|| { |
| 3178 | Err(format!( |
| 3179 | "unexpected resolve_export_path({raw}) on empty fake" |
| 3180 | )) |
| 3181 | }) |
| 3182 | } |
| 3183 | fn default_export_path(&self, file_name: &str) -> Result<PathBuf, String> { |
| 3184 | self.calls |
| 3185 | .borrow_mut() |
| 3186 | .push(format!("default_export_path:{file_name}")); |
| 3187 | self.resolved.clone().unwrap_or_else(|| { |
| 3188 | Err(format!( |
| 3189 | "unexpected default_export_path({file_name}) on empty fake" |
| 3190 | )) |
| 3191 | }) |
| 3192 | } |
| 3193 | fn write_export_file(&self, path: &Path, contents: &[u8], force: bool) -> Result<(), String> { |
| 3194 | self.calls.borrow_mut().push(format!( |
| 3195 | "write_export_file:{}:{}:{force}", |
| 3196 | path.display(), |
| 3197 | contents.len() |
| 3198 | )); |
| 3199 | self.write |
| 3200 | .clone() |
| 3201 | .unwrap_or_else(|| Err("unexpected write_export_file() on empty fake".to_string())) |
| 3202 | } |
| 3203 | } |
| 3204 | |
| 3205 | fn export_metadata() -> ExportMetadata { |
| 3206 | ExportMetadata { |
| 3207 | session_label: "abc123".to_string(), |
| 3208 | title: None, |
| 3209 | provider: "deepseek".to_string(), |
| 3210 | model: "deepseek-chat".to_string(), |
| 3211 | mode: "ACT".to_string(), |
| 3212 | workspace_name: "workspace".to_string(), |
| 3213 | message_count: 2, |
| 3214 | exported_at_unix: 1_760_000_000, |
| 3215 | } |
| 3216 | } |
| 3217 | |
| 3218 | fn export_recorded_snapshot() -> RestoreSnapshot { |
| 3219 | RestoreSnapshot { |
| 3220 | id: "0123456789abcdef".to_string(), |
| 3221 | label: "pre-turn:3: fix parser".to_string(), |
| 3222 | timestamp_unix: 1_759_999_000, |
| 3223 | kind: "pre-turn".to_string(), |
| 3224 | sequence: Some(3), |
| 3225 | prompt_snippet: Some("fix parser".to_string()), |
| 3226 | } |
| 3227 | } |
| 3228 | |
| 3229 | #[test] |
| 3230 | fn export_facet_is_object_safe_and_transports_every_outcome() { |
| 3231 | // Object safety: usable behind a single `dyn` reference. |
| 3232 | fn accepts_dyn(_: &dyn CommandSessionExportContext) {} |
| 3233 | fn accepts_dyn_mut(_: &mut dyn CommandSessionExportContext) {} |
| 3234 | |
| 3235 | let mut fake = FakeExport { |
| 3236 | projection: Some(ConversationExportProjection { |
| 3237 | metadata: export_metadata(), |
| 3238 | transcript: TranscriptProjection::Authoritative(vec![ExportMessage { |
| 3239 | is_user_role: false, |
| 3240 | role: "assistant".to_string(), |
| 3241 | prompt_snippet: Some("fix parser".to_string()), |
| 3242 | blocks: vec![ |
| 3243 | ExportBlock::Text { |
| 3244 | text: "visible".to_string(), |
| 3245 | }, |
| 3246 | ExportBlock::ImageReference { |
| 3247 | url: "https://example.test/a.png".to_string(), |
| 3248 | }, |
| 3249 | ExportBlock::ImageOmitted, |
| 3250 | ExportBlock::InternalReasoning, |
| 3251 | ExportBlock::ToolCall { |
| 3252 | id: "tool-1".to_string(), |
| 3253 | name: "read".to_string(), |
| 3254 | caller: Some(ToolCallerProjection { |
| 3255 | caller_type: "direct".to_string(), |
| 3256 | tool_id: Some("caller-1".to_string()), |
| 3257 | }), |
| 3258 | input: serde_json::json!({"path": "a.txt"}), |
| 3259 | }, |
| 3260 | ExportBlock::ToolResult { |
| 3261 | tool_use_id: "tool-1".to_string(), |
| 3262 | content: "ok".to_string(), |
| 3263 | is_error: false, |
| 3264 | structured: Some(serde_json::json!([{"type": "text", "text": "ok"}])), |
| 3265 | }, |
| 3266 | ExportBlock::ServerToolCall { |
| 3267 | id: "server-1".to_string(), |
| 3268 | name: "web_search".to_string(), |
| 3269 | input: serde_json::json!({"q": "rust"}), |
| 3270 | }, |
| 3271 | ExportBlock::ToolSearchResult { |
| 3272 | tool_use_id: "search-1".to_string(), |
| 3273 | content: serde_json::json!({"results": []}), |
| 3274 | }, |
| 3275 | ExportBlock::CodeExecutionResult { |
| 3276 | tool_use_id: "code-1".to_string(), |
| 3277 | content: serde_json::json!({"stdout": "hi"}), |
| 3278 | }, |
| 3279 | ], |
| 3280 | }]), |
| 3281 | restore_points: RestorePointProjection::Recorded { |
| 3282 | snapshots: vec![export_recorded_snapshot()], |
| 3283 | }, |
| 3284 | turn_outcomes: Vec::new(), |
| 3285 | }), |
| 3286 | turn: Some(TurnHandoffProjection { |
| 3287 | markdown: "# turn handoff".to_string(), |
| 3288 | workspace_path: "/workspace/example".to_string(), |
| 3289 | }), |
| 3290 | terminal_paste: true, |
| 3291 | recovery: Some(Some(PathBuf::from( |
| 3292 | "/home/u/.codewhale/exports/last-copy.md", |
| 3293 | ))), |
| 3294 | clipboard: Some(Ok(())), |
| 3295 | resolved: Some(Ok(PathBuf::from("/workspace/example/out.md"))), |
| 3296 | write: Some(Ok(())), |
| 3297 | ..FakeExport::default() |
| 3298 | }; |
| 3299 | accepts_dyn(&fake); |
| 3300 | accepts_dyn_mut(&mut fake); |
| 3301 | |
| 3302 | let projection = fake.conversation_projection(); |
| 3303 | assert_eq!(projection.metadata.session_label, "abc123"); |
| 3304 | assert_eq!(projection.metadata.provider, "deepseek"); |
| 3305 | assert_eq!(projection.metadata.model, "deepseek-chat"); |
| 3306 | assert_eq!(projection.metadata.mode, "ACT"); |
| 3307 | assert_eq!(projection.metadata.workspace_name, "workspace"); |
| 3308 | assert_eq!(projection.metadata.message_count, 2); |
| 3309 | assert_eq!(projection.metadata.exported_at_unix, 1_760_000_000); |
| 3310 | let TranscriptProjection::Authoritative(messages) = projection.transcript else { |
| 3311 | panic!("expected authoritative transcript"); |
| 3312 | }; |
| 3313 | assert_eq!(messages.len(), 1); |
| 3314 | assert_eq!(messages[0].role, "assistant"); |
| 3315 | assert_eq!(messages[0].prompt_snippet.as_deref(), Some("fix parser")); |
| 3316 | assert_eq!(messages[0].blocks.len(), 9); |
| 3317 | let ExportBlock::ToolCall { |
| 3318 | caller: Some(caller), |
| 3319 | input, |
| 3320 | .. |
| 3321 | } = &messages[0].blocks[4] |
| 3322 | else { |
| 3323 | panic!("expected tool call with caller"); |
| 3324 | }; |
| 3325 | assert_eq!(caller.caller_type, "direct"); |
| 3326 | assert_eq!(caller.tool_id.as_deref(), Some("caller-1")); |
| 3327 | assert_eq!(input["path"], "a.txt"); |
| 3328 | let ExportBlock::ToolResult { |
| 3329 | is_error, |
| 3330 | structured, |
| 3331 | .. |
| 3332 | } = &messages[0].blocks[5] |
| 3333 | else { |
| 3334 | panic!("expected tool result"); |
| 3335 | }; |
| 3336 | assert!(!is_error); |
| 3337 | assert!(structured.is_some()); |
| 3338 | let RestorePointProjection::Recorded { snapshots } = projection.restore_points else { |
| 3339 | panic!("expected recorded restore points"); |
| 3340 | }; |
| 3341 | assert_eq!(snapshots.len(), 1); |
| 3342 | assert_eq!(snapshots[0].id, "0123456789abcdef"); |
| 3343 | assert_eq!(snapshots[0].label, "pre-turn:3: fix parser"); |
| 3344 | assert_eq!(snapshots[0].timestamp_unix, 1_759_999_000); |
| 3345 | assert_eq!(snapshots[0].kind, "pre-turn"); |
| 3346 | assert_eq!(snapshots[0].sequence, Some(3)); |
| 3347 | assert_eq!(snapshots[0].prompt_snippet.as_deref(), Some("fix parser")); |
| 3348 | |
| 3349 | let turn = fake.turn_handoff_projection(); |
| 3350 | assert_eq!(turn.markdown, "# turn handoff"); |
| 3351 | assert_eq!(turn.workspace_path, "/workspace/example"); |
| 3352 | |
| 3353 | assert!(fake.clipboard_requires_terminal_paste()); |
| 3354 | assert_eq!( |
| 3355 | fake.write_recovery_copy("# md"), |
| 3356 | Some(PathBuf::from("/home/u/.codewhale/exports/last-copy.md")) |
| 3357 | ); |
| 3358 | assert!(fake.write_clipboard("# md").is_ok()); |
| 3359 | assert_eq!( |
| 3360 | fake.resolve_export_path("out.md").expect("resolved"), |
| 3361 | PathBuf::from("/workspace/example/out.md") |
| 3362 | ); |
| 3363 | assert!( |
| 3364 | fake.write_export_file(Path::new("/workspace/example/out.md"), b"# md", false) |
| 3365 | .is_ok() |
| 3366 | ); |
| 3367 | // Effectful delegates were exercised exactly once each, in call order. |
| 3368 | let expected: Vec<String> = [ |
| 3369 | "conversation_projection", |
| 3370 | "turn_handoff_projection", |
| 3371 | "clipboard_requires_terminal_paste", |
| 3372 | "write_recovery_copy:# md", |
| 3373 | "write_clipboard:# md", |
| 3374 | "resolve_export_path:out.md", |
| 3375 | "write_export_file:/workspace/example/out.md:4:false", |
| 3376 | ] |
| 3377 | .into_iter() |
| 3378 | .map(str::to_string) |
| 3379 | .collect(); |
| 3380 | assert_eq!(fake.calls.borrow().as_slice(), expected.as_slice()); |
| 3381 | } |
| 3382 | |
| 3383 | #[test] |
| 3384 | fn export_error_and_empty_states_transport_exactly() { |
| 3385 | let fake = FakeExport { |
| 3386 | projection: Some(ConversationExportProjection { |
| 3387 | metadata: export_metadata(), |
| 3388 | transcript: TranscriptProjection::HistoryFallback(vec![ |
| 3389 | HistoryEntry::Sanitized { |
| 3390 | role: "user".to_string(), |
| 3391 | body: "visible history".to_string(), |
| 3392 | }, |
| 3393 | HistoryEntry::Literal { |
| 3394 | role: "system".to_string(), |
| 3395 | body: "[internal context omitted]".to_string(), |
| 3396 | }, |
| 3397 | ]), |
| 3398 | restore_points: RestorePointProjection::Unreadable { |
| 3399 | reason: "permission denied".to_string(), |
| 3400 | }, |
| 3401 | turn_outcomes: Vec::new(), |
| 3402 | }), |
| 3403 | recovery: Some(None), |
| 3404 | clipboard: Some(Err("clipboard unavailable".to_string())), |
| 3405 | resolved: Some(Err("export paths may not contain `..`".to_string())), |
| 3406 | write: Some(Err("destination already exists".to_string())), |
| 3407 | ..FakeExport::default() |
| 3408 | }; |
| 3409 | |
| 3410 | let projection = fake.conversation_projection(); |
| 3411 | let TranscriptProjection::HistoryFallback(entries) = projection.transcript else { |
| 3412 | panic!("expected history fallback"); |
| 3413 | }; |
| 3414 | assert_eq!(entries.len(), 2); |
| 3415 | assert!(matches!( |
| 3416 | &entries[0], |
| 3417 | HistoryEntry::Sanitized { role, body } |
| 3418 | if role == "user" && body == "visible history" |
| 3419 | )); |
| 3420 | assert!(matches!( |
| 3421 | &entries[1], |
| 3422 | HistoryEntry::Literal { role, body } |
| 3423 | if role == "system" && body == "[internal context omitted]" |
| 3424 | )); |
| 3425 | let RestorePointProjection::Unreadable { reason } = projection.restore_points else { |
| 3426 | panic!("expected unreadable restore points"); |
| 3427 | }; |
| 3428 | assert_eq!(reason, "permission denied"); |
| 3429 | |
| 3430 | assert!(!fake.clipboard_requires_terminal_paste()); |
| 3431 | assert_eq!(fake.write_recovery_copy("# md"), None); |
| 3432 | assert_eq!( |
| 3433 | fake.write_clipboard("# md").unwrap_err(), |
| 3434 | "clipboard unavailable" |
| 3435 | ); |
| 3436 | assert_eq!( |
| 3437 | fake.resolve_export_path("../out.md").unwrap_err(), |
| 3438 | "export paths may not contain `..`" |
| 3439 | ); |
| 3440 | assert_eq!( |
| 3441 | fake.write_export_file(Path::new("/tmp/out.md"), b"x", false) |
| 3442 | .unwrap_err(), |
| 3443 | "destination already exists" |
| 3444 | ); |
| 3445 | } |
| 3446 | |
| 3447 | #[test] |
| 3448 | fn export_projection_distinguishes_restore_states() { |
| 3449 | let states = [ |
| 3450 | RestorePointProjection::None, |
| 3451 | RestorePointProjection::Unreadable { |
| 3452 | reason: "boom".to_string(), |
| 3453 | }, |
| 3454 | RestorePointProjection::Recorded { snapshots: vec![] }, |
| 3455 | RestorePointProjection::Recorded { |
| 3456 | snapshots: vec![export_recorded_snapshot()], |
| 3457 | }, |
| 3458 | ]; |
| 3459 | assert!(matches!(&states[0], RestorePointProjection::None)); |
| 3460 | assert!(matches!( |
| 3461 | &states[1], |
| 3462 | RestorePointProjection::Unreadable { reason } if reason == "boom" |
| 3463 | )); |
| 3464 | let RestorePointProjection::Recorded { snapshots } = &states[2] else { |
| 3465 | panic!("expected recorded state"); |
| 3466 | }; |
| 3467 | assert!(snapshots.is_empty(), "existing-but-empty stays distinct"); |
| 3468 | let RestorePointProjection::Recorded { snapshots } = &states[3] else { |
| 3469 | panic!("expected recorded state"); |
| 3470 | }; |
| 3471 | assert_eq!(snapshots.len(), 1); |
| 3472 | } |
| 3473 | |
| 3474 | #[test] |
| 3475 | fn export_projection_omission_markers_carry_no_hidden_payload() { |
| 3476 | // D9: the projection has no field for a reasoning body, reasoning |
| 3477 | // signature, or inline/local image payload. Omission markers are data-free |
| 3478 | // unit variants, so prohibited payloads cannot be transported even by |
| 3479 | // accident. |
| 3480 | let block = ExportBlock::InternalReasoning; |
| 3481 | let ExportBlock::InternalReasoning = block else { |
| 3482 | panic!("internal reasoning must be a payload-free marker"); |
| 3483 | }; |
| 3484 | let block = ExportBlock::ImageOmitted; |
| 3485 | let ExportBlock::ImageOmitted = block else { |
| 3486 | panic!("omitted image must be a payload-free marker"); |
| 3487 | }; |
| 3488 | |
| 3489 | const HIDDEN_REASONING: &str = "signed-thinking-secret-body"; |
| 3490 | const HIDDEN_SIGNATURE: &str = "sig_1234567890"; |
| 3491 | const HIDDEN_IMAGE: &str = "data:image/png;base64,QUJD"; |
| 3492 | |
| 3493 | let projection = ConversationExportProjection { |
| 3494 | metadata: export_metadata(), |
| 3495 | transcript: TranscriptProjection::Authoritative(vec![ExportMessage { |
| 3496 | is_user_role: false, |
| 3497 | role: "assistant".to_string(), |
| 3498 | prompt_snippet: None, |
| 3499 | blocks: vec![ExportBlock::InternalReasoning, ExportBlock::ImageOmitted], |
| 3500 | }]), |
| 3501 | restore_points: RestorePointProjection::None, |
| 3502 | turn_outcomes: Vec::new(), |
| 3503 | }; |
| 3504 | let rendered = format!("{projection:?}"); |
| 3505 | assert!(!rendered.contains(HIDDEN_REASONING)); |
| 3506 | assert!(!rendered.contains(HIDDEN_SIGNATURE)); |
| 3507 | assert!(!rendered.contains(HIDDEN_IMAGE)); |
| 3508 | assert!(rendered.contains("InternalReasoning")); |
| 3509 | assert!(rendered.contains("ImageOmitted")); |
| 3510 | } |
| 3511 | |
| 3512 | #[test] |
| 3513 | fn envelope_export_slot_is_independent_and_rejects_duplicates() { |
| 3514 | let mut first = FakeExport::default(); |
| 3515 | let mut second = FakeExport::default(); |
| 3516 | let mut control = FakeControl::default(); |
| 3517 | |
| 3518 | let parts = CommandContexts::empty() |
| 3519 | .with_export(&mut first) |
| 3520 | .with_control(&mut control) |
| 3521 | .into_parts(); |
| 3522 | assert!( |
| 3523 | parts.export.is_some(), |
| 3524 | "export slot must be present when declared" |
| 3525 | ); |
| 3526 | assert!( |
| 3527 | parts.control.is_some(), |
| 3528 | "control slot may coexist with export" |
| 3529 | ); |
| 3530 | assert!( |
| 3531 | parts.session.is_none() |
| 3532 | && parts.lifecycle.is_none() |
| 3533 | && parts.plugin.is_none() |
| 3534 | && parts.skill_group.is_none(), |
| 3535 | "unrelated slots must stay absent (exact exposure)" |
| 3536 | ); |
| 3537 | |
| 3538 | let bare = CommandContexts::empty().into_parts(); |
| 3539 | assert!(bare.export.is_none(), "undeclared export stays absent"); |
| 3540 | |
| 3541 | let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 3542 | CommandContexts::empty() |
| 3543 | .with_export(&mut first) |
| 3544 | .with_export(&mut second); |
| 3545 | })); |
| 3546 | assert!( |
| 3547 | result.is_err(), |
| 3548 | "duplicate export slot must assert deterministically" |
| 3549 | ); |
| 3550 | |
| 3551 | // Reading through the dyn facet works after insertion. |
| 3552 | let mut projection = FakeExport { |
| 3553 | terminal_paste: true, |
| 3554 | ..FakeExport::default() |
| 3555 | }; |
| 3556 | let inserted = CommandContexts::empty().with_export(&mut projection); |
| 3557 | let export = inserted.into_parts().export.expect("inserted export"); |
| 3558 | assert!(export.clipboard_requires_terminal_paste()); |
| 3559 | } |
| 3560 | |
| 3561 | #[test] |
| 3562 | fn whole_debug_capabilities_extend_published_bits_without_aliasing_authority() { |
| 3563 | let old = (1u64 << 17) - 1; |
| 3564 | let capabilities = [ |
| 3565 | CommandCapabilities::DEBUG_RECEIPTS, |
| 3566 | CommandCapabilities::DEBUG_CHANGE, |
| 3567 | CommandCapabilities::DEBUG_HISTORY, |
| 3568 | CommandCapabilities::DEBUG_DIFF, |
| 3569 | CommandCapabilities::DEBUG_UNDO, |
| 3570 | ]; |
| 3571 | let mut seen = old; |
| 3572 | for (index, capability) in capabilities.into_iter().enumerate() { |
| 3573 | assert_eq!(capability.bits_for_test(), 1 << (17 + index)); |
| 3574 | assert_eq!(seen & capability.bits_for_test(), 0); |
| 3575 | assert!(!capability.contains(CommandCapabilities::DEBUG_DIAGNOSTICS)); |
| 3576 | seen |= capability.bits_for_test(); |
| 3577 | } |
| 3578 | assert_eq!(seen, (1u64 << 22) - 1); |
| 3579 | } |
| 3580 | |
| 3581 | struct StructcopyFixture { |
| 3582 | delivery: Result<StructcopyTransport, String>, |
| 3583 | writes: RefCell<Vec<String>>, |
| 3584 | } |
| 3585 | impl CommandSessionStructcopyContext for StructcopyFixture { |
| 3586 | fn transcript_item(&self, index: usize) -> Result<StructcopyTranscript, StructcopyError> { |
| 3587 | Ok(StructcopyTranscript { |
| 3588 | index, |
| 3589 | role: "system".into(), |
| 3590 | content: StructcopyContent::InternalContext, |
| 3591 | }) |
| 3592 | } |
| 3593 | fn tool_pair(&self, _: &str) -> Result<StructcopyToolPair, StructcopyError> { |
| 3594 | Ok(StructcopyToolPair { |
| 3595 | name: "tool".into(), |
| 3596 | input: serde_json::json!({}), |
| 3597 | result: None, |
| 3598 | }) |
| 3599 | } |
| 3600 | fn plan_snapshot(&self) -> Result<StructcopyPlan, StructcopyError> { |
| 3601 | Err(StructcopyError::Busy) |
| 3602 | } |
| 3603 | fn workflow_projection(&self, _: &str) -> Result<StructcopyWorkflow, StructcopyError> { |
| 3604 | Err(StructcopyError::Unavailable) |
| 3605 | } |
| 3606 | fn path_roots(&self) -> StructcopyPathRoots { |
| 3607 | StructcopyPathRoots::default() |
| 3608 | } |
| 3609 | fn write_clipboard(&self, text: &str) -> Result<StructcopyTransport, String> { |
| 3610 | self.writes.borrow_mut().push(text.into()); |
| 3611 | self.delivery.clone() |
| 3612 | } |
| 3613 | } |
| 3614 | |
| 3615 | #[test] |
| 3616 | fn structcopy_capability_preserves_all_published_identities() { |
| 3617 | let capabilities = [ |
| 3618 | CommandCapabilities::SESSION, |
| 3619 | CommandCapabilities::MODEL, |
| 3620 | CommandCapabilities::COST, |
| 3621 | CommandCapabilities::MODE_POLICY, |
| 3622 | CommandCapabilities::SYSTEM_PROMPT, |
| 3623 | CommandCapabilities::SKILLS, |
| 3624 | CommandCapabilities::WORKSPACE, |
| 3625 | CommandCapabilities::PRESENTATION, |
| 3626 | CommandCapabilities::MEDIA, |
| 3627 | CommandCapabilities::MEMORY, |
| 3628 | CommandCapabilities::PROJECT, |
| 3629 | CommandCapabilities::SKILL_GROUP, |
| 3630 | CommandCapabilities::PLUGIN, |
| 3631 | CommandCapabilities::SESSION_LIFECYCLE, |
| 3632 | CommandCapabilities::SESSION_CONTROL, |
| 3633 | CommandCapabilities::SESSION_EXPORT, |
| 3634 | CommandCapabilities::DEBUG_DIAGNOSTICS, |
| 3635 | CommandCapabilities::DEBUG_RECEIPTS, |
| 3636 | CommandCapabilities::DEBUG_CHANGE, |
| 3637 | CommandCapabilities::DEBUG_HISTORY, |
| 3638 | CommandCapabilities::DEBUG_DIFF, |
| 3639 | CommandCapabilities::DEBUG_UNDO, |
| 3640 | CommandCapabilities::SESSION_STRUCTCOPY, |
| 3641 | CommandCapabilities::PERMISSIONS, |
| 3642 | CommandCapabilities::CONFIG_STATUS, |
| 3643 | CommandCapabilities::CONFIG, |
| 3644 | CommandCapabilities::PET, |
| 3645 | CommandCapabilities::TRUST, |
| 3646 | CommandCapabilities::LOGIN, |
| 3647 | CommandCapabilities::WORK_SURFACE, |
| 3648 | CommandCapabilities::NAVIGATION, |
| 3649 | CommandCapabilities::VOICE_INPUT, |
| 3650 | ]; |
| 3651 | let exact = CommandCapabilities::SESSION_STRUCTCOPY | CommandCapabilities::PRESENTATION; |
| 3652 | for (index, capability) in capabilities.into_iter().enumerate() { |
| 3653 | assert_eq!(capability.bits_for_test(), 1u64 << index); |
| 3654 | assert_eq!(exact.contains(capability), index == 7 || index == 22); |
| 3655 | } |
| 3656 | assert!(!exact.contains(CommandCapabilities::NONE)); |
| 3657 | } |
| 3658 | |
| 3659 | #[test] |
| 3660 | fn config_slots_are_optional_and_independent() { |
| 3661 | assert_eq!(CommandCapabilities::CONFIG.bits_for_test(), 1 << 25); |
| 3662 | assert_eq!(CommandCapabilities::PET.bits_for_test(), 1 << 26); |
| 3663 | assert_eq!(CommandCapabilities::TRUST.bits_for_test(), 1 << 27); |
| 3664 | let config = CommandCapabilities::CONFIG | CommandCapabilities::PRESENTATION; |
| 3665 | let pet = CommandCapabilities::PET | CommandCapabilities::PRESENTATION; |
| 3666 | let trust = CommandCapabilities::TRUST | CommandCapabilities::WORKSPACE; |
| 3667 | assert!(!config.contains(CommandCapabilities::PET)); |
| 3668 | assert!(!config.contains(CommandCapabilities::TRUST)); |
| 3669 | assert!(!pet.contains(CommandCapabilities::CONFIG)); |
| 3670 | assert!(!pet.contains(CommandCapabilities::TRUST)); |
| 3671 | assert!(!trust.contains(CommandCapabilities::CONFIG)); |
| 3672 | assert!(!trust.contains(CommandCapabilities::PET)); |
| 3673 | } |
| 3674 | |
| 3675 | #[test] |
| 3676 | fn structcopy_slot_is_optional_and_does_not_grant_other_authority() { |
| 3677 | assert!(CommandContexts::empty().into_parts().structcopy.is_none()); |
| 3678 | let mut fixture = StructcopyFixture { |
| 3679 | delivery: Ok(StructcopyTransport::Native), |
| 3680 | writes: RefCell::default(), |
| 3681 | }; |
| 3682 | let mut presentation = Presentation; |
| 3683 | let ContextParts { |
| 3684 | session, |
| 3685 | model, |
| 3686 | cost, |
| 3687 | mode_policy, |
| 3688 | system_prompt, |
| 3689 | skills, |
| 3690 | workspace, |
| 3691 | presentation, |
| 3692 | media, |
| 3693 | memory, |
| 3694 | project, |
| 3695 | skill_group, |
| 3696 | plugin, |
| 3697 | lifecycle, |
| 3698 | control, |
| 3699 | export, |
| 3700 | structcopy, |
| 3701 | debug_receipts, |
| 3702 | debug_change, |
| 3703 | debug_history, |
| 3704 | debug_diff, |
| 3705 | debug_undo, |
| 3706 | debug_diagnostics, |
| 3707 | permissions, |
| 3708 | config_status, |
| 3709 | config, |
| 3710 | pet, |
| 3711 | trust, |
| 3712 | login, |
| 3713 | work_surface, |
| 3714 | navigation, |
| 3715 | voice_input, |
| 3716 | } = CommandContexts::empty() |
| 3717 | .with_structcopy(&mut fixture) |
| 3718 | .with_presentation(&mut presentation) |
| 3719 | .into_parts(); |
| 3720 | assert!(presentation.is_some()); |
| 3721 | let copy = structcopy.expect("selected structcopy facet"); |
| 3722 | assert_eq!( |
| 3723 | copy.transcript_item(3).unwrap(), |
| 3724 | StructcopyTranscript { |
| 3725 | index: 3, |
| 3726 | role: "system".into(), |
| 3727 | content: StructcopyContent::InternalContext |
| 3728 | } |
| 3729 | ); |
| 3730 | assert_eq!(copy.tool_pair("id").unwrap().result, None); |
| 3731 | assert_eq!(copy.plan_snapshot(), Err(StructcopyError::Busy)); |
| 3732 | assert_eq!( |
| 3733 | copy.workflow_projection("id"), |
| 3734 | Err(StructcopyError::Unavailable) |
| 3735 | ); |
| 3736 | for present in [ |
| 3737 | session.is_some(), |
| 3738 | model.is_some(), |
| 3739 | cost.is_some(), |
| 3740 | mode_policy.is_some(), |
| 3741 | system_prompt.is_some(), |
| 3742 | skills.is_some(), |
| 3743 | workspace.is_some(), |
| 3744 | media.is_some(), |
| 3745 | memory.is_some(), |
| 3746 | project.is_some(), |
| 3747 | skill_group.is_some(), |
| 3748 | plugin.is_some(), |
| 3749 | lifecycle.is_some(), |
| 3750 | control.is_some(), |
| 3751 | export.is_some(), |
| 3752 | debug_receipts.is_some(), |
| 3753 | debug_change.is_some(), |
| 3754 | debug_history.is_some(), |
| 3755 | debug_diff.is_some(), |
| 3756 | debug_undo.is_some(), |
| 3757 | debug_diagnostics.is_some(), |
| 3758 | permissions.is_some(), |
| 3759 | config_status.is_some(), |
| 3760 | config.is_some(), |
| 3761 | pet.is_some(), |
| 3762 | trust.is_some(), |
| 3763 | login.is_some(), |
| 3764 | work_surface.is_some(), |
| 3765 | navigation.is_some(), |
| 3766 | voice_input.is_some(), |
| 3767 | ] { |
| 3768 | assert!(!present); |
| 3769 | } |
| 3770 | assert!( |
| 3771 | fixture.writes.borrow().is_empty(), |
| 3772 | "observations do not write clipboard" |
| 3773 | ); |
| 3774 | } |
| 3775 | |
| 3776 | #[test] |
| 3777 | #[should_panic(expected = "structcopy facet already set")] |
| 3778 | fn structcopy_duplicate_slot_fails_loudly() { |
| 3779 | let mut a = StructcopyFixture { |
| 3780 | delivery: Ok(StructcopyTransport::Native), |
| 3781 | writes: RefCell::default(), |
| 3782 | }; |
| 3783 | let mut b = StructcopyFixture { |
| 3784 | delivery: Ok(StructcopyTransport::Native), |
| 3785 | writes: RefCell::default(), |
| 3786 | }; |
| 3787 | let _ = CommandContexts::empty() |
| 3788 | .with_structcopy(&mut a) |
| 3789 | .with_structcopy(&mut b); |
| 3790 | } |
| 3791 | |
| 3792 | #[test] |
| 3793 | fn structcopy_transport_and_unknown_observations_remain_distinct() { |
| 3794 | for delivery in [ |
| 3795 | Ok(StructcopyTransport::Native), |
| 3796 | Ok(StructcopyTransport::TerminalQueued), |
| 3797 | Err("original host error".into()), |
| 3798 | ] { |
| 3799 | let fixture = StructcopyFixture { |
| 3800 | delivery: delivery.clone(), |
| 3801 | writes: RefCell::default(), |
| 3802 | }; |
| 3803 | assert_eq!(fixture.write_clipboard("exact bytes"), delivery); |
| 3804 | assert_eq!(*fixture.writes.borrow(), ["exact bytes"]); |
| 3805 | } |
| 3806 | let unknown = StructcopyToolResult { |
| 3807 | content: "recorded".into(), |
| 3808 | is_error: None, |
| 3809 | content_blocks: None, |
| 3810 | }; |
| 3811 | assert_ne!( |
| 3812 | unknown, |
| 3813 | StructcopyToolResult { |
| 3814 | is_error: Some(false), |
| 3815 | ..unknown.clone() |
| 3816 | } |
| 3817 | ); |
| 3818 | assert_ne!( |
| 3819 | StructcopyError::Preparation("detail".into()), |
| 3820 | StructcopyError::Unavailable |
| 3821 | ); |
| 3822 | let result = crate::outcome::StructcopyCommandResult::error("detail"); |
| 3823 | assert_eq!(result.message.as_deref(), Some("Error: detail")); |
| 3824 | assert!(result.action.is_none()); |
| 3825 | } |
| 3826 | |
| 3827 | #[test] |
| 3828 | fn structcopy_known_projection_fields_preserve_nulls_and_omission_rules() { |
| 3829 | let plan: StructcopyPlan = serde_json::from_value( |
| 3830 | serde_json::json!({"title":"plan","items":[{"step":"one","status":"in_progress"}]}), |
| 3831 | ) |
| 3832 | .unwrap(); |
| 3833 | assert_eq!( |
| 3834 | serde_json::to_value(plan).unwrap(), |
| 3835 | serde_json::json!({"title":"plan","items":[{"step":"one","status":"in_progress"}]}) |
| 3836 | ); |
| 3837 | let workflow = serde_json::json!({ |
| 3838 | "run_id":"run","status":"degraded","lifecycle_seq":1,"started_at_ms":2,"completed_at_ms":null, |
| 3839 | "source_file":"flow.js","workflow_id":null,"workflow_goal":null, |
| 3840 | "child_count":0,"schema_error_count":0,"schema_repair_count":0,"dispatch_failure_count":0, |
| 3841 | "progress_count":0,"last_progress":null,"event_count":0,"last_event_type":null, |
| 3842 | "leaf_count":null,"branch_count":null,"control_count":null,"execution_status":null, |
| 3843 | "gate_count":1,"blocked_gate_count":0,"gate_status":[{"gate_id":"gate","state":"pending"}], |
| 3844 | "error":null,"usage":{"tasks_reported":0,"input_tokens":0},"events_dropped":4 |
| 3845 | }); |
| 3846 | let parsed: StructcopyWorkflow = serde_json::from_value(workflow.clone()).unwrap(); |
| 3847 | assert_eq!(parsed.status, StructcopyWorkflowStatus::Degraded); |
| 3848 | assert_eq!(parsed.leaf_count, None); |
| 3849 | assert_eq!(parsed.usage.as_ref().unwrap().input_tokens, Some(0)); |
| 3850 | assert_eq!(parsed.usage.as_ref().unwrap().output_tokens, None); |
| 3851 | assert_eq!(serde_json::to_value(parsed).unwrap(), workflow); |
| 3852 | } |
| 3853 | |
| 3854 | #[test] |
| 3855 | fn config_policy_authorities_append_without_widening_each_other() { |
| 3856 | assert_eq!( |
| 3857 | CommandCapabilities::SESSION_STRUCTCOPY.bits_for_test(), |
| 3858 | 1 << 22 |
| 3859 | ); |
| 3860 | assert_eq!(CommandCapabilities::PERMISSIONS.bits_for_test(), 1 << 23); |
| 3861 | assert_eq!(CommandCapabilities::CONFIG_STATUS.bits_for_test(), 1 << 24); |
| 3862 | let permissions = CommandCapabilities::PERMISSIONS | CommandCapabilities::PRESENTATION; |
| 3863 | let status = CommandCapabilities::CONFIG_STATUS | CommandCapabilities::PRESENTATION; |
| 3864 | assert!(!permissions.contains(CommandCapabilities::CONFIG_STATUS)); |
| 3865 | assert!(!status.contains(CommandCapabilities::PERMISSIONS)); |
| 3866 | for caps in [permissions, status] { |
| 3867 | assert!(caps.contains(CommandCapabilities::PRESENTATION)); |
| 3868 | assert!(!caps.contains(CommandCapabilities::MODE_POLICY)); |
| 3869 | assert!(!caps.contains(CommandCapabilities::SESSION)); |
| 3870 | assert!(!caps.contains(CommandCapabilities::WORKSPACE)); |
| 3871 | assert!(!caps.contains(CommandCapabilities::NONE)); |
| 3872 | } |
| 3873 | let empty = CommandContexts::empty().into_parts(); |
| 3874 | assert!(empty.permissions.is_none()); |
| 3875 | assert!(empty.config_status.is_none()); |
| 3876 | } |
| 3877 | |
| 3878 | #[test] |
| 3879 | fn permission_facet_is_object_safe_and_keeps_removal_token_with_rule() { |
| 3880 | use crate::config_policy::*; |
| 3881 | struct Permissions; |
| 3882 | impl CommandPermissionsContext for Permissions { |
| 3883 | fn snapshot(&self) -> Result<PermissionsView, String> { |
| 3884 | Ok(PermissionsView { |
| 3885 | path: PathBuf::from("permissions.toml"), |
| 3886 | file_state: CommandPermissionsFileState::Present, |
| 3887 | rules: vec![PermissionRule { |
| 3888 | action: CommandPermissionAction::Ask, |
| 3889 | tool: "exec_shell".into(), |
| 3890 | command: Some("cargo test".into()), |
| 3891 | command_exact: true, |
| 3892 | path: None, |
| 3893 | workspace: None, |
| 3894 | applies_here: true, |
| 3895 | warning: None, |
| 3896 | removal_token: "opaque-token".into(), |
| 3897 | }], |
| 3898 | approval_mode: CommandApprovalMode::Suggest, |
| 3899 | audit_path: None, |
| 3900 | }) |
| 3901 | } |
| 3902 | fn remove_rule( |
| 3903 | &mut self, |
| 3904 | index: usize, |
| 3905 | expected_token: &str, |
| 3906 | ) -> Result<RemovedPermissionRule, String> { |
| 3907 | if index != 0 || expected_token != "opaque-token" { |
| 3908 | return Err("stale".into()); |
| 3909 | } |
| 3910 | Ok(RemovedPermissionRule { |
| 3911 | action: CommandPermissionAction::Ask, |
| 3912 | tool: "exec_shell".into(), |
| 3913 | }) |
| 3914 | } |
| 3915 | } |
| 3916 | let mut fixture = Permissions; |
| 3917 | let parts = CommandContexts::empty() |
| 3918 | .with_permissions(&mut fixture) |
| 3919 | .into_parts(); |
| 3920 | assert!(parts.config_status.is_none()); |
| 3921 | assert!(parts.mode_policy.is_none()); |
| 3922 | assert!(parts.session.is_none()); |
| 3923 | let facet = parts.permissions.unwrap(); |
| 3924 | let view = facet.snapshot().unwrap(); |
| 3925 | assert_eq!(view.rules[0].removal_token, "opaque-token"); |
| 3926 | assert_eq!(facet.remove_rule(0, "wrong"), Err("stale".into())); |
| 3927 | assert_eq!( |
| 3928 | facet |
| 3929 | .remove_rule(0, &view.rules[0].removal_token) |
| 3930 | .unwrap() |
| 3931 | .tool, |
| 3932 | "exec_shell" |
| 3933 | ); |
| 3934 | } |
| 3935 | |
| 3936 | #[test] |
| 3937 | fn status_facet_is_object_safe_and_construction_never_observes_or_grants_mutation() { |
| 3938 | struct Status; |
| 3939 | impl CommandConfigStatusContext for Status { |
| 3940 | fn snapshot(&self) -> crate::config_policy::ConfigStatusView { |
| 3941 | panic!("envelope construction must not observe status") |
| 3942 | } |
| 3943 | } |
| 3944 | let mut status = Status; |
| 3945 | let parts = CommandContexts::empty() |
| 3946 | .with_config_status(&mut status) |
| 3947 | .into_parts(); |
| 3948 | assert!(parts.config_status.is_some()); |
| 3949 | assert!(parts.permissions.is_none()); |
| 3950 | assert!(parts.presentation.is_none()); |
| 3951 | assert!(parts.mode_policy.is_none()); |
| 3952 | assert!(parts.session.is_none()); |
| 3953 | assert!(parts.workspace.is_none()); |
| 3954 | } |
| 3955 | |
| 3956 | type ParkedJob = ( |
| 3957 | &'static str, |
| 3958 | crate::BackgroundJob, |
| 3959 | crate::BackgroundRequest, |
| 3960 | crate::BackgroundCancel, |
| 3961 | ); |
| 3962 | |
| 3963 | #[derive(Default)] |
| 3964 | struct BackgroundFixture { |
| 3965 | parked: Vec<ParkedJob>, |
| 3966 | } |
| 3967 | |
| 3968 | impl BackgroundFixture { |
| 3969 | fn running(&self, command: &str) -> Option<&crate::BackgroundCancel> { |
| 3970 | self.parked |
| 3971 | .iter() |
| 3972 | .find(|(name, _, _, cancel)| { |
| 3973 | *name == command && !cancel.load(std::sync::atomic::Ordering::SeqCst) |
| 3974 | }) |
| 3975 | .map(|(_, _, _, cancel)| cancel) |
| 3976 | } |
| 3977 | } |
| 3978 | |
| 3979 | impl CommandBackgroundContext for BackgroundFixture { |
| 3980 | fn start( |
| 3981 | &mut self, |
| 3982 | command: &'static str, |
| 3983 | job: crate::BackgroundJob, |
| 3984 | request: crate::BackgroundRequest, |
| 3985 | ) -> Result<String, String> { |
| 3986 | if self.running(command).is_some() { |
| 3987 | return Err(format!("/{command} is already running")); |
| 3988 | } |
| 3989 | self.parked |
| 3990 | .push((command, job, request, crate::BackgroundCancel::default())); |
| 3991 | Ok(format!("/{command} started")) |
| 3992 | } |
| 3993 | |
| 3994 | fn cancel(&mut self, command: &'static str) -> Result<String, String> { |
| 3995 | let Some(cancel) = self.running(command) else { |
| 3996 | return Err(format!("/{command} is not running")); |
| 3997 | }; |
| 3998 | cancel.store(true, std::sync::atomic::Ordering::SeqCst); |
| 3999 | Ok(format!("/{command} cancelled")) |
| 4000 | } |
| 4001 | } |
| 4002 | |
| 4003 | fn echo_job( |
| 4004 | request: crate::BackgroundRequest, |
| 4005 | cancel: crate::BackgroundCancel, |
| 4006 | ) -> crate::outcome::BackgroundCommandResult { |
| 4007 | if cancel.load(std::sync::atomic::Ordering::SeqCst) { |
| 4008 | return crate::outcome::BackgroundCommandResult::error("cancelled"); |
| 4009 | } |
| 4010 | crate::outcome::BackgroundCommandResult::message(request.argument) |
| 4011 | } |
| 4012 | |
| 4013 | fn echo_request(argument: &str) -> crate::BackgroundRequest { |
| 4014 | crate::BackgroundRequest { |
| 4015 | argument: argument.to_string(), |
| 4016 | ..crate::BackgroundRequest::default() |
| 4017 | } |
| 4018 | } |
| 4019 | |
| 4020 | #[test] |
| 4021 | fn background_capability_takes_the_first_bit_past_the_u32_space() { |
| 4022 | assert_eq!(CommandCapabilities::VOICE_INPUT.bits_for_test(), 1u64 << 31); |
| 4023 | assert_eq!(CommandCapabilities::BACKGROUND.bits_for_test(), 1u64 << 32); |
| 4024 | let declared = CommandCapabilities::BACKGROUND | CommandCapabilities::WORKSPACE; |
| 4025 | assert!(declared.contains(CommandCapabilities::BACKGROUND)); |
| 4026 | assert!(declared.contains(CommandCapabilities::WORKSPACE)); |
| 4027 | assert!(!declared.contains(CommandCapabilities::VOICE_INPUT)); |
| 4028 | assert!(!CommandCapabilities::VOICE_INPUT.contains(CommandCapabilities::BACKGROUND)); |
| 4029 | assert!(!CommandCapabilities::SESSION.contains(CommandCapabilities::BACKGROUND)); |
| 4030 | } |
| 4031 | |
| 4032 | #[test] |
| 4033 | fn background_slot_is_optional_and_taken_once() { |
| 4034 | assert!(CommandContexts::empty().take_background().is_none()); |
| 4035 | let mut fixture = BackgroundFixture::default(); |
| 4036 | let mut contexts = CommandContexts::empty().with_background(&mut fixture); |
| 4037 | let background = contexts |
| 4038 | .take_background() |
| 4039 | .expect("selected background facet"); |
| 4040 | assert!(contexts.take_background().is_none()); |
| 4041 | let parts = contexts.into_parts(); |
| 4042 | assert!(parts.workspace.is_none()); |
| 4043 | assert!(parts.presentation.is_none()); |
| 4044 | assert_eq!( |
| 4045 | background.start("update", echo_job, echo_request("done")), |
| 4046 | Ok("/update started".to_string()) |
| 4047 | ); |
| 4048 | } |
| 4049 | |
| 4050 | #[test] |
| 4051 | #[should_panic(expected = "background facet already set")] |
| 4052 | fn background_duplicate_slot_fails_loudly() { |
| 4053 | let mut a = BackgroundFixture::default(); |
| 4054 | let mut b = BackgroundFixture::default(); |
| 4055 | let _ = CommandContexts::empty() |
| 4056 | .with_background(&mut a) |
| 4057 | .with_background(&mut b); |
| 4058 | } |
| 4059 | |
| 4060 | #[test] |
| 4061 | fn background_facet_refuses_a_second_run_and_cancel_signals_the_job() { |
| 4062 | let mut fixture = BackgroundFixture::default(); |
| 4063 | let facet: &mut dyn CommandBackgroundContext = &mut fixture; |
| 4064 | assert!(facet.start("init", echo_job, echo_request("first")).is_ok()); |
| 4065 | assert_eq!( |
| 4066 | facet.start("init", echo_job, echo_request("second")), |
| 4067 | Err("/init is already running".to_string()) |
| 4068 | ); |
| 4069 | assert!( |
| 4070 | facet |
| 4071 | .start("update", echo_job, echo_request("other")) |
| 4072 | .is_ok() |
| 4073 | ); |
| 4074 | assert_eq!(facet.cancel("init"), Ok("/init cancelled".to_string())); |
| 4075 | assert_eq!( |
| 4076 | facet.cancel("init"), |
| 4077 | Err("/init is not running".to_string()) |
| 4078 | ); |
| 4079 | assert!(facet.start("init", echo_job, echo_request("again")).is_ok()); |
| 4080 | |
| 4081 | let results: Vec<_> = fixture |
| 4082 | .parked |
| 4083 | .drain(..) |
| 4084 | .map(|(_, job, request, cancel)| job(request, cancel)) |
| 4085 | .collect(); |
| 4086 | assert!(results[0].is_error, "the cancelled job sees its flag"); |
| 4087 | assert_eq!(results[1].message.as_deref(), Some("other")); |
| 4088 | assert_eq!(results[2].message.as_deref(), Some("again")); |
| 4089 | } |
| 4090 | |
| 4091 | #[test] |
| 4092 | fn background_result_carries_only_the_send_message_follow_up() { |
| 4093 | use crate::outcome::{BackgroundAction, BackgroundCommandResult}; |
| 4094 | let result = BackgroundCommandResult::with_message_and_action( |
| 4095 | "Creating AGENTS.md", |
| 4096 | BackgroundAction::SendMessage("prompt".to_string()), |
| 4097 | ); |
| 4098 | assert_eq!(result.message.as_deref(), Some("Creating AGENTS.md")); |
| 4099 | assert_eq!( |
| 4100 | result.action, |
| 4101 | Some(BackgroundAction::SendMessage("prompt".to_string())) |
| 4102 | ); |
| 4103 | assert!(!result.is_error); |
| 4104 | let failed = BackgroundCommandResult::error("updater failed"); |
| 4105 | assert!(failed.is_error); |
| 4106 | assert!(failed.action.is_none()); |
| 4107 | } |
| 4108 |