返回 CodeWhale
gate_receipts.rs
根目录 / crates / tui / src / tui / gate_receipts.rs
1 //! Transcript receipts for permission decisions nobody was prompted for.
2 //!
3 //! Auto-Review makes decisions a person would otherwise never see: the model
4 //! guardian allows or denies a held call, the deterministic policy blocks one,
5 //! or a hold that needs a person is denied instead of opening a modal. The
6 //! audit log keeps the full record; these one-line notes make the decision
7 //! and its stated reason visible in the transcript, the way a permission
8 //! prompt would have been.
9 //!
10 //! Proven-safe deterministic allows are deliberately silent (a routine read
11 //! is not news) — the same convention other harnesses use for rule-based
12 //! auto-approvals.
13
14 use std::borrow::Cow;
15
16 use codewhale_engine::core::events::{ToolGate, ToolGateVerdict, bounded_gate_reason};
17 use codewhale_localization::{Locale, MessageId, tr};
18
19 /// Longest tool name echoed into a receipt. Tool names are model-authored
20 /// text on some wire dialects, so they are bounded like every other field.
21 const MAX_TOOL_NAME_CHARS: usize = 64;
22
23 /// One transcript line for a [`codewhale_engine::core::events::Event::ToolGateDecision`].
24 #[must_use]
25 pub fn tool_gate_receipt(
26 locale: Locale,
27 tool_name: &str,
28 gate: ToolGate,
29 decision: ToolGateVerdict,
30 risk: Option<&str>,
31 reviewer_model: Option<&str>,
32 reason: &str,
33 ) -> String {
34 let id = match (gate, decision) {
35 (ToolGate::AutoReviewGuardian, ToolGateVerdict::Allowed) => {
36 MessageId::AutoReviewReceiptGuardianAllowed
37 }
38 (ToolGate::AutoReviewGuardian, ToolGateVerdict::Denied) => {
39 MessageId::AutoReviewReceiptGuardianDenied
40 }
41 (ToolGate::AutoReviewGuardian, ToolGateVerdict::Unavailable) => {
42 MessageId::AutoReviewReceiptGuardianUnavailable
43 }
44 // The deterministic engine only surfaces blocks; an allow it proved
45 // safe stays silent and an unavailable deterministic verdict does not
46 // exist (the engine always answers).
47 (
48 ToolGate::AutoReviewDeterministic,
49 ToolGateVerdict::Denied | ToolGateVerdict::Allowed | ToolGateVerdict::Unavailable,
50 ) => MessageId::AutoReviewReceiptDeterministicBlocked,
51 };
52 let mut rendered = fill(
53 tr(locale, id),
54 tool_name,
55 risk.unwrap_or("unknown"),
56 &bounded_gate_reason(reason),
57 );
58 if gate == ToolGate::AutoReviewGuardian
59 && let Some(model) = reviewer_model
60 .map(bounded_gate_reason)
61 .filter(|m| !m.is_empty())
62 {
63 rendered.push_str(&format!(" [reviewer: {model}]"));
64 }
65 rendered
66 }
67
68 #[must_use]
69 #[allow(clippy::too_many_arguments)]
70 pub fn tool_gate_receipt_with_retry_info(
71 locale: Locale,
72 tool_name: &str,
73 gate: ToolGate,
74 decision: ToolGateVerdict,
75 risk: Option<&str>,
76 reviewer_model: Option<&str>,
77 reason: &str,
78 receipt_id: Option<&str>,
79 ) -> String {
80 let mut receipt = tool_gate_receipt(
81 locale,
82 tool_name,
83 gate,
84 decision,
85 risk,
86 reviewer_model,
87 reason,
88 );
89 if let Some(id) = receipt_id {
90 let hint = tr(locale, MessageId::AutoReviewReceiptRetryHint)
91 .replace("{id}", &bounded_gate_reason(id));
92 receipt.push_str(". ");
93 receipt.push_str(&hint);
94 }
95 receipt
96 }
97
98 #[must_use]
99 pub fn auto_review_paused_receipt(locale: Locale, reason: &str) -> String {
100 tr(locale, MessageId::AutoReviewPausedReceipt).replace("{reason}", &bounded_gate_reason(reason))
101 }
102
103 /// The `tool.gate.decision` record `audit.log` keeps for the same decision.
104 /// The reason goes through the secret redactor: a reviewer's rationale can
105 /// quote the command it judged. The caller adds `session_id`.
106 #[must_use]
107 pub fn tool_gate_audit_record(
108 agent_id: Option<&str>,
109 tool_id: &str,
110 tool_name: &str,
111 gate: ToolGate,
112 decision: ToolGateVerdict,
113 risk: Option<&str>,
114 reviewer_model: Option<&str>,
115 reason: &str,
116 ) -> serde_json::Value {
117 serde_json::json!({
118 "agent_id": agent_id,
119 "tool_id": tool_id,
120 "tool_name": tool_name,
121 "gate": gate.as_str(),
122 "decision": decision.as_str(),
123 "risk": risk,
124 "reviewer_model": reviewer_model,
125 "reason": codewhale_sanitize::redact::redact_secrets(reason),
126 })
127 }
128
129 #[must_use]
130 #[allow(clippy::too_many_arguments)]
131 pub fn tool_gate_audit_record_with_metadata(
132 agent_id: Option<&str>,
133 tool_id: &str,
134 tool_name: &str,
135 gate: ToolGate,
136 decision: ToolGateVerdict,
137 risk: Option<&str>,
138 reviewer_model: Option<&str>,
139 reason: &str,
140 rule: Option<&str>,
141 receipt_id: Option<&str>,
142 call_digest: Option<&str>,
143 action_summary: Option<&str>,
144 ) -> serde_json::Value {
145 let mut record = tool_gate_audit_record(
146 agent_id,
147 tool_id,
148 tool_name,
149 gate,
150 decision,
151 risk,
152 reviewer_model,
153 reason,
154 );
155 if let Some(rule) = rule {
156 record["rule"] = serde_json::json!(rule);
157 }
158 if let Some(receipt_id) = receipt_id {
159 record["receipt_id"] = serde_json::json!(receipt_id);
160 }
161 if let Some(call_digest) = call_digest {
162 record["call_digest"] = serde_json::json!(call_digest);
163 }
164 if let Some(action_summary) = action_summary {
165 record["action_summary"] =
166 serde_json::json!(codewhale_sanitize::redact::redact_secrets(action_summary));
167 }
168 record
169 }
170
171 /// The receipt for a safety-floor hold that Auto-Review denied without
172 /// pausing (the posture never opens a prompt).
173 #[must_use]
174 pub fn auto_review_held_receipt(locale: Locale, tool_name: &str) -> String {
175 fill(
176 tr(locale, MessageId::AutoReviewReceiptHeld),
177 tool_name,
178 "",
179 "",
180 )
181 }
182
183 fn fill(template: Cow<'static, str>, tool_name: &str, risk: &str, reason: &str) -> String {
184 template
185 .replace("{tool}", &bounded_tool_name(tool_name))
186 .replace("{risk}", risk)
187 .replace("{reason}", reason)
188 }
189
190 fn bounded_tool_name(tool_name: &str) -> String {
191 let cleaned = bounded_gate_reason(tool_name);
192 if cleaned.chars().count() <= MAX_TOOL_NAME_CHARS {
193 return cleaned;
194 }
195 let mut out: String = cleaned.chars().take(MAX_TOOL_NAME_CHARS - 1).collect();
196 out.push('…');
197 out
198 }
199
200 #[cfg(test)]
201 mod tests {
202 use super::*;
203
204 #[test]
205 fn gate_audit_record_names_the_gate_and_redacts_the_reason() {
206 let record = tool_gate_audit_record(
207 None,
208 "call-1",
209 "bash",
210 ToolGate::AutoReviewDeterministic,
211 ToolGateVerdict::Denied,
212 None,
213 None,
214 "blocked `curl -H 'Authorization: Bearer sk-live-abcdefghijklmnopqrstuv' x`",
215 );
216 assert_eq!(record["gate"], "auto_review_deterministic");
217 assert_eq!(record["decision"], "denied");
218 assert_eq!(record["tool_id"], "call-1");
219 let reason = record["reason"].as_str().expect("reason");
220 assert!(
221 !reason.contains("sk-live-abcdefghijklmnopqrstuv"),
222 "{reason}"
223 );
224
225 // Written where every other audit event goes.
226 let home = tempfile::tempdir().expect("tempdir");
227 codewhale_runtime::audit::log_sensitive_event_in(home.path(), "tool.gate.decision", record);
228 let log = std::fs::read_to_string(home.path().join("audit.log")).expect("audit.log");
229 assert!(log.contains("\"event\":\"tool.gate.decision\""), "{log}");
230 assert!(
231 log.contains("\"gate\":\"auto_review_deterministic\""),
232 "{log}"
233 );
234 }
235
236 #[test]
237 fn guardian_allow_names_tool_risk_and_reason() {
238 let line = tool_gate_receipt(
239 Locale::En,
240 "bash",
241 ToolGate::AutoReviewGuardian,
242 ToolGateVerdict::Allowed,
243 Some("low"),
244 None,
245 "reads a log file inside the workspace",
246 );
247 assert_eq!(
248 line,
249 "Auto-Review allowed 'bash' (low risk, model guardian): reads a log file inside the workspace"
250 );
251 }
252
253 #[test]
254 fn guardian_deny_and_unavailable_are_distinct_receipts() {
255 let denied = tool_gate_receipt(
256 Locale::En,
257 "bash",
258 ToolGate::AutoReviewGuardian,
259 ToolGateVerdict::Denied,
260 Some("high"),
261 None,
262 "would push to a remote",
263 );
264 assert!(denied.starts_with("Auto-Review denied 'bash' (high risk, model guardian): "));
265 let unavailable = tool_gate_receipt(
266 Locale::En,
267 "File",
268 ToolGate::AutoReviewGuardian,
269 ToolGateVerdict::Unavailable,
270 None,
271 None,
272 "guardian request timed out",
273 );
274 assert!(unavailable.contains("could not review 'File' (guardian request timed out)"));
275 assert!(
276 unavailable.ends_with("denied, fail closed"),
277 "{unavailable}"
278 );
279 assert!(!unavailable.contains("unknown risk"), "{unavailable}");
280 }
281
282 #[test]
283 fn deterministic_block_receipt_names_the_policy() {
284 let line = tool_gate_receipt(
285 Locale::En,
286 "bash",
287 ToolGate::AutoReviewDeterministic,
288 ToolGateVerdict::Denied,
289 None,
290 None,
291 "publish-like command",
292 );
293 assert_eq!(
294 line,
295 "Auto-Review blocked 'bash' (deterministic policy): publish-like command"
296 );
297 }
298
299 #[test]
300 fn receipts_bound_and_defang_untrusted_reason_and_tool_text() {
301 let long = "x".repeat(600);
302 let line = tool_gate_receipt(
303 Locale::En,
304 "ba\u{1b}[31msh\n\u{202E}",
305 ToolGate::AutoReviewGuardian,
306 ToolGateVerdict::Denied,
307 Some("medium"),
308 None,
309 &format!("evil\u{1b}]0;title\u{7} {long}"),
310 );
311 assert!(!line.contains('\u{1b}'));
312 assert!(!line.contains('\n'));
313 assert!(!line.contains('\u{202E}'));
314 assert!(!line.contains('\u{7}'));
315 assert!(line.chars().count() < 340, "{}", line.chars().count());
316 }
317
318 #[test]
319 fn held_receipt_is_localized_and_names_the_tool() {
320 let en = auto_review_held_receipt(Locale::En, "write");
321 assert!(en.starts_with("Auto-Review held 'write' without pausing"));
322 let ja = auto_review_held_receipt(Locale::Ja, "write");
323 assert!(ja.contains("'write'"));
324 assert_ne!(ja, en);
325 }
326
327 #[test]
328 fn every_shipped_pack_keeps_receipt_placeholders() {
329 for locale in Locale::shipped_complete() {
330 let line = tool_gate_receipt(
331 *locale,
332 "bash",
333 ToolGate::AutoReviewGuardian,
334 ToolGateVerdict::Allowed,
335 Some("low"),
336 None,
337 "REASON-SENTINEL",
338 );
339 assert!(line.contains("'bash'"), "{locale:?}: {line}");
340 assert!(line.contains("REASON-SENTINEL"), "{locale:?}: {line}");
341 assert!(!line.contains('{'), "{locale:?}: {line}");
342 }
343 }
344
345 #[test]
346 fn guardian_receipt_and_audit_record_include_reviewer_model() {
347 let allowed = tool_gate_receipt(
348 Locale::En,
349 "bash",
350 ToolGate::AutoReviewGuardian,
351 ToolGateVerdict::Allowed,
352 Some("low"),
353 Some("claude-sonnet-5-5"),
354 "workspace test",
355 );
356 assert!(
357 allowed.ends_with("[reviewer: claude-sonnet-5-5]"),
358 "{allowed}"
359 );
360
361 let unavailable = tool_gate_receipt(
362 Locale::En,
363 "File",
364 ToolGate::AutoReviewGuardian,
365 ToolGateVerdict::Unavailable,
366 None,
367 Some("gpt-5.6"),
368 "timed out",
369 );
370 assert!(unavailable.contains("[reviewer: gpt-5.6]"), "{unavailable}");
371
372 let deterministic = tool_gate_receipt(
373 Locale::En,
374 "bash",
375 ToolGate::AutoReviewDeterministic,
376 ToolGateVerdict::Denied,
377 None,
378 Some("should-not-print"),
379 "blocked",
380 );
381 assert!(!deterministic.contains("[reviewer:"), "{deterministic}");
382
383 let audit = tool_gate_audit_record(
384 None,
385 "call-2",
386 "bash",
387 ToolGate::AutoReviewGuardian,
388 ToolGateVerdict::Denied,
389 Some("high"),
390 Some("deepseek-v4-pro"),
391 "blocked by reviewer",
392 );
393 assert_eq!(audit["reviewer_model"], "deepseek-v4-pro");
394 }
395
396 #[test]
397 fn retry_receipt_includes_and_omits_retry_hint_cleanly() {
398 let with_hint = tool_gate_receipt_with_retry_info(
399 Locale::En,
400 "bash",
401 ToolGate::AutoReviewGuardian,
402 ToolGateVerdict::Denied,
403 Some("high"),
404 Some("claude-sonnet-5-5"),
405 "dangerous delete",
406 Some("ar-7\x1b[2J"),
407 );
408 assert!(with_hint.contains("ar-7"), "{with_hint}");
409 assert!(!with_hint.contains('\x1b'), "{with_hint}");
410 assert!(
411 with_hint.contains("/permissions blocked approve ar-7"),
412 "{with_hint}"
413 );
414
415 let without_hint = tool_gate_receipt_with_retry_info(
416 Locale::En,
417 "bash",
418 ToolGate::AutoReviewGuardian,
419 ToolGateVerdict::Denied,
420 Some("high"),
421 None,
422 "dangerous delete",
423 None,
424 );
425 assert!(
426 !without_hint.contains("/permissions blocked approve"),
427 "{without_hint}"
428 );
429 }
430
431 #[test]
432 fn paused_receipt_renders_across_shipped_locales_without_controls() {
433 for locale in Locale::shipped_complete() {
434 let line =
435 auto_review_paused_receipt(*locale, "\x1b[31m3 blocked actions in a row\x07");
436 assert!(
437 line.contains("3 blocked actions in a row"),
438 "{locale:?}: {line}"
439 );
440 assert!(!line.contains('\x1b'), "{locale:?}: {line}");
441 assert!(!line.contains('\x07'), "{locale:?}: {line}");
442 assert!(!line.contains('{'), "{locale:?}: {line}");
443 }
444 }
445
446 #[test]
447 fn audit_record_with_metadata_redacts_secrets_and_sets_optional_fields() {
448 let full = tool_gate_audit_record_with_metadata(
449 Some("sub-1"),
450 "call-9",
451 "Bash",
452 ToolGate::AutoReviewGuardian,
453 ToolGateVerdict::Denied,
454 Some("high"),
455 Some("deepseek-v4-pro"),
456 "held",
457 Some("guardian"),
458 Some("ar-3"),
459 Some("digest-abc"),
460 Some("curl -H 'Authorization: Bearer sk-secret1234567890abcdef'"),
461 );
462 assert_eq!(full["rule"], "guardian");
463 assert_eq!(full["receipt_id"], "ar-3");
464 assert_eq!(full["call_digest"], "digest-abc");
465 assert_eq!(full["reviewer_model"], "deepseek-v4-pro");
466 let summary = full["action_summary"].as_str().unwrap();
467 assert!(!summary.contains("sk-secret1234567890abcdef"), "{summary}");
468
469 let minimal = tool_gate_audit_record_with_metadata(
470 None,
471 "call-10",
472 "Read",
473 ToolGate::AutoReviewDeterministic,
474 ToolGateVerdict::Denied,
475 None,
476 None,
477 "blocked",
478 None,
479 None,
480 None,
481 None,
482 );
483 assert!(minimal.get("rule").is_none());
484 assert!(minimal.get("receipt_id").is_none());
485 assert!(minimal.get("call_digest").is_none());
486 assert!(minimal.get("action_summary").is_none());
487 }
488 }
489
489 lines RUST