Skip to content

fix(ai-vault): read legacy OpenCode JSON message parts - #50643

Closed
Afloat16 wants to merge 6 commits into
stablyai:mainfrom
Afloat16:afloat16/orca50-20261127-opencode-json-message-parts
Closed

Afloat16 wants to merge 6 commits into
stablyai:mainfrom
Afloat16:afloat16/orca50-20261127-opencode-json-message-parts

Conversation

@Afloat16

@Afloat16 Afloat16 commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Read the message files that older OpenCode sessions actually use, so saved conversations regain their prompts and replies in History and conversation search, and refresh when separate parts change.

What Changed

  • Load separately stored message parts when inline content is absent, using the producer’s part-ID order.
  • Convert text, reasoning and tool parts into the existing transcript shapes; retain older records that already contain inline content.
  • Preserve consecutive text/reasoning runs around tool calls/results when reading legacy fallback parts, while first-user prompt capture and previews still use the complete decoded message.
  • Reuse the existing JSON read, cancellation and WSL handling, and reject message IDs that could escape the expected part directory.
  • Apply one-time repairs only to OpenCode JSON parse rows and search cursors. SQLite-backed OpenCode sessions and other agents retain their existing entries.
  • Track a separate signature of message/part paths, sizes, mtimes and ctimes. Keep the parent session file’s real mtime, size and read offsets.
  • Persist and compare that signature across History, Search, worker snapshots and failed-version retries. Add nullable columns within locked migrations, retaining existing cache data.
  • Select part dependencies from the actual message role, inline content and safe ID. Preserve inline sessions without consulting unused part directories.
  • Keep dependent message/part I/O failures retryable without publishing a complete replacement or permanently exhausting the Search retry budget. Successfully read malformed JSON records retain their existing skip policy.

Why

OpenCode’s legacy MessageV2 JSON format stores message metadata under storage/message/<sessionId> and content under storage/part/<messageId>. Orca still discovers these JSON sessions, but the parser looked only for inline content. This produces empty prompts and transcripts. Existing parse-cache rows and current search cursors can preserve that omission even after the reader is corrected. Later writes to separate message or part files can also leave the parent session JSON unchanged, so retained JSON candidates need their own dependency revision.

Linked Issue

Fixes #50642

Visual Proof

N/A

No graphical layout or interaction component changes. The following before/after results come from the affected production operation with the same fixture input.

Before After
firstUserPrompt is absent and separately stored bodies are omitted. Previously cached empty previews and current search cursors survive a parser-only fix. The prompt is “Inspect the build failure.\nKeep the command output.” Replies, reasoning, tool calls/results and the inline control are emitted. Only affected JSON cache rows/cursors are invalidated once; SQLite-backed sessions and other agents remain intact.
An assistant part changes from draftquery to same-length finalquery after both caches restart, while the parent stat stays unchanged. History remains stale and conversation Search misses the new text. History shows finalquery and Search finds it. A later dependent-content revision receives a fresh retry budget and becomes searchable after previous read failures.

Testing

  • I manually tested these changes locally through the production-entry reproductions described below
  • Automated tests added/updated, or explained why not below
  • Every added test fails without this change and avoids the test anti-patterns

Persisted transcript, import-parser and search-index data integrity. The fixture uses real files and SQLite rather than replacing internal parser/storage chains.

The original two regression tests pass. The producer-shaped filesystem fixture failed on the original parser. With that reader corrected, a separate baseline check reproduced the stale real-SQLite parse row until its repair was added. The search migration regression failed with the JSON cursor still at 100; the fix sets it to the existing partial-file sentinel -1 while SQLite/Claude controls stay at 100. A later cursor of 200 survives reopening, proving the repair is one-time.

The dependency-freshness follow-up passes 6 targeted tests across 5 files, including a same-length assistant-part rewrite after both persistent caches restart and recovery after held-out failures. Its previous-head baseline fails the preview, Search and retry assertions. Two additional validation-only old-schema probes preserve indexed/parse rows and prove rollback after a real SQLite trigger rejects migration metadata. The actual migration functions also pass six concurrent two-connection rounds, adding each column once. All seven blocking-I/O ratchets pass without an allowance increase; changed-code quality reports zero findings across 147 integrated paths.

