Skip to main content

codewhale_command_contract/facets/
debug_receipts.rs

1//! Receipt output data, moved from the shared receipt builder without schema changes.
2//! The builder stays host-owned; CLI, API and slash commands share these shapes.
3
4use chrono::{DateTime, Utc};
5use serde::{Deserialize, Serialize};
6
7/// Maximum number of listed actions; totals include omitted actions.
8pub const MAX_RECEIPT_ACTIONS: usize = 2_000;
9pub const RECEIPT_SCHEMA_ID: &str = "codewhale.receipt/v1";
10
11/// Who resolved an approval request. Recorded on the decision half so a
12/// receipt says "approved by you" only when a person answered. Records
13/// written before this field existed carry no decider; readers report it as
14/// not recorded rather than guessing.
15#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
16#[serde(rename_all = "snake_case")]
17pub enum ApprovalDecider {
18    /// A person answered the prompt: the terminal card, the app, the web
19    /// mirror, or a Runtime API client acting for them.
20    User,
21    /// A remembered "allow/deny for this session" rule answered it.
22    SessionRule,
23    /// The active mode or permission posture answered it without a prompt.
24    Posture,
25    /// The host resolved it without a person: the turn had ended, was
26    /// cancelled, or the decision channel closed.
27    Host,
28}
29
30#[derive(Debug, Clone, Serialize, PartialEq)]
31pub struct Receipt {
32    pub schema_id: &'static str,
33    pub source: ReceiptSource,
34    /// Set when the receipt covers one turn instead of the whole session.
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub turn: Option<String>,
37    /// Permission postures the covered turns ran under, in first-seen order
38    /// (`Ask`, `Auto-Review`, `Full Access`, `Never`). Read from each turn's
39    /// own record; empty when no turn recorded one.
40    pub postures: Vec<&'static str>,
41    pub totals: ReceiptTotals,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub usage: Option<ReceiptUsage>,
44    pub actions: Vec<ReceiptAction>,
45    /// Actions left off the list because it hit [`MAX_RECEIPT_ACTIONS`].
46    pub omitted_actions: usize,
47    /// Facts this record does not hold, stated instead of guessed.
48    pub not_recorded: Vec<String>,
49    pub claim_ceiling: [&'static str; 3],
50}
51
52#[derive(Debug, Clone, Serialize, PartialEq)]
53pub struct ReceiptUsage {
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub tokens: Option<ReceiptTokens>,
56    #[serde(skip_serializing_if = "Option::is_none")]
57    pub cost: Option<ReceiptCost>,
58}
59
60#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
61pub struct ReceiptTokens {
62    #[serde(skip_serializing_if = "Option::is_none")]
63    pub input: Option<u64>,
64    #[serde(skip_serializing_if = "Option::is_none")]
65    pub output: Option<u64>,
66    pub total: u64,
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub cache_read: Option<u64>,
69    #[serde(skip_serializing_if = "Option::is_none")]
70    pub cache_write: Option<u64>,
71    #[serde(skip_serializing_if = "Option::is_none")]
72    pub reasoning: Option<u64>,
73    #[serde(skip_serializing_if = "Option::is_none")]
74    pub calls: Option<usize>,
75}
76
77#[derive(Debug, Clone, Serialize, PartialEq)]
78pub struct ReceiptCost {
79    pub state: ReceiptCostState,
80    #[serde(skip_serializing_if = "Option::is_none")]
81    pub amount: Option<f64>,
82    pub currency: &'static str,
83    pub priced_turns: u32,
84    pub unpriced_turns: u32,
85    pub report: String,
86}
87
88#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
89#[serde(rename_all = "snake_case")]
90pub enum ReceiptCostState {
91    Priced,
92    Partial,
93    Unknown,
94}
95
96#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
97#[serde(rename_all = "snake_case")]
98pub enum SourceKind {
99    /// A terminal session (saved transcript + approval log).
100    Session,
101    /// A Runtime thread (turn/item records + event log).
102    Thread,
103}
104
105#[derive(Debug, Clone, Serialize, PartialEq)]
106pub struct ReceiptSource {
107    pub kind: SourceKind,
108    pub id: String,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub title: Option<String>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub workspace: Option<String>,
113    #[serde(skip_serializing_if = "Option::is_none")]
114    pub model: Option<String>,
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub started_at: Option<DateTime<Utc>>,
117    #[serde(skip_serializing_if = "Option::is_none")]
118    pub updated_at: Option<DateTime<Utc>>,
119}
120
121#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
122pub struct ReceiptTotals {
123    /// Distinct paths changed, by file tools or (from the turn's workspace
124    /// snapshots) by anything else during the turn.
125    pub files_changed: usize,
126    /// Of `files_changed`, paths no file tool changed: a command, a build, or
127    /// another process wrote them during the turn.
128    pub files_changed_outside_file_tools: usize,
129    pub files_created: usize,
130    pub files_deleted: usize,
131    /// Sum over changes whose line counts are recorded.
132    pub lines_added: u64,
133    pub lines_removed: u64,
134    /// False when at least one file change has no recorded line counts, so
135    /// the sums above are a floor.
136    pub line_counts_complete: bool,
137    pub commands: usize,
138    pub commands_failed: usize,
139    pub code_runs: usize,
140    pub network: usize,
141    pub mcp_calls: usize,
142    pub plugin_calls: usize,
143    #[serde(default)]
144    pub plugin_changes: usize,
145    pub subagents: usize,
146    pub approvals: ApprovalTotals,
147    /// File changes, commands, code runs, web and MCP calls, and agents that
148    /// ran with no approval on record: the posture, an allow rule, or a
149    /// remembered grant let them run without a prompt. A call Codewhale
150    /// refused before it started, or one the record does not show starting,
151    /// is not counted. Zero, with a `not_recorded` note, for a session older
152    /// than its approval log.
153    pub ran_without_asking: usize,
154    /// Actions that ran and failed, plus failed turns.
155    pub failures: usize,
156    /// Calls Codewhale refused before they started: an Auto-Review or
157    /// guardian block, a tool-policy or allow-list denial, a sandbox
158    /// escalation the posture cannot grant, invalid input, or a tool that is
159    /// not available. Not counted as run, as failed, or as ran without asking.
160    pub blocked: usize,
161    /// Reads, searches, and other calls that are counted but not listed
162    /// unless they failed.
163    pub other_tool_calls: usize,
164}
165
166#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
167pub struct ApprovalTotals {
168    pub total: usize,
169    pub approved: usize,
170    pub denied: usize,
171    pub timed_out: usize,
172    /// Cancelled, or resolved by Codewhale because nobody could be asked
173    /// (the turn had ended or stopped). Never a person's no.
174    pub not_answered: usize,
175    pub pending: usize,
176    /// Who gave each approval counted in `approved`.
177    pub approved_by: DeciderCounts,
178    /// Who gave each denial counted in `denied`.
179    pub denied_by: DeciderCounts,
180}
181
182#[derive(Debug, Clone, Default, Serialize, PartialEq, Eq)]
183pub struct DeciderCounts {
184    pub you: usize,
185    pub session_rule: usize,
186    pub posture: usize,
187    /// The record predates Codewhale keeping who decided, or came from a
188    /// sub-agent's request, which does not carry it yet.
189    pub not_recorded: usize,
190}
191
192#[derive(Debug, Clone, Serialize, PartialEq)]
193pub struct ReceiptAction {
194    /// 1-based position in the session's action order.
195    pub seq: usize,
196    /// Runtime turn id, or the 1-based turn number in a terminal session.
197    #[serde(skip_serializing_if = "Option::is_none")]
198    pub turn: Option<String>,
199    #[serde(skip_serializing_if = "Option::is_none")]
200    pub at: Option<DateTime<Utc>>,
201    #[serde(skip_serializing_if = "Option::is_none")]
202    pub call_id: Option<String>,
203    /// The tool name exactly as called.
204    pub tool: String,
205    #[serde(flatten)]
206    pub what: ActionKind,
207    pub status: ActionStatus,
208    #[serde(skip_serializing_if = "Option::is_none")]
209    pub duration_ms: Option<u64>,
210    #[serde(skip_serializing_if = "Option::is_none")]
211    pub approval: Option<ApprovalFact>,
212    /// First line of the failure, bounded and redacted.
213    #[serde(skip_serializing_if = "Option::is_none")]
214    pub error: Option<String>,
215}
216
217#[derive(Debug, Clone, Serialize, PartialEq)]
218#[serde(tag = "kind", rename_all = "snake_case")]
219pub enum ActionKind {
220    FileChange {
221        files: Vec<FileTouch>,
222    },
223    /// Files that changed in the workspace during a turn with no file tool
224    /// naming them, read from the turn's before/after snapshots. A command
225    /// changed them, or something else writing to the workspace did.
226    WorkspaceChange {
227        files: Vec<FileTouch>,
228        /// More paths changed than are listed.
229        #[serde(skip_serializing_if = "std::ops::Not::not")]
230        truncated: bool,
231    },
232    Command {
233        command: String,
234        #[serde(skip_serializing_if = "Option::is_none")]
235        cwd: Option<String>,
236        #[serde(skip_serializing_if = "Option::is_none")]
237        exit_code: Option<i64>,
238    },
239    Code {
240        #[serde(skip_serializing_if = "Option::is_none")]
241        exit_code: Option<i64>,
242        /// Tool calls the program made (`execute_tools`), when recorded.
243        #[serde(skip_serializing_if = "Vec::is_empty")]
244        nested: Vec<NestedCall>,
245    },
246    Network {
247        action: String,
248        #[serde(skip_serializing_if = "Option::is_none")]
249        host: Option<String>,
250        #[serde(skip_serializing_if = "Option::is_none")]
251        query: Option<String>,
252    },
253    Mcp {
254        #[serde(skip_serializing_if = "Option::is_none")]
255        server: Option<String>,
256        plugin: bool,
257    },
258    PluginChange {
259        method: String,
260        plugin: String,
261        #[serde(skip_serializing_if = "Option::is_none")]
262        hash: Option<String>,
263        approver: String,
264        #[serde(default, skip_serializing_if = "Vec::is_empty")]
265        services: Vec<String>,
266    },
267    Subagent {
268        #[serde(skip_serializing_if = "Option::is_none")]
269        name: Option<String>,
270        #[serde(skip_serializing_if = "Option::is_none")]
271        agent_id: Option<String>,
272        /// Last status the record holds for this agent.
273        #[serde(skip_serializing_if = "Option::is_none")]
274        outcome: Option<String>,
275    },
276    /// An approval with no matching call in the record (for example a
277    /// sub-agent's request).
278    Approval,
279    /// Any other tool. Listed only when it failed.
280    Tool,
281    /// A Runtime turn that ended in failure.
282    TurnFailed,
283}
284
285#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
286#[serde(rename_all = "snake_case")]
287pub enum FileChangeKind {
288    Edited,
289    Created,
290    Deleted,
291    /// Written whole; the record does not say whether the file existed.
292    Written,
293}
294
295#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
296pub struct FileTouch {
297    pub path: String,
298    pub change: FileChangeKind,
299    #[serde(skip_serializing_if = "Option::is_none")]
300    pub lines_added: Option<u64>,
301    #[serde(skip_serializing_if = "Option::is_none")]
302    pub lines_removed: Option<u64>,
303}
304
305#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
306pub struct NestedCall {
307    pub tool: String,
308    pub ok: bool,
309    #[serde(skip_serializing_if = "Option::is_none")]
310    pub elapsed_ms: Option<u64>,
311}
312
313#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
314#[serde(rename_all = "snake_case")]
315pub enum ActionStatus {
316    Ok,
317    /// Ran and failed.
318    Failed,
319    /// Did not run: held at approval (denied, timed out, never answered).
320    NotRun,
321    /// Did not run: Codewhale refused it before it started (an Auto-Review
322    /// or guardian block, a policy or allow-list denial, a sandbox escalation
323    /// the posture cannot grant, invalid input, a tool that is not
324    /// available). `error` carries the reason.
325    Blocked,
326    Interrupted,
327    Running,
328    /// The record does not show whether it ran: there is no result, or a
329    /// command returned an error with no exit code or shell status.
330    Unknown,
331}
332
333#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
334#[serde(rename_all = "snake_case")]
335pub enum ApprovalDecisionLabel {
336    Approved,
337    /// Approved with a wider sandbox after a sandbox denial.
338    ApprovedWithPolicy,
339    Denied,
340    TimedOut,
341    Cancelled,
342    /// The host answered because nobody could be asked.
343    Unavailable,
344    Pending,
345}
346
347impl ApprovalDecisionLabel {
348    pub fn ran(self) -> bool {
349        matches!(self, Self::Approved | Self::ApprovedWithPolicy)
350    }
351}
352
353#[derive(Debug, Clone, Copy, Serialize, PartialEq, Eq)]
354pub struct ApprovalFact {
355    pub decision: ApprovalDecisionLabel,
356    /// `None` when the decision names its own cause (timeout, pending) or the
357    /// record predates deciders.
358    #[serde(skip_serializing_if = "Option::is_none")]
359    pub decided_by: Option<ApprovalDecider>,
360    #[serde(skip_serializing_if = "Option::is_none")]
361    pub at: Option<DateTime<Utc>>,
362}
363
364impl ReceiptAction {
365    /// A change, command, code run, web or MCP call, or agent that ran with
366    /// no approval on record.
367    pub fn ran_without_asking(&self) -> bool {
368        // `Unknown`, `NotRun`, and `Blocked` are left out: the call did not
369        // start, or the record does not show that it did. A workspace change
370        // is not a call.
371        self.approval.is_none()
372            && matches!(
373                self.status,
374                ActionStatus::Ok
375                    | ActionStatus::Failed
376                    | ActionStatus::Interrupted
377                    | ActionStatus::Running
378            )
379            && matches!(
380                self.what,
381                ActionKind::FileChange { .. }
382                    | ActionKind::Command { .. }
383                    | ActionKind::Code { .. }
384                    | ActionKind::Network { .. }
385                    | ActionKind::Mcp { .. }
386                    | ActionKind::PluginChange { .. }
387                    | ActionKind::Subagent { .. }
388            )
389    }
390}