返回 CodeWhale
hooks.rs
根目录 / crates / tui / src / conformance / hooks.rs
1 //! Hook-receipt family: what a configured shell hook receives and what its
2 //! answer does, before hook orchestration moves to the host (Phase 2).
3 //!
4 //! A case is user hook configuration (the `[[hooks.hooks]]` shape, as JSON)
5 //! plus one tool call. `tool_call_before` cases run the engine's admission
6 //! fold (`turn_loop::run_tool_call_before_hooks`, the gate every frontend
7 //! shares); `tool_call_after` cases build the completion context the way the
8 //! TUI and Runtime API do (`HookContext::with_tool_outcome`) and run
9 //! `HookExecutor::execute`. Each hook command records its stdin and
10 //! environment under `{{capture}}`; the golden pins the verdict (or the
11 //! observer results), the schema-1 stdin document, and the documented
12 //! `DEEPSEEK_*` / `CODEWHALE_*` environment contract.
13 //!
14 //! POSIX shell fixtures: Unix only. The hook session id and temp paths are
15 //! masked.
16
17 use std::path::Path;
18 use std::sync::Arc;
19
20 use serde_json::{Value, json};
21
22 use codewhale_config::AppMode;
23
24 use super::golden::{self, Failures, Sandbox};
25 use codewhale_config::hooks::{HookEvent, HooksConfig};
26 use codewhale_engine::hooks::{HookContext, HookExecutor};
27 use codewhale_engine::tools::spec::{ToolError, ToolResult};
28
29 const FAMILY: &str = "hooks";
30
31 /// The environment keys `HookContext::to_env_vars` documents. Anything else a
32 /// hook child sees is inherited process state, not contract.
33 const HOOK_ENV_CONTRACT: &[&str] = &[
34 "CODEWHALE_SESSION_ID",
35 "CODEWHALE_TOOL_CALL_ID",
36 "DEEPSEEK_ERROR",
37 "DEEPSEEK_MESSAGE",
38 "DEEPSEEK_MODE",
39 "DEEPSEEK_MODEL",
40 "DEEPSEEK_PREVIOUS_MODE",
41 "DEEPSEEK_SESSION_COST",
42 "DEEPSEEK_SESSION_ID",
43 "DEEPSEEK_TOOL_ARGS",
44 "DEEPSEEK_TOOL_CALL_ID",
45 "DEEPSEEK_TOOL_EXECUTION_RECEIPT",
46 "DEEPSEEK_TOOL_EXIT_CODE",
47 "DEEPSEEK_TOOL_NAME",
48 "DEEPSEEK_TOOL_RESULT",
49 "DEEPSEEK_TOOL_STATUS",
50 "DEEPSEEK_TOOL_SUCCESS",
51 "DEEPSEEK_TOTAL_TOKENS",
52 "DEEPSEEK_WORKSPACE",
53 ];
54
55 fn shell_quote(path: &Path) -> String {
56 format!("'{}'", path.to_string_lossy().replace('\'', r"'\''"))
57 }
58
59 /// Write the capture helper a fixture command invokes as `{{capture}} <name>`:
60 /// it saves the hook's stdin and every contract variable that is set, as
61 /// NUL-separated key/value pairs (values may span lines).
62 fn install_capture_helper(capture: &Path) -> String {
63 let script = capture.join("capture.sh");
64 let keys = HOOK_ENV_CONTRACT.join(" ");
65 std::fs::write(
66 &script,
67 format!(
68 "dir=$(dirname \"$0\")\n\
69 cat > \"$dir/$1.stdin\"\n\
70 for key in {keys}; do\n\
71 \x20 eval \"present=\\${{$key+x}}\"\n\
72 \x20 if [ -n \"$present\" ]; then eval \"value=\\${{$key}}\"; printf '%s\\0%s\\0' \"$key\" \"$value\"; fi\n\
73 done > \"$dir/$1.env\"\n"
74 ),
75 )
76 .expect("write capture helper");
77 format!("sh {}", shell_quote(&script))
78 }
79
80 fn hooks_config(case: &Value, capture_command: &str) -> HooksConfig {
81 let raw = serde_json::to_string(&case["hooks"]).expect("case.hooks");
82 // Substitute inside the JSON text, escaping the command for JSON.
83 let quoted = serde_json::to_string(capture_command).expect("quote");
84 let substituted = raw.replace("{{capture}}", &quoted[1..quoted.len() - 1]);
85 let hooks: Value = serde_json::from_str(&substituted).expect("substituted hooks");
86 serde_json::from_value(json!({ "hooks": hooks })).expect("case.hooks is HooksConfig")
87 }
88
89 fn read_capture(capture: &Path, hook: &str) -> Value {
90 let stdin = std::fs::read_to_string(capture.join(format!("{hook}.stdin")));
91 let env = std::fs::read(capture.join(format!("{hook}.env")));
92 let (Ok(stdin), Ok(env)) = (stdin, env) else {
93 return json!({ "name": hook, "ran": false });
94 };
95 let stdin = if stdin.trim().is_empty() {
96 Value::String(String::new())
97 } else {
98 serde_json::from_str::<Value>(&stdin).unwrap_or(Value::String(stdin))
99 };
100 let fields: Vec<String> = env
101 .split(|byte| *byte == 0)
102 .map(|field| String::from_utf8_lossy(field).into_owned())
103 .collect();
104 let env: serde_json::Map<String, Value> = fields
105 .as_chunks::<2>()
106 .0
107 .iter()
108 .filter(|pair| HOOK_ENV_CONTRACT.contains(&pair[0].as_str()))
109 .map(|pair| (pair[0].clone(), Value::String(pair[1].clone())))
110 .collect();
111 json!({ "name": hook, "ran": true, "stdin": stdin, "env": env })
112 }
113
114 fn tool_outcome(case: &Value) -> Result<ToolResult, ToolError> {
115 let outcome = &case["tool"]["outcome"];
116 if let Some(ok) = outcome.get("ok") {
117 return Ok(serde_json::from_value(ok.clone()).expect("tool.outcome.ok is a ToolResult"));
118 }
119 let failed = &outcome["execution_failed"];
120 let message = failed["message"]
121 .as_str()
122 .expect("execution_failed.message");
123 Err(match failed.get("metadata") {
124 Some(metadata) => ToolError::execution_failed_with_metadata(message, metadata.clone()),
125 None => ToolError::execution_failed(message),
126 })
127 }
128
129 fn run_case(name: &str, case: &Value, failures: &mut Failures) {
130 assert!(
131 case["hooks"]
132 .as_array()
133 .is_some_and(|hooks| !hooks.is_empty()),
134 "hook case must contain a hook"
135 );
136 let sandbox = Sandbox::new(case);
137 let capture = sandbox.workspace.join(".conformance-capture");
138 std::fs::create_dir_all(&capture).expect("capture dir");
139 let capture_command = install_capture_helper(&capture);
140 let executor = Arc::new(HookExecutor::new(
141 hooks_config(case, &capture_command),
142 sandbox.workspace.clone(),
143 ));
144 let tool = &case["tool"];
145 let tool_name = tool["name"].as_str().expect("tool.name");
146 let call_id = tool["call_id"].as_str().expect("tool.call_id");
147
148 let outcome = match case["event"].as_str().expect("case.event") {
149 "tool_call_before" => {
150 let runtime = tokio::runtime::Builder::new_current_thread()
151 .enable_all()
152 .build()
153 .expect("runtime");
154 let verdict = runtime.block_on(
155 codewhale_engine::core::engine::turn_loop::run_tool_call_before_hooks(
156 Some(&executor),
157 None, // This surface has no TypeScript host attachment.
158 tool_name,
159 call_id,
160 &tool["input"],
161 AppMode::Agent,
162 &sandbox.workspace,
163 case["model"].as_str().unwrap_or("deepseek-v4-pro"),
164 ),
165 );
166 drop(runtime);
167 match verdict {
168 Ok(admitted) => json!({ "admit": {
169 "requires_approval": admitted.requires_approval,
170 "updated_input": admitted.updated_input,
171 "additional_context": admitted.additional_context,
172 } }),
173 Err(error) => json!({ "refuse": {
174 "kind": golden::tool_error_kind(&error),
175 "detail": error.to_string(),
176 } }),
177 }
178 }
179 "tool_call_after" => {
180 let context = HookContext::new()
181 .with_workspace(sandbox.workspace.clone())
182 .with_session_id(executor.session_id())
183 .with_tool_name(tool_name)
184 .with_tool_call_id(call_id)
185 .with_tool_outcome(&tool_outcome(case));
186 let results = executor.execute(HookEvent::ToolCallAfter, &context);
187 json!({ "observers": results.iter().map(|result| json!({
188 "name": result.name,
189 "success": result.success,
190 "exit_code": result.exit_code,
191 "background": result.background,
192 "stdout": result.stdout,
193 "stderr": result.stderr,
194 "error": result.error,
195 })).collect::<Vec<_>>() })
196 }
197 other => panic!("unknown hook event `{other}`"),
198 };
199
200 let hooks: Vec<Value> = case["hooks"]
201 .as_array()
202 .expect("case.hooks")
203 .iter()
204 .map(|hook| {
205 read_capture(
206 &capture,
207 hook["name"].as_str().expect("every hook is named"),
208 )
209 })
210 .collect();
211 let mut golden_value = json!({ "outcome": outcome, "hooks": hooks });
212 if !hooks.iter().any(|hook| hook["ran"] == true) {
213 failures.push(name, "no configured hook produced a capture");
214 return;
215 }
216 let mut masker = sandbox
217 .masker(&[])
218 .literal(executor.session_id(), "<HOOK_SESSION>");
219 masker.value(&mut golden_value);
220 failures.record(
221 name,
222 golden::check_golden(
223 &golden::family_dir(FAMILY).join(format!("{name}.golden.json")),
224 &golden::pretty(&golden::canonical(&golden_value)),
225 ),
226 );
227 }
228
229 #[test]
230 fn hook_receipts_match_goldens() {
231 let names = golden::case_names(FAMILY);
232 let mut failures = Failures::default();
233 for name in &names {
234 let case = golden::read_case(FAMILY, name);
235 run_case(name, &case, &mut failures);
236 }
237 failures.finish(FAMILY, names.len());
238 }
239
239 lines RUST