|
| 1 | +//! Claude Code 文件工具事件到 Rust 快检的受限转换;只回传脱敏对话摘要。 |
| 2 | +
|
| 3 | +use crate::hook_execute_command::execute_host_input; |
| 4 | +use codeguard_core::{HookEvent, HookTriggerInput, HookWriteOutcome}; |
| 5 | +use serde_json::{Value, json}; |
| 6 | +use std::fs; |
| 7 | +use std::io::Read; |
| 8 | +use std::path::{Path, PathBuf}; |
| 9 | +use std::process::ExitCode; |
| 10 | + |
| 11 | +const MAX_HOST_INPUT_BYTES: u64 = 1024 * 1024; |
| 12 | +const MAX_CONTEXT_CHARS: usize = 1200; |
| 13 | + |
| 14 | +/// 从 Claude Code stdin 读取成功的文件工具事件并注入局部检查摘要。 |
| 15 | +/// 参数包含项目根和原 `hook execute` 的显式选项;返回宿主退出码而非质量结论。 |
| 16 | +pub fn run(args: &[String]) -> ExitCode { |
| 17 | + let [event, rest @ ..] = args else { |
| 18 | + eprintln!("需要 Claude Code 事件与项目路径"); |
| 19 | + return ExitCode::from(2); |
| 20 | + }; |
| 21 | + if event != "post-tool-use" || rest.first().is_none_or(|value| value.starts_with('-')) { |
| 22 | + eprintln!("目前仅支持 post-tool-use PATH --timeout DURATION --format=json"); |
| 23 | + return ExitCode::from(2); |
| 24 | + } |
| 25 | + let root = match Path::new(&rest[0]).canonicalize() { |
| 26 | + Ok(root) if root.is_dir() => root, |
| 27 | + _ => { |
| 28 | + print_context("范围未确定:项目根不可读取;本次源码检查未运行,交付未评估。"); |
| 29 | + return ExitCode::SUCCESS; |
| 30 | + } |
| 31 | + }; |
| 32 | + let mut raw = Vec::new(); |
| 33 | + if std::io::stdin() |
| 34 | + .lock() |
| 35 | + .take(MAX_HOST_INPUT_BYTES + 1) |
| 36 | + .read_to_end(&mut raw) |
| 37 | + .is_err() |
| 38 | + || raw.is_empty() |
| 39 | + || raw.len() as u64 > MAX_HOST_INPUT_BYTES |
| 40 | + { |
| 41 | + print_context("范围未确定:宿主事件缺失或超出输入预算;本次源码检查未运行,交付未评估。"); |
| 42 | + return ExitCode::SUCCESS; |
| 43 | + } |
| 44 | + let host = match codeguard_adapters::parse_unique_json(&raw) { |
| 45 | + Ok(host) => host, |
| 46 | + Err(_) => { |
| 47 | + print_context("范围未确定:宿主事件格式无效;本次源码检查未运行,交付未评估。"); |
| 48 | + return ExitCode::SUCCESS; |
| 49 | + } |
| 50 | + }; |
| 51 | + let path = match selected_file(&root, &host) { |
| 52 | + Some(path) => path, |
| 53 | + None => { |
| 54 | + print_context( |
| 55 | + "范围未确定:成功编辑事件没有可核对的项目内普通文件;本次源码检查未运行,交付未评估。", |
| 56 | + ); |
| 57 | + return ExitCode::SUCCESS; |
| 58 | + } |
| 59 | + }; |
| 60 | + let input = HookTriggerInput { |
| 61 | + event: HookEvent::FileChanged, |
| 62 | + changed_paths: vec![path.clone()], |
| 63 | + task_id: None, |
| 64 | + write_outcome: HookWriteOutcome::Confirmed, |
| 65 | + host_claims_blocking: false, |
| 66 | + }; |
| 67 | + match execute_host_input(rest, &input) { |
| 68 | + Ok((report, _)) => print_context(&summarize(&path, &report)), |
| 69 | + Err(_) => { |
| 70 | + print_context("CodeGuard:宿主事件参数或路由无效;本次源码检查未运行,交付未评估。") |
| 71 | + } |
| 72 | + } |
| 73 | + ExitCode::SUCCESS |
| 74 | +} |
| 75 | + |
| 76 | +fn selected_file(root: &Path, host: &Value) -> Option<String> { |
| 77 | + if host["hook_event_name"] != "PostToolUse" |
| 78 | + || !matches!( |
| 79 | + host["tool_name"].as_str(), |
| 80 | + Some("Write" | "Edit" | "MultiEdit") |
| 81 | + ) |
| 82 | + { |
| 83 | + return None; |
| 84 | + } |
| 85 | + let cwd = Path::new(host["cwd"].as_str()?); |
| 86 | + if !cwd.is_absolute() || !cwd.canonicalize().ok()?.starts_with(root) { |
| 87 | + return None; |
| 88 | + } |
| 89 | + let path = PathBuf::from(host["tool_input"]["file_path"].as_str()?); |
| 90 | + if !host["tool_response"].is_object() { |
| 91 | + return None; |
| 92 | + } |
| 93 | + if !path.is_absolute() || !fs::symlink_metadata(&path).ok()?.file_type().is_file() { |
| 94 | + return None; |
| 95 | + } |
| 96 | + if let Some(response_path) = host["tool_response"]["filePath"].as_str() { |
| 97 | + if response_path != path.to_str()? { |
| 98 | + return None; |
| 99 | + } |
| 100 | + } |
| 101 | + let canonical = path.canonicalize().ok()?; |
| 102 | + let relative = canonical.strip_prefix(root).ok()?.to_str()?; |
| 103 | + if relative.is_empty() || relative.contains('\\') || relative.chars().any(char::is_control) { |
| 104 | + return None; |
| 105 | + } |
| 106 | + Some(relative.to_owned()) |
| 107 | +} |
| 108 | + |
| 109 | +fn summarize(path: &str, report: &Value) -> String { |
| 110 | + let label = if path.len() <= 128 |
| 111 | + && path |
| 112 | + .bytes() |
| 113 | + .all(|byte| byte.is_ascii_alphanumeric() || b"._/-".contains(&byte)) |
| 114 | + { |
| 115 | + path |
| 116 | + } else { |
| 117 | + "<changed-file>" |
| 118 | + }; |
| 119 | + if report["execution"] != "local_observation" { |
| 120 | + let reason = report["reason"] |
| 121 | + .as_str() |
| 122 | + .unwrap_or("local_check_unavailable"); |
| 123 | + return format!( |
| 124 | + "CodeGuard:{label} 的局部检查未运行({reason});请按项目原生检查要求复检,交付未评估。" |
| 125 | + ); |
| 126 | + } |
| 127 | + let files = report["local_feedback"]["files"].as_array(); |
| 128 | + let incomplete = report["local_feedback"]["local_scan_complete"] != true; |
| 129 | + let mut rules = Vec::new(); |
| 130 | + if let Some(files) = files { |
| 131 | + for finding in files.iter().flat_map(|file| { |
| 132 | + file["findings"] |
| 133 | + .as_array() |
| 134 | + .into_iter() |
| 135 | + .flat_map(|findings| findings.iter()) |
| 136 | + }) { |
| 137 | + let Some(rule) = finding["rule_id"].as_str() else { |
| 138 | + continue; |
| 139 | + }; |
| 140 | + if rule.len() <= 32 |
| 141 | + && rule |
| 142 | + .bytes() |
| 143 | + .all(|byte| byte.is_ascii_uppercase() || byte.is_ascii_digit()) |
| 144 | + { |
| 145 | + rules.push(rule.to_owned()); |
| 146 | + if rules.len() == 3 { |
| 147 | + break; |
| 148 | + } |
| 149 | + } |
| 150 | + } |
| 151 | + } |
| 152 | + let count = files.map_or(0, |files| { |
| 153 | + files |
| 154 | + .iter() |
| 155 | + .map(|file| file["findings"].as_array().map_or(0, Vec::len)) |
| 156 | + .sum::<usize>() |
| 157 | + }); |
| 158 | + let status = if incomplete { |
| 159 | + "局部检查未完成" |
| 160 | + } else { |
| 161 | + "局部检查已运行" |
| 162 | + }; |
| 163 | + let detail = if count == 0 { |
| 164 | + "未取得可展示的原生诊断".to_owned() |
| 165 | + } else { |
| 166 | + format!("原生诊断 {count} 项;规则 {}", rules.join(", ")) |
| 167 | + }; |
| 168 | + let summary = format!( |
| 169 | + "CodeGuard:{label} {status},{detail}。请核对原生报告并在修复后复检;完整项目与交付未评估。" |
| 170 | + ); |
| 171 | + summary.chars().take(MAX_CONTEXT_CHARS).collect() |
| 172 | +} |
| 173 | + |
| 174 | +fn print_context(context: &str) { |
| 175 | + println!( |
| 176 | + "{}", |
| 177 | + json!({ |
| 178 | + "hookSpecificOutput": { |
| 179 | + "hookEventName":"PostToolUse", |
| 180 | + "additionalContext":context |
| 181 | + }, |
| 182 | + "systemMessage":"CodeGuard 局部检查反馈" |
| 183 | + }) |
| 184 | + ); |
| 185 | +} |
0 commit comments