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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Use the selected OpenCode companion for coding memory (#562)
Deeb35a0232d665
diff --git a/cli/scripts/memory-native-opencode-binding-probe.mjs b/cli/scripts/memory-native-opencode-binding-probe.mjsnew file mode 100644index 000000000..e948158f5--- /dev/null+++ b/cli/scripts/memory-native-opencode-binding-probe.mjs@@ -0,0 +1,163 @@+// Manual integration check: node cli/scripts/memory-native-opencode-binding-probe.mjs+// A live disposable OpenCode server observes foreground selection, then the actual companion+// intelligence extracts with that binding. All credentials and model responses are synthetic.+import assert from 'node:assert/strict'+import { spawn } from 'node:child_process'+import { createServer } from 'node:http'+import { mkdtemp, mkdir, readFile, readdir, rm, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { build } from 'esbuild'++const fixture = await mkdtemp(join(tmpdir(), 'native-opencode-binding-'))+const cli = dirname(dirname(fileURLToPath(import.meta.url)))+const requests = [], hooks = []+const keySource = process.env.HARNESS_MEMORY_NATIVE_KEY_SOURCE === 'auth' ? 'auth' : 'config'+let native, nativeUrl, stdout = '', stderr = '', phase = 'startup', sessionId, enabled = false, binding+const processKey = () => native && `${native.pid}:disposable-opencode-server`+const alive = () => native?.exitCode === null && native?.signalCode === null+const actor = () => ({ agentId: 'synthetic-companion', sessionId, processKey: processKey() })+const owner = () => enabled && alive() && sessionId ? { ...actor(), ownerKey: 'synthetic-owner', model: null } : null+const model = createServer(async (request, response) => {+ const chunks = []+ for await (const chunk of request) chunks.push(chunk)+ let body+ try { body = JSON.parse(Buffer.concat(chunks)) }+ catch { response.writeHead(400).end(); return }+ if (request.url === '/api/hook/opencode-memory-runtime') {+ assert.equal(body.callerPid, native.pid)+ assert.equal(body.sessionId, sessionId)+ assert.equal(body.tmuxPane, '%424242')+ assert.equal(request.headers['x-harness-hook-token'], 'synthetic-hook-token')+ hooks.push({ phase, kind: body.input.kind, nativeVersion: body.input.nativeVersion,+ model: body.input.snapshot?.model, variant: body.input.snapshot?.variant,+ selectedCredential: body.input.snapshot ? body.input.snapshot.auth?.key === 'synthetic-selected-account' : undefined })+ const result = binding.receive(actor(), body.input)+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(result))+ return+ }+ requests.push({ phase, route: request.url, model: body.model, reasoningEffort: body.reasoning_effort,+ tools: (body.tools ?? []).map(tool => tool.function?.name ?? tool.name),+ selectedCredential: request.headers.authorization === 'Bearer synthetic-selected-account' })+ const base = { id: 'chatcmpl_fixture', object: 'chat.completion.chunk', created: 1, model: body.model }+ response.writeHead(200, { 'content-type': 'text/event-stream' })+ for (const [delta, finish_reason] of [[{ role: 'assistant', content: '{"proposals":[]}' }, null], [{}, 'stop']]) {+ response.write('data: ' + JSON.stringify({ ...base, choices: [{ index: 0, delta, finish_reason }] }) + '\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', 'reasoning']) await mkdir(join(fixture, name), { mode: 0o700 })+ const bundle = join(fixture, 'probe.mjs')+ await build({ stdin: { contents: [+ `export { opencodeMemoryPluginSource } from ${JSON.stringify(join(cli, 'src/lib/opencodeMemoryPlugin.ts'))};`,+ `export { OpenCodeMemoryBinding } from ${JSON.stringify(join(cli, 'src/memory/opencodeBinding.ts'))};`,+ `export { CompanionIntelligence } from ${JSON.stringify(join(cli, 'src/pair/intelligence.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 { opencodeMemoryPluginSource, OpenCodeMemoryBinding, CompanionIntelligence } = await import(pathToFileURL(bundle).href)+ binding = new OpenCodeMemoryBinding({ current: owner })+ const plugin = join(fixture, 'plugin.mjs')+ await writeFile(plugin, `const hookToken = () => 'synthetic-hook-token';+ export const Fixture = async ({client}) => { ${opencodeMemoryPluginSource(model.address().port)}; return { 'chat.message': memoryMessage, 'chat.params': memoryParams } }`, { mode: 0o600 })+ const selectedModel = 'memory-fixture/alias'+ const config = { autoupdate: false, share: 'disabled', snapshot: false, permission: { '*': 'deny' },+ plugin: [pathToFileURL(plugin).href], mcp: {}, instructions: [], enabled_providers: ['memory-fixture'],+ model: selectedModel, small_model: selectedModel,+ agent: { memory_fixture: { mode: 'primary', description: 'Synthetic foreground agent',+ prompt: 'Return only the requested JSON without tools.', permission: { '*': 'deny' }, steps: 1 } },+ provider: { 'memory-fixture': { name: 'Synthetic selected provider', npm: '@ai-sdk/openai-compatible',+ options: { ...(keySource === 'config' ? { apiKey: 'synthetic-selected-account' } : {}),+ baseURL: `http://127.0.0.1:${model.address().port}/v1` },+ models: { alias: { id: 'provider-native-id', name: 'Synthetic model alias', reasoning: true,+ limit: { context: 128000, output: 4096 }, variants: { high: { reasoningEffort: 'high' } } } } } },+ }+ const environment = { PATH: process.env.PATH, HOME: join(fixture, 'home'), TMPDIR: fixture, TMUX_PANE: '%424242',+ XDG_CONFIG_HOME: join(fixture, 'config'), XDG_DATA_HOME: join(fixture, 'data'), XDG_CACHE_HOME: join(fixture, 'cache'),+ XDG_STATE_HOME: join(fixture, 'state'), OPENCODE_DB: join(fixture, 'foreground.db'), OPENCODE_CONFIG_CONTENT: JSON.stringify(config),+ OPENCODE_AUTH_CONTENT: JSON.stringify({ 'memory-fixture': { type: 'api', key: keySource === 'auth' ? 'synthetic-selected-account' : 'synthetic-unselected-login' } }),+ OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_MODELS_FETCH: '1',+ OPENCODE_DISABLE_AUTOCOMPACT: '1', TERM: 'dumb' }+ native = spawn(process.env.OPENCODE_PATH || 'opencode', ['serve', '--hostname', '127.0.0.1', '--port', '0'], {+ cwd: join(fixture, 'work'), env: environment, detached: true, stdio: ['ignore', 'pipe', 'pipe'],+ })+ native.stdout.on('data', chunk => { stdout = (stdout + String(chunk)).slice(-5000); nativeUrl = stdout.match(/http:\/\/127\.0\.0\.1:\d+/)?.[0] })+ native.stderr.on('data', chunk => { stderr = (stderr + String(chunk)).slice(-5000) })+ const waitUntil = Date.now() + 10000+ while (!nativeUrl && alive() && Date.now() < waitUntil) await new Promise(resolve => setTimeout(resolve, 50))+ assert.ok(nativeUrl && alive(), `Disposable native server did not start: ${stderr}`)+ const call = async (route, body) => {+ const response = await fetch(nativeUrl + route, { method: body === undefined ? 'GET' : 'POST',+ headers: { 'content-type': 'application/json', 'x-opencode-directory': join(fixture, 'work') },+ signal: AbortSignal.timeout(25000), ...(body === undefined ? {} : { body: JSON.stringify(body) }) })+ assert.ok(response.ok, `Native fixture route failed (${response.status})`)+ return response.json()+ }+ const health = await call('/global/health')+ assert.equal(health.version, '1.18.34')+ sessionId = (await call('/session', { title: 'Synthetic companion fixture' })).id+ assert.ok(sessionId)+ const prompt = () => call(`/session/${sessionId}/message`, { agent: 'memory_fixture',+ model: { providerID: 'memory-fixture', modelID: 'alias' }, variant: 'high',+ parts: [{ type: 'text', text: 'Synthetic foreground request. Return {"proposals":[]} without tools.' }] })+ phase = 'off'; await prompt()+ assert.equal(binding.read(actor()), null)+ assert.ok(hooks.some(hook => hook.phase === 'off' && hook.kind === 'probe'))+ assert.equal(hooks.some(hook => hook.phase === 'off' && hook.kind === 'observe'), false)+ enabled = true; phase = 'foreground'; await prompt()+ const snapshot = binding.read(actor())+ assert.equal(snapshot?.model, selectedModel)+ assert.equal(snapshot?.auth.key, 'synthetic-selected-account')+ assert.equal(snapshot?.variant, 'high')+ phase = 'compaction'+ const observedBeforeCompaction = binding.identity(actor()), hooksBeforeCompaction = hooks.length+ await call(`/session/${sessionId}/summarize`, { providerID: 'memory-fixture', modelID: 'alias' })+ assert.equal(binding.identity(actor()), observedBeforeCompaction, 'Internal compaction cannot replace the user selection')+ assert.equal(hooks.length, hooksBeforeCompaction, 'Internal compaction must not request a new selection grant')+ assert.ok(alive())+ const intelligence = new CompanionIntelligence({ enabled: () => enabled, current: () => ({ ...actor(),+ engine: 'opencode', stopped: !alive(), profile: null, nativeProcessKey: processKey(),+ accountKey: binding.identity(actor()), customProvider: true }),+ directory: join(fixture, 'reasoning'), stateFile: join(fixture, 'profile.json'),+ openCodeSnapshot: () => binding.read(actor()),+ })+ phase = 'extraction'+ const target = await intelligence.extractionStatus()+ assert.equal(target.state, 'ready')+ const text = await intelligence.extract('Synthetic historical coding evidence. Return {"proposals":[]} without tools.', {+ timeoutMs: 20000, signal: new AbortController().signal, contextKey: target.contextKey,+ })+ assert.equal(text, '{"proposals":[]}')+ assert.ok(alive(), 'The selected foreground process must remain alive during extraction')+ assert.equal((await readFile(join(fixture, 'profile.json'), 'utf8')).includes('synthetic-selected-account'), false)+ assert.deepEqual(await readdir(join(fixture, 'reasoning')), [])+ for (const request of requests) {+ assert.equal(request.model, 'provider-native-id'); assert.equal(request.selectedCredential, true)+ if (request.phase !== 'compaction') assert.equal(request.reasoningEffort, 'high')+ assert.deepEqual(request.tools, [])+ }+ enabled = false; binding.clear()+ const before = requests.length+ assert.equal(await intelligence.extract('Must not run while off.', { timeoutMs: 20000,+ signal: new AbortController().signal, contextKey: target.contextKey }), null)+ assert.equal(requests.length, before)+ console.log(JSON.stringify({ at: new Date().toISOString(), version: health.version, keySource, requests, hooks,+ result: { observedSelection: true, selectedProcessAliveDuringExtraction: true, inheritedAccountModelVariant: true,+ manualCompactionPreservedSelection: true,+ offSentCredentials: false, offLaunchedExtraction: false, credentialsPersistedInProfile: false, privateStorageRemoved: true },+ limitations: ['Synthetic localhost responses; no personal conversations or semantic-quality measurement.',+ 'Consent and process ownership are fixture inputs; the actual hook-server authorization is covered separately.',+ 'No OAuth, OpenCode 2.x, automatic compaction, capture or recall certification.'],+ }, null, 2))+} finally {+ if (alive()) {+ 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))+ await rm(fixture, { recursive: true, force: true })+}diff --git a/cli/scripts/memory-native-opencode-inference-probe.mjs b/cli/scripts/memory-native-opencode-inference-probe.mjsnew file mode 100644index 000000000..d1f440645--- /dev/null+++ b/cli/scripts/memory-native-opencode-inference-probe.mjs@@ -0,0 +1,98 @@+// Manual native transport check: node cli/scripts/memory-native-opencode-inference-probe.mjs+// Disposable storage, synthetic credentials and localhost responses only. No real inference.+import assert from 'node:assert/strict'+import { createServer } from 'node:http'+import { mkdtemp, readdir, rm, stat } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath, pathToFileURL } from 'node:url'+import { build } from 'esbuild'++const fixture = await mkdtemp(join(tmpdir(), 'native-opencode-memory-'))+const forbidden = join(fixture, 'forbidden-tool-action')+const runs = []+let current+const server = createServer(async (request, response) => {+ const chunks = []+ for await (const chunk of request) chunks.push(chunk)+ let body+ try { body = JSON.parse(Buffer.concat(chunks)) }+ catch { response.writeHead(400).end(); return }+ current.requests.push({ route: request.url, model: body.model,+ tools: (body.tools ?? []).map(tool => tool.function?.name ?? tool.name ?? tool.type),+ selectedCredential: request.headers.authorization === 'Bearer synthetic-memory-account',+ })+ const forced = current.mode !== 'text' && current.requests.length === 1+ const tool = { index: 0, id: 'call_fixture', type: 'function', function: { name: current.mode,+ arguments: JSON.stringify(current.mode === 'bash'+ ? { command: `touch '${forbidden.replaceAll("'", "'\\''")}'`, description: 'Synthetic forbidden action' }+ : { questions: [{ question: 'Synthetic choice?', header: 'Fixture', options: [{ label: 'A', description: 'A' }] }] }),+ } }+ const base = { id: 'chatcmpl_fixture', created: 1, model: body.model }+ if (!body.stream) {+ response.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify({ ...base,+ object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content: '{"proposals":[]}' }, finish_reason: 'stop' }],+ usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 },+ }))+ return+ }+ response.writeHead(200, { 'content-type': 'text/event-stream' })+ const send = (delta, finish_reason = null) => response.write('data: ' + JSON.stringify({ ...base,+ object: 'chat.completion.chunk', choices: [{ index: 0, delta, finish_reason }],+ }) + '\n\n')+ send({ role: 'assistant', ...(forced ? { tool_calls: [tool] } : { content: '{"proposals":[]}' }) })+ send({}, forced ? 'tool_calls' : 'stop')+ response.end('data: [DONE]\n\n')+})++try {+ const bundle = join(fixture, 'inference.mjs')+ await build({ entryPoints: [fileURLToPath(new URL('../src/memory/opencodeInference.ts', import.meta.url))],+ outfile: bundle, bundle: true, platform: 'node', format: 'esm', target: 'node22',+ banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },+ })+ const { runOpenCodeMemoryInference, openCodeSnapshotIdentity, opencodeMemoryCapability } = await import(pathToFileURL(bundle).href)+ const capability = await opencodeMemoryCapability()+ assert.equal(capability.supported, true, 'Installed OpenCode version must match the adapter')+ await new Promise((resolve, reject) => { server.once('error', reject); server.listen(0, '127.0.0.1', resolve) })+ const snapshot = { model: 'memory-fixture/memory-model', auth: { type: 'api', key: 'synthetic-memory-account' },+ provider: { npm: '@ai-sdk/openai-compatible', name: 'Memory fixture',+ options: { baseURL: `http://127.0.0.1:${server.address().port}/v1` },+ models: { 'memory-model': { name: 'Memory fixture', limit: { context: 128_000, output: 4096 } } },+ },+ }+ for (const mode of ['text', 'bash', 'question']) {+ current = { mode, requests: [], snapshotReads: 0 }+ runs.push(current)+ try {+ current.result = await runOpenCodeMemoryInference({ cwd: fixture, model: snapshot.model,+ prompt: 'Synthetic extraction fixture. Return {"proposals":[]} without tools.', timeoutMs: 20_000,+ expectedSnapshot: openCodeSnapshotIdentity(snapshot), readSnapshot: async () => { current.snapshotReads++; return snapshot },+ })+ } catch (error) { current.error = error.message }+ current.forbiddenFileExists = await stat(forbidden).then(() => true, () => false)+ current.privateStorageRemoved = !(await readdir(fixture)).some(name => name.startsWith('opencode-memory-'))+ assert.equal(current.forbiddenFileExists, false, 'A forbidden tool must not execute')+ assert.equal(current.privateStorageRemoved, true, 'Disposable session storage must be removed')+ assert.ok(current.requests.length > 0, 'The installed native CLI must reach the mock')+ for (const request of current.requests) {+ assert.deepEqual(request.tools, [])+ assert.equal(request.selectedCredential, true)+ assert.equal(request.model, 'memory-model')+ assert.equal(request.route, '/v1/chat/completions')+ }+ if (mode === 'text') {+ assert.deepEqual(current.result, { text: '{"proposals":[]}' })+ assert.equal(current.snapshotReads, 3)+ } else assert.equal(current.error, 'inference_tool_or_error')+ }+ console.log(JSON.stringify({ at: new Date().toISOString(), capability, runs,+ limitations: ['Synthetic localhost responses; no personal conversations or real model inference.',+ 'Native transport only. Host account/config observation and companion wiring remain unimplemented.',+ 'No claim about extraction quality, OAuth, automatic compaction or task benefit.'],+ }, null, 2))+} finally {+ server.closeAllConnections()+ await new Promise(resolve => server.close(resolve))+ await rm(fixture, { recursive: true, force: true })+}diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex fcd7ce99f..10619a969 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -100,6 +100,7 @@ import { serveMcp } from './pair/mcp.js'import { PairHarness, type PairEngine } from './pair/pairHarness.js'import { CompanionIntelligence } from './pair/intelligence.js'import { CodingMemoryRuntime } from './memory/runtime.js'+import { OpenCodeMemoryBinding } from './memory/opencodeBinding.js'import { MemoryExperimentSettings } from './memory/experiment.js'import { MemoryControl } from './memory/control.js'import { isOwnerProcess } from './memory/ownerProcess.js'@@ -192,7 +193,7 @@ import {import { ALL_TERMINAL_BACKENDS } from './config/terminalConfig.js'import { TerminalBackendCoordinator } from './lib/terminalBackendCoordinator.js'import { TerminalStreamManager } from './lib/terminalStreamManager.js'-import { terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'+import { processIdentityKey, terminalRouteKey, terminalRuntimeLabel } from './lib/terminalRuntime.js'import { TerminalAgentReconciler } from './lib/terminalAgentReconciler.js'import { processRows, type DiscoveredTerminalAgent } from './lib/terminalAgentDiscovery.js'import { remoteCommand } from './remoteCommand.js'@@ -1948,6 +1949,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {let pairHarnessActivity: (agentId: string) => void = () => {}let companionPromptContext: (agentId: string) => string | null = () => nulllet companionProfileChanged: () => void = () => {}+ let openCodeMemoryBinding: OpenCodeMemoryBinding | null = null// Local account opt-in, exposed in Settings → Experimental. The old env flag is a migration default.const memoryExperiment = new MemoryExperimentSettings(join(env.ADAPTER_DATA_DIR, 'coding-memory-settings'), process.env.HARNESS_CODING_MEMORY === '1')const guestMemoryProfile = createHash('sha256').update(JSON.stringify(['harness-memory-guest-v1', computerId()])).digest('hex')@@ -4172,6 +4174,13 @@ async function runForeground(session: AuthSession | null): Promise<void> {...(recalled?.receipt ? { memoryReceiptId: recalled.receipt.id } : {}) }},onMemoryContextEmitted: async (agentId, receiptId) => await codingMemory?.promptRecallEmitted(agentId, receiptId) ?? false,+ onOpenCodeMemoryRuntime: (agent, input) => {+ if (!agent.processIdentity) return { observe: false }+ const result = openCodeMemoryBinding?.receive({ agentId: agent.agentId, sessionId: agent.sessionId,+ processKey: processIdentityKey('opencode', agent.processIdentity) }, input) ?? { observe: false }+ if (result.observe) codingMemory?.activity()+ return result+ },onCommandBar: commandBarService,onAutonomousDeviceRequest: async (method, target, body) => {if (!autonomousDeviceService) return { status: 503, body: { error: { code: 'UNAVAILABLE', message: 'Autonomous device service is starting' } } }@@ -4942,14 +4951,32 @@ async function runForeground(session: AuthSession | null): Promise<void> {const live = registry.advertised().find(s => s.agentId === agentId)const session = live ?? stoppedAgents.get(agentId)if (!session || session.dsh !== PAIR_HARNESS_DSH) return null+ const nativeProcessKey = live?.processIdentity ? processIdentityKey(session.engine, live.processIdentity) : nullreturn { agentId, sessionId: session.sessionId, engine: session.engine,profile: runtimeProfiles.selectedModel(session), stopped: !live,startup: live ? companionStartupProfile.selected(session) : null,+ nativeProcessKey,+ accountKey: session.engine === 'opencode' && nativeProcessKey ? openCodeMemoryBinding?.identity({+ agentId, sessionId: session.sessionId, processKey: nativeProcessKey,+ }) ?? null : undefined,codexHome: session.codexHome, customProvider: !!(session.grid || session.gridLaunch || session.gateway) }},+ openCodeSnapshot: runtime => runtime.sessionId && runtime.nativeProcessKey ? openCodeMemoryBinding?.read({+ agentId: runtime.agentId, sessionId: runtime.sessionId, processKey: runtime.nativeProcessKey,+ }) ?? null : null,directory: join(env.ADAPTER_DATA_DIR, 'pair', 'reasoning'),stateFile: join(env.ADAPTER_DATA_DIR, 'pair', 'intelligence.json'),})+ openCodeMemoryBinding = new OpenCodeMemoryBinding({ current: () => {+ const ownerKey = codingMemory?.ownerKey(), status = codingMemory?.status()+ if (!daemons.on() || !codingMemoryPreview() || !ownerKey || status?.state !== 'ready' || !status.preferences?.learn) return null+ const session = registry.advertised().find(s => s.agentId === pairHarness.agentId())+ if (!session || !session.active || session.dsh !== PAIR_HARNESS_DSH || session.engine !== 'opencode'+ || !session.sessionId || !session.processIdentity) return null+ return { ownerKey, agentId: session.agentId, sessionId: session.sessionId,+ processKey: processIdentityKey('opencode', session.processIdentity),+ model: parseRuntimeProfile(runtimeProfiles.selectedModel(session))?.model ?? null }+ } })companionProfileChanged = () => { companionIntelligence.status(); pairBrain?.stateChanged() }{const roster = new MemorySessionRoster(homedir())@@ -5110,6 +5137,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {let learnTick: ReturnType<typeof setInterval> | null = nulllet pairConfigTick: ReturnType<typeof setInterval> | null = nullapplyCodingMemorySetting = async () => {+ openCodeMemoryBinding?.clear()pairLearner?.cancelReviews()conversationReview.stop()memoryPause = memoryPause.then(() => codingMemory?.pause()).catch(() => {})@@ -5135,6 +5163,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {pairConfigTick ??= setInterval(() => { daemons.recheck(); if (daemons.on()) { pairRulesConfig(); void refreshMemoryIdentity() } }, 30_000)pairConfigTick.unref?.()} else {+ openCodeMemoryBinding?.clear()memoryPause = memoryPause.then(() => codingMemory?.pause()).catch(() => {})if (learnTick) { clearInterval(learnTick); learnTick = null }if (pairConfigTick) { clearInterval(pairConfigTick); pairConfigTick = null }diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex b3288bae2..bfacf4886 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -63,6 +63,43 @@ async function start(overrides: Partial<HookServerHandlers> = {}) {}describe('process-owned hook server', () => {+ it('accepts private OpenCode runtime observations only from the verified live session', async () => {+ const entry = { engine: 'opencode', agentId: 'companion', sessionId: 'native',+ processIdentity: { pid: 42, executable: 'opencode', startMarker: 'same-process' } } as RegisteredSession+ const resolveHookAgent = vi.fn(async () => entry as RegisteredSession | null)+ const onOpenCodeMemoryRuntime = vi.fn(() => ({ observe: true, recorded: true }))+ const registration = vi.spyOn(registry, 'register')+ try {+ const { base, headers, handlers } = await start({ resolveHookAgent, onOpenCodeMemoryRuntime })+ const body = { engine: 'opencode', sessionId: 'native', tmuxPane: '%41', callerPid: 42,+ input: { kind: 'observe', snapshot: { private: 'synthetic-secret' } } }+ const submit = (value: unknown = body, authenticated = true) => fetch(`${base}/api/hook/opencode-memory-runtime`, {+ method: 'POST', headers: authenticated ? headers : { 'content-type': 'application/json' }, body: JSON.stringify(value) })+ expect((await submit(body, false)).status).toBe(401)+ expect((await submit({ ...body, sessionId: 'previous-session' })).status).toBe(403)+ expect((await submit({ ...body, engine: 'codex' })).status).toBe(400)+ expect((await submit({ ...body, callerPid: undefined })).status).toBe(400)+ expect((await submit({ ...body, input: { blob: 'x'.repeat(51_000) } })).status).toBe(400)+ expect(onOpenCodeMemoryRuntime).not.toHaveBeenCalled()+ const accepted = await submit()+ expect(await accepted.json()).toEqual({ observe: true, recorded: true })+ expect(onOpenCodeMemoryRuntime).toHaveBeenCalledExactlyOnceWith(entry, body.input)+ expect(registration).not.toHaveBeenCalled()+ expect(handlers.onRegistered).not.toHaveBeenCalled()+ resolveHookAgent.mockResolvedValue(null)+ expect((await submit()).status).toBe(403)+ } finally { registration.mockRestore() }+ })++ it('does not accept private runtime data through discovery fallback without ancestry verification', async () => {+ const callback = vi.fn()+ const { base, headers } = await start({ onOpenCodeMemoryRuntime: callback })+ const result = await fetch(`${base}/api/hook/opencode-memory-runtime`, { method: 'POST', headers,+ body: JSON.stringify({ engine: 'opencode', sessionId: 'native', tmuxPane: '%41', callerPid: 42, input: { kind: 'probe' } }) })+ expect(result.status).toBe(403)+ expect(callback).not.toHaveBeenCalled()+ })+it('attributes prompt text only after resolving the actual engine process', async () => {const entry = { engine: 'claude', agentId: 'agent-scope', sessionId: 'session-scope', runtimes: [{ backend: 'tmux', paneId: '%41' }] } as RegisteredSessionconst onPromptSubmitted = vi.fn()diff --git a/cli/src/hookServer.ts b/cli/src/hookServer.tsindex ad883db09..a2b7045e8 100644--- a/cli/src/hookServer.ts+++ b/cli/src/hookServer.ts@@ -78,6 +78,8 @@ export interface HookServerHandlers {onPromptContext?: (agentId: string, prompt: string) => PromptContext | Promise<PromptContext>/** Called only for the same process-owned native session after its hook writes context to stdout. */onMemoryContextEmitted?: (agentId: string, receiptId: string) => Promise<boolean>+ /** Private, process-verified OpenCode request metadata. Never enters the session registry or clients. */+ onOpenCodeMemoryRuntime?: (agent: RegisteredSession, input: unknown) => Record<string, unknown>onCommandBar?: Pick<CommandBarService, 'status' | 'decide'>onAutonomousDeviceRequest?: (method: string, target: string, body?: unknown) => Promise<{ status: number; body: unknown }>@@ -590,6 +592,21 @@ export function startHookServer(return}+ if (req.method === 'POST' && url === '/api/hook/opencode-memory-runtime') {+ if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }+ let body: BoundHookBody+ try {+ const parsed: unknown = JSON.parse(await readBody(req))+ if (!validHookBody(parsed) || parsed.engine !== 'opencode' || !parsed.callerPid+ || !optionalBoundedJson(parsed.input, 50_000)) { json(400, { error: 'invalid hook body' }); return }+ body = parsed+ } catch { json(400, { error: 'bad json' }); return }+ // Unlike discovery fallback, credentials always require the host's live ancestry resolver.+ const agent = handlers.resolveHookAgent ? await verifiedBoundMutation(body, handlers) : null+ if (!agent?.processIdentity) { json(403, { error: 'UNBOUND_HOOK' }); return }+ json(200, handlers.onOpenCodeMemoryRuntime?.(agent, body.input) ?? { observe: false }); return+ }+if (req.method === 'POST' && url === '/api/hook/memory-emitted') {if (!hookOk) { json(401, { error: 'UNAUTHORIZED' }); return }let body: BoundHookBodydiff --git a/cli/src/lib/hooks.ts b/cli/src/lib/hooks.tsindex 8c0d249d2..10ef8e74c 100644--- a/cli/src/lib/hooks.ts+++ b/cli/src/lib/hooks.ts@@ -14,6 +14,7 @@ import { env } from '../config/env.js'import { VERSION } from '../version.js'import { hermesConfigHomes } from '../engines/hermes/home.js'import { managedNodePath } from './nodeRuntime.js'+import { opencodeMemoryPluginSource } from './opencodeMemoryPlugin.js'const SETTINGS_PATH = join(homedir(), '.claude', 'settings.json')const GROK_HOOKS_PATH = join(env.GROK_HOME, 'hooks', 'harness.json')@@ -423,7 +424,7 @@ function forkPluginSource(engine: 'opencode' | 'kilo', port: number): string {// local machine daemon (127.0.0.1:${port}) so it can be mirrored to web/device. No-op if machine isn't running.import { readFileSync } from "node:fs"const hookToken = () => { try { return readFileSync(${JSON.stringify(join(env.ADAPTER_DATA_DIR, 'hook-credential'))}, "utf8").trim() } catch { return "" } }-export const MachineRegister = async ({ directory, worktree, project }) => {+export const MachineRegister = async ({ directory, worktree, project, client }) => {const seen = new Set()const post = async (sessionID) => {const pane = process.env.TMUX_PANE@@ -448,7 +449,9 @@ export const MachineRegister = async ({ directory, worktree, project }) => {})} catch {}}+${engine === 'opencode' ? opencodeMemoryPluginSource(port) : ''}return {+ ${engine === 'opencode' ? '"chat.message": memoryMessage, "chat.params": memoryParams,' : ''}event: async ({ event }) => {if (!event) returnif (event.type === "session.created" || event.type === "session.updated") {diff --git a/cli/src/lib/opencodeMemoryPlugin.spec.ts b/cli/src/lib/opencodeMemoryPlugin.spec.tsnew file mode 100644index 000000000..f4b10d3f3--- /dev/null+++ b/cli/src/lib/opencodeMemoryPlugin.spec.ts@@ -0,0 +1,92 @@+import { afterEach, expect, it, vi } from 'vitest'+import { opencodeMemoryPluginSource } from './opencodeMemoryPlugin.js'++afterEach(() => { vi.restoreAllMocks(); vi.unstubAllEnvs() })+function fixture() {+ vi.stubEnv('TMUX_PANE', '%42')+ const posts: Record<string, any>[] = []+ const fetch = vi.spyOn(globalThis, 'fetch').mockImplementation(async (_url, init) => {+ posts.push(JSON.parse(String(init?.body)))+ return new Response(JSON.stringify({ observe: true, challenge: 'one-use-grant' }), { status: 200 })+ })+ const health = vi.fn(async () => ({ data: { version: '1.18.34' } }))+ const { hook, submitted } = new Function('client', 'hookToken', `${opencodeMemoryPluginSource(12345)}; return { hook: memoryParams, submitted: memoryMessage }`)({ _client: { get: health } }, () => 'synthetic-hook-token')+ const input = { sessionID: 'native', agent: 'build', message: { id: 'user-one', sessionID: 'native', role: 'user', agent: 'build', model: { providerID: 'selected', modelID: 'alias', variant: 'high' } },+ provider: { id: 'selected', name: 'Selected', key: 'native-api-account', options: { baseURL: 'https://selected.invalid/v1' } },+ model: { providerID: 'selected', id: 'alias', name: 'Alias', api: { id: 'provider-native-id', npm: '@ai-sdk/openai-compatible', url: 'https://catalog.invalid/v1' },+ capabilities: { temperature: false, reasoning: true, attachment: false, toolcall: true, input: { text: true }, output: { text: true }, interleaved: false },+ limit: { context: 10000, output: 1000 }, options: {}, variants: { high: { reasoningEffort: 'high' } }, headers: {},+ } }+ void submitted({ sessionID: 'native' }, { message: input.message })+ return { hook, submitted, input, health, fetch, posts }+}++it('hands over the actual resolved model alias, route, API account and variant only after the host grant', async () => {+ const f = fixture(), before = structuredClone(f.input)+ await f.hook(f.input)+ expect(f.posts).toHaveLength(2)+ expect(f.posts[0]).toMatchObject({ engine: 'opencode', callerPid: process.pid, sessionId: 'native', input: { kind: 'probe' } })+ expect(f.posts[1].input).toMatchObject({ kind: 'observe', nativeVersion: '1.18.34', snapshot: {+ model: 'selected/alias', variant: 'high', auth: { type: 'api', key: 'native-api-account' }, provider: {+ options: { baseURL: 'https://selected.invalid/v1' }, models: { alias: { id: 'provider-native-id', variants: { high: { reasoningEffort: 'high' } } } },+ },+ } })+ expect(f.input).toEqual(before)+})++it('does not inspect provider credentials or request health when the owner has not opted in', async () => {+ const f = fixture()+ f.fetch.mockResolvedValue(new Response('{"observe":false}'))+ Object.defineProperty(f.input, 'provider', { get() { throw new Error('credentials must not be read') } })+ await f.hook(f.input)+ expect(f.posts).toHaveLength(0)+ expect(f.fetch).toHaveBeenCalledOnce()+ expect(f.health).not.toHaveBeenCalled()+})++it('uses an explicit provider credential override instead of a different native login', async () => {+ const f = fixture()+ Object.assign(f.input.provider.options, { apiKey: 'selected-provider-account' })+ await f.hook(f.input)+ expect(f.posts[1].input.snapshot.auth.key).toBe('selected-provider-account')+ expect(f.posts[1].input.snapshot.provider.options.apiKey).toBeUndefined()+})++it.each(['version', 'model', 'oauth', 'fetch'] as const)('declines unrepresentable %s context without changing the foreground request', async kind => {+ const f = fixture()+ if (kind === 'version') f.health.mockResolvedValue({ data: { version: '2.0.0' } })+ if (kind === 'model') f.input.message.model.modelID = 'another-model'+ if (kind === 'oauth') f.input.provider.key = 'OAUTH_DUMMY_KEY'+ if (kind === 'fetch') Object.assign(f.input.provider.options, { fetch: () => {} })+ await f.hook(f.input)+ expect(f.posts).toHaveLength(kind === 'model' ? 0 : 1)+})++it('bounds an unresponsive native health request', async () => {+ const f = fixture()+ f.health.mockImplementation(() => new Promise(() => {}))+ await f.hook(f.input)+ expect(f.posts).toHaveLength(1)+})++it('does not treat compaction, internal agents or synthetic continuation as a new user selection', async () => {+ const f = fixture()+ await f.hook({ ...f.input, agent: 'compaction' })+ await f.hook({ ...f.input, message: { ...f.input.message, id: 'synthetic-continue', model: {+ providerID: 'selected', modelID: 'alias',+ } } })+ expect(f.posts).toEqual([])+ expect(f.health).not.toHaveBeenCalled()+ await f.hook(f.input)+ expect(f.posts[1].input.snapshot.variant).toBe('high')+})++it('requires the latest submitted message in that session and accepts its actual variant change', async () => {+ const f = fixture()+ const next = { ...f.input.message, id: 'user-two', model: { ...f.input.message.model, variant: 'low' } }+ await f.submitted({ sessionID: 'native' }, { message: next })+ await f.hook(f.input)+ expect(f.posts).toEqual([])+ await f.hook({ ...f.input, message: next })+ expect(f.posts[1].input.snapshot.variant).toBe('low')+})diff --git a/cli/src/lib/opencodeMemoryPlugin.ts b/cli/src/lib/opencodeMemoryPlugin.tsnew file mode 100644index 000000000..290e5ec61--- /dev/null+++ b/cli/src/lib/opencodeMemoryPlugin.ts@@ -0,0 +1,74 @@+/** Standalone source embedded in the existing 1.x plugin; no additional installation artifact. */+export function opencodeMemoryPluginSource(port: number): string {+ return `+ const memoryMessages = new Map()+ const memoryMessage = async (input, output) => {+ const message = output.message+ if (!input.sessionID || message?.sessionID !== input.sessionID || message.role !== "user"+ || typeof message.id !== "string" || typeof message.agent !== "string") return+ // Only chat.message observes an actual submitted request. Compaction and its synthetic+ // auto-continue messages are written internally and must not replace the user's selection.+ memoryMessages.delete(input.sessionID)+ memoryMessages.set(input.sessionID, { id: message.id, agent: message.agent })+ if (memoryMessages.size > 128) memoryMessages.delete(memoryMessages.keys().next().value)+ }+ const memoryRequest = async (sessionID, input) => {+ const pane = process.env.TMUX_PANE, token = hookToken()+ if (!pane || !token || !sessionID) return null+ const response = await fetch("http://127.0.0.1:${port}/api/hook/opencode-memory-runtime", {+ method: "POST", signal: AbortSignal.timeout(400),+ headers: { "content-type": "application/json", "x-harness-hook-token": token },+ body: JSON.stringify({ engine: "opencode", sessionId: sessionID, callerPid: process.pid,+ tmuxPane: pane, runtimeHints: [{ backend: "tmux", paneId: pane }], input }),+ })+ return response.ok ? response.json() : null+ }+ const memoryParams = async (input) => {+ try {+ const submitted = memoryMessages.get(input.sessionID)+ if (!submitted || submitted.id !== input.message?.id || submitted.agent !== input.agent+ || input.message.agent !== input.agent) return+ // Internal title/summary calls can use a different small model; they are not a new selection.+ const model = input.model, selection = input.message?.model+ if (!model || selection?.providerID !== model.providerID || selection?.modelID !== model.id) return+ const grant = await memoryRequest(input.sessionID, { kind: "probe" })+ if (!grant?.observe || typeof grant.challenge !== "string") return+ let healthTimer+ // The pinned 1.x plugin SDK omits a health wrapper; its in-process client still serves the route.+ const health = await Promise.race([client._client.get({ url: "/global/health", signal: AbortSignal.timeout(400) }),+ new Promise(resolve => { healthTimer = setTimeout(() => resolve(null), 400) })])+ .finally(() => clearTimeout(healthTimer))+ if (health?.data?.version !== "1.18.34") return+ const provider = input.provider+ if (!provider || provider.id !== model.providerID) return+ // Functions (including OAuth fetch wrappers) are not representable by an isolated API call.+ const json = (value, depth = 0) => {+ if (depth > 16 || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") throw new Error("unsupported")+ if (value && typeof value === "object") for (const item of Object.values(value)) json(item, depth + 1)+ }+ json(provider.options); json(model)+ const options = { ...provider.options }+ const key = options.apiKey === undefined ? provider.key : options.apiKey+ if (typeof key !== "string" || !key || key === "OAUTH_DUMMY_KEY") return+ delete options.apiKey+ const capabilities = model.capabilities+ const modalities = (value) => Object.entries(value || {}).filter(([, enabled]) => enabled === true).map(([name]) => name)+ const snapshot = { model: model.providerID + "/" + model.id,+ ...(selection.variant ? { variant: selection.variant } : {}), auth: { type: "api", key },+ provider: { name: provider.name, npm: model.api.npm, options,+ models: { [model.id]: { id: model.api.id, name: model.name,+ provider: { npm: model.api.npm, api: model.api.url }, limit: model.limit,+ reasoning: capabilities.reasoning, temperature: capabilities.temperature,+ attachment: capabilities.attachment, tool_call: capabilities.toolcall, interleaved: capabilities.interleaved,+ modalities: { input: modalities(capabilities.input), output: modalities(capabilities.output) },+ options: model.options, variants: model.variants, headers: model.headers,+ } },+ },+ }+ if (Buffer.byteLength(JSON.stringify(snapshot)) > 48000) return+ await memoryRequest(input.sessionID, { kind: "observe", challenge: grant.challenge,+ nativeVersion: health.data.version, snapshot })+ } catch { /* Optional memory never fails or modifies the foreground request. */ }+ }+`+}diff --git a/cli/src/memory/companion.spec.ts b/cli/src/memory/companion.spec.tsindex c9736a7f4..0b3bde065 100644--- a/cli/src/memory/companion.spec.ts+++ b/cli/src/memory/companion.spec.ts@@ -34,3 +34,14 @@ it('uses only the selected companion for foreground priority and waits when thatexpect(await inference.target()).toEqual({ state: 'waiting' })expect(capability).not.toHaveBeenCalled()})++it('checks OpenCode native compatibility without probing a different engine', async () => {+ const claude = vi.fn(), codex = vi.fn()+ const opencode = vi.fn(async () => ({ supported: false, version: '2.0.0' }))+ const inference = companionMemoryInference({ extractionStatus: async () => ({ state: 'ready', agentId: 'companion',+ engine: 'opencode', contextKey: 'native-binding' }), extract: async () => null }, () => false, codex, claude, opencode)+ expect(await inference.target()).toEqual({ state: 'unsupported' })+ opencode.mockResolvedValue({ supported: true, version: '1.18.34' })+ expect(await inference.target()).toEqual({ state: 'ready', key: 'native-binding', foregroundBusy: false })+ expect(codex).not.toHaveBeenCalled(); expect(claude).not.toHaveBeenCalled()+})diff --git a/cli/src/memory/companion.ts b/cli/src/memory/companion.tsindex 323bebae5..017e0bb2c 100644--- a/cli/src/memory/companion.ts+++ b/cli/src/memory/companion.ts@@ -2,11 +2,13 @@import type { CompanionIntelligence } from '../pair/intelligence.js'import { codexMemoryCapability } from './inference.js'import { claudeMemoryCapability } from './claudeInference.js'+import { opencodeMemoryCapability } from './opencodeInference.js'import type { MemoryInference } from './learner.js'export function companionMemoryInference(intelligence: Pick<CompanionIntelligence, 'extractionStatus' | 'extract'>,foregroundBusy: (companionAgentId: string) => boolean,- codexCapability = codexMemoryCapability, claudeCapability = claudeMemoryCapability): MemoryInference {+ codexCapability = codexMemoryCapability, claudeCapability = claudeMemoryCapability,+ opencodeCapability = opencodeMemoryCapability): MemoryInference {return {async target() {const status = await intelligence.extractionStatus()@@ -15,6 +17,8 @@ export function companionMemoryInference(intelligence: Pick<CompanionIntelligencif (status.state !== 'ready' || !status.contextKey || !status.agentId) return { state: 'waiting' }if (status.engine === 'codex' && !(await codexCapability()).supported) return { state: 'unsupported' }if (status.engine === 'claude' && !(await claudeCapability()).supported) return { state: 'unsupported' }+ if (status.engine === 'opencode' && !(await opencodeCapability()).supported) return { state: 'unsupported' }+ if (!['claude', 'codex', 'opencode'].includes(status.engine ?? '')) return { state: 'unsupported' }return { state: 'ready', key: status.contextKey, foregroundBusy: foregroundBusy(status.agentId) }},run: (prompt, options) => intelligence.extract(prompt, options),diff --git a/cli/src/memory/opencodeBinding.spec.ts b/cli/src/memory/opencodeBinding.spec.tsnew file mode 100644index 000000000..cfc59c884--- /dev/null+++ b/cli/src/memory/opencodeBinding.spec.ts@@ -0,0 +1,86 @@+import { expect, it } from 'vitest'+import { OpenCodeMemoryBinding, type OpenCodeMemoryOwner } from './opencodeBinding.js'++const snapshot = { model: 'selected/model', variant: 'high', auth: { type: 'api', key: 'synthetic-account-a' },+ provider: { npm: '@ai-sdk/openai-compatible', models: { model: { name: 'Selected', limit: { context: 10000, output: 1000 } } } } }+function world() {+ let owner: OpenCodeMemoryOwner | null = { ownerKey: 'owner', agentId: 'companion', sessionId: 'native', processKey: 'process-one', model: 'selected/model' }+ let now = 100+ const binding = new OpenCodeMemoryBinding({ current: () => owner, now: () => now })+ const actor = { agentId: owner.agentId, sessionId: owner.sessionId, processKey: owner.processKey }+ const observe = (value: unknown = snapshot) => {+ const { challenge } = binding.receive(actor, { kind: 'probe' })+ return binding.receive(actor, { kind: 'observe', challenge, nativeVersion: '1.18.34', snapshot: value })+ }+ return { binding, actor, observe, owner: () => owner!, set: (next: OpenCodeMemoryOwner | null) => { owner = next }, advance: (ms: number) => { now += ms } }+}++it('requires a one-use process-owned handshake and does not return credentials to the hook', () => {+ const w = world()+ expect(w.binding.read(w.actor)).toBeNull()+ const grant = w.binding.receive(w.actor, { kind: 'probe' })+ const payload = { kind: 'observe', challenge: grant.challenge, nativeVersion: '1.18.34', snapshot }+ expect(w.binding.receive(w.actor, payload)).toEqual({ observe: true, recorded: true })+ expect(w.binding.receive(w.actor, payload)).toEqual({ observe: false })+ expect(w.binding.read(w.actor)).toEqual(snapshot)+ w.binding.read(w.actor)!.auth.key = 'mutated-caller-copy'+ expect(w.binding.read(w.actor)!.auth.key).toBe('synthetic-account-a')+})++it('keeps identical native credentials bound to the Harness owner who authorized them', () => {+ const w = world(); w.observe()+ const before = w.binding.identity(w.actor)+ expect(before).toMatch(/^[a-f0-9]{64}$/)+ w.set({ ...w.owner(), ownerKey: 'replacement-owner' })+ expect(w.binding.identity(w.actor)).toBeNull()+ w.observe()+ expect(w.binding.identity(w.actor)).not.toBe(before)+})++it.each(['ownerKey', 'agentId', 'sessionId', 'processKey'] as const)('withdraws credentials and pending grants after %s changes', field => {+ const w = world(); w.observe()+ const grant = w.binding.receive(w.actor, { kind: 'probe' })+ w.set({ ...w.owner(), [field]: 'replacement' })+ expect(w.binding.read(w.actor)).toBeNull()+ expect(w.binding.receive(w.actor, { kind: 'observe', challenge: grant.challenge, nativeVersion: '1.18.34', snapshot })).toEqual({ observe: false })+})++it('refuses another process/session without erasing the selected companion binding', () => {+ const w = world(); w.observe()+ expect(w.binding.receive({ ...w.actor, sessionId: 'subagent' }, { kind: 'probe' })).toEqual({ observe: false })+ expect(w.binding.read(w.actor)).toEqual(snapshot)+})++it('withdraws on off/consent loss and does not resurrect credentials when reenabled', () => {+ const w = world(); w.observe(); const owner = w.owner()+ w.set(null)+ expect(w.binding.read(w.actor)).toBeNull()+ w.set(owner)+ expect(w.binding.read(w.actor)).toBeNull()+ expect(w.observe()).toEqual({ observe: true, recorded: true })+ w.binding.clear()+ expect(w.binding.read(w.actor)).toBeNull()+})++it('withdraws a changed model and waits for a matching native request', () => {+ const w = world(); w.observe()+ w.set({ ...w.owner(), model: 'changed/model' })+ expect(w.binding.read(w.actor)).toBeNull()+ expect(w.observe()).toEqual({ observe: false })+ w.set({ ...w.owner(), model: null })+ expect(w.binding.read(w.actor)).toBeNull()+ w.observe()+ expect(w.binding.read(w.actor)).toEqual(snapshot)+})++it('expires grants and observations, and withdraws old credentials before an unsupported new request', () => {+ const w = world()+ const grant = w.binding.receive(w.actor, { kind: 'probe' })+ w.advance(5000)+ expect(w.binding.receive(w.actor, { kind: 'observe', challenge: grant.challenge, nativeVersion: '1.18.34', snapshot })).toEqual({ observe: false })+ w.observe(); w.advance(15 * 60_000)+ expect(w.binding.read(w.actor)).toBeNull()+ w.observe()+ expect(w.observe({ ...snapshot, auth: { type: 'oauth', access: 'unsupported' } })).toEqual({ observe: false })+ expect(w.binding.read(w.actor)).toBeNull()+})diff --git a/cli/src/memory/opencodeBinding.ts b/cli/src/memory/opencodeBinding.tsnew file mode 100644index 000000000..558e0a445--- /dev/null+++ b/cli/src/memory/opencodeBinding.ts@@ -0,0 +1,65 @@+/** One volatile credential binding for the owner's selected, live OpenCode companion. */+import { randomUUID } from 'node:crypto'+import { z } from 'zod'+import { digest } from './admission.js'+import { openCodeSnapshotIdentity, parseOpenCodeMemorySnapshot, type OpenCodeMemorySnapshot } from './opencodeInference.js'++export interface OpenCodeMemoryActor { agentId: string; sessionId: string; processKey: string }+export interface OpenCodeMemoryOwner extends OpenCodeMemoryActor { ownerKey: string; model: string | null }+interface Deps { current(): OpenCodeMemoryOwner | null; now?: () => number }+const probe = z.object({ kind: z.literal('probe') }).strict()+const observation = z.object({ kind: z.literal('observe'), challenge: z.string().uuid(),+ nativeVersion: z.literal('1.18.34'), snapshot: z.unknown() }).strict()++/** Nothing here is serialized, logged, sent to clients, or reused after an owner/process change. */+export class OpenCodeMemoryBinding {+ private pending: { challenge: string; key: string; until: number } | null = null+ private observed: { snapshot: OpenCodeMemorySnapshot; key: string; until: number } | null = null+ private readonly now: () => number+ constructor(private readonly deps: Deps) { this.now = deps.now ?? Date.now }++ clear(): void { this.pending = null; this.observed = null }++ private context(actor?: OpenCodeMemoryActor): { owner: OpenCodeMemoryOwner; key: string } | null {+ const owner = this.deps.current()+ if (!owner || !owner.ownerKey || !owner.sessionId || !owner.processKey) { this.clear(); return null }+ const key = digest([owner.ownerKey, owner.agentId, owner.sessionId, owner.processKey])+ if (this.observed && (this.observed.key !== key || this.observed.until <= this.now()+ || (owner.model && owner.model !== this.observed.snapshot.model))) this.observed = null+ if (this.pending && (this.pending.key !== key || this.pending.until <= this.now())) this.pending = null+ if (actor && (actor.agentId !== owner.agentId || actor.sessionId !== owner.sessionId || actor.processKey !== owner.processKey)) return null+ return { owner, key }+ }++ /** The hook asks before reading or handing over its selected provider's credentials. */+ receive(actor: OpenCodeMemoryActor, input: unknown): Record<string, unknown> {+ const context = this.context(actor)+ if (!context) return { observe: false }+ if (probe.safeParse(input).success) {+ // A new foreground request withdraws the earlier selection even if the new one is unsupported.+ this.observed = null+ this.pending = { challenge: randomUUID(), key: context.key, until: this.now() + 5_000 }+ return { observe: true, challenge: this.pending.challenge }+ }+ const result = observation.safeParse(input)+ if (!result.success || !this.pending || result.data.challenge !== this.pending.challenge || this.pending.key !== context.key) return { observe: false }+ this.pending = null+ try {+ const snapshot = parseOpenCodeMemorySnapshot(result.data.snapshot)+ if (context.owner.model && snapshot.model !== context.owner.model) return { observe: false }+ this.observed = { snapshot, key: context.key, until: this.now() + 15 * 60_000 }+ return { observe: true, recorded: true }+ } catch { this.observed = null; return { observe: false } }+ }++ read(actor: OpenCodeMemoryActor): OpenCodeMemorySnapshot | null {+ const context = this.context(actor), snapshot = this.observed?.snapshot+ if (!context || !snapshot) return null+ return structuredClone(snapshot)+ }++ identity(actor: OpenCodeMemoryActor): string | null {+ const snapshot = this.read(actor)+ return snapshot && this.observed ? digest([this.observed.key, openCodeSnapshotIdentity(snapshot)]) : null+ }+}diff --git a/cli/src/memory/opencodeInference.spec.ts b/cli/src/memory/opencodeInference.spec.tsnew file mode 100644index 000000000..c7f1f41ea--- /dev/null+++ b/cli/src/memory/opencodeInference.spec.ts@@ -0,0 +1,161 @@+import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { lstat } from 'node:fs/promises'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'+import { openCodeSnapshotIdentity, opencodeMemoryCapability, runOpenCodeMemoryInference, type OpenCodeMemorySnapshot } from './opencodeInference.js'++vi.mock('node:fs/promises', async importOriginal => {+ const original = await importOriginal<typeof import('node:fs/promises')>()+ return { ...original, lstat: vi.fn(original.lstat) }+})++let directory: string, binary: string+beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), 'opencode-memory-test-'))+ binary = join(directory, 'opencode-fixture'); vi.stubEnv('OPENCODE_PATH', binary)+})+afterEach(() => { vi.unstubAllEnvs(); vi.mocked(lstat).mockReset(); rmSync(directory, { recursive: true, force: true }) })+const snapshot: OpenCodeMemorySnapshot = { model: 'selected/model', variant: 'high', auth: { type: 'api', key: 'synthetic-account-a' },+ provider: { npm: '@ai-sdk/openai-compatible', options: { baseURL: 'https://selected.invalid/v1' },+ models: { model: { name: 'Selected model', limit: { context: 128_000, output: 4096 } } } } }+const event = (type: string, part: Record<string, unknown>) => ({ type, sessionID: 'session',+ part: { sessionID: 'session', messageID: 'message', ...part } })+const start = event('step_start', { type: 'step-start' })+const text = (value = '{"proposals":[]}') => event('text', { type: 'text', id: 'text', text: value })+const finish = event('step_finish', { type: 'step-finish', reason: 'stop' })+const emit = (events: unknown[]) => events.map(value => `console.log(${JSON.stringify(JSON.stringify(value))})`).join(';')+function program(body = emit([start, text(), finish]), version = '1.18.34'): void {+ writeFileSync(binary, `#!${process.execPath}+if(process.argv.includes('--version')){ console.log('${version}'); process.exit(0) }+let input='';process.stdin.on('data',chunk=>input+=chunk);process.stdin.on('end',()=>{${body}})+`, { mode: 0o700 })+}+function options() {+ return { cwd: directory, prompt: 'synthetic evidence', model: snapshot.model, timeoutMs: 2000,+ expectedSnapshot: openCodeSnapshotIdentity(snapshot), readSnapshot: vi.fn(async () => snapshot) }+}++it('uses only the bound provider, credential, model and variant in disposable native storage', async () => {+ const output = join(directory, 'launch.json')+ program(`const env=process.env;+ require('node:fs').writeFileSync(${JSON.stringify(output)},JSON.stringify({args:process.argv.slice(2),cwd:process.cwd(),prompt:input,+ auth:JSON.parse(env.OPENCODE_AUTH_CONTENT),config:JSON.parse(env.OPENCODE_CONFIG_CONTENT),db:env.OPENCODE_DB,+ originalConfig:env.OPENCODE_CONFIG,foreignKey:env.OPENAI_API_KEY,tmux:env.TMUX,nodeOptions:env.NODE_OPTIONS}));+ ${emit([start, text(), finish])}`)+ vi.stubEnv('OPENAI_API_KEY', 'unselected-account'); vi.stubEnv('OPENCODE_CONFIG', '/unselected/provider.json')+ vi.stubEnv('TMUX', 'foreground-pane'); vi.stubEnv('NODE_OPTIONS', '--require=unselected-hook')+ const opts = options()+ expect(await runOpenCodeMemoryInference(opts)).toEqual({ text: '{"proposals":[]}' })+ expect(opts.readSnapshot).toHaveBeenCalledTimes(3)+ const launch = JSON.parse(readFileSync(output, 'utf8'))+ expect(launch.args).toEqual(['run', '--pure', '--format', 'json', '--model', snapshot.model, '--agent', 'harness_memory',+ '--title', 'Private coding memory', '--variant', 'high'])+ expect(launch.auth).toEqual({ selected: snapshot.auth })+ expect(launch.config).toMatchObject({ model: snapshot.model, small_model: snapshot.model, enabled_providers: ['selected'],+ permission: { '*': 'deny' }, agent: { harness_memory: { permission: { '*': 'deny' } } }, provider: { selected: snapshot.provider } })+ for (const key of ['originalConfig', 'foreignKey', 'tmux', 'nodeOptions']) expect(launch[key]).toBeUndefined()+ expect(launch.cwd).toContain('/opencode-memory-')+ expect(launch.db).toContain('/opencode-memory-')+ expect(launch.prompt).toBe('synthetic evidence')+ expect(readdirSync(directory).filter(name => name.startsWith('opencode-memory-'))).toEqual([])+})++it.each(['model', 'variant', 'auth', 'provider'] as const)('rejects a changed %s before launching a leased prompt', async field => {+ program('process.exit(9)')+ const changed = { ...snapshot, [field]: field === 'model' ? 'other/model' : field === 'variant' ? 'low'+ : field === 'auth' ? { type: 'api', key: 'synthetic-account-b' } : { ...snapshot.provider, options: { baseURL: 'https://other.invalid' } } }+ await expect(runOpenCodeMemoryInference({ ...options(), readSnapshot: async () => changed }))+ .rejects.toThrow('inference_context_changed')+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])+})++it('rechecks the binding immediately before invocation and after output, then removes temporary state', async () => {+ program()+ for (const failAt of [2, 3]) {+ let reads = 0+ await expect(runOpenCodeMemoryInference({ ...options(), readSnapshot: async () => ++reads === failAt ? null : snapshot }))+ .rejects.toThrow('inference_context_changed')+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])+ }+})++it('preserves final synchronous host authorization after asynchronous snapshot checks', async () => {+ program('process.exit(9)')+ await expect(runOpenCodeMemoryInference({ ...options(), assertAuthorized: () => { throw new Error('owner_changed') } }))+ .rejects.toThrow('owner_changed')+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])+})++it.each([+ event('tool_use', { type: 'tool', tool: 'bash', state: { status: 'error' } }),+ event('step_finish', { type: 'step-finish', reason: 'tool-calls' }),+])('rejects even unsuccessful native tool attempts before a later answer', bad => {+ program(emit([start, bad, text(), finish]))+ return expect(runOpenCodeMemoryInference(options())).rejects.toThrow('inference_tool_or_error')+})++it.each([+ [text(), finish],+ [start, text()],+ [start, text(), finish, start],+ [start, { ...text(), sessionID: 'another-session' }, finish],+ [start, text('first'), text('different'), finish],+ [start, { type: 'unknown_event' }, text(), finish],+].map(events => ({ events })))('rejects partial, mixed, rewritten or changed-protocol output', ({ events }) => {+ program(emit(events))+ return expect(runOpenCodeMemoryInference(options())).rejects.toThrow()+})++it('combines complete native text parts without duplicating repeated full snapshots', async () => {+ program(emit([start, text('{"pro'), text('{"proposals":'), event('text', { type: 'text', id: 'second', text: '[]}' }), finish]))+ expect(await runOpenCodeMemoryInference(options())).toEqual({ text: '{"proposals":[]}' })+})++it('retains only native usage and cost, leaving the provider-resolved model unknown', async () => {+ program(emit([start, text(), event('step_finish', { type: 'step-finish', reason: 'stop', cost: 0.02,+ tokens: { input: 20, output: 10, cache: { read: 4, write: 5 }, private: 'ignored' } })]))+ const observations: unknown[] = []+ await runOpenCodeMemoryInference({ ...options(), observe: value => { observations.push(value) } })+ expect(observations).toEqual([{ reportedCostUsd: 0.02, usage: { inputTokens: 20, outputTokens: 10,+ cacheReadInputTokens: 4, cacheCreationInputTokens: 5 } }])+})++it('does not probe accounts or invoke an uncertified version', async () => {+ program('process.exit(9)', '2.0.0')+ expect(await opencodeMemoryCapability()).toEqual({ supported: false, version: '2.0.0' })+ const opts = options()+ await expect(runOpenCodeMemoryInference(opts)).rejects.toThrow('opencode_version_uncertified')+ expect(opts.readSnapshot).not.toHaveBeenCalled()+})++it.each(['present', 'unreadable'])('refuses %s managed policy instead of overriding it', async kind => {+ program('process.exit(9)')+ if (kind === 'present') vi.mocked(lstat).mockResolvedValue({} as Awaited<ReturnType<typeof lstat>>)+ else vi.mocked(lstat).mockRejectedValue(Object.assign(new Error('unreadable'), { code: 'EACCES' }))+ const opts = options()+ await expect(runOpenCodeMemoryInference(opts)).rejects.toThrow('opencode_managed_config_unsupported')+ expect(opts.readSnapshot).not.toHaveBeenCalled()+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])+})++it('refuses unresolved routing, implicit model definitions and nested executable providers', () => {+ for (const provider of [+ { ...snapshot.provider, npm: 'file:///tmp/provider.mjs' },+ { ...snapshot.provider, models: {} },+ { ...snapshot.provider, models: { model: {}, other: {} } },+ { ...snapshot.provider, models: { model: { provider: { npm: 'unselected-package' } } } },+ { ...snapshot.provider, options: { baseURL: '{env:UNSELECTED_URL}' } },+ { ...snapshot.provider, options: { apiKey: '{file:/private/credential}' } },+ { ...snapshot.provider, options: { baseURL: 'https://${UNSELECTED_HOST}/v1' } },+ ]) expect(() => openCodeSnapshotIdentity({ ...snapshot, provider } as OpenCodeMemorySnapshot)).toThrow()+})++it('cancels a running native process and cleans up its private session storage', async () => {+ program('setTimeout(()=>{},10000)')+ const controller = new AbortController()+ const assertion = expect(runOpenCodeMemoryInference({ ...options(), signal: controller.signal })).rejects.toThrow('inference_cancelled')+ setTimeout(() => controller.abort(), 100)+ await assertion+ expect(readdirSync(directory)).toEqual(['opencode-fixture'])+})diff --git a/cli/src/memory/opencodeInference.ts b/cli/src/memory/opencodeInference.tsnew file mode 100644index 000000000..35b62eeee--- /dev/null+++ b/cli/src/memory/opencodeInference.ts@@ -0,0 +1,164 @@+/** Isolated OpenCode extraction. A host-bound snapshot is required; native defaults are never guessed. */+import { execFile } from 'node:child_process'+import { lstat, mkdtemp, mkdir, rm } from 'node:fs/promises'+import { userInfo } from 'node:os'+import { join } from 'node:path'+import { promisify } from 'node:util'+import { z } from 'zod'+import { digest } from './admission.js'+import { nativeMemoryEnvironment } from './account.js'+import { MemoryError, parse } from './types.js'+import { nativeMemoryUsage, runInferenceProcess, type MemoryInferenceOptions, type InferenceFrame } from './inferenceProcess.js'++const exec = promisify(execFile)+const bundledSdks = ['@ai-sdk/openai-compatible', '@ai-sdk/openai', '@ai-sdk/anthropic'] as const+function resolvedProvider(value: unknown): boolean {+ if (typeof value === 'string') return !/\{(?:env|file):|\$\{/.test(value)+ if (!value || typeof value !== 'object') return true+ return Object.entries(value).every(([key, child]) => (key !== 'npm' || bundledSdks.includes(child as typeof bundledSdks[number]))+ && resolvedProvider(child))+}+const snapshotSchema = z.object({+ model: z.string().max(200).regex(/^[a-z0-9][\w.-]*\/[\w./-]+$/i),+ variant: z.string().max(40).regex(/^[a-z][a-z0-9_-]*$/).optional(),+ // API credentials are the first supported native auth type. OAuth needs separate refresh/account certification.+ auth: z.object({ type: z.literal('api'), key: z.string().min(1).max(8_000),+ metadata: z.record(z.string().max(200), z.string().max(2_000)).optional() }).strict(),+ provider: z.object({+ name: z.string().max(200).optional(),+ // Do not let a provider snapshot load arbitrary npm packages or local executable modules.+ npm: z.enum(bundledSdks),+ options: z.record(z.string(), z.json()).optional(),+ models: z.record(z.string(), z.json()),+ }).strict().refine(resolvedProvider),+}).strict().refine(value => Buffer.byteLength(JSON.stringify(value)) <= 48_000+ && Object.keys(value.provider.models).length === 1+ && Object.hasOwn(value.provider.models, value.model.slice(value.model.indexOf('/') + 1)))++/** Supplied by a native account/config observer, never by an extraction response or remembered text. */+export type OpenCodeMemorySnapshot = z.infer<typeof snapshotSchema>+export function parseOpenCodeMemorySnapshot(value: unknown): OpenCodeMemorySnapshot {+ return parse(snapshotSchema, value)+}+export interface OpenCodeMemoryInferenceOptions extends MemoryInferenceOptions {+ expectedSnapshot: string+ /** Fresh observation of the same selected runtime's provider, account, model and variant. */+ readSnapshot: () => Promise<OpenCodeMemorySnapshot | null>+}++export function openCodeSnapshotIdentity(value: OpenCodeMemorySnapshot): string {+ return digest(parse(snapshotSchema, value))+}++export async function opencodeMemoryCapability(signal?: AbortSignal): Promise<{ supported: boolean; version: string | null }> {+ try {+ const result = await exec(process.env.OPENCODE_PATH || 'opencode', ['--version'], {+ timeout: 5_000, maxBuffer: 2_000, env: nativeMemoryEnvironment(), ...(signal ? { signal } : {}),+ })+ const version = /^(\d+\.\d+\.\d+)$/.exec(result.stdout.trim())?.[1] ?? null+ return { supported: version === '1.18.34', version }+ } catch { return { supported: false, version: null } }+}++export async function runOpenCodeMemoryInference(options: OpenCodeMemoryInferenceOptions): Promise<{ text: string }> {+ if (options.signal?.aborted) throw new MemoryError('inference_cancelled')+ if (!options.model || Buffer.byteLength(options.prompt) > 120_000 || !/^[a-f0-9]{64}$/.test(options.expectedSnapshot)) throw new MemoryError('invalid_inference_input')+ await assertNoManagedConfig()+ const capability = await opencodeMemoryCapability(options.signal)+ if (options.signal?.aborted) throw new MemoryError('inference_cancelled')+ if (!capability.supported) throw new MemoryError('opencode_version_uncertified')+ const read = async (): Promise<OpenCodeMemorySnapshot> => {+ await assertNoManagedConfig()+ const raw = await options.readSnapshot()+ if (!raw) throw new MemoryError('inference_context_changed')+ const snapshot = parse(snapshotSchema, raw)+ if (snapshot.model !== options.model || digest(snapshot) !== options.expectedSnapshot) throw new MemoryError('inference_context_changed')+ return snapshot+ }+ const snapshot = await read()+ const providerId = snapshot.model.slice(0, snapshot.model.indexOf('/'))+ const config = JSON.stringify({ autoupdate: false, share: 'disabled', snapshot: false,+ model: snapshot.model, small_model: snapshot.model, enabled_providers: [providerId],+ permission: { '*': 'deny' }, plugin: [], mcp: {}, instructions: [],+ agent: { harness_memory: { mode: 'primary', description: 'Private coding memory extraction',+ prompt: 'Extract only the requested JSON from the supplied historical evidence. Do not use tools.',+ permission: { '*': 'deny' }, steps: 1 } },+ provider: { [providerId]: snapshot.provider },+ })+ // Strings are immutable snapshots. A later caller mutation cannot change credentials or routing mid-launch.+ const auth = JSON.stringify({ [providerId]: snapshot.auth })+ const directory = await mkdtemp(join(options.cwd, 'opencode-memory-'))+ try {+ for (const name of ['home', 'config', 'data', 'cache', 'state', 'work']) await mkdir(join(directory, name), { mode: 0o700 })+ const environment = { ...nativeMemoryEnvironment(), 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: join(directory, 'opencode.db'), OPENCODE_CONFIG_CONTENT: config, OPENCODE_AUTH_CONTENT: auth,+ OPENCODE_DISABLE_PROJECT_CONFIG: '1', OPENCODE_DISABLE_AUTOUPDATE: '1', OPENCODE_DISABLE_MODELS_FETCH: '1',+ OPENCODE_DISABLE_AUTOCOMPACT: '1',+ }+ const args = ['run', '--pure', '--format', 'json', '--model', snapshot.model, '--agent', 'harness_memory',+ '--title', 'Private coding memory', ...(snapshot.variant ? ['--variant', snapshot.variant] : [])]+ const result = await runInferenceProcess({ ...options, cwd: join(directory, 'work'), beforeRun: async () => {+ await options.beforeRun?.()+ await read()+ } }, process.env.OPENCODE_PATH || 'opencode', args, environment, openCodeMemoryDecoder())+ await read()+ return result+ } finally { await rm(directory, { recursive: true, force: true }) }+}++/** Native 1.18.34 merges system policy after inline configuration. Refuse, never bypass it. */+async function assertNoManagedConfig(): Promise<void> {+ const directory = process.platform === 'darwin' ? '/Library/Application Support/opencode'+ : process.platform === 'win32' ? join('C:\\ProgramData', 'opencode') : '/etc/opencode'+ const paths = ['opencode.json', 'opencode.jsonc'].map(name => join(directory, name))+ if (process.platform === 'darwin') {+ let username = 'user'+ try { username = userInfo().username || username } catch { /* Match the native fallback. */ }+ paths.push(join('/Library/Managed Preferences', username, 'ai.opencode.managed.plist'),+ '/Library/Managed Preferences/ai.opencode.managed.plist')+ }+ for (const path of paths) {+ try { await lstat(path) }+ catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') continue+ throw new MemoryError('opencode_managed_config_unsupported')+ }+ throw new MemoryError('opencode_managed_config_unsupported')+ }+}++/** Events observed on native 1.18.34, including rejected forced tool calls. */+function openCodeMemoryDecoder(): (event: Record<string, unknown>) => InferenceFrame {+ let started = false, completed = false, session: unknown, message: unknown+ const text = new Map<string, string>()+ return event => {+ if (event.type === 'tool_use') return { error: 'inference_tool_or_error' }+ if (event.type === 'error') return { error: /rate.?limit|quota|usage limit/i.test(JSON.stringify(event.error))+ ? 'inference_usage_limit' : 'inference_unavailable' }+ const part = event.part as Record<string, unknown> | undefined+ if (!part || typeof part !== 'object' || !['step_start', 'text', 'step_finish'].includes(String(event.type))) return { error: 'inference_protocol_changed' }+ if (event.type === 'step_start') {+ if (started || completed || part.type !== 'step-start' || typeof event.sessionID !== 'string' || typeof part.messageID !== 'string') return { error: 'inference_protocol_changed' }+ started = true; session = event.sessionID; message = part.messageID+ return {}+ }+ if (!started || completed || event.sessionID !== session || part.sessionID !== session || part.messageID !== message) return { error: 'inference_protocol_changed' }+ if (event.type === 'text') {+ if (part.type !== 'text' || typeof part.id !== 'string' || typeof part.text !== 'string'+ || !part.text.startsWith(text.get(part.id) ?? '')) return { error: 'invalid_inference_output' }+ text.set(part.id, part.text)+ return { text: [...text.values()].join('') }+ }+ if (part.type !== 'step-finish' || part.reason !== 'stop') return { error: 'inference_tool_or_error' }+ completed = true+ const tokens = part.tokens as Record<string, unknown> | undefined+ const cache = tokens?.cache as Record<string, unknown> | undefined+ return { completed: true, observation: {+ usage: nativeMemoryUsage({ input_tokens: tokens?.input, output_tokens: tokens?.output,+ cache_read_input_tokens: cache?.read, cache_creation_input_tokens: cache?.write }),+ ...(typeof part.cost === 'number' && Number.isFinite(part.cost) && part.cost >= 0 ? { reportedCostUsd: part.cost } : {}),+ } }+ }+}diff --git a/cli/src/pair/intelligence.spec.ts b/cli/src/pair/intelligence.spec.tsindex 34b236294..3dfc3137e 100644--- a/cli/src/pair/intelligence.spec.ts+++ b/cli/src/pair/intelligence.spec.ts@@ -5,6 +5,7 @@ import { join } from 'node:path'import { CompanionIntelligence, type CompanionRuntime } from './intelligence.js'import { encodeRuntimeProfile } from '../lib/runtimeProfile.js'import type { OneShotOptions } from '../lib/oneshot.js'+import { openCodeSnapshotIdentity, type OpenCodeMemorySnapshot, type OpenCodeMemoryInferenceOptions } from '../memory/opencodeInference.js'let directory: stringbeforeEach(() => { directory = mkdtempSync(join(tmpdir(), 'collection-model-')) })@@ -148,3 +149,71 @@ describe('the collection DSH supplies its intelligence', () => {expect(w.run).not.toHaveBeenCalled()})})++describe('OpenCode companion request binding', () => {+ function openCodeWorld() {+ const w = world()+ w.set({ ...w.get(), engine: 'opencode', nativeProcessKey: 'native-process', accountKey: 'harness-owner-binding', profile: null, customProvider: true })+ let snapshot: OpenCodeMemorySnapshot | null = { model: 'selected/model', variant: 'high',+ auth: { type: 'api', key: 'synthetic-selected-account' }, provider: {+ npm: '@ai-sdk/openai-compatible', options: { baseURL: 'https://selected.invalid/v1' },+ models: { model: { name: 'Selected', limit: { context: 10000, output: 1000 } } },+ } }+ const run = vi.fn<(options: OpenCodeMemoryInferenceOptions) => Promise<{ text: string }>>(async options => {+ await options.beforeRun?.(); options.assertAuthorized?.()+ return { text: '{"proposals":[]}' }+ })+ const accountIdentity = vi.fn(async () => 'must-not-fall-back')+ const brain = new CompanionIntelligence({ ...w.deps, openCodeSnapshot: () => snapshot, runOpenCode: run, accountIdentity })+ return { ...w, brain, openCodeRun: run, accountIdentity, snapshot: () => snapshot!, setSnapshot: (value: OpenCodeMemorySnapshot | null) => { snapshot = value } }+ }++ it('uses the foreground model/account/variant for extraction and ordinary companion intelligence', async () => {+ const w = openCodeWorld()+ expect(w.brain.status()).toMatchObject({ state: 'ready', engine: 'opencode', model: 'selected/model', effort: 'high' })+ const contextKey = (await w.brain.extractionStatus()).contextKey!+ expect(await w.brain.extract('coding evidence', { contextKey, timeoutMs: 1000, signal: new AbortController().signal })).toBe('{"proposals":[]}')+ expect(w.openCodeRun).toHaveBeenLastCalledWith(expect.objectContaining({ model: 'selected/model', expectedSnapshot: openCodeSnapshotIdentity(w.snapshot()) }))+ expect(await w.openCodeRun.mock.calls[0][0].readSnapshot()).toEqual(w.snapshot())+ await w.brain.run('companion triage', { timeoutMs: 1000, signal: new AbortController().signal })+ expect(w.openCodeRun).toHaveBeenCalledTimes(2)+ expect(w.run).not.toHaveBeenCalled()+ expect(w.accountIdentity).not.toHaveBeenCalled()+ expect(readFileSync(w.deps.stateFile, 'utf8')).not.toContain('synthetic-selected-account')+ })++ it('waits for live observation, never falling back to another provider or saved OpenCode profile', async () => {+ const w = openCodeWorld()+ w.brain.status()+ w.setSnapshot(null)+ expect(w.brain.status().state).toBe('waiting')+ expect(await w.brain.run('triage', { timeoutMs: 1000, signal: new AbortController().signal })).toBeNull()+ w.set({ ...w.get(), stopped: true })+ expect(w.brain.status().state).toBe('waiting')+ expect(w.openCodeRun).not.toHaveBeenCalled()+ expect(w.run).not.toHaveBeenCalled()+ })++ it('rejects a queued extraction after the observed account changes', async () => {+ const w = openCodeWorld(), contextKey = (await w.brain.extractionStatus()).contextKey!+ w.setSnapshot({ ...w.snapshot(), auth: { type: 'api', key: 'replacement-account' } })+ await expect(w.brain.extract('leased evidence', { contextKey, timeoutMs: 1000, signal: new AbortController().signal })).rejects.toThrow('inference_context_changed')+ expect(w.openCodeRun).not.toHaveBeenCalled()+ })++ it.each(['account', 'variant', 'process', 'owner', 'off'] as const)('discards a running extraction after %s changes', async change => {+ const w = openCodeWorld(), contextKey = (await w.brain.extractionStatus()).contextKey!+ let finish!: (value: { text: string }) => void+ w.openCodeRun.mockImplementation(() => new Promise(resolve => { finish = resolve }))+ const result = w.brain.extract('evidence', { contextKey, timeoutMs: 1000, signal: new AbortController().signal })+ await vi.waitFor(() => expect(w.openCodeRun).toHaveBeenCalledOnce())+ if (change === 'account') w.setSnapshot({ ...w.snapshot(), auth: { type: 'api', key: 'replacement' } })+ if (change === 'variant') w.setSnapshot({ ...w.snapshot(), variant: 'low' })+ if (change === 'process') w.set({ ...w.get(), nativeProcessKey: 'new-native-process' })+ if (change === 'owner') w.set({ ...w.get(), accountKey: 'replacement-harness-owner-binding' })+ if (change === 'off') w.off()+ await expect(w.openCodeRun.mock.calls[0][0].beforeRun!()).rejects.toThrow('inference_context_changed')+ finish({ text: 'old-context-answer' })+ expect(await result).toBeNull()+ })+})diff --git a/cli/src/pair/intelligence.ts b/cli/src/pair/intelligence.tsindex 32de6cce3..fc063f5d0 100644--- a/cli/src/pair/intelligence.ts+++ b/cli/src/pair/intelligence.ts@@ -2,7 +2,7 @@import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'import { dirname } from 'node:path'import { createHash } from 'node:crypto'-import { parseRuntimeProfile, type RuntimeProfile } from '../lib/runtimeProfile.js'+import { encodeRuntimeProfile, parseRuntimeProfile, type RuntimeProfile } from '../lib/runtimeProfile.js'import { runClaudeOneShot, runCodexOneShot, type OneShotOptions } from '../lib/oneshot.js'import type { PairOneShot } from './triage.js'import type { StartupProfile } from './startupProfile.js'@@ -12,6 +12,8 @@ import { memoryAccountIdentity } from '../memory/account.js'import type { MemoryInference, MemoryInferenceRunOptions } from '../memory/learner.js'import type { MemoryInferenceOptions } from '../memory/inferenceProcess.js'import { MemoryError } from '../memory/types.js'+import { openCodeSnapshotIdentity, runOpenCodeMemoryInference,+ type OpenCodeMemorySnapshot, type OpenCodeMemoryInferenceOptions } from '../memory/opencodeInference.js'export interface CompanionRuntime {agentId: string@@ -21,6 +23,7 @@ export interface CompanionRuntime {stopped: booleancodexHome?: string | nullcustomProvider?: boolean+ nativeProcessKey?: string | null/** Opaque observed account identity, when supplied by the native host. */accountKey?: string | nullstartup?: StartupProfile | null@@ -42,6 +45,9 @@ interface IntelligenceDeps {stateFile: stringrun?: (engine: 'claude' | 'codex', options: MemoryInferenceOptions) => Promise<{ text: string }>accountIdentity?: (runtime: CompanionRuntime) => Promise<string | null>+ /** Volatile observation from the selected foreground process, with host consent checked on each read. */+ openCodeSnapshot?: (runtime: CompanionRuntime) => OpenCodeMemorySnapshot | null+ runOpenCode?: (options: OpenCodeMemoryInferenceOptions) => Promise<{ text: string }>}export class CompanionIntelligence {@@ -68,32 +74,38 @@ export class CompanionIntelligence {if (opts.signal?.aborted) controller.abort()this.calls.add(controller)try {- const target = extraction ? await this.extractionTarget() : this.target()+ const bound = extraction || this.deps.current()?.engine === 'opencode'+ const target = bound ? await this.extractionTarget() : this.target()if (controller.signal.aborted || !target.profile || !target.runtime || target.status.state !== 'ready') return nullif (extraction && (!('contextKey' in opts) || opts.contextKey !== target.status.contextKey)) throw new MemoryError('inference_context_changed')const { runtime, profile } = target- const engine = runtime.engine as 'claude' | 'codex'+ const engine = runtime.engine as 'claude' | 'codex' | 'opencode'const assertAuthorized = (): void => {if (controller.signal.aborted) throw new MemoryError('inference_cancelled')if ('assertAuthorized' in opts) opts.assertAuthorized?.()if (this.target().status.contextKey !== target.runtimeContextKey) throw new MemoryError('inference_context_changed')}- if (extraction) assertAuthorized()+ if (bound) assertAuthorized()mkdirSync(this.deps.directory, { recursive: true, mode: 0o700 })const options: MemoryInferenceOptions = {prompt, cwd: this.deps.directory, model: profile.model,...(profile.effort !== 'auto' ? { effort: profile.effort as OneShotOptions['effort'] } : {}),...(engine === 'codex' && runtime.codexHome ? { codexHome: runtime.codexHome } : {}),timeoutMs: opts.timeoutMs, signal: controller.signal,- ...(extraction ? { assertAuthorized, beforeRun: async () => {+ ...(bound ? { assertAuthorized, beforeRun: async () => {const current = await this.extractionTarget()if (current.status.state !== 'ready' || current.status.contextKey !== target.status.contextKey) throw new MemoryError('inference_context_changed')} } : {}),}const run = this.deps.run ?? ((engine, options) => engine === 'claude' ? extraction ? runClaudeMemoryInference(options) : runClaudeOneShot(options): extraction ? runCodexMemoryInference(options) : runCodexOneShot(options))- const result = await run(engine, options)- const current = extraction ? await this.extractionTarget() : this.target()+ const result = engine === 'opencode'+ ? await (this.deps.runOpenCode ?? runOpenCodeMemoryInference)({ ...options,+ expectedSnapshot: openCodeSnapshotIdentity(target.openCodeSnapshot!),+ readSnapshot: async () => this.target().openCodeSnapshot ?? null,+ })+ : await run(engine, options)+ const current = bound ? await this.extractionTarget() : this.target()// A result from an old model, account, or conversation is never accepted under the new one.if (controller.signal.aborted || current.status.state !== 'ready' ||current.runtime?.sessionId !== runtime.sessionId || current.profile?.id !== profile.id ||@@ -109,6 +121,7 @@ export class CompanionIntelligence {private async extractionTarget(): Promise<ReturnType<CompanionIntelligence['target']>> {const target = this.target()if (target.status.state !== 'ready' || !target.runtime) return target+ if (target.runtime.engine === 'opencode') return targetconst identity = target.runtime.accountKey ?? await (this.deps.accountIdentity ?? memoryAccountIdentity)(target.runtime)const current = this.target()if (current.status.contextKey !== target.status.contextKey || !identity) return { status: { ...current.status, state: 'waiting' } }@@ -116,24 +129,30 @@ export class CompanionIntelligence {contextKey: createHash('sha256').update(JSON.stringify([target.status.contextKey, identity])).digest('hex') } }}- private target(): { status: IntelligenceStatus; runtimeContextKey?: string; runtime?: CompanionRuntime; profile?: RuntimeProfile } {+ private target(): { status: IntelligenceStatus; runtimeContextKey?: string; runtime?: CompanionRuntime; profile?: RuntimeProfile;+ openCodeSnapshot?: OpenCodeMemorySnapshot } {if (!this.deps.enabled()) return { status: { state: 'off' } }const runtime = this.deps.current()if (!runtime) return { status: { state: 'unopened' } }const status: IntelligenceStatus = { state: 'waiting', agentId: runtime.agentId, engine: runtime.engine }// Custom provider credentials must not silently fall back to the local subscription.- if (!['claude', 'codex'].includes(runtime.engine) || runtime.customProvider) return { status: { ...status, state: 'unsupported' } }+ if (!['claude', 'codex', 'opencode'].includes(runtime.engine) || (runtime.customProvider && runtime.engine !== 'opencode')) return { status: { ...status, state: 'unsupported' } }+ const openCodeSnapshot = runtime.engine === 'opencode' ? this.deps.openCodeSnapshot?.(runtime) ?? undefined : undefined+ if (runtime.engine === 'opencode' && (!runtime.sessionId || runtime.stopped || !runtime.nativeProcessKey+ || !runtime.accountKey || !openCodeSnapshot)) return { status }if (!runtime.sessionId && (runtime.stopped || !runtime.startup)) return { status }this.load()const cached = this.saved![runtime.agentId]const value = runtime.sessionId- ? runtime.profile ?? (runtime.stopped && cached?.sessionId === runtime.sessionId ? cached.profile : null)+ ? runtime.profile ?? (openCodeSnapshot ? encodeRuntimeProfile({ sessionId: runtime.agentId, engine: 'opencode', model: openCodeSnapshot.model, effort: 'auto' })+ : runtime.stopped && cached?.sessionId === runtime.sessionId ? cached.profile : null): runtime.startup?.profileconst profile = parseRuntimeProfile(value)const efforts = runtime.engine === 'claude'? ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']- : ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']+ : runtime.engine === 'opencode' ? ['auto'] : ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultra']if (!profile || profile.sessionId !== runtime.agentId || profile.engine !== runtime.engine || !efforts.includes(profile.effort)) return { status }+ if (openCodeSnapshot && openCodeSnapshot.model !== profile.model) return { status }// Pre-conversation readiness is live evidence, never a durable substitute for a conversation ID.if (runtime.sessionId && (cached?.profile !== profile.id || cached.sessionId !== runtime.sessionId)) {this.saved![runtime.agentId] = { sessionId: runtime.sessionId, profile: profile.id }@@ -143,8 +162,10 @@ export class CompanionIntelligence {renameSync(tmp, this.deps.stateFile)}const contextKey = createHash('sha256').update(JSON.stringify([runtime.agentId, runtime.sessionId,- runtime.sessionId ? null : runtime.startup?.processKey, runtime.engine, profile.id, runtime.codexHome ?? null, runtime.accountKey ?? null])).digest('hex')- return { runtime, profile, runtimeContextKey: contextKey, status: { ...status, state: 'ready', model: profile.model, effort: profile.effort, contextKey } }+ runtime.sessionId ? null : runtime.startup?.processKey, runtime.engine, profile.id, runtime.codexHome ?? null, runtime.accountKey ?? null,+ runtime.nativeProcessKey ?? null, openCodeSnapshot ? openCodeSnapshotIdentity(openCodeSnapshot) : null])).digest('hex')+ return { runtime, profile, openCodeSnapshot, runtimeContextKey: contextKey,+ status: { ...status, state: 'ready', model: profile.model, effort: openCodeSnapshot?.variant ?? profile.effort, contextKey } }}private load(): void {diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.mdindex a03199c2b..0b58c22a8 100644--- a/docs/plans/2026-09-30-coding-memory-review-log.md+++ b/docs/plans/2026-09-30-coding-memory-review-log.md@@ -580,3 +580,75 @@ A fresh host check at 16:21 UTC showed the user had switched the companion fromCodex accounts still reported exhausted weekly limits; neither was substituted for the selectedcompanion. OpenCode integration is now the immediate requirement for the requested end-to-endtest. Actual Tim extraction and the held-out quality/rollout gates remain open.++### OpenCode extraction transport, isolated and not enabled++The capture repair merged in [PR 557](https://github.com/autonomous-ai/openharness/pull/557)+as `a6f2bd0ebcfebfdfa594460609942a99c62ee204` after all four CI jobs passed for the+exact submitted head. A fresh read of the running app still returned `DAEMONS_OFF`.+No setting, selected model, installed app or production memory was changed to bypass that state.++The new OpenCode adapter requires an explicit snapshot of the selected API account, provider,+model definition and variant. It checks the binding before launch and after output, isolates+native session storage, denies tools, and removes disposable state. Unknown versions, OAuth,+unresolved configuration placeholders, non-bundled provider modules and system managed policy+are unsupported. System policy is refused rather than overridden; native 1.18.34 loads it after+inline configuration. This is a version-specific native transport, not a process sandbox.++The [installed 1.18.34 probe](../research/2026-10-01-memory-opencode-inference.json) invoked the+actual adapter with fake credentials and localhost responses. Normal text passed; forced shell+and question tools were denied and rejected by the adapter, even though the native CLI retried+the model after the denied attempt. Every request exposed zero tools and the selected synthetic+credential/model. No forbidden file was created, and temporary session storage was removed.+Twenty-two focused tests, the full 378-check memory/companion suite and TypeScript checking passed.++This module is intentionally not connected to the companion yet. An authoritative observer for+the foreground OpenCode account/configuration and the host runtime binding still need to be+implemented. OpenCode capture and recall are separate remaining work. No real model evaluated+the user's private sample, and no model-quality, useful-memory or task-benefit claim follows+from the transport checks.++### OpenCode foreground binding and companion integration++The 1.x Harness plugin now observes the selected companion's native request. It asks the host+before inspecting credentials; the host grants a five-second, one-use challenge only for the+process-owned companion session while Coding memory, watching consent and Learn are enabled.+The observed provider, model alias, API credential and native variant stay in volatile memory.+No credential enters the session registry, saved profile, browser/device frames or research logs.+The binding expires after fifteen minutes and is withdrawn on an owner, process, session, selected+model or authorization change. Identical model credentials cannot carry a result across Harness+owners. Only the latest submitted `chat.message` and its selected agent may observe request settings.+Internal title, summary and compaction requests do not replace the user's selection.++`CompanionIntelligence` now uses this binding for OpenCode extraction and companion reasoning,+with checks before launch and after completion. It never guesses a provider from the machine's+default configuration or falls back to Claude/Codex. This requires a fresh foreground request+from the updated plugin; already-running OpenCode processes must restart to load it. The native+version remains pinned to 1.18.34. OAuth/function-based credential wrappers, managed system+configuration, other SDKs and OpenCode 2.x remain unsupported.++The [native binding probe](../research/2026-10-01-memory-opencode-binding.json) kept a disposable+OpenCode process alive, observed a real foreground request through the generated hook, and then+ran the actual companion extraction against a localhost model. Both a native API login and an+explicit provider-key override used the expected account, provider model ID and `high` variant.+Off sent no credential snapshot and launched no extraction; scratch storage was removed. The+first probe exposed the 1.x SDK's missing health wrapper, so the hook now uses that pinned SDK's+in-process HTTP client for `/global/health`; the corrected path was exercised natively.++A further native manual-compaction check caught an internal request replacing the user's `high`+variant with the compaction default. Matching the request to its submitted message and agent fixed+that regression. Both native account cases now compact and then extract with the original selected+variant, while compaction itself requests no observation grant. Synthetic continuations are also+excluded by the message binding; automatic compaction remains uncertified. The hook boundaries are+defined in the [pinned plugin interface](https://github.com/anomalyco/opencode/blob/v1.18.34/packages/plugin/src/index.ts).++Validation: **516 tests across 34 affected suites**, TypeScript checking and the CLI bundle passed.+The first unprivileged hook-server run could not bind localhost (`EPERM`); the permitted run passed.+The required real multiplexer suite ran in a separate temporary tmux 3.7c server: nine checks+passed, including discovery for Claude 2.1.287, Codex 0.159.3, OpenCode 1.18.34, Pi 0.85.1,+Hermes 0.18.0 (2026.7.1), Grok 1.0.44 and its `agent` alias. Nine unavailable engine rows were+skipped. This verifies discovery/lifecycle behavior, not those engines' memory-inference support.+These are synthetic integration results. The host's ownership/consent inputs are supplied by the+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.diff --git a/docs/research/2026-10-01-memory-opencode-binding.json b/docs/research/2026-10-01-memory-opencode-binding.jsonnew file mode 100644index 000000000..54b309b99--- /dev/null+++ b/docs/research/2026-10-01-memory-opencode-binding.json@@ -0,0 +1,182 @@+{+ "schema": 1,+ "purpose": "Native OpenCode foreground binding and companion extraction transport verification",+ "personalConversationsUsed": 0,+ "semanticQualityMeasured": false,+ "runs": [+ {+ "at": "2026-10-02T00:46:04.231Z",+ "version": "1.18.34",+ "keySource": "auth",+ "requests": [+ {+ "phase": "off",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "foreground",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "compaction",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "extraction",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ }+ ],+ "hooks": [+ {+ "phase": "off",+ "kind": "probe"+ },+ {+ "phase": "foreground",+ "kind": "probe"+ },+ {+ "phase": "foreground",+ "kind": "observe",+ "nativeVersion": "1.18.34",+ "model": "memory-fixture/alias",+ "variant": "high",+ "selectedCredential": true+ }+ ],+ "result": {+ "observedSelection": true,+ "selectedProcessAliveDuringExtraction": true,+ "inheritedAccountModelVariant": true,+ "manualCompactionPreservedSelection": true,+ "offSentCredentials": false,+ "offLaunchedExtraction": false,+ "credentialsPersistedInProfile": false,+ "privateStorageRemoved": true+ },+ "limitations": [+ "Synthetic localhost responses; no personal conversations or semantic-quality measurement.",+ "Consent and process ownership are fixture inputs; the actual hook-server authorization is covered separately.",+ "No OAuth, OpenCode 2.x, automatic compaction, capture or recall certification."+ ]+ },+ {+ "at": "2026-10-02T00:45:02.210Z",+ "version": "1.18.34",+ "keySource": "config",+ "requests": [+ {+ "phase": "off",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "foreground",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "compaction",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "tools": [],+ "selectedCredential": true+ },+ {+ "phase": "extraction",+ "route": "/v1/chat/completions",+ "model": "provider-native-id",+ "reasoningEffort": "high",+ "tools": [],+ "selectedCredential": true+ }+ ],+ "hooks": [+ {+ "phase": "off",+ "kind": "probe"+ },+ {+ "phase": "foreground",+ "kind": "probe"+ },+ {+ "phase": "foreground",+ "kind": "observe",+ "nativeVersion": "1.18.34",+ "model": "memory-fixture/alias",+ "variant": "high",+ "selectedCredential": true+ }+ ],+ "result": {+ "observedSelection": true,+ "selectedProcessAliveDuringExtraction": true,+ "inheritedAccountModelVariant": true,+ "manualCompactionPreservedSelection": true,+ "offSentCredentials": false,+ "offLaunchedExtraction": false,+ "credentialsPersistedInProfile": false,+ "privateStorageRemoved": true+ },+ "limitations": [+ "Synthetic localhost responses; no personal conversations or semantic-quality measurement.",+ "Consent and process ownership are fixture inputs; the actual hook-server authorization is covered separately.",+ "No OAuth, OpenCode 2.x, automatic compaction, capture or recall certification."+ ]+ }+ ],+ "validation": {+ "affectedTestFiles": 34,+ "affectedTestsPassed": 516,+ "typecheck": "passed",+ "bundle": "passed",+ "tmuxDiscovery": {+ "tmux": "3.7c",+ "isolatedServer": true,+ "passed": 9,+ "unavailableRows": 9,+ "engines": {+ "claude": "2.1.287",+ "codex": "0.159.3",+ "opencode": "1.18.34",+ "pi": "0.85.1",+ "hermes": "0.18.0 (2026.7.1)",+ "grok": "1.0.44"+ },+ "scope": "Installed process discovery, pane-preserving deletion, input and test-owned session lifecycle only"+ }+ },+ "limits": [+ "Local mock responses establish request routing and authorization behavior, not model understanding.",+ "Production daemon settings and the installed review app were not changed."+ ],+ "regressions": [+ {+ "case": "Manual native compaction with the same provider and model",+ "before": "Internal compaction replaced the user-selected high variant with its default.",+ "after": "Only chat.params for the latest submitted chat.message and its selected agent may observe credentials; the native compaction path does not request a grant."+ }+ ]+}diff --git a/docs/research/2026-10-01-memory-opencode-inference.json b/docs/research/2026-10-01-memory-opencode-inference.jsonnew file mode 100644index 000000000..f502a25f0--- /dev/null+++ b/docs/research/2026-10-01-memory-opencode-inference.json@@ -0,0 +1,78 @@+{+ "at": "2026-10-01T17:39:27.386Z",+ "capability": {+ "supported": true,+ "version": "1.18.34"+ },+ "runs": [+ {+ "mode": "text",+ "requests": [+ {+ "route": "/v1/chat/completions",+ "model": "memory-model",+ "tools": [],+ "selectedCredential": true+ }+ ],+ "snapshotReads": 3,+ "result": {+ "text": "{\"proposals\":[]}"+ },+ "forbiddenFileExists": false,+ "privateStorageRemoved": true+ },+ {+ "mode": "bash",+ "requests": [+ {+ "route": "/v1/chat/completions",+ "model": "memory-model",+ "tools": [],+ "selectedCredential": true+ },+ {+ "route": "/v1/chat/completions",+ "model": "memory-model",+ "tools": [],+ "selectedCredential": true+ }+ ],+ "snapshotReads": 2,+ "error": "inference_tool_or_error",+ "forbiddenFileExists": false,+ "privateStorageRemoved": true+ },+ {+ "mode": "question",+ "requests": [+ {+ "route": "/v1/chat/completions",+ "model": "memory-model",+ "tools": [],+ "selectedCredential": true+ },+ {+ "route": "/v1/chat/completions",+ "model": "memory-model",+ "tools": [],+ "selectedCredential": true+ }+ ],+ "snapshotReads": 2,+ "error": "inference_tool_or_error",+ "forbiddenFileExists": false,+ "privateStorageRemoved": true+ }+ ],+ "limitations": [+ "Synthetic localhost responses; no personal conversations or real model inference.",+ "Native transport only. Host account/config observation and companion wiring remain unimplemented.",+ "No claim about extraction quality, OAuth, automatic compaction or task benefit."+ ],+ "sources": [+ "https://raw.githubusercontent.com/anomalyco/opencode/v1.18.34/packages/opencode/src/auth/index.ts",+ "https://raw.githubusercontent.com/anomalyco/opencode/v1.18.34/packages/opencode/src/provider/provider.ts",+ "https://raw.githubusercontent.com/anomalyco/opencode/v1.18.34/packages/opencode/src/config/managed.ts"+ ]+}