The I/O recovery follow-up passes 8 targeted tests across 6 files. The existing real scan/Search regression now injects three consecutive part-read refusals at the gated filesystem boundary, closes both persistent stores, and verifies that Search recovers before History reads again, with the part mtime, ctime and size unchanged. A persistently malformed part remains skippable and the complete readable preview can still be reused. This extended case fails on 89f916f0; its existing inline/safe-message-ID case continues to pass. Two additional validation-only cases preserve previously indexed content during failures and check empty-inline versus required-fallback recovery. All seven blocking ratchets pass unchanged; changed-code quality has zero findings across 150 integrated paths.

The emission-order follow-up passes 6 targeted tests across 5 files. The real file-backed parser case and explicitly ordered emitter regression fail on exact 92ef85ee sources because the final answer precedes its tool result. With the correction, the emitted sequence is reasoning → tool call → tool result → final text; the full first-user prompt and whole-message preview assertions still pass. The default-mode control verifies unchanged output. Only legacy OpenCode fallback parts opt in; inline content and other-agent callers retain their existing emission behavior.

Each emitted text run retains the existing 262144 UTF-16 code-unit cap, surrogate-safe truncation and textTruncated flag. This is a per-run limit, not a byte limit or an aggregate cap for the original message; splitting runs can retain more text overall, and a truncated early run does not suppress later tool or final-text runs.

Reproduce the focused tests with:

pnpm test src/main/ai-vault/scanners/opencode/session-scanner-opencode-json-parts.test.ts src/main/ai-vault/transcripts/session-transcript-message-content.test.ts src/main/ai-vault/scanners/opencode/session-scanner-opencode-freshness.test.ts src/main/ai-vault-search/indexing/session-search-opencode-json-read-errors.test.ts src/main/ai-vault-search/storage/session-search-opencode-parts-repair.test.ts src/main/ai-vault/parse-cache/session-parse-cache-persistence.test.ts src/main/ai-vault-search/indexing/session-search-unchanged-reread.test.ts --maxWorkers=2

Locally executed through the repository’s test-runtime runner on Linux with Node 24.22.3. macOS, Windows and remote SSH execution are not claimed.

Final integrated validation: 32 focused regression tests in 22 files passed, including the unchanged archive-write failure case that had timed out under earlier heavy concurrent checking. The Drive performance contract passed separately (1 file/1 test). Changed-code quality passed with zero new findings across 129 changed paths; final touched-file formatting and git diff --check passed. Node typechecking passed for 17,026 files and web typechecking for 16,094 files using the repository-supported Bun compiler with one worker. These are aggregate validation results for the prepared contributions, not per-PR test counts.

Initial local check:changed attempts stopped during workspace-package build because this environment rejected the tsx CLI IPC socket (listen EPERM); a later attempt hit ENOSPC when pnpm automatically rebuilt native dependencies. The default tsrs typechecker was also terminated with SIGKILL; the supported Bun typechecking route completed successfully. No complete local gate pass is claimed.

Current candidate 51431a17d47ed1e590cb04fdd6109a4f5d9f39cc passed the complete required pnpm check:changed gate in exact-source fork CI. The job checked the candidate against 9890ea181c0f9ae59fb82da64c4a6fbc0504a817, verified both commit IDs, and confirmed that validation left tracked sources unchanged.

Performance

The legacy JSON reader now performs the part-file reads required to recover omitted content; inline messages skip those reads. Sorting follows the producer’s storage-key order. Marker-gated cache/search repairs cause one reread of affected JSON sessions, preserving SQLite-backed sessions and unrelated agents.

Discovery lists and stats message/part files for each retained legacy JSON candidate after SQLite duplicate filtering. Each unique retained session is observed once per discovery, with at most four sessions observed concurrently. To select only dependencies used by the parser, discovery also reads and decodes every retained message JSON, inspecting its role, nullish inline content and safe message ID. This includes inline message bodies and adds content I/O and JSON decoding on each discovery pass. Part bodies are read by the transcript parser rather than the fingerprint observer. Unchanged signatures remain eligible for History and Search reuse; candidate ordering and retention still use the real parent-file stat.

