返回 CodeWhale
policy_tests.rs
根目录 / crates / tui / src / commands / groups / config / policy_tests.rs
1 //! Real portable handlers exercised with deterministic semantic facets.
2 use super::*;
3 use codewhale_command_contract::config_policy::*;
4 use codewhale_command_contract::facets::CommandPresentationContext;
5 use codewhale_command_contract::handler::{CommandCapabilities as Caps, CommandContexts};
6 use codewhale_command_contract::outcome::ConfigPolicyAction;
7 use codewhale_command_contract::types::{CommandApprovalMode, CommandCurrency, CommandMode};
8 use std::cell::Cell;
9
10 struct English {
11 fail_key: Option<&'static str>,
12 }
13 impl CommandPresentationContext for English {
14 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
15 if self.fail_key == Some(key) {
16 return Err("invalid translation replacement contract".into());
17 }
18 translate_from(
19 include_str!("../../../../../localization/locales/en.json"),
20 key,
21 replacements,
22 )
23 }
24 }
25 struct ZhHans;
26 impl CommandPresentationContext for ZhHans {
27 fn translate(&self, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
28 translate_from(
29 include_str!("../../../../../localization/locales/zh-Hans.json"),
30 key,
31 replacements,
32 )
33 }
34 }
35 fn translate_from(pack: &str, key: &str, replacements: &[(&str, &str)]) -> Result<String, String> {
36 let catalog: serde_json::Value = serde_json::from_str(pack).unwrap();
37 let id: String = key
38 .split('_')
39 .map(|word| {
40 let mut chars = word.chars();
41 chars
42 .next()
43 .unwrap()
44 .to_uppercase()
45 .chain(chars)
46 .collect::<String>()
47 })
48 .collect();
49 let template = catalog[&id]
50 .as_str()
51 .ok_or_else(|| format!("unknown test key {key}"))?;
52 let names: Vec<_> = replacements
53 .iter()
54 .map(|(name, value)| (format!("{{{name}}}"), *value))
55 .collect();
56 Ok(interpolate(
57 template,
58 &names
59 .iter()
60 .map(|(name, value)| (name.as_str(), *value))
61 .collect::<Vec<_>>(),
62 ))
63 }
64 struct Permissions {
65 view: PermissionsView,
66 reads: Cell<usize>,
67 removals: Vec<(usize, String)>,
68 failure: bool,
69 blocked: Vec<BlockedPermissionAction>,
70 }
71 impl Permissions {
72 fn new() -> Self {
73 Self {
74 view: PermissionsView {
75 path: "permissions.toml".into(),
76 file_state: CommandPermissionsFileState::Present,
77 rules: vec![PermissionRule {
78 action: CommandPermissionAction::Allow,
79 tool: "exec_{tool}\n".into(),
80 command: Some("echo {command}".into()),
81 command_exact: true,
82 path: None,
83 workspace: None,
84 applies_here: true,
85 warning: None,
86 removal_token: "opaque".into(),
87 }],
88 approval_mode: CommandApprovalMode::Suggest,
89 audit_path: None,
90 },
91 reads: Cell::new(0),
92 removals: vec![],
93 failure: false,
94 blocked: vec![],
95 }
96 }
97 }
98 impl CommandPermissionsContext for Permissions {
99 fn snapshot(&self) -> Result<PermissionsView, String> {
100 self.reads.set(self.reads.get() + 1);
101 if self.failure {
102 Err("permission read failed".into())
103 } else {
104 Ok(self.view.clone())
105 }
106 }
107 fn remove_rule(&mut self, index: usize, token: &str) -> Result<RemovedPermissionRule, String> {
108 self.removals.push((index, token.into()));
109 if self.failure || index != 0 || token != "opaque" {
110 return Err("stale token".into());
111 }
112 let rule = self.view.rules.remove(index);
113 Ok(RemovedPermissionRule {
114 action: rule.action,
115 tool: rule.tool,
116 })
117 }
118 fn blocked_actions(&self) -> Vec<BlockedPermissionAction> {
119 self.blocked.clone()
120 }
121 }
122 fn permission(p: &mut Permissions, arg: Option<&str>) -> CommandResult {
123 permissions::execute(
124 CommandContexts::empty()
125 .with_permissions(p)
126 .with_presentation(&mut English { fail_key: None }),
127 arg,
128 )
129 }
130 fn status_view() -> ConfigStatusView {
131 ConfigStatusView {
132 version: "fixture".into(),
133 provider: "provider-{model}".into(),
134 model: "model-{provider}".into(),
135 reasoning: "max".into(),
136 workspace: "/workspace".into(),
137 home: None,
138 project_docs: vec![],
139 mode: CommandMode::Agent,
140 approval_mode: CommandApprovalMode::Suggest,
141 trusted: false,
142 allow_shell: false,
143 safety: StatusSafety::ReadOnly { enforced: true },
144 mcp_configured_count: 2,
145 model_pin_drift: None,
146 fleet_drift: None,
147 snapshot_notice: None,
148 context_used: 25,
149 context_window: 100,
150 context_source: StatusContextSource::Catalog,
151 window_override: Some(StatusWindowOverride::Provider("custom".into())),
152 catalog: StatusCatalog {
153 freshness: StatusCatalogFreshness::Bundled,
154 offering_count: 0,
155 fetched_at: None,
156 last_error: None,
157 },
158 cloud_facts: codewhale_protocol::cloud_facts::CloudFactsState::Off,
159 observed_at: 3600,
160 session_id: None,
161 history_count: 3,
162 message_count: 4,
163 input_tokens: 5,
164 output_tokens: 6,
165 total_tokens: 11,
166 cache_hit_tokens: 0,
167 cache_miss_tokens: 0,
168 cost: 0.00001,
169 currency: CommandCurrency::Usd,
170 cost_label: None,
171 metrics: StatusMetrics::default(),
172 ascii_safe: false,
173 tool_outputs: StatusToolOutputs::default(),
174 }
175 }
176 struct Status {
177 view: ConfigStatusView,
178 reads: Cell<usize>,
179 }
180 impl CommandConfigStatusContext for Status {
181 fn snapshot(&self) -> ConfigStatusView {
182 self.reads.set(self.reads.get() + 1);
183 self.view.clone()
184 }
185 }
186 fn report(view: ConfigStatusView) -> String {
187 report_in(view, &mut English { fail_key: None })
188 }
189 fn report_in(view: ConfigStatusView, presentation: &mut dyn CommandPresentationContext) -> String {
190 let expected = view.clone();
191 let mut s = Status {
192 view,
193 reads: Cell::new(0),
194 };
195 let result = status::execute(
196 CommandContexts::empty()
197 .with_config_status(&mut s)
198 .with_presentation(presentation),
199 Some("ignored"),
200 );
201 assert!(!result.is_error, "{result:?}");
202 assert!(result.action.is_none());
203 assert_eq!(s.reads.get(), 1);
204 assert_eq!(s.view, expected);
205 result.message.unwrap()
206 }
207 #[test]
208 fn inventory_metadata_and_authority_are_the_actual_two_entry_slice() {
209 let entries = portable_handlers();
210 assert_eq!(
211 entries
212 .iter()
213 .map(|(info, _)| info.name)
214 .collect::<Vec<_>>(),
215 ["permissions", "status"]
216 );
217 assert_eq!(
218 entries[0].0.aliases,
219 ["permission-rules", "permission_rules"]
220 );
221 assert_eq!(
222 entries[0].0.usage,
223 "/permissions [list|remove <rule-number> [--confirm <token>]]"
224 );
225 assert_eq!(entries[1].0.usage, "/status");
226 for ((_, handler), caps) in entries.into_iter().zip([
227 Caps::PERMISSIONS | Caps::PRESENTATION,
228 Caps::CONFIG_STATUS | Caps::PRESENTATION,
229 ]) {
230 let CommandHandler::Contextual {
231 capabilities,
232 handler,
233 } = handler
234 else {
235 panic!("contextual handler required")
236 };
237 assert_eq!(capabilities, caps);
238 let result = handler(CommandContexts::empty(), None);
239 assert!(result.is_error);
240 assert!(result.action.is_none());
241 }
242 }
243 #[test]
244 fn missing_presentation_rejects_before_any_observation_or_mutation() {
245 let mut p = Permissions::new();
246 assert!(
247 permissions::execute(
248 CommandContexts::empty().with_permissions(&mut p),
249 Some("remove 1 --confirm opaque")
250 )
251 .is_error
252 );
253 assert_eq!(p.reads.get(), 0);
254 assert!(p.removals.is_empty());
255 let mut s = Status {
256 view: status_view(),
257 reads: Cell::new(0),
258 };
259 assert!(status::execute(CommandContexts::empty().with_config_status(&mut s), None).is_error);
260 assert_eq!(s.reads.get(), 0);
261 let mut m = English { fail_key: None };
262 assert!(
263 permissions::execute(CommandContexts::empty().with_presentation(&mut m), None).is_error
264 );
265 assert!(status::execute(CommandContexts::empty().with_presentation(&mut m), None).is_error);
266 }
267 #[test]
268 fn translation_failure_precedes_even_confirmed_permission_write() {
269 let mut p = Permissions::new();
270 let mut m = English {
271 fail_key: Some("permissions_removed"),
272 };
273 let result = permissions::execute(
274 CommandContexts::empty()
275 .with_permissions(&mut p)
276 .with_presentation(&mut m),
277 Some("remove 1 --confirm opaque"),
278 );
279 assert!(result.is_error);
280 assert!(result.action.is_none());
281 assert!(p.removals.is_empty());
282 assert_eq!(p.reads.get(), 0);
283 }
284 #[test]
285 fn permission_grammar_rejects_without_touching_host_and_preview_is_read_only() {
286 let mut p = Permissions::new();
287 for args in [
288 "unknown",
289 "remove",
290 "remove NaN",
291 "remove 0",
292 "remove 1 extra",
293 "remove 1 --bad opaque",
294 ] {
295 let result = permission(&mut p, Some(args));
296 assert!(result.is_error, "{args}");
297 assert!(result.action.is_none());
298 }
299 assert_eq!(p.reads.get(), 0);
300 assert!(p.removals.is_empty());
301 let preview = permission(&mut p, Some(" ReMoVe 1 "));
302 assert!(!preview.is_error);
303 assert!(preview.action.is_none());
304 let text = preview.message.unwrap();
305 assert!(text.contains("/permissions remove 1 --confirm opaque"));
306 assert!(text.contains("echo {command}"));
307 assert_eq!(p.reads.get(), 1);
308 assert!(p.removals.is_empty());
309 assert_eq!(p.view.rules.len(), 1);
310 }
311 #[test]
312 fn confirmation_preserves_opaque_values_and_emits_one_shared_action() {
313 let mut p = Permissions::new();
314 let result = permission(&mut p, Some("remove 1 --CONFIRM opaque"));
315 assert!(!result.is_error);
316 assert_eq!(
317 result.action,
318 Some(ConfigPolicyAction::PermissionRulesChanged)
319 );
320 assert!(result.message.unwrap().contains("exec_{tool}\\n"));
321 assert_eq!(p.removals, [(0, "opaque".into())]);
322 assert_eq!(p.reads.get(), 0);
323 assert!(p.view.rules.is_empty());
324 }
325 #[test]
326 fn read_and_stale_removal_failures_do_not_emit_actions() {
327 let mut p = Permissions::new();
328 p.failure = true;
329 let read = permission(&mut p, None);
330 assert!(read.is_error);
331 assert!(read.message.unwrap().contains("permission read failed"));
332 assert!(read.action.is_none());
333 let remove = permission(&mut p, Some("remove 1 --confirm opaque"));
334 assert!(remove.is_error);
335 assert!(remove.message.unwrap().contains("stale token"));
336 assert!(remove.action.is_none());
337 assert_eq!(p.view.rules.len(), 1);
338 }
339 #[test]
340 fn status_renders_typed_observations_once_and_keeps_runtime_braces() {
341 let text = report(status_view());
342 assert!(text.starts_with("codewhale fixture\n\n"));
343 assert!(text.contains("provider-{model} · model-{provider} · reasoning max"));
344 assert!(text.contains("25.0% used (25 / 100 tokens)"));
345 assert!(text.contains("5 in · 6 out · 11 total · cache not reported"));
346 assert!(text.contains("<$0.0001"));
347 assert!(text.contains("[providers.custom] context_window in config.toml"));
348 assert!(!text.contains("Catalog:"));
349 assert!(!text.contains("Session metrics:"));
350 assert!(text.contains("3 cells · 4 API messages"));
351 }
352 #[test]
353 fn status_optional_drift_notice_catalog_metrics_and_output_keep_order() {
354 let mut view = status_view();
355 view.model_pin_drift = Some("raw-{model}".into());
356 view.fleet_drift = Some(StatusFleetDrift {
357 name: "fleet-{ids}".into(),
358 ids: vec!["operator".into(), "worker".into()],
359 });
360 view.snapshot_notice = Some(StatusSnapshotNotice {
361 workspace: "place-{limit}".into(),
362 scope: StatusSnapshotScope::WorkspaceTooLarge,
363 limit: "2 GB".into(),
364 });
365 view.catalog = StatusCatalog {
366 freshness: StatusCatalogFreshness::Failed,
367 offering_count: 8,
368 fetched_at: Some(0),
369 last_error: Some("offline".into()),
370 };
371 view.context_used = 200;
372 view.window_override = None;
373 view.cache_hit_tokens = 7;
374 view.cache_miss_tokens = 8;
375 view.metrics.turns = 1;
376 view.metrics.steps = 2;
377 view.tool_outputs.artifact_count = 2;
378 view.tool_outputs.artifact_bytes = 1025;
379 let text = report(view);
380 assert!(text.contains("raw-{model}"));
381 assert!(text.contains("fleet-{ids}"));
382 assert!(text.contains("operator, worker"));
383 assert!(text.contains("place-{limit}"));
384 assert!(text.contains("[snapshots] max_workspace_gb"));
385 assert!(text.contains("100.0% used"));
386 assert!(!text.contains("Window override:"));
387 assert!(text.contains("models.dev refresh failed · 8 offerings · fetched 1h ago (offline)"));
388 assert!(text.contains("1 turn · 2 steps"));
389 assert!(text.contains("2 KB"));
390 assert!(text.find("Fleet:").unwrap() < text.find("Context window:").unwrap());
391 }
392 #[test]
393 fn status_window_source_row_follows_the_locale() {
394 let mut view = status_view();
395 view.catalog = StatusCatalog {
396 freshness: StatusCatalogFreshness::Live,
397 offering_count: 9070,
398 fetched_at: Some(3480),
399 last_error: None,
400 };
401 let english = report(view.clone());
402 assert!(
403 english.contains(
404 "Catalog: models.dev live · 9070 offerings · fetched 2m ago · Cloud facts: off"
405 ),
406 "{english}"
407 );
408 let chinese = report_in(view, &mut ZhHans);
409 assert!(
410 chinese.contains("目录: models.dev 实时 · 9070 个可用模型 · 2 分钟前获取 · 云端事实: 关闭"),
411 "{chinese}"
412 );
413 }
414 #[test]
415 fn status_translation_failure_never_observes_host() {
416 let mut s = Status {
417 view: status_view(),
418 reads: Cell::new(0),
419 };
420 let mut m = English {
421 fail_key: Some("status_route_summary"),
422 };
423 let result = status::execute(
424 CommandContexts::empty()
425 .with_config_status(&mut s)
426 .with_presentation(&mut m),
427 None,
428 );
429 assert!(result.is_error);
430 assert!(result.action.is_none());
431 assert_eq!(s.reads.get(), 0);
432 }
433
434 #[test]
435 fn missing_facets_use_the_inherited_exact_error_contract() {
436 let missing = permissions::execute(CommandContexts::empty(), None);
437 assert_eq!(
438 missing.message.as_deref(),
439 Some("Error: Command capability unavailable: permissions")
440 );
441 let missing = status::execute(CommandContexts::empty(), None);
442 assert_eq!(
443 missing.message.as_deref(),
444 Some("Error: Command capability unavailable: config_status")
445 );
446 let mut permissions = Permissions::new();
447 let missing = permissions::execute(
448 CommandContexts::empty().with_permissions(&mut permissions),
449 None,
450 );
451 assert_eq!(
452 missing.message.as_deref(),
453 Some("Error: Command capability unavailable: presentation")
454 );
455 let mut status = Status {
456 view: status_view(),
457 reads: Cell::new(0),
458 };
459 let missing = status::execute(
460 CommandContexts::empty().with_config_status(&mut status),
461 None,
462 );
463 assert_eq!(
464 missing.message.as_deref(),
465 Some("Error: Command capability unavailable: presentation")
466 );
467 assert_eq!(permissions.reads.get(), 0);
468 assert_eq!(status.reads.get(), 0);
469 }
470
471 #[cfg(unix)]
472 #[test]
473 fn permissions_quote_non_utf8_paths_without_losing_bytes_or_emitting_controls() {
474 use std::os::unix::ffi::OsStringExt;
475 let mut permissions = Permissions::new();
476 permissions.view.path = std::ffi::OsString::from_vec(vec![b'b', b'a', b'd', 0xff, 0x1b]).into();
477 let result = permission(&mut permissions, None);
478 assert!(!result.is_error);
479 let text = result.message.unwrap();
480 assert!(text.contains("\"bad\\xff\\x1b\""), "{text}");
481 assert!(!text.contains('\u{1b}'));
482 assert!(permissions.removals.is_empty());
483 }
484
485 #[test]
486 fn permissions_blocked_lists_escapes_and_approves_retry() {
487 let mut permissions = Permissions::new();
488 let empty = permission(&mut permissions, Some("blocked"));
489 assert!(!empty.is_error);
490 let empty_msg = empty.message.unwrap();
491 assert!(empty_msg.contains("No blocked"), "{empty_msg}");
492
493 let no_latest = permission(&mut permissions, Some("blocked approve"));
494 assert!(no_latest.is_error);
495
496 permissions.blocked = vec![
497 BlockedPermissionAction {
498 receipt_id: Some("ar-1".into()),
499 tool_name: "Bash".into(),
500 rule: "guardian".into(),
501 reason: "rm\x1b[31m blocked".into(),
502 action_summary: "rm -rf\n/tmp/x".into(),
503 approvable: true,
504 approved: true,
505 },
506 BlockedPermissionAction {
507 receipt_id: Some("ar-2".into()),
508 tool_name: "Bash".into(),
509 rule: "guardian".into(),
510 reason: "chmod 777".into(),
511 action_summary: "chmod 777 /tmp/y".into(),
512 approvable: true,
513 approved: false,
514 },
515 BlockedPermissionAction {
516 receipt_id: None,
517 tool_name: "MCPTool".into(),
518 rule: "guardian".into(),
519 reason: "unapprovable".into(),
520 action_summary: "ext:run".into(),
521 approvable: false,
522 approved: false,
523 },
524 ];
525
526 let listed = permission(&mut permissions, Some("blocked"));
527 assert!(!listed.is_error);
528 let msg = listed.message.unwrap();
529 assert!(!msg.contains('\x1b'), "{msg}");
530 assert!(msg.contains("ar-2"), "{msg}");
531 assert!(msg.contains("/permissions blocked approve"), "{msg}");
532
533 let latest = permission(&mut permissions, Some("blocked approve"));
534 assert!(!latest.is_error);
535 assert_eq!(
536 latest.action,
537 Some(ConfigPolicyAction::ApproveAutoReviewRetry {
538 target: "ar-2".into(),
539 })
540 );
541
542 let explicit = permission(&mut permissions, Some("blocked approve ar-1"));
543 assert!(!explicit.is_error);
544 assert_eq!(
545 explicit.action,
546 Some(ConfigPolicyAction::ApproveAutoReviewRetry {
547 target: "ar-1".into(),
548 })
549 );
550
551 let bad = permission(&mut permissions, Some("blocked unknown"));
552 assert!(bad.is_error);
553 }
554
554 lines RUST