Skip to content

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

Add Coding memory to Experimental settings (#539)

Dee7be7ae16afca
diff --git a/cli/src/backendSocket.memorySettings.spec.ts b/cli/src/backendSocket.memorySettings.spec.ts
new file mode 100644
index 000000000..7fd2bf8d0
--- /dev/null
+++ b/cli/src/backendSocket.memorySettings.spec.ts
@@ -0,0 +1,62 @@
+import { mkdtempSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, expect, it, vi } from 'vitest'
+import { BackendSocket } from './backendSocket.js'
+import { MemoryControl } from './memory/control.js'
+import { MemoryExperimentSettings } from './memory/experiment.js'
+
+afterEach(() => vi.restoreAllMocks())
+
+it('lets the verified local owner disable coding memory while companions stay off', async () => {
+ const directory = mkdtempSync(join(tmpdir(), 'memory-setting-route-'))
+ const settings = new MemoryExperimentSettings(directory)
+ const owner = 'a'.repeat(64)
+ settings.write(owner, true, 0)
+ const socket = new BackendSocket('fixture')
+ const runtime = vi.fn(() => null)
+ let person = true
+ const verify = vi.fn(async () => person ? { ok: true as const, pid: 123 }
+ : { ok: false as const, error: 'INSIDE_HARNESS' as const, detail: 'agent' })
+ const memory = new MemoryControl({ runtime, verify,
+ experiment: { owner: () => owner, read: key => settings.read(key),
+ write: async (key, enabled, expected) => settings.write(key, enabled, expected) } })
+ socket.daemonsOn = () => false
+ socket.pairControl = { verbs: new Set(['memory']), local: (payload, connId) => memory.local(payload, connId) }
+ const frames: Array<Record<string, any>> = []
+ vi.spyOn(socket, 'sendTo').mockImplementation((_to, frame) => { frames.push(frame) })
+ socket.registerLocalClient('local:settings', { sendFrame: () => true, sendBinary: () => true }, { tool: true })
+ const ask = async (input: Record<string, unknown>) => {
+ const requestId = String(frames.length)
+ socket.handleLocalFrame('local:settings', { type: 'pair', payload: { requestId, verb: 'memory', ...input } })
+ await vi.waitFor(() => expect(frames.some(frame => frame.payload?.requestId === requestId)).toBe(true))
+ return frames.find(frame => frame.payload?.requestId === requestId)!.payload
+ }
+ try {
+ expect(await ask({ action: 'experiment' })).toMatchObject({ ok: true, enabled: true, revision: 1 })
+ expect(await ask({ action: 'configure_experiment', enabled: false, expected: 1 }))
+ .toMatchObject({ ok: true, enabled: false, revision: 2 })
+ expect(new MemoryExperimentSettings(directory).enabled(owner)).toBe(false)
+ expect(await ask({ action: 'configure_experiment', enabled: true, expected: 2, token: 'agent' }))
+ .toMatchObject({ error: 'PERSON_ONLY' })
+ person = false
+ expect(await ask({ action: 'configure_experiment', enabled: true, expected: 2 }))
+ .toMatchObject({ error: 'INSIDE_HARNESS' })
+ person = true
+ expect(await ask({ action: 'experiment', owner: 'b'.repeat(64) })).toMatchObject({ error: 'INVALID_INPUT' })
+ verify.mockClear()
+ for (const action of ['status', 'list', 'show', 'preview', 'apply']) {
+ expect(await ask({ action })).toMatchObject({ error: 'DAEMONS_OFF' })
+ }
+ expect(await ask({ verb: 'recall_memory', query: 'test' })).toMatchObject({ error: 'DAEMONS_OFF' })
+ expect(verify).not.toHaveBeenCalled()
+ expect(runtime).not.toHaveBeenCalled()
+ expect(settings.enabled(owner)).toBe(false)
+ socket.pairControl = null
+ expect(await ask({ action: 'experiment' })).toMatchObject({ error: 'DAEMONS_OFF' })
+ } finally {
+ await socket.unregisterLocalClient('local:settings')
+ await socket.stop()
+ rmSync(directory, { recursive: true, force: true })
+ }
+})
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 9c9fe7698..51772606e 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -790,7 +790,8 @@ export class BackendSocket {
private readonly devlogAppends = new Map<string, (payload: Record<string, unknown> | null) => void>()
/**
* Whether daemons run at all (lib/daemonsSwitch.ts). Off, the loopback `pair` request (`harness pair`, the
- * MCP server) is answered DAEMONS_OFF before any verb runs. Null: always on, as before the switch.
+ * MCP server) is answered DAEMONS_OFF before any verb runs, except the verified owner's local coding
+ * memory opt-in setting. That setting does not read memory or start a companion. Null: always on.
*/
daemonsOn: (() => boolean) | null = null
/**
@@ -1690,9 +1691,14 @@ export class BackendSocket {
}
if (type === 'pair') {
if (!local) { reply(type, requestId, { error: 'LOCAL_ONLY', detail: 'Ask the pair brain on this computer.' }); return }
- if (this.daemonsOn && !this.daemonsOn()) { reply(type, requestId, { error: 'DAEMONS_OFF', detail: 'Daemons are off for this account or on this computer.' }); return }
const verb = typeof payload.verb === 'string' ? payload.verb : ''
const control = this.pairControl
+ // The owner must be able to clear the saved opt-in without turning companions on. Only these
+ // two settings actions reach MemoryControl, which checks their full schema and verifies the OS
+ // caller. Ordinary library, recall and agent tools remain inert while the master switch is off.
+ const memorySetting = control?.verbs.has('memory') && verb === 'memory' &&
+ (payload.action === 'experiment' || payload.action === 'configure_experiment')
+ if (this.daemonsOn && !this.daemonsOn() && !memorySetting) { reply(type, requestId, { error: 'DAEMONS_OFF', detail: 'Daemons are off for this account or on this computer.' }); return }
if (control && control.verbs.has(verb)) { detached(control.local(payload, connId)); return }
if (!service) { reply(type, requestId, { error: 'UNSUPPORTED' }); return }
detached(service.local(payload))
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 8267ed584..b462133fa 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 { MemoryExperimentSettings } from './memory/experiment.js'
import { MemoryControl } from './memory/control.js'
import { isOwnerProcess } from './memory/ownerProcess.js'
import { hasMemoryForegroundActivity, MemorySessionRoster } from './memory/hostSessions.js'
@@ -1942,8 +1943,15 @@ async function runForeground(session: AuthSession | null): Promise<void> {
let pairHarnessActivity: (agentId: string) => void = () => {}
let companionPromptContext: (agentId: string) => string | null = () => null
let companionProfileChanged: () => void = () => {}
- // Development rollout only until the memory viewer, delivery receipts and migration are reviewed.
- const codingMemoryPreview = process.env.HARNESS_CODING_MEMORY === '1'
+ // 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')
+ const memoryProfile = (): string | null => {
+ const current = readAuthSession()
+ return current ? current.memoryOwner?.key ?? null : guestMemoryProfile
+ }
+ const codingMemoryPreview = () => memoryExperiment.enabled(memoryProfile())
+ let applyCodingMemorySetting: () => Promise<void> = async () => {}
let codingMemory: CodingMemoryRuntime | null = null
let memoryPause = Promise.resolve()
let refreshMemoryIdentity: () => Promise<void> = async () => {}
@@ -3334,7 +3342,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// pair chats, sub-agents and replay stay excluded. Tool-free background reviews
// never register as agents, so they cannot feed their own results back in here.
const learnFrom = registry.bySession(sessionId)
- if (!codingMemoryPreview && learnFrom && pairSensor.enabled() && !isTerminalEngine(learnFrom.engine) && !isSubagentSession(sessionId) &&
+ if (!codingMemoryPreview() && learnFrom && pairSensor.enabled() && !isTerminalEngine(learnFrom.engine) && !isSubagentSession(sessionId) &&
(!isPairHarnessSession(sessionId) || isCollectionAgent(learnFrom.agentId))) {
lessonSignals.ingest({ agentId: learnFrom.agentId, sessionId, engine: learnFrom.engine, cwd: learnFrom.cwd ?? null }, events,
{ replay: !!(opts?.resumed || opts?.replay) })
@@ -3345,7 +3353,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
lessonUsage.ingest({ cwd: learnFrom.cwd ?? null }, events, { replay: !!(opts?.resumed || opts?.replay) })
}
mirror.ingest(events, sessionId, { replay: !!(opts?.resumed || opts?.replay) })
- if (codingMemoryPreview && daemons.on() && !opts?.resumed && !opts?.replay) void codingMemory?.tick()
+ if (codingMemoryPreview() && daemons.on() && !opts?.resumed && !opts?.replay) void codingMemory?.tick()
// Subscribed devices only (lib/autonomous-device/stream.ts). A transcript re-read is history, not live.
if (!opts?.replay) autonomousDeviceService?.stream(agentIdFor(sessionId), events)
}
@@ -3944,7 +3952,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
const json = await res.json().catch(() => ({})) as Record<string, unknown>
const result = { status: res.status, body: json }
if (latest?.accessToken === accessToken && latest.memoryOwner) memoryZooOwners.set(result, latest.memoryOwner.key)
- if (codingMemoryPreview && daemons.on() && method === 'GET' && path === '/api/auth/me' && res.status === 200 && json?.success === true) {
+ if (method === 'GET' && path === '/api/auth/me' && res.status === 200 && json?.success === true) {
const userId = (json.data as { user?: { id?: unknown } } | undefined)?.user?.id
if (typeof userId === 'string') {
const binding = auth.bindMemoryOwner(userId, accessToken, latest?.autonomousEnv ?? env.AUTONOMOUS_ENV).catch(() => null)
@@ -4514,7 +4522,7 @@ async function runForeground(session: AuthSession | null): Promise<void> {
...(tmuxBackend ? [{ backend: 'tmux', instance: 'default', state: 'configured' }] : []),
],
dormantAgents: registry.list().filter((session) => !session.active).length,
- ...(codingMemoryPreview ? { codingMemory: codingMemory?.status() ?? { state: 'off' } } : {}),
+ ...(codingMemoryPreview() ? { codingMemory: codingMemory?.status() ?? { state: 'off' } } : {}),
dataDir: tildify(env.ADAPTER_DATA_DIR),
port: daemonPort(),
},
@@ -4803,7 +4811,12 @@ async function runForeground(session: AuthSession | null): Promise<void> {
processes: () => processRows(),
harnessPanePids: async () => { const inventory = await listTmuxPanes(); return inventory.ok ? inventory.panes.map((pane) => pane.rootPid) : null },
})
- const memoryControl = new MemoryControl({ runtime: () => codingMemory, verify: async connId => {
+ const memoryControl = new MemoryControl({ runtime: () => codingMemoryPreview() ? codingMemory : null,
+ experiment: { owner: memoryProfile, read: owner => memoryExperiment.read(owner), write: async (owner, enabled, expected) => {
+ const choice = memoryExperiment.write(owner, enabled, expected)
+ await applyCodingMemorySetting()
+ return choice
+ } }, verify: async connId => {
const verdict = await verifyLessonCaller(connId)
if (!verdict.ok) return verdict
if (!await isOwnerProcess(verdict.pid)) return { ok: false, error: 'UNVERIFIED', detail: 'The memory library requires a verified process belonging to this computer’s owner.' }
@@ -4918,15 +4931,14 @@ async function runForeground(session: AuthSession | null): Promise<void> {
stateFile: join(env.ADAPTER_DATA_DIR, 'pair', 'intelligence.json'),
})
companionProfileChanged = () => { companionIntelligence.status(); pairBrain?.stateChanged() }
- if (codingMemoryPreview) {
+ {
const roster = new MemorySessionRoster(homedir())
- const guestProfile = createHash('sha256').update(JSON.stringify(['harness-memory-guest-v1', computerId()])).digest('hex')
codingMemory = new CodingMemoryRuntime({
directory: join(env.ADAPTER_DATA_DIR, 'coding-memory'),
context: () => {
const current = readAuthSession()
- const profileId = current ? current.memoryOwner?.key ?? null : guestProfile
- return { experimental: daemons.on(), profileId,
+ const profileId = current ? current.memoryOwner?.key ?? null : guestMemoryProfile
+ return { experimental: daemons.on() && codingMemoryPreview(), profileId,
watching: !!pairSensor.pairedDaemon() && (current
? !!profileId && zooMemoryOwner === profileId && zooPair.consent : guestConsent) }
},
@@ -5077,6 +5089,16 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// paused if it was live (its conversation kept).
let learnTick: ReturnType<typeof setInterval> | null = null
let pairConfigTick: ReturnType<typeof setInterval> | null = null
+ applyCodingMemorySetting = async () => {
+ pairLearner?.cancelReviews()
+ conversationReview.stop()
+ memoryPause = memoryPause.then(() => codingMemory?.pause()).catch(() => {})
+ await memoryPause
+ if (daemons.on() && codingMemoryPreview()) {
+ codingMemory?.start()
+ await refreshMemoryIdentity()
+ }
+ }
onDaemonsChanged = (on) => {
plates.setOn(on)
if (on) {
@@ -5084,11 +5106,11 @@ async function runForeground(session: AuthSession | null): Promise<void> {
// everything off within the tick (before the rest of the file is read), and any other change asks for
// the person's yes soon.
pairRulesConfig()
- if (!codingMemoryPreview) {
- learnTick ??= setInterval(() => { void pairLearner?.tick().catch((err) => console.warn(`[learn] tick failed: ${err instanceof Error ? err.message : err}`)) }, 60_000)
+ {
+ learnTick ??= setInterval(() => { if (!codingMemoryPreview()) void pairLearner?.tick().catch((err) => console.warn(`[learn] tick failed: ${err instanceof Error ? err.message : err}`)) }, 60_000)
learnTick.unref?.()
}
- void memoryPause.then(() => { if (daemons.on()) codingMemory?.start() })
+ void memoryPause.then(() => { if (daemons.on() && codingMemoryPreview()) codingMemory?.start() })
void refreshMemoryIdentity()
pairConfigTick ??= setInterval(() => { daemons.recheck(); if (daemons.on()) { pairRulesConfig(); void refreshMemoryIdentity() } }, 30_000)
pairConfigTick.unref?.()
diff --git a/cli/src/lib/daemonsSwitch.spec.ts b/cli/src/lib/daemonsSwitch.spec.ts
index 31ed15257..e5f76a821 100644
--- a/cli/src/lib/daemonsSwitch.spec.ts
+++ b/cli/src/lib/daemonsSwitch.spec.ts
@@ -440,14 +440,16 @@ describe('cli.ts routes everything daemon-related through the switch', () => {
})
it('arms the pair\'s timers only inside onDaemonsChanged, and starts the switch once all of it is wired', () => {
- const timers = [...source.matchAll(/setInterval\(\(\) => \{ (void pairLearner|daemons\.recheck\(\))/g)]
+ // Track the owned registrations, independent of the optional feature guards in their callbacks.
+ const timers = [...source.matchAll(/(?:learnTick|pairConfigTick)\s*\?\?=\s*setInterval\([^\n]+/g)]
expect(timers).toHaveLength(2)
for (const timer of timers) expect(onChanged).toContain(timer[0])
expect(onChanged).toContain('clearInterval(learnTick)')
expect(onChanged).toContain('clearInterval(pairConfigTick)')
expect(onChanged).toContain('zooTurnReporter.clear()')
expect(onChanged).toContain('pairHarness.off()')
- expect(onChanged).toContain('if (daemons.on()) codingMemory?.start()')
+ expect(onChanged).toContain('if (daemons.on() && codingMemoryPreview()) codingMemory?.start()')
+ expect(onChanged).toContain('if (!codingMemoryPreview()) void pairLearner?.tick()')
expect(onChanged).toContain('codingMemory?.pause()')
expect(at('daemons.start()')).toBeGreaterThan(at('pairBrain = new PairBrain({'))
expect(at('daemons.start()')).toBeGreaterThan(at('onDaemonsChanged = (on) => {'))
diff --git a/cli/src/memory/control.ts b/cli/src/memory/control.ts
index 8fe21ea2d..19c95c426 100644
--- a/cli/src/memory/control.ts
+++ b/cli/src/memory/control.ts
@@ -5,9 +5,12 @@ import { libraryCommandSchema, libraryQuerySchema, libraryProjectQuerySchema, ty
import { MemoryError, parse } from './types.js'
import type { CodingMemoryRuntime } from './runtime.js'
import type { CallerVerdict } from '../pair/learn/approval.js'
+import type { MemoryExperimentChoice } from './experiment.js'
const requestSchema = z.discriminatedUnion('action', [
z.object({ action: z.literal('status') }).strict(),
+ z.object({ action: z.literal('experiment') }).strict(),
+ z.object({ action: z.literal('configure_experiment'), enabled: z.boolean(), expected: z.number().int().nonnegative().safe() }).strict(),
z.object({ action: z.literal('list'), query: libraryQuerySchema.optional() }).strict(),
z.object({ action: z.literal('projects'), query: libraryProjectQuerySchema.optional() }).strict(),
z.object({ action: z.literal('show'), id: z.string().min(1).max(200) }).strict(),
@@ -20,6 +23,11 @@ interface Deps {
/** Must verify the OS owner as well as rejecting a process inside an agent's harness. */
verify(connId: string): Promise<CallerVerdict>
now?: () => number
+ experiment?: {
+ owner(): string | null
+ read(owner: string): MemoryExperimentChoice
+ write(owner: string, enabled: boolean, expected: number): Promise<MemoryExperimentChoice>
+ }
}
interface Capability { owner: string; connId: string; pid: number; expires: number; preview: LibraryPreview }
const TTL_MS = 2 * 60_000
@@ -33,13 +41,26 @@ export class MemoryControl {
// A token-bearing agent cannot turn itself into the person with `confirmed`, a claimed owner,
// another agentId, or an independently supplied command at apply time.
if (payload.token) return { ok: false, error: 'PERSON_ONLY' }
- const runtime = this.deps.runtime()
- if (!runtime) return { ok: false, error: 'UNSUPPORTED' }
- const owner = runtime.ownerKey()
- if (!owner) return { ok: false, error: 'MEMORY_UNAVAILABLE' }
try {
const { verb: _verb, requestId: _requestId, token: _token, ...input } = payload
const request = parse(requestSchema, input)
+ if (request.action === 'experiment' || request.action === 'configure_experiment') {
+ const experiment = this.deps.experiment
+ if (!experiment) return { ok: false, error: 'UNSUPPORTED' }
+ const owner = experiment.owner()
+ if (!owner) return { ok: false, error: 'MEMORY_UNAVAILABLE' }
+ const verdict = await this.deps.verify(connId)
+ if (!verdict.ok) return { ok: false, error: verdict.error }
+ if (owner !== experiment.owner()) throw new MemoryError('owner_changed')
+ const choice = request.action === 'experiment' ? experiment.read(owner)
+ : await experiment.write(owner, request.enabled, request.expected)
+ if (owner !== experiment.owner()) throw new MemoryError('owner_changed')
+ return { ok: true, ...choice }
+ }
+ const runtime = this.deps.runtime()
+ if (!runtime) return { ok: false, error: 'UNSUPPORTED' }
+ const owner = runtime.ownerKey()
+ if (!owner) return { ok: false, error: 'MEMORY_UNAVAILABLE' }
const verdict = await this.deps.verify(connId)
if (!verdict.ok) return { ok: false, error: verdict.error, detail: verdict.detail }
if (runtime !== this.deps.runtime() || owner !== runtime.ownerKey()) throw new MemoryError('owner_changed')
diff --git a/cli/src/memory/experiment.spec.ts b/cli/src/memory/experiment.spec.ts
new file mode 100644
index 000000000..957ef4888
--- /dev/null
+++ b/cli/src/memory/experiment.spec.ts
@@ -0,0 +1,73 @@
+import { existsSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { MemoryExperimentSettings } from './experiment.js'
+import { MemoryControl } from './control.js'
+
+let directory: string, settings: MemoryExperimentSettings
+const owner = 'a'.repeat(64), other = 'b'.repeat(64)
+beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'memory-experiment-'))
+ settings = new MemoryExperimentSettings(directory)
+})
+afterEach(() => rmSync(directory, { recursive: true, force: true }))
+
+it('defaults off without writing and persists each account independently across restart', () => {
+ expect(settings.read(owner)).toEqual({ enabled: false, revision: 0 })
+ expect(existsSync(join(directory, `${owner}.json`))).toBe(false)
+ expect(settings.write(owner, true, 0)).toEqual({ enabled: true, revision: 1 })
+ expect(settings.enabled(other)).toBe(false)
+ expect(settings.enabled(null)).toBe(false)
+ settings = new MemoryExperimentSettings(directory)
+ expect(settings.read(owner)).toEqual({ enabled: true, revision: 1 })
+ expect(statSync(join(directory, `${owner}.json`)).mode & 0o777).toBe(0o600)
+ expect(() => settings.write(owner, false, 0)).toThrow('settings_changed')
+ expect(settings.write(owner, false, 1)).toEqual({ enabled: false, revision: 2 })
+})
+
+it('lets an explicit off override the legacy environment default and fails closed on unreadable settings', () => {
+ settings = new MemoryExperimentSettings(directory, true)
+ expect(settings.enabled(owner)).toBe(true)
+ settings.write(owner, false, 0)
+ expect(new MemoryExperimentSettings(directory, true).enabled(owner)).toBe(false)
+ writeFileSync(join(directory, `${other}.json`), '{broken')
+ expect(settings.enabled(other)).toBe(false)
+ expect(() => settings.read(other)).toThrow('settings_unavailable')
+ expect(() => settings.read('../escape')).toThrow('owner_changed')
+})
+
+it('exposes the choice to the verified owner even while the preview runtime is off', async () => {
+ let current = owner, changes = 0, person = true
+ const control = new MemoryControl({ runtime: () => null,
+ verify: async () => person ? { ok: true, pid: 123 } : { ok: false, error: 'INSIDE_HARNESS', detail: 'agent' },
+ experiment: { owner: () => current, read: id => settings.read(id), write: async (id, on, expected) => {
+ const choice = settings.write(id, on, expected); changes++; return choice
+ } } })
+ const request = (payload: Record<string, unknown>) => control.local({ verb: 'memory', ...payload }, 'socket')
+ expect(await request({ action: 'experiment' })).toEqual({ ok: true, enabled: false, revision: 0 })
+ expect(changes).toBe(0)
+ const command = { action: 'configure_experiment', enabled: true, expected: 0 }
+ expect(await request({ ...command, token: 'agent' })).toMatchObject({ error: 'PERSON_ONLY' })
+ person = false
+ expect(await request(command)).toMatchObject({ error: 'INSIDE_HARNESS' })
+ person = true
+ expect(await request({ ...command, owner: other })).toMatchObject({ error: 'INVALID_INPUT' })
+ expect(await request(command)).toEqual({ ok: true, enabled: true, revision: 1 })
+ expect(changes).toBe(1)
+ expect(await request(command)).toMatchObject({ error: 'SETTINGS_CHANGED' })
+ current = other
+ expect(await request({ action: 'experiment' })).toEqual({ ok: true, enabled: false, revision: 0 })
+ expect(readFileSync(join(directory, `${owner}.json`), 'utf8')).toContain('"enabled":true')
+})
+
+it('rejects an account change during process verification before writing a choice', async () => {
+ let current = owner
+ const control = new MemoryControl({ runtime: () => null,
+ verify: async () => { current = other; return { ok: true, pid: 123 } },
+ experiment: { owner: () => current, read: id => settings.read(id), write: async (id, on, expected) => settings.write(id, on, expected) } })
+ expect(await control.local({ action: 'configure_experiment', enabled: true, expected: 0 }, 'socket'))
+ .toMatchObject({ error: 'OWNER_CHANGED' })
+ expect(settings.enabled(owner)).toBe(false)
+ expect(settings.enabled(other)).toBe(false)
+})
diff --git a/cli/src/memory/experiment.ts b/cli/src/memory/experiment.ts
new file mode 100644
index 000000000..994dc5a8f
--- /dev/null
+++ b/cli/src/memory/experiment.ts
@@ -0,0 +1,51 @@
+/** Local, account-scoped opt-in. Reading a choice never creates a store or starts learning. */
+import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'
+import { join } from 'node:path'
+import { randomUUID } from 'node:crypto'
+import { MemoryError } from './types.js'
+
+export interface MemoryExperimentChoice { enabled: boolean; revision: number }
+export class MemoryExperimentSettings {
+ private readonly choices = new Map<string, MemoryExperimentChoice>()
+ constructor(private readonly directory: string, private readonly legacyDefault = false) {}
+
+ read(owner: string): MemoryExperimentChoice {
+ const file = this.file(owner)
+ const cached = this.choices.get(owner)
+ if (cached) return { ...cached }
+ if (!existsSync(file)) return { enabled: this.legacyDefault, revision: 0 }
+ if (!lstatSync(file).isFile() || lstatSync(file).isSymbolicLink()) throw new MemoryError('settings_unavailable')
+ try {
+ const data = JSON.parse(readFileSync(file, 'utf8'))
+ if (data.version !== 1 || typeof data.enabled !== 'boolean' || !Number.isSafeInteger(data.revision) || data.revision < 1) throw Error()
+ const choice = { enabled: data.enabled, revision: data.revision }
+ this.choices.set(owner, choice)
+ return { ...choice }
+ } catch { throw new MemoryError('settings_unavailable') }
+ }
+
+ enabled(owner: string | null): boolean {
+ if (!owner) return false
+ try { return this.read(owner).enabled } catch { return false }
+ }
+
+ write(owner: string, enabled: boolean, expected: number): MemoryExperimentChoice {
+ const previous = this.read(owner)
+ if (previous.revision !== expected) throw new MemoryError('settings_changed')
+ if (previous.enabled === enabled && previous.revision > 0) return previous
+ const choice = { enabled, revision: previous.revision + 1 }
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 })
+ const file = this.file(owner), temp = `${file}.${randomUUID()}.tmp`
+ try {
+ writeFileSync(temp, JSON.stringify({ version: 1, ...choice }), { mode: 0o600, flag: 'wx' })
+ renameSync(temp, file)
+ } finally { rmSync(temp, { force: true }) }
+ this.choices.set(owner, choice)
+ return { ...choice }
+ }
+
+ private file(owner: string): string {
+ if (!/^[a-f0-9]{64}$/.test(owner)) throw new MemoryError('owner_changed')
+ return join(this.directory, `${owner}.json`)
+ }
+}
diff --git a/daemons/BRAIN.md b/daemons/BRAIN.md
index 468e85be5..8759a3c31 100644
--- a/daemons/BRAIN.md
+++ b/daemons/BRAIN.md
@@ -56,8 +56,10 @@ One implementation, `pair/control.ts`, behind a local-only `pair` request. Expos
Every write, local or remote, runs through the owning machine's `PairOwner` (`pair/owner.ts`), so the
floor and the journal live where the harness does.
-The unshipped coding-memory service requires `HARNESS_CODING_MEMORY=1` in addition to the existing
-experimental and watching controls. `recall_memory { query, conditions? }` is an agent read, bound by
+The experimental coding-memory service is enabled in **Settings → Experimental → Coding memory**,
+in addition to the companion and watching controls. The choice is local to this computer and account,
+defaults off, and takes effect without restarting. `HARNESS_CODING_MEMORY=1` remains a migration default
+only until the owner saves a choice; an explicit off wins. `recall_memory { query, conditions? }` is an agent read, bound by
the host to the current collection, with a byte-bounded historical-context packet and an unverified
delivery receipt. Its token is required even at `watch`; it cannot select an owner, project, session,
or avatar. It cannot inspect the owner's whole library, correct records, change privacy, or forget.
@@ -69,8 +71,11 @@ person. `harness pair memory list|status|show <id> --json` exposes the initial r
The internal owner API also supplies paginated listing, retained evidence, and correction/forget/
Learn/Recall previews. Applying a change needs a two-minute, one-use capability bound to owner,
process, connection, exact command, and the unchanged library snapshot. `confirmed: true` never
-counts. The desktop viewer and its verified transport are still pending; do not enable this prototype
-as the production memory path. Like existing lesson approval, process checks do not defend against
+counts. The desktop viewer uses this transport in **Companions → Memories**. Two preference actions,
+`experiment` and `configure_experiment { enabled, expected }`, remain available while companions are off;
+the latter checks the saved revision. Neither can access memories or start learning with companions off.
+Turning Coding memory off cancels its background work and keeps saved records. Real-model quality and
+the rollout gates remain unverified. Like existing lesson approval, process checks do not defend against
arbitrary malware running as the same OS user with access to the memory files.
**Autonomy dial** (zoo op `zoo.autonomy`, default `watch`): `watch` (read tools only, facts; lines
diff --git a/daemons/README.md b/daemons/README.md
index fbe6f8330..d0f95bf28 100644
--- a/daemons/README.md
+++ b/daemons/README.md
@@ -217,7 +217,10 @@ Deploy the backend settings routes and CLI proxy before the desktop update that
- **What harnessd answers while off.** A window's `/api/zoo` and `/api/zoo/ops`: the server's 404, or —
killed locally — `404 { error: { code: 'DAEMONS_OFF' } }` without asking. `daemon_act`, `daemon_confirm`,
`daemon_talk`: `{ ok: false, error: 'DAEMONS_OFF' }`. The `pair` request (`harness pair`, the MCP server):
- `{ error: 'DAEMONS_OFF' }`. `daemon_shown` and `daemon_presence` are dropped (but a guest's consent), and
+ `{ error: 'DAEMONS_OFF' }`, except `memory { action: experiment | configure_experiment }`: the
+ verified local owner can read or clear the Coding memory opt-in without turning companions on.
+ This only changes a local account setting; memory access, capture, learning and recall remain off.
+ `daemon_shown` and `daemon_presence` are dropped (but a guest's consent), and
no `daemon_*` frame is sent. Another machine's `pair_*`: `PAIR_OFF`. `GET /api/status` says
`daemons: { on, server, killed }`.
- **What every client does** (desktop, phone, `hn`, web). A 404 from `GET /api/zoo`, or a `DAEMONS_OFF`
diff --git a/desktop/lib/companions/coding_memory_settings.dart b/desktop/lib/companions/coding_memory_settings.dart
new file mode 100644
index 000000000..d7e84da8a
--- /dev/null
+++ b/desktop/lib/companions/coding_memory_settings.dart
@@ -0,0 +1,127 @@
+import 'package:flutter/foundation.dart';
+
+import 'coding_memory_connection.dart';
+
+/// Owns an explicit local opt-in, using the same owner-verified transport as the library.
+class CodingMemorySettings extends ChangeNotifier {
+ CodingMemorySettings(this.openConnection);
+ final CodingMemoryConnection? Function() openConnection;
+ CodingMemoryConnection? _connection;
+ bool enabled = false, loaded = false, saving = false, _disposed = false;
+ int _revision = 0, _generation = 0;
+ String? error;
+ Future<void>? _reading;
+
+ void _notify() {
+ if (!_disposed) notifyListeners();
+ }
+
+ void _ownerChanged() {
+ if (_connection?.valid != false) return;
+ ++_generation;
+ enabled = loaded = saving = false;
+ error = 'Your account or local connection changed. Refresh this setting.';
+ _notify();
+ }
+
+ Future<Map<String, dynamic>> _request(Map<String, dynamic> payload) async {
+ final connection = _connection;
+ if (connection == null || !connection.valid) {
+ throw const CodingMemoryFailure('OWNER_CHANGED');
+ }
+ final response = await connection.request(payload);
+ if (!connection.valid) throw const CodingMemoryFailure('OWNER_CHANGED');
+ if (response['ok'] != true) {
+ throw CodingMemoryFailure(
+ response['error'] as String? ?? 'MEMORY_UNAVAILABLE',
+ );
+ }
+ if (response['enabled'] is! bool || response['revision'] is! int) {
+ throw const CodingMemoryFailure('UNSUPPORTED');
+ }
+ return response;
+ }
+
+ void _apply(Map<String, dynamic> response) {
+ final revision = response['revision'] as int;
+ if (revision < _revision) return;
+ enabled = response['enabled'] as bool;
+ _revision = revision;
+ loaded = true;
+ error = null;
+ }
+
+ Future<void> refresh() {
+ if (_disposed || saving) return Future.value();
+ return _reading ??= _read().whenComplete(() => _reading = null);
+ }
+
+ Future<void> _read() async {
+ if (_connection?.valid != true) {
+ _connection?.removeListener(_ownerChanged);
+ _connection?.dispose();
+ _connection = openConnection()?..addListener(_ownerChanged);
+ _revision = 0;
+ loaded = enabled = false;
+ }
+ final generation = _generation;
+ try {
+ if (_connection == null) {
+ throw const CodingMemoryFailure('LOCAL_UNAVAILABLE');
+ }
+ final response = await _request({'action': 'experiment'});
+ if (!_disposed && generation == _generation) _apply(response);
+ } catch (failure) {
+ if (!_disposed && generation == _generation) {
+ loaded = false;
+ error = _message(failure);
+ }
+ }
+ _notify();
+ }
+
+ Future<void> setEnabled(bool value) async {
+ if (_disposed || saving || !loaded || _connection?.valid != true) return;
+ final generation = ++_generation;
+ saving = true;
+ error = null;
+ _notify();
+ try {
+ final response = await _request({
+ 'action': 'configure_experiment',
+ 'enabled': value,
+ 'expected': _revision,
+ });
+ if (!_disposed && generation == _generation) _apply(response);
+ } catch (failure) {
+ if (!_disposed && generation == _generation) {
+ loaded = false;
+ error = '${_message(failure)} Refresh to check the saved choice.';
+ }
+ } finally {
+ if (!_disposed && generation == _generation) saving = false;
+ _notify();
+ }
+ }
+
+ static String _message(Object failure) => switch (failure) {
+ CodingMemoryFailure(code: 'DAEMONS_OFF') =>
+ 'Turn on Focus-bar creature above to use coding memory.',
+ CodingMemoryFailure(code: 'UNSUPPORTED') =>
+ 'Update the local Harness service to use this setting.',
+ CodingMemoryFailure(code: 'LOCAL_UNAVAILABLE') =>
+ 'Connect this computer to Harness to choose this setting.',
+ CodingMemoryFailure(code: 'SETTINGS_CHANGED') =>
+ 'This setting changed in another window.',
+ _ => codingMemoryError(failure),
+ };
+
+ @override
+ void dispose() {
+ _disposed = true;
+ ++_generation;
+ _connection?.removeListener(_ownerChanged);
+ _connection?.dispose();
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/companions/companion_home.dart b/desktop/lib/companions/companion_home.dart
index 214797368..1d756f8c7 100644
--- a/desktop/lib/companions/companion_home.dart
+++ b/desktop/lib/companions/companion_home.dart
@@ -125,8 +125,7 @@ class _CompanionHomeState extends State<CompanionHome> {
_memoryRefresh?.cancel();
_memoryRefresh = value == 'Memories'
? Timer.periodic(const Duration(seconds: 30), (_) {
- if (_codingMemory?.valid == true &&
- _codingMemory?.available != false) {
+ if (_codingMemory?.valid == true) {
unawaited(_codingMemory!.refresh());
}
if (widget.brain.active && !_lessons.busy) {
diff --git a/desktop/lib/settings/sections/experimental_section.dart b/desktop/lib/settings/sections/experimental_section.dart
index 9aecdb0c8..3d2115fea 100644
--- a/desktop/lib/settings/sections/experimental_section.dart
+++ b/desktop/lib/settings/sections/experimental_section.dart
@@ -6,12 +6,20 @@ import '../../shared/widgets/section_scaffold.dart';
import '../../shared/widgets/setting_row.dart';
import '../experimental_features.dart';
import '../../teams/swarm_settings_controller.dart';
+import '../../companions/coding_memory_connection.dart';
+import '../../companions/coding_memory_settings.dart';
class ExperimentalSection extends StatefulWidget {
- const ExperimentalSection({super.key, this.store, this.controller});
+ const ExperimentalSection({
+ super.key,
+ this.store,
+ this.controller,
+ this.openCodingMemory,
+ });
final ExperimentalFeaturesStore? store;
final SwarmSettingsController? controller;
+ final CodingMemoryConnection? Function()? openCodingMemory;
@override
State<ExperimentalSection> createState() => _ExperimentalSectionState();
@@ -40,7 +48,7 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
final features = ExperimentalFeature.values.where((f) => f.available);
return SectionScaffold(
title: 'Experimental',
- subtitle: 'Try features that are still taking shape. These settings sync across your account.',
+ subtitle: 'Try features that are still taking shape. Account experiments sync across your devices; coding memory is local to this computer.',
child: SingleChildScrollView(
child: ListenableBuilder(
listenable: Listenable.merge([preferences, widget.controller]),
@@ -112,6 +120,13 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
),
if (widget.controller case final controller?)
_SwarmCollaborationSetting(controller: controller),
+ if (widget.openCodingMemory case final open?)
+ _CodingMemorySetting(
+ open: open,
+ companionEnabled: preferences.enabled(
+ ExperimentalFeature.focusBarCreature,
+ ),
+ ),
],
),
),
@@ -120,6 +135,86 @@ class _ExperimentalSectionState extends State<ExperimentalSection> {
}
}
+class _CodingMemorySetting extends StatefulWidget {
+ const _CodingMemorySetting({
+ required this.open,
+ required this.companionEnabled,
+ });
+ final CodingMemoryConnection? Function() open;
+ final bool companionEnabled;
+ @override
+ State<_CodingMemorySetting> createState() => _CodingMemorySettingState();
+}
+
+class _CodingMemorySettingState extends State<_CodingMemorySetting> {
+ late final settings = CodingMemorySettings(() => widget.open());
+ @override
+ void initState() {
+ super.initState();
+ unawaited(settings.refresh());
+ }
+
+ @override
+ void didUpdateWidget(_CodingMemorySetting oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ if (oldWidget.companionEnabled != widget.companionEnabled) {
+ unawaited(settings.refresh());
+ }
+ }
+
+ @override
+ void dispose() {
+ settings.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => ListenableBuilder(
+ listenable: settings,
+ builder: (context, _) => SettingRow(
+ title: 'Coding memory',
+ detail: 'Let your companion learn coding preferences and project knowledge across supported agents on this computer. Uses the model selected in Companions.',
+ control: Semantics(
+ label: 'Coding memory',
+ child: Align(
+ alignment: Alignment.centerLeft,
+ child: Switch(
+ key: const Key('experimental-coding-memory'),
+ value: settings.enabled,
+ onChanged: settings.loaded && !settings.saving
+ ? (value) => unawaited(settings.setEnabled(value))
+ : null,
+ ),
+ ),
+ ),
+ footer: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ const Text(
+ 'For your account on this computer. Review memories and control learning and recall in Companions → Memories. Turning this off keeps saved memories.',
+ ),
+ if (!widget.companionEnabled)
+ const Text(
+ 'Learning and recall are paused while Focus-bar creature is off.',
+ ),
+ if (settings.saving)
+ const Text('Saving…')
+ else if (!settings.loaded && settings.error == null)
+ const Text('Loading…'),
+ if (settings.error case final error?) ...[
+ const SizedBox(height: 8),
+ Semantics(liveRegion: true, child: Text(error)),
+ TextButton(
+ onPressed: settings.saving ? null : settings.refresh,
+ child: const Text('Refresh setting'),
+ ),
+ ],
+ ],
+ ),
+ ),
+ );
+}
+
class _SwarmCollaborationSetting extends StatelessWidget {
const _SwarmCollaborationSetting({required this.controller});
final SwarmSettingsController controller;
diff --git a/desktop/lib/settings/settings_body.dart b/desktop/lib/settings/settings_body.dart
index 4f1233cda..97a90376b 100644
--- a/desktop/lib/settings/settings_body.dart
+++ b/desktop/lib/settings/settings_body.dart
@@ -34,7 +34,9 @@ class SettingsBody extends StatelessWidget {
Widget build(BuildContext context) {
final screen = switch (section) {
SettingsSection.account => AccountSection(notifier: notifier),
- SettingsSection.accountDevices => AccountDevicesSection(notifier: notifier),
+ SettingsSection.accountDevices => AccountDevicesSection(
+ notifier: notifier,
+ ),
SettingsSection.profiles => ProfilesSection(notifier: notifier),
SettingsSection.usage => const UsageSection(),
SettingsSection.customize => throw StateError(
@@ -44,6 +46,7 @@ class SettingsBody extends StatelessWidget {
SettingsSection.experimental => ExperimentalSection(
store: experimentalFeatures ?? notifier.experimentalFeatures,
controller: notifier.swarmSettings,
+ openCodingMemory: notifier.openCodingMemoryConnection,
),
SettingsSection.devices => ListenableBuilder(
listenable: experimentalFeatures ?? notifier.experimentalFeatures,
diff --git a/desktop/test/coding_memory_settings_test.dart b/desktop/test/coding_memory_settings_test.dart
new file mode 100644
index 000000000..e54c7b6b4
--- /dev/null
+++ b/desktop/test/coding_memory_settings_test.dart
@@ -0,0 +1,232 @@
+import 'dart:async';
+import 'dart:io';
+import 'dart:ui' as ui;
+
+import 'package:flutter/material.dart';
+import 'package:flutter/rendering.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness/companions/coding_memory_connection.dart';
+import 'package:harness/companions/coding_memory_settings.dart';
+import 'package:harness/settings/experimental_features.dart';
+import 'package:harness/settings/sections/experimental_section.dart';
+import 'package:harness/shared/theme/app_theme.dart';
+import 'package:harness/shared/theme/color_palette.dart';
+
+import 'experimental_features_test.dart' show AccountSettings;
+import 'support/real_fonts.dart';
+
+class SettingsConnection extends CodingMemoryConnection {
+ @override
+ bool valid = true;
+ @override
+ int epoch = 1;
+ bool enabled = false;
+ int revision = 0;
+ String? failure;
+ Completer<void>? hold;
+ final calls = <Map<String, dynamic>>[];
+ @override
+ Future<Map<String, dynamic>> request(Map<String, dynamic> payload) async {
+ calls.add(payload);
+ await hold?.future;
+ if (failure != null) throw CodingMemoryFailure(failure!);
+ if (payload['action'] == 'configure_experiment') {
+ expect(payload['expected'], revision);
+ enabled = payload['enabled'] as bool;
+ revision++;
+ }
+ return {'ok': true, 'enabled': enabled, 'revision': revision};
+ }
+
+ @override
+ void invalidate() {
+ valid = false;
+ epoch++;
+ notifyListeners();
+ }
+}
+
+void main() {
+ TestWidgetsFlutterBinding.ensureInitialized();
+ setUpAll(loadRealFonts);
+ late SettingsConnection connection;
+ late CodingMemorySettings settings;
+ setUp(() {
+ connection = SettingsConnection();
+ settings = CodingMemorySettings(() => connection);
+ });
+ tearDown(() => settings.dispose());
+
+ test(
+ 'reads without writing, waits for acknowledgement, and can turn memory off',
+ () async {
+ await settings.refresh();
+ expect(settings.loaded, isTrue);
+ expect(settings.enabled, isFalse);
+ expect(connection.calls, [
+ {'action': 'experiment'},
+ ]);
+ connection.hold = Completer();
+ final saving = settings.setEnabled(true);
+ expect(settings.saving, isTrue);
+ expect(settings.enabled, isFalse);
+ connection.hold!.complete();
+ await saving;
+ expect(settings.enabled, isTrue);
+ expect(settings.saving, isFalse);
+ await settings.setEnabled(false);
+ expect(settings.enabled, isFalse);
+ expect(connection.revision, 2);
+ },
+ );
+
+ test(
+ 'clears the previous account and rejects a late setting reply',
+ () async {
+ await settings.refresh();
+ connection.hold = Completer();
+ final saving = settings.setEnabled(true);
+ connection.invalidate();
+ connection.hold!.complete();
+ await saving;
+ expect(settings.loaded, isFalse);
+ expect(settings.enabled, isFalse);
+ expect(settings.error, contains('account'));
+ },
+ );
+
+ test(
+ 'does not repeat an uncertain write and refreshes the actual saved value',
+ () async {
+ await settings.refresh();
+ connection.failure = 'TIMEOUT';
+ await settings.setEnabled(true);
+ expect(settings.loaded, isFalse);
+ expect(settings.enabled, isFalse);
+ await settings.setEnabled(true);
+ expect(connection.calls.length, 2);
+ connection.failure = null;
+ connection.enabled = true;
+ connection.revision = 1;
+ await settings.refresh();
+ expect(settings.enabled, isTrue);
+ },
+ );
+
+ test(
+ 'explains the companion prerequisite without enabling anything',
+ () async {
+ connection.failure = 'DAEMONS_OFF';
+ await settings.refresh();
+ expect(settings.loaded, isFalse);
+ expect(settings.error, contains('Focus-bar creature'));
+ expect(connection.calls, [
+ {'action': 'experiment'},
+ ]);
+ },
+ );
+
+ for (final brightness in [Brightness.light, Brightness.dark]) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'coding memory stays manageable with companions off, ${brightness.name} ${scale}x',
+ (tester) async {
+ tester.view.physicalSize = Size(scale == 1 ? 780 : 420, 1100);
+ tester.view.devicePixelRatio = 1;
+ addTearDown(tester.view.reset);
+ final oldPalette = AppTheme.palette.value;
+ final oldBrightness = AppTheme.brightness.value;
+ AppTheme.palette.value = brightness == Brightness.dark
+ ? HarnessPalette.graphite
+ : HarnessPalette.paper;
+ AppTheme.brightness.value = brightness;
+ addTearDown(() {
+ AppTheme.palette.value = oldPalette;
+ AppTheme.brightness.value = oldBrightness;
+ });
+ final account = AccountSettings('synthetic-owner');
+ final experiments = ExperimentalFeaturesStore(
+ pollInterval: Duration.zero,
+ )..bind(account.accountId, transport: account);
+ addTearDown(experiments.dispose);
+ connection.enabled = true;
+ connection.revision = 1;
+ final boundary = GlobalKey();
+ await tester.pumpWidget(
+ RepaintBoundary(
+ key: boundary,
+ child: MaterialApp(
+ debugShowCheckedModeBanner: false,
+ theme: buildAppTheme(brightness: brightness),
+ builder: (context, child) => MediaQuery(
+ data: MediaQuery.of(context)
+ .copyWith(textScaler: TextScaler.linear(scale)),
+ child: child!,
+ ),
+ home: Scaffold(
+ body: ExperimentalSection(
+ store: experiments,
+ openCodingMemory: () => connection,
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pumpAndSettle();
+ final toggle = find.byKey(const Key('experimental-coding-memory'));
+ await tester.ensureVisible(toggle);
+ await tester.pumpAndSettle();
+ expect(tester.widget<Switch>(toggle).value, isTrue);
+ expect(tester.widget<Switch>(toggle).onChanged, isNotNull);
+ expect(
+ find.text(
+ 'Learning and recall are paused while Focus-bar creature is off.',
+ ),
+ findsOneWidget,
+ );
+ expect(account.writes, isEmpty);
+ final output =
+ Platform.environment['HARNESS_MEMORY_SETTINGS_CAPTURE_DIR'];
+ if (output != null) {
+ await tester.runAsync(() async {
+ final image =
+ await (boundary.currentContext!.findRenderObject()
+ as RenderRepaintBoundary)
+ .toImage(pixelRatio: 1);
+ final bytes = await image.toByteData(
+ format: ui.ImageByteFormat.png,
+ );
+ await Directory(output).create(recursive: true);
+ await File('$output/setting-${brightness.name}-${scale}x.png')
+ .writeAsBytes(bytes!.buffer.asUint8List());
+ image.dispose();
+ });
+ }
+ connection.hold = Completer();
+ await tester.tap(toggle);
+ await tester.pump();
+ expect(tester.widget<Switch>(toggle).value, isTrue);
+ expect(tester.widget<Switch>(toggle).onChanged, isNull);
+ connection.hold!.complete();
+ await tester.pumpAndSettle();
+ expect(tester.widget<Switch>(toggle).value, isFalse);
+ expect(
+ connection.calls.where(
+ (call) => call['action'] == 'configure_experiment',
+ ),
+ [
+ {
+ 'action': 'configure_experiment',
+ 'enabled': false,
+ 'expected': 1,
+ },
+ ],
+ );
+ expect(account.writes, isEmpty);
+ expect(tester.takeException(), isNull);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+ }
+ }
+}
diff --git a/desktop/test/companion_home_test.dart b/desktop/test/companion_home_test.dart
index df0826955..88b147c41 100644
--- a/desktop/test/companion_home_test.dart
+++ b/desktop/test/companion_home_test.dart
@@ -388,6 +388,36 @@ void main() {
},
);
+ testWidgets(
+ 'an open Memories viewer discovers coding memory enabled in settings',
+ (tester) async {
+ final memory = MemoryFixture()
+ ..handle = (_) async => {'ok': false, 'error': 'UNSUPPORTED'};
+ await mount(tester, codingMemory: memory);
+ await tester.tap(find.byKey(const ValueKey('companion-nav-Memories')));
+ brain.receive('pair_result', {
+ 'requestId': sent.single.$2['requestId'],
+ 'ok': true,
+ 'lessons': [],
+ });
+ await tester.pump();
+ await tester.pump();
+ expect(find.text('For regression fixes, start with a small failing test.'), findsNothing);
+ memory.handle = null;
+ await tester.pump(const Duration(seconds: 30));
+ brain.receive('pair_result', {
+ 'requestId': sent.last.$2['requestId'],
+ 'ok': true,
+ 'lessons': [],
+ });
+ await tester.pump();
+ expect(find.text('For regression fixes, start with a small failing test.'), findsOneWidget);
+ expect(input, isEmpty);
+ expect(memory.calls.where((c) => ['apply', 'preview'].contains(c['action'])), isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ },
+ );
+
testWidgets(
'DSH keeps its viewer left and real agent terminal right, including setup',
(tester) async {
diff --git a/docs/plans/2026-09-30-coding-memory-product.md b/docs/plans/2026-09-30-coding-memory-product.md
index 9736f691d..cf1162d82 100644
--- a/docs/plans/2026-09-30-coding-memory-product.md
+++ b/docs/plans/2026-09-30-coding-memory-product.md
@@ -171,6 +171,15 @@ Add a maintained coding notebook to Project knowledge. It synthesizes supported
## Experience in the coding companion
+In the review build, enable **Settings → Experimental → Coding memory**, then open **Companions → Memories**.
+The setting is off by default, belongs to the current account on this computer, and needs no environment
+variable or restart. It uses the model selected in Companions and retains the existing watching consent.
+The viewer separates **How you work**, **Project knowledge**, and **Learning**. Turning the experiment
+off stops its background work and keeps saved memories; Learn and Recall have their own controls inside
+Memories. Companions must be enabled for learning or recall to run, but the local opt-in can still be
+cleared while companions are off. This is an opt-in preview, not evidence that the real-model rollout
+gates have passed.
+
The memory viewer should answer four practical questions: “How do you understand my way of working?”, “What do you know about this project?”, “Why did you choose that?”, and “Where were we?” Keep the existing terminal as the place where coding work happens.
Show natural statements with scope and evidence. Allow the user to correct a reason, mark an observed tool as a preference, limit a preference to one project, attach an approved reference, or forget it. Do not show personality scores or demand that the user approve an endless stream of obvious lessons. Ask for clarification only when uncertainty materially changes a current decision.
diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.md
index 1f7e2137b..74cbbcb32 100644
--- a/docs/plans/2026-09-30-coding-memory-review-log.md
+++ b/docs/plans/2026-09-30-coding-memory-review-log.md
@@ -272,3 +272,19 @@ Final targeted validation passed **272 tests across 22 memory and companion-inte
Local full-suite runs did not produce one clean run on this host. The first used an incomplete PATH; its two failing files passed all 100 checks with the normal PATH restored. The next run had timing failures in twelve files; all 412 checks in those files passed alone with one worker. A final one-worker full run passed 7,748 tests with two failures (a hook registry missing at the assertion and an installer timeout), plus 38 skips; those two files then passed all 48 tests unchanged. These rechecks do not relabel the failed full runs as passing. The final native quota cases were verified in the 272-test focused run. The follow-up PR must also record the result of its manually dispatched CI at the exact commit.
PR #521 merged the previous checkpoint into main as `3988b8bbf`. This follow-up preserves the development flag, experimental-companion toggle and watching-consent gates. Task/session navigation, a collection-wide Helping now view, learned retrieval improvements, maintained notebooks, legacy-lesson migration, full native lifecycle verification and the held-out release evidence remain unfinished. The installed app, daemon and firmware remain unchanged.
+
+## Round nineteen: make the coding-memory preview an explicit app setting
+
+The owner can now choose **Settings → Experimental → Coding memory** instead of setting an environment variable. The choice defaults off and persists separately for each account on this computer. An explicit saved off overrides the old environment default. Changing it stops the current learner before applying the new choice, keeps saved memories, and retains the companion/watching and selected-model requirements. Opening settings reads the choice without creating a memory database or launching inference.
+
+The local preference API uses the existing verified owner-process connection, rejects agent tokens and body-supplied owner authority, checks the expected revision, and rechecks identity after asynchronous work. The UI waits for acknowledgement, clears the old account's choice, ignores late replies, and offers a read after an uncertain save without automatically repeating the write. A saved opt-in remains manageable with companions off; only its two preference actions pass that gate, while memory browsing, recall and agent tools remain off. The setting explains that learning is paused in that state.
+
+Two regressions failed before their fixes: companion-off routing prevented clearing the saved choice, and an already open Memories viewer stopped checking after an unsupported response. The viewer now discovers an enabled local service during its ordinary read refresh. This neither sends terminal input nor replays conversation history. The new regression's first post-fix run exposed an unanswered legacy-lesson fixture request; answering that request removed its pending test timer. Strict type checking also required the new route fixture's caller verdict to retain its literal error type.
+
+Validation passed **108 desktop tests across eight files**, **27 local routing/settings tests across three files**, CLI type checking, scoped Flutter analysis, release bundling and the bundled version smoke check. The normal Apple Silicon macOS debug build passed with its local signature. Synthetic [light](../research/2026-10-01-memory-setting/setting-light-1.0x.png) and [enlarged dark](../research/2026-10-01-memory-setting/setting-dark-2.0x.png) renders cover the setting at 100% and 200% text, including a narrow window. These are widget renders, not physical VoiceOver/IME validation. The full CLI run initially hit installer timeouts; a separate loopback probe proved the sandbox denied listening with `EPERM`. That run was stopped and the suite restarted with the required local-server access; the PR records its final result and exact-commit CI.
+
+At the user's request, the earlier review build and matching local CLI were installed for review. The separate review app was opened at **Companions → Memories**, and the new setting's saved on state was observed through the native UI. The personal library was empty. The later regression fixes rebuilt successfully but did not replace or restart that open app. No public release or firmware was published, no synthetic personal memories were seeded, and no additional native model calls were made. The selected Claude account's last observed weekly limit still blocks semantic evaluation. The full product gates, maintained notebook, usefulness-based ranking and other outstanding evidence remain unfinished. The programmer council continues to mean our source-grounded review, not actual participation or endorsement.
+
+The first PR #539 CI run passed 8,001 CLI tests but failed the existing `cli.ts` source-wiring check: its timer regex only recognized a callback beginning directly with `void pairLearner`, and its startup assertion predated the dynamic preview guard. The check now locates the two owned timer registrations independently of callback formatting, still requires both inside the master-switch handler, and checks the new preview gates alongside the existing shutdown assertions. No runtime behavior or test was disabled for that correction. The PR records the subsequent checks on the updated commit.
+
+The permitted local full run completed with **8,043 passed, 6 failed and 38 skipped**. One failure was that timer assertion; all **61 checks across the switch, runtime, settings and local settings-route files** passed after its correction. The remaining five failures were the installed OpenCode TUI's missing `--auto`/`--agent` flags; the OpenCode implementation and flag tests are unchanged in this PR. The full local run is recorded as failed, not relabeled by focused rechecks. Native OpenCode compatibility and the memory model-quality gates are separate from the opt-in setting's validation.
diff --git a/docs/plans/2026-09-30-tim-memory.md b/docs/plans/2026-09-30-tim-memory.md
index b412ca9f8..e8509abec 100644
--- a/docs/plans/2026-09-30-tim-memory.md
+++ b/docs/plans/2026-09-30-tim-memory.md
@@ -4,6 +4,13 @@ Status: implementation in progress, 2026-09-30. The memory core, native transcri
The executable [six-case extraction diagnostic](../research/2026-09-30-memory-extraction-cases.json) now exercises the actual learner, admission and recall. Its [first native attempt](../research/2026-09-30-memory-extraction-baseline.json) stopped with the selected Claude login unavailable: **zero completed extractions**, no quality score. This is separate from the 64 design scenarios and from the required held-out evaluation.
+The review build now exposes the local opt-in in **Settings → Experimental → Coding memory**.
+It defaults off per account on this computer; the existing environment flag supplies only an unsaved
+default. The companion and watching gates still apply. A saved off stops coding-memory capture,
+learning and recall without deleting records. The [later native diagnostic](../research/2026-10-01-memory-native-quality-blocked.json)
+corrected the login-environment defect but stopped on the selected provider's weekly usage limit,
+again with zero completed extractions. Neither the setting nor the UI review satisfies the model-quality gates.
+
Companion experience: a coding agent understands how the developer works, the project's engineering decisions, and the state of the current task. Tim can explain what he remembers, where it came from, and when it may no longer apply. Switching Claude Code to Codex, or Tim to GNU, should preserve that knowledge.
Scope: coding work on one machine across agent frameworks, beginning with Claude Code and Codex. The [coding product model](2026-09-30-coding-memory-product.md) defines developer work contexts, preferences, design taste, technical knowledge, and their boundaries. General DSH domains, cross-machine transport, merge resolution, and account synchronization are outside this release. [Research and source comparison](../research/2026-09-30-cross-framework-memory.md). [Evaluation cases](2026-09-30-tim-memory-cases.json).
diff --git a/docs/research/2026-10-01-memory-setting/setting-dark-1.0x.png b/docs/research/2026-10-01-memory-setting/setting-dark-1.0x.png
new file mode 100644
index 000000000..557634c6e
Binary files /dev/null and b/docs/research/2026-10-01-memory-setting/setting-dark-1.0x.png differ
diff --git a/docs/research/2026-10-01-memory-setting/setting-dark-2.0x.png b/docs/research/2026-10-01-memory-setting/setting-dark-2.0x.png
new file mode 100644
index 000000000..91e9845c7
Binary files /dev/null and b/docs/research/2026-10-01-memory-setting/setting-dark-2.0x.png differ
diff --git a/docs/research/2026-10-01-memory-setting/setting-light-1.0x.png b/docs/research/2026-10-01-memory-setting/setting-light-1.0x.png
new file mode 100644
index 000000000..a5175a081
Binary files /dev/null and b/docs/research/2026-10-01-memory-setting/setting-light-1.0x.png differ
diff --git a/docs/research/2026-10-01-memory-setting/setting-light-2.0x.png b/docs/research/2026-10-01-memory-setting/setting-light-2.0x.png
new file mode 100644
index 000000000..704e7b50d
Binary files /dev/null and b/docs/research/2026-10-01-memory-setting/setting-light-2.0x.png differ