Risk

Level: Medium

The sensitive path is historical JSON storage while part files are missing or being written. Existing guarded file reads and cancellation behavior are reused, and older inline content remains authoritative. Repair markers touch derived cache/search state only; original session and part files are unchanged. A revert restores the old reader but does not reinstate invalidated cache rows or previous cursors; normal scans rebuild derived data.

The optional signature columns are added without rebuilding either cache. One writer transaction protects the parse-cache schema and scope-version update; the Search column migration uses its existing writer lock. Failed migration writes roll back, and simultaneous openers check columns after acquiring that lock. Unreadable required dependency observations are reported rather than accepted as a fresh revision. Dependent message/part I/O failures leave whole reads retryable without publishing a complete replacement. Malformed JSON records retain the existing skip policy. Message content and safe IDs decide whether part directories are dependencies at all.

AI Disclosure

Core contribution owner: @Afloat16. Required tooling disclosure: GPT-6 Astra Pro was used for implementation and review.

Review

Reviewed the actual MessageV2 producer, part ordering, content conversion and persisted upgrade behavior. Existing path joining and host/WSL restrictions remain in use; message IDs with separators are rejected. SQLite-backed OpenCode parsing, other agents, SSH routing and mobile wire shapes are unchanged. No new polling or graphical layout code is added. Dependency observation is limited to retained legacy JSON candidates; message JSON is read to classify actual fallback dependencies, including when message IDs differ from filenames.

Agent skill upstream boundary

  • Not applicable: this change copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments or documentation.

Notes

MessageV2.parts(messageID) reads Storage.list([part, messageID]) and sorts by part ID; get() reads metadata separately. Reviewed related first-prompt, native-chat, WSL and cache-version work; those changes did not load these legacy JSON message bodies.

Primary references:

Checklist

  • This PR is small and focused
  • I explained what changed and why, including the mechanism and before/after result
  • I stated the risk and how to back it out
  • Before/after data evidence is included, with N/A and a reason for graphical proof
  • Self-reviewed for correctness, security and performance
  • Cross-platform, SSH/remote and path/shortcut impact considered
  • The required pnpm check:changed gate passed for the current candidate; exact-source CI is linked in Testing.

@coderabbitai

coderabbitai Bot commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • Resume reviews
  • Trigger review

No actionable comments were generated in the recent review.

Walkthrough

The OpenCode parser now reads separately stored message parts when message records lack inline content. It orders message and part records and expands tool records into transcript entries. Dependency signatures track revisions of separately stored transcript content in parse-cache and search records. One-time repairs invalidate affected OpenCode JSON cache rows and search cursors. Tests cover parsing, cache behavior, freshness, read failures, and cursor repair.

Severity of issue fixed: Medium

Merge Risk: Moderate · previous review 92ef8

The change restores prompts and transcripts for legacy OpenCode JSON sessions, and part-read failures now stay retryable instead of being cached as complete. Two issues remain. Final text can appear before tool results in transcripts. Every History and Search scan now reads all message files for each legacy session, which adds I/O that the repository's zero-performance-regression rule does not allow. Measure or reduce that scan cost before merging.

Pre-merge checks: Passed 3 · Failed 1

Failed Failed checks: 1 warning

