Skip to content

feat(storage): import opencode sessions through ExternalSessionAdapter - #3671

Merged
likun666661 merged 3 commits into
apache:mainfrom
Joob1n:feat/opencode-session-adapter
Aug 24, 2026
Merged

likun666661 merged 3 commits into
apache:mainfrom
Joob1n:feat/opencode-session-adapter

Conversation

@Joob1n

@Joob1n Joob1n commented Aug 24, 2026 •

Copy link
Copy Markdown
Member

Summary

A user with history in opencode had no way to bring it into Maka. This adds OpenCodeSessionAdapter and registers it, so the source-agnostic importer gains a third source without the importer or the persistence path changing — the property #2499 asked for.

The storage layout in the issue body is obsolete. It documents a storage/session/{info,message,part} JSON tree plus a migration between two directory layouts. On opencode 1.18.21 neither exists — find ~/.local/share/opencode -name '*.json' returns nothing. State is one SQLite database at ~/.local/share/opencode/opencode.db, which the CLI will name with opencode db path. A conversation is session plus message and part, each keeping its payload in an opaque data JSON column. Full findings are in this comment.

Turn state is derivable, so this does not inherit the Ledger constraint discussed on #3142. Read from captured sessions rather than from the binary:

  • step-finish is durably persisted, carrying reason, tokens and cost;
  • the field is time.completed, not time.end, and it is set on every assistant message — including the aborted one;
  • finish is stop on a closing step, tool-calls on an intermediate one, and absent on a message carrying error.name: "MessageAbortedError".

So a turn closes as completed only on stop, as aborted on an abort error, and as aborted when the last step asked for tools and no answer followed. A run stopped between a call and its result did not complete, and recording it as completed would assert a reply the session never produced.

Two shapes had no captured sample, and both fail closed rather than guess. Every tool part observed had state.status: "completed" (6 of 6), so a call in any other status is imported without a synthesised result. A child session (parent_id set) is neither listed nor readable as a conversation, since it is one leg of a parent dialogue rather than something a user started.

Part of #2499. Fixes #3403

Self-review

Reviewing the first commit as a reviewer rather than re-running its tests turned up three defects, each confirmed by probing the built code before changing it. They are fixed in 9a0e526, with a test each.

#withDatabase flattened every failure into undefined and both callers turned that into an empty result:

  • a corrupt or locked database listed nothing and answered readSession with "opencode session not found" — sending a user to look for a session that exists in a database this could not open;
  • a readable session row whose transcript tables were missing — what a future opencode that renames them produces — imported successfully with zero messages. The user is told the import worked and gets an empty conversation. This was the worst of the three.

Failure is now reported. Discovery still answers an empty catalog when the database file is absent, since an opencode installed and never used is a normal state.

A user message with no text part also opened a turn, so a session beginning with one emitted a turn_state for a turn holding no messages — a terminal verdict on a conversation that is not there.

Reverting either fix turns the new tests red: restoring the swallowed read error fails 2, restoring the empty-prompt turn fails 1.

Verification

New suite, 11 tests:

$ node --test packages/storage/dist/__tests__/opencode-session-adapter.test.js
ℹ tests 14
ℹ pass 14
ℹ fail 0

The three load-bearing rules of the mapping were mutation-checked — each break turns the suite red, so the tests fail without the change rather than merely running alongside it:

Mutation Result
stop filtering non-completed tool calls 10 pass, 1 fail
stop recognising MessageAbortedError 10 pass, 1 fail
stop filtering child sessions 10 pass, 1 fail

Every emitted message is asserted to survive decodeCanonicalMessage, so an import is rejected here rather than at the persistence boundary.

Whole package, plus the dependent that consumes the registry:

$ node --test --test-concurrency=2 "packages/storage/dist/__tests__/*.test.js"
ℹ tests 934
ℹ pass 920
ℹ fail 0

