Repository navigation
Render turns that have content: fix export's codex defect, add a content fallback, correct the MCP type enum - #184
Conversation
… content when raw_json recognises nothing Markdown export read an assistant turn's prose and its calls out of the turn's raw_json, switching on Claude Code's three content-block types, and `exportAssistantTurn` returned as soon as that parse *succeeded*. Codex's raw_json parses perfectly and carries none of those three types, so all 7,035 codex assistant turns in the author's archive exported with an empty body — and a fallback keyed on parse failure could never fire for them, because nothing failed. This is the export half of #179, which fixed the same two defects in the conversation view. Same shape: - prose from raw_json when a block type the exporter knows appeared, otherwise from the `content` column. "Knows" includes `tool_use`, which is why a claude-code tool-only turn does not print its stored "[Tool: Bash]" summary above the call it summarises. - calls from tool_uses via db.SessionToolCallsByTurn, which every adapter fills identically. A codex turn's calls are on transcript lines of their own and are not in that turn's raw_json at all. `internal/export` now imports `internal/db` for the db.ToolCall type. That is a new edge, and worth it: the alternative is a duplicate struct plus a conversion at all four call sites, and db depends on nothing but pkg/models so there is no cycle. The exporter still takes no database handle — callers pass the grouping in with WithToolCalls, and the conversation view hands over the one it already holds. Also renders tool arguments that are not a JSON object as the text they are, previewed at 50 lines. 26,552 of codex's 33,294 calls store exactly that, because custom_tool_call carries a plain-text body: dropping it, which returning early used to do, answers "a command ran" without answering which one. The tool_use tests in richcontent_test.go now seed the call where the exporter reads it, keeping the tool_use block in raw_json too, so they also pin that one call is not written twice.
…ontent Both switches in the conversation view and the one in markdown export had a case for user, assistant and tool_result and no default, so a turn of any other type was dropped without a word. That accounted for the archive's 51,794 nanoclaw `system` turns — each a 1,000+ character agent prompt (max 6,433, 424 distinct) explaining why the session did anything. A nanoclaw conversation read as though the agent started acting for no reason, and copying one into a bug report lost the same turns for a second reason. docs/plans/2026-02-13-ccvault-design.md:42 declared the turn types as user, assistant, tool_use, tool_result and progress. Measured on the author's archive, tool_use and tool_result have zero rows — declared, and no source emits them — while `system` and `attachment` are present in volume and were never declared. The renderers were written from the declaration and nothing reconciled the two. (tool_use/tool_result handling is left alone; an empty table today is not an argument that nothing will ever write to it.) The fix keys on whether the turn carries content, not on its type name. That splits the archive cleanly where type names do not: nanoclaw system 51,834 turns 51,794 with content claude-code progress 131,581 turns 0 with content claude-code attachment 26,971 turns 0 with content claude-code system 6,396 turns 0 with content nanoclaw progress 4,051 turns 0 with content So the rule surfaces exactly the substantive turns and leaves ~169,000 machinery turns hidden, with nobody having to classify type names — and a future source's new type renders if it carries text and stays quiet if it doesn't, without anyone coming back here to add a case. #179's lesson was that a type-name switch is the bug. Unhandled types are labelled with the type as stored ("[SYSTEM]", "### ⚙️ system") rather than a prettier name: a reader needs to know what produced the text, and this code does not know enough about a type it has no renderer for to rename it. copyToClipboard's text building moves into plainTextTranscript so the clipboard's copy of the rule can be asserted without writing to the machine's clipboard during a test run. TestExportTurn_UnknownTypeIsSkipped is replaced rather than edited: it asserted that a `system` turn with content produced no output at all, which is the defect, stated as a requirement. Its successor keeps the part that was right — an unknown type must not be exported under a known type's header — and contentfallback_test.go pins both directions of the new rule.
get_turns advertised Enum: ["user", "assistant", "tool_result"] on its
`type` parameter. The filter behind it is `AND type = ?` and accepts any
string, so the enum was wrong in both directions at once:
- `tool_result` has no rows in the author's 50,000-session archive. It
was declared in docs/plans/2026-02-13-ccvault-design.md:42 and no
source emits it, so the enum offered a filter that can only ever
return nothing.
- `system` (58,230 rows) and `attachment` (26,971) went unadvertised,
while working. type:"system" returns 532 turns with full content on a
real session — verified against the live archive.
And it contradicted get_session_summary sitting beside it, which already
reports every type a session holds with counts:
{"assistant":3945,"progress":337,"system":532,"user":2220}. An agent
reading both got a list of three from one tool and a list of four from
the other.
Dropped the constraint rather than relisting the types. A list of type
names is what #179 and the content fallback just removed from the
renderers, and reintroducing one here puts it in the hardest place to
keep current: a schema an agent reads and believes. An adapter can add a
type at any time, and an enum naming types a *given* archive may not
contain is its own kind of wrong — the author's archive has no
tool_result rows, so even a freshly-measured list would have been false
for somebody. get_session_summary answers the question properly, per
session and from the rows, so the description now says so.
No behaviour change to the filter; this is the advertisement catching up
with it. The test asserting a type the enum never named still filters
correctly is a regression guard for the other direction, so nobody
"fixes" this by adding validation against a relisted enum.
|
No actionable comments were generated in the recent review. WalkthroughMarkdown exports now include stored per-turn tool calls and assistant prose. Markdown export and TUI rendering also retain nonempty content from otherwise-unhandled turn types. The MCP ChangesTurn rendering and export
Estimated code review effort: 3 (Moderate) | ~25 minutes Change: Bug fix Sequence Diagram(s)sequenceDiagram
participant MCP as MCP server
participant SessionDB
participant MarkdownExporter
MCP->>SessionDB: SessionToolCallsByTurn(sessionID)
SessionDB-->>MCP: Calls grouped by turn
MCP->>MarkdownExporter: Export turns with WithToolCalls(calls)
MarkdownExporter-->>MCP: Markdown
Possibly related PRs
Suggested reviewers: Merge Risk:
|
… 315,985 rows already stored, and make the renderers that were waiting on the type actually work (#186) * parser: retag user lines that carry only tool_result blocks Claude Code writes a tool result as a role:"user" message on a line of type "user" — the API shape, where a result is what the caller hands back to the model. pkg/parser copied that type verbatim, so every tool result in the author's archive is filed as a message the person typed: 315,985 of them across 52,375 sessions, while `tool_result` — the type the TUI, the exporter and the MCP schema were all written for — had zero rows (#185). A `user` line whose content blocks are all tool_result is now stored as type tool_result. Mixed content stays `user`: a line carrying prose beside a result is a user message with a result attached, and retagging it would file the person's words under a machine's answer. The nested content shape is read as well. UserContentBlock.Content is typed as a string, so a tool_result whose content is an array of blocks made the whole block array fail to unmarshal — that failure is 145,648 contentless turns, and it took any prose on the same line down with it. User blocks are now read through a local type whose Content is raw. turns.content gets a bounded preview, not the body. The full text is already in turns.raw_json and in tool_uses.result_content under #28's policy with an FTS index of its own; measured on the archive, storing the bodies here too would add 453 MB to a turns.content holding 296 MB and duplicate all of it into turns_fts. Image-bearing results get no preview at all, by the same shape rule #28 uses. The preview's truncation moves from bytes to runes. A byte cut can land inside a multi-byte rune — demonstrated by a failing test that produced invalid UTF-8 — and migration 017 has to reproduce this string in SQL, where substr() counts characters. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * export, tui: render a tool result from the shape the transcripts write Both renderers read $.toolUseId and $.data at the top level of a turn's raw_json. No source in this repo produces that shape — it comes from docs/plans/2026-02-13-ccvault-design.md, and the renderers were written from the declaration. Claude Code puts a result's body at $.message.content[].content. So the type being wrong was only half of #185. Retagging those turns without this would have made them render *worse*: in export, a heading with nothing under it; in the TUI, nothing at all, because renderConversation skips a tool_result whose render comes out empty. A test demonstrates each before the fix. The Claude Code shape is read first, the declared shape second, and the turn's stored preview last — the preview is all a turn has when its oversized line was replaced by a placeholder. Image payloads are dropped and their captions kept: a view is not an index, so the partial #28 refuses to store is the right thing to show, where 1-2 MB of base64 answers nothing. The TUI's 1,000-character cut now counts characters and runs ToValidUTF8, for the reason formatToolUseBlock already does: tool output is bytes nobody validated and a byte cut leaves the terminal a fragment to draw. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * db, show: migration 017 retags the stored tool results The write-path fix cannot reach these rows. The mislabeled turns run from 2026-02 to now and the oldest transcript left on disk is dated Sep 25 — ~78% of them (114,389, May to August) have no source file to resync from. raw_json is present on 100% of them and is the only surviving record, which is the fidelity purpose that column exists for. Two statements and a verdict. The first recovers the result text for the rows that stored none, as the same bounded preview pkg/parser writes; the second flips the type, which costs nothing in turns_fts because turns_au fires on content and timestamp only. Keeping them apart is deliberate: naming content in a SET clause fires the trigger for every matched row whether the value changes or not. Expressed in SQLite's JSON1 without strain, with one restriction worth naming: the content fill reads $.message.content[0] rather than joining over N blocks, because SQLite cannot correlate a json_each into the updated table from inside a FROM subquery. Every one of the archive's 315,985 all-tool_result user turns carries exactly one block, and statement 2 retags whatever shape appears, so the restriction costs nothing measurable and a resync covers the rest. Idempotent: statement 1 keys on type = 'user', which statement 2 has already cleared, so a second run writes zero rows. Verified on a scratch copy of a real nanoclaw session — two runs, zero rows differing, and the migrated rows byte-identical to a fresh parse of the same transcript. TestMigration017AgreesWithTheParser is what keeps the two implementations of one rule from drifting. It earns its place on the truncation: SQLite's substr() counts characters and a Go slice counts bytes, and 67,845 of the 145,006 rows this fills carry a non-ASCII character inside the first 200. The negative controls are rows that must not move: the mixed-content turn, the 4,557 with no raw_json, the oversized-line placeholders, the pasted screenshots and PDFs, and every assistant turn. `ccvault show` gets #184's missing default in the same change, because the retag is what made its absence cost something new. Its switch listed user and assistant and had nothing else, so on this branch the 41 tool results of a real nanoclaw session went from 38 blank [USER] blocks to not being printed at all. The rule is the one the exporter and the conversation view already use — show a turn that carries text, label it with the type as stored — which also recovers the 51,794 nanoclaw `system` turns show has been dropping all along. Not run against ~/.ccvault/ccvault.db. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * export, tui: record that the tool-result defaults were decided Issue #185 asks for this and it is the only part with no code in it. includeToolResults was written true when `tool_result` had no rows, so it governed nothing; the retag makes it govern every export, and a default nobody chose is not an answer. It stays true, and the measurement is in the comment: four real sessions export at 1.33x, 1.35x, 2.91x and 3.11x their old size, each result previewed at 100 lines with image payloads dropped by shape. What settles it is that neither default regresses — with results off the export is still better than before, because the blank User headers are gone, and one real nanoclaw session came out smaller than it used to be. So --tool-results=false gives a reader the old volume and costs them nothing, while a default of false would leave whoever does not know the flag exists still reading the bug. The TUI shows them with no toggle, for the same reason and with its own numbers. A keybinding to hide them is human-facing surface nobody has asked for; the cap stays at the 1,000 characters it already was. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> * export: make a code fence outlast the payload inside it Every fence in markdown.go was exactly three backticks and the bodies are tool payloads. Measured on the author's archive: 10,514 of the retagged tool results carry a triple-backtick fence of their own and 1,152 of the tool inputs do — a Read of a markdown file, a Bash cat of a README. An inner fence closes the block early. The rest of the result renders as markdown and the real closing fence opens a new block that swallows every turn after it. CommonMark's answer is to let the opening fence be longer than anything inside, which writeFenced now does. Reachable before this branch for the tool inputs; the retag is what made it reachable for results, which is why it is fixed here. One function rather than the fix at each of six call sites: a fence somebody adds later is the one that gets forgotten. Verified on a real claude-code session with six fenced results: longest fence emitted is four backticks, six of them, and no block is left open at end of file. Found by CodeRabbit on #186. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Follow-on to #179, which fixed the conversation view's two rendering defects. The same two are in markdown export, and the measurement that motivated #179 turned up a third thing worth fixing in MCP. No issue is open for any of it; the background is below.
The investigation
docs/plans/2026-02-13-ccvault-design.md:42declared the turn types asuser, assistant, tool_use, tool_result, progress. That was a guess at Claude Code's wire format and nothing ever reconciled it. Measured on a real ~50,000-session archive:system/ nanoclawprogress/ claude-codeattachment/ claude-codesystem/ claude-codeprogress/ nanoclawtool_useandtool_resulthave zero rows — declared, and no source emits them.systemandattachmentare present in volume and were never declared. Both TUI switches and export's switch were written from the declaration, with nodefault, so every undeclared type was dropped silently.The useful finding is that
turns.contentalready separates signal from machinery. Rendering on whether a turn has content surfaces exactly the 51,794 substantive turns and leaves ~169,000 machinery turns hidden, without anybody classifying type names.tool_use/tool_resulthandling is left alone. An empty table today is not an argument that nothing will ever write to it.Three changes, three commits
1.
fix(export)— export a turn's calls fromtool_uses, prose fromcontentwhenraw_jsonrecognises nothing.exportAssistantRichContentswitched on Claude Code's three content-block types andexportAssistantTurnreturned as soon as that parse succeeded. Codex'sraw_jsonparses perfectly and carries none of those types, so all 7,035 codex assistant turns exported with empty bodies — and a fallback keyed on parse failure could never fire, because nothing failed.Same shape #179 proved in the TUI: prose from
raw_jsonwhen a block type the exporter knows appeared (includingtool_use, which is why a claude-code tool-only turn doesn't print its stored[Tool: Bash]summary above the call it summarises), otherwise fromcontent; calls fromtool_usesvia the existingdb.SessionToolCallsByTurn.Also renders tool arguments that aren't a JSON object as the text they are. 26,552 of codex's 33,294 calls store exactly that, because
custom_tool_callcarries a plain-text body.internal/exportnow importsinternal/dbfor thedb.ToolCalltype. That's a new edge and worth stating: the alternative is a duplicate struct plus a conversion at all four call sites, andinternal/dbdepends on nothing butpkg/models, so there's no cycle. The exporter still takes no database handle — callers pass the grouping in withWithToolCalls, and the conversation view hands over the one it already holds.2.
fix(tui,export)— a content fallback as thedefaultin both renderers.A turn of an unhandled type renders its
contentif it has any and is skipped if not. This is what recovers the 51,794 nanoclawsystemturns, each a 1,000+ character agent prompt (max 6,433, 424 distinct) explaining why the session did anything.Nothing special-cases
system. The point is the rule: a future source's new type renders if it carries text and stays quiet if it doesn't, without anyone coming back to add a case. Unhandled types are labelled with the type as stored ([SYSTEM],### ⚙️ system) rather than a prettier name — a reader needs to know what produced the text, and this code doesn't know enough about a type it has no renderer for to rename it.copyToClipboard's text building moves intoplainTextTranscriptso the clipboard's copy of the rule can be asserted without writing to the machine's clipboard during a test run.3.
fix(mcp)— stop advertising a turn-type enum that contradicts the filter.get_turnsadvertisedEnum: ["user", "assistant", "tool_result"]. The filter isAND type = ?and accepts any string, so the enum was wrong in both directions:tool_resulthas no rows anywhere, so it offered a filter that can only return nothing;system(58,230 rows) andattachment(26,971) went unadvertised while working. It also contradictedget_session_summarybeside it, which already reports every type with counts.Dropped the constraint rather than relisting. A list of type names is what #179 and change 2 just removed from the renderers, and reintroducing one here puts it in the hardest place to keep current: a schema an agent reads and believes. An enum naming types a given archive may not contain is its own kind of wrong — this archive has no
tool_resultrows, so even a freshly-measured list would be false for somebody. The description now points atget_session_summary, which answers it per session and from the rows.No behaviour change to the filter; the advertisement is catching up with it.
Before / after, on real sessions
Built from source,
--data-dirinto a scratch directory holding three real transcripts: one codex rollout from~/.codex/sessions, one nanoclaw session with a scheduled-tasksystemturn, one claude-code session with nineattachmentturns. The live archive was never written to.Codex session
019cddae-01fe-77c0-a805-b273abd1b103:Nanoclaw session
372b0343-3b12-4f1c-a013-f73a65bf69b6— before, the conversation opens with the assistant thinking out of nowhere; after, it opens with the prompt that caused it:Claude-code session
01b3f698-626c-4673-a65f-60e3e3551a3e(18 assistant turns, 9 calls, 9attachmentturns with empty content) — the two exports are byte-identical, 396 lines each, zero⚙️headers. Machinery stays hidden, and moving claude-code's calls fromraw_jsontotool_useschanges nothing about its output.MCP, over stdio:
"type": { "type": "string", - "description": "Filter by turn type", - "enum": ["user", "assistant", "tool_result"] + "description": "Filter by turn type, e.g. \"user\", \"assistant\", \"system\". Any type + the archive stores is accepted; which types a session actually holds, with counts, + comes from get_session_summary." }get_turnswithtype:"system"on the real nanoclaw session returnstotal_turns: 1with the full prompt, andget_session_summarybeside it reports{"assistant": 10, "system": 1, "user": 5}— the two now agree.Non-vacuity
Three vacuous tests were found and deleted in this repo last month, so each decisive assertion was demonstrated failing before the behaviour existed:
mainwith the real empty body between header and---.[PROGRESS] 19:25:27\n\n\n[ATTACHMENT] ...and### ⚙️ progressheaders with empty bodies.get_turnstype filter (2 subtests) fails when the filter is gated back to the old enum's three names: bothsystemandhandoffreturn 2 turns instead of 1.get_sessionmarkdown over a real database) fails againstmain's exporter, which is the point — a formatter can read calls out of a grouping and still produce an empty transcript if nobody hands it one.Fixtures are checked against real shapes: codex's
payload.content[].output_textunder nomessageobject, copied from a real rollout; nanoclaw'ssystemturn whoseraw_jsonstill says"type":"user"because the retag happens above the parser; realhook_progress/deferred_tools_delta/turn_durationpayloads for the machinery turns.TestExportTurn_UnknownTypeIsSkippedwas replaced, not edited: it asserted that asystemturn with content produced no output at all, which is the defect stated as a requirement. Its successor keeps the part that was right — an unknown type must not be exported under a known type's header — and adds at.Fatalfguard so it can't go vacuous. Thetool_usetests inrichcontent_test.gonow seed the call where the exporter reads it while keeping thetool_useblock inraw_json, so they also pin that one call isn't written twice.Verification
Coverage 73.6% → 73.9% (+0.3). All 14 pre-commit hooks ran on each of the three commits (12 passed, 2 skipped as not-applicable).
Does not touch
internal/db/db.go, so it should not conflict with #183.Open in [code]smith · Need help on this PR? Tag
@codesmith-botwith what you need.Summary by CodeRabbit