Check name Status Explanation Resolution
Description check Warning The description follows the template, and most sections are filled in with substantive detail. ELI5, What Changed, Why, Linked Issue (Fixes #50642), Visual Proof (N/A with reason), Testing, Performanc… 1. Reconcile the candidate commit referenced in Testing (92ef85e) with the candidate in the PR objectives (e6fa4c6), and link only the CI run for the final head. 2. Shorten t…
Passed Passed checks: 3 passed

Check name Status Explanation
Title check Passed The title "fix(ai-vault): read legacy OpenCode JSON message parts" matches the main change. The changeset adds loading of separately stored OpenCode message and part files when inline content is absen…
Linked Issues check Passed The only active direct target is #50642. Its coding requirements are: (1) read separately stored OpenCode JSON parts from storage/part/ when inline content is absent; (2) order parts by par…
Out of Scope Changes check Passed All changed paths in the raw summary relate to #50642. The parser change (part reading, ordering, tool expansion, ID guard) implements requirements 1 to 4. The parse-cache and search-schema repairs im…
Full details: Title check

Explanation

The title "fix(ai-vault): read legacy OpenCode JSON message parts" matches the main change. The changeset adds loading of separately stored OpenCode message and part files when inline content is absent. The title is specific and concise, and it follows a conventional commit form. The broader dependency-signature, cache, and search repair work is not named, but the title does not need to cover every detail.

Full details: Linked Issues check

Explanation

The only active direct target is #50642. Its coding requirements are: (1) read separately stored OpenCode JSON parts from storage/part/<messageId> when inline content is absent; (2) order parts by part filename (producer part-ID order); (3) convert text, reasoning and tool parts into existing transcript shapes; (4) keep inline content as the control; (5) apply one-time repairs only to OpenCode JSON parse-cache rows and search cursors, leaving SQLite-backed sessions and other agents intact; (6) add automated regression tests.

Evidence at the reviewed head 92ef85e:

  • session-scanner-opencode-parser.ts: consumeOpenCodeMessages uses message.content ?? readOpenCodeMessageParts(...), so inline content takes precedence. readOpenCodeMessageParts reads storage/part/<messageId> via readOpenCodeJsonDirectory, sorts entries by name, and expands tool parts into tool_use and tool_result records. Message IDs with '/', '', NUL, '.', '..' or empty values return no parts.
  • Messages are ordered by creation time, with filename as tie-breaker (readOpenCodeMessagesInOrder).
  • session-scanner-opencode-dependencies.ts: openCodeDependencySignature observes message and part .json files for user or assistant messages without content, using the same ID guard. This supports the dependency-freshness requirement in the PR summary.

The parse-cache and search-cursor repairs (session-search-schema.ts filesRepairSql with *.json glob, parse-cache database repair) are described in the PR and the raw summary. I did not read those hunks at head in this pass. Their behavior rests on the diff summary and the author-reported test results. I did not run the tests. The head changed since the previous reviewed head 89f916f, and the incremental diff was not available, so that interval is not independently verified. The parser and dependency code evidence is consistent with the previous PASS.

Full details: Out of Scope Changes check

Explanation

All changed paths in the raw summary relate to #50642. The parser change (part reading, ordering, tool expansion, ID guard) implements requirements 1 to 4. The parse-cache and search-schema repairs implement the one-time, OpenCode JSON-only invalidation in requirement 5. The dependency signature (session-scanner-opencode-dependencies.ts, file-record and worker plumbing, read-decision changes) supports correct freshness for separately stored part edits, which the issue's expected behavior needs. The signature is undefined for non-OpenCode and SQLite-backed sessions. Test files and the test fixture helper support the required regression coverage. The additive, transactional column migrations are needed to persist the signature. No unrelated feature, SSH routing, or mobile wire change appears in the summary. The PR description does not describe the dependency-signature mechanism in the Why section, but this is a documentation gap, not unrelated work. The incremental diff since 89f916f was not verified in this pass.

Full details: Description check

Explanation

The description follows the template, and most sections are filled in with substantive detail. ELI5, What Changed, Why, Linked Issue (Fixes #50642), Visual Proof (N/A with reason), Testing, Performance, Risk (Level: Medium, with a rollback explanation), and AI Disclosure are all present. The description still fails for two reasons. First, the Testing section is very long and mixes local runs, aggregate validation counts, and CI links with unverifiable claims, which makes it hard to confirm what was actually verified. Second, the Testing checkboxes and the Performance section need to be verified against the actual change. The raw summary shows the discovery path now reads and decodes every retained message JSON, which the Performance section discloses. Two items are missing or unclear: the 'Review' section and the 'Agent skill upstream boundary' checkbox are present, but the template's 'Notes' and 'Checklist' items are partly filled. The description also refers to commit IDs and a CI run that differ from the PR objectives (candidate 92ef85e... in the description versus e6fa4c6... in the objectives), so the reviewer cannot tell which candidate was tested.

Resolution

  1. Reconcile the candidate commit referenced in Testing (92ef85e) with the candidate in the PR objectives (e6fa4c6), and link only the CI run for the final head. 2. Shorten the Testing section to clear, reproducible steps: the focused test command, the platforms tested (Linux, Node 24.22.3), and the result of each step. Move the aggregate validation counts and the local tooling failures to a separate note. 3. Confirm the Testing checkboxes: the description checks the 'every added test fails without this change' box, but the baseline results are described only partly for some tests. 4. Fill in the 'Notes' section with concrete items rather than the template checklist sentence, or remove the template sentence. 5. Give the Performance section a single clear summary line that states the added I/O cost for discovery, since the template asks for one line at the top of the section.
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: eee8d491-cc0b-4e48-ba80-e21668583ecc
Commits

Reviewing files that changed from the base of the PR and between 89f916f and 92ef85e.

Files selected for processing: 5

  • src/main/ai-vault-search/indexing/session-search-index-consumer.ts
  • src/main/ai-vault-search/indexing/session-search-opencode-json-read-errors.test.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts
  • src/main/ai-vault/transcripts/session-transcript-consumers.ts
  • src/main/ai-vault/transcripts/session-transcript-reader.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: bbcf3a51-5d97-46d5-8540-fcc7ee09750f
Commits

Reviewing files that changed from the base of the PR and between 2bd1b46 and 12ba475.

Files selected for processing: 6

  • src/main/ai-vault-search/storage/session-search-opencode-parts-repair.test.ts
  • src/main/ai-vault-search/storage/session-search-schema.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-database.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-previous-row.test-fixture.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-json-parts.test.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 4ae63dfe-4806-480b-92d0-eb810e4c8aa0
Commits

Reviewing files that changed from the base of the PR and between 12ba475 and 2c86f32.

Files selected for processing: 19

  • src/main/ai-vault-search/indexing/session-search-index-consumer.ts
  • src/main/ai-vault-search/indexing/session-search-read-decision.ts
  • src/main/ai-vault-search/storage/session-search-file-records.ts
  • src/main/ai-vault-search/storage/session-search-schema.ts
  • src/main/ai-vault-search/storage/session-search-store-types.ts
  • src/main/ai-vault-search/storage/session-search-store.ts
  • src/main/ai-vault-search/worker/session-search-cursor-snapshot.ts
  • src/main/ai-vault-search/worker/session-search-worker-entry.ts
  • src/main/ai-vault-search/worker/session-search-worker-protocol.ts
  • src/main/ai-vault-search/worker/session-search-worker-store-base.ts
  • src/main/ai-vault-search/worker/session-search-worker-store.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-database.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-schema.ts
  • src/main/ai-vault/parse-cache/session-parse-cache-store.ts
  • src/main/ai-vault/parse-cache/session-scanner-parse-cache.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-dependencies.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-freshness.test.ts
  • src/main/ai-vault/scanners/opencode/sqlite/session-scanner-opencode-sqlite-discovery.ts
  • src/main/ai-vault/session-scanner-types.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 55b473ff-3422-4c35-bbfe-9346f1b1fd10
Commits

Reviewing files that changed from the base of the PR and between e6fa4c6 and 89f916f.

Files selected for processing: 3

  • src/main/ai-vault-search/indexing/session-search-opencode-json-read-errors.test.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-dependencies.ts
  • src/main/ai-vault/scanners/opencode/session-scanner-opencode-parser.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@nwparker

Copy link
Copy Markdown
Contributor

Thanks so much for this fix, @Afloat16! We carried it forward in #50781: rebased onto current main, with a few follow-ups (part dirs keyed by message file name, shared tool-state normalization, bounded part reads on listing and first-prompt, and First Prompt routing for legacy .json sessions). The commit keeps you as the author. Closing this one in favour of #50781.

@nwparker nwparker closed this Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Legacy OpenCode JSON sessions lose separately stored message bodies in History and search

2 participants