$ npm --workspace @maka/runtime-host run build     clean
$ npm run format:check    Checked 1608 files. No fixes applied.
$ npx biome lint <the two new files>   no findings

Fixture

opencode-session-1.18.21.json is a real captured session — two file reads, three commands, one write, and a final aborted message — exported with opencode db. Paths are rewritten to /workspace/project and /home/user, and tool output longer than 400 characters is truncated. Record shapes are verbatim, because the shapes are the thing under test.

AI use

Select exactly one:

  • No generative tool made a substantive contribution
  • Generative tooling made a substantive contribution

Tool(s) and scope: Claude Opus 5 via Claude Code — read the live database to establish the current format, captured and sanitised the fixture, wrote the adapter and its tests, and ran the mutation checks. Every claim above came from running the command shown against real opencode data. The commit carries a Generated-by trailer.

Checklist

  • Tests cover the change and fail without it
  • Lint, format, typecheck and the affected suites pass locally

Does this PR entail a change in behavior?

  • Yes — described under Summary above
  • No

A user with history in opencode had no way to bring it into Maka. Adds
`OpenCodeSessionAdapter` and registers it, so the source-agnostic
importer gains a third source without the importer or the persistence
path changing.

The issue documented a `storage/session/{info,message,part}` JSON tree
and a migration between two directory layouts. Neither exists on
opencode 1.18.21: state is one SQLite database at
`~/.local/share/opencode/opencode.db`, which the CLI will name with
`opencode db path`. A conversation is `session` plus `message` and
`part`, each keeping its payload in an opaque `data` JSON column.

Turn state is derivable from the record, so this adapter does not
inherit the Ledger constraint discussed on apache#3142. Read from captured
sessions rather than from the binary:

- `step-finish` is durably persisted, carrying `reason`, tokens and cost;
- the field is `time.completed`, not `time.end`, and it is set on every
  assistant message including an aborted one;
- `finish` is `stop` on a closing step and `tool-calls` on an
  intermediate one, and is absent on a message that carries
  `error.name: "MessageAbortedError"`.

The mapping therefore closes a turn as completed only on `stop`, as
aborted on an abort error, and as aborted when the last step asked for
tools and no answer followed — a run stopped between a call and its
result did not complete.

Two shapes had no captured sample, and both fail closed rather than
guess: a `tool` part whose `state.status` is not `completed` yields a
call with no synthesised result, and a child session is neither listed
nor readable as a conversation.

The fixture is a real 1.18.21 session — reads, a command, a write, and a
final aborted message — with paths rewritten and long tool output
truncated. Record shapes are verbatim.

Verified: 11 new tests pass, and the mapping's three load-bearing rules
were mutation-checked — dropping the non-completed tool filter, the
abort detection, or the child-session filter each turns the suite red.
Full @maka/storage suite: 931 tests, 0 failures.

Part of apache#2499. Fixes apache#3403

Generated-by: Claude Opus 5 via Claude Code

@M4n5ter M4n5ter left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

English

Exact-head review of 8fa2df01f66f766725df0f2b7a5ccea574908488: 3 P2 findings. The adapter reuses the existing registry, importer, and atomic persistence authority, but three supported/read-failure paths can still publish a materially false transcript: terminal tool failures are dropped, source part order is rewritten, and transcript read/decode failure is collapsed into a valid empty import.

Verification: the focused adapter suite passes 11/11 on the PR head and on a conflict-free current-main merge result. Core, Storage, Runtime, and Runtime Host builds pass; Biome and git diff --check pass. The full Storage suite reached 914 pass / 16 skipped / 1 environment-only failure because Node 24's experimental SQLite warning reached a child-process stderr assertion; that isolated file passes 5/5 with NODE_NO_WARNINGS=1. Hosted exact-head test is still in progress, so it is not counted as green evidence.

Simplify audit: this adds a source-specific decoder and fixture but does not create a second registry/import/persistence authority. It removes no concept, state, path, or contract; I found no bounded simplification that should replace the integration structure.

