Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Capture OpenCode conversations for coding memory (#573)

Deea41f04aadee8
diff --git a/cli/scripts/memory-native-opencode-source-probe.mjs b/cli/scripts/memory-native-opencode-source-probe.mjs
new file mode 100644
index 000000000..2133939a2
--- /dev/null
+++ b/cli/scripts/memory-native-opencode-source-probe.mjs
@@ -0,0 +1,155 @@
+// Real OpenCode 1.18.34, disposable HOME/database, synthetic localhost model only.
+// Run: node cli/scripts/memory-native-opencode-source-probe.mjs
+import assert from 'node:assert/strict'
+import { execFileSync, spawn } from 'node:child_process'
+import { createServer } from 'node:http'
+import { mkdtemp, mkdir, realpath, rm, writeFile } from 'node:fs/promises'
+import { tmpdir } from 'node:os'
+import { dirname, join } from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import { DatabaseSync } from 'node:sqlite'
+import { build } from 'esbuild'
+
+const directory = await realpath(await mkdtemp(join(tmpdir(), 'memory-opencode-source-')))
+const database = join(directory, 'native.db'), workspace = join(directory, 'work')
+const cli = dirname(dirname(fileURLToPath(import.meta.url)))
+const consentAt = Date.now()
+let native, nativeUrl, stderr = '', stdout = '', phase = 'turn', requestedTool = false
+let store
+let closeSources = () => {}
+const model = createServer(async (request, response) => {
+ const chunks = []
+ for await (const chunk of request) chunks.push(chunk)
+ const body = JSON.parse(Buffer.concat(chunks))
+ const tools = (body.tools ?? []).map(tool => tool.function?.name)
+ const read = phase === 'turn' && tools.includes('read') && !requestedTool
+ if (read) requestedTool = true
+ const base = { id: 'chatcmpl_source', object: 'chat.completion.chunk', created: 1, model: body.model }
+ response.writeHead(200, { 'content-type': 'text/event-stream' })
+ const delta = read ? { role: 'assistant', tool_calls: [{ index: 0, id: 'call_source', type: 'function',
+ function: { name: 'read', arguments: JSON.stringify({ filePath: join(workspace, 'fixture.txt') }) } }] }
+ : { role: 'assistant', content: phase === 'compaction' ? 'Synthetic context summary.' : 'I will keep the viewer on the left.' }
+ response.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason: null }] }) + '\n\n')
+ response.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta: {}, finish_reason: read ? 'tool_calls' : 'stop' }] }) + '\n\n')
+ response.end('data: [DONE]\n\n')
+})
+
+try {
+ await new Promise((resolve, reject) => { model.once('error', reject); model.listen(0, '127.0.0.1', resolve) })
+ for (const name of ['home', 'config', 'data', 'cache', 'state', 'work']) await mkdir(join(directory, name), { mode: 0o700 })
+ execFileSync('git', ['init', '-q', workspace])
+ await writeFile(join(workspace, 'fixture.txt'), 'Synthetic fixture data.\n')
+ const bundle = join(directory, 'capture.mjs')
+ await build({ stdin: { contents: [
+ `export { NativeMemoryCapture } from ${JSON.stringify(join(cli, 'src/memory/capture.ts'))};`,
+ `export { CodingMemoryStore } from ${JSON.stringify(join(cli, 'src/memory/store.ts'))};`,
+ `export { QUEUE_OPERATIONS } from ${JSON.stringify(join(cli, 'src/memory/operations.ts'))};`,
+ `export { closeSqliteHandles } from ${JSON.stringify(join(cli, 'src/lib/sqliteRead.ts'))};`,
+ ].join('\n'), resolveDir: cli }, outfile: bundle, bundle: true, platform: 'node', format: 'esm', target: 'node22',
+ banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" } })
+ const { NativeMemoryCapture, CodingMemoryStore, QUEUE_OPERATIONS, closeSqliteHandles } = await import(pathToFileURL(bundle).href)
+ closeSources = closeSqliteHandles
+ const opened = CodingMemoryStore.open({ directory: join(directory, 'memory'), profileId: 'fixture', now: () => consentAt })
+ assert.ok(opened.ok); store = opened.store
+ store.registerProject('project'); store.setControls({ learn: true, recall: true })
+ const capture = new NativeMemoryCapture({ async request(operation, args) {
+ const receiver = QUEUE_OPERATIONS.includes(operation) ? store.learning : store
+ return receiver[operation](...args)
+ } })
+ const captureSession = id => capture.poll({ profileId: 'fixture', projectId: 'project', engine: 'opencode',
+ sessionId: id, transcriptPath: database, workspace, busy: false })
+ const drain = () => {
+ const target = { state: 'ready', key: 'synthetic' }, claim = store.learning.claim(target)
+ assert.equal(claim.state, 'claimed')
+ store.learning.finish(claim.lease, [], target)
+ return claim.lease
+ }
+ const config = { autoupdate: false, share: 'disabled', snapshot: false, plugin: [], mcp: {}, instructions: [],
+ permission: { '*': 'deny', read: { '*': 'deny', 'fixture.txt': 'allow', [join(workspace, 'fixture.txt')]: 'allow' } },
+ enabled_providers: ['fixture'], model: 'fixture/model', small_model: 'fixture/model',
+ agent: { source_fixture: { mode: 'primary', description: 'Native source fixture',
+ prompt: 'Use read once, then answer briefly.', steps: 3 } },
+ provider: { fixture: { npm: '@ai-sdk/openai-compatible',
+ options: { apiKey: 'synthetic', baseURL: `http://127.0.0.1:${model.address().port}/v1` },
+ models: { model: { name: 'Synthetic', limit: { context: 128000, output: 4096 } } } } } }
+ native = spawn(process.env.OPENCODE_PATH || 'opencode', ['serve', '--hostname', '127.0.0.1', '--port', '0'], {
+ cwd: workspace, detached: true, stdio: ['ignore', 'pipe', 'pipe'], env: { PATH: process.env.PATH,
+ HOME: join(directory, 'home'), TMPDIR: directory, XDG_CONFIG_HOME: join(directory, 'config'),
+ XDG_DATA_HOME: join(directory, 'data'), XDG_CACHE_HOME: join(directory, 'cache'), XDG_STATE_HOME: join(directory, 'state'),
+ OPENCODE_DB: database, OPENCODE_CONFIG_CONTENT: JSON.stringify(config), OPENCODE_AUTH_CONTENT: '{}',
+ OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_MODELS_FETCH: '1',
+ OPENCODE_DISABLE_AUTOCOMPACT: '1', TERM: 'dumb' },
+ })
+ native.stdout.on('data', chunk => { stdout = (stdout + chunk).slice(-5000); nativeUrl = stdout.match(/http:\/\/127\.0\.0\.1:\d+/)?.[0] })
+ native.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-5000) })
+ const deadline = Date.now() + 10000
+ while (!nativeUrl && native.exitCode === null && Date.now() < deadline) await new Promise(resolve => setTimeout(resolve, 50))
+ assert.ok(nativeUrl, `Native server did not start: ${stderr}`)
+ const call = async (path, body) => {
+ const response = await fetch(nativeUrl + path, { method: body === undefined ? 'GET' : 'POST',
+ headers: { 'content-type': 'application/json', 'x-opencode-directory': workspace },
+ signal: AbortSignal.timeout(25000), ...(body === undefined ? {} : { body: JSON.stringify(body) }) })
+ assert.ok(response.ok, `${path}: ${response.status} ${response.ok ? '' : await response.text()}`)
+ return response.json()
+ }
+ assert.equal((await call('/global/health')).version, '1.18.34')
+ const session = await call('/session', { title: 'Synthetic memory source' })
+ const send = (id, text) => call(`/session/${id}/message`, { agent: 'source_fixture',
+ model: { providerID: 'fixture', modelID: 'model' }, parts: [{ type: 'text', text }] })
+ await send(session.id, 'Keep the viewer on the left.\n\n> A quote: put the viewer on the right.\n\nRead fixture.txt once.')
+ const db = new DatabaseSync(database, { readOnly: true })
+ const snapshot = id => ({
+ sessions: db.prepare('SELECT id,parent_id,directory,version,revert,time_created,time_updated FROM session WHERE id=?').all(id),
+ messages: db.prepare('SELECT * FROM message WHERE session_id=? ORDER BY time_created,id').all(id),
+ parts: db.prepare('SELECT * FROM part WHERE session_id=? ORDER BY time_created,id').all(id),
+ })
+ try {
+ const turn = snapshot(session.id)
+ const tool = turn.parts.map(row => JSON.parse(row.data)).find(part => part.type === 'tool')
+ assert.equal(tool.tool, 'read'); assert.equal(tool.state.status, 'completed', JSON.stringify(tool.state))
+ assert.match(tool.state.output, /Synthetic fixture data/)
+ assert.equal((await captureSession(session.id)).sources, 6)
+ assert.deepEqual(drain().sources.map(row => row.role), ['user', 'reference', 'user', 'assistant', 'tool', 'assistant'])
+ assert.equal((await captureSession(session.id)).sources, 0)
+ const fork = await call(`/session/${session.id}/fork`, {})
+ const copied = snapshot(fork.id)
+ assert.ok(copied.messages.length > 0)
+ assert.ok(copied.messages.every(row => JSON.parse(row.data).time.created < copied.sessions[0].time_created))
+ assert.equal((await captureSession(fork.id)).sources, 0)
+ await send(fork.id, 'This is a fresh instruction in the fork.')
+ const forkWithNewTurn = snapshot(fork.id)
+ assert.equal((await captureSession(fork.id)).sources, 2)
+ assert.equal(drain().sources[0].text, 'This is a fresh instruction in the fork.')
+ phase = 'compaction'
+ await call(`/session/${session.id}/summarize`, { providerID: 'fixture', modelID: 'model' })
+ const compaction = snapshot(session.id)
+ assert.ok(compaction.parts.some(row => JSON.parse(row.data).type === 'compaction'))
+ assert.ok(compaction.messages.some(row => JSON.parse(row.data).summary === true))
+ assert.equal((await captureSession(session.id)).sources, 0)
+ const user = forkWithNewTurn.messages.filter(row => JSON.parse(row.data).role === 'user').at(-1)
+ await call(`/session/${fork.id}/revert`, { messageID: user.id })
+ const reverted = snapshot(fork.id)
+ assert.equal(JSON.parse(reverted.sessions[0].revert).messageID, user.id)
+ assert.equal((await captureSession(fork.id)).reason, 'native_session_reverted')
+ const recording = { version: '1.18.34', synthetic: true,
+ schema: db.prepare("SELECT name,sql FROM sqlite_master WHERE type='table' AND name IN ('session','message','part') ORDER BY name").all(),
+ turn, copied, forkWithNewTurn, compaction, reverted }
+ // Recording contains only fixture text; replace the disposable absolute path before storing it.
+ const sanitized = JSON.stringify(recording, null, 2).replaceAll(directory, '/fixture') + '\n'
+ const destination = process.env.MEMORY_SOURCE_RECORDING
+ if (destination) await writeFile(destination, sanitized, { mode: 0o600 })
+ console.log(JSON.stringify({ version: '1.18.34', nativeTool: tool.tool, nativeToolStatus: tool.state.status,
+ copiedForkKeepsOriginalTimestamps: true, compactionRecorded: true, revertRecorded: true,
+ nativeCaptureVerified: true, repeatedPollDuplicateSources: 0, copiedForkSources: 0, compactionSources: 0,
+ recording: destination ?? null, limitations: ['Synthetic model responses; no personal memory-quality measurement.'] }, null, 2))
+ } finally { db.close() }
+} finally {
+ if (native?.exitCode === null && native?.signalCode === null) {
+ try { process.kill(-native.pid, 'SIGKILL') } catch { native.kill('SIGKILL') }
+ await new Promise(resolve => native.once('close', resolve))
+ }
+ model.closeAllConnections(); await new Promise(resolve => model.close(resolve))
+ store?.close()
+ closeSources()
+ await rm(directory, { recursive: true, force: true })
+}
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 32a166e85..aba3e0266 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -4990,7 +4990,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
} })
companionProfileChanged = () => { companionIntelligence.status(); pairBrain?.stateChanged() }
{
- const roster = new MemorySessionRoster(homedir())
+ const roster = new MemorySessionRoster(homedir(), Date.now, { opencode: OPENCODE_DB })
codingMemory = new CodingMemoryRuntime({
directory: join(env.ADAPTER_DATA_DIR, 'coding-memory'),
context: () => {
diff --git a/cli/src/memory/__fixtures__/opencode-1.18.34-source.json b/cli/src/memory/__fixtures__/opencode-1.18.34-source.json
new file mode 100644
index 000000000..14740383f
--- /dev/null
+++ b/cli/src/memory/__fixtures__/opencode-1.18.34-source.json
@@ -0,0 +1,626 @@
+{
+ "version": "1.18.34",
+ "synthetic": true,
+ "schema": [
+ {
+ "name": "message",
+ "sql": "CREATE TABLE `message` (\n `id` text PRIMARY KEY,\n `session_id` text NOT NULL,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n `data` text NOT NULL,\n CONSTRAINT `fk_message_session_id_session_id_fk` FOREIGN KEY (`session_id`) REFERENCES `session`(`id`) ON DELETE CASCADE\n )"
+ },
+ {
+ "name": "part",
+ "sql": "CREATE TABLE `part` (\n `id` text PRIMARY KEY,\n `message_id` text NOT NULL,\n `session_id` text NOT NULL,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n `data` text NOT NULL,\n CONSTRAINT `fk_part_message_id_message_id_fk` FOREIGN KEY (`message_id`) REFERENCES `message`(`id`) ON DELETE CASCADE\n )"
+ },
+ {
+ "name": "session",
+ "sql": "CREATE TABLE `session` (\n `id` text PRIMARY KEY,\n `project_id` text NOT NULL,\n `workspace_id` text,\n `parent_id` text,\n `slug` text NOT NULL,\n `directory` text NOT NULL,\n `path` text,\n `title` text NOT NULL,\n `version` text NOT NULL,\n `share_url` text,\n `summary_additions` integer,\n `summary_deletions` integer,\n `summary_files` integer,\n `summary_diffs` text,\n `metadata` text,\n `cost` real DEFAULT 0 NOT NULL,\n `tokens_input` integer DEFAULT 0 NOT NULL,\n `tokens_output` integer DEFAULT 0 NOT NULL,\n `tokens_reasoning` integer DEFAULT 0 NOT NULL,\n `tokens_cache_read` integer DEFAULT 0 NOT NULL,\n `tokens_cache_write` integer DEFAULT 0 NOT NULL,\n `revert` text,\n `permission` text,\n `agent` text,\n `model` text,\n `time_created` integer NOT NULL,\n `time_updated` integer NOT NULL,\n `time_compacting` integer,\n `time_archived` integer,\n CONSTRAINT `fk_session_project_id_project_id_fk` FOREIGN KEY (`project_id`) REFERENCES `project`(`id`) ON DELETE CASCADE\n )"
+ }
+ ],
+ "turn": {
+ "sessions": [
+ {
+ "id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "parent_id": null,
+ "directory": "/fixture/work",
+ "version": "1.18.34",
+ "revert": null,
+ "time_created": 1790905955370,
+ "time_updated": 1790905956756
+ }
+ ],
+ "messages": [
+ {
+ "id": "msg_0fa50349c001kaMn1c5SsQzezN",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955484,
+ "time_updated": 1790905955488,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905955484},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955763,
+ "time_updated": 1790905956731,
+ "data": "{\"parentID\":\"msg_0fa50349c001kaMn1c5SsQzezN\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905955763,\"completed\":1790905956731},\"finish\":\"tool-calls\"}"
+ },
+ {
+ "id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956733,
+ "time_updated": 1790905956753,
+ "data": "{\"parentID\":\"msg_0fa50349c001kaMn1c5SsQzezN\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956733,\"completed\":1790905956753},\"finish\":\"stop\"}"
+ }
+ ],
+ "parts": [
+ {
+ "id": "prt_0fa5034a00010Ws8gM1qalwMDv",
+ "message_id": "msg_0fa50349c001kaMn1c5SsQzezN",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955756,
+ "time_updated": 1790905955757,
+ "data": "{\"type\":\"text\",\"text\":\"Keep the viewer on the left.\\n\\n> A quote: put the viewer on the right.\\n\\nRead fixture.txt once.\"}"
+ },
+ {
+ "id": "prt_0fa503962001I1PJGXWH9bovgH",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956707,
+ "time_updated": 1790905956707,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa503965001jEZQxHkvcf07Jg",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956709,
+ "time_updated": 1790905956725,
+ "data": "{\"type\":\"tool\",\"tool\":\"read\",\"callID\":\"call_source\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"/fixture/work/fixture.txt\"},\"output\":\"<path>/fixture/work/fixture.txt</path>\\n<type>file</type>\\n<content>\\n1: Synthetic fixture data.\\n\\n(End of file - total 1 lines)\\n</content>\",\"metadata\":{\"preview\":\"Synthetic fixture data.\",\"truncated\":false,\"loaded\":[],\"display\":{\"type\":\"file\",\"path\":\"/fixture/work/fixture.txt\",\"text\":\"Synthetic fixture data.\",\"lineStart\":1,\"lineEnd\":1,\"totalLines\":1,\"truncated\":false}},\"title\":\"fixture.txt\",\"time\":{\"start\":1790905956714,\"end\":1790905956725}}}"
+ },
+ {
+ "id": "prt_0fa503977001nC8pJDeftCt3fW",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956728,
+ "time_updated": 1790905956728,
+ "data": "{\"reason\":\"tool-calls\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa50398b001ybownrXnYyDiKp",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956747,
+ "time_updated": 1790905956748,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa50398d0011fCGV6iufRWGUe",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956749,
+ "time_updated": 1790905956750,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956749,\"end\":1790905956750}}"
+ },
+ {
+ "id": "prt_0fa50398f001QeltjQ2ngmVY5f",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956751,
+ "time_updated": 1790905956751,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ }
+ ]
+ },
+ "copied": {
+ "sessions": [
+ {
+ "id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "parent_id": null,
+ "directory": "/fixture/work",
+ "version": "1.18.34",
+ "revert": null,
+ "time_created": 1790905956764,
+ "time_updated": 1790905956764
+ }
+ ],
+ "messages": [
+ {
+ "id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955484,
+ "time_updated": 1790905956766,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905955484},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955763,
+ "time_updated": 1790905956768,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905955763,\"completed\":1790905956731},\"finish\":\"tool-calls\"}"
+ },
+ {
+ "id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956733,
+ "time_updated": 1790905956772,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956733,\"completed\":1790905956753},\"finish\":\"stop\"}"
+ }
+ ],
+ "parts": [
+ {
+ "id": "prt_0fa50399f001XjajkGblzofl1w",
+ "message_id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956767,
+ "time_updated": 1790905956767,
+ "data": "{\"type\":\"text\",\"text\":\"Keep the viewer on the left.\\n\\n> A quote: put the viewer on the right.\\n\\nRead fixture.txt once.\"}"
+ },
+ {
+ "id": "prt_0fa5039a1001rCzDT7e3PZVbmS",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956769,
+ "time_updated": 1790905956769,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a2001chJKR00Laavgni",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956770,
+ "time_updated": 1790905956770,
+ "data": "{\"type\":\"tool\",\"tool\":\"read\",\"callID\":\"call_source\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"/fixture/work/fixture.txt\"},\"output\":\"<path>/fixture/work/fixture.txt</path>\\n<type>file</type>\\n<content>\\n1: Synthetic fixture data.\\n\\n(End of file - total 1 lines)\\n</content>\",\"metadata\":{\"preview\":\"Synthetic fixture data.\",\"truncated\":false,\"loaded\":[],\"display\":{\"type\":\"file\",\"path\":\"/fixture/work/fixture.txt\",\"text\":\"Synthetic fixture data.\",\"lineStart\":1,\"lineEnd\":1,\"totalLines\":1,\"truncated\":false}},\"title\":\"fixture.txt\",\"time\":{\"start\":1790905956714,\"end\":1790905956725}}}"
+ },
+ {
+ "id": "prt_0fa5039a3001Vmq4LrhG2tsFid",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956771,
+ "time_updated": 1790905956771,
+ "data": "{\"reason\":\"tool-calls\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039a4002opjulFdqKdSd65",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956772,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a5001V0z4rbOmk9YijA",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956773,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956749,\"end\":1790905956750}}"
+ },
+ {
+ "id": "prt_0fa5039a60019Nat1RNmiH0Pm4",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956774,
+ "time_updated": 1790905956774,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ }
+ ]
+ },
+ "forkWithNewTurn": {
+ "sessions": [
+ {
+ "id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "parent_id": null,
+ "directory": "/fixture/work",
+ "version": "1.18.34",
+ "revert": null,
+ "time_created": 1790905956764,
+ "time_updated": 1790905956790
+ }
+ ],
+ "messages": [
+ {
+ "id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955484,
+ "time_updated": 1790905956766,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905955484},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955763,
+ "time_updated": 1790905956768,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905955763,\"completed\":1790905956731},\"finish\":\"tool-calls\"}"
+ },
+ {
+ "id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956733,
+ "time_updated": 1790905956772,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956733,\"completed\":1790905956753},\"finish\":\"stop\"}"
+ },
+ {
+ "id": "msg_0fa5039ae001XNcEr2DXKyRy7H",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956782,
+ "time_updated": 1790905956784,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905956782},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956788,
+ "time_updated": 1790905956800,
+ "data": "{\"parentID\":\"msg_0fa5039ae001XNcEr2DXKyRy7H\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956788,\"completed\":1790905956799},\"finish\":\"stop\"}"
+ }
+ ],
+ "parts": [
+ {
+ "id": "prt_0fa50399f001XjajkGblzofl1w",
+ "message_id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956767,
+ "time_updated": 1790905956767,
+ "data": "{\"type\":\"text\",\"text\":\"Keep the viewer on the left.\\n\\n> A quote: put the viewer on the right.\\n\\nRead fixture.txt once.\"}"
+ },
+ {
+ "id": "prt_0fa5039a1001rCzDT7e3PZVbmS",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956769,
+ "time_updated": 1790905956769,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a2001chJKR00Laavgni",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956770,
+ "time_updated": 1790905956770,
+ "data": "{\"type\":\"tool\",\"tool\":\"read\",\"callID\":\"call_source\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"/fixture/work/fixture.txt\"},\"output\":\"<path>/fixture/work/fixture.txt</path>\\n<type>file</type>\\n<content>\\n1: Synthetic fixture data.\\n\\n(End of file - total 1 lines)\\n</content>\",\"metadata\":{\"preview\":\"Synthetic fixture data.\",\"truncated\":false,\"loaded\":[],\"display\":{\"type\":\"file\",\"path\":\"/fixture/work/fixture.txt\",\"text\":\"Synthetic fixture data.\",\"lineStart\":1,\"lineEnd\":1,\"totalLines\":1,\"truncated\":false}},\"title\":\"fixture.txt\",\"time\":{\"start\":1790905956714,\"end\":1790905956725}}}"
+ },
+ {
+ "id": "prt_0fa5039a3001Vmq4LrhG2tsFid",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956771,
+ "time_updated": 1790905956771,
+ "data": "{\"reason\":\"tool-calls\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039a4002opjulFdqKdSd65",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956772,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a5001V0z4rbOmk9YijA",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956773,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956749,\"end\":1790905956750}}"
+ },
+ {
+ "id": "prt_0fa5039a60019Nat1RNmiH0Pm4",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956774,
+ "time_updated": 1790905956774,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039af001GKUPOUEofBZB10",
+ "message_id": "msg_0fa5039ae001XNcEr2DXKyRy7H",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956784,
+ "time_updated": 1790905956785,
+ "data": "{\"type\":\"text\",\"text\":\"This is a fresh instruction in the fork.\"}"
+ },
+ {
+ "id": "prt_0fa5039ba001lHpOGevTfAVl12",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956794,
+ "time_updated": 1790905956795,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039bb001O24h6sIunRcjy3",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956795,
+ "time_updated": 1790905956797,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956795,\"end\":1790905956796}}"
+ },
+ {
+ "id": "prt_0fa5039bd001RyM9U9DbDS8Wwq",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956797,
+ "time_updated": 1790905956798,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ }
+ ]
+ },
+ "compaction": {
+ "sessions": [
+ {
+ "id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "parent_id": null,
+ "directory": "/fixture/work",
+ "version": "1.18.34",
+ "revert": null,
+ "time_created": 1790905955370,
+ "time_updated": 1790905956756
+ }
+ ],
+ "messages": [
+ {
+ "id": "msg_0fa50349c001kaMn1c5SsQzezN",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955484,
+ "time_updated": 1790905955488,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905955484},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955763,
+ "time_updated": 1790905956731,
+ "data": "{\"parentID\":\"msg_0fa50349c001kaMn1c5SsQzezN\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905955763,\"completed\":1790905956731},\"finish\":\"tool-calls\"}"
+ },
+ {
+ "id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956733,
+ "time_updated": 1790905956753,
+ "data": "{\"parentID\":\"msg_0fa50349c001kaMn1c5SsQzezN\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956733,\"completed\":1790905956753},\"finish\":\"stop\"}"
+ },
+ {
+ "id": "msg_0fa5039cb001hj2qrNREiPP41J",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956811,
+ "time_updated": 1790905956811,
+ "data": "{\"role\":\"user\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"},\"agent\":\"source_fixture\",\"time\":{\"created\":1790905956811}}"
+ },
+ {
+ "id": "msg_0fa5039cf001khN9tojJcmsgp4",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956815,
+ "time_updated": 1790905956823,
+ "data": "{\"role\":\"assistant\",\"parentID\":\"msg_0fa5039cb001hj2qrNREiPP41J\",\"mode\":\"compaction\",\"agent\":\"compaction\",\"summary\":true,\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956815,\"completed\":1790905956823},\"finish\":\"stop\"}"
+ }
+ ],
+ "parts": [
+ {
+ "id": "prt_0fa5034a00010Ws8gM1qalwMDv",
+ "message_id": "msg_0fa50349c001kaMn1c5SsQzezN",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905955756,
+ "time_updated": 1790905955757,
+ "data": "{\"type\":\"text\",\"text\":\"Keep the viewer on the left.\\n\\n> A quote: put the viewer on the right.\\n\\nRead fixture.txt once.\"}"
+ },
+ {
+ "id": "prt_0fa503962001I1PJGXWH9bovgH",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956707,
+ "time_updated": 1790905956707,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa503965001jEZQxHkvcf07Jg",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956709,
+ "time_updated": 1790905956725,
+ "data": "{\"type\":\"tool\",\"tool\":\"read\",\"callID\":\"call_source\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"/fixture/work/fixture.txt\"},\"output\":\"<path>/fixture/work/fixture.txt</path>\\n<type>file</type>\\n<content>\\n1: Synthetic fixture data.\\n\\n(End of file - total 1 lines)\\n</content>\",\"metadata\":{\"preview\":\"Synthetic fixture data.\",\"truncated\":false,\"loaded\":[],\"display\":{\"type\":\"file\",\"path\":\"/fixture/work/fixture.txt\",\"text\":\"Synthetic fixture data.\",\"lineStart\":1,\"lineEnd\":1,\"totalLines\":1,\"truncated\":false}},\"title\":\"fixture.txt\",\"time\":{\"start\":1790905956714,\"end\":1790905956725}}}"
+ },
+ {
+ "id": "prt_0fa503977001nC8pJDeftCt3fW",
+ "message_id": "msg_0fa5035b30017lwXgD8pwSa3Ll",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956728,
+ "time_updated": 1790905956728,
+ "data": "{\"reason\":\"tool-calls\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa50398b001ybownrXnYyDiKp",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956747,
+ "time_updated": 1790905956748,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa50398d0011fCGV6iufRWGUe",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956749,
+ "time_updated": 1790905956750,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956749,\"end\":1790905956750}}"
+ },
+ {
+ "id": "prt_0fa50398f001QeltjQ2ngmVY5f",
+ "message_id": "msg_0fa50397d001CLjiHWGN0PfJ8z",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956751,
+ "time_updated": 1790905956751,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039cb002kJpAdIeb5EMzF7",
+ "message_id": "msg_0fa5039cb001hj2qrNREiPP41J",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956812,
+ "time_updated": 1790905956812,
+ "data": "{\"type\":\"compaction\",\"auto\":false}"
+ },
+ {
+ "id": "prt_0fa5039d30016sH330I921D8gA",
+ "message_id": "msg_0fa5039cf001khN9tojJcmsgp4",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956819,
+ "time_updated": 1790905956819,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039d4001NSKJ2koPE5leXK",
+ "message_id": "msg_0fa5039cf001khN9tojJcmsgp4",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956820,
+ "time_updated": 1790905956821,
+ "data": "{\"type\":\"text\",\"text\":\"Synthetic context summary.\",\"time\":{\"start\":1790905956820,\"end\":1790905956821}}"
+ },
+ {
+ "id": "prt_0fa5039d6001u4GAIgXypqs8Q1",
+ "message_id": "msg_0fa5039cf001khN9tojJcmsgp4",
+ "session_id": "ses_f05afcbd5ffeBNEw6BoVJB5rKC",
+ "time_created": 1790905956822,
+ "time_updated": 1790905956822,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ }
+ ]
+ },
+ "reverted": {
+ "sessions": [
+ {
+ "id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "parent_id": null,
+ "directory": "/fixture/work",
+ "version": "1.18.34",
+ "revert": "{\"messageID\":\"msg_0fa5039ae001XNcEr2DXKyRy7H\"}",
+ "time_created": 1790905956764,
+ "time_updated": 1790905956840
+ }
+ ],
+ "messages": [
+ {
+ "id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955484,
+ "time_updated": 1790905956766,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905955484},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905955763,
+ "time_updated": 1790905956768,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905955763,\"completed\":1790905956731},\"finish\":\"tool-calls\"}"
+ },
+ {
+ "id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956733,
+ "time_updated": 1790905956772,
+ "data": "{\"parentID\":\"msg_0fa50399e001vDporihXz28WNR\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956733,\"completed\":1790905956753},\"finish\":\"stop\"}"
+ },
+ {
+ "id": "msg_0fa5039ae001XNcEr2DXKyRy7H",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956782,
+ "time_updated": 1790905956784,
+ "data": "{\"role\":\"user\",\"time\":{\"created\":1790905956782},\"agent\":\"source_fixture\",\"model\":{\"providerID\":\"fixture\",\"modelID\":\"model\"}}"
+ },
+ {
+ "id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956788,
+ "time_updated": 1790905956800,
+ "data": "{\"parentID\":\"msg_0fa5039ae001XNcEr2DXKyRy7H\",\"role\":\"assistant\",\"mode\":\"source_fixture\",\"agent\":\"source_fixture\",\"path\":{\"cwd\":\"/fixture/work\",\"root\":\"/fixture/work\"},\"cost\":0,\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"modelID\":\"model\",\"providerID\":\"fixture\",\"time\":{\"created\":1790905956788,\"completed\":1790905956799},\"finish\":\"stop\"}"
+ }
+ ],
+ "parts": [
+ {
+ "id": "prt_0fa50399f001XjajkGblzofl1w",
+ "message_id": "msg_0fa50399e001vDporihXz28WNR",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956767,
+ "time_updated": 1790905956767,
+ "data": "{\"type\":\"text\",\"text\":\"Keep the viewer on the left.\\n\\n> A quote: put the viewer on the right.\\n\\nRead fixture.txt once.\"}"
+ },
+ {
+ "id": "prt_0fa5039a1001rCzDT7e3PZVbmS",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956769,
+ "time_updated": 1790905956769,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a2001chJKR00Laavgni",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956770,
+ "time_updated": 1790905956770,
+ "data": "{\"type\":\"tool\",\"tool\":\"read\",\"callID\":\"call_source\",\"state\":{\"status\":\"completed\",\"input\":{\"filePath\":\"/fixture/work/fixture.txt\"},\"output\":\"<path>/fixture/work/fixture.txt</path>\\n<type>file</type>\\n<content>\\n1: Synthetic fixture data.\\n\\n(End of file - total 1 lines)\\n</content>\",\"metadata\":{\"preview\":\"Synthetic fixture data.\",\"truncated\":false,\"loaded\":[],\"display\":{\"type\":\"file\",\"path\":\"/fixture/work/fixture.txt\",\"text\":\"Synthetic fixture data.\",\"lineStart\":1,\"lineEnd\":1,\"totalLines\":1,\"truncated\":false}},\"title\":\"fixture.txt\",\"time\":{\"start\":1790905956714,\"end\":1790905956725}}}"
+ },
+ {
+ "id": "prt_0fa5039a3001Vmq4LrhG2tsFid",
+ "message_id": "msg_0fa5039a0001OXOnNhANZhBHvZ",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956771,
+ "time_updated": 1790905956771,
+ "data": "{\"reason\":\"tool-calls\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039a4002opjulFdqKdSd65",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956772,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039a5001V0z4rbOmk9YijA",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956773,
+ "time_updated": 1790905956773,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956749,\"end\":1790905956750}}"
+ },
+ {
+ "id": "prt_0fa5039a60019Nat1RNmiH0Pm4",
+ "message_id": "msg_0fa5039a4001QdNl0H6zS7VAXK",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956774,
+ "time_updated": 1790905956774,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ },
+ {
+ "id": "prt_0fa5039af001GKUPOUEofBZB10",
+ "message_id": "msg_0fa5039ae001XNcEr2DXKyRy7H",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956784,
+ "time_updated": 1790905956785,
+ "data": "{\"type\":\"text\",\"text\":\"This is a fresh instruction in the fork.\"}"
+ },
+ {
+ "id": "prt_0fa5039ba001lHpOGevTfAVl12",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956794,
+ "time_updated": 1790905956795,
+ "data": "{\"type\":\"step-start\"}"
+ },
+ {
+ "id": "prt_0fa5039bb001O24h6sIunRcjy3",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956795,
+ "time_updated": 1790905956797,
+ "data": "{\"type\":\"text\",\"text\":\"I will keep the viewer on the left.\",\"time\":{\"start\":1790905956795,\"end\":1790905956796}}"
+ },
+ {
+ "id": "prt_0fa5039bd001RyM9U9DbDS8Wwq",
+ "message_id": "msg_0fa5039b4001xxIkQ5rVpVGfBp",
+ "session_id": "ses_f05afc663ffeHwrvZ1zE1756B0",
+ "time_created": 1790905956797,
+ "time_updated": 1790905956798,
+ "data": "{\"reason\":\"stop\",\"type\":\"step-finish\",\"tokens\":{\"input\":0,\"output\":0,\"reasoning\":0,\"cache\":{\"write\":0,\"read\":0}},\"cost\":0}"
+ }
+ ]
+ }
+}
diff --git a/cli/src/memory/capture.ts b/cli/src/memory/capture.ts
index 2061e28a5..a1c891941 100644
--- a/cli/src/memory/capture.ts
+++ b/cli/src/memory/capture.ts
@@ -4,13 +4,16 @@ import { open, type FileHandle } from 'node:fs/promises'
import { z } from 'zod'
import { digest } from './admission.js'
import { decodeMemoryRecord } from './native.js'
+import { OpenCodeMemoryCapture } from './opencodeCapture.js'
import type { MemoryPort } from './operations.js'
import { MemoryError, type SourceEvent } from './types.js'
export interface CaptureSession {
- profileId: string; projectId: string | null; engine: 'claude' | 'codex'; sessionId: string
- /** Bound by the host registry, never copied from a model-supplied path. */
+ profileId: string; projectId: string | null; engine: 'claude' | 'codex' | 'opencode'; sessionId: string
+ /** Native JSONL or SQLite source, bound by the host, never copied from a model-supplied path. */
transcriptPath: string
+ /** Required for SQLite sources to verify native session identity against the host. */
+ workspace?: string
busy: boolean
/** Host-observed fork/private-mode boundary. Copied older turns are not fresh user statements. */
liveFrom?: number
@@ -36,7 +39,8 @@ export class NativeMemoryCapture {
const streamId = digest([session.profileId, session.engine, session.sessionId])
const pending = this.active.get(streamId)
if (pending) return pending
- const operation = this.read(session, streamId).finally(() => this.active.delete(streamId))
+ const operation = (session.engine === 'opencode' ? new OpenCodeMemoryCapture(this.memory, this.now).poll(session, streamId)
+ : this.read(session, streamId)).finally(() => this.active.delete(streamId))
this.active.set(streamId, operation)
return operation
}
@@ -103,7 +107,7 @@ export class NativeMemoryCapture {
const line = await frame(handle, cursor.o, stat.size, cursor.s)
if (!line) break // A partial UTF-8/JSON record is left intact for the next append.
const record = line.text === null ? { parts: [], ended: false, incomplete: true } : line.text.trim()
- ? decodeMemoryRecord(session.engine, line.text) : { parts: [], ended: false, incomplete: false }
+ ? decodeMemoryRecord(session.engine as 'claude' | 'codex', line.text) : { parts: [], ended: false, incomplete: false }
const events: SourceEvent[] = record.parts.filter(part => part.observedAt >= notBefore).map(part => {
const id = digest([session.profileId, session.engine, session.sessionId, part.nativeEventId])
return { ...part, id, profileId: session.profileId, projectId: session.projectId, engine: session.engine,
diff --git a/cli/src/memory/hostSessions.spec.ts b/cli/src/memory/hostSessions.spec.ts
index 370b9f908..bcc6ea9e9 100644
--- a/cli/src/memory/hostSessions.spec.ts
+++ b/cli/src/memory/hostSessions.spec.ts
@@ -43,6 +43,19 @@ it('uses personal scope only for the current verified collection conversation, n
expect(roster.refresh([], no, no, 'another_agent')).toEqual([])
})
+it('binds OpenCode to the host database and includes only the verified collection conversation in personal scope', () => {
+ const roster = new MemorySessionRoster('/home/person', Date.now, { opencode: '/native/opencode.db' })
+ const companion = { ...session, engine: 'opencode', transcriptPath: null, dsh: 'autonomous/pair' }
+ expect(roster.refresh([companion], no, no)).toEqual([])
+ expect(roster.refresh([companion], no, no, 'agent')).toMatchObject([
+ { engine: 'opencode', scope: 'profile', transcriptPath: '/native/opencode.db', sessionId: 'native' },
+ ])
+ expect(roster.refresh([{ ...companion, transcriptPath: '/model/supplied/path' }], no, no, 'agent')[0].transcriptPath)
+ .toBe('/native/opencode.db')
+ expect(roster.refresh([companion], no, () => true, 'agent')).toEqual([])
+ expect(new MemorySessionRoster('/home/person').refresh([companion], no, no, 'agent')).toEqual([])
+})
+
it('recognizes fresh requests in both native event formats without treating their streamed replies as new activity', () => {
const claude = newTurnState()
const user = lineToEvents(JSON.stringify({ type: 'user', uuid: 'question', message: { role: 'user', content: 'Fix the parser.' } }), claude)
diff --git a/cli/src/memory/hostSessions.ts b/cli/src/memory/hostSessions.ts
index adc614342..96013fdf4 100644
--- a/cli/src/memory/hostSessions.ts
+++ b/cli/src/memory/hostSessions.ts
@@ -21,7 +21,8 @@ const CODING_DSHS = new Set(['autonomous/web-studio', 'autonomous/firmware-studi
/** A short grace period finishes native records after a process exits, without scanning archives. */
export class MemorySessionRoster {
private readonly recent = new Map<string, { session: MemoryHostSession; seenAt: number }>()
- constructor(private readonly home: string, private readonly now: () => number = Date.now) {}
+ constructor(private readonly home: string, private readonly now: () => number = Date.now,
+ private readonly nativeSources: { opencode?: string } = {}) {}
refresh(live: RegisteredMemorySession[], busy: (sessionId: string) => boolean, subagent: (sessionId: string) => boolean,
collectionAgentId: string | null = null): MemoryHostSession[] {
@@ -29,15 +30,17 @@ export class MemorySessionRoster {
const current = new Set<string>()
for (const session of live) {
const companion = session.dsh === 'autonomous/pair' && session.agentId === collectionAgentId
- if (!['claude', 'codex'].includes(session.engine) || !session.sessionId || !session.cwd || !session.transcriptPath
- || !isAbsolute(session.cwd) || !isAbsolute(session.transcriptPath) || subagent(session.sessionId)
+ // OpenCode keeps all conversations in a host-configured SQLite store. It has no JSONL path.
+ const transcriptPath = session.engine === 'opencode' ? this.nativeSources.opencode : session.transcriptPath
+ if (!['claude', 'codex', 'opencode'].includes(session.engine) || !session.sessionId || !session.cwd || !transcriptPath
+ || !isAbsolute(session.cwd) || !isAbsolute(transcriptPath) || subagent(session.sessionId)
|| (session.dsh && !companion && !CODING_DSHS.has(session.dsh)) || resolve(session.cwd) === resolve(this.home)
|| resolve(session.cwd) === parse(resolve(session.cwd)).root) continue
current.add(session.agentId)
this.recent.set(session.agentId, { seenAt: this.now(), session: { agentId: session.agentId,
name: session.title || session.defaultName, present: true,
- engine: session.engine as 'claude' | 'codex', sessionId: session.sessionId, workspace: session.cwd,
- transcriptPath: session.transcriptPath, coding: true, busy: busy(session.sessionId), scope: companion ? 'profile' : 'project',
+ engine: session.engine as MemoryHostSession['engine'], sessionId: session.sessionId, workspace: session.cwd,
+ transcriptPath, coding: true, busy: busy(session.sessionId), scope: companion ? 'profile' : 'project',
...(session.cliVersion ? { cliVersion: session.cliVersion } : {}),
...(session.forkedFrom ? { liveFrom: session.registeredAt } : {}) } })
}
diff --git a/cli/src/memory/native.ts b/cli/src/memory/native.ts
index 49a7ad10e..6a281c258 100644
--- a/cli/src/memory/native.ts
+++ b/cli/src/memory/native.ts
@@ -23,21 +23,7 @@ export function decodeMemoryRecord(engine: 'claude' | 'codex', text: string): Na
result.parts.push({ nativeEventId: digest([engine, native, index++, role]), role, text: value, observedAt: at })
}
const user = (value: string): void => {
- const kind = askKind(value)
- if (kind === 'notice') return
- if (kind === 'agent') { add('reference', value); return }
- const cleaned = stripBashModeBlocks(stripSystemBlocks(stripContextSummary(personAsk(value)) ?? ''))
- .replace(/<(?:environment_context|user_instructions|user-prompt-submit-hook|turn_aborted)>[\s\S]*?<\/(?:environment_context|user_instructions|user-prompt-submit-hook|turn_aborted)>/g, '')
- // Fenced code, block quotes, and explicit paste regions retain a separate, lower-trust role.
- // Other ambiguous quotations remain an extraction judgement, never proven personal preference by this parser.
- const quoted = /<pasted_content\b[^>]*>[\s\S]*?<\/pasted_content>|^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*(?:\n|$)|^(?:[ \t]*>[^\n]*(?:\n|$))+/gm
- let end = 0
- for (const match of cleaned.matchAll(quoted)) {
- add('user', cleaned.slice(end, match.index))
- add('reference', match[0])
- end = match.index! + match[0].length
- }
- add('user', cleaned.slice(end))
+ for (const part of memoryUserParts(value)) add(part.role, part.text)
}
if (engine === 'claude') {
@@ -81,6 +67,25 @@ export function decodeMemoryRecord(engine: 'claude' | 'codex', text: string): Na
return result
}
+/** Shared role boundaries for native user text; provider-specific synthetic flags are checked first. */
+export function memoryUserParts(value: string): Array<{ role: 'user' | 'reference'; text: string }> {
+ const kind = askKind(value)
+ if (kind === 'notice') return []
+ if (kind === 'agent') return [{ role: 'reference', text: value }]
+ const cleaned = stripBashModeBlocks(stripSystemBlocks(stripContextSummary(personAsk(value)) ?? ''))
+ .replace(/<(?:environment_context|user_instructions|user-prompt-submit-hook|turn_aborted)>[\s\S]*?<\/(?:environment_context|user_instructions|user-prompt-submit-hook|turn_aborted)>/g, '')
+ // Pasted/fenced material is evidence about its contents, not a preference of the person quoting it.
+ const quoted = /<pasted_content\b[^>]*>[\s\S]*?<\/pasted_content>|^(```|~~~)[^\n]*\n[\s\S]*?^\1[^\n]*(?:\n|$)|^(?:[ \t]*>[^\n]*(?:\n|$))+/gm
+ const result: Array<{ role: 'user' | 'reference'; text: string }> = []
+ let end = 0
+ for (const match of cleaned.matchAll(quoted)) {
+ result.push({ role: 'user', text: cleaned.slice(end, match.index) }, { role: 'reference', text: match[0] })
+ end = match.index! + match[0].length
+ }
+ result.push({ role: 'user', text: cleaned.slice(end) })
+ return result.filter(part => part.text.trim())
+}
+
function object(value: unknown): Record<string, unknown> {
return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
}
diff --git a/cli/src/memory/opencodeCapture.spec.ts b/cli/src/memory/opencodeCapture.spec.ts
new file mode 100644
index 000000000..6f57b42b4
--- /dev/null
+++ b/cli/src/memory/opencodeCapture.spec.ts
@@ -0,0 +1,241 @@
+import { createRequire } from 'node:module'
+import { execFileSync } from 'node:child_process'
+import { mkdtempSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { closeSqliteHandles, overrideBuiltinSqlite } from '../lib/sqliteRead.js'
+import { NativeMemoryCapture, type CaptureSession } from './capture.js'
+import { CodingMemoryStore } from './store.js'
+import type { Database } from './database.js'
+import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from './operations.js'
+import { decodeOpenCodeMemoryMessage } from './opencodeSource.js'
+import { readOpenCodeMemoryMessage } from './opencodeRead.js'
+
+const { DatabaseSync } = createRequire(import.meta.url)('node:sqlite') as { DatabaseSync: new (path: string) => Database }
+const hasSqliteCli = (() => { try { execFileSync('sqlite3', ['-version'], { stdio: 'ignore' }); return true } catch { return false } })()
+interface MessageRow { id: string; session_id: string; time_created: number; time_updated: number; data: string }
+interface Snapshot {
+ sessions: Array<{ id: string; parent_id: string | null; directory: string; version: string; revert: string | null; time_created: number; time_updated: number }>
+ messages: MessageRow[]
+ parts: Array<MessageRow & { message_id: string }>
+}
+const recorded = JSON.parse(readFileSync(new URL('./__fixtures__/opencode-1.18.34-source.json', import.meta.url), 'utf8')) as {
+ turn: Snapshot; copied: Snapshot; forkWithNewTurn: Snapshot; compaction: Snapshot; reverted: Snapshot
+}
+const target = { state: 'ready' as const, key: 'selected' }
+let directory: string, workspace: string, db: Database, store: CodingMemoryStore, memory: MemoryPort
+let capture: NativeMemoryCapture, session: CaptureSession, now: number, serial: number
+
+function createDatabase() {
+ db = new DatabaseSync(session.transcriptPath)
+ // Columns and contents recorded from 1.18.34; unrelated native tables are not used by capture.
+ db.exec(`PRAGMA journal_mode=WAL;
+ CREATE TABLE session(id TEXT PRIMARY KEY,parent_id TEXT,directory TEXT,version TEXT,revert TEXT,time_created INTEGER,time_updated INTEGER);
+ CREATE TABLE message(id TEXT PRIMARY KEY,session_id TEXT,time_created INTEGER,time_updated INTEGER,data TEXT);
+ CREATE INDEX messages_session ON message(session_id);
+ CREATE TABLE part(id TEXT PRIMARY KEY,session_id TEXT,message_id TEXT,time_created INTEGER,time_updated INTEGER,data TEXT);
+ CREATE INDEX parts_message ON part(message_id);`)
+}
+function insert(snapshot: Snapshot) {
+ for (const row of snapshot.sessions) db.prepare('INSERT OR REPLACE INTO session VALUES(?,?,?,?,?,?,?)')
+ .run(row.id, row.parent_id, workspace, row.version, row.revert, row.time_created, row.time_updated)
+ for (const row of snapshot.messages) db.prepare('INSERT OR REPLACE INTO message VALUES(?,?,?,?,?)')
+ .run(row.id, row.session_id, row.time_created, row.time_updated, row.data)
+ for (const row of snapshot.parts) db.prepare('INSERT OR REPLACE INTO part VALUES(?,?,?,?,?,?)')
+ .run(row.id, row.session_id, row.message_id, row.time_created, row.time_updated, row.data)
+}
+function sources() {
+ const result = store.learning.claim(target)
+ if (result.state !== 'claimed') throw new Error(result.state)
+ store.learning.finish(result.lease, [], target)
+ return result.lease
+}
+function append(text: string, at = now + 1) {
+ const suffix = `_${++serial}`
+ const user = recorded.turn.messages.find(row => JSON.parse(row.data).role === 'user')!
+ const answer = recorded.turn.messages.at(-1)!
+ const userPart = recorded.turn.parts.find(row => row.message_id === user.id)!
+ const answerPart = recorded.turn.parts.find(row => row.message_id === answer.id && JSON.parse(row.data).type === 'text')!
+ const copy: Snapshot = { sessions: [], messages: [
+ { ...user, id: user.id + suffix, session_id: session.sessionId, time_created: at, time_updated: at,
+ data: JSON.stringify({ ...JSON.parse(user.data), time: { created: at } }) },
+ { ...answer, id: answer.id + suffix, session_id: session.sessionId, time_created: at + 1, time_updated: at + 2,
+ data: JSON.stringify({ ...JSON.parse(answer.data), parentID: user.id + suffix, time: { created: at + 1, completed: at + 2 } }) },
+ ], parts: [
+ { ...userPart, id: userPart.id + suffix, session_id: session.sessionId, message_id: user.id + suffix, time_created: at, time_updated: at,
+ data: JSON.stringify({ type: 'text', text }) },
+ { ...answerPart, id: answerPart.id + suffix, session_id: session.sessionId, message_id: answer.id + suffix, time_created: at + 1, time_updated: at + 2,
+ data: JSON.stringify({ type: 'text', text: 'Understood.', time: { start: at + 1, end: at + 2 } }) },
+ ] }
+ insert(copy)
+ return copy
+}
+
+beforeEach(() => {
+ directory = realpathSync(mkdtempSync(join(tmpdir(), 'memory-opencode-capture-')))
+ workspace = join(directory, 'project'); mkdirSync(workspace)
+ now = recorded.turn.sessions[0].time_created - 1000; serial = 0
+ session = { profileId: 'owner', projectId: 'project', engine: 'opencode', sessionId: recorded.turn.sessions[0].id,
+ transcriptPath: join(directory, 'opencode.db'), workspace, busy: true }
+ createDatabase(); insert(recorded.turn)
+ const opened = CodingMemoryStore.open({ directory: join(directory, 'memory'), profileId: 'owner', now: () => now })
+ if (!opened.ok) throw new Error(opened.reason)
+ store = opened.store; store.registerProject('project'); store.setControls({ learn: true, recall: true })
+ memory = { async request<K extends Operation>(operation: K, args: Arguments<K>): Promise<Result<K>> {
+ const receiver = (QUEUE_OPERATIONS as readonly string[]).includes(operation) ? store.learning : store
+ return (receiver as unknown as Record<string, (...args: unknown[]) => unknown>)[operation].apply(receiver, args) as Result<K>
+ } }
+ capture = new NativeMemoryCapture(memory, () => now)
+})
+afterEach(() => {
+ closeSqliteHandles(); overrideBuiltinSqlite(undefined); db.close(); store.close()
+ rmSync(directory, { recursive: true, force: true })
+})
+
+for (const path of ['builtin', 'cli']) it.skipIf(path === 'cli' && !hasSqliteCli)(`captures recorded native roles and resumes without replay through ${path} SQLite`, async () => {
+ if (path === 'cli') overrideBuiltinSqlite(null)
+ expect(await capture.poll(session)).toEqual({ state: 'captured', sources: 6 })
+ const lease = sources()
+ expect(lease.sources.map(row => row.role)).toEqual(['user', 'reference', 'user', 'assistant', 'tool', 'assistant'])
+ expect(lease.sources.every(row => row.engine === 'opencode' && !row.verification)).toBe(true)
+ expect(lease.sources[4].text).toContain('Synthetic fixture data.')
+ expect(lease.episodes.map(episode => episode.context)).toEqual(['complete'])
+ capture = new NativeMemoryCapture(memory, () => now)
+ expect(await capture.poll(session)).toEqual({ state: 'idle', sources: 0 })
+})
+
+it('waits for the native streaming reply to finish before advancing past it', async () => {
+ const reply = recorded.turn.messages.at(-1)!, part = recorded.turn.parts.find(row => row.message_id === reply.id && JSON.parse(row.data).type === 'text')!
+ const data = JSON.parse(reply.data); delete data.time.completed
+ db.prepare('UPDATE message SET data=? WHERE id=?').run(JSON.stringify(data), reply.id)
+ const text = JSON.parse(part.data); delete text.time.end
+ db.prepare('UPDATE part SET data=? WHERE id=?').run(JSON.stringify(text), part.id)
+ expect((await capture.poll(session)).sources).toBe(5)
+ expect(store.learning.claim(target).state).toBe('idle')
+ capture = new NativeMemoryCapture(memory, () => now)
+ expect((await capture.poll(session)).sources).toBe(0)
+ db.prepare('UPDATE message SET data=? WHERE id=?').run(reply.data, reply.id)
+ db.prepare('UPDATE part SET data=? WHERE id=?').run(part.data, part.id)
+ expect((await capture.poll(session)).sources).toBe(1)
+ expect(sources().sources).toHaveLength(6)
+})
+
+it('does not borrow another engine\'s completion marker when deciding that context is complete', async () => {
+ const reply = recorded.turn.messages.at(-1)!
+ const data = JSON.parse(reply.data); data.finish = 'end-turn'
+ db.prepare('UPDATE message SET data=? WHERE id=?').run(JSON.stringify(data), reply.id)
+ await capture.poll({ ...session, busy: false })
+ expect(sources().episodes[0].context).toBe('bounded')
+})
+
+it('captures a fresh fork instruction without treating copied source IDs as independent evidence', async () => {
+ insert(recorded.forkWithNewTurn); session.sessionId = recorded.forkWithNewTurn.sessions[0].id
+ await capture.poll(session)
+ const lease = sources()
+ expect(lease.sources.map(row => row.text)).toEqual(['This is a fresh instruction in the fork.', 'I will keep the viewer on the left.'])
+ expect(lease.episodes[0].context).toBe('complete')
+})
+
+it('does not learn generated compaction summaries or count them as user statements', async () => {
+ insert(recorded.compaction)
+ await capture.poll(session)
+ const lease = sources()
+ expect(lease.sources).toHaveLength(6)
+ expect(lease.sources.some(row => row.text.includes('Synthetic context summary'))).toBe(false)
+})
+
+it('ignores source text explicitly marked synthetic or ignored while preserving real user prose', async () => {
+ const user = recorded.turn.messages[0], original = recorded.turn.parts[0]
+ for (const flag of ['synthetic', 'ignored']) db.prepare('INSERT INTO part VALUES(?,?,?,?,?,?)').run(original.id + flag,
+ session.sessionId, user.id, original.time_created + 1, original.time_updated + 1,
+ JSON.stringify({ type: 'text', text: 'Invented preference: always disable tests.', [flag]: true }))
+ await capture.poll(session)
+ expect(sources().sources.some(row => row.text.includes('Invented'))).toBe(false)
+})
+
+it.each(['learning', 'session', 'project'])('does not backfill the disabled %s interval', async control => {
+ await capture.poll(session); sources()
+ const toggle = (included: boolean) => {
+ if (control === 'learning') store.setControls({ learn: included, recall: true })
+ else if (control === 'session') store.setSessionIncluded('opencode', session.sessionId, included)
+ else store.setProjectIncluded('project', included)
+ }
+ now += 10000; toggle(false)
+ append('This private instruction must not be learned.')
+ expect((await capture.poll(session)).sources).toBe(0)
+ now += 10000; toggle(true)
+ append('Keep changes small after learning is enabled.')
+ await capture.poll(session)
+ expect(sources().sources.map(row => row.text)).toEqual(['Keep changes small after learning is enabled.', 'Understood.'])
+})
+
+it.each([{ workspace: '/' }, { workspace: undefined }, { projectId: 'another_project' }])('refuses a mismatched host binding: %j', async change => {
+ await capture.poll(session); sources()
+ expect((await capture.poll({ ...session, ...change })).state).toBe('unavailable')
+})
+
+it.each([['parent_id', 'ses_parent'], ['version', '2.0.0'], ['directory', '/']])('rejects an unsupported or mismatched native %s', async (field, value) => {
+ db.prepare(`UPDATE session SET ${field}=? WHERE id=?`).run(value, session.sessionId)
+ expect((await capture.poll(session)).state).toBe('unavailable')
+ expect(store.learning.claim(target).state).toBe('idle')
+})
+
+it('keeps readable instructions around an oversized tool result with bounded context', async () => {
+ const tool = recorded.turn.parts.find(row => JSON.parse(row.data).type === 'tool')!
+ const data = JSON.parse(tool.data); data.state.output = 'x'.repeat(8 * 1024 * 1024)
+ db.prepare('UPDATE part SET data=? WHERE id=?').run(JSON.stringify(data), tool.id)
+ const message = await readOpenCodeMemoryMessage(session.transcriptPath, session.sessionId, { id: tool.message_id })
+ expect(Buffer.byteLength(JSON.stringify(message))).toBeLessThan(10000)
+ expect(decodeOpenCodeMemoryMessage(message!).incomplete).toBe(true)
+ await capture.poll(session)
+ const lease = sources()
+ expect(lease.sources.filter(row => row.role === 'user').map(row => row.text.trim()))
+ .toEqual(['Keep the viewer on the left.', 'Read fixture.txt once.'])
+ expect(lease.episodes.every(episode => episode.context === 'bounded')).toBe(true)
+ now += 20000; append('A fresh complete turn after the large output.')
+ await capture.poll(session)
+ expect(sources().episodes[0].context).toBe('complete')
+})
+
+it('bounds the combined size and number of native parts before loading them into the host', async () => {
+ const user = recorded.turn.messages[0]
+ for (let index = 0; index < 100; index++) db.prepare('INSERT INTO part VALUES(?,?,?,?,?,?)').run(`prt_bulk_${index}`,
+ session.sessionId, user.id, user.time_created + index + 1, user.time_updated,
+ JSON.stringify({ type: 'text', text: 'x'.repeat(30000) }))
+ const message = await readOpenCodeMemoryMessage(session.transcriptPath, session.sessionId, { id: user.id })
+ expect(message!.parts).toHaveLength(65)
+ expect(Buffer.byteLength(JSON.stringify(message))).toBeLessThan(105000)
+ expect(decodeOpenCodeMemoryMessage(message!).incomplete).toBe(true)
+ expect((await capture.poll(session)).state).toBe('captured')
+})
+
+it('keeps a monotonic cursor across undo cleanup and captures the next fresh request', async () => {
+ await capture.poll(session); sources()
+ const last = recorded.turn.messages.at(-1)!
+ db.prepare('UPDATE session SET revert=? WHERE id=?').run(JSON.stringify({ messageID: last.id }), session.sessionId)
+ expect((await capture.poll(session)).reason).toBe('native_session_reverted')
+ db.prepare('DELETE FROM message WHERE id=?').run(last.id)
+ db.prepare('DELETE FROM part WHERE message_id=?').run(last.id)
+ db.prepare('UPDATE session SET revert=NULL WHERE id=?').run(session.sessionId)
+ now += 20000; append('A new request after undo.')
+ expect((await capture.poll(session)).state).toBe('source_changed')
+ expect((await capture.poll(session)).sources).toBe(2)
+ expect(sources().sources.map(row => row.text)).toEqual(['A new request after undo.', 'Understood.'])
+})
+
+it('does not replay a replaced native database but can capture new messages after its baseline', async () => {
+ await capture.poll(session); sources()
+ closeSqliteHandles(); db.close(); renameSync(session.transcriptPath, join(directory, 'old.db'))
+ createDatabase(); insert(recorded.turn)
+ expect((await capture.poll(session)).reason).toBe('native_store_replaced')
+ now += 20000; append('Only new requests after the database was replaced.')
+ expect((await capture.poll(session)).sources).toBe(2)
+ expect(sources().sources[0].text).toContain('Only new requests')
+})
+
+it('does not read another session from the same database', async () => {
+ insert(recorded.forkWithNewTurn)
+ await capture.poll(session)
+ expect(sources().sources.every(row => row.sessionId === session.sessionId && !row.text.includes('fresh instruction in the fork'))).toBe(true)
+})
diff --git a/cli/src/memory/opencodeCapture.ts b/cli/src/memory/opencodeCapture.ts
new file mode 100644
index 000000000..2720dd793
--- /dev/null
+++ b/cli/src/memory/opencodeCapture.ts
@@ -0,0 +1,142 @@
+/** Incremental capture of a single host-registered OpenCode SQLite conversation. */
+import { randomUUID } from 'node:crypto'
+import { realpath, stat } from 'node:fs/promises'
+import { isAbsolute } from 'node:path'
+import { z } from 'zod'
+import { digest } from './admission.js'
+import type { CaptureOutcome, CaptureSession } from './capture.js'
+import type { MemoryPort } from './operations.js'
+import { decodeOpenCodeMemoryMessage, openCodeMessageSettled, type OpenCodeSourceMessage } from './opencodeSource.js'
+import { openCodeMemoryTail, readOpenCodeMemoryMessage, readOpenCodeMemorySession } from './opencodeRead.js'
+import { MemoryError, type SourceEvent } from './types.js'
+
+const integer = z.number().int().nonnegative().safe()
+const cursorSchema = z.object({ v: z.literal(2), f: z.string().length(24), t: integer,
+ m: z.string().max(64).regex(/^[A-Za-z0-9_]*$/), a: z.string().length(16), e: z.string().uuid().nullable(),
+ l: integer, q: integer, p: integer, g: z.boolean(), n: integer, b: integer }).strict()
+type Cursor = z.infer<typeof cursorSchema>
+type Boundary = 'open' | 'complete' | 'bounded' | 'incomplete'
+function anchor(message: OpenCodeSourceMessage | null): string {
+ // Later replies change settlement, not the already acknowledged source payload.
+ return digest(message && [message.id, message.created, message.updated, message.data, message.parts]).slice(0, 16)
+}
+
+export class OpenCodeMemoryCapture {
+ constructor(private readonly memory: MemoryPort, private readonly now: () => number = Date.now) {}
+
+ /** NativeMemoryCapture serializes calls per owner/engine/session, including this adapter. */
+ async poll(session: CaptureSession, streamId: string): Promise<CaptureOutcome> {
+ let captured = 0
+ try {
+ const controls = await this.memory.request('capturePolicy', [session.projectId, session.engine, session.sessionId])
+ if (!controls.learn) return { state: 'learning_off', sources: 0 }
+ if (!controls.included) return { state: 'unavailable', sources: 0, reason: 'source_ineligible' }
+ if (!session.workspace || !isAbsolute(session.workspace) || !isAbsolute(session.transcriptPath)) throw new MemoryError('source_ineligible')
+ if (session.liveFrom !== undefined && !integer.safeParse(session.liveFrom).success) throw new MemoryError('invalid_capture_boundary')
+ const native = await readOpenCodeMemorySession(session.transcriptPath, session.sessionId)
+ if (native.parent_id || await realpath(native.directory) !== await realpath(session.workspace)) throw new MemoryError('source_ineligible')
+ // Forks mint fresh row IDs and SQL timestamps but retain message.time.created. Neither
+ // a copied fork nor a generated compaction summary is independent personal evidence.
+ const notBefore = Math.max(controls.learnSince ?? Infinity, controls.liveFrom, session.liveFrom ?? 0, native.time_created)
+ const source = await stat(session.transcriptPath)
+ if (!source.isFile()) throw new MemoryError('source_unavailable')
+ const identity = digest([source.dev, source.ino, source.birthtimeMs, native.time_created, native.directory]).slice(0, 24)
+ let raw = await this.memory.request('cursor', [streamId])
+ let cursor: Cursor | null = null
+ if (raw) {
+ try { cursor = cursorSchema.parse(JSON.parse(raw)) } catch { throw new MemoryError('capture_cursor_invalid') }
+ }
+ const base = { streamId, engine: session.engine, sessionId: session.sessionId, projectId: session.projectId, generation: controls.generation }
+ const commit = async (next: Cursor, events: SourceEvent[] = [], boundary: Boundary = 'open', episode?: string): Promise<void> => {
+ const to = JSON.stringify(next), episodeId = episode ?? cursor?.e ?? next.e
+ if (raw === to && !events.length) return
+ if (episodeId) await this.memory.request('capture', [{ ...base, from: raw, to, episodeId, events, boundary }])
+ else await this.memory.request('checkpoint', [{ ...base, from: raw, to }])
+ raw = to; cursor = next
+ }
+ const seal = async (boundary: Exclude<Boundary, 'open'>): Promise<void> => {
+ if (!cursor?.e) return
+ await commit({ ...cursor, e: null, n: 0, b: 0, g: true }, [], boundary === 'complete' && cursor.g ? 'bounded' : boundary)
+ }
+ if (cursor?.e && !await this.memory.request('episodeOpen', [streamId, cursor.e])) {
+ const next = { ...cursor, e: null, n: 0, b: 0, g: true }, to = JSON.stringify(next)
+ await this.memory.request('checkpoint', [{ ...base, from: raw, to }]); cursor = next; raw = to
+ }
+ const replaced = cursor && cursor.f !== identity
+ const paused = cursor && (cursor.l !== controls.captureEpoch || cursor.q !== controls.sessionEpoch || cursor.p !== controls.projectEpoch)
+ if (!cursor || replaced || paused) {
+ if (cursor?.e) await seal('incomplete')
+ const position = replaced ? await openCodeMemoryTail(session.transcriptPath, session.sessionId)
+ : cursor ? { t: cursor.t, m: cursor.m } : { t: Math.max(0, notBefore - 1), m: '' }
+ const last = position.m ? await readOpenCodeMemoryMessage(session.transcriptPath, session.sessionId, { id: position.m }) : null
+ await commit({ v: 2, f: identity, ...position, a: anchor(last), e: null,
+ l: controls.captureEpoch, q: controls.sessionEpoch, p: controls.projectEpoch, g: true, n: 0, b: 0 })
+ if (replaced) return { state: 'source_changed', sources: 0, reason: 'native_store_replaced' }
+ }
+ if (!cursor) throw new MemoryError('capture_cursor_invalid')
+ // Native undo removes messages/parts after a boundary. Wait for its cleanup; do not copy a
+ // reverted tail, reset the high-water mark, or lose the next fresh instruction after undo.
+ if (native.revert) {
+ await seal('incomplete')
+ return { state: 'unavailable', sources: 0, reason: 'native_session_reverted' }
+ }
+ if (cursor.m) {
+ const last = await readOpenCodeMemoryMessage(session.transcriptPath, session.sessionId, { id: cursor.m })
+ if (anchor(last) !== cursor.a) {
+ await seal('incomplete')
+ await commit({ ...cursor, a: anchor(last), g: true })
+ return { state: 'source_changed', sources: 0, reason: 'native_message_rewritten' }
+ }
+ }
+ let bytesRead = 0
+ for (let count = 0; count < 16 && bytesRead < 1024 * 1024; count++) {
+ const message = await readOpenCodeMemoryMessage(session.transcriptPath, session.sessionId, cursor)
+ if (!message) {
+ // Native completion normally closes the episode. An interrupted/crashed process has
+ // only bounded context; inactivity must never manufacture a completed assistant turn.
+ if (cursor.e && !session.busy) await seal('bounded')
+ break
+ }
+ if (!openCodeMessageSettled(message, session.busy, this.now())) break
+ bytesRead += Buffer.byteLength(JSON.stringify(message))
+ const record = decodeOpenCodeMemoryMessage(message)
+ const position = { t: message.created, m: message.id, a: anchor(message) }
+ if (record.observedAt !== null && record.observedAt < notBefore) {
+ await seal('incomplete')
+ await commit({ ...cursor, ...position, g: true })
+ continue
+ }
+ const guard = await readOpenCodeMemorySession(session.transcriptPath, session.sessionId)
+ const current = await stat(session.transcriptPath)
+ if (guard.revert || guard.parent_id || guard.directory !== native.directory || guard.time_created !== native.time_created
+ || current.ino !== source.ino || current.dev !== source.dev) throw new MemoryError('source_changed')
+ if (record.compacted) {
+ await seal('bounded')
+ await commit({ ...cursor, ...position, g: true })
+ continue
+ }
+ const events: SourceEvent[] = []
+ let bytes = 0
+ for (const part of record.parts) {
+ const id = digest([session.profileId, session.engine, session.sessionId, part.nativeEventId])
+ const event: SourceEvent = { ...part, id, profileId: session.profileId, projectId: session.projectId,
+ engine: session.engine, sessionId: session.sessionId, rootIds: [id], eligibility: 'coding' }
+ const size = Buffer.byteLength(JSON.stringify(event))
+ if (events.length >= 64 || bytes + size > 90_000) { record.incomplete = true; continue }
+ events.push(event); bytes += size
+ }
+ if (cursor.e && (record.started || record.incomplete || cursor.n + events.length > 128 || cursor.b + bytes > 90_000)) await seal('bounded')
+ const gap = (record.started ? false : cursor.g) || record.incomplete
+ const episode = cursor.e ?? (events.length ? randomUUID() : null)
+ const next: Cursor = { ...cursor, ...position, e: episode, g: gap, n: cursor.n + events.length, b: cursor.b + bytes }
+ const close = record.ended || record.incomplete
+ await commit(close ? { ...next, e: null, n: 0, b: 0, g: true } : next, events,
+ close ? gap ? 'bounded' : 'complete' : 'open', episode ?? undefined)
+ captured += events.length
+ }
+ return { state: captured ? 'captured' : 'idle', sources: captured }
+ } catch (error) {
+ return { state: 'unavailable', sources: captured, reason: error instanceof MemoryError ? error.code : 'source_unavailable' }
+ }
+ }
+}
diff --git a/cli/src/memory/opencodeRead.ts b/cli/src/memory/opencodeRead.ts
new file mode 100644
index 000000000..fb1fdef27
--- /dev/null
+++ b/cli/src/memory/opencodeRead.ts
@@ -0,0 +1,70 @@
+/** Bounded, read-only access to one host-bound OpenCode session. Never loads the live UI's clipped text. */
+import { z } from 'zod'
+import { sqliteReadAll, type SqliteParam } from '../lib/sqliteRead.js'
+import { MemoryError } from './types.js'
+import type { OpenCodeSourceMessage } from './opencodeSource.js'
+
+const time = z.number().int().nonnegative()
+const nativeId = z.string().min(1).max(64).regex(/^[a-zA-Z0-9_]+$/)
+const sessionSchema = z.object({ parent_id: z.string().max(200).nullable(), directory: z.string().min(1).max(4096),
+ version: z.literal('1.18.34'), time_created: time, revert: z.string().max(2048).nullable() })
+const messageSchema = z.object({ id: nativeId, created: time, updated: time, data: z.string().max(64000).nullable(),
+ parts: z.array(z.object({ id: nativeId, created: time, updated: time, data: z.string().max(64000).nullable() })).max(65),
+ hasReply: z.boolean(), hasLaterUser: z.boolean() })
+
+async function query(path: string, sql: string, params: SqliteParam[]) {
+ const result = await sqliteReadAll(path, sql, params, { maxBuffer: 768 * 1024, cliTimeoutMs: 1000 })
+ if (!result.ok) throw new MemoryError('source_unavailable')
+ return result.rows
+}
+
+export async function readOpenCodeMemorySession(path: string, id: string) {
+ const [row] = await query(path, `SELECT parent_id,substr(directory,1,4097) AS directory,
+ substr(version,1,32) AS version,time_created,substr(revert,1,2049) AS revert FROM session WHERE id=?`, [id])
+ const parsed = sessionSchema.safeParse(row)
+ if (!parsed.success) throw new MemoryError('native_source_unsupported')
+ return parsed.data
+}
+
+// Bound both row count and JSON bytes in SQL. sqliteReadAll's in-process path has no stdout cap.
+// One huge tool result gets a null marker; it cannot consume the budget of subsequent small parts.
+const parts = `selected_parts AS (
+ SELECT id,time_created,time_updated,CASE WHEN length(CAST(data AS BLOB))<=64000 THEN data END AS data
+ FROM part WHERE session_id=? AND message_id=(SELECT id FROM candidate)
+ ORDER BY time_created,id LIMIT 65
+), weighted_parts AS (
+ SELECT *,SUM(COALESCE(length(CAST(data AS BLOB)),0)) OVER (ORDER BY time_created,id) AS bytes FROM selected_parts
+)
+SELECT m.id,m.time_created AS created,m.time_updated AS updated,
+ CASE WHEN length(CAST(m.data AS BLOB))<=64000 THEN m.data END AS data,
+ (SELECT json_group_array(json_object('id',id,'created',time_created,'updated',time_updated,
+ 'data',CASE WHEN bytes<=96000 THEN data END)) FROM weighted_parts) AS parts,
+ EXISTS(SELECT 1 FROM message reply WHERE reply.session_id=m.session_id AND reply.time_created>=m.time_created
+ AND CASE WHEN json_valid(reply.data) THEN json_extract(reply.data,'$.parentID') END=m.id) AS has_reply,
+ EXISTS(SELECT 1 FROM message later WHERE later.session_id=m.session_id
+ AND (later.time_created>m.time_created OR (later.time_created=m.time_created AND later.id>m.id))
+ AND CASE WHEN json_valid(later.data) THEN json_extract(later.data,'$.role') END='user') AS has_later_user
+FROM candidate m`
+
+/** Cursor order is native SQL insertion time plus ID; evidence time is the separate native message timestamp. */
+export async function readOpenCodeMemoryMessage(path: string, sessionId: string,
+ after: { t: number; m: string } | { id: string }): Promise<OpenCodeSourceMessage | null> {
+ const exact = 'id' in after
+ const rows = await query(path, `WITH candidate AS (SELECT * FROM message WHERE session_id=? AND
+ ${exact ? 'id=?' : '(time_created>? OR (time_created=? AND id>?))'} ORDER BY time_created,id LIMIT 1), ${parts}`,
+ [sessionId, ...(exact ? [after.id] : [after.t, after.t, after.m]), sessionId])
+ if (!rows.length) return null
+ const row = rows[0]
+ const parsed = messageSchema.safeParse({ ...row, parts: JSON.parse(String(row.parts)),
+ hasReply: row.has_reply === 1, hasLaterUser: row.has_later_user === 1 })
+ if (!parsed.success) throw new MemoryError('native_source_unsupported')
+ return parsed.data
+}
+
+export async function openCodeMemoryTail(path: string, sessionId: string): Promise<{ t: number; m: string }> {
+ const [row] = await query(path, 'SELECT time_created AS t,id AS m FROM message WHERE session_id=? ORDER BY time_created DESC,id DESC LIMIT 1', [sessionId])
+ if (!row) return { t: 0, m: '' }
+ const parsed = z.object({ t: time, m: nativeId }).safeParse(row)
+ if (!parsed.success) throw new MemoryError('native_source_unsupported')
+ return parsed.data
+}
diff --git a/cli/src/memory/opencodeSource.ts b/cli/src/memory/opencodeSource.ts
new file mode 100644
index 000000000..cb51955d6
--- /dev/null
+++ b/cli/src/memory/opencodeSource.ts
@@ -0,0 +1,88 @@
+/** OpenCode 1.18.34's native message/part records, before live-view clipping. */
+import { digest } from './admission.js'
+import { memoryUserParts, type NativeRecord } from './native.js'
+import type { SourceEvent } from './types.js'
+
+export interface OpenCodeSourceMessage {
+ id: string; created: number; updated: number; data: string | null
+ parts: Array<{ id: string; created: number; updated: number; data: string | null }>
+ hasReply: boolean; hasLaterUser: boolean
+}
+export interface OpenCodeSourceRecord extends NativeRecord {
+ started: boolean
+ /** Summaries and their generated continuation are not new statements by the person. */
+ compacted: boolean
+ observedAt: number | null
+}
+function object(value: unknown): Record<string, unknown> {
+ return value && typeof value === 'object' && !Array.isArray(value) ? value as Record<string, unknown> : {}
+}
+function json(value: string | null): Record<string, unknown> | null {
+ try { return value === null ? null : object(JSON.parse(value)) } catch { return null }
+}
+function timestamp(value: unknown): value is number { return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 }
+
+export function openCodeMessageSettled(message: OpenCodeSourceMessage, busy: boolean, now: number): boolean {
+ const data = json(message.data), time = object(data?.time)
+ if (data?.role === 'assistant' && timestamp(time.completed)) return true
+ if (data?.role === 'user' && message.parts.length && message.hasReply) return true
+ // A crashed/interrupted message must not hold a later real user turn forever.
+ if (message.hasLaterUser) return true
+ const updated = Math.max(message.updated, ...message.parts.map(part => part.updated))
+ return (!busy || data?.role === 'user') && now - updated >= 5_000
+}
+
+export function decodeOpenCodeMemoryMessage(message: OpenCodeSourceMessage): OpenCodeSourceRecord {
+ const result: OpenCodeSourceRecord = { parts: [], ended: false, incomplete: false, started: false,
+ compacted: false, observedAt: null }
+ const data = json(message.data), at = object(data?.time).created
+ if (!data || !timestamp(at) || !['user', 'assistant'].includes(String(data.role))) return { ...result, incomplete: true }
+ result.observedAt = at
+ // Forking copies this native timestamp while minting new SQL row IDs/timestamps.
+ // The capture boundary compares this timestamp with the new session's creation time.
+ if (data.summary === true || data.agent === 'compaction' || data.mode === 'compaction') {
+ return { ...result, compacted: true, ended: true }
+ }
+ const decoded = message.parts.map(part => ({ part, data: json(part.data) }))
+ if (decoded.some(part => part.data?.type === 'compaction')) return { ...result, compacted: true, ended: true }
+ let ordinal = 0
+ const add = (partId: string, role: SourceEvent['role'], text: string): void => {
+ if (!text.trim()) return
+ if (text.length > 32_000) { result.incomplete = true; return }
+ result.parts.push({ nativeEventId: digest(['opencode', message.id, partId, ordinal++, role]), role, text, observedAt: at })
+ }
+ for (const { part, data: value } of decoded) {
+ if (!value) { result.incomplete = true; continue }
+ if (value.synthetic === true || value.ignored === true) continue
+ if (value.type === 'text' && typeof value.text === 'string') {
+ if (data.role === 'user') {
+ const fragments = memoryUserParts(value.text)
+ for (const fragment of fragments) add(part.id, fragment.role, fragment.text)
+ if (fragments.some(fragment => fragment.role === 'user')) result.started = true
+ } else if (timestamp(object(value.time).end)) add(part.id, 'assistant', value.text)
+ else result.incomplete = true
+ } else if (value.type === 'tool' && data.role === 'assistant') {
+ const state = object(value.state)
+ if (typeof value.tool !== 'string' || typeof value.callID !== 'string'
+ || !['completed', 'error'].includes(String(state.status))) { result.incomplete = true; continue }
+ add(part.id, 'assistant', JSON.stringify({ tool: value.tool, callId: value.callID, input: state.input }))
+ const output = state.status === 'error' ? state.error : state.output
+ if (typeof output === 'string') add(part.id, 'tool', JSON.stringify({ callId: value.callID,
+ isError: state.status === 'error', output }))
+ else result.incomplete = true
+ } else if (!['reasoning', 'step-start', 'step-finish', 'snapshot', 'patch', 'retry', 'agent'].includes(String(value.type))) {
+ // Attachments and unsupported parts can explain ambiguous prose. Preserve that gap.
+ result.incomplete = true
+ }
+ }
+ if (message.parts.length > 64 || result.parts.length > 64) {
+ result.parts = result.parts.slice(0, 64)
+ result.incomplete = true
+ }
+ if (data.role === 'assistant') {
+ const completed = timestamp(object(data.time).completed)
+ result.ended = completed && (data.finish === 'stop' || !!data.error)
+ if (!completed || data.error) result.incomplete = true
+ }
+ return result
+}
diff --git a/cli/src/memory/receipts.ts b/cli/src/memory/receipts.ts
index 3204cab2a..1dbfe4cd5 100644
--- a/cli/src/memory/receipts.ts
+++ b/cli/src/memory/receipts.ts
@@ -7,7 +7,7 @@ import { visibleEvidenceSql } from './visibility.js'
import { MemoryError, parse, type Conditions, type MemoryAccess, type MemoryRecord, type RecallPacket, type RecallRequest } from './types.js'
const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)
-const bindingSchema = z.object({ engine: z.enum(['claude', 'codex']), sessionId: id, projectId: id.nullable(),
+const bindingSchema = z.object({ engine: z.enum(['claude', 'codex', 'opencode']), sessionId: id, projectId: id.nullable(),
route: z.enum(['prompt_hook', 'mcp', 'manual']) }).strict()
/** Always constructed from the authenticated host session, never copied from agent arguments. */
export type MemoryDeliveryBinding = z.infer<typeof bindingSchema>
@@ -36,7 +36,7 @@ export interface MemoryRecallUse {
}
/** Ephemeral host identities are supplied by the runtime, never persisted in activity rows. */
export const activityReceiversSchema = z.array(z.object({ agentId: id,
- engine: z.enum(['claude', 'codex']), sessionId: id }).strict()).max(128)
+ engine: z.enum(['claude', 'codex', 'opencode']), sessionId: id }).strict()).max(128)
export type ActivityReceiver = z.infer<typeof activityReceiversSchema>[number]
export interface RecallActivity {
agentId: string; engine: MemoryDeliveryBinding['engine']; projectId: string | null
diff --git a/cli/src/memory/runtime.spec.ts b/cli/src/memory/runtime.spec.ts
index 4c2b3ff9d..0e551c765 100644
--- a/cli/src/memory/runtime.spec.ts
+++ b/cli/src/memory/runtime.spec.ts
@@ -166,6 +166,9 @@ it('reuses the selected collection across engines for scoped MCP recall, with a
expect(reply).toMatchObject({ ok: true, status: 'ok', context: expect.stringContaining(preference), receipt: { delivery: 'unverified' } })
sessions[0] = { ...sessions[0], engine: 'codex', cliVersion: '0.159.0', sessionId: 'codex_collection' }
expect(await runtime.recallCollection('agent', { query: 'coding changes' })).toMatchObject({ status: 'ok', context: expect.stringContaining(preference) })
+ sessions[0] = { ...sessions[0], engine: 'opencode', cliVersion: '1.18.34', sessionId: 'opencode_collection' }
+ expect(await runtime.recallCollection('agent', { query: 'coding changes' })).toMatchObject({ status: 'ok', context: expect.stringContaining(preference) })
+ expect((await runtime.libraryActivity('owner_a')).sessions).toMatchObject([{ engine: 'opencode', name: 'OpenCode session' }])
await expect(runtime.recallCollection('agent', { query: 'coding', profileId: 'foreign' })).rejects.toThrow('invalid_input')
await expect(runtime.recallCollection('agent', { query: 'coding', projectId: 'foreign' })).rejects.toThrow('invalid_input')
sessions[0].scope = 'project'
@@ -213,7 +216,7 @@ it('prepares a host-bound prompt receipt and rejects a native-session replacemen
expect(await runtime.promptRecallReceipts('agent')).toEqual([])
})
-it.each(['claude', 'codex'] as const)('keeps %s prompt delivery unavailable on an unverified release while preserving explicit scoped recall', async engine => {
+it.each(['claude', 'codex', 'opencode'] as const)('keeps %s prompt delivery unavailable on an unverified release while preserving explicit scoped recall', async engine => {
await learn()
sessions[0] = { ...sessions[0], engine, cliVersion: '2.99.0' }
expect((await runtime.preparePromptRecall('agent', { query: 'coding changes' })).packet.status).toBe('unavailable')
diff --git a/cli/src/memory/runtime.ts b/cli/src/memory/runtime.ts
index bac3db7fd..8dc4a15b1 100644
--- a/cli/src/memory/runtime.ts
+++ b/cli/src/memory/runtime.ts
@@ -27,7 +27,7 @@ export interface MemoryHostSession {
name?: string
/** Exited sessions can remain briefly for capture, but never appear as open activity. */
present?: boolean
- engine: 'claude' | 'codex'
+ engine: 'claude' | 'codex' | 'opencode'
cliVersion?: string | null
sessionId: string
workspace: string
@@ -151,7 +151,7 @@ export class CodingMemoryRuntime {
}
return { ...result, sessions: result.sessions.map(row => ({ ...row,
name: redact((sessions.find(s => s.agentId === row.agentId)?.name ||
- `${row.engine === 'claude' ? 'Claude' : 'Codex'} session`).slice(0, 200)) })) }
+ `${row.engine === 'claude' ? 'Claude' : row.engine === 'opencode' ? 'OpenCode' : 'Codex'} session`).slice(0, 200)) })) }
})
}
diff --git a/desktop/lib/companions/coding_memory_activity_view.dart b/desktop/lib/companions/coding_memory_activity_view.dart
index 2f213aed2..e47832862 100644
--- a/desktop/lib/companions/coding_memory_activity_view.dart
+++ b/desktop/lib/companions/coding_memory_activity_view.dart
@@ -74,7 +74,11 @@ class _CodingMemoryActivityViewState extends State<_CodingMemoryActivityView> {
}
String _where(Map<String, dynamic> session) =>
- '${session['engine'] == 'claude' ? 'Claude' : 'Codex'} · ${memoryMap(session['project'])['name'] ?? 'Companion conversation'}';
+ '${switch (session['engine']) {
+ 'claude' => 'Claude',
+ 'opencode' => 'OpenCode',
+ _ => 'Codex',
+ }} · ${memoryMap(session['project'])['name'] ?? 'Companion conversation'}';
@override
Widget build(BuildContext context) => ListenableBuilder(
diff --git a/desktop/lib/companions/coding_memory_recall_history.dart b/desktop/lib/companions/coding_memory_recall_history.dart
index d6df447b3..b3357e07c 100644
--- a/desktop/lib/companions/coding_memory_recall_history.dart
+++ b/desktop/lib/companions/coding_memory_recall_history.dart
@@ -108,7 +108,11 @@ class _CodingMemoryRecallHistoryState extends State<CodingMemoryRecallHistory> {
final feedback = memoryMap(recall['feedback']);
final value = feedback['value'];
final project = memoryMap(recall['project']);
- final engine = recall['engine'] == 'claude' ? 'Claude' : 'Codex';
+ final engine = switch (recall['engine']) {
+ 'claude' => 'Claude',
+ 'opencode' => 'OpenCode',
+ _ => 'Codex',
+ };
final where = project['name'] as String? ?? 'Companion conversation';
final millis = recall['preparedAt'];
final date = millis is num
diff --git a/desktop/lib/daemons/daemon_lessons.dart b/desktop/lib/daemons/daemon_lessons.dart
index 7e5e85018..148873f8d 100644
--- a/desktop/lib/daemons/daemon_lessons.dart
+++ b/desktop/lib/daemons/daemon_lessons.dart
@@ -220,7 +220,7 @@ class DaemonLearning {
return 'Learning resumes when your companion is turned on.';
}
if (state == 'unsupported') {
- return 'Background learning currently needs Codex or Claude Code. Change agent to enable it; your conversation and saved memories are kept.';
+ return 'Background learning is not available with this connection yet. Your conversation and saved memories are kept.';
}
if (state == 'unopened') {
return 'Open your companion with OpenCode, Codex, or Claude Code.';
diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.md
index 0b58c22a8..720b25323 100644
--- a/docs/plans/2026-09-30-coding-memory-review-log.md
+++ b/docs/plans/2026-09-30-coding-memory-review-log.md
@@ -652,3 +652,42 @@ These are synthetic integration results. The host's ownership/consent inputs are
fixture and tested separately through the real hook server. The installed review app, its settings,
and personal memories remain unchanged. OpenCode source capture and prompt recall, real-user
extraction quality and the broader task-benefit/rollout requirements are still open.
+
+### OpenCode native capture and collection recall
+
+OpenCode 1.18.34 conversations now enter the same consent-controlled capture queue as Claude
+and Codex. The host supplies the database and current session/workspace identity; the reader
+checks native ownership, parent-session exclusion, version and directory before reading that
+session. SQL bounds both returned JSON bytes and part counts. The persisted cursor survives
+host restarts, detects database replacement and changed/deleted messages, and keeps a monotonic
+position after native undo cleanup. Learn-off, session exclusion and project exclusion intervals
+are not backfilled when re-enabled.
+
+Forked messages retain their original native timestamps despite receiving new row IDs and SQL
+insertion times. Comparing those timestamps with the new session's creation time excludes copied
+history. Generated summaries, compaction markers, synthetic prompts, ignored parts and reasoning
+are not fresh user evidence. Quoted user material remains a reference; tool calls and results
+have separate roles and do not manufacture verification. Streaming replies wait for native
+completion. Interrupted or incomplete context admits only the queue's existing bounded-context
+rules, preserving readable instructions around oversized results.
+
+The verified OpenCode collection session can now retrieve shared personal memories through its
+existing scoped MCP tool. Receipt/activity schemas and desktop labels recognize OpenCode.
+Automatic prompt delivery remains disabled for OpenCode pending an outgoing native-model-request
+test; capture and extraction transport do not establish prompt delivery or useful recall.
+
+The reproducible `cli/scripts/memory-native-opencode-source-probe.mjs` uses the real 1.18.34
+binary, an isolated HOME/database, fixture-only file permission and synthetic localhost responses.
+It recorded a native completed `read` call, fork, manual compaction and undo, then exercised the
+actual capture implementation against the running database: six original role-separated sources,
+zero duplicates on a repeated poll, zero copied-fork sources, two fresh fork sources, zero summary
+sources, and capture suspended while undo was active. The sanitized source recording is committed
+under `cli/src/memory/__fixtures__`; no personal conversations or credentials are included.
+
+Validation: 401 memory checks, TypeScript checking, CLI bundling, 56 desktop memory widget checks
+and targeted Flutter analysis passed. The full CLI suite ran 8,480 tests: 8,433 passed, 45 skipped,
+and two unrelated tmux probes failed near their timeouts while another suite was active on this Mac.
+Both complete tmux suites then passed all 36 checks with one worker. The required isolated native
+tmux suite passed nine checks and skipped nine unavailable engine rows. No app, firmware or release
+was installed by this increment. Real-user extraction quality remains unmeasured: the prepared
+private sample is waiting for explicit approval of its selected external model destination.