返回 CodeWhale
terminal_mode_test_cases_02.rs
根目录 / crates / tui / src / lib / terminal_mode_test_cases_02.rs
1 #[test]
2 fn review_failure_after_publication_preserves_all_usage_and_post_state() {
3 let mut usage = codewhale_models::Usage::default();
4 for response_usage in [
5 codewhale_models::Usage {
6 input_tokens: 21,
7 output_tokens: 5,
8 reasoning_tokens: Some(2),
9 ..Default::default()
10 },
11 codewhale_models::Usage {
12 input_tokens: 34,
13 output_tokens: 8,
14 reasoning_tokens: Some(3),
15 ..Default::default()
16 },
17 ] {
18 codewhale_engine::tools::review::add_review_usage(&mut usage, &response_usage);
19 }
20
21 for (publication, message) in [
22 (
23 ReviewPublication::Uncertain,
24 "PR review publication failed after request dispatch",
25 ),
26 (
27 ReviewPublication::Posted,
28 "review posted but receipt write failed",
29 ),
30 ] {
31 let payload = review_failure_payload(
32 "fixture-provider",
33 "fixture-model",
34 &usage,
35 2,
36 2,
37 publication,
38 message,
39 );
40 assert_eq!(payload["success"], false);
41 assert_eq!(payload["complete"], false);
42 assert_eq!(payload["publication"], publication.as_str());
43 assert_eq!(payload["usage_scope"], "completed_review_passes");
44 assert_eq!(payload["usage_coverage"], "incomplete");
45 assert_eq!(payload["usage"]["input_tokens"], 55);
46 assert_eq!(payload["usage"]["output_tokens"], 13);
47 assert_eq!(payload["usage"]["reasoning_tokens"], 5);
48 assert!(payload.get("review").is_none());
49 assert!(payload.get("receipt").is_none());
50 }
51 }
52
53 #[tokio::test]
54 async fn review_provider_flag_pins_route_for_multi_route_model() {
55 // A genuinely multi-route model: `shared-review-model` is the
56 // configured model of BOTH named routes below, while the active route
57 // (custom-a) does not offer it. (Two custom providers can never be
58 // ambiguous — the route inventory resolves only the active custom
59 // entry — so the multi-route pair has to be named providers.)
60 // Without `--provider`, an explicit `--model` lets cross-provider
61 // inventory inference run, and a model offered by more than one
62 // configured route hard-errors in `resolve_cli_auto_route`
63 // ("available from configured provider route(s): ..."). That error
64 // already tells the user to "Pass `--provider <provider>`" — until
65 // now `codewhale review` had no such flag to pass.
66 let mut config = custom_exec_config("custom-a");
67 {
68 let providers = config.providers.as_mut().expect("providers");
69 for entry in [&mut providers.deepseek, &mut providers.openrouter] {
70 *entry = codewhale_runtime::config::ProviderConfig {
71 model: Some("shared-review-model".to_string()),
72 api_key: Some("local-test-key".to_string()),
73 ..Default::default()
74 };
75 }
76 }
77
78 let inferred = review_args(&["codewhale", "review", "--model", "shared-review-model"]);
79 let (inferred_config, inferred_force) =
80 review_execution_route(&config, &inferred).expect("model-only route");
81 assert!(
82 !inferred_force,
83 "an explicit model with no provider stays open to inventory inference"
84 );
85 assert_eq!(inferred_config.provider.as_deref(), Some("custom-a"));
86
87 // Without the flag the multi-route model must refuse to guess.
88 let err = resolve_cli_exec_route(
89 &inferred_config,
90 &resolve_review_model(&inferred_config, inferred.model.as_deref()),
91 "review diff",
92 inferred_force,
93 None,
94 )
95 .await
96 .expect_err("a model offered by two configured routes must hard-error");
97 let message = err.to_string();
98 assert!(
99 message.contains("available from configured provider route(s)"),
100 "unexpected error: {message}"
101 );
102 assert!(
103 message.contains("deepseek") && message.contains("openrouter"),
104 "both candidate routes must be named: {message}"
105 );
106
107 // With the flag the same model pins to the named route and resolves.
108 let pinned = review_args(&[
109 "codewhale",
110 "review",
111 "--provider",
112 "deepseek",
113 "--model",
114 "shared-review-model",
115 ]);
116 let (pinned_config, pinned_force) =
117 review_execution_route(&config, &pinned).expect("pinned route");
118 assert!(pinned_force, "--provider makes the route authoritative");
119 assert_eq!(pinned_config.provider.as_deref(), Some("deepseek"));
120
121 let route = resolve_cli_exec_route(
122 &pinned_config,
123 &resolve_review_model(&pinned_config, pinned.model.as_deref()),
124 "review diff",
125 pinned_force,
126 None,
127 )
128 .await
129 .expect("pinned review route");
130 let execution = config_for_cli_route(&pinned_config, &route).expect("admitted execution route");
131
132 assert_eq!(
133 route.provider.provider,
134 codewhale_config::ProviderKind::Deepseek
135 );
136 assert_eq!(route.model, "shared-review-model");
137 assert_eq!(
138 execution.active_provider_identity().unwrap().key.as_str(),
139 "deepseek",
140 "the review runs on the provider the flag named"
141 );
142
143 // Pinning a configured custom provider (the workflow's
144 // CODEWHALE_REVIEW_PROVIDER="my-proxy" case) is equally authoritative
145 // for the same multi-route model.
146 let pinned_custom = review_args(&[
147 "codewhale",
148 "review",
149 "--provider",
150 "custom-b",
151 "--model",
152 "shared-review-model",
153 ]);
154 let (custom_config, custom_force) =
155 review_execution_route(&config, &pinned_custom).expect("pinned custom route");
156 assert!(custom_force);
157 let custom_route = resolve_cli_exec_route(
158 &custom_config,
159 &resolve_review_model(&custom_config, pinned_custom.model.as_deref()),
160 "review diff",
161 custom_force,
162 None,
163 )
164 .await
165 .expect("pinned custom review route");
166 let custom_execution =
167 config_for_cli_route(&custom_config, &custom_route).expect("admitted execution route");
168
169 assert_eq!(
170 custom_route.provider.provider,
171 codewhale_config::ProviderKind::Custom
172 );
173 assert_eq!(custom_route.model, "shared-review-model");
174 assert_eq!(
175 custom_execution
176 .active_provider_identity()
177 .unwrap()
178 .key
179 .as_str(),
180 "custom-b",
181 "the review runs on the custom provider the flag named"
182 );
183 }
184
185 #[test]
186 fn review_provider_flag_rejects_unknown_provider() {
187 let config = custom_exec_config("custom-a");
188 let args = review_args(&["codewhale", "review", "--provider", "not-a-provider"]);
189
190 let err = review_execution_route(&config, &args)
191 .expect_err("unknown provider must fail before any diff is fetched");
192 assert!(
193 err.to_string().contains("Unrecognized --provider"),
194 "unexpected error: {err}"
195 );
196 }
197
198 #[test]
199 fn review_without_provider_flag_keeps_configured_route_authoritative() {
200 let config = custom_exec_config("custom-a");
201 let args = review_args(&["codewhale", "review"]);
202
203 let (resolved, force) = review_execution_route(&config, &args).expect("default route");
204 assert!(
205 force,
206 "the configured/default review route is authoritative"
207 );
208 assert_eq!(resolved.provider.as_deref(), Some("custom-a"));
209 }
210
211 fn review_issue(
212 severity: &str,
213 path: Option<&str>,
214 line: Option<u32>,
215 ) -> codewhale_engine::tools::review::ReviewIssue {
216 codewhale_engine::tools::review::ReviewIssue {
217 severity: severity.to_string(),
218 title: format!("{severity} finding"),
219 description: "detail".to_string(),
220 path: path.map(str::to_string),
221 line,
222 ..Default::default()
223 }
224 }
225
226 fn review_suggestion(
227 path: Option<&str>,
228 line: Option<u32>,
229 replacement: Option<&str>,
230 ) -> codewhale_engine::tools::review::ReviewSuggestion {
231 codewhale_engine::tools::review::ReviewSuggestion {
232 path: path.map(str::to_string),
233 line,
234 start_line: None,
235 end_line: None,
236 suggestion: "Use the checked variant".to_string(),
237 replacement: replacement.map(str::to_string),
238 }
239 }
240
241 fn review_with(
242 issues: Vec<codewhale_engine::tools::review::ReviewIssue>,
243 suggestions: Vec<codewhale_engine::tools::review::ReviewSuggestion>,
244 ) -> codewhale_engine::tools::review::ReviewOutput {
245 codewhale_engine::tools::review::ReviewOutput {
246 summary: "summary".to_string(),
247 issues,
248 suggestions,
249 ..Default::default()
250 }
251 }
252
253 /// Two hunks in one file: right lines 10..=12 and 40..=41.
254 ///
255 /// Built from a slice, not one string literal: a `\` continuation strips
256 /// the leading space that marks a context line.
257 fn review_test_diff() -> String {
258 [
259 "diff --git a/crates/tui/src/lib.rs b/crates/tui/src/lib.rs",
260 "index 1111111..2222222 100644",
261 "--- a/crates/tui/src/lib.rs",
262 "+++ b/crates/tui/src/lib.rs",
263 "@@ -10,2 +10,3 @@ fn head() {",
264 " let a = 1;",
265 "+let b = a.unwrap();",
266 " let c = 2;",
267 "@@ -40,2 +40,2 @@ fn tail() {",
268 " let d = 3;",
269 "-let e = d;",
270 "+let e = d + 1;",
271 "",
272 ]
273 .join("\n")
274 }
275
276 #[cfg(unix)]
277 #[test]
278 fn local_review_collects_raw_changes_without_running_diff_helpers() {
279 use std::os::unix::fs::PermissionsExt;
280
281 for helper_kind in ["textconv", "external", "clean", "process"] {
282 for mode in ["working", "staged", "base", "path"] {
283 let workspace = tempfile::tempdir().unwrap();
284 let path = workspace.path();
285 let git = |args: &[&str]| {
286 let output = codewhale_dependencies::Git::command()
287 .expect("git")
288 .current_dir(path)
289 .args([
290 "-c",
291 "core.hooksPath=/dev/null",
292 "-c",
293 "commit.gpgSign=false",
294 ])
295 .args(args)
296 .output()
297 .unwrap();
298 assert!(
299 output.status.success(),
300 "{args:?}: {}",
301 String::from_utf8_lossy(&output.stderr)
302 );
303 String::from_utf8(output.stdout).unwrap()
304 };
305 git(&["init", "-q"]);
306 git(&["config", "user.name", "Review fixture"]);
307 git(&["config", "user.email", "fixture@example.invalid"]);
308 std::fs::write(
309 path.join(".gitattributes"),
310 "*.txt diff=fixture filter=fixture=odd\n",
311 )
312 .unwrap();
313 for name in ["- source.txt", "other.txt"] {
314 std::fs::write(path.join(name), "before\n").unwrap();
315 }
316 std::fs::write(path.join("binary.dat"), b"\0before").unwrap();
317 git(&["add", "."]);
318 git(&["commit", "-qm", "before"]);
319 for name in ["- source.txt", "other.txt"] {
320 std::fs::write(path.join(name), "after\n").unwrap();
321 }
322 std::fs::write(path.join("binary.dat"), b"\0after").unwrap();
323 if matches!(mode, "staged" | "base") {
324 git(&["add", "."]);
325 }
326 if mode == "base" {
327 git(&["commit", "-qm", "after"]);
328 }
329 let script = match helper_kind {
330 "external" => "#!/bin/sh\nprintf touched > helper-marker\nprintf external-diff\n",
331 "clean" => "#!/bin/sh\nprintf touched > helper-marker\ncat\n",
332 "process" => "#!/bin/sh\nprintf touched > helper-marker\nexit 1\n",
333 _ => "#!/bin/sh\nprintf touched > helper-marker\ncat < \"$1\"\n",
334 };
335 let helper = path.join("helper.sh");
336 std::fs::write(&helper, script).unwrap();
337 std::fs::set_permissions(&helper, std::fs::Permissions::from_mode(0o700)).unwrap();
338 git(&[
339 "config",
340 match helper_kind {
341 "external" => "diff.external",
342 "clean" => "filter.fixture=odd.clean",
343 "process" => "filter.fixture=odd.process",
344 _ => "diff.fixture.textconv",
345 },
346 "./helper.sh",
347 ]);
348 if matches!(helper_kind, "clean" | "process") {
349 git(&["config", "filter.fixture=odd.required", "true"]);
350 }
351 let (review_flags, diff_flags): (&[&str], &[&str]) = match mode {
352 "staged" => (&["--staged"], &["--cached"]),
353 "base" => (&["--base", "HEAD^"], &["HEAD^...HEAD"]),
354 "path" => (&["--path=- source.txt"], &["--", "- source.txt"]),
355 _ => (&[], &[]),
356 };
357 // Positive control: the same repository really can invoke its helper.
358 let mut baseline = vec!["diff", "--ext-diff"];
359 baseline.extend_from_slice(diff_flags);
360 let baseline = codewhale_dependencies::Git::command()
361 .unwrap()
362 .current_dir(path)
363 .args(&baseline)
364 .output()
365 .unwrap();
366 let marker = path.join("helper-marker");
367 let conversion = matches!(helper_kind, "clean" | "process");
368 let reads_worktree = matches!(mode, "working" | "path");
369 assert_eq!(
370 marker.exists(),
371 !conversion || reads_worktree,
372 "positive control: {mode}, {helper_kind}"
373 );
374 assert_eq!(
375 baseline.status.success(),
376 helper_kind != "process" || !reads_worktree
377 );
378 if marker.exists() {
379 std::fs::remove_file(&marker).unwrap();
380 }
381
382 let mut argv = vec!["codewhale", "review"];
383 argv.extend_from_slice(review_flags);
384 let mut args = review_args(&argv);
385 let diff = collect_diff(&args, None, path).unwrap();
386 assert!(!marker.exists(), "{mode}, {helper_kind}");
387 assert!(diff.contains("-before\n+after"), "{diff}");
388 assert!(diff.contains("- source.txt"));
389 if mode == "path" {
390 assert!(!diff.contains("other.txt"));
391 assert!(!diff.contains("binary.dat"));
392 } else {
393 assert!(diff.contains("other.txt"));
394 assert!(diff.contains("Binary files") && diff.contains("binary.dat"));
395 }
396 args.max_chars = 1;
397 assert!(
398 collect_diff(&args, None, path)
399 .unwrap_err()
400 .to_string()
401 .contains("No review was run")
402 );
403 assert!(!marker.exists());
404 }
405 }
406 }
407
408 #[test]
409 fn local_review_budget_rejects_changes_beyond_a_shared_prefix() {
410 let prefix = review_test_diff();
411 let limit = prefix.chars().count();
412 for tail in ["+safe_change();\n", "+dangerous_change();\n"] {
413 let diff = format!("{prefix}{tail}");
414 let error = ensure_local_review_diff_fits(&diff, limit).unwrap_err();
415 assert!(error.to_string().contains("No review was run"));
416 assert!(
417 error
418 .to_string()
419 .contains("no receipt was written or accepted")
420 );
421 }
422 }
423
424 #[test]
425 fn review_in_a_bare_repository_is_not_called_outside_git() {
426 let bare = tempfile::tempdir().expect("tempdir");
427 let init = std::process::Command::new("git")
428 .args(["init", "--bare", "-q"])
429 .current_dir(bare.path())
430 .status()
431 .expect("git init --bare");
432 assert!(init.success());
433 let error = ensure_review_workspace_is_git_repo(bare.path())
434 .expect_err("a bare repository has no work tree");
435 let text = error.to_string();
436 assert!(text.starts_with("Not inside a git work tree"), "{text}");
437 }
438
439 #[test]
440 fn review_outside_a_git_repository_says_so_in_one_line() {
441 let outside = tempfile::tempdir().expect("tempdir");
442 let error = ensure_review_workspace_is_git_repo(outside.path())
443 .expect_err("a plain directory is not a work tree");
444 assert_eq!(
445 error.to_string(),
446 format!(
447 "Not inside a git repository (cwd: {})",
448 outside.path().display()
449 )
450 );
451 assert_eq!(
452 first_stderr_line("\nfatal: bad revision 'nope...HEAD'\nusage: git diff\n --stat\n"),
453 "fatal: bad revision 'nope...HEAD'"
454 );
455 }
456
457 #[test]
458 fn exec_resume_error_redacts_the_typed_id_and_names_the_list_command() {
459 let id = "sk-live-pasted-by-mistake";
460 let text = exec_resume_load_error(id);
461 assert!(!text.contains(id), "{text}");
462 assert!(text.contains("<redacted:"), "{text}");
463 assert!(
464 text.ends_with("Run `codewhale sessions` to list ids."),
465 "{text}"
466 );
467 }
468
469 #[test]
470 fn doctor_shows_plain_value_errors_with_a_fix_and_hides_the_rest() {
471 let invalid = {
472 let __cw_config_init_0_0 = Some("chatty".to_string());
473 let mut __cw_config_init_0_value: codewhale_runtime::config::Config = Default::default();
474 __cw_config_init_0_value.verbosity = __cw_config_init_0_0;
475 __cw_config_init_0_value
476 }
477 .validate()
478 .expect_err("unknown verbosity");
479 let wrapped = invalid.context("Failed to load config file /tmp/config.toml");
480 let text = doctor_config_error_text(&wrapped);
481 assert_eq!(
482 text,
483 "doctor configuration validation failed: Invalid verbosity (value not shown): expected normal or concise.\nfix: codewhale config set verbosity normal (if a profile or managed config sets it, correct it there)"
484 );
485 assert!(!text.contains("chatty"), "{text}");
486
487 let opaque = anyhow::anyhow!("TOML parse error near api_key = \"sk-live-secret\"");
488 let text = doctor_config_error_text(&opaque);
489 assert!(text.contains("details omitted"), "{text}");
490 assert!(!text.contains("sk-live-secret"), "{text}");
491 }
492
493 #[test]
494 fn local_review_budget_counts_unicode_characters_without_cutting_input() {
495 let diff = format!("{}+鲸鱼\n", review_test_diff());
496 let limit = diff.chars().count();
497 assert!(diff.len() > limit);
498 ensure_local_review_diff_fits(&diff, limit).unwrap();
499 assert!(ensure_local_review_diff_fits(&diff, limit - 1).is_err());
500 }
501
502 #[test]
503 fn inline_review_comments_keep_only_hunk_locatable_issues() {
504 let review = review_with(
505 vec![
506 review_issue("error", Some("./crates/tui/src/lib.rs"), Some(11)),
507 review_issue("warning", Some("docs/NOT_IN_DIFF.md"), Some(3)),
508 review_issue("info", Some("crates/tui/src/lib.rs"), None),
509 review_issue("error", None, Some(7)),
510 ],
511 Vec::new(),
512 );
513 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
514 // GitHub rejects the entire review (422) when a comment's path is not
515 // part of the diff, and inline comments need a line to anchor to.
516 assert_eq!(comments.len(), 1);
517 assert_eq!(comments[0]["path"], "crates/tui/src/lib.rs");
518 assert_eq!(comments[0]["line"], 11);
519 assert_eq!(comments[0]["side"], "RIGHT");
520 }
521
522 #[test]
523 fn inline_review_comments_drop_one_out_of_hunk_anchor_not_the_whole_review() {
524 // Line 25 is inside the file but between the two hunks. Before the
525 // hunk filter this single bad anchor 422'd the whole review request.
526 let review = review_with(
527 vec![
528 review_issue("error", Some("crates/tui/src/lib.rs"), Some(11)),
529 review_issue("error", Some("crates/tui/src/lib.rs"), Some(25)),
530 review_issue("warning", Some("crates/tui/src/lib.rs"), Some(41)),
531 ],
532 Vec::new(),
533 );
534 let plan = plan_inline_review_comments(&review, &review_test_diff());
535 let lines: Vec<_> = plan.comments.iter().map(|c| c["line"].clone()).collect();
536 assert_eq!(lines, vec![serde_json::json!(11), serde_json::json!(41)]);
537 // The loss is counted and reported, never silent.
538 assert_eq!(plan.dropped_out_of_hunk, 1);
539 assert_eq!(plan.dropped_untouched_file, 0);
540 assert!(
541 plan.receipt()
542 .expect("receipt")
543 .contains("no line inside a diff hunk")
544 );
545 }
546
547 #[test]
548 fn review_suggestion_with_replacement_posts_a_committable_block() {
549 let review = review_with(
550 Vec::new(),
551 vec![review_suggestion(
552 Some("crates/tui/src/lib.rs"),
553 Some(11),
554 Some("let b = a.unwrap_or_default();"),
555 )],
556 );
557 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
558 assert_eq!(comments.len(), 1);
559 let body = comments[0]["body"].as_str().expect("body");
560 assert!(body.starts_with("Use the checked variant"), "{body}");
561 assert!(
562 body.contains("```suggestion\nlet b = a.unwrap_or_default();\n```"),
563 "{body}"
564 );
565 assert_eq!(comments[0]["side"], "RIGHT");
566 // Single-line suggestions must not carry start_line.
567 assert!(comments[0].get("start_line").is_none());
568 }
569
570 #[test]
571 fn multi_line_review_suggestion_spans_start_line_to_line() {
572 let mut suggestion = review_suggestion(
573 Some("crates/tui/src/lib.rs"),
574 Some(12),
575 Some("let b = a.unwrap_or_default();\nlet c = 2;"),
576 );
577 suggestion.start_line = Some(11);
578 suggestion.end_line = Some(12);
579 let review = review_with(Vec::new(), vec![suggestion]);
580 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
581 assert_eq!(comments.len(), 1);
582 assert_eq!(comments[0]["start_line"], 11);
583 assert_eq!(comments[0]["start_side"], "RIGHT");
584 assert_eq!(comments[0]["line"], 12);
585 assert_eq!(comments[0]["side"], "RIGHT");
586 }
587
588 #[test]
589 fn review_suggestion_without_replacement_degrades_to_prose() {
590 // SAFETY: a committable suggestion is one click from being merged, so
591 // a suggestion the model did not back with literal code must never
592 // render as an applicable block.
593 let review = review_with(
594 Vec::new(),
595 vec![review_suggestion(
596 Some("crates/tui/src/lib.rs"),
597 Some(11),
598 None,
599 )],
600 );
601 let plan = plan_inline_review_comments(&review, &review_test_diff());
602 assert_eq!(plan.comments.len(), 1);
603 let body = plan.comments[0]["body"].as_str().expect("body");
604 assert_eq!(body, "Use the checked variant");
605 assert!(!body.contains("```suggestion"), "{body}");
606 assert_eq!(plan.degraded_to_prose, 1);
607 }
608
609 #[test]
610 fn review_suggestion_spanning_outside_a_hunk_degrades_to_prose() {
611 // Line 12 is in a hunk but line 13 is not, so the span cannot be
612 // committed. Keep the finding, drop the one-click apply.
613 let mut suggestion = review_suggestion(
614 Some("crates/tui/src/lib.rs"),
615 Some(12),
616 Some("let c = 2;\nlet d = 3;"),
617 );
618 suggestion.start_line = Some(12);
619 suggestion.end_line = Some(13);
620 let review = review_with(Vec::new(), vec![suggestion]);
621 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
622 // end_line 13 is outside every hunk, so there is no anchor at all.
623 assert!(comments.is_empty());
624
625 // Same replacement anchored at an in-hunk end line but with a start
626 // line outside the hunk: anchor is valid, span is not -> prose.
627 let mut suggestion = review_suggestion(
628 Some("crates/tui/src/lib.rs"),
629 Some(11),
630 Some("let a = 1;\nlet b = a.unwrap_or_default();"),
631 );
632 suggestion.start_line = Some(9);
633 suggestion.end_line = Some(11);
634 let review = review_with(Vec::new(), vec![suggestion]);
635 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
636 assert_eq!(comments.len(), 1);
637 let body = comments[0]["body"].as_str().expect("body");
638 assert!(!body.contains("```suggestion"), "{body}");
639 assert!(comments[0].get("start_line").is_none());
640 }
641
642 #[test]
643 fn review_suggestion_anchored_to_a_deleted_line_is_not_committable() {
644 // Right line 41 is `+let e = d + 1;`; the deleted `-let e = d;` has no
645 // RIGHT-side number, so a model that anchors at the pre-image line 42
646 // gets nothing rather than a suggestion on the wrong line.
647 let review = review_with(
648 Vec::new(),
649 vec![review_suggestion(
650 Some("crates/tui/src/lib.rs"),
651 Some(42),
652 Some("let e = d + 2;"),
653 )],
654 );
655 assert!(
656 plan_inline_review_comments(&review, &review_test_diff())
657 .comments
658 .is_empty()
659 );
660 }
661
662 #[test]
663 fn review_suggestion_replacement_containing_backticks_is_fenced_safely() {
664 let review = review_with(
665 Vec::new(),
666 vec![review_suggestion(
667 Some("crates/tui/src/lib.rs"),
668 Some(11),
669 Some("let b = \"```\";"),
670 )],
671 );
672 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
673 let body = comments[0]["body"].as_str().expect("body");
674 assert!(body.contains("````suggestion\n"), "{body}");
675 assert!(body.ends_with("\n````"), "{body}");
676 }
677
678 #[test]
679 fn review_suggestion_multi_line_replacement_without_span_degrades_to_prose() {
680 // SAFETY: with no start_line/end_line, GitHub would insert these two
681 // lines at line 11 and leave the original line 11 duplicated below.
682 let review = review_with(
683 Vec::new(),
684 vec![review_suggestion(
685 Some("crates/tui/src/lib.rs"),
686 Some(11),
687 Some("let b = a.unwrap_or_default();\nlet c = 2;"),
688 )],
689 );
690 let plan = plan_inline_review_comments(&review, &review_test_diff());
691 assert_eq!(plan.comments.len(), 1);
692 assert!(
693 !plan.comments[0]["body"]
694 .as_str()
695 .expect("body")
696 .contains("```suggestion")
697 );
698 assert_eq!(plan.degraded_to_prose, 1);
699 }
700
701 #[test]
702 fn review_suggestion_prose_fence_is_never_committable() {
703 // SAFETY: only the replacement this reviewer validated against the
704 // diff may be one click from merging. A fence the model wrote inside
705 // its explanation is downgraded to a plain code block.
706 let mut suggestion = review_suggestion(Some("crates/tui/src/lib.rs"), Some(11), None);
707 suggestion.suggestion =
708 "Try this:\n\n```suggestion\nlet b = a.unwrap_or_default();\n```".to_string();
709 let review = review_with(Vec::new(), vec![suggestion]);
710 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
711 let body = comments[0]["body"].as_str().expect("body");
712 assert!(!body.contains("```suggestion"), "{body}");
713 assert!(body.contains("```text"), "{body}");
714 assert!(body.contains("let b = a.unwrap_or_default();"), "{body}");
715 }
716
717 #[test]
718 fn review_suggestion_tilde_prose_fence_is_neutralized() {
719 let mut suggestion = review_suggestion(Some("crates/tui/src/lib.rs"), Some(11), None);
720 suggestion.suggestion = " ~~~suggestion\n x\n ~~~".to_string();
721 let review = review_with(Vec::new(), vec![suggestion]);
722 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
723 let body = comments[0]["body"].as_str().expect("body");
724 assert!(body.contains(" ~~~text"), "{body}");
725 }
726
727 #[test]
728 fn suggestion_fence_behind_list_marker_or_blockquote_is_neutralized() {
729 // Whether GitHub renders a fence nested behind a list marker,
730 // blockquote cue, or ordered-list marker applicable is unverified,
731 // so those shapes are treated as live and downgraded too. Ordinary
732 // prose lines that merely start with a marker stay untouched.
733 let neutralized = neutralize_model_suggestion_fences(
734 "```suggestion\n- ```suggestion\n rm -rf /\n> ```suggestion\n1. ```suggestion\n> - ~~~suggestion\n- fix the `foo` call",
735 );
736 assert_eq!(
737 neutralized,
738 "```text\n- ```text\n rm -rf /\n> ```text\n1. ```text\n> - ~~~text\n- fix the `foo` call"
739 );
740 }
741
742 #[test]
743 fn inline_issue_comment_neutralizes_model_suggestion_fences_in_issue_text() {
744 // SAFETY: regression for a proven hole — the issue title and
745 // description are raw model text, and a ```suggestion fence in
746 // either used to reach the inline comment body verbatim: a
747 // one-click mergeable block that bypassed every span and size
748 // check. Only a replacement validated against the diff hunks may
749 // ever be committable.
750 let mut fenced_description = review_issue("error", Some("crates/tui/src/lib.rs"), Some(11));
751 fenced_description.title = "Cleanup script".to_string();
752 fenced_description.description = "Run this:\n\n```suggestion\nrm -rf /\n```\n".to_string();
753 let mut fenced_title = review_issue("warning", Some("crates/tui/src/lib.rs"), Some(12));
754 fenced_title.title = "Fix all\n```suggestion\nrm -rf ~\n```".to_string();
755 fenced_title.description = "detail".to_string();
756 let review = review_with(vec![fenced_description, fenced_title], Vec::new());
757
758 let comments = plan_inline_review_comments(&review, &review_test_diff()).comments;
759 assert_eq!(comments.len(), 2);
760 for comment in &comments {
761 let body = comment["body"].as_str().expect("body");
762 assert!(!body.contains("```suggestion"), "{body}");
763 }
764 let description_body = comments[0]["body"].as_str().expect("body");
765 assert!(
766 description_body.contains("```text\nrm -rf /"),
767 "{description_body}"
768 );
769 let title_body = comments[1]["body"].as_str().expect("body");
770 assert!(title_body.contains("```text\nrm -rf ~"), "{title_body}");
771 }
772
773 #[test]
774 fn pr_review_unreviewed_note_names_budget_stops_and_plan_skips() {
775 assert_eq!(pr_review_unreviewed_note(None, 0), "the entire diff");
776 fn patch(name: &str, content: &str) -> String {
777 format!(
778 "diff --git a/{name} b/{name}\nnew file mode 100644\n--- /dev/null\n+++ b/{name}\n@@ -0,0 +1 @@\n+{content}\n"
779 )
780 }
781 let patches = [
782 patch("a.txt", "alpha"),
783 patch("b.txt", "bravo"),
784 patch("c.txt", "charlie"),
785 ];
786 let diff = patches.concat();
787 let max_chars = patches
788 .iter()
789 .map(|patch| patch.chars().count())
790 .max()
791 .unwrap();
792 let view = GhPullRequest {
793 changed_files: 3,
794 ..Default::default()
795 };
796 // Two passes of budget: a and b are planned, c is skipped by the plan.
797 let plan = codewhale_engine::tools::review::plan_pr_review(&diff, &view, max_chars, 2).unwrap();
798 let note = pr_review_unreviewed_note(Some(&plan), 0);
799 assert!(note.contains("were never read"), "{note}");
800 assert!(note.contains("a/b.txt b/b.txt"), "{note}");
801 assert!(note.contains("the plan never scheduled"), "{note}");
802 assert!(note.contains("a/c.txt b/c.txt"), "{note}");
803 // One pass done: only b is left unread, but the plan skip still stands.
804 let note = pr_review_unreviewed_note(Some(&plan), 1);
805 assert!(!note.contains("a/a.txt b/a.txt"), "{note}");
806 assert!(note.contains("a/b.txt b/b.txt"), "{note}");
807 assert!(note.contains("a/c.txt b/c.txt"), "{note}");
808 // A complete plan with every pass done names nothing.
809 let complete =
810 codewhale_engine::tools::review::plan_pr_review(&diff, &view, max_chars, 3).unwrap();
811 assert_eq!(
812 pr_review_unreviewed_note(Some(&complete), 3),
813 "no planned file was left unread"
814 );
815 }
816
817 #[tokio::test(flavor = "current_thread")]
818 async fn actual_cli_review_report_host_matches_legacy_and_core_keeps_inline_authority() {
819 let _home = crate::test_support::SealedHome::new();
820 let _policy = codewhale_plugins::activation::TestPolicyGuard::extension_host(false);
821 let Some(node) =
822 codewhale_engine::extension_host::test_support::node_for_tests("cli_review_report_parity")
823 else {
824 return;
825 };
826 let root = tempfile::tempdir().unwrap();
827 let manager = std::sync::Arc::new(codewhale_engine::extension_host::ExtensionHostManager::new(
828 codewhale_engine::extension_host::ExtensionHostOptions {
829 runtime: codewhale_config::extension_host::ExtensionHostRuntime::Node,
830 node_override: Some(node),
831 root: Some(root.path().join("host")),
832 ..Default::default()
833 },
834 ));
835 let _manager = codewhale_engine::extension_host::TestManagerGuard::install(
836 std::sync::Arc::clone(&manager),
837 );
838 let mut flags = codewhale_runtime::features::Features::with_defaults();
839 flags.enable(codewhale_runtime::features::Feature::ReviewHost);
840 let context = codewhale_engine::tools::spec::ToolContext::new(root.path()).with_features(flags);
841 let mut issue = review_issue("warning", Some("crates/tui/src/lib.rs"), Some(11));
842 issue.description = "malicious body\n> - ```suggestion\nnot approved\n```".into();
843 let valid = review_suggestion(
844 Some("crates/tui/src/lib.rs"),
845 Some(11),
846 Some("let b = a.unwrap_or_default();"),
847 );
848 let invalid = review_suggestion(Some("untouched.rs"), Some(11), Some("unowned replacement"));
849 let review = review_with(vec![issue], vec![valid, invalid]);
850 let view = GhPullRequest {
851 head_sha: "a".repeat(40),
852 base_sha: "b".repeat(40),
853 ..Default::default()
854 };
855 let local = render_review_report_for_context(Some(&review), "unused", None, &context)
856 .await
857 .unwrap();
858 assert_eq!(local, render_review_markdown(&review, None));
859 let posted =
860 render_review_report_for_context(Some(&review), "unused", Some((7, &view)), &context)
861 .await
862 .unwrap();
863 assert_eq!(posted, render_review_markdown(&review, Some((7, &view))));
864 assert!(posted.ends_with(&review_advisory_footer(7, &view)));
865 let safe = neutralize_model_suggestion_fences(&posted);
866 assert!(!safe.contains("```suggestion"));
867 assert!(safe.contains("> - ```text"));
868 let plan = plan_inline_review_comments(&review, &review_test_diff());
869 assert_eq!(plan.comments.len(), 2);
870 assert_eq!(plan.dropped_untouched_file, 1);
871 assert!(
872 plan.comments[1]["body"]
873 .as_str()
874 .unwrap()
875 .contains("```suggestion")
876 );
877 assert!(
878 !plan.comments[0]["body"]
879 .as_str()
880 .unwrap()
881 .contains("```suggestion")
882 );
883 assert_eq!(
884 render_review_report_for_context(None, "plain prose", None, &context)
885 .await
886 .unwrap(),
887 "plain prose"
888 );
889 manager.shutdown().await;
890 }
891
892 #[test]
893 fn pr_review_markdown_shows_the_computed_replacement() {
894 // A plain `codewhale review --pr` (no --post) computes and validates
895 // the literal fix; the local report must show it, not just the prose.
896 let view = GhPullRequest {
897 title: "T".to_string(),
898 body: String::new(),
899 base: "main".to_string(),
900 head: "feature".to_string(),
901 url: "https://example.invalid/pr/1".to_string(),
902 head_sha: "abc123".to_string(),
903 ..Default::default()
904 };
905 let mut single = review_suggestion(
906 Some("crates/tui/src/lib.rs"),
907 Some(11),
908 Some("let b = a.unwrap_or_default();"),
909 );
910 single.suggestion = "Use the checked variant".to_string();
911 let mut multi = review_suggestion(
912 Some("crates/tui/src/lib.rs"),
913 Some(11),
914 Some("let b = a.unwrap_or_default();\nlet c = 2;"),
915 );
916 multi.suggestion = "Replace both lines".to_string();
917 multi.start_line = Some(11);
918 multi.end_line = Some(12);
919 let review = review_with(Vec::new(), vec![single, multi]);
920
921 let local = render_review_markdown(&review, None);
922 assert!(local.contains("### Suggestions"), "{local}");
923 assert!(
924 local.contains("\n ```suggestion\n let b = a.unwrap_or_default();\n ```\n"),
925 "{local}"
926 );
927 assert!(
928 local
929 .contains("\n ```suggestion\n let b = a.unwrap_or_default();\n let c = 2;\n ```\n"),
930 "{local}"
931 );
932
933 // The posted body keeps the fix visible but never as a live
934 // one-click block: only diff-validated inline suggestion comments
935 // may carry those to GitHub.
936 let posted = render_review_markdown(&review, Some((1, &view)));
937 assert!(
938 posted.contains("let b = a.unwrap_or_default();"),
939 "{posted}"
940 );
941 assert!(!posted.contains("```suggestion"), "{posted}");
942 assert!(posted.contains("```diff"), "{posted}");
943 }
944
945 /// #6510: a plain-diff review now asks for the one structured review
946 /// contract. A reply that keeps it renders as the Markdown report; one
947 /// that ignores it is printed verbatim, as the old prose path did.
948 #[test]
949 fn plain_diff_review_renders_structured_reply_and_keeps_prose() {
950 let json = r#"{"summary":"One risky unwrap.","issues":[{"severity":"high","title":"Unchecked unwrap","description":"Panics on None.","path":"src/lib.rs","line":11}],"suggestions":[],"overall_assessment":"request changes"}"#;
951 let structured = codewhale_engine::tools::review::ReviewOutput::from_structured_str(json);
952 let report = plain_diff_review_report(structured.as_ref(), json);
953 assert!(report.starts_with("## Codewhale review"), "{report}");
954 assert!(report.contains("One risky unwrap."), "{report}");
955 assert!(report.contains("### Findings"), "{report}");
956 assert!(report.contains("`src/lib.rs:11`"), "{report}");
957 assert!(
958 !report.contains("\"issues\""),
959 "raw JSON must not leak: {report}"
960 );
961
962 let prose = "Looks fine overall; consider a test for the empty case.";
963 let structured = codewhale_engine::tools::review::ReviewOutput::from_structured_str(prose);
964 assert!(structured.is_none());
965 assert_eq!(plain_diff_review_report(structured.as_ref(), prose), prose);
966 }
967
968 #[test]
969 fn oversized_review_suggestion_degrades_to_prose() {
970 use codewhale_engine::tools::review::MAX_COMMITTABLE_SUGGESTION_LINES;
971
972 // A whole-hunk rewrite is not a mechanical fix, so it must not be
973 // committable even though every line is inside the diff.
974 let span = MAX_COMMITTABLE_SUGGESTION_LINES + 5;
975 let added: String = (1..=span).map(|i| format!("+line {i}\n")).collect();
976 let diff = format!(
977 "diff --git a/big.rs b/big.rs\nnew file mode 100644\n--- /dev/null\n\
978 +++ b/big.rs\n@@ -0,0 +1,{span} @@\n{added}"
979 );
980 let replacement: String = (1..=span)
981 .map(|i| format!("line {i} fixed"))
982 .collect::<Vec<_>>()
983 .join("\n");
984
985 let mut suggestion = review_suggestion(Some("big.rs"), Some(span), Some(&replacement));
986 suggestion.start_line = Some(1);
987 suggestion.end_line = Some(span);
988 let review = review_with(Vec::new(), vec![suggestion]);
989 let comments = plan_inline_review_comments(&review, &diff).comments;
990 assert_eq!(comments.len(), 1);
991 let body = comments[0]["body"].as_str().expect("body");
992 assert!(!body.contains("```suggestion"), "{body}");
993
994 // The same shape, trimmed to the budget, stays committable.
995 let mut suggestion = review_suggestion(
996 Some("big.rs"),
997 Some(MAX_COMMITTABLE_SUGGESTION_LINES),
998 Some("line 1 fixed"),
999 );
1000 suggestion.start_line = Some(1);
1001 suggestion.end_line = Some(MAX_COMMITTABLE_SUGGESTION_LINES);
1002 let review = review_with(Vec::new(), vec![suggestion]);
1003 let comments = plan_inline_review_comments(&review, &diff).comments;
1004 assert!(
1005 comments[0]["body"]
1006 .as_str()
1007 .expect("body")
1008 .contains("```suggestion"),
1009 "a span at the budget limit stays committable"
1010 );
1011 }
1012
1013 #[test]
1014 fn resumed_exec_persistence_updates_provider_and_model_as_one_route() {
1015 let saved_a = saved_exec_session(
1016 "custom-a",
1017 codewhale_config::catalog::reviewed::constants::ZAI_GLM_5_2_MODEL,
1018 );
1019 let mut config = custom_exec_config("custom-a");
1020 apply_exec_provider_override(&mut config, "custom-b").expect("custom B");
1021 let model = resolve_exec_resume_route(&mut config, &saved_a, true, None)
1022 .expect("explicit provider route");
1023 let mut persisted = saved_a;
1024 stamp_exec_session_metadata(
1025 &mut persisted,
1026 &model,
1027 codewhale_config::ProviderKind::Custom.as_str(),
1028 Some("custom-b"),
1029 Path::new("/tmp/exec-resume"),
1030 );
1031
1032 let mut next_config = custom_exec_config("custom-a");
1033 let resumed_model = resolve_exec_resume_route(&mut next_config, &persisted, false, None)
1034 .expect("next plain resume");
1035
1036 assert_eq!(persisted.metadata.model_provider, "custom");
1037 assert_eq!(
1038 persisted.metadata.model_provider_id.as_deref(),
1039 Some("custom-b")
1040 );
1041 assert_eq!(persisted.metadata.model, "model-b");
1042 assert_eq!(next_config.provider.as_deref(), Some("custom-b"));
1043 assert_eq!(resumed_model, "model-b");
1044 }
1045
1046 #[test]
1047 fn exec_parses_reasoning_effort_flag_alongside_provider() {
1048 let cli = parse_cli(&[
1049 "codewhale",
1050 "exec",
1051 "--provider",
1052 "openrouter",
1053 "--model",
1054 "glm-5.2",
1055 "--reasoning-effort",
1056 "max",
1057 "audit",
1058 ]);
1059 let Some(Commands::Exec(args)) = cli.command else {
1060 panic!("expected exec command");
1061 };
1062
1063 assert_eq!(args.provider.as_deref(), Some("openrouter"));
1064 assert_eq!(args.model.as_deref(), Some("glm-5.2"));
1065 assert_eq!(args.reasoning_effort.as_deref(), Some("max"));
1066 assert_eq!(args.prompt, vec!["audit"]);
1067 }
1068
1069 #[test]
1070 fn cli_reasoning_effort_normalizes_aliases_and_rejects_typos() {
1071 // The thinking ladder split these: `xhigh` is a tier the CLI can now
1072 // name, `ultracode` is still an alias and resolves to `ultra`.
1073 assert_eq!(
1074 normalize_cli_reasoning_effort("xhigh").unwrap().as_deref(),
1075 Some("xhigh")
1076 );
1077 assert_eq!(
1078 normalize_cli_reasoning_effort("ultracode")
1079 .unwrap()
1080 .as_deref(),
1081 Some("ultra")
1082 );
1083 assert_eq!(normalize_cli_reasoning_effort("default").unwrap(), None);
1084 assert!(normalize_cli_reasoning_effort("expensive").is_err());
1085 }
1086
1087 #[test]
1088 fn saved_reasoning_preference_overrides_config_for_non_tui_runtimes() {
1089 let mut config = {
1090 let __cw_config_init_3_0 = Some("max".to_string());
1091 let __cw_config_init_3_1 = true;
1092 let mut __cw_config_init_3_value: Config = Default::default();
1093 __cw_config_init_3_value.reasoning_effort = __cw_config_init_3_0;
1094 __cw_config_init_3_value.reasoning_effort_inferred_from_legacy_alias = __cw_config_init_3_1;
1095 __cw_config_init_3_value
1096 };
1097 let settings = {
1098 let __cw_config_init_4_0 = Some("low".to_string());
1099 let mut __cw_config_init_4_value: codewhale_runtime::settings::Settings =
1100 Default::default();
1101 __cw_config_init_4_value.reasoning_effort = __cw_config_init_4_0;
1102 __cw_config_init_4_value
1103 };
1104
1105 apply_saved_reasoning_preference(&mut config, &settings);
1106
1107 assert_eq!(config.reasoning_effort(), Some("low"));
1108 assert!(config.reasoning_effort_is_explicit());
1109 }
1110
1111 #[test]
1112 fn exec_accepts_resume_session_flags_for_harnesses() {
1113 let cli = parse_cli(&[
1114 "codewhale",
1115 "exec",
1116 "--resume",
1117 "abc123",
1118 "--output-format",
1119 "stream-json",
1120 "follow up",
1121 ]);
1122 let Some(Commands::Exec(args)) = cli.command else {
1123 panic!("expected exec command");
1124 };
1125
1126 assert_eq!(args.resume.as_deref(), Some("abc123"));
1127 assert_eq!(args.output_format, ExecOutputFormat::StreamJson);
1128 assert_eq!(args.prompt, vec!["follow up"]);
1129 assert!(!args.hooks, "headless hooks stay opt-in by default");
1130 }
1131
1132 #[test]
1133 fn exec_accepts_session_id_alias() {
1134 let cli = parse_cli(&["codewhale", "exec", "--session-id", "abc123", "follow up"]);
1135 let Some(Commands::Exec(args)) = cli.command else {
1136 panic!("expected exec command");
1137 };
1138
1139 assert_eq!(args.session_id.as_deref(), Some("abc123"));
1140 assert_eq!(args.output_format, ExecOutputFormat::Text);
1141 }
1142
1143 #[test]
1144 fn exec_parses_tool_gate_and_hardening_flags() {
1145 let envelope = r#"{"schema_version":1,"owner":"fleet-worker-1","authority":"read_only"}"#;
1146 let cli = parse_cli(&[
1147 "codewhale",
1148 "exec",
1149 "--allowed-tools",
1150 "File,Git",
1151 "--disallowed-tools",
1152 "Bash",
1153 "--max-turns",
1154 "7",
1155 "--max-tool-calls",
1156 "9",
1157 "--append-system-prompt",
1158 "extra rules",
1159 "--tool-authority-json",
1160 envelope,
1161 "--hooks",
1162 "do the thing",
1163 ]);
1164 let Some(Commands::Exec(args)) = cli.command else {
1165 panic!("expected exec command");
1166 };
1167
1168 assert_eq!(
1169 args.allowed_tools.as_deref(),
1170 Some(&["File".to_string(), "Git".to_string()][..])
1171 );
1172 assert_eq!(
1173 args.disallowed_tools.as_deref(),
1174 Some(&["Bash".to_string()][..])
1175 );
1176 assert_eq!(args.max_turns, Some(7));
1177 assert_eq!(args.max_tool_calls, Some(9));
1178 assert_eq!(args.append_system_prompt.as_deref(), Some("extra rules"));
1179 assert_eq!(args.tool_authority_json.as_deref(), Some(envelope));
1180 assert!(args.hooks);
1181 assert_eq!(args.prompt, vec!["do the thing"]);
1182 }
1183
1184 #[test]
1185 fn exec_rejects_zero_max_tool_calls() {
1186 let err = Cli::try_parse_from(["codewhale", "exec", "--max-tool-calls", "0", "do the thing"])
1187 .expect_err("max-tool-calls must be >= 1");
1188 assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
1189 }
1190
1191 #[test]
1192 fn exec_auto_does_not_authorize_sandbox_elevation() {
1193 let cli = parse_cli(&["codewhale", "exec", "--auto", "run it"]);
1194 let Some(Commands::Exec(args)) = cli.command else {
1195 panic!("expected exec command");
1196 };
1197
1198 assert!(!exec_sandbox_elevation_authorized(
1199 args.allow_sandbox_elevation,
1200 args.sandbox.as_deref()
1201 ));
1202 }
1203
1204 #[test]
1205 fn exec_explicit_sandbox_elevation_opt_ins_authorize_retry() {
1206 let danger = parse_cli(&[
1207 "codewhale",
1208 "exec",
1209 "--auto",
1210 "--sandbox",
1211 "danger-full-access",
1212 "run it",
1213 ]);
1214 let Some(Commands::Exec(args)) = danger.command else {
1215 panic!("expected exec command");
1216 };
1217 assert!(exec_sandbox_elevation_authorized(
1218 args.allow_sandbox_elevation,
1219 args.sandbox.as_deref()
1220 ));
1221
1222 let flag = parse_cli(&[
1223 "codewhale",
1224 "exec",
1225 "--auto",
1226 "--allow-sandbox-elevation",
1227 "run it",
1228 ]);
1229 let Some(Commands::Exec(args)) = flag.command else {
1230 panic!("expected exec command");
1231 };
1232 assert!(exec_sandbox_elevation_authorized(
1233 args.allow_sandbox_elevation,
1234 args.sandbox.as_deref()
1235 ));
1236 }
1237
1238 #[test]
1239 fn exec_help_discloses_full_access_and_session_persistence() {
1240 let _env_lock = crate::test_support::lock_test_env();
1241 let _locale = crate::test_support::EnvVarGuard::set("LC_ALL", "en_US.UTF-8");
1242 let mut cli = Cli::command();
1243 let help = cli
1244 .find_subcommand_mut("exec")
1245 .expect("exec command")
1246 .render_help()
1247 .to_string()
1248 .split_whitespace()
1249 .collect::<Vec<_>>()
1250 .join(" ");
1251 assert!(help.contains("--auto"));
1252 assert!(help.contains("--sandbox"));
1253 assert!(help.contains("--allow-sandbox-elevation"));
1254 assert!(help.contains("Full Access"));
1255 assert!(help.contains("no shell sandbox"));
1256 assert!(help.contains("trust mode on"));
1257 assert!(help.contains("--sandbox workspace-write"));
1258 assert!(help.contains("any --sandbox other than danger-full-access"));
1259 assert!(help.contains("equivalent sandbox_mode in config"));
1260 assert!(help.contains("Put -- before a prompt starting with -"));
1261 assert!(help.contains("--no-tools"));
1262 assert!(help.contains("--prompt-file"));
1263 }
1264
1265 #[test]
1266 fn permission_mode_flag_parses_for_root_and_exec_and_respects_managed_switch() {
1267 use codewhale_engine::runtime_options::PermissionMode;
1268
1269 for (raw, expected) in [
1270 ("ask", PermissionMode::Ask),
1271 ("accept-edits", PermissionMode::AcceptEdits),
1272 ("plan", PermissionMode::Plan),
1273 ("auto-review", PermissionMode::AutoReview),
1274 ("full-access", PermissionMode::FullAccess),
1275 ] {
1276 let root = parse_cli_args(&["codewhale", "--permission-mode", raw]).unwrap();
1277 assert_eq!(root.options.permission_mode, Some(expected));
1278
1279 let exec = parse_cli_args(&["codewhale", "exec", "--permission-mode", raw, "hi"]).unwrap();
1280 assert_eq!(exec.options.permission_mode, Some(expected));
1281 }
1282
1283 assert!(parse_cli_args(&["codewhale", "--permission-mode", "unknown"]).is_err());
1284 assert!(parse_cli_args(&["codewhale", "exec", "hi", "--permission-mode", "ask"]).is_err());
1285
1286 let mut config = Config::default();
1287 config.auto_review = Some(codewhale_runtime::config::AutoReviewConfig {
1288 disabled: true,
1289 ..Default::default()
1290 });
1291 let err = validate_cli_permission_mode(
1292 Some(PermissionMode::AutoReview),
1293 &config,
1294 false,
1295 "conflict",
1296 )
1297 .expect_err("auto-review flag must fail when auto_review.disabled = true");
1298 assert!(err.to_string().contains("auto_review.disabled = true"));
1299
1300 assert!(
1301 validate_cli_permission_mode(Some(PermissionMode::Ask), &config, false, "conflict")
1302 .is_ok()
1303 );
1304 assert!(
1305 validate_cli_permission_mode(Some(PermissionMode::Ask), &config, true, "conflict")
1306 .is_err()
1307 );
1308 }
1309
1310 #[test]
1311 fn exec_shell_only_tool_surface_env_sets_shell_allowlist() {
1312 let _env_lock = crate::test_support::lock_test_env();
1313 let _surface =
1314 crate::test_support::EnvVarGuard::set(CODEWHALE_TOOL_SURFACE_ENV, " shell-only ");
1315
1316 let allowed_tools = resolve_exec_allowed_tools(None, exec_tool_surface_from_env())
1317 .expect("shell-only surface should set an allowlist");
1318
1319 assert_eq!(allowed_tools, vec!["bash".to_string()]);
1320 }
1321
1322 #[test]
1323 fn exec_explicit_allowed_tools_override_shell_only_env() {
1324 let _env_lock = crate::test_support::lock_test_env();
1325 let _surface = crate::test_support::EnvVarGuard::set(CODEWHALE_TOOL_SURFACE_ENV, "shell-only");
1326 let explicit = vec![" File ".to_string(), "GIT".to_string()];
1327
1328 let allowed_tools = resolve_exec_allowed_tools(Some(&explicit), exec_tool_surface_from_env())
1329 .expect("explicit allowlist should be preserved");
1330
1331 assert_eq!(allowed_tools, vec!["file".to_string(), "git".to_string()]);
1332 }
1333
1334 #[test]
1335 fn exec_full_tool_surface_env_leaves_allowlist_unset() {
1336 let _env_lock = crate::test_support::lock_test_env();
1337 let _surface = crate::test_support::EnvVarGuard::set(CODEWHALE_TOOL_SURFACE_ENV, "full");
1338
1339 assert_eq!(
1340 resolve_exec_allowed_tools(None, exec_tool_surface_from_env()),
1341 None
1342 );
1343 }
1344
1345 #[test]
1346 fn exec_unknown_tool_surface_env_warns_without_allowlist() {
1347 assert!(should_warn_unknown_exec_tool_surface("shell_onyl"));
1348 assert!(!should_warn_unknown_exec_tool_surface("shell-only"));
1349 assert!(!should_warn_unknown_exec_tool_surface("native-tools"));
1350 assert!(!should_warn_unknown_exec_tool_surface("full"));
1351 assert!(!should_warn_unknown_exec_tool_surface(" "));
1352 assert_eq!(parse_exec_tool_surface("shell_onyl"), None);
1353 }
1354
1355 #[test]
1356 fn exec_rejects_zero_max_turns() {
1357 let err = Cli::try_parse_from(["codewhale", "exec", "--max-turns", "0", "hello"])
1358 .expect_err("max-turns must be >= 1");
1359 assert_eq!(err.kind(), clap::error::ErrorKind::ValueValidation);
1360 }
1361
1361 lines RUST