Withdrawn candidates: the non-string completed.output case is malformed relative to the 1.18.21 source contract and is covered by the fail-closed decode finding rather than reported separately; the captured reasoning-first fixture does not by itself prove ordering, so the order finding below is instead based on opencode's own accepted text -> reasoning -> tool test shape.

中文

对 exact head 8fa2df01f66f766725df0f2b7a5ccea574908488 的审查结论:3 条 P2。这个适配器复用了现有 registry、importer 与原子持久化权威,没有另起第二套导入路径;但三个可达路径仍会发布实质失真的历史:终态工具失败被丢弃、源 part 顺序被改写、transcript 读取/解码失败被折叠成合法的空导入。

验证:PR head 与基于当前 main 的无冲突 merge result 上,focused adapter 测试均为 11/11;Core、Storage、Runtime、Runtime Host build 通过,Biome 与 git diff --check 通过。Storage 全量为 914 pass / 16 skipped / 1 个环境性失败:Node 24 的 SQLite experimental warning 进入了子进程 stderr 断言;加 NODE_NO_WARNINGS=1 单独重跑该文件为 5/5。Hosted exact-head test 仍在运行,因此不把它算作绿色证据。

简化审计:本 PR 增加了源格式专用 decoder 与 fixture,但没有新增第二份 registry/import/persistence authority。它没有删除概念、状态、路径或契约;在不削弱这项集成的前提下,我没有找到应替代当前结构的有界简化。

撤回候选:completed.output 非字符串相对 1.18.21 契约属于畸形输入,已并入 fail-closed 解码 finding,不另报;现有 reasoning-first fixture 本身不能证明顺序问题,因此下面的顺序 finding 使用的是 opencode 自己接受的 text -> reasoning -> tool 测试形状。

// call still in flight when the session was written, and this adapter
// has no captured sample of their shape. Synthesising a result for one
// would put words the tool never said into the transcript.
if (status !== 'completed') continue;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

English

[P2] Preserve terminal opencode tool failures

status !== 'completed' is not equivalent to an in-flight call. opencode 1.18.21 defines a distinct terminal ToolStateError, and its own replay maps that state to output-error.

Reproduction with supported rows: user message -> assistant finish: "tool-calls" containing {status:"error", input:{...}, error:"exit 1"} -> assistant finish:"stop". convertTranscript emits user -> tool_call -> assistant -> turn_state(completed) with no tool_result. The existing guard only mutates captured calls to running; canonical decoding accepts the dangling call, and the later stop makes the whole turn look completed. Please emit a terminal tool_result with isError:true from the recorded error (while handling pending/running separately), so a persisted failure cannot be rewritten as an unresolved call inside a completed turn.

中文

[P2] 保留 opencode 的终态工具失败

status !== 'completed' 不等于“仍在执行”。opencode 1.18.21 明确定义了终态 ToolStateError,它自己的 replay 也把该状态映射为 output-error。

可复现路径:user -> 含 {status:"error", input:{...}, error:"exit 1"} 且 finish:"tool-calls" 的 assistant -> finish:"stop" 的 assistant。当前 convertTranscript 输出 user -> tool_call -> assistant -> turn_state(completed),没有 tool_result。现有测试只把捕获样本改成 running;canonical decoder 接受这个悬空 call,后续 stop 又把整个 turn 标成 completed。请从已记录的 error 生成 isError:true 的终态 tool_result,并把 pending/running 分开处理,避免把真实失败改写成 completed turn 中的未决调用。

.filter((row): row is PartRow => row !== undefined);
return { messages, parts };
});
return read ?? { messages: [], parts: [] };

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

English

[P2] Fail a selected import when transcript reading fails

