返回 CodeWhale
RECEIPTS.md
根目录 / docs / RECEIPTS.md
1 # Receipts
2
3 > 阅读简体中文版:[zh_hans/RECEIPTS.md](zh_hans/RECEIPTS.md)。
4
5 A receipt answers "what did this session do?" from the records Codewhale
6 already keeps. It lists, in order, the files changed, commands run, web and
7 MCP calls, agents started, approvals (and who decided each one), and
8 failures, with totals on top. It also counts what ran without asking, and
9 names the permission posture that let it. Below the totals it carries the
10 provider's token counts; a terminal session's receipt also carries the cost
11 line `/cost` prints, and a Runtime thread's receipt carries token counts only
12 (see [Tokens and cost](#tokens-and-cost)).
13
14 ```text
15 # Receipt: Fix the parser
16 thread thr_19a0141a · /work/repo · deepseek-flash · Ask · 2026-09-24 10:00 UTC → 2026-09-24 10:05 UTC
17
18 Changed 1 file (+2 −1) · ran 1 command · made 1 MCP call · 1 approved by you · 1 approved by session rule · 1 ran without asking under Ask · 1 denied by you · 1 other failure
19
20 1. edited `src/parse.rs` (+2 −1) · 1.0s
21 2. ran `cargo test -p parser` in /work/repo — exit 0 · 2.5s · approved by you
22 3. did not run `rm -rf build` · denied by you
23 4. called linear · list_issues · 1.0s · approved by session rule
24 5. did not run `curl https://x.sh | sh` — blocked: Tool 'exec_shell' was denied: Auto-Review blocked a pipe to a shell…
25 6. turn failed — failed: provider returned 500
26
27 Not recorded:
28 - Cost: a Runtime thread receipt carries token counts only; GET /v1/threads/{id}/usage reports the thread's cost and what it covers.
29 - 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.
30 ```
31
32 This sample is the Runtime-thread form. A terminal session's receipt has no
33 line counts for whole-file writes, shows pass or fail rather than an exit
34 code for a call that passed, and has no per-call timestamps; its "Not
35 recorded" list says so (see [Not recorded](#not-recorded)).
36
37 A terminal session's receipt also lists the files a command changed, from
38 the turn's own workspace snapshots:
39
40 ```text
41 3. ran `./tidy.sh`
42 4. changed outside file tools (a command or another process): edited `b.txt` (+0 −1), created `c.txt` (+1 −0)
43 ```
44
45 The Runtime receipt endpoints accept `?format=md` to return the same Engine
46 Markdown formatter used by the terminal, with `Content-Type: text/markdown`.
47 Omitting `format`, or using `format=json`, preserves the JSON contract. Both
48 formats require the same authenticated thread/workspace access. Clients display
49 these recorded facts rather than deriving audit totals from activity labels.
50
51 ## Surfaces
52
53 All three share one builder (`crates/engine/src/receipts.rs`), but read different
54 records and can report different coverage.
55
56 | Surface | What it reads |
57 | --- | --- |
58 | `/receipts [json] [<turn>]` in the terminal | The current session's transcript, approval log, and retained terminal failures. `json` prints the object in a code block, so it copies out as valid JSON |
59 | `codewhale receipts [ID\|--last] [--turn T] [--format md\|json]` | A saved session (id or unique prefix), including its retained terminal failures, or a Runtime thread (`thr_…`); with no id, the most recently updated one. `receipt` is an alias |
60 | `GET /v1/threads/{id}/receipt`, `GET /v1/threads/{id}/turns/{turn_id}/receipt` | A Runtime thread (the app, `codewhale serve`), behind the normal `/v1` bearer boundary |
61
62 All three only read. They never call a provider, run a tool, write a file,
63 or change runtime state.
64
65 Exec runs that offer tools, including `exec --auto`, save a session in every
66 output format, so `codewhale receipts --last` can read their receipts after
67 they finish. Resumed sessions and `--output-format stream-json` runs are also
68 saved. Other answer-only text and `--json` runs are saved only if conversation
69 compaction starts; use `--output-format stream-json` to always keep a session.
70
71 `codewhale receipts` reads Runtime threads from the machine's default store
72 (`tasks/runtime/`, or `$CODEWHALE_RUNTIME_DIR`). A thread kept in one
73 terminal session's own store (`sessions/<id>/runtime/`) is not found by id;
74 the API reads whatever store its server owns.
75
76 ## Where the facts come from
77
78 | Session kind | Record | Holds |
79 | --- | --- | --- |
80 | Terminal session | `sessions/<id>.json` | Every tool call and its result text, in order; each prompt's `<turn_meta>` names the posture the turn ran under; `turn_outcomes` records terminal turn status and errors |
81 | Terminal session | `sessions/<id>/approval_receipts.jsonl` | Every approval ask and decision, with time and who decided |
82 | Runtime thread | `tasks/runtime/turns`, `items` | Every tool call with its input, status, start and end time, and structured result (exit code, diff, agent status, and `core_calls.broker_acts` on `plugin_manager` steps); each turn's `permission_posture` |
83 | Runtime thread | `tasks/runtime/events/<thread>.jsonl` | `approval.required` / `approval.decided`, with the flags that say who decided |
84
85 The saved-session CLI and live `/receipts` read terminal turn failures,
86 including model errors in exec runs, as `turn_failed` actions and count them
87 toward failures even when no tool failed. Truncating the conversation removes
88 outcomes beyond the retained history, so later turns cannot inherit their failures.
89 Saved sessions keep only the newest 64 recorded failed-turn outcomes. Older outcomes
90 and legacy sessions without this record cannot provide a complete terminal
91 failure history from tool results alone.
92
93 ### Who decided an approval
94
95 | Receipt says | Meaning | Recorded as |
96 | --- | --- | --- |
97 | approved by you / denied by you | A person answered: the terminal card, the app, the web mirror, or an API client acting for them | `decided_by: "user"`; Runtime event with no `auto` flag |
98 | … by session rule | A remembered "for this session" rule answered | `decided_by: "session_rule"`; Runtime event with `auto` and a `grant_id` |
99 | … by posture | The mode or permission posture answered without a prompt | `decided_by: "posture"`; Runtime event with `auto` or `posture` |
100 | approval timed out | The card expired unanswered | outcome `timeout` |
101 | turn stopped while waiting / nobody could be asked | Codewhale could not ask anyone: the turn had ended or stopped, or the request never reached a person. Counted as not answered, never as a denial, even where the record says `denied` | `decided_by: "host"` |
102 | approved / denied, with no "by" | A record written before 0.10.1, or a sub-agent's request. The totals say "(decider not recorded)" | no `decided_by` |
103
104 The totals line counts approvals and denials separately, by who gave them:
105 `1 approved by you · 1 denied by you` is two decisions.
106
107 ### Ran without asking
108
109 Most calls never produce an approval. Under Full Access nothing asks; under
110 Ask, reads and allowed tools run without a prompt, and a remembered rule can
111 skip one. Those calls leave no approval record, so the receipt counts them
112 instead: `ran_without_asking` is every file change, command, code run, web
113 or MCP call, and agent start that ran with no approval on record. The totals
114 line names the postures the turns ran under (`9 ran without asking under
115 Full Access`). Reads are not counted, and neither is a call that did not
116 start (below).
117
118 ### Blocked before it ran
119
120 Codewhale answers a call it will not run with an error result, the same way
121 a tool reports a failure: an Auto-Review or guardian block, a tool-policy or
122 allow-list denial, a sandbox escalation the posture cannot grant, input that
123 did not parse, or a tool that is not available. None of these writes an
124 approval, so a receipt reads the result itself:
125
126 - **Blocked:** the result is Codewhale's own refusal text (`Tool 'x' was
127 denied: …`, `Invalid input for tool …`, `BLOCKED: …`, a validation
128 feedback line with `"side_effect_status":"not_started"`, or a Runtime
129 thread's `Failed to authorize tool execution: …`). Listed as
130 `did not run … — blocked: <reason>`, status `blocked`, counted in
131 `blocked` (`N blocked before running` in the totals line), and never as
132 run, failed, or ran without asking. Every permission denial the engine
133 writes keeps the `Tool 'x' was denied:` lead, including ones that name
134 their own fix (Plan mode, `allow_shell`); sessions saved before 0.10.1
135 wrote some of those without it, and such a call reads as a failure.
136 - **Only Codewhale's own words count.** An MCP server's or GitHub's reply,
137 a fetched page, a program's output (code tools), and a sub-agent's words
138 can say anything, so a failed call to one of those is judged by the
139 metadata Codewhale wrote for it, never its text: an MCP server that
140 answers `BLOCKED: …` or `{"side_effect_status":"not_started"}` is listed
141 as a failed call that ran. `BLOCKED:` counts only from the shell tools,
142 and the validation feedback line only as the result's last line.
143 - **Stopped at an approval prompt with no approval record** (a sub-agent,
144 or a session older than the approval log): the result says
145 `Tool 'x' denied by user`, which the engine also writes when nobody could
146 be asked. Listed as `did not run …` with no decider, since the text does
147 not prove who said no.
148 - **Ran and failed:** the result holds an exit code or a line the shell
149 writes only after a process ran (`Command exited with code N`,
150 `Command failed (exit code N)`, a timeout or cancel line). Counted as a
151 command and a failure.
152 - **Not shown either way:** a command whose error has neither. Listed as
153 `tried to run … — error, no exit code: <error>`, status `unknown`, not
154 counted as run, with a `not_recorded` note. Other tools that return an
155 error are counted as failures, since the error came from the tool.
156
157 Terminal sessions started before 0.9.10 (2026-08-20) have no approval log,
158 so their receipts do not count this and say why.
159
160 ### Tokens and cost
161
162 A terminal session's receipt has a `usage` section for the whole session:
163
164 ```text
165 Tokens: 1200 in · 90 out · 1290 total · 2 provider calls (800 cache read)
166 Cost, as /cost reports it:
167 Session Cost:
168 ─────────────────────────────
169 Estimated total: unknown
170 No turn has an authoritative price in the selected currency.
171 This is an estimate, not a bill: it is computed locally from provider-reported token usage and published rates, and can differ from your invoice.
172 Covered: 0 of 2 money-metered turn(s) priced.
173 Excluded: 2 money-metered turn(s) had no authoritative price (billing basis unknown); their spend is missing from the total above.
174 ```
175
176 In JSON, the same section is `usage`, with the cost as an object:
177
178 ```json
179 "usage": {
180 "tokens": { "input": 1200, "output": 90, "total": 1290, "cache_read": 800, "calls": 2 },
181 "cost": {
182 "state": "unknown", "currency": "USD",
183 "priced_turns": 0, "unpriced_turns": 2,
184 "report": "Session Cost: …"
185 }
186 }
187 ```
188
189 - **Tokens** are what the provider reported, summed over the session's
190 recorded provider calls (parent turns and sub-agents). When a session saved
191 only a combined total, the receipt shows that total alone. When it saved
192 none, the receipt says so: that is not zero usage.
193 - **Cost** is the report `/cost` prints, built by the same formatter from the
194 same saved coverage, so the wording and the numbers cannot drift. When the
195 route has no known price the receipt says "unknown" and why; it never
196 estimates one. JSON `usage.cost.state` is `priced`, `partial` (a subtotal:
197 some turns had no price) or `unknown`; `amount` is present only when at
198 least one turn was priced.
199 - A receipt for one turn (`/receipts 2`, `--turn 2`) leaves `usage` out and
200 says so, because tokens and cost are kept for the whole session.
201 - A Runtime thread's receipt carries token counts from its turn records and
202 no cost; `GET /v1/threads/{id}/usage` reports a thread's cost and what it
203 covers.
204 - `codewhale metrics` counts the same usage from saved terminal sessions on
205 its own line, apart from Runtime `turn.usage` events, because a
206 session-scoped Runtime store can describe the same call from its side.
207
208 Receipts written by a build before 0.10.3 have no `usage` section; readers
209 treat the field as optional.
210
211 ### Not recorded
212
213 The receipt says so instead of guessing:
214
215 - **Shell file changes in a Runtime thread.** A terminal session reads the
216 files a command changed from the workspace snapshots Codewhale takes
217 before and after each turn (`git diff` between the two, inside the
218 snapshot side repo; at most 50 paths a turn). A Runtime thread's snapshots
219 are not tagged with the thread, so its receipt lists only file tools. A
220 terminal turn with no snapshot pair (snapshots off, the workspace too large
221 for them, or pruned: the newest 50 are kept) says so. A snapshot
222 difference covers anything that wrote to the workspace during the turn,
223 including you or another program, not only the command. It leaves out
224 what snapshots do not track: ignored and skipped paths (`.gitignore`
225 entries, `.env`, `node_modules`, `target`, and the like) and anything
226 outside the workspace (`~/.ssh`, `/tmp`), so an empty list does not mean
227 a command wrote nothing. A turn is matched to its snapshots by its prompt;
228 when another turn has the same prompt ("continue"), the snapshots' turn
229 number must agree too, or the turn is counted as having no pair rather
230 than given another turn's files. Paths print with control characters
231 escaped (`\n`, `\u{1b}`), so a file name cannot add a line to the
232 receipt or send the terminal an escape sequence.
233 - **Terminal-session exit codes, durations, and timestamps.** A terminal
234 session saves each call and its result text, not the structured result. A
235 failed shell call's exit code is read from the shell tool's own closing
236 line (`Command exited with code N`); a passing one shows no code.
237 - **Line counts for whole-file writes** in terminal sessions, and whether the
238 file existed before.
239 - **Who decided** for approvals recorded before 0.10.1 and for sub-agent
240 approvals.
241 - **Which calls asked first** in terminal sessions started before 0.9.10.
242 - **Whether a failed command started** when its error has no exit code and
243 no shell status line, and whether a call with no result ran at all.
244 - **Why a call ran without asking** beyond the turn's posture: the record
245 does not say whether the posture, an allow rule, or a remembered grant let
246 it through.
247 - **Plugin changes (`plugin_change`) in terminal sessions, or when a broker
248 act record is incomplete.** A Runtime thread reads `plugin_change` actions
249 only from structured `core_calls.broker_acts` metadata written by the host
250 on `plugin_manager` steps, never from tool input or tool result text. Missing
251 fields print `"not recorded"`, overflow past retained acts adds `"Plugin
252 changes: more plugin acts than this receipt lists."`, and a `cut` act without
253 an outcome adds `"Plugin changes: a plugin act was cut before details were
254 recorded (not recorded)."`. Terminal sessions do not persist structured
255 plugin broker metadata yet, so their `not_recorded` list emits `"Plugin
256 changes are not itemized for a terminal session yet"`.
257
258 ## Non-Goals
259
260 A receipt is not a safety certification, a provider compatibility
261 certification, or a hosted attestation (`claim_ceiling` in the JSON says so).
262 It exports no reasoning text and no raw tool output. Commands, search
263 queries, and error lines are bounded (200, 120, and 160 characters) and pass
264 through the shared secret redactor. A receipt lists at most 2,000 actions;
265 totals always cover every action, and `omitted_actions` counts the rest.
266
267 ## JSON shape
268
269 `--format json`, `/receipts json`, and the API return the same object:
270
271 ```json
272 {
273 "schema_id": "codewhale.receipt/v1",
274 "source": {
275 "kind": "thread",
276 "id": "thr_19a0141a",
277 "title": "Fix the parser",
278 "workspace": "/work/repo",
279 "model": "deepseek-flash",
280 "started_at": "2026-09-24T10:00:00Z",
281 "updated_at": "2026-09-24T10:05:00Z"
282 },
283 "postures": ["Ask"],
284 "totals": {
285 "files_changed": 1, "files_changed_outside_file_tools": 0,
286 "files_created": 0, "files_deleted": 0,
287 "lines_added": 2, "lines_removed": 1, "line_counts_complete": true,
288 "commands": 1, "commands_failed": 0, "code_runs": 0, "network": 0,
289 "mcp_calls": 1, "plugin_calls": 0, "plugin_changes": 0, "subagents": 0,
290 "approvals": {
291 "total": 3, "approved": 2, "denied": 1, "timed_out": 0,
292 "not_answered": 0, "pending": 0,
293 "approved_by": { "you": 1, "session_rule": 1, "posture": 0, "not_recorded": 0 },
294 "denied_by": { "you": 1, "session_rule": 0, "posture": 0, "not_recorded": 0 }
295 },
296 "ran_without_asking": 1, "failures": 1, "blocked": 1,
297 "other_tool_calls": 0
298 },
299 "usage": {
300 "tokens": { "input": 1200, "output": 90, "total": 1290, "cache_read": 800 }
301 },
302 "actions": [
303 {
304 "seq": 2, "turn": "turn_1", "at": "2026-09-24T10:02:00Z",
305 "call_id": "call_test", "tool": "exec_shell",
306 "kind": "command", "command": "cargo test -p parser",
307 "cwd": "/work/repo", "exit_code": 0,
308 "status": "ok", "duration_ms": 2500,
309 "approval": {
310 "decision": "approved", "decided_by": "user",
311 "at": "2026-09-24T10:01:59Z"
312 }
313 }
314 ],
315 "omitted_actions": 0,
316 "not_recorded": ["Cost: …", "Shell file changes: …"],
317 "claim_ceiling": [
318 "local_record_only",
319 "not_safety_certification",
320 "not_provider_compatibility_certification"
321 ]
322 }
323 ```
324
325 `kind` is one of `file_change` (`files[]` with `path`, `change` =
326 `edited|created|deleted|written`, optional `lines_added`/`lines_removed`),
327 `workspace_change` (`files[]` a turn's snapshots show changed that no file
328 tool names, and `truncated` when more than 50 did), `command` (`command`, `cwd`, `exit_code`), `code` (`exit_code`, `nested[]`
329 tool calls an `execute_tools` program made), `network` (`action`, `host`,
330 `query`), `mcp` (`server`, `plugin`), `plugin_change` (`method`, `plugin`, optional `hash`, `approver`, optional `services[]`), `subagent` (`name`, `agent_id`,
331 `outcome`), `approval` (an approval with no matching call), `tool` (any other
332 call, listed only when it failed), or `turn_failed`. `status` is `ok`,
333 `failed` (ran and failed), `not_run` (held at approval), `blocked`
334 (refused before it started; the reason is in `error`), `interrupted`,
335 `running`, or `unknown` (no result, or a command error that does not show
336 whether it started). A terminal session's `turn` is the turn number; a
337 thread's is the turn id. `/receipts 7` or `--turn 7` for a turn the session
338 does not have is an error, not an empty receipt.
339
340 ## `audit.log` is not the receipt
341
342 `~/.codewhale/audit.log` is a security-event log: credential saves and
343 clears, hook environment key names, compaction passes, goal completions, the
344 terminal's own approval routing, Auto-Review verdicts (`tool.gate.decision`),
345 and outbound network decisions when `[network]` auditing is
346 on. It has never held commands or file changes, and
347 turns run by the app or `codewhale serve` write no approvals there. Their
348 approvals are in the session's `approval_receipts.jsonl` and the thread's
349 event log, which is where receipts read them.
350
351 A quiet `audit.log` does not mean nothing ran. It gets an approval line only
352 when the terminal routes an approval request. The engine decides auto-allowed calls itself, so
353 they never become requests; under Full Access almost nothing does. On one
354 developer machine the last `tool.approval.*` line was written on 2026-08-19,
355 the last `tool.approval.auto_approve` line on 2026-06-30, and the writes
356 after that were test runs, which since `244368675b` go to a scratch log. Use
357 a receipt to see what ran.
358
359 ## Review Receipts
360
361 `codewhale review --write-receipt` writes a local JSON receipt for the reviewed
362 diff under the Codewhale state directory (`review-receipts/`) unless
363 `--receipt-path <path>` is provided. This is a pre-push handoff artifact: it
364 records what diff was reviewed and what the review reported, without pushing,
365 tagging, opening a PR, or claiming to replace maintainer review.
366
367 The current receipt includes:
368
369 - `diff_fingerprint`: SHA-256 of the reviewed diff.
370 - `provider` and `model`: the routed review provider/model.
371 - `checks_run`: local checks attached to the receipt when available. Empty
372 means no checks were attached; attached checks must report a passing status.
373 - `findings`: structured issue/suggestion counts and issue locations when the
374 review output is structured.
375 - `unresolved_risk`: a conservative summary derived from unresolved findings.
376 - `review_content_sha256`: SHA-256 of the review text.
377 - `coverage` (PR receipts): the exact base/head and complete-diff
378 fingerprint, ordered per-pass diff fingerprints/file counts, and one
379 response-content hash for every completed pass. Manifest-backed PR receipts
380 use schema version 2 so older readers reject rather than misinterpret them.
381
382 The receipt deliberately does not include the raw diff body. Re-run
383 `codewhale review --write-receipt` after changing the diff; reviewers should
384 compare the `diff_fingerprint` before reusing a receipt in a PR handoff.
385
386 `codewhale review --check-receipt` is the local pre-push gate. It does not call
387 a model; it compares the current diff fingerprint with a supplied receipt
388 (`--receipt-path <path>`) or the latest matching local receipt. The check exits
389 nonzero when the diff no longer matches, the receipt schema is unsupported, the
390 receipt has unresolved risk, or an attached check did not pass.
391
392 By default receipt generation rejects a PR that needs more than one
393 `--max-chars` pass before calling a model. An explicit `--max-passes N` admits
394 at most N complete ordered PR passes; any missing, malformed, reordered or
395 stale pass prevents a receipt. Receipt checking is provider-free and validates
396 the exact stored manifest without authorizing another run. Neither mode
397 fingerprints a truncated prefix. A receipt for
398 `review --base <base-sha> --path <path>` covers only that selected path at the
399 checked-out revision; validate it with the same base, path, and input limit.
400 It does not cover the rest of a pull request or prove that separately reviewed
401 changes work together. With `--base`, the reviewer also reads the
402 `base..HEAD` commit messages (merges excluded, capped at 16,000 characters) as
403 the author's stated intent; the receipt fingerprints the diff, not those
404 messages.
405
406 `docs/RELEASE_CHECKLIST.md` uses one receipt per crate or path as the
407 regression pass before a release candidate: run `--write-receipt` per slice,
408 then `--check-receipt`; a receipt with unresolved risk blocks the candidate
409 until a maintainer reads the findings. The pass is a maintainer action, because
410 `--write-receipt` calls a model; the release candidate's provider-free
411 Regression report job only lists unstated behaviour changes to start from.
412
413 ## Builder Rules
414
415 The builder is deterministic and conservative:
416
417 1. A thread receipt loads the thread, its turns, the items each turn lists
418 (plus items that name the turn but are not listed yet, for a live turn),
419 and the thread's `approval.*` events. A turn id from another thread is
420 rejected.
421 2. A session receipt reads `tool_use`/`tool_result` pairs from the
422 transcript and replays the approval log; a log that does not replay is
423 reported, not half-used.
424 3. Approvals attach to their call by tool call id. One with no matching call
425 is listed on its own.
426 4. File changes come from a tool's structured mutation record (the applied
427 diff) when saved, otherwise from the call's own input (an edit's
428 replacement text, a patch's hunks). A failed call changed nothing and
429 carries no counts.
430 5. Nothing is derived from model prose. Two fixed kinds of text Codewhale
431 itself writes are read: the shell's status lines (for an exit code) and
432 its refusal text (for a call it blocked); see "Blocked before it ran".
433
433 lines MARKDOWN