返回 CodeWhale
hooks.rs
根目录 / crates / commands / src / hooks.rs
1 use std::collections::BTreeMap;
2
3 use codewhale_command_contract::handler::{CommandCapabilities, CommandContexts, CommandHandler};
4 use codewhale_command_contract::hooks::{HooksAction, HooksListSnapshot};
5 use codewhale_command_contract::metadata::{CommandInfo, RegisterCommand};
6 use codewhale_command_contract::model_setup::resolve_action;
7 use codewhale_command_contract::outcome::CommandResult;
8
9 const COMMAND_INFO: CommandInfo = CommandInfo {
10 name: "hooks",
11 aliases: &["hook", "gouzi"],
12 usage: "/hooks [list|events|edit|review|approve <digest>|revoke]",
13 description_key: "cmd_hooks_description",
14 };
15
16 pub struct HooksCmd;
17
18 impl<A: TryFrom<HooksAction>> RegisterCommand<CommandResult<A>> for HooksCmd
19 where
20 A::Error: std::fmt::Display,
21 {
22 fn info() -> &'static CommandInfo {
23 &COMMAND_INFO
24 }
25
26 fn handler() -> CommandHandler<CommandResult<A>> {
27 CommandHandler::Contextual {
28 capabilities: CommandCapabilities::HOOKS,
29 handler: hooks,
30 }
31 }
32 }
33
34 fn hooks<A: TryFrom<HooksAction>>(
35 mut contexts: CommandContexts<'_>,
36 arg: Option<&str>,
37 ) -> CommandResult<A>
38 where
39 A::Error: std::fmt::Display,
40 {
41 if arg.is_none_or(|value| value.trim().is_empty()) {
42 return resolve_action(HooksAction::OpenExtensionsTab, None);
43 }
44 let sub = arg.map(str::trim).unwrap_or("list").to_ascii_lowercase();
45 if let Some(digest) = sub.strip_prefix("approve ") {
46 let Some(ctx) = contexts.take_hooks() else {
47 return CommandResult::error("Command capability unavailable: hooks");
48 };
49 return match ctx.approve_project_hooks(digest.trim()) {
50 Ok(()) => CommandResult::message(
51 "Approved these exact project hooks. They will load on your next session. Changes require another review.",
52 ),
53 Err(error) => CommandResult::error(error),
54 };
55 }
56 match sub.as_str() {
57 "" | "list" | "ls" | "show" => {
58 let Some(ctx) = contexts.take_hooks() else {
59 return CommandResult::error("Command capability unavailable: hooks");
60 };
61 render_list(&ctx.list_hooks())
62 }
63 "events" | "event" | "list-events" => events(),
64 "review" => {
65 let Some(ctx) = contexts.take_hooks() else {
66 return CommandResult::error("Command capability unavailable: hooks");
67 };
68 match ctx.review_project_hooks() {
69 Ok(review) => CommandResult::message(format!(
70 "Project hooks can run shell commands, including scripts they reference. Review the file and those scripts before approval.\n\n{}\n\nTo approve these exact hooks: /hooks approve {}",
71 review.sanitized_contents, review.digest
72 )),
73 Err(error) => CommandResult::error(error),
74 }
75 }
76 "revoke" => {
77 let Some(ctx) = contexts.take_hooks() else {
78 return CommandResult::error("Command capability unavailable: hooks");
79 };
80 match ctx.revoke_project_hooks() {
81 Ok(()) => CommandResult::message(
82 "Project hook approval revoked. Pending hooks will be refused; already running commands are unaffected.",
83 ),
84 Err(_) => CommandResult::error("Could not revoke project hook approval"),
85 }
86 }
87 "edit" | "add" | "new" => resolve_action(HooksAction::EditProjectHooks, None),
88 other => CommandResult::error(format!(
89 "unknown subcommand `{other}`. Try `/hooks list`, `/hooks events`, `/hooks edit`, `/hooks review`, `/hooks approve <digest>`, or `/hooks revoke`."
90 )),
91 }
92 }
93
94 pub fn events<A>() -> CommandResult<A> {
95 let mut out = String::new();
96 out.push_str(
97 "Available hook events (use one of these as `event = \"...\"` in your `[[hooks.hooks]]` entry).\n\
98 Hooks are a TUI runtime feature: `codewhale exec`, the CLI dispatcher, the app-server,\n\
99 and the workflow tool do not fire them.\n\n",
100 );
101 let ordered = [
102 ("session_start", "fires once when the TUI launches"),
103 ("session_end", "fires once on graceful shutdown"),
104 ("turn_end", "fires after a turn completes (observer-only)"),
105 (
106 "message_submit",
107 "fires before model dispatch; can transform or block submitted text",
108 ),
109 (
110 "tool_call_before",
111 "fires before each tool call; can allow/deny/ask, rewrite input, add context",
112 ),
113 (
114 "tool_call_after",
115 "fires after each tool call (observer-only)",
116 ),
117 ("mode_change", "fires on Plan/Work transitions"),
118 ("on_error", "fires on transport / capacity / tool errors"),
119 (
120 "subagent_spawn",
121 "fires when a sub-agent starts (observer-only)",
122 ),
123 (
124 "subagent_complete",
125 "fires when a sub-agent completes, fails, or is cancelled (observer-only)",
126 ),
127 (
128 "shell_env",
129 "fires before each exec_shell; stdout KEY=VALUE lines are merged into its environment",
130 ),
131 (
132 "session_idle",
133 "fires when the session settles back to idle after a turn or a wait (observer-only)",
134 ),
135 (
136 "session_error",
137 "fires when a turn ends in a terminal failure; absorbed tool failures never fire it (observer-only)",
138 ),
139 (
140 "waiting_for_user",
141 "fires when an approval prompt opens, a question is presented, or a goal continuation parks (observer-only)",
142 ),
143 ("session_busy", "idle / waiting → in_progress"),
144 (
145 "pre_compact",
146 "fires before context compaction summarizes and trims history (observer-only)",
147 ),
148 ];
149 for (event, desc) in ordered {
150 out.push_str(&format!(" - `{event}` — {desc}\n"));
151 }
152 out.push_str(
153 "\nOnly `message_submit`, `tool_call_before`, and `shell_env` can steer a turn.\n\
154 Observer-only means the *result* is ignored — the command still runs\n\
155 and can have any external side effect.\n\n\
156 Full contract: docs/HOOKS.md\n",
157 );
158 CommandResult::message(out.trim_end().to_string())
159 }
160
161 fn render_list<A>(snapshot: &HooksListSnapshot) -> CommandResult<A> {
162 if snapshot.hooks.is_empty() && snapshot.problem_summaries.is_empty() {
163 return CommandResult::message(
164 "No hooks configured. Add a `[[hooks.hooks]]` entry to `~/.codewhale/config.toml` to define one.",
165 );
166 }
167 if snapshot.hooks.is_empty() {
168 let mut out =
169 String::from("No runnable hooks. Every configured entry was rejected at load:\n\n");
170 for problem in &snapshot.problem_summaries {
171 out.push_str(&format!(" - {problem}\n"));
172 }
173 return CommandResult::message(out.trim_end().to_string());
174 }
175
176 let mut out = String::new();
177 out.push_str(&format!(
178 "{} configured hook(s) (global enabled: {}):\n\n",
179 snapshot.hooks.len(),
180 if snapshot.enabled {
181 "yes"
182 } else {
183 "no — all hooks suppressed"
184 }
185 ));
186
187 let mut by_event: BTreeMap<&str, Vec<_>> = BTreeMap::new();
188 for hook in &snapshot.hooks {
189 by_event
190 .entry(hook.event_label.as_str())
191 .or_default()
192 .push(hook);
193 }
194
195 for (event, hooks) in by_event {
196 out.push_str(&format!("### {event}\n"));
197 for hook in hooks {
198 let bg = if hook.background && hook.honors_background {
199 " [bg, submitted not awaited]"
200 } else {
201 ""
202 };
203 let condition = hook
204 .condition_summary
205 .as_deref()
206 .map(|c| format!(" if {c}"))
207 .unwrap_or_default();
208 out.push_str(&format!(
209 " - {}{bg} (timeout {}){condition}\n $ {}\n",
210 hook.label, hook.timeout_display, hook.command_preview
211 ));
212 }
213 out.push('\n');
214 }
215
216 if !snapshot.problem_summaries.is_empty() {
217 out.push_str("### configuration problems\n");
218 for problem in &snapshot.problem_summaries {
219 out.push_str(&format!(" - {problem}\n"));
220 }
221 out.push('\n');
222 }
223
224 if !snapshot.enabled {
225 out.push_str(
226 "Hooks are globally disabled — set `[hooks].enabled = true` in `config.toml` to fire them.\n",
227 );
228 }
229
230 CommandResult::message(out.trim_end().to_string())
231 }
232
233 #[cfg(test)]
234 mod tests {
235 use super::*;
236 use codewhale_command_contract::hooks::CommandHooksContext;
237 use codewhale_command_contract::hooks::ProjectHooksReview;
238
239 #[derive(Default)]
240 struct MockHooksContext {
241 snapshot: HooksListSnapshot,
242 approved_digest: Option<String>,
243 revoked: bool,
244 }
245
246 impl CommandHooksContext for MockHooksContext {
247 fn list_hooks(&self) -> HooksListSnapshot {
248 self.snapshot.clone()
249 }
250 fn review_project_hooks(&self) -> Result<ProjectHooksReview, String> {
251 Ok(ProjectHooksReview {
252 digest: "abc123".to_string(),
253 sanitized_contents: "[[hooks]]".to_string(),
254 })
255 }
256 fn approve_project_hooks(&mut self, digest: &str) -> Result<(), String> {
257 self.approved_digest = Some(digest.to_string());
258 Ok(())
259 }
260 fn revoke_project_hooks(&mut self) -> Result<(), String> {
261 self.revoked = true;
262 Ok(())
263 }
264 }
265
266 #[test]
267 fn bare_and_edit_hooks_dispatch_without_capability() {
268 let CommandHandler::Contextual {
269 capabilities,
270 handler,
271 } = HooksCmd::handler()
272 else {
273 panic!("expected contextual handler");
274 };
275 assert_eq!(capabilities, CommandCapabilities::HOOKS);
276 let res: CommandResult<HooksAction> = handler(CommandContexts::empty(), None);
277 assert_eq!(res.action, Some(HooksAction::OpenExtensionsTab));
278 let res: CommandResult<HooksAction> = handler(CommandContexts::empty(), Some("edit"));
279 assert_eq!(res.action, Some(HooksAction::EditProjectHooks));
280 let res: CommandResult<HooksAction> = handler(CommandContexts::empty(), Some("events"));
281 assert!(!res.is_error);
282 assert!(res.message.unwrap().contains("session_start"));
283 }
284
285 #[test]
286 fn contextual_hooks_require_capability() {
287 let CommandHandler::Contextual { handler, .. } = HooksCmd::handler() else {
288 panic!("expected contextual handler");
289 };
290 let res: CommandResult<HooksAction> = handler(CommandContexts::empty(), Some("list"));
291 assert!(res.is_error);
292 assert_eq!(
293 res.message.as_deref(),
294 Some("Error: Command capability unavailable: hooks")
295 );
296 }
297
298 #[test]
299 fn review_approve_and_revoke_preserve_receipts() {
300 let CommandHandler::Contextual { handler, .. } = HooksCmd::handler() else {
301 panic!("expected contextual handler");
302 };
303 let mut ctx = MockHooksContext::default();
304 let review: CommandResult<HooksAction> = handler(
305 CommandContexts::empty().with_hooks(&mut ctx),
306 Some("review"),
307 );
308 assert!(review.message.unwrap().contains("/hooks approve abc123"));
309
310 let approve: CommandResult<HooksAction> = handler(
311 CommandContexts::empty().with_hooks(&mut ctx),
312 Some("approve abc123"),
313 );
314 assert!(
315 approve
316 .message
317 .unwrap()
318 .contains("Approved these exact project hooks")
319 );
320 assert_eq!(ctx.approved_digest.as_deref(), Some("abc123"));
321
322 let revoke: CommandResult<HooksAction> = handler(
323 CommandContexts::empty().with_hooks(&mut ctx),
324 Some("revoke"),
325 );
326 assert!(
327 revoke
328 .message
329 .unwrap()
330 .contains("Project hook approval revoked")
331 );
332 assert!(ctx.revoked);
333 }
334 }
335
335 lines RUST