This fallback makes a real read failure indistinguishable from a legitimately empty session. I created a read-only database with a valid, listable session row but no message/part tables. Both SELECTs throw; #withDatabase catches the exception, this line returns empty arrays, and the real ExternalSessionImporter + SessionStore publishes one Session with externalOrigin:{adapterId:"opencode", sourceSessionId:"ses_schema"} and zero messages. The same path silently filters malformed JSON rows at lines 187-195, producing a partial transcript.

Existing guards cannot stop this: decodeCanonicalMessage only validates rows that were emitted, and the generic importer intentionally accepts an empty message array. Keep discovery/listing best-effort if desired, but once readSession selects a source, missing schema, query failure, and undecodable message/part rows need to throw rather than commit an empty or truncated canonical history.

中文

[P2] 选定会话后,transcript 读取失败必须让导入失败

这个 fallback 把真实读取失败与“会话确实为空”合并成了同一个结果。我构造了一个只读数据库:有合法、可列出的 session 行,但没有 message / part 表。两个 SELECT 抛错后,#withDatabase 吞掉异常,本行返回空数组;真实 ExternalSessionImporter + SessionStore 随后发布了一个带 externalOrigin:{adapterId:"opencode", sourceSessionId:"ses_schema"}、但消息数为 0 的 Session。187-195 行对畸形 JSON 行的静默过滤也会通过同一路径生成残缺 transcript。

现有守卫拦不住:decodeCanonicalMessage 只验证实际 emitted 的行,而通用 importer 有意接受空消息数组。discovery/listing 可以继续 best-effort;但 readSession 一旦选定源会话,缺失 schema、查询失败、无法解码的 message/part 行都应抛错,不能提交空的或截断的 canonical history。


const modelId = stringOf(data.modelID) ?? 'opencode';

const reasoning = messageParts

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

English

[P2] Preserve the source part order instead of bucketing by type

The three-pass mapping (reasoning, then text, then tool) rewrites a valid source sequence. opencode 1.18.21's own test accepts text -> reasoning -> tool and expects that order to survive conversion (input, expected output). Feeding that same supported order to this function produces reasoning -> text -> tool_call -> tool_result.

The fixture does not guard this because every mixed assistant message happens to be reasoning-first, and the tests only assert that message kinds exist. Iterate the ordered parts (or encode their order in the canonical assistant step) so imported display/replay history does not move reasoning or text across another source part.

中文

[P2] 按源 part 顺序转换,不要按类型分桶

当前三遍处理(先 reasoning、再 text、最后 tool)会改写合法的源顺序。opencode 1.18.21 自己的测试接受 text -> reasoning -> tool,并要求转换后仍保持该顺序(输入,预期输出)。把同一支持形状交给本函数,实际得到 reasoning -> text -> tool_call -> tool_result。

现有 fixture 没有守住它:所有混合 assistant message 恰好都是 reasoning-first,测试也只检查 message kind 是否存在。请遍历已有顺序的 parts(或在 canonical assistant step 中编码其顺序),避免导入后的展示/重放历史把 reasoning 或 text 移到另一个源 part 前后。

Joob1n added 2 commits August 24, 2026 12:38
…pty one

Self-review of the adapter found three defects, each confirmed by
probing the built code before it was changed.

`#withDatabase` flattened every failure into `undefined`, and both
callers turned that into an empty result. Two consequences:

- a corrupt or locked database listed no sessions and answered
  `readSession` with "opencode session not found", sending a user to
  look for a session that exists in a database this could not open;
- a readable `session` row whose transcript tables were missing —
  what a future opencode that renames them would produce — imported
  successfully with zero messages. The user is told the import worked
  and gets an empty conversation.

Failure is now reported. Discovery still answers an empty catalog when
the database file is absent, because an opencode that was installed and
never used is a normal state rather than a failure.

A user message carrying no text part also opened a turn, so a session
that began with one emitted a `turn_state` for a turn holding no
messages — a terminal verdict on a conversation that is not there. The
boundary still closes the previous turn; an assistant message that
follows opens its own.

Three tests added, one per defect. Reverting either fix turns them red:
restoring the swallowed read error fails 2, restoring the empty-prompt
turn fails 1.

@maka/storage: 934 tests, 0 failures.

Generated-by: Claude Opus 5 via Claude Code
All three P2 findings from @M4n5ter's review are real. Two were new to
me; the third overlapped a defect I had already fixed but did not fix
completely.

**Terminal tool failures were dropped.** `status !== 'completed'` was
treated as "still in flight", but opencode's tool state union is
`pending | running | completed | error`, and `error` is terminal —
confirmed against the installed 1.18.21 binary, which records
`{ status: "error", input, error: <string>, metadata, time }`. A failed
call therefore became a call with no answer inside a turn that a later
`finish: "stop"` marked completed: a transcript asserting the tool never
replied when it replied with a failure. `error` now emits a
`tool_result` with `isError: true` carrying the recorded message;
`pending` and `running` still get none, because those are the calls that
genuinely had no answer.

**Source part order was rewritten.** The mapping ran three passes —
reasoning, then text, then tool — so a message opencode recorded as
`text -> reasoning -> tool` imported as `reasoning -> text -> tool`.
opencode accepts that order and its own replay preserves it. Parts are
now walked once, in the order the session recorded them.

**Undecodable rows were silently skipped.** `9a0e526` made a failed read
throw, but a row that would not decode was still filtered out, so a
transcript could import a message or a part short while reporting
success. A selected import now carries what the session recorded or
fails. Discovery stays best-effort.

Four tests added. Reverting any of the three fixes turns the suite red:
dropping terminal failures fails 1, restoring the silent row filter
fails 1, and re-bucketing parts by type fails 1.

@maka/storage: 938 tests, 0 failures.

Generated-by: Claude Opus 5 via Claude Code
@Joob1n

Joob1n commented Aug 24, 2026

Copy link
Copy Markdown
Member Author

Thank you — all three are real, and two of them I had not seen. Fixed in e0506ba.

[P2] Terminal tool failures. You are right that status !== 'completed' is not "in flight". I checked the installed 1.18.21 binary rather than only the linked types: the union is pending | running | completed | error, and the error state is recorded as { status: "error", input, error: <string>, metadata, time } — including the "Tool execution aborted" and "Cancelled" cases. error now emits a tool_result with isError: true carrying the recorded message. pending and running still get none, since those are the calls that genuinely had no answer.

Your reproduction is now a test: user → assistant finish: "tool-calls" holding {status:"error", input:{...}, error:"exit 1"} → assistant finish:"stop". It asserts the errored result exists and pairs with the call, so a persisted failure can no longer be rewritten as an unresolved call inside a completed turn.

[P2] Source part order. Also right, and the fixture hid it exactly as you say — every mixed assistant message in the capture happens to be reasoning-first. The three passes are gone; parts are walked once in recorded order. The new test feeds text → reasoning → tool and asserts the import comes out text → thinking → tool_call → tool_result.

[P2] Transcript read failure. This one overlapped a defect I found in my own review and fixed in 9a0e526 — but I fixed only half of it. The read failure now throws, which covers your missing-tables reproduction; what I had left in place was the silent filtering of undecodable rows at what were lines 187-195, so a transcript could still import a message or a part short while reporting success. That is fixed too: a selected import now carries what the session recorded or fails. Discovery and listing stay best-effort, as you suggested.

Each fix is pinned by reverting it: dropping terminal failures fails 1 test, restoring the silent row filter fails 1, re-bucketing parts by type fails 1.

@maka/storage: 938 tests, 0 failures.

@Joob1n
Joob1n requested a review from M4n5ter August 24, 2026 05:41

@likun666661 likun666661 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

LGTM

@likun666661
likun666661 merged commit 04836d3 into apache:main Aug 24, 2026
1 check passed
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.

feat(storage): import opencode sessions through ExternalSessionAdapter

3 participants