返回 CodeWhale
receipts.rs
根目录 / crates / engine / src / receipts.rs
1 //! Session receipts: what a session or turn actually did, read back from the
2 //! records Codewhale already persists.
3 //!
4 //! There is one builder. It reads two persisted shapes and nothing else:
5 //!
6 //! - a terminal session: the saved transcript (`sessions/<id>.json`, whose
7 //! `tool_use`/`tool_result` blocks are the calls) plus the session's
8 //! approval log (`sessions/<id>/approval_receipts.jsonl`) and saved turn outcomes;
9 //! - a Runtime thread (the app, `codewhale serve`): the thread's turn and item
10 //! records plus the `approval.*` events in its append-only event log.
11 //!
12 //! A terminal session also reads the workspace snapshots the engine already
13 //! takes before and after each turn (`codewhale_snapshot`, when snapshots are
14 //! on): their difference is every file the turn changed, including files a
15 //! shell command changed, which no tool record names.
16 //!
17 //! Both are normalized into [`ToolStep`]s and [`ApprovalStep`]s and then
18 //! classified by the same code for `/receipts`, `codewhale receipts`, and
19 //! `GET /v1/threads/{id}/receipt`. Live and saved terminal sessions supply
20 //! their recorded turn outcomes so both surfaces report the same failures.
21 //!
22 //! The builder only reads. It never calls a provider, runs a tool, or writes
23 //! a file (reading the snapshots runs `git diff` inside the side repo, which
24 //! touches neither the work tree nor the user's repository). It exports no reasoning text and no raw tool output: commands,
25 //! queries, and error lines are bounded and passed through the shared secret
26 //! redactor. A fact the record does not hold is reported as not recorded,
27 //! never inferred from display text (see `docs/RECEIPTS.md`).
28 //!
29 //! Known limits: a Runtime thread's engine does not tag its snapshots with
30 //! the thread, so a thread receipt cannot read them and says that shell file
31 //! changes are not itemized. A snapshot difference covers everything that
32 //! wrote to the workspace during the turn, not only this agent. Snapshots are
33 //! pruned to the newest [`codewhale_snapshot::DEFAULT_MAX_SNAPSHOTS`], so older
34 //! turns have none.
35
36 use std::collections::{BTreeSet, HashMap};
37
38 use chrono::{DateTime, Utc};
39 use codewhale_execpolicy::ApprovalMode;
40 use codewhale_models::{ContentBlock, Message};
41 use serde_json::Value;
42
43 use crate::approval_log::{ApprovalOutcome, ApprovalReceipt, ApprovalReplay};
44 use crate::runtime_threads::{
45 RuntimeEventRecord, RuntimeTurnStatus, ThreadRecord, TurnItemKind, TurnItemLifecycleStatus,
46 TurnItemRecord, TurnRecord,
47 };
48 use crate::tools::diff_format::make_unified_diff;
49
50 const MAX_COMMAND_CHARS: usize = 200;
51 const MAX_ERROR_CHARS: usize = 160;
52 const MAX_QUERY_CHARS: usize = 120;
53 const MAX_FILES_PER_ACTION: usize = 50;
54 const MAX_NESTED_CALLS: usize = 20;
55
56 /// Terminal sessions have kept an approval log since 0.9.10 (commit
57 /// 11717b48ff, released 2026-08-20). A session that started earlier has no
58 /// record of which calls asked first, so its receipt does not count calls that
59 /// "ran without asking".
60 const APPROVAL_LOG_SINCE: &str = "2026-08-20T00:00:00Z";
61
62 const CLAIM_CEILING: [&str; 3] = [
63 "local_record_only",
64 "not_safety_certification",
65 "not_provider_compatibility_certification",
66 ];
67
68 // ---------------------------------------------------------------------------
69 // Output shape
70 // ---------------------------------------------------------------------------
71
72 pub use codewhale_command_contract::facets::debug_receipts::*;
73
74 mod usage;
75 pub use usage::{
76 cost_projection_from_snapshot, receipt_cost, saved_session_usage, session_usage,
77 tokens_from_sources, with_usage,
78 };
79
80 // ---------------------------------------------------------------------------
81 // Normalized input
82 // ---------------------------------------------------------------------------
83
84 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
85 enum StepOutcome {
86 Ok,
87 Failed,
88 Interrupted,
89 Running,
90 Unknown,
91 }
92
93 /// One tool call as a persisted record holds it.
94 #[derive(Debug, Clone)]
95 struct ToolStep {
96 turn: Option<String>,
97 call_id: Option<String>,
98 name: String,
99 input: Value,
100 outcome: StepOutcome,
101 output: Option<String>,
102 metadata: Option<Value>,
103 started_at: Option<DateTime<Utc>>,
104 ended_at: Option<DateTime<Utc>>,
105 }
106
107 /// A turn and the permission posture its own record names, if any.
108 type TurnPosture = (String, Option<&'static str>);
109
110 /// A turn and the user's prompt text, if it had any.
111 type TurnPrompt = (String, Option<String>);
112
113 type TurnFailure = (Option<String>, Option<DateTime<Utc>>, Option<String>);
114
115 /// Each matched turn's workspace change, and how many turns had no pair.
116 type TurnChanges = (Vec<(String, TurnWorkspaceChange)>, usize);
117
118 /// Files a turn changed, from its before/after workspace snapshots.
119 #[derive(Debug, Clone, Default)]
120 struct TurnWorkspaceChange {
121 files: Vec<FileTouch>,
122 /// More paths changed than [`MAX_FILES_PER_ACTION`].
123 truncated: bool,
124 }
125
126 #[derive(Debug, Clone)]
127 struct ApprovalStep {
128 turn: Option<String>,
129 call_id: Option<String>,
130 tool: String,
131 fact: ApprovalFact,
132 }
133
134 // ---------------------------------------------------------------------------
135 // Entry points
136 // ---------------------------------------------------------------------------
137
138 /// Receipt for a terminal session: its transcript plus its approval log.
139 /// `turn` is a 1-based turn number; `None` covers the whole session.
140 pub fn session_receipt(
141 source: ReceiptSource,
142 messages: &[Message],
143 approval_receipts: &[ApprovalReceipt],
144 turn_outcomes: &[crate::session_manager::SavedTurnOutcome],
145 turn: Option<&str>,
146 ) -> anyhow::Result<Receipt> {
147 let mut notes = BTreeSet::new();
148 let (steps, turn_postures, turn_prompts) = steps_from_messages(messages);
149 let failures = turn_outcomes
150 .iter()
151 .filter(|outcome| {
152 outcome.status == crate::core::events::TurnOutcomeStatus::Failed
153 && outcome.after_message_count <= messages.len()
154 })
155 .map(|outcome| {
156 let turn = messages
157 .iter()
158 .take(outcome.after_message_count)
159 .filter(|message| {
160 codewhale_models::turn_classify::classify_user_turn_prompt(message)
161 != codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt
162 })
163 .count();
164 (
165 (turn > 0).then(|| turn.to_string()),
166 Some(outcome.ended_at),
167 Some(outcome.error.clone()),
168 )
169 })
170 .collect();
171 let approvals = match ApprovalReplay::from_receipts(approval_receipts) {
172 Ok(replay) => approvals_from_replay(&replay),
173 Err(error) => {
174 notes.insert(format!(
175 "Approvals: the session's approval log did not replay ({error}), so approvals are left out."
176 ));
177 Vec::new()
178 }
179 };
180 if let Some(turn) = turn {
181 let count = turn_postures.len();
182 if !turn
183 .parse::<usize>()
184 .is_ok_and(|number| (1..=count).contains(&number))
185 {
186 anyhow::bail!(
187 "turn '{turn}' is not a turn in this session; it has {}",
188 plural(count, "turn", "turns")
189 );
190 }
191 }
192 notes.insert(
193 "Timestamps: a terminal session saves calls in order, not when each one ran.".to_string(),
194 );
195 notes.insert("Plugin changes are not itemized for a terminal session yet".to_string());
196 let log_since = DateTime::parse_from_rfc3339(APPROVAL_LOG_SINCE)
197 .map(|at| at.with_timezone(&Utc))
198 .ok();
199 let approvals_recorded = match (source.started_at, log_since) {
200 (Some(started), Some(since)) => started >= since,
201 _ => true,
202 };
203 if !approvals_recorded {
204 notes.insert(
205 "Approvals: this session started before Codewhale kept an approval log (0.9.10, 2026-08-20), so it cannot show which calls asked first.".to_string(),
206 );
207 }
208 let snapshot_changes = match source.workspace.as_deref() {
209 Some(workspace) => snapshot_turn_changes(
210 std::path::Path::new(workspace),
211 &source.id,
212 &turn_prompts,
213 turn,
214 ),
215 None => Ok(None),
216 };
217 let workspace_changes = match snapshot_changes {
218 Ok(Some((changes, unmatched))) => {
219 notes.insert(
220 "Files changed outside file tools come from the workspace snapshots taken before and after each turn, so they include anything that wrote to the workspace during the turn, not only Codewhale. They leave out what snapshots do not track: ignored and skipped paths (.gitignore entries, .env, node_modules, target, and the like) and anything outside the workspace.".to_string(),
221 );
222 if unmatched > 0 {
223 notes.insert(format!(
224 "Shell file changes: {} without a before/after snapshot (snapshots off, or pruned: the newest {} are kept; or a repeated prompt whose snapshots could not be told apart), so files a command changed there are not itemized.",
225 plural(unmatched, "turn", "turns"),
226 codewhale_snapshot::DEFAULT_MAX_SNAPSHOTS
227 ));
228 }
229 changes
230 }
231 Ok(None) => {
232 notes.insert(
233 "Shell file changes: this workspace has no snapshots (snapshots are off, or the workspace is too large for them), so files a command changed are not itemized; only file tools are.".to_string(),
234 );
235 Vec::new()
236 }
237 Err(error) => {
238 notes.insert(format!(
239 "Shell file changes: the workspace snapshots could not be read ({}), so files a command changed are not itemized; only file tools are.",
240 bounded(&error, MAX_ERROR_CHARS)
241 ));
242 Vec::new()
243 }
244 };
245 Ok(assemble(
246 source,
247 steps,
248 approvals,
249 failures,
250 workspace_changes,
251 Assembly {
252 turn,
253 kind: SourceKind::Session,
254 turn_postures,
255 approvals_recorded,
256 },
257 notes,
258 ))
259 }
260
261 /// Receipt for a Runtime thread from its snapshot and event log. `turn` is a
262 /// turn id of this thread; `None` covers every turn.
263 pub fn thread_receipt(
264 thread: &ThreadRecord,
265 turns: &[TurnRecord],
266 items: &[TurnItemRecord],
267 events: &[RuntimeEventRecord],
268 turn: Option<&str>,
269 ) -> anyhow::Result<Receipt> {
270 if let Some(turn) = turn
271 && !turns.iter().any(|record| {
272 record.id == turn
273 && crate::runtime_threads::runtime_usage_partition_parent(record).is_none()
274 })
275 {
276 anyhow::bail!("turn '{turn}' does not belong to thread '{}'", thread.id);
277 }
278 let mut ordered: Vec<&TurnRecord> = turns
279 .iter()
280 .filter(|record| crate::runtime_threads::runtime_usage_partition_parent(record).is_none())
281 .collect();
282 ordered.sort_by_key(|record| record.created_at);
283 let items_by_id: HashMap<&str, &TurnItemRecord> =
284 items.iter().map(|item| (item.id.as_str(), item)).collect();
285 let mut steps = Vec::new();
286 let mut failures = Vec::new();
287 let mut turn_postures: Vec<TurnPosture> = Vec::new();
288 for record in &ordered {
289 turn_postures.push((
290 record.id.clone(),
291 record.permission_posture.as_deref().and_then(posture_label),
292 ));
293 let mut turn_items: Vec<&TurnItemRecord> = record
294 .item_ids
295 .iter()
296 .filter_map(|id| items_by_id.get(id.as_str()).copied())
297 .collect();
298 // Items a turn record does not list yet (a live turn) still belong
299 // to it by their own turn id.
300 for item in items {
301 if item.turn_id == record.id && !record.item_ids.contains(&item.id) {
302 turn_items.push(item);
303 }
304 }
305 for item in turn_items {
306 if let Some(step) = step_from_item(item) {
307 steps.push(step);
308 }
309 }
310 if record.status == RuntimeTurnStatus::Failed {
311 failures.push((
312 Some(record.id.clone()),
313 record.ended_at,
314 record.error.clone(),
315 ));
316 }
317 }
318 let approvals = approvals_from_events(events);
319 let source = ReceiptSource {
320 kind: SourceKind::Thread,
321 id: thread.id.clone(),
322 title: thread.title.clone().or_else(|| {
323 ordered
324 .first()
325 .map(|record| record.input_summary.clone())
326 .filter(|text| !text.trim().is_empty())
327 }),
328 workspace: Some(thread.workspace.display().to_string()),
329 model: Some(thread.model.clone()),
330 started_at: Some(thread.created_at),
331 updated_at: Some(thread.updated_at),
332 };
333 let notes = BTreeSet::from([
334 "Shell file changes: a Runtime thread's workspace snapshots are not tagged with the thread, so files a command changed are not itemized; only file tools are.".to_string(),
335 ]);
336 let covered: Vec<&TurnRecord> = ordered
337 .iter()
338 .copied()
339 .filter(|record| turn.is_none_or(|turn| record.id == turn))
340 .collect();
341 let tokens = usage::thread_tokens(&covered);
342 let mut notes = notes;
343 notes.insert(usage::thread_cost_note().to_string());
344 let mut receipt = assemble(
345 source,
346 steps,
347 approvals,
348 failures,
349 Vec::new(),
350 Assembly {
351 turn,
352 kind: SourceKind::Thread,
353 turn_postures,
354 approvals_recorded: true,
355 },
356 notes,
357 );
358 receipt.usage = tokens.map(|tokens| ReceiptUsage {
359 tokens: Some(tokens),
360 cost: None,
361 });
362 Ok(receipt)
363 }
364
365 // ---------------------------------------------------------------------------
366 // Loading from disk (`codewhale receipts`)
367 // ---------------------------------------------------------------------------
368
369 #[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum, serde::Deserialize)]
370 #[serde(rename_all = "lowercase")]
371 pub enum ReceiptFormat {
372 Md,
373 Json,
374 }
375
376 /// Receipt for a Runtime thread read straight from its store.
377 pub fn thread_receipt_from_store(
378 store: &crate::runtime_threads::RuntimeThreadStore,
379 thread_id: &str,
380 turn: Option<&str>,
381 ) -> anyhow::Result<Receipt> {
382 let thread = store.load_thread(thread_id)?;
383 let turns = store.list_turns_for_thread(thread_id)?;
384 let turn_ids: Vec<String> = turns.iter().map(|record| record.id.clone()).collect();
385 let items: Vec<TurnItemRecord> = store
386 .list_items_for_turns_map(&turn_ids)?
387 .into_values()
388 .flatten()
389 .collect();
390 let events: Vec<RuntimeEventRecord> = store
391 .events_since(thread_id, None)?
392 .into_iter()
393 .filter(|event| event.event.starts_with("approval."))
394 .collect();
395 thread_receipt(&thread, &turns, &items, &events, turn)
396 }
397
398 pub fn session_source(metadata: &crate::session_manager::SessionMetadata) -> ReceiptSource {
399 ReceiptSource {
400 kind: SourceKind::Session,
401 id: metadata.id.clone(),
402 title: Some(metadata.title.clone()).filter(|title| !title.trim().is_empty()),
403 workspace: Some(metadata.workspace.display().to_string()),
404 model: Some(metadata.model.clone()).filter(|model| !model.is_empty()),
405 started_at: Some(metadata.created_at),
406 updated_at: Some(metadata.updated_at),
407 }
408 }
409
410 /// `codewhale receipts [ID|--last] [--turn T] [--format md|json]`.
411 ///
412 /// `ID` is a saved session id (or unique prefix) or a Runtime thread id
413 /// (`thr_…`). With neither an id nor `--last`, the most recently updated
414 /// session or thread is used. Reads only.
415 pub fn run_receipts_command(
416 id: Option<&str>,
417 turn: Option<&str>,
418 format: ReceiptFormat,
419 ) -> anyhow::Result<()> {
420 use anyhow::Context as _;
421 let sessions = crate::session_manager::SessionManager::default_location()
422 .context("could not open the saved sessions directory")?;
423 let runtime_root =
424 crate::runtime_threads::manager::RuntimeThreadManagerConfig::from_task_data_dir(
425 crate::task_manager::default_tasks_dir(),
426 )
427 .data_dir;
428 let store = crate::runtime_threads::RuntimeThreadStore::open_read_only(runtime_root)?;
429
430 let receipt = match id.map(str::trim).filter(|id| !id.is_empty()) {
431 Some(id) if id.starts_with("thr_") => {
432 let store = store.context("no Runtime thread store exists on this machine")?;
433 thread_receipt_from_store(&store, id, turn)?
434 }
435 Some(prefix) => {
436 let id = sessions.resolve_session_id_prefix(prefix)?;
437 let session = sessions.load_session_snapshot(&id)?;
438 with_usage(
439 session_receipt(
440 session_source(&session.metadata),
441 &session.messages,
442 &session.approval_receipts,
443 &session.turn_outcomes,
444 turn,
445 )?,
446 saved_session_usage(&session.metadata),
447 )
448 }
449 None => {
450 let latest_session = sessions.list_sessions()?.into_iter().next();
451 let latest_thread = store
452 .as_ref()
453 .map(|store| store.list_threads())
454 .transpose()?
455 .and_then(|threads| threads.into_iter().find(|thread| !thread.archived));
456 let thread_is_newer = match (&latest_session, &latest_thread) {
457 (Some(session), Some(thread)) => thread.updated_at > session.updated_at,
458 (None, Some(_)) => true,
459 _ => false,
460 };
461 match (latest_session, latest_thread, store.as_ref()) {
462 (_, Some(thread), Some(store)) if thread_is_newer => {
463 thread_receipt_from_store(store, &thread.id, turn)?
464 }
465 (Some(metadata), _, _) => {
466 let session = sessions.load_session_snapshot(&metadata.id)?;
467 with_usage(
468 session_receipt(
469 session_source(&session.metadata),
470 &session.messages,
471 &session.approval_receipts,
472 &session.turn_outcomes,
473 turn,
474 )?,
475 saved_session_usage(&session.metadata),
476 )
477 }
478 _ => anyhow::bail!("no saved session or Runtime thread to read"),
479 }
480 }
481 };
482 let text = match format {
483 ReceiptFormat::Md => render_markdown(&receipt),
484 ReceiptFormat::Json => render_json(&receipt),
485 };
486 println!("{}", text.trim_end());
487 Ok(())
488 }
489
490 // ---------------------------------------------------------------------------
491 // Readers: persisted shape -> normalized steps
492 // ---------------------------------------------------------------------------
493
494 /// Tool calls in transcript order, plus each turn's posture. A turn starts at
495 /// a real user prompt, by the same rule edit-last-turn and titles use
496 /// ([`codewhale_models::turn_classify::classify_user_turn_prompt`]); runtime-injected
497 /// messages and tool results do not start one.
498 /// Each turn's prompt text (the user's words, without the `<turn_meta>`
499 /// block) comes back too: it labels the turn's workspace snapshots.
500 fn steps_from_messages(messages: &[Message]) -> (Vec<ToolStep>, Vec<TurnPosture>, Vec<TurnPrompt>) {
501 let mut steps: Vec<ToolStep> = Vec::new();
502 let mut by_id = HashMap::new();
503 let mut call_counts = HashMap::<codewhale_models::ToolCallKey<'_>, usize>::new();
504 let mut raw_counts = HashMap::<&str, usize>::new();
505 let mut results = HashMap::new();
506 for block in messages.iter().flat_map(|message| &message.content) {
507 let Some(key) = block.tool_call_key() else {
508 continue;
509 };
510 match block {
511 ContentBlock::ToolUse { .. } | ContentBlock::ServerToolUse { .. } => {
512 *call_counts.entry(key).or_default() += 1;
513 *raw_counts.entry(key.as_str()).or_default() += 1;
514 }
515 ContentBlock::ToolResult { tool_use_id, .. } => {
516 results
517 .entry(key)
518 .and_modify(|entry| *entry = None)
519 .or_insert(Some(tool_use_id.as_str()));
520 }
521 _ => {}
522 }
523 }
524 let mut turn_postures: Vec<TurnPosture> = Vec::new();
525 let mut turn_prompts: Vec<TurnPrompt> = Vec::new();
526 let mut turn = 0usize;
527 for message in messages {
528 if codewhale_models::turn_classify::classify_user_turn_prompt(message)
529 != codewhale_models::turn_classify::UserTurnPromptKind::NotPrompt
530 {
531 turn += 1;
532 turn_postures.push((turn.to_string(), turn_meta_posture(message)));
533 turn_prompts.push((turn.to_string(), prompt_text(message)));
534 }
535 for block in &message.content {
536 match block {
537 ContentBlock::ToolUse {
538 id, name, input, ..
539 }
540 | ContentBlock::ServerToolUse {
541 id, name, input, ..
542 } => {
543 let key = block.tool_call_key().expect("tool use key");
544 let unambiguous = !key.as_str().trim().is_empty()
545 && call_counts.get(&key) == Some(&1)
546 && raw_counts.get(key.as_str()) == Some(&1)
547 && results
548 .get(&key)
549 .is_none_or(|result| result.as_deref() == Some(id.as_str()));
550 if unambiguous {
551 by_id.insert(key, (steps.len(), id.as_str()));
552 }
553 steps.push(ToolStep {
554 turn: (turn > 0).then(|| turn.to_string()),
555 call_id: unambiguous.then(|| key.as_str().to_string()),
556 name: name.clone(),
557 input: input.clone(),
558 outcome: StepOutcome::Unknown,
559 output: None,
560 metadata: None,
561 started_at: None,
562 ended_at: None,
563 });
564 }
565 ContentBlock::ToolResult {
566 tool_use_id,
567 content,
568 is_error,
569 ..
570 } => {
571 if let Some(&(index, provider_id)) =
572 block.tool_call_key().and_then(|key| by_id.get(&key))
573 && provider_id == tool_use_id
574 {
575 let step = &mut steps[index];
576 step.outcome = if is_error.unwrap_or(false) {
577 StepOutcome::Failed
578 } else {
579 StepOutcome::Ok
580 };
581 step.output = Some(content.clone());
582 }
583 }
584 _ => {}
585 }
586 }
587 }
588 (steps, turn_postures, turn_prompts)
589 }
590
591 /// The prompt a user message carries: its text blocks, less the
592 /// `<turn_meta>` block the engine appends.
593 pub fn prompt_text(message: &Message) -> Option<String> {
594 let meta_index =
595 codewhale_models::turn_classify::turn_metadata_text(message).map(|(index, _)| index);
596 message
597 .content
598 .iter()
599 .enumerate()
600 .find_map(|(index, block)| match block {
601 ContentBlock::Text { text, .. } if Some(index) != meta_index => Some(text.clone()),
602 _ => None,
603 })
604 }
605
606 /// Files each turn changed, from the `pre-turn:N` / `post-turn:N` snapshots
607 /// the engine takes around a turn in this session (`core::turn`). A turn is
608 /// matched to its pair by the prompt snippet the labels carry, in order, the
609 /// same way `/restore` listings are read ([`crate::core::turn::
610 /// snapshot_label_prompt_snippet`]). When another turn has the same snippet
611 /// ("continue", "yes", or none), the snippet cannot say whose pair it is, so
612 /// the pair's turn number `N` must agree too ([`seq_fits`]); otherwise the
613 /// turn counts as unmatched rather than taking a later turn's files. The
614 /// count of unmatched turns is returned beside the changes. `None` when this
615 /// workspace has no snapshot repo.
616 fn snapshot_turn_changes(
617 workspace: &std::path::Path,
618 session_id: &str,
619 turn_prompts: &[TurnPrompt],
620 wanted: Option<&str>,
621 ) -> Result<Option<TurnChanges>, String> {
622 use crate::core::turn::{parse_snapshot_label, snapshot_label_prompt_snippet};
623 let Some(repo) = codewhale_snapshot::SnapshotRepo::open_existing(workspace)
624 .map_err(|error| error.to_string())?
625 else {
626 return Ok(None);
627 };
628 let mut snapshots = repo.list(usize::MAX).map_err(|error| error.to_string())?;
629 snapshots.reverse();
630 // Pair each post-turn:N with the open pre-turn:N of this session, oldest
631 // first. The sequence restarts when the session is resumed, so a pair
632 // closes on the first matching post-turn.
633 let mut open: HashMap<u64, (codewhale_snapshot::SnapshotId, Option<String>)> = HashMap::new();
634 let mut pairs = Vec::new();
635 for snapshot in snapshots
636 .into_iter()
637 .filter(|snapshot| snapshot.session_id.as_deref() == Some(session_id))
638 {
639 let label = parse_snapshot_label(&snapshot.label);
640 let Some(seq) = label.seq else { continue };
641 match label.kind.as_str() {
642 "pre-turn" => {
643 open.insert(seq, (snapshot.id, label.prompt_snippet));
644 }
645 "post-turn" => {
646 if let Some((pre, snippet)) = open.remove(&seq) {
647 pairs.push((pre, snapshot.id, snippet, seq));
648 }
649 }
650 _ => {}
651 }
652 }
653 let snippets: Vec<Option<String>> = turn_prompts
654 .iter()
655 .map(|(_, prompt)| prompt.as_deref().and_then(snapshot_label_prompt_snippet))
656 .collect();
657 let mut changes = Vec::new();
658 let mut unmatched = 0usize;
659 let mut next_pair = 0usize;
660 // The last turn given a pair: its place in the transcript (1-based) and
661 // the pair's turn number.
662 let mut last: Option<(u64, u64)> = None;
663 let mut last_position = 0u64;
664 for (position, ((turn, _), snippet)) in turn_prompts.iter().zip(&snippets).enumerate() {
665 let position = position as u64 + 1;
666 let repeated = snippets
667 .iter()
668 .enumerate()
669 .any(|(other, label)| other as u64 + 1 != position && label == snippet);
670 let found = pairs[next_pair..]
671 .iter()
672 .position(|(_, _, label, _)| label == snippet)
673 .map(|offset| next_pair + offset)
674 .filter(|&index| {
675 // Engine turns with no transcript prompt (a `!` shell
676 // command) number a pair too; count the ones still listed.
677 let extra = pairs[next_pair..index]
678 .iter()
679 .filter(|(_, _, label, _)| !snippets.contains(label))
680 .count() as u64;
681 let since = position - last_position + extra;
682 !repeated || seq_fits(pairs[index].3, since, last.map(|(_, seq)| seq))
683 });
684 let Some(index) = found else {
685 if wanted.is_none_or(|wanted| wanted == turn) {
686 unmatched += 1;
687 }
688 continue;
689 };
690 next_pair = index + 1;
691 last = Some((position, pairs[index].3));
692 last_position = position;
693 if wanted.is_some_and(|wanted| wanted != turn) {
694 continue;
695 }
696 let (pre, post, _, _) = &pairs[index];
697 let (paths, truncated) = repo
698 .path_changes_between(pre, post, MAX_FILES_PER_ACTION)
699 .map_err(|error| error.to_string())?;
700 let files = paths
701 .into_iter()
702 .map(|change| FileTouch {
703 path: change.path,
704 change: match change.status {
705 'A' => FileChangeKind::Created,
706 'D' => FileChangeKind::Deleted,
707 _ => FileChangeKind::Edited,
708 },
709 lines_added: change.added,
710 lines_removed: change.removed,
711 })
712 .collect();
713 changes.push((turn.clone(), TurnWorkspaceChange { files, truncated }));
714 }
715 Ok(Some((changes, unmatched)))
716 }
717
718 /// Whether a snapshot pair numbered `seq` can belong to a turn that comes
719 /// `since` engine turns after the last matched pair (numbered `last_seq`),
720 /// or `since` turns after the session started when none matched yet. The
721 /// engine numbers turns from 1 each time it starts, so within one run the
722 /// number moves in step with the turns; after a resume it restarts, and can
723 /// be at most `since`.
724 fn seq_fits(seq: u64, since: u64, last_seq: Option<u64>) -> bool {
725 let restarted = (1..=since).contains(&seq);
726 match last_seq {
727 Some(last_seq) => seq == last_seq + since || restarted,
728 None => restarted,
729 }
730 }
731
732 /// `path` relative to `workspace` when it is inside it, without a leading
733 /// `./`, for comparing a file tool's path with a snapshot's.
734 fn workspace_relative(path: &str, workspace: Option<&str>) -> String {
735 let relative = workspace
736 .and_then(|workspace| {
737 path.strip_prefix(workspace.trim_end_matches('/'))
738 .and_then(|rest| rest.strip_prefix('/'))
739 })
740 .unwrap_or(path);
741 relative.trim_start_matches("./").to_string()
742 }
743
744 /// The posture line the engine writes into a prompt's `<turn_meta>` block
745 /// ([`crate::core::engine::PERMISSION_POSTURE_LINE`]).
746 fn turn_meta_posture(message: &Message) -> Option<&'static str> {
747 let (_, meta) = codewhale_models::turn_classify::turn_metadata_text(message)?;
748 meta.lines().find_map(|line| {
749 line.trim()
750 .strip_prefix(crate::core::engine::PERMISSION_POSTURE_LINE)
751 .and_then(posture_label)
752 })
753 }
754
755 /// The chip label for a posture the host wrote: a `<turn_meta>` label
756 /// (`Full Access`) or a Runtime turn's wire value (`full_access`). Anything
757 /// else is not a posture and yields `None`.
758 fn posture_label(value: &str) -> Option<&'static str> {
759 let value = value.trim();
760 [
761 ApprovalMode::Suggest,
762 ApprovalMode::Auto,
763 ApprovalMode::Bypass,
764 ApprovalMode::Never,
765 ]
766 .into_iter()
767 .map(ApprovalMode::permission_chip_label)
768 .find(|label| label.eq_ignore_ascii_case(value))
769 .or_else(|| ApprovalMode::from_config_value(value).map(ApprovalMode::permission_chip_label))
770 }
771
772 fn step_from_item(item: &TurnItemRecord) -> Option<ToolStep> {
773 if !matches!(
774 item.kind,
775 TurnItemKind::ToolCall | TurnItemKind::FileChange | TurnItemKind::CommandExecution
776 ) {
777 return None;
778 }
779 let metadata = item.metadata.clone();
780 let meta = metadata.as_ref();
781 let name = meta
782 .and_then(|meta| meta.get("tool_name"))
783 .and_then(Value::as_str)?
784 .to_string();
785 let call_id = meta
786 .and_then(|meta| meta.get("tool_use_id").or_else(|| meta.get("tool_call_id")))
787 .and_then(Value::as_str)
788 .map(str::to_string);
789 let input = meta
790 .and_then(|meta| meta.get("tool_input"))
791 .map(|raw| match raw {
792 Value::String(text) => serde_json::from_str(text).unwrap_or(Value::Null),
793 other => other.clone(),
794 })
795 .unwrap_or(Value::Null);
796 let outcome = match item.status {
797 TurnItemLifecycleStatus::Completed => StepOutcome::Ok,
798 TurnItemLifecycleStatus::Failed => StepOutcome::Failed,
799 TurnItemLifecycleStatus::Interrupted | TurnItemLifecycleStatus::Canceled => {
800 StepOutcome::Interrupted
801 }
802 TurnItemLifecycleStatus::Queued | TurnItemLifecycleStatus::InProgress => {
803 StepOutcome::Running
804 }
805 };
806 let finished = !matches!(outcome, StepOutcome::Running);
807 Some(ToolStep {
808 turn: Some(item.turn_id.clone()),
809 call_id,
810 name,
811 input,
812 outcome,
813 output: finished.then(|| item.detail.clone()).flatten(),
814 metadata,
815 started_at: item.started_at,
816 ended_at: item.ended_at,
817 })
818 }
819
820 fn approvals_from_replay(replay: &ApprovalReplay) -> Vec<ApprovalStep> {
821 let mut out = Vec::new();
822 for completed in &replay.completed {
823 let (decision, implied) = match &completed.outcome {
824 ApprovalOutcome::ApprovedOnce => (ApprovalDecisionLabel::Approved, None),
825 // The Runtime answers "deny" for a request it could not put in
826 // front of anyone (no active turn, the turn stopped, the channel
827 // closed). That is nobody answering, not a no.
828 ApprovalOutcome::Denied if completed.decided_by == Some(ApprovalDecider::Host) => {
829 (ApprovalDecisionLabel::Unavailable, None)
830 }
831 ApprovalOutcome::Denied => (ApprovalDecisionLabel::Denied, None),
832 ApprovalOutcome::Timeout => (ApprovalDecisionLabel::TimedOut, None),
833 ApprovalOutcome::Cancelled => (
834 ApprovalDecisionLabel::Cancelled,
835 Some(ApprovalDecider::Host),
836 ),
837 ApprovalOutcome::Unavailable => (
838 ApprovalDecisionLabel::Unavailable,
839 Some(ApprovalDecider::Host),
840 ),
841 ApprovalOutcome::RetryWithPolicy { .. } => {
842 (ApprovalDecisionLabel::ApprovedWithPolicy, None)
843 }
844 };
845 out.push(ApprovalStep {
846 turn: None,
847 call_id: Some(completed.ask.approval_id().to_string()),
848 tool: completed.ask.tool_name().unwrap_or("unknown").to_string(),
849 fact: ApprovalFact {
850 decision,
851 decided_by: completed.decided_by.or(implied),
852 at: Some(completed.decided_at),
853 },
854 });
855 }
856 for ask in &replay.unmatched_asks {
857 out.push(ApprovalStep {
858 turn: None,
859 call_id: Some(ask.approval_id().to_string()),
860 tool: ask.tool_name().unwrap_or("unknown").to_string(),
861 fact: ApprovalFact {
862 decision: ApprovalDecisionLabel::Pending,
863 decided_by: None,
864 at: Some(ask.created_at()),
865 },
866 });
867 }
868 out
869 }
870
871 /// Pair `approval.required` with `approval.decided` by approval id. Who
872 /// decided is read from the flags the Runtime writes on the decision event:
873 /// `timeout`, `cancelled`, `posture`, `auto` (+ `grant_id` for a session
874 /// rule). A decision with none of them came from a client acting for a
875 /// person.
876 fn approvals_from_events(events: &[RuntimeEventRecord]) -> Vec<ApprovalStep> {
877 let mut order: Vec<String> = Vec::new();
878 let mut steps: HashMap<String, ApprovalStep> = HashMap::new();
879 for event in events {
880 let payload = &event.payload;
881 let Some(approval_id) = payload
882 .get("approval_id")
883 .or_else(|| payload.get("id"))
884 .and_then(Value::as_str)
885 else {
886 continue;
887 };
888 match event.event.as_str() {
889 "approval.required" => {
890 if !steps.contains_key(approval_id) {
891 order.push(approval_id.to_string());
892 }
893 steps.insert(
894 approval_id.to_string(),
895 ApprovalStep {
896 turn: event.turn_id.clone(),
897 call_id: payload
898 .get("tool_call_id")
899 .and_then(Value::as_str)
900 .map(str::to_string),
901 tool: payload
902 .get("tool_name")
903 .and_then(Value::as_str)
904 .unwrap_or("unknown")
905 .to_string(),
906 fact: ApprovalFact {
907 decision: ApprovalDecisionLabel::Pending,
908 decided_by: None,
909 at: Some(event.timestamp),
910 },
911 },
912 );
913 }
914 "approval.decided" => {
915 let flag = |key: &str| payload.get(key).and_then(Value::as_bool) == Some(true);
916 let allowed = payload.get("decision").and_then(Value::as_str) == Some("allow");
917 let decision = if allowed {
918 ApprovalDecisionLabel::Approved
919 } else if flag("timeout") {
920 ApprovalDecisionLabel::TimedOut
921 } else if flag("cancelled") {
922 ApprovalDecisionLabel::Cancelled
923 } else {
924 ApprovalDecisionLabel::Denied
925 };
926 let decided_by = if flag("timeout") {
927 None
928 } else if flag("cancelled") {
929 Some(ApprovalDecider::Host)
930 } else if payload.get("posture").is_some() {
931 Some(ApprovalDecider::Posture)
932 } else if flag("auto") {
933 if payload
934 .get("grant_id")
935 .is_some_and(|grant| !grant.is_null())
936 {
937 Some(ApprovalDecider::SessionRule)
938 } else {
939 Some(ApprovalDecider::Posture)
940 }
941 } else {
942 Some(ApprovalDecider::User)
943 };
944 let fact = ApprovalFact {
945 decision,
946 decided_by,
947 at: Some(event.timestamp),
948 };
949 match steps.get_mut(approval_id) {
950 Some(step) => step.fact = fact,
951 None => {
952 order.push(approval_id.to_string());
953 steps.insert(
954 approval_id.to_string(),
955 ApprovalStep {
956 turn: event.turn_id.clone(),
957 call_id: payload
958 .get("tool_call_id")
959 .and_then(Value::as_str)
960 .map(str::to_string),
961 tool: "unknown".to_string(),
962 fact,
963 },
964 );
965 }
966 }
967 }
968 _ => {}
969 }
970 }
971 order
972 .into_iter()
973 .filter_map(|id| steps.remove(&id))
974 .collect()
975 }
976
977 // ---------------------------------------------------------------------------
978 // Classification: normalized step -> action
979 // ---------------------------------------------------------------------------
980
981 enum Classified {
982 Listed(ActionKind),
983 /// Counted as an other tool call; listed only if it failed.
984 Other,
985 /// A later call on an agent the receipt already lists (status, wait,
986 /// cancel): it updates that agent's outcome instead of adding a line.
987 AgentFollowUp {
988 agent_id: String,
989 status: Option<String>,
990 },
991 }
992
993 fn classify(step: &ToolStep, notes: &mut BTreeSet<String>) -> Classified {
994 let structured = structured_output(step);
995 let facts = step.metadata.as_ref().or(structured.as_ref());
996 if let Some(files) = mutation_files(facts) {
997 return Classified::Listed(ActionKind::FileChange { files });
998 }
999 let semantic =
1000 codewhale_execpolicy::canonical_action::canonical_action_alias(&step.name, &step.input);
1001 match semantic {
1002 "write_file" | "edit_file" | "apply_patch" | "fim_edit" => {
1003 let files = files_from_input(semantic, &step.input, step.outcome);
1004 if files.is_empty() {
1005 return Classified::Other;
1006 }
1007 if files.iter().any(|file| file.lines_added.is_none()) {
1008 notes.insert(
1009 "Line counts: some file changes have no saved diff, so their +/- counts are not recorded.".to_string(),
1010 );
1011 }
1012 Classified::Listed(ActionKind::FileChange { files })
1013 }
1014 "exec_shell" | "task_shell_start" | "task_gate_run" | "run_tests" | "run_verifiers" => {
1015 let exit_code = number(facts, &["exit_code", "return_code"])
1016 .or_else(|| closing_exit_code(step.output.as_deref()));
1017 if exit_code.is_none() && matches!(step.outcome, StepOutcome::Ok) {
1018 notes.insert(
1019 "Exit codes: calls that saved no structured result (terminal sessions) show pass or fail, not the exit code.".to_string(),
1020 );
1021 }
1022 Classified::Listed(ActionKind::Command {
1023 command: command_text(&step.name, semantic, &step.input),
1024 cwd: string_field(
1025 Some(&step.input),
1026 &["cwd", "working_dir", "workdir", "workspace"],
1027 )
1028 .or_else(|| string_field(facts, &["working_dir", "cwd"])),
1029 exit_code,
1030 })
1031 }
1032 "code_execution" | "execute_tools" | "rlm_eval" => Classified::Listed(ActionKind::Code {
1033 exit_code: number(facts, &["return_code", "exit_code"]),
1034 nested: nested_calls(structured.as_ref().or(facts)),
1035 }),
1036 "web_search" | "fetch_url" | "web.run" | "rlm_open" | "git_fetch" => {
1037 let url = string_field(Some(&step.input), &["url", "uri"]);
1038 let host = url
1039 .as_deref()
1040 .and_then(|url| reqwest::Url::parse(url).ok())
1041 .and_then(|url| url.host_str().map(str::to_string))
1042 .or_else(|| {
1043 (semantic == "git_fetch")
1044 .then(|| string_field(Some(&step.input), &["remote"]))
1045 .flatten()
1046 });
1047 let action = match semantic {
1048 "web_search" => "search",
1049 "git_fetch" => "git_fetch",
1050 _ if url.is_some() => "fetch",
1051 _ => "request",
1052 };
1053 let query = string_field(Some(&step.input), &["query", "q", "search_query"])
1054 .map(|query| bounded(&redact(&query), MAX_QUERY_CHARS));
1055 Classified::Listed(ActionKind::Network {
1056 action: action.to_string(),
1057 host,
1058 query,
1059 })
1060 }
1061 name if name.starts_with("github_") => Classified::Listed(ActionKind::Network {
1062 action: name.trim_start_matches("github_").to_string(),
1063 host: Some("github.com".to_string()),
1064 query: None,
1065 }),
1066 name if name.starts_with("mcp_") => {
1067 let server = crate::mcp::connected_app_server(name).map(str::to_string);
1068 let plugin = server
1069 .as_deref()
1070 .is_some_and(|server| server.starts_with("plugin"));
1071 Classified::Listed(ActionKind::Mcp { server, plugin })
1072 }
1073 "agent" => {
1074 let action = step
1075 .input
1076 .get("action")
1077 .and_then(Value::as_str)
1078 .unwrap_or("start");
1079 let agent_id = string_field(facts, &["agent_id"]);
1080 let status = string_field(facts, &["status"]);
1081 if action == "start" {
1082 Classified::Listed(ActionKind::Subagent {
1083 name: string_field(Some(&step.input), &["name"])
1084 .or_else(|| string_field(facts, &["name"])),
1085 agent_id,
1086 outcome: status,
1087 })
1088 } else if let Some(agent_id) = agent_id {
1089 Classified::AgentFollowUp { agent_id, status }
1090 } else {
1091 Classified::Other
1092 }
1093 }
1094 _ => Classified::Other,
1095 }
1096 }
1097
1098 /// The host-owned JSON a tool returned as its text result (agent, code,
1099 /// execute_tools), when the persisted record has no structured metadata. A
1100 /// leading approval note is skipped. Anything that is not a JSON object is
1101 /// ignored rather than read as prose, and so is JSON another party wrote
1102 /// ([`result_is_outside_text`]): an MCP server's reply cannot claim a file
1103 /// change or an exit code.
1104 fn structured_output(step: &ToolStep) -> Option<Value> {
1105 if result_is_outside_text(step) {
1106 return None;
1107 }
1108 let output = step.output.as_deref()?.trim_start();
1109 let body = if output.starts_with("[approval] ") {
1110 output.split_once("\n\n").map(|(_, rest)| rest)?
1111 } else {
1112 output
1113 };
1114 let value: Value = serde_json::from_str(body.trim()).ok()?;
1115 value.is_object().then_some(value)
1116 }
1117
1118 fn mutation_files(facts: Option<&Value>) -> Option<Vec<FileTouch>> {
1119 let mutation = facts?.get("mutation")?;
1120 let files = mutation.get("files")?.as_array()?;
1121 let counts = mutation
1122 .get("diff")
1123 .and_then(Value::as_str)
1124 .map(diff_counts_by_path)
1125 .unwrap_or_default();
1126 let mut out: Vec<FileTouch> = files
1127 .iter()
1128 .filter_map(|file| {
1129 let path = file.get("path")?.as_str()?.to_string();
1130 let change = match file.get("outcome").and_then(Value::as_str) {
1131 Some("created") => FileChangeKind::Created,
1132 Some("deleted") => FileChangeKind::Deleted,
1133 _ => FileChangeKind::Edited,
1134 };
1135 let (added, removed) = counts.get(&path).copied().unwrap_or((0, 0));
1136 Some(FileTouch {
1137 path,
1138 change,
1139 lines_added: Some(added),
1140 lines_removed: Some(removed),
1141 })
1142 })
1143 .collect();
1144 if let Some(renames) = mutation.get("renames").and_then(Value::as_array) {
1145 for rename in renames {
1146 if let Some(to) = rename.get("to").and_then(Value::as_str) {
1147 out.push(FileTouch {
1148 path: to.to_string(),
1149 change: FileChangeKind::Created,
1150 lines_added: Some(0),
1151 lines_removed: Some(0),
1152 });
1153 }
1154 if let Some(from) = rename.get("from").and_then(Value::as_str) {
1155 out.push(FileTouch {
1156 path: from.to_string(),
1157 change: FileChangeKind::Deleted,
1158 lines_added: Some(0),
1159 lines_removed: Some(0),
1160 });
1161 }
1162 }
1163 }
1164 out.truncate(MAX_FILES_PER_ACTION);
1165 (!out.is_empty()).then_some(out)
1166 }
1167
1168 /// One line of a unified diff or patch, read in context.
1169 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1170 enum DiffLine<'a> {
1171 /// A `--- old` / `+++ new` file header pair, as their raw paths.
1172 Header {
1173 old: &'a str,
1174 new: &'a str,
1175 },
1176 /// `diff --git …`: a new file section starts.
1177 FileStart,
1178 Added,
1179 Removed,
1180 Other(&'a str),
1181 }
1182
1183 /// Classify a diff's lines. `--- ` and `+++ ` are file headers only as an
1184 /// adjacent pair outside a hunk: inside one they are a removed `-- …` or
1185 /// added `++ …` line (a SQL or Lua comment), and a hunk's `@@ -a,b +c,d @@`
1186 /// counts say where it ends.
1187 fn diff_lines(text: &str) -> Vec<DiffLine<'_>> {
1188 let lines: Vec<&str> = text.lines().collect();
1189 let mut out = Vec::with_capacity(lines.len());
1190 let (mut old_left, mut new_left) = (0u64, 0u64);
1191 let mut index = 0;
1192 while index < lines.len() {
1193 let line = lines[index];
1194 index += 1;
1195 // Never hunk content, which always starts with ` `, `+`, or `-`.
1196 if line.starts_with("diff --git ") {
1197 (old_left, new_left) = (0, 0);
1198 out.push(DiffLine::FileStart);
1199 continue;
1200 }
1201 let in_hunk = old_left > 0 || new_left > 0;
1202 if !in_hunk {
1203 if let (Some(old), Some(new)) = (
1204 line.strip_prefix("--- "),
1205 lines.get(index).and_then(|next| next.strip_prefix("+++ ")),
1206 ) {
1207 out.push(DiffLine::Header { old, new });
1208 index += 1;
1209 continue;
1210 }
1211 if line.starts_with("@@") {
1212 if let Some((old, new)) = hunk_counts(line) {
1213 (old_left, new_left) = (old, new);
1214 }
1215 out.push(DiffLine::Other(line));
1216 continue;
1217 }
1218 }
1219 out.push(match line.as_bytes().first() {
1220 Some(b'+') => {
1221 new_left = new_left.saturating_sub(1);
1222 DiffLine::Added
1223 }
1224 Some(b'-') => {
1225 old_left = old_left.saturating_sub(1);
1226 DiffLine::Removed
1227 }
1228 // A blank line is a context line whose leading space was trimmed.
1229 Some(b' ') | None => {
1230 old_left = old_left.saturating_sub(1);
1231 new_left = new_left.saturating_sub(1);
1232 DiffLine::Other(line)
1233 }
1234 _ => DiffLine::Other(line),
1235 });
1236 }
1237 out
1238 }
1239
1240 /// `(old, new)` line counts from `@@ -a[,b] +c[,d] @@`; a missing count is 1.
1241 fn hunk_counts(line: &str) -> Option<(u64, u64)> {
1242 let mut ranges = line.strip_prefix("@@ ")?.split_whitespace();
1243 let count = |range: &str, sign: char| -> Option<u64> {
1244 let range = range.strip_prefix(sign)?;
1245 match range.split_once(',') {
1246 Some((_, count)) => count.parse().ok(),
1247 None => range.parse::<u64>().ok().map(|_| 1),
1248 }
1249 };
1250 Some((count(ranges.next()?, '-')?, count(ranges.next()?, '+')?))
1251 }
1252
1253 /// Per-file `(+, -)` from a unified diff, keyed by the `+++ b/<path>` (or
1254 /// `--- a/<path>` for deletions) header.
1255 fn diff_counts_by_path(diff: &str) -> HashMap<String, (u64, u64)> {
1256 let mut counts: HashMap<String, (u64, u64)> = HashMap::new();
1257 let mut current: Option<String> = None;
1258 for line in diff_lines(diff) {
1259 match line {
1260 DiffLine::Header { old, new } => {
1261 current = header_path(new).or_else(|| header_path(old));
1262 if let Some(path) = &current {
1263 counts.entry(path.clone()).or_default();
1264 }
1265 }
1266 DiffLine::FileStart => current = None,
1267 DiffLine::Added | DiffLine::Removed => {
1268 let Some(path) = &current else { continue };
1269 let entry = counts.entry(path.clone()).or_default();
1270 if line == DiffLine::Added {
1271 entry.0 += 1;
1272 } else {
1273 entry.1 += 1;
1274 }
1275 }
1276 DiffLine::Other(_) => {}
1277 }
1278 }
1279 counts
1280 }
1281
1282 fn header_path(rest: &str) -> Option<String> {
1283 let path = rest.split('\t').next()?.trim();
1284 if path == "/dev/null" {
1285 return None;
1286 }
1287 Some(
1288 path.strip_prefix("a/")
1289 .or_else(|| path.strip_prefix("b/"))
1290 .unwrap_or(path)
1291 .to_string(),
1292 )
1293 }
1294
1295 /// File changes from a call's own input, for records without a saved diff.
1296 /// A failed call changed nothing, so it lists its paths with no counts.
1297 fn files_from_input(semantic: &str, input: &Value, outcome: StepOutcome) -> Vec<FileTouch> {
1298 let succeeded = outcome == StepOutcome::Ok;
1299 let path = string_field(Some(input), &["path", "file_path", "filePath"]);
1300 match semantic {
1301 "write_file" => path
1302 .map(|path| {
1303 vec![FileTouch {
1304 path,
1305 change: FileChangeKind::Written,
1306 lines_added: None,
1307 lines_removed: None,
1308 }]
1309 })
1310 .unwrap_or_default(),
1311 "edit_file" | "fim_edit" => {
1312 let Some(path) = path else {
1313 return Vec::new();
1314 };
1315 let (added, removed) = if succeeded {
1316 edit_line_counts(input)
1317 } else {
1318 (None, None)
1319 };
1320 vec![FileTouch {
1321 path,
1322 change: FileChangeKind::Edited,
1323 lines_added: added,
1324 lines_removed: removed,
1325 }]
1326 }
1327 "apply_patch" => {
1328 let Some(patch) = string_field(Some(input), &["patch", "input"]) else {
1329 return path
1330 .map(|path| {
1331 vec![FileTouch {
1332 path,
1333 change: FileChangeKind::Edited,
1334 lines_added: None,
1335 lines_removed: None,
1336 }]
1337 })
1338 .unwrap_or_default();
1339 };
1340 let mut files = patch_files(&patch, path.as_deref());
1341 if !succeeded {
1342 for file in &mut files {
1343 file.lines_added = None;
1344 file.lines_removed = None;
1345 }
1346 }
1347 files
1348 }
1349 _ => Vec::new(),
1350 }
1351 }
1352
1353 fn edit_line_counts(input: &Value) -> (Option<u64>, Option<u64>) {
1354 const SEARCH: &[&str] = &["search", "old_string", "old_str", "oldText", "old_text"];
1355 const REPLACE: &[&str] = &[
1356 "replace",
1357 "new_string",
1358 "new_str",
1359 "newText",
1360 "new_text",
1361 "replacement",
1362 ];
1363 let pairs: Vec<&Value> = match input.get("edits").and_then(Value::as_array) {
1364 Some(edits) => edits.iter().collect(),
1365 None => vec![input],
1366 };
1367 let mut added = 0u64;
1368 let mut removed = 0u64;
1369 let mut any = false;
1370 for pair in pairs {
1371 let old = string_field(Some(pair), SEARCH);
1372 let new = string_field(Some(pair), REPLACE);
1373 if old.is_none() && new.is_none() {
1374 continue;
1375 }
1376 any = true;
1377 let (pair_added, pair_removed) =
1378 pair_line_counts(old.as_deref().unwrap_or(""), new.as_deref().unwrap_or(""));
1379 added += pair_added;
1380 removed += pair_removed;
1381 }
1382 if any {
1383 (Some(added), Some(removed))
1384 } else {
1385 (None, None)
1386 }
1387 }
1388
1389 fn pair_line_counts(old: &str, new: &str) -> (u64, u64) {
1390 let whole_lines = |text: &str| {
1391 if text.is_empty() || text.ends_with('\n') {
1392 text.to_string()
1393 } else {
1394 format!("{text}\n")
1395 }
1396 };
1397 let diff = make_unified_diff("edit", &whole_lines(old), &whole_lines(new));
1398 diff_counts_by_path(&diff)
1399 .get("edit")
1400 .copied()
1401 .unwrap_or_default()
1402 }
1403
1404 /// Files and counts from a patch the call supplied: `*** Add/Update/Delete
1405 /// File:` envelopes or unified-diff headers.
1406 fn patch_files(patch: &str, fallback_path: Option<&str>) -> Vec<FileTouch> {
1407 let mut files: Vec<FileTouch> = Vec::new();
1408 for line in diff_lines(patch) {
1409 let (added, removed) = match line {
1410 DiffLine::Header { old, new } => {
1411 let (path, change) = match (header_path(new), header_path(old)) {
1412 (Some(path), Some(_)) => (path, FileChangeKind::Edited),
1413 (Some(path), None) => (path, FileChangeKind::Created),
1414 (None, Some(old)) => (old, FileChangeKind::Deleted),
1415 (None, None) => continue,
1416 };
1417 files.push(FileTouch {
1418 path,
1419 change,
1420 lines_added: Some(0),
1421 lines_removed: Some(0),
1422 });
1423 continue;
1424 }
1425 DiffLine::FileStart => continue,
1426 DiffLine::Added => (1, 0),
1427 DiffLine::Removed => (0, 1),
1428 DiffLine::Other(line) => {
1429 envelope_file(line, &mut files);
1430 continue;
1431 }
1432 };
1433 if files.is_empty()
1434 && let Some(path) = fallback_path
1435 {
1436 files.push(FileTouch {
1437 path: path.to_string(),
1438 change: FileChangeKind::Edited,
1439 lines_added: Some(0),
1440 lines_removed: Some(0),
1441 });
1442 }
1443 if let Some(file) = files.last_mut() {
1444 *file.lines_added.get_or_insert(0) += added;
1445 *file.lines_removed.get_or_insert(0) += removed;
1446 }
1447 }
1448 files.truncate(MAX_FILES_PER_ACTION);
1449 files
1450 }
1451
1452 /// A `*** Add/Update/Delete File: <path>` envelope line starts a file.
1453 fn envelope_file(line: &str, files: &mut Vec<FileTouch>) {
1454 let envelope = [
1455 ("*** Add File: ", FileChangeKind::Created),
1456 ("*** Update File: ", FileChangeKind::Edited),
1457 ("*** Delete File: ", FileChangeKind::Deleted),
1458 ]
1459 .into_iter()
1460 .find_map(|(prefix, change)| line.strip_prefix(prefix).map(|path| (path, change)));
1461 if let Some((path, change)) = envelope {
1462 files.push(FileTouch {
1463 path: path.trim().to_string(),
1464 change,
1465 lines_added: Some(0),
1466 lines_removed: Some(0),
1467 });
1468 }
1469 }
1470
1471 fn command_text(tool: &str, semantic: &str, input: &Value) -> String {
1472 let raw = match input.get("command").or_else(|| input.get("cmd")) {
1473 Some(Value::String(command)) => command.clone(),
1474 Some(Value::Array(parts)) => parts
1475 .iter()
1476 .map(|part| {
1477 part.as_str()
1478 .map_or_else(|| part.to_string(), str::to_string)
1479 })
1480 .collect::<Vec<_>>()
1481 .join(" "),
1482 _ => match semantic {
1483 "run_tests" => format!("{tool} tests"),
1484 "run_verifiers" => format!("{tool} verifiers"),
1485 _ => tool.to_string(),
1486 },
1487 };
1488 // Redact the text as written: the redactor finds a private-key block by
1489 // its lines, which flattening would join into one.
1490 let flat = redact(&raw)
1491 .split_whitespace()
1492 .collect::<Vec<_>>()
1493 .join(" ");
1494 bounded(&flat, MAX_COMMAND_CHARS)
1495 }
1496
1497 /// The engine's own closing status line for a failed shell call, e.g.
1498 /// `Command exited with code 2`. This is a fixed format the shell tool writes,
1499 /// not model prose; anything else yields `None`.
1500 fn closing_exit_code(output: Option<&str>) -> Option<i64> {
1501 let last = output?.trim_end().lines().last()?.trim();
1502 last.strip_prefix("Command exited with code ")?.parse().ok()
1503 }
1504
1505 /// What a failed call's own result shows about whether it started.
1506 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1507 enum FailureEvidence {
1508 /// An exit code, or a status line the shell writes only after a process
1509 /// ran.
1510 Ran,
1511 /// Codewhale refused the call before it started.
1512 Refused,
1513 /// Stopped at an approval prompt. The text says `denied by user` for any
1514 /// decider (a host with nobody to ask writes it too), so without an
1515 /// approval-log record it proves the call did not run, not who stopped it.
1516 DeniedAtApproval,
1517 /// Neither.
1518 Unclear,
1519 }
1520
1521 /// Lines the shell tools write only after a process ran
1522 /// (`tools/shell.rs`: `contract_bash_error_status` and the `exec_shell`
1523 /// result).
1524 const SHELL_RAN_LINES: [&str; 5] = [
1525 "Command exited with code ",
1526 "Command failed (",
1527 "Command timed out",
1528 "Command canceled",
1529 "Command aborted",
1530 ];
1531
1532 /// The shell tools, by semantic name. Only these write `BLOCKED:` (their
1533 /// policy and safety blocks) and [`SHELL_RAN_LINES`].
1534 const SHELL_TOOLS: [&str; 5] = [
1535 "exec_shell",
1536 "task_shell_start",
1537 "task_gate_run",
1538 "run_tests",
1539 "run_verifiers",
1540 ];
1541
1542 /// Tools whose result text is someone else's words: an MCP server's or
1543 /// GitHub's reply, or a fetched page. Nothing in it is read as a fact about
1544 /// the call, not even JSON; only metadata Codewhale wrote is.
1545 fn result_is_outside_text(step: &ToolStep) -> bool {
1546 let semantic =
1547 codewhale_execpolicy::canonical_action::canonical_action_alias(&step.name, &step.input);
1548 step.name.starts_with("mcp_")
1549 || semantic.starts_with("mcp_")
1550 || semantic.starts_with("github_")
1551 || matches!(
1552 semantic,
1553 "web_search" | "fetch_url" | "web.run" | "rlm_open" | "git_fetch"
1554 )
1555 }
1556
1557 /// Tools whose failed result can open with text nobody at Codewhale framed:
1558 /// [`result_is_outside_text`], plus a program's own output (code tools) and a
1559 /// sub-agent's words. Their failure text never proves a refusal.
1560 fn failure_text_is_outside(step: &ToolStep) -> bool {
1561 let semantic =
1562 codewhale_execpolicy::canonical_action::canonical_action_alias(&step.name, &step.input);
1563 result_is_outside_text(step)
1564 || matches!(
1565 semantic,
1566 "code_execution" | "execute_tools" | "rlm_eval" | "agent"
1567 )
1568 }
1569
1570 /// Whether a failed call's result shows it started. The record keeps no
1571 /// "blocked" flag, so only shapes Codewhale itself writes are read, never
1572 /// model prose or another program's text:
1573 ///
1574 /// - `side_effect_status: not_started` in the call's metadata (the engine
1575 /// writes it), or on the `Tool validation feedback:` line
1576 /// `dispatch::format_tool_error_with_schema` appends as the result's last
1577 /// line.
1578 /// - a call refused before it runs gets its error as the result. A terminal
1579 /// session saves `Error: ` plus `dispatch::format_tool_error_with_schema`;
1580 /// a Runtime thread saves the `ToolError`'s own text. A shell tool's policy
1581 /// and safety blocks start with `BLOCKED:`.
1582 /// - a process that ran leaves an exit code or one of [`SHELL_RAN_LINES`].
1583 ///
1584 /// A tool whose failure text can come from outside Codewhale
1585 /// ([`failure_text_is_outside`]) is judged by metadata alone: an MCP server
1586 /// that answers `BLOCKED:` or `{"side_effect_status":"not_started"}` must not
1587 /// hide a call that ran. Such a call reads as failed, which over-counts what
1588 /// ran rather than under-counting it.
1589 fn failure_evidence(step: &ToolStep) -> FailureEvidence {
1590 let structured = structured_output(step);
1591 let facts = step.metadata.as_ref().or(structured.as_ref());
1592 if number(facts, &["exit_code", "return_code"]).is_some() {
1593 return FailureEvidence::Ran;
1594 }
1595 if string_field(step.metadata.as_ref(), &["side_effect_status"]).as_deref()
1596 == Some("not_started")
1597 {
1598 return FailureEvidence::Refused;
1599 }
1600 if failure_text_is_outside(step) {
1601 return FailureEvidence::Unclear;
1602 }
1603 let Some(output) = step.output.as_deref() else {
1604 return FailureEvidence::Unclear;
1605 };
1606 let lines = || output.lines().map(str::trim);
1607 if lines().any(|line| {
1608 SHELL_RAN_LINES
1609 .iter()
1610 .any(|prefix| line.starts_with(prefix))
1611 }) {
1612 return FailureEvidence::Ran;
1613 }
1614 let not_started = lines()
1615 .rfind(|line| !line.is_empty())
1616 .and_then(|last| last.strip_prefix("Tool validation feedback: "))
1617 .and_then(|feedback| serde_json::from_str::<Value>(feedback).ok())
1618 .is_some_and(|feedback| {
1619 feedback.get("side_effect_status").and_then(Value::as_str) == Some("not_started")
1620 });
1621 if not_started {
1622 return FailureEvidence::Refused;
1623 }
1624 let Some(first) = lines().find(|line| !line.is_empty() && !line.starts_with("[approval]"))
1625 else {
1626 return FailureEvidence::Unclear;
1627 };
1628 let first = first.strip_prefix("Error: ").unwrap_or(first);
1629 if first.starts_with("BLOCKED:") {
1630 let semantic =
1631 codewhale_execpolicy::canonical_action::canonical_action_alias(&step.name, &step.input);
1632 return if SHELL_TOOLS.contains(&semantic) {
1633 FailureEvidence::Refused
1634 } else {
1635 FailureEvidence::Unclear
1636 };
1637 }
1638 if first.starts_with("Tool '") && first.contains("' denied by user") {
1639 return FailureEvidence::DeniedAtApproval;
1640 }
1641 const REFUSED_PREFIXES: [&str; 6] = [
1642 "Invalid input for tool '",
1643 "Path escapes workspace:",
1644 // `ToolError` text, as a Runtime thread saves it.
1645 "Failed to authorize tool execution:",
1646 "Failed to validate input:",
1647 "Failed to locate tool:",
1648 "Failed to resolve path '",
1649 ];
1650 const REFUSED_MARKERS: [&str; 3] = [
1651 "' was denied: ",
1652 "' is not available",
1653 "' is missing required field ",
1654 ];
1655 let refused = REFUSED_PREFIXES
1656 .iter()
1657 .any(|prefix| first.starts_with(prefix))
1658 || (first.starts_with("Tool '")
1659 && REFUSED_MARKERS.iter().any(|marker| first.contains(marker)))
1660 || first.contains("is not available in Plan mode");
1661 if refused {
1662 FailureEvidence::Refused
1663 } else {
1664 FailureEvidence::Unclear
1665 }
1666 }
1667
1668 #[must_use]
1669 pub fn parse_nested_calls(facts: &Value) -> Vec<NestedCall> {
1670 nested_calls(Some(facts))
1671 }
1672
1673 fn nested_calls(facts: Option<&Value>) -> Vec<NestedCall> {
1674 let Some(calls) = facts
1675 .and_then(|facts| facts.get("calls"))
1676 .and_then(Value::as_array)
1677 else {
1678 return Vec::new();
1679 };
1680 calls
1681 .iter()
1682 .take(MAX_NESTED_CALLS)
1683 .filter_map(|call| {
1684 Some(NestedCall {
1685 tool: call.get("tool")?.as_str()?.to_string(),
1686 ok: call.get("ok").and_then(Value::as_bool).unwrap_or(false),
1687 elapsed_ms: call.get("elapsed_ms").and_then(Value::as_u64),
1688 })
1689 })
1690 .collect()
1691 }
1692
1693 fn string_field(value: Option<&Value>, keys: &[&str]) -> Option<String> {
1694 let value = value?;
1695 keys.iter().find_map(|key| {
1696 value
1697 .get(*key)
1698 .and_then(Value::as_str)
1699 .map(str::trim)
1700 .filter(|text| !text.is_empty())
1701 .map(str::to_string)
1702 })
1703 }
1704
1705 fn number(value: Option<&Value>, keys: &[&str]) -> Option<i64> {
1706 let value = value?;
1707 keys.iter()
1708 .find_map(|key| value.get(*key).and_then(Value::as_i64))
1709 }
1710
1711 fn redact(text: &str) -> String {
1712 codewhale_sanitize::redact::redact_secrets(text)
1713 }
1714
1715 use codewhale_commands::diagnostics_reports::receipts::{bounded, plural};
1716
1717 fn first_error_line(output: Option<&str>) -> Option<String> {
1718 let line = output?
1719 .lines()
1720 .map(str::trim)
1721 .find(|line| !line.is_empty() && !line.starts_with("[approval]"))?;
1722 let line = line.strip_prefix("Error: ").unwrap_or(line);
1723 Some(bounded(&redact(line), MAX_ERROR_CHARS))
1724 }
1725
1726 fn step_duration_ms(step: &ToolStep) -> Option<u64> {
1727 number(step.metadata.as_ref(), &["duration_ms"])
1728 .and_then(|ms| u64::try_from(ms).ok())
1729 .or_else(|| match (step.started_at, step.ended_at) {
1730 (Some(start), Some(end)) if end >= start => {
1731 u64::try_from((end - start).num_milliseconds()).ok()
1732 }
1733 _ => None,
1734 })
1735 }
1736
1737 fn non_empty_act_str<'a>(act: &'a Value, key: &str) -> Option<&'a str> {
1738 act.get(key)
1739 .and_then(Value::as_str)
1740 .map(str::trim)
1741 .filter(|value| !value.is_empty())
1742 }
1743
1744 fn plugin_changes_from_step(
1745 step: &ToolStep,
1746 workspace: Option<&str>,
1747 notes: &mut BTreeSet<String>,
1748 ) -> Vec<ActionKind> {
1749 let semantic =
1750 codewhale_execpolicy::canonical_action::canonical_action_alias(&step.name, &step.input);
1751 if step.name != "plugin_manager" && semantic != "plugin_manager" {
1752 return Vec::new();
1753 }
1754 let Some(broker_acts) = step
1755 .metadata
1756 .as_ref()
1757 .and_then(|meta| meta.pointer("/core_calls/broker_acts"))
1758 else {
1759 return Vec::new();
1760 };
1761 let total = broker_acts
1762 .get("total")
1763 .and_then(Value::as_u64)
1764 .and_then(|count| usize::try_from(count).ok());
1765 let acts = broker_acts.get("acts").and_then(Value::as_array);
1766 if let Some(total) = total
1767 && total > acts.map_or(0, Vec::len)
1768 {
1769 notes.insert("Plugin changes: more plugin acts than this receipt lists.".to_string());
1770 }
1771 let mut changes = Vec::new();
1772 for act in acts.into_iter().flatten() {
1773 if non_empty_act_str(act, "service") != Some("plugins") {
1774 continue;
1775 }
1776 let is_cut = act.get("cut").and_then(Value::as_bool) == Some(true);
1777 let application = non_empty_act_str(act, "application");
1778 let outcome = non_empty_act_str(act, "outcome");
1779 let applied = application == Some("applied")
1780 || (is_cut && matches!(outcome, Some("applied" | "completed" | "ok")));
1781 if !applied {
1782 if is_cut && application.is_none() && outcome.is_none() {
1783 notes.insert(
1784 "Plugin changes: a plugin act was cut before details were recorded (not recorded)."
1785 .to_string(),
1786 );
1787 }
1788 continue;
1789 }
1790 let method = non_empty_act_str(act, "method")
1791 .map(|value| bounded(&redact(value), MAX_QUERY_CHARS))
1792 .unwrap_or_else(|| "not recorded".to_string());
1793 let plugin = non_empty_act_str(act, "plugin")
1794 .map(|value| {
1795 bounded(
1796 &workspace_relative(&redact(value), workspace),
1797 MAX_COMMAND_CHARS,
1798 )
1799 })
1800 .unwrap_or_else(|| "not recorded".to_string());
1801 let hash = non_empty_act_str(act, "hash")
1802 .or_else(|| non_empty_act_str(act, "content_hash"))
1803 .map(|value| bounded(&redact(value), MAX_QUERY_CHARS));
1804 let approver = codewhale_plugins::host_services::recorded_approver_label(
1805 non_empty_act_str(act, "approver"),
1806 non_empty_act_str(act, "posture"),
1807 )
1808 .map(str::to_string)
1809 .unwrap_or_else(|| "not recorded".to_string());
1810 let services = act
1811 .get("services")
1812 .and_then(Value::as_array)
1813 .map(|items| {
1814 items
1815 .iter()
1816 .filter_map(Value::as_str)
1817 .map(str::trim)
1818 .filter(|value| !value.is_empty())
1819 .map(|value| bounded(&redact(value), MAX_QUERY_CHARS))
1820 .collect()
1821 })
1822 .unwrap_or_default();
1823 changes.push(ActionKind::PluginChange {
1824 method,
1825 plugin,
1826 hash,
1827 approver,
1828 services,
1829 });
1830 }
1831 changes
1832 }
1833
1834 // ---------------------------------------------------------------------------
1835 // Assembly
1836 // ---------------------------------------------------------------------------
1837
1838 /// What [`assemble`] needs to know about the record besides its steps.
1839 struct Assembly<'a> {
1840 turn: Option<&'a str>,
1841 kind: SourceKind,
1842 turn_postures: Vec<TurnPosture>,
1843 /// False when the record predates its approval log, so "no approval on
1844 /// record" does not mean "did not ask".
1845 approvals_recorded: bool,
1846 }
1847
1848 fn assemble(
1849 source: ReceiptSource,
1850 steps: Vec<ToolStep>,
1851 approvals: Vec<ApprovalStep>,
1852 turn_failures: Vec<TurnFailure>,
1853 workspace_changes: Vec<(String, TurnWorkspaceChange)>,
1854 scope: Assembly<'_>,
1855 mut notes: BTreeSet<String>,
1856 ) -> Receipt {
1857 let Assembly {
1858 turn,
1859 kind,
1860 turn_postures,
1861 approvals_recorded,
1862 } = scope;
1863 let mut approvals_by_call = HashMap::new();
1864 let mut calls_by_id = HashMap::<&str, usize>::new();
1865 for step in &steps {
1866 if let Some(id) = step.call_id.as_deref() {
1867 *calls_by_id.entry(id).or_default() += 1;
1868 }
1869 }
1870 for (index, approval) in approvals.iter().enumerate() {
1871 if let Some(call_id) = &approval.call_id {
1872 approvals_by_call
1873 .entry(call_id.as_str())
1874 .and_modify(|entry| *entry = None)
1875 .or_insert(Some(index));
1876 }
1877 }
1878 if steps.iter().any(|step| step.call_id.is_none())
1879 || calls_by_id.values().any(|count| *count > 1)
1880 || approvals_by_call.values().any(Option::is_none)
1881 {
1882 notes.insert("Tool identity: missing, mismatched or repeated call identities cannot establish a unique approval association.".to_string());
1883 }
1884 let mut approval_used = vec![false; approvals.len()];
1885 let mut totals = ReceiptTotals {
1886 line_counts_complete: true,
1887 ..ReceiptTotals::default()
1888 };
1889 let mut actions: Vec<ReceiptAction> = Vec::new();
1890 let mut agents: HashMap<String, usize> = HashMap::new();
1891 let in_scope = |step_turn: Option<&str>| turn.is_none_or(|turn| step_turn == Some(turn));
1892
1893 for step in &steps {
1894 let approval_index = step
1895 .call_id
1896 .as_deref()
1897 .filter(|id| !id.trim().is_empty() && calls_by_id.get(id) == Some(&1))
1898 .and_then(|id| approvals_by_call.get(id).copied().flatten());
1899 if let Some(index) = approval_index {
1900 approval_used[index] = true;
1901 }
1902 let approval = approval_index.map(|index| approvals[index].fact);
1903 if !in_scope(step.turn.as_deref()) {
1904 continue;
1905 }
1906 let plugin_changes =
1907 plugin_changes_from_step(step, source.workspace.as_deref(), &mut notes);
1908 if !plugin_changes.is_empty() {
1909 let duration_ms = step_duration_ms(step);
1910 for what in plugin_changes {
1911 actions.push(ReceiptAction {
1912 seq: 0,
1913 turn: step.turn.clone(),
1914 at: step.started_at,
1915 call_id: step.call_id.clone(),
1916 tool: step.name.clone(),
1917 what,
1918 status: ActionStatus::Ok,
1919 duration_ms,
1920 approval,
1921 error: None,
1922 });
1923 }
1924 if step.outcome == StepOutcome::Ok {
1925 continue;
1926 }
1927 }
1928 let classified = classify(step, &mut notes);
1929 let is_command = matches!(classified, Classified::Listed(ActionKind::Command { .. }));
1930 let held_at_approval = approval.is_some_and(|fact| {
1931 !fact.decision.ran() && fact.decision != ApprovalDecisionLabel::Pending
1932 });
1933 let status = match step.outcome {
1934 _ if held_at_approval => ActionStatus::NotRun,
1935 StepOutcome::Ok => ActionStatus::Ok,
1936 // A failed result is not proof the call ran: Codewhale answers a
1937 // call it blocks before running with an error result too.
1938 StepOutcome::Failed => match failure_evidence(step) {
1939 FailureEvidence::Ran => ActionStatus::Failed,
1940 FailureEvidence::Refused => ActionStatus::Blocked,
1941 FailureEvidence::DeniedAtApproval => ActionStatus::NotRun,
1942 FailureEvidence::Unclear if is_command => ActionStatus::Unknown,
1943 FailureEvidence::Unclear => ActionStatus::Failed,
1944 },
1945 StepOutcome::Interrupted => ActionStatus::Interrupted,
1946 StepOutcome::Running => ActionStatus::Running,
1947 StepOutcome::Unknown => ActionStatus::Unknown,
1948 };
1949 let what = match classified {
1950 Classified::Listed(what) => what,
1951 Classified::AgentFollowUp { agent_id, status } => {
1952 if let (Some(&index), Some(status)) = (agents.get(&agent_id), status)
1953 && let ActionKind::Subagent { outcome, .. } = &mut actions[index].what
1954 {
1955 *outcome = Some(status);
1956 }
1957 totals.other_tool_calls += 1;
1958 continue;
1959 }
1960 Classified::Other => {
1961 totals.other_tool_calls += 1;
1962 if !matches!(
1963 status,
1964 ActionStatus::Failed | ActionStatus::NotRun | ActionStatus::Blocked
1965 ) {
1966 continue;
1967 }
1968 ActionKind::Tool
1969 }
1970 };
1971 if let ActionKind::Subagent {
1972 agent_id: Some(agent_id),
1973 ..
1974 } = &what
1975 {
1976 agents.insert(agent_id.clone(), actions.len());
1977 }
1978 let duration_ms = step_duration_ms(step);
1979 actions.push(ReceiptAction {
1980 seq: 0,
1981 turn: step.turn.clone(),
1982 at: step.started_at,
1983 call_id: step.call_id.clone(),
1984 tool: step.name.clone(),
1985 what,
1986 status,
1987 duration_ms,
1988 approval,
1989 // A block's reason is the fact worth keeping; a held call's
1990 // approval already says why it did not run.
1991 error: matches!(
1992 status,
1993 ActionStatus::Failed | ActionStatus::Unknown | ActionStatus::Blocked
1994 )
1995 .then(|| first_error_line(step.output.as_deref()))
1996 .flatten(),
1997 });
1998 }
1999
2000 for (index, approval) in approvals.iter().enumerate() {
2001 if approval_used[index] {
2002 continue;
2003 }
2004 // Session approvals carry no turn; they are in scope only for a
2005 // whole-session receipt.
2006 if turn.is_some() && approval.turn.as_deref() != turn {
2007 continue;
2008 }
2009 actions.push(ReceiptAction {
2010 seq: 0,
2011 turn: approval.turn.clone(),
2012 at: approval.fact.at,
2013 call_id: approval.call_id.clone(),
2014 tool: approval.tool.clone(),
2015 what: ActionKind::Approval,
2016 status: if approval.fact.decision.ran() {
2017 ActionStatus::Ok
2018 } else if approval.fact.decision == ApprovalDecisionLabel::Pending {
2019 ActionStatus::Running
2020 } else {
2021 ActionStatus::NotRun
2022 },
2023 duration_ms: None,
2024 approval: Some(approval.fact),
2025 error: None,
2026 });
2027 }
2028
2029 for (turn_id, ended_at, error) in turn_failures {
2030 if !in_scope(turn_id.as_deref()) {
2031 continue;
2032 }
2033 actions.push(ReceiptAction {
2034 seq: 0,
2035 turn: turn_id,
2036 at: ended_at,
2037 call_id: None,
2038 tool: "turn".to_string(),
2039 what: ActionKind::TurnFailed,
2040 status: ActionStatus::Failed,
2041 duration_ms: None,
2042 approval: None,
2043 error: error.map(|error| bounded(&redact(&error), MAX_ERROR_CHARS)),
2044 });
2045 }
2046
2047 for (turn_id, change) in workspace_changes {
2048 if !in_scope(Some(&turn_id)) {
2049 continue;
2050 }
2051 // File tools already itemize their own paths in this turn.
2052 let tool_paths: BTreeSet<String> = actions
2053 .iter()
2054 .filter(|action| action.turn.as_deref() == Some(turn_id.as_str()))
2055 .filter(|action| action.status == ActionStatus::Ok)
2056 .filter_map(|action| match &action.what {
2057 ActionKind::FileChange { files } => Some(files),
2058 _ => None,
2059 })
2060 .flatten()
2061 .map(|file| workspace_relative(&file.path, source.workspace.as_deref()))
2062 .collect();
2063 let files: Vec<FileTouch> = change
2064 .files
2065 .into_iter()
2066 .filter(|file| !tool_paths.contains(&file.path))
2067 .collect();
2068 if files.is_empty() && !change.truncated {
2069 continue;
2070 }
2071 // Slot it after the turn's last listed action.
2072 let at = actions
2073 .iter()
2074 .rposition(|action| action.turn.as_deref() == Some(turn_id.as_str()))
2075 .map_or(actions.len(), |index| index + 1);
2076 actions.insert(
2077 at,
2078 ReceiptAction {
2079 seq: 0,
2080 turn: Some(turn_id),
2081 at: None,
2082 call_id: None,
2083 tool: "workspace".to_string(),
2084 what: ActionKind::WorkspaceChange {
2085 files,
2086 truncated: change.truncated,
2087 },
2088 status: ActionStatus::Ok,
2089 duration_ms: None,
2090 approval: None,
2091 error: None,
2092 },
2093 );
2094 }
2095
2096 if kind == SourceKind::Thread {
2097 // Runtime actions carry timestamps; keep each turn's order and slot
2098 // standalone approvals and turn failures where they happened.
2099 actions.sort_by_key(|action| action.at);
2100 }
2101 for (index, action) in actions.iter_mut().enumerate() {
2102 action.seq = index + 1;
2103 }
2104
2105 tally(&actions, &mut totals);
2106 if approvals_recorded {
2107 totals.ran_without_asking = actions
2108 .iter()
2109 .filter(|action| {
2110 action.ran_without_asking()
2111 && action.call_id.as_deref().is_some_and(|id| {
2112 !id.trim().is_empty()
2113 && calls_by_id.get(id) == Some(&1)
2114 && approvals_by_call.get(id).is_none_or(Option::is_some)
2115 })
2116 })
2117 .count();
2118 }
2119 let mut postures: Vec<&'static str> = Vec::new();
2120 for (turn_id, posture) in &turn_postures {
2121 if let Some(posture) = posture
2122 && in_scope(Some(turn_id.as_str()))
2123 && !postures.contains(posture)
2124 {
2125 postures.push(posture);
2126 }
2127 }
2128 let decider_not_recorded =
2129 totals.approvals.approved_by.not_recorded + totals.approvals.denied_by.not_recorded;
2130 if decider_not_recorded > 0 {
2131 notes.insert(format!(
2132 "Who decided: {} decision(s) predate Codewhale recording the decider, or came from a sub-agent, so they show the decision without who made it.",
2133 decider_not_recorded
2134 ));
2135 }
2136 let unclear = actions
2137 .iter()
2138 .filter(|action| action.status == ActionStatus::Unknown)
2139 .count();
2140 if unclear > 0 {
2141 notes.insert(format!(
2142 "Whether it ran: {unclear} call(s) have no result, or returned an error with no exit code, so the record does not show that they started. They are listed but not counted as run."
2143 ));
2144 }
2145
2146 let omitted_actions = actions.len().saturating_sub(MAX_RECEIPT_ACTIONS);
2147 actions.truncate(MAX_RECEIPT_ACTIONS);
2148 Receipt {
2149 schema_id: RECEIPT_SCHEMA_ID,
2150 source,
2151 turn: turn.map(str::to_string),
2152 postures,
2153 totals,
2154 usage: None,
2155 actions,
2156 omitted_actions,
2157 not_recorded: notes.into_iter().collect(),
2158 claim_ceiling: CLAIM_CEILING,
2159 }
2160 }
2161
2162 fn tally(actions: &[ReceiptAction], totals: &mut ReceiptTotals) {
2163 let mut changed: BTreeSet<&str> = BTreeSet::new();
2164 let mut created: BTreeSet<&str> = BTreeSet::new();
2165 let mut deleted: BTreeSet<&str> = BTreeSet::new();
2166 let mut outside: BTreeSet<&str> = BTreeSet::new();
2167 let mut seen_approval_calls: BTreeSet<&str> = BTreeSet::new();
2168 for action in actions {
2169 let ran = !matches!(
2170 action.status,
2171 ActionStatus::NotRun | ActionStatus::Blocked | ActionStatus::Unknown
2172 );
2173 match action.status {
2174 ActionStatus::Failed => totals.failures += 1,
2175 ActionStatus::Blocked => totals.blocked += 1,
2176 _ => {}
2177 }
2178 match &action.what {
2179 ActionKind::FileChange { files } | ActionKind::WorkspaceChange { files, .. }
2180 if action.status == ActionStatus::Ok =>
2181 {
2182 if matches!(action.what, ActionKind::WorkspaceChange { .. }) {
2183 outside.extend(files.iter().map(|file| file.path.as_str()));
2184 }
2185 for file in files {
2186 changed.insert(&file.path);
2187 match file.change {
2188 FileChangeKind::Created => {
2189 created.insert(&file.path);
2190 }
2191 FileChangeKind::Deleted => {
2192 deleted.insert(&file.path);
2193 }
2194 FileChangeKind::Edited | FileChangeKind::Written => {}
2195 }
2196 match (file.lines_added, file.lines_removed) {
2197 (Some(added), Some(removed)) => {
2198 totals.lines_added += added;
2199 totals.lines_removed += removed;
2200 }
2201 _ => totals.line_counts_complete = false,
2202 }
2203 }
2204 }
2205 ActionKind::Command { .. } if ran => {
2206 totals.commands += 1;
2207 if action.status == ActionStatus::Failed {
2208 totals.commands_failed += 1;
2209 }
2210 }
2211 ActionKind::Code { .. } if ran => totals.code_runs += 1,
2212 ActionKind::Network { .. } if ran => totals.network += 1,
2213 ActionKind::Mcp { plugin, .. } if ran => {
2214 totals.mcp_calls += 1;
2215 if *plugin {
2216 totals.plugin_calls += 1;
2217 }
2218 }
2219 ActionKind::PluginChange { .. } if ran => totals.plugin_changes += 1,
2220 ActionKind::Subagent { .. } if ran => totals.subagents += 1,
2221 _ => {}
2222 }
2223 if let Some(fact) = action.approval.filter(|_| {
2224 action
2225 .call_id
2226 .as_deref()
2227 .filter(|id| !id.is_empty())
2228 .is_none_or(|id| seen_approval_calls.insert(id))
2229 }) {
2230 let approvals = &mut totals.approvals;
2231 approvals.total += 1;
2232 match fact.decision {
2233 ApprovalDecisionLabel::Approved | ApprovalDecisionLabel::ApprovedWithPolicy => {
2234 approvals.approved += 1
2235 }
2236 ApprovalDecisionLabel::Denied => approvals.denied += 1,
2237 ApprovalDecisionLabel::TimedOut => approvals.timed_out += 1,
2238 ApprovalDecisionLabel::Cancelled | ApprovalDecisionLabel::Unavailable => {
2239 approvals.not_answered += 1
2240 }
2241 ApprovalDecisionLabel::Pending => approvals.pending += 1,
2242 }
2243 let by = match fact.decision {
2244 ApprovalDecisionLabel::Approved | ApprovalDecisionLabel::ApprovedWithPolicy => {
2245 &mut approvals.approved_by
2246 }
2247 ApprovalDecisionLabel::Denied => &mut approvals.denied_by,
2248 _ => continue,
2249 };
2250 match fact.decided_by {
2251 Some(ApprovalDecider::User) => by.you += 1,
2252 Some(ApprovalDecider::SessionRule) => by.session_rule += 1,
2253 Some(ApprovalDecider::Posture) => by.posture += 1,
2254 // Codewhale never approves, and its denials are read as not
2255 // answered (`approvals_from_replay`), so this is only a
2256 // record that says neither.
2257 Some(ApprovalDecider::Host) | None => by.not_recorded += 1,
2258 }
2259 }
2260 }
2261 totals.files_changed = changed.len();
2262 totals.files_created = created.len();
2263 totals.files_deleted = deleted.len();
2264 totals.files_changed_outside_file_tools = outside.len();
2265 }
2266
2267 // ---------------------------------------------------------------------------
2268 // Rendering
2269 // ---------------------------------------------------------------------------
2270
2271 #[cfg(test)]
2272 use codewhale_commands::diagnostics_reports::receipts::code_span;
2273 #[cfg(test)]
2274 use codewhale_commands::diagnostics_reports::receipts::{action_line, totals_line};
2275 pub use codewhale_commands::diagnostics_reports::receipts::{render_json, render_markdown};
2276
2277 #[cfg(test)]
2278 #[path = "receipts/tests.rs"]
2279 mod tests;
2280
2280 lines RUST