返回 CodeWhale
mod.rs
根目录 / crates / engine / src / tools / github / mod.rs
1 //! GitHub context and guarded write tools backed by the `gh` CLI.
2 //!
3 //! Unified surface (piagent phase B): the model sees one tool, `github`,
4 //! with an `action` parameter routing to the per-action logic. The legacy
5 //! `github_*` execution aliases were removed in v0.9.3.
6 //!
7 //! This file is the surface and its guards — which action a call names, and
8 //! whether the input is allowed to run it. The work itself is split by
9 //! responsibility: [`schema`] declares the input contracts, [`actions`] runs
10 //! the actions, [`cli`] builds every `gh`/`git` invocation, and [`shape`]
11 //! turns payloads into tool results.
12
13 use async_trait::async_trait;
14 use serde_json::Value;
15
16 use crate::tools::spec::{
17 ApprovalRequirement, ToolCapability, ToolContext, ToolError, ToolResult, ToolSpec,
18 };
19
20 mod actions;
21 mod cli;
22 pub mod host;
23 pub mod report;
24 mod schema;
25 mod shape;
26
27 use actions::{GithubCloseTarget, close_github_thread};
28 use schema::canonical_schema;
29
30 // The suite at the bottom of this file builds JSON inputs and a recorder path
31 // that nothing in the production surface above names.
32 #[cfg(test)]
33 use serde_json::json;
34 // Unix-only like the recorder helper that returns it (`install_recording_gh`)
35 // — on Windows the test binary compiles without them, and an ungated import
36 // fails `-D warnings`.
37 #[cfg(all(test, unix))]
38 use std::path::PathBuf;
39
40 /// Actions the Plan-mode read-only surface exposes.
41 const READ_ACTIONS: &[&str] = &["issue_context", "pr_context", "report_read"];
42 const ALL_ACTIONS: &[&str] = &[
43 "issue_context",
44 "pr_context",
45 "comment",
46 "close_issue",
47 "close_pr",
48 "report_draft",
49 "report_read",
50 ];
51
52 /// Unified GitHub tool.
53 ///
54 /// One struct, one input schema per surface: the canonical `github` tool
55 /// (all actions, or the read-only subset via [`GithubTool::read_only`]).
56 pub struct GithubTool {
57 name: &'static str,
58 read_only: bool,
59 }
60
61 impl GithubTool {
62 pub const fn new(name: &'static str) -> Self {
63 Self {
64 name,
65 read_only: false,
66 }
67 }
68
69 /// Plan-mode variant: only the read-only actions are advertised and routed.
70 pub const fn read_only(name: &'static str) -> Self {
71 Self {
72 name,
73 read_only: true,
74 }
75 }
76
77 fn allowed_actions(&self) -> &'static [&'static str] {
78 if self.read_only {
79 READ_ACTIONS
80 } else {
81 ALL_ACTIONS
82 }
83 }
84
85 fn resolve_action<'a>(&'a self, input: &'a Value) -> Result<&'a str, ToolError> {
86 let action = input.get("action").and_then(Value::as_str).ok_or_else(|| {
87 ToolError::invalid_input(format!(
88 "github: missing `action` (one of: {})",
89 self.allowed_actions().join(", ")
90 ))
91 })?;
92 if self.allowed_actions().contains(&action) {
93 Ok(action)
94 } else {
95 Err(ToolError::invalid_input(format!(
96 "github: invalid action `{action}` (one of: {})",
97 self.allowed_actions().join(", ")
98 )))
99 }
100 }
101
102 fn action_is_read(action: &str) -> bool {
103 READ_ACTIONS.contains(&action)
104 }
105 }
106
107 #[async_trait]
108 impl ToolSpec for GithubTool {
109 fn name(&self) -> &'static str {
110 self.name
111 }
112
113 fn description(&self) -> &'static str {
114 if self.read_only {
115 "Read GitHub issue/PR context using gh (issue_context, pr_context), or read a local current-session Codewhale issue draft with report_read. Local report publication is unavailable."
116 } else {
117 "GitHub context (issue_context, pr_context) and guarded comment/close_issue/close_pr actions. Closes are rejected when the worktree is dirty unless allow_dirty=true. Also report_draft and report_read: save/revise/read a LOCAL structured Codewhale issue draft in this session, without network or publication. When you observe evidence of a likely Codewhale/runtime/tool defect, you may draft it yourself, separate observations from inferences, offer /feedback review, and continue the original task. Ordinary user-code failures alone are not Codewhale defects; avoid repeated reports. Include only bounded narrative evidence, never prompts, logs, private code, credentials or paths. report_draft revises an existing draft when revises is supplied; exact repeats converge. Draft publication and duplicate search are unavailable: do not use other tools to post the draft without separate explicit user authorization. No push/merge."
118 }
119 }
120
121 fn input_schema(&self) -> Value {
122 canonical_schema(self.allowed_actions(), self.read_only)
123 }
124
125 fn capabilities(&self) -> Vec<ToolCapability> {
126 if self.read_only {
127 vec![ToolCapability::ReadOnly, ToolCapability::Network]
128 } else {
129 vec![ToolCapability::Network, ToolCapability::RequiresApproval]
130 }
131 }
132
133 fn approval_requirement(&self) -> ApprovalRequirement {
134 if self.read_only {
135 ApprovalRequirement::Auto
136 } else {
137 ApprovalRequirement::Required
138 }
139 }
140
141 fn approval_requirement_for(&self, input: &Value) -> ApprovalRequirement {
142 match self.resolve_action(input) {
143 Ok("report_draft") => ApprovalRequirement::Auto,
144 Ok(action) if Self::action_is_read(action) => ApprovalRequirement::Auto,
145 _ => ApprovalRequirement::Required,
146 }
147 }
148
149 fn is_read_only_for(&self, input: &Value) -> bool {
150 match self.resolve_action(input) {
151 Ok(action) => Self::action_is_read(action),
152 Err(_) => self.is_read_only(),
153 }
154 }
155
156 async fn execute(&self, input: Value, context: &ToolContext) -> Result<ToolResult, ToolError> {
157 let action = self.resolve_action(&input)?;
158 if context
159 .features
160 .enabled(codewhale_runtime::features::Feature::GithubHost)
161 {
162 let request = host::Request::capture(action, &input, context)?;
163 return crate::extension_host::manager()
164 .execute_github(request, context)
165 .await;
166 }
167 match action {
168 "report_draft" => report::draft(input, context),
169 "report_read" => report::read(input, context),
170 "issue_context" => self.execute_issue_context(&input, context).await,
171 "pr_context" => self.execute_pr_context(&input, context).await,
172 "comment" => self.execute_comment(&input, context).await,
173 "close_issue" => close_github_thread(input, context, GithubCloseTarget::Issue).await,
174 "close_pr" => close_github_thread(input, context, GithubCloseTarget::Pr).await,
175 action => Err(ToolError::invalid_input(format!(
176 "github: invalid action `{action}`"
177 ))),
178 }
179 }
180 }
181
182 fn validate_evidence(input: &Value, closing: bool) -> Result<(), ToolError> {
183 let evidence = input
184 .get("evidence")
185 .and_then(Value::as_object)
186 .ok_or_else(|| ToolError::invalid_input("evidence object is required"))?;
187 if closing {
188 let criteria = input
189 .get("acceptance_criteria")
190 .and_then(Value::as_array)
191 .filter(|items| !items.is_empty())
192 .ok_or_else(|| ToolError::invalid_input("acceptance_criteria must be non-empty"))?;
193 if criteria
194 .iter()
195 .any(|item| item.as_str().unwrap_or("").trim().is_empty())
196 {
197 return Err(ToolError::invalid_input(
198 "acceptance_criteria entries must be non-empty",
199 ));
200 }
201 for key in ["files_changed", "tests_run", "final_status"] {
202 if !evidence.contains_key(key) {
203 return Err(ToolError::invalid_input(format!(
204 "closure evidence missing {key}"
205 )));
206 }
207 }
208 }
209 Ok(())
210 }
211
212 #[cfg(test)]
213 mod tests {
214 use super::*;
215 use crate::tools::spec::ToolSpec;
216
217 #[tokio::test]
218 async fn close_refuses_when_git_cannot_determine_worktree_status() {
219 use codewhale_dependencies::{ExternalTool, Git};
220
221 let tmp = tempfile::tempdir().expect("tempdir");
222 assert!(
223 Git::output(&["init", "-q"], tmp.path())
224 .unwrap()
225 .status
226 .success()
227 );
228 let context = ToolContext::new(tmp.path());
229 assert!(
230 super::cli::git_status_porcelain(&context)
231 .unwrap()
232 .is_empty()
233 );
234 std::fs::write(tmp.path().join("work.txt"), "uncommitted work").unwrap();
235 assert!(
236 !super::cli::git_status_porcelain(&context)
237 .unwrap()
238 .is_empty()
239 );
240 // A real Git failure can have empty stdout; that is not a clean tree.
241 std::fs::write(tmp.path().join(".git/index"), "invalid index").unwrap();
242 let input = json!({
243 "number": 424_242,
244 "dry_run": true,
245 "acceptance_criteria": ["done"],
246 "evidence": {
247 "files_changed": ["work.txt"],
248 "tests_run": ["local fixture"],
249 "final_status": "green"
250 }
251 });
252 let error = close_github_thread(input, &context, GithubCloseTarget::Issue)
253 .await
254 .expect_err("unknown worktree state must not authorize closure")
255 .to_string();
256 assert!(error.contains("git status failed"), "{error}");
257 assert!(error.contains("cannot verify"), "{error}");
258 }
259
260 #[test]
261 fn close_tools_distinguish_issue_and_pr_wording() {
262 assert_eq!(GithubCloseTarget::Issue.display(), "issue");
263 assert_eq!(GithubCloseTarget::Pr.display(), "PR");
264 }
265
266 // The dirty-worktree refusal is easy to hit on a real close; the
267 // model-facing text must disclose it and the flag that overrides it.
268 #[test]
269 fn close_disclosure_names_the_dirty_worktree_refusal() {
270 let tool = GithubTool::new("github");
271 let description = tool.description();
272 assert!(
273 description.contains("dirty") && description.contains("allow_dirty"),
274 "close descriptions must disclose the dirty-worktree refusal: {description}"
275 );
276 let schema = GithubTool::new("github").input_schema();
277 let allow_dirty = schema["properties"]["allow_dirty"]["description"]
278 .as_str()
279 .expect("allow_dirty must carry a description");
280 assert!(
281 allow_dirty.contains("rejected when the worktree is dirty"),
282 "allow_dirty must disclose the refusal it overrides: {allow_dirty}"
283 );
284 }
285
286 /// D03-03: only the schema's `issue`/`pr` select a thread kind. Any other
287 /// spelling is refused before `gh` runs instead of commenting on an issue.
288 #[tokio::test]
289 async fn comment_refuses_a_target_outside_the_schema_enum() {
290 let tmp = tempfile::tempdir().expect("tempdir");
291 let context = ToolContext::new(tmp.path());
292 let tool = GithubTool::new("github");
293 for target in ["PR", "pull_request", "pull"] {
294 let error = tool
295 .execute(
296 json!({
297 "action": "comment",
298 "target": target,
299 "number": 7,
300 "body": "evidence",
301 "evidence": {},
302 "dry_run": true
303 }),
304 &context,
305 )
306 .await
307 .expect_err("an unknown target must not resolve to an issue")
308 .to_string();
309 assert!(error.contains("target must be"), "{target}: {error}");
310 }
311 for target in ["issue", "pr"] {
312 let result = tool
313 .execute(
314 json!({
315 "action": "comment",
316 "target": target,
317 "number": 7,
318 "body": "evidence",
319 "evidence": {},
320 "dry_run": true
321 }),
322 &context,
323 )
324 .await
325 .expect("schema targets stay valid");
326 assert!(result.content.contains(&format!("{target} #7")));
327 }
328 }
329
330 #[test]
331 fn missing_close_evidence_refuses() {
332 let input = json!({
333 "number": 1,
334 "acceptance_criteria": ["done"],
335 "evidence": { "files_changed": [] }
336 });
337 let err = validate_evidence(&input, true).expect_err("should refuse");
338 assert!(err.to_string().contains("tests_run"));
339 }
340
341 #[test]
342 fn canonical_schema_lists_all_actions() {
343 let schema = GithubTool::new("github").input_schema();
344 let actions = schema["properties"]["action"]["enum"]
345 .as_array()
346 .expect("action enum");
347 for action in [
348 "issue_context",
349 "pr_context",
350 "comment",
351 "close_issue",
352 "close_pr",
353 ] {
354 assert!(
355 actions.iter().any(|value| value.as_str() == Some(action)),
356 "canonical schema must offer action {action}"
357 );
358 }
359 for field in [
360 "number",
361 "target",
362 "body",
363 "evidence",
364 "acceptance_criteria",
365 ] {
366 assert!(
367 schema["properties"][field].is_object(),
368 "canonical schema must carry union field {field}"
369 );
370 }
371 assert_eq!(schema["additionalProperties"], json!(false));
372 }
373
374 #[test]
375 fn read_only_variant_only_offers_read_actions() {
376 let tool = GithubTool::read_only("github");
377 let schema = tool.input_schema();
378 assert_eq!(
379 schema["properties"]["action"]["enum"],
380 json!(["issue_context", "pr_context", "report_read"])
381 );
382 assert!(!schema["properties"]["body"].is_object());
383 assert_eq!(tool.approval_requirement(), ApprovalRequirement::Auto);
384 assert!(tool.is_read_only());
385 }
386
387 #[test]
388 fn canonical_routes_approval_and_read_only_by_action() {
389 let canonical = GithubTool::new("github");
390 assert!(canonical.capabilities().contains(&ToolCapability::Network));
391 assert!(canonical.model_visible());
392 assert_eq!(
393 canonical.approval_requirement_for(&json!({"action": "pr_context"})),
394 ApprovalRequirement::Auto
395 );
396 assert_eq!(
397 canonical.approval_requirement_for(&json!({"action": "close_pr"})),
398 ApprovalRequirement::Required
399 );
400 assert!(canonical.is_read_only_for(&json!({"action": "issue_context"})));
401 assert!(!canonical.is_read_only_for(&json!({"action": "comment"})));
402 }
403
404 #[test]
405 fn canonical_rejects_unknown_or_missing_action() {
406 let tool = GithubTool::new("github");
407 let err = tool
408 .resolve_action(&json!({}))
409 .expect_err("missing action must fail");
410 assert!(err.to_string().contains("missing `action`"));
411 let err = tool
412 .resolve_action(&json!({"action": "merge"}))
413 .expect_err("unknown action must fail");
414 assert!(err.to_string().contains("invalid action"));
415
416 let read_only = GithubTool::read_only("github");
417 let err = read_only
418 .resolve_action(&json!({"action": "close_pr"}))
419 .expect_err("read-only surface must reject write actions");
420 assert!(err.to_string().contains("invalid action"));
421 }
422
423 /// Install a `gh` stand-in that appends its argv to `log` and succeeds.
424 ///
425 /// The close path must never reach a real `gh`, so the recorder both
426 /// proves what was attempted and keeps the test from touching GitHub.
427 /// Unix-only like its consumers: the recorder is a `sh` script, and on
428 /// Windows the ungated helper is dead code that fails `-D warnings` —
429 /// this was the unexplained red `Test (windows-latest)` on #5135.
430 #[cfg(unix)]
431 fn install_recording_gh(dir: &std::path::Path, log: &std::path::Path) -> PathBuf {
432 let bin = dir.join("gh-recorder.sh");
433 std::fs::write(
434 &bin,
435 format!(
436 "#!/bin/sh\nprintf '%s\\n' \"$*\" >> {}\nexit 0\n",
437 log.display()
438 ),
439 )
440 .expect("write recorder");
441 #[cfg(unix)]
442 {
443 use std::os::unix::fs::PermissionsExt;
444 std::fs::set_permissions(&bin, std::fs::Permissions::from_mode(0o755))
445 .expect("chmod recorder");
446 }
447 bin
448 }
449
450 #[cfg(unix)]
451 fn close_input_with_dry_run(dry_run: Value) -> Value {
452 json!({
453 "number": 424_242,
454 "allow_dirty": true,
455 "dry_run": dry_run,
456 "acceptance_criteria": ["done"],
457 "evidence": {
458 "files_changed": ["src/lib.rs"],
459 "tests_run": ["cargo test"],
460 "final_status": "green"
461 }
462 })
463 }
464
465 #[tokio::test]
466 #[cfg(unix)]
467 #[allow(clippy::await_holding_lock)]
468 async fn stringy_dry_run_never_closes_the_thread() {
469 let tmp = tempfile::tempdir().expect("tempdir");
470 let log = tmp.path().join("gh-calls.log");
471 let bin = install_recording_gh(tmp.path(), &log);
472 let ctx = ToolContext::new(tmp.path());
473
474 let _env = crate::test_support::lock_test_env();
475 // SAFETY: serialized behind the process-wide test env lock.
476 unsafe {
477 std::env::set_var("CODEWHALE_GH_BIN", &bin);
478 }
479 let result = close_github_thread(
480 close_input_with_dry_run(json!("true")),
481 &ctx,
482 GithubCloseTarget::Issue,
483 )
484 .await;
485 // SAFETY: same lock; restores the process environment.
486 unsafe {
487 std::env::remove_var("CODEWHALE_GH_BIN");
488 }
489
490 let invocations = std::fs::read_to_string(&log).unwrap_or_default();
491 assert!(
492 invocations.is_empty(),
493 "a stringy dry_run must not invoke gh at all; got: {invocations}"
494 );
495 let err = result.expect_err("dry_run must not be silently coerced to its default");
496 let err = err.to_string();
497 assert!(err.contains("dry_run"), "error must name the field: {err}");
498 assert!(
499 err.contains("boolean") && err.contains("string"),
500 "error must name expected and received types: {err}"
501 );
502 }
503
504 #[tokio::test]
505 #[cfg(unix)]
506 #[allow(clippy::await_holding_lock)]
507 async fn real_dry_run_bool_still_short_circuits() {
508 let tmp = tempfile::tempdir().expect("tempdir");
509 let log = tmp.path().join("gh-calls.log");
510 let bin = install_recording_gh(tmp.path(), &log);
511 let ctx = ToolContext::new(tmp.path());
512
513 let _env = crate::test_support::lock_test_env();
514 // SAFETY: serialized behind the process-wide test env lock.
515 unsafe {
516 std::env::set_var("CODEWHALE_GH_BIN", &bin);
517 }
518 let result = close_github_thread(
519 close_input_with_dry_run(json!(true)),
520 &ctx,
521 GithubCloseTarget::Issue,
522 )
523 .await;
524 // SAFETY: same lock; restores the process environment.
525 unsafe {
526 std::env::remove_var("CODEWHALE_GH_BIN");
527 }
528
529 let result = result.expect("a real bool dry_run stays a dry run");
530 assert!(result.success);
531 assert!(result.content.contains("Dry run"), "{}", result.content);
532 assert!(
533 std::fs::read_to_string(&log).unwrap_or_default().is_empty(),
534 "dry run must not invoke gh"
535 );
536 }
537 }
538
538 lines RUST