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
Explain why companion memory learning is waiting (#659)
Dee2e200908efdd
diff --git a/cli/src/memory/companion.spec.ts b/cli/src/memory/companion.spec.tsindex ec1bff0aa..378ca4d0f 100644--- a/cli/src/memory/companion.spec.ts+++ b/cli/src/memory/companion.spec.ts@@ -8,6 +8,7 @@ import { CodingMemoryStore } from './store.js'import { MemoryLearner } from './learner.js'import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from './operations.js'import { MemoryError } from './types.js'+import type { InferenceWaitReason } from './inferenceStatus.js'it('waits for a certified selected Codex runtime and preserves foreground priority', async () => {const intelligence = { extractionStatus: async () => ({ state: 'ready' as const, agentId: 'companion', engine: 'codex', contextKey: 'selected' }),@@ -16,7 +17,7 @@ it('waits for a certified selected Codex runtime and preserves foreground priorilet busy = trueconst foreground = vi.fn((id: string) => id === 'companion' && busy)const inference = companionMemoryInference(intelligence, foreground, capability)- expect(await inference.target()).toEqual({ state: 'unsupported' })+ expect(await inference.target()).toEqual({ state: 'unsupported', reason: 'codex_version_uncertified' })expect(intelligence.extract).not.toHaveBeenCalled()capability.mockResolvedValue({ supported: true, version: '0.159.0' })expect(await inference.target()).toEqual({ state: 'ready', key: 'selected', foregroundBusy: true })@@ -48,12 +49,31 @@ it('checks OpenCode native compatibility without probing a different engine', asconst 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' })+ expect(await inference.target()).toEqual({ state: 'unsupported', reason: 'opencode_version_uncertified' })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()})+it.each<InferenceWaitReason>(['companion_unopened', 'companion_stopped', 'companion_starting',+ 'companion_connection_unavailable', 'companion_model_unavailable', 'companion_account_unavailable',+ 'companion_configuration_unsupported', 'inference_context_changed'])(+ 'preserves %s without probing native versions or running extraction', async reason => {+ const capability = vi.fn(), extract = vi.fn()+ const inference = companionMemoryInference({ extractionStatus: async () => ({ state: 'waiting', reason }), extract },+ () => false, capability, capability, capability)+ expect(await inference.target()).toEqual({ state: 'waiting', reason })+ expect(capability).not.toHaveBeenCalled()+ expect(extract).not.toHaveBeenCalled()+ })++it('reports an unsupported Claude version as compatibility, not missing setup', async () => {+ const capability = vi.fn(async () => ({ supported: false, version: 'unverified' }))+ const inference = companionMemoryInference({ extractionStatus: async () => ({ state: 'ready', agentId: 'companion',+ engine: 'claude', contextKey: 'binding' }), extract: vi.fn() }, () => false, vi.fn(), capability, vi.fn())+ expect(await inference.target()).toEqual({ state: 'unsupported', reason: 'claude_version_uncertified' })+})+it('preserves queued evidence and stops calls and native probes after a refusal, then resumes on a new connection', async () => {const directory = mkdtempSync(join(tmpdir(), 'memory-refusal-'))let now = 10_000diff --git a/cli/src/memory/companion.ts b/cli/src/memory/companion.tsindex f8668bc31..47cdb6a90 100644--- a/cli/src/memory/companion.ts+++ b/cli/src/memory/companion.ts@@ -4,6 +4,7 @@ import { codexMemoryCapability } from './inference.js'import { claudeMemoryCapability } from './claudeInference.js'import { opencodeMemoryCapability } from './opencodeInference.js'import type { MemoryInference } from './learner.js'+import { inferenceWaitReason } from './inferenceStatus.js'export function companionMemoryInference(intelligence: Pick<CompanionIntelligence, 'extractionStatus' | 'extract'>,foregroundBusy: (companionAgentId: string) => boolean,@@ -12,13 +13,14 @@ export function companionMemoryInference(intelligence: Pick<CompanionIntelligencreturn {async target() {const status = await intelligence.extractionStatus()+ const reason = inferenceWaitReason(status.reason)if (status.state === 'off') return { state: 'off' }- if (status.state === 'unsupported') return { state: 'unsupported', ...(status.reason ? { reason: status.reason } : {}) }- if (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' }+ if (status.state === 'unsupported') return { state: 'unsupported', ...(reason ? { reason } : {}) }+ if (status.state !== 'ready' || !status.contextKey || !status.agentId) return { state: 'waiting', ...(reason ? { reason } : {}) }+ if (status.engine === 'codex' && !(await codexCapability()).supported) return { state: 'unsupported', reason: 'codex_version_uncertified' }+ if (status.engine === 'claude' && !(await claudeCapability()).supported) return { state: 'unsupported', reason: 'claude_version_uncertified' }+ if (status.engine === 'opencode' && !(await opencodeCapability()).supported) return { state: 'unsupported', reason: 'opencode_version_uncertified' }+ if (!['claude', 'codex', 'opencode'].includes(status.engine ?? '')) return { state: 'unsupported', reason: 'companion_configuration_unsupported' }return { state: 'ready', key: status.contextKey, foregroundBusy: foregroundBusy(status.agentId) }},run: (prompt, options) => intelligence.extract(prompt, options),diff --git a/cli/src/memory/inferenceStatus.ts b/cli/src/memory/inferenceStatus.tsnew file mode 100644index 000000000..19d98f725--- /dev/null+++ b/cli/src/memory/inferenceStatus.ts@@ -0,0 +1,13 @@+/** Bounded availability codes, safe to persist or expose instead of native/provider output. */+const reasons = [+ 'companion_unopened', 'companion_stopped', 'companion_starting', 'companion_model_unavailable',+ 'companion_connection_unavailable', 'companion_account_unavailable', 'companion_configuration_unsupported',+ 'inference_context_changed', 'inference_provider_restricted',+ 'claude_version_uncertified', 'codex_version_uncertified', 'opencode_version_uncertified',+] as const+export type InferenceWaitReason = typeof reasons[number]++export function inferenceWaitReason(value: unknown): InferenceWaitReason | undefined {+ return typeof value === 'string' && (reasons as readonly string[]).includes(value)+ ? value as InferenceWaitReason : undefined+}diff --git a/cli/src/memory/learner.spec.ts b/cli/src/memory/learner.spec.tsindex 20793d88a..8fa61f628 100644--- a/cli/src/memory/learner.spec.ts+++ b/cli/src/memory/learner.spec.ts@@ -6,6 +6,7 @@ import { CodingMemoryStore } from './store.js'import { MemoryLearner, type MemoryInference } from './learner.js'import { QUEUE_OPERATIONS, type MemoryPort, type Operation, type Arguments, type Result } from './operations.js'import { MemoryError, type MemoryAccess, type MemoryDraft, type SourceEvent } from './types.js'+import { PENDING_RETENTION_MS } from './queue.js'const access: MemoryAccess = { profileId: 'owner', projectIds: ['project'], includeProfile: false }const event: SourceEvent = { id: 'first', profileId: 'owner', projectId: 'project', engine: 'codex', sessionId: 'session',@@ -59,6 +60,50 @@ function originalSources(prompt: string): SourceEvent[] {return promptSources(prompt).map(({ excerpts, ...metadata }) => ({ ...metadata, text: excerpts.map(part => part.text).join('') }))}+it('keeps the model wait reason across retry delays and restart without extra probes or losing queued evidence', async () => {+ const provider = inference()+ provider.target = vi.fn(async () => ({ state: 'waiting' as const, reason: 'companion_stopped' as const }))+ const waiting = { state: 'waiting_for_model', reason: 'companion_stopped' }+ const learner = new MemoryLearner(memory, provider)+ expect(await learner.tick()).toEqual(waiting)+ expect(await learner.tick()).toEqual(waiting)+ expect(provider.target).toHaveBeenCalledOnce()+ expect(provider.run).not.toHaveBeenCalled()+ expect(store.learning.status().callsLastHour).toBe(0)+ expect(store.source(event.id, access)).toEqual(event)++ store.close()+ const reopened = CodingMemoryStore.open({ directory, profileId: 'owner', now: () => now })+ if (!reopened.ok) throw new Error(reopened.reason)+ store = reopened.store+ const restarted = new MemoryLearner(memory, provider)+ expect(await restarted.tick()).toEqual(waiting)+ expect(provider.target).toHaveBeenCalledOnce()+ now += 60_001+ provider.target = vi.fn(async () => ({ state: 'ready' as const, key: 'new-selected-connection' }))+ expect(await restarted.tick()).toEqual({ state: 'learned', learned: 1 })+ expect(store.learning.waitingForModel()).toBeNull()+ expect(store.list(access)[0].evidence[0].quote).toBe(event.text)+ expect(provider.run).toHaveBeenCalledOnce()+})++it.each(['off', 'excluded', 'private', 'expired'] as const)('does not retain a model-wait notice for %s work', async change => {+ const provider = inference()+ provider.target = async () => ({ state: 'waiting', reason: 'companion_account_unavailable' })+ expect((await new MemoryLearner(memory, provider).tick()).reason).toBe('companion_account_unavailable')+ if (change === 'off') store.setControls({ learn: false, recall: true })+ if (change === 'excluded') store.setProjectIncluded('project', false)+ if (change === 'private') store.setSessionIncluded('codex', 'session', false)+ if (change === 'expired') now += PENDING_RETENTION_MS+ expect(store.learning.waitingForModel()).toBeNull()+})++it('never persists or exposes a raw provider error as an availability reason', () => {+ const target = { state: 'unsupported' as const, reason: 'secret-provider-response' as 'companion_stopped' }+ expect(store.learning.claim(target)).toEqual({ state: 'waiting_for_model' })+ expect(store.learning.waitingForModel()).toEqual({ state: 'waiting_for_model' })+})+it('extracts scoped knowledge through one selected target and retains its exact evidence', async () => {const provider = inference()const outcome = await new MemoryLearner(memory, provider).tick()@@ -177,7 +222,7 @@ it('records a no-useful-memory result separately from unavailable intelligence',expect(await learner.tick()).toEqual({ state: 'waiting_for_model' })expect(store.learning.status().jobs.no_useful_memory).toBeUndefined()expect(store.learning.status().jobs.waiting_for_model).toBe(1)- expect((await learner.tick()).state).toBe('idle')+ expect((await learner.tick()).state).toBe('waiting_for_model')expect(provider.target).toHaveBeenCalledOnce()now += 60_001provider.run = vi.fn(async () => '{"proposals":[]}')diff --git a/cli/src/memory/learner.ts b/cli/src/memory/learner.tsindex 2da9f2f38..56aa12ec1 100644--- a/cli/src/memory/learner.ts+++ b/cli/src/memory/learner.ts@@ -5,6 +5,7 @@ import type { InferenceTarget, LearningLease } from './queue.js'import { MEMORY_CONTEXT_GUIDE } from './context.js'import { notebookProposalSchema, type NotebookLease } from './notebook.js'import { extractionOutputSchema, extractionSources, resolveExtractionProposals } from './extractionEvidence.js'+import { inferenceWaitReason } from './inferenceStatus.js'const outputSchema = JSON.stringify(z.toJSONSchema(extractionOutputSchema, { io: 'input' }))export const EXTRACTION_PROMPT_VERSION = 'coding-memory-v6'@@ -126,7 +127,11 @@ export class MemoryLearner {const notebook = await this.memory.request('notebookPending', [])assertActive(controller.signal)const buildNotebook = notebook.state === 'ready' && (pending !== 'ready' || notebook.prefer)- if (!buildNotebook && pending !== 'ready') return { state: notebook.state === 'idle' ? pending : notebook.state }+ if (!buildNotebook && pending !== 'ready') {+ const waiting = await this.memory.request('waitingForModel', [])+ assertActive(controller.signal)+ return waiting ?? { state: notebook.state === 'idle' ? pending : notebook.state }+ }target ??= await this.inference.target()if (controller.signal.aborted) return { state: controller.signal.reason === 'foreground_activity' ? 'waiting_for_quiet' : 'cancelled' }if (target.reason === 'inference_provider_restricted') {@@ -134,9 +139,11 @@ export class MemoryLearner {return { state: 'waiting_for_model', reason: target.reason }}const timeoutMs = Math.max(1, Math.min(this.timeoutMs, 90_000))+ const waitReason = inferenceWaitReason(target.reason)if (buildNotebook) {const claim = await this.memory.request('notebookClaim', [target])- if (claim.state !== 'claimed') return { state: claim.state }+ if (claim.state !== 'claimed') return { state: claim.state,+ ...(claim.state === 'waiting_for_model' && waitReason ? { reason: waitReason } : {}) }notebookLease = claim.leaseassertActive(controller.signal)const answer = await infer(this.inference, notebookPrompt(notebookLease), controller, timeoutMs, target.key!)@@ -152,7 +159,7 @@ export class MemoryLearner {return { state: committed.state === 'ready' ? 'notebook_updated' : committed.state === 'empty' ? 'notebook_empty' : 'stale' }}const claim = await this.memory.request('claim', [target])- if (claim.state !== 'claimed') return { state: claim.state }+ if (claim.state !== 'claimed') return { state: claim.state, ...(claim.reason ? { reason: claim.reason } : {}) }lease = claim.leaseassertActive(controller.signal)const existing = await this.memory.request('list', [lease.access, 100])diff --git a/cli/src/memory/operations.ts b/cli/src/memory/operations.tsindex 347e20a27..9b75f88a1 100644--- a/cli/src/memory/operations.ts+++ b/cli/src/memory/operations.ts@@ -9,7 +9,7 @@ export type MemoryOperations = Pick<CodingMemoryStore,| 'libraryPage' | 'libraryProjects' | 'libraryActivity' | 'libraryDetail' | 'libraryCorrect' | 'libraryForget' | 'libraryPreview' | 'libraryApply'| 'notebookPending' | 'notebookClaim' | 'notebookFinish' | 'notebookDefer' | 'libraryNotebooks' | 'libraryNotebook'| 'prepareRecall' | 'recallEmitted' | 'recallReceipts' | 'putTopic' | 'topic' | 'forget'>- & Pick<MemoryQueue, 'capture' | 'checkpoint' | 'pendingReview' | 'claim' | 'finish' | 'defer' | 'cursor' | 'episodeOpen' | 'status'>+ & Pick<MemoryQueue, 'capture' | 'checkpoint' | 'pendingReview' | 'waitingForModel' | 'claim' | 'finish' | 'defer' | 'cursor' | 'episodeOpen' | 'status'>export type Operation = keyof MemoryOperationsexport type Arguments<K extends Operation> = Parameters<MemoryOperations[K]>export type Result<K extends Operation> = ReturnType<MemoryOperations[K]>@@ -21,4 +21,4 @@ export const STORE_OPERATIONS = ['controls', 'setControls', 'preferences', 'setP'libraryPage', 'libraryProjects', 'libraryActivity', 'libraryDetail', 'libraryCorrect', 'libraryForget', 'libraryPreview', 'libraryApply','notebookPending', 'notebookClaim', 'notebookFinish', 'notebookDefer', 'libraryNotebooks', 'libraryNotebook','prepareRecall', 'recallEmitted', 'recallReceipts', 'putTopic', 'topic', 'forget'] as const-export const QUEUE_OPERATIONS = ['capture', 'checkpoint', 'pendingReview', 'claim', 'finish', 'defer', 'cursor', 'episodeOpen', 'status'] as const+export const QUEUE_OPERATIONS = ['capture', 'checkpoint', 'pendingReview', 'waitingForModel', 'claim', 'finish', 'defer', 'cursor', 'episodeOpen', 'status'] as constdiff --git a/cli/src/memory/queue.ts b/cli/src/memory/queue.tsindex 7921da001..c111ccd10 100644--- a/cli/src/memory/queue.ts+++ b/cli/src/memory/queue.ts@@ -3,6 +3,7 @@ import { z } from 'zod'import { digest } from './admission.js'import { memoryCallAllowance, reserveMemoryCall, MEMORY_CALL_PURPOSE_SCHEMA } from './budget.js'import type { Database } from './database.js'+import { inferenceWaitReason, type InferenceWaitReason } from './inferenceStatus.js'import { MemoryError, parse, sourceSchema, type MemoryAccess, type MemoryDraft, type MemoryRecord, type SourceEvent } from './types.js'export const QUEUE_SCHEMA = `@@ -60,8 +61,8 @@ export interface InferenceTarget {state: 'ready' | 'waiting' | 'off' | 'unsupported'/** Opaque host-derived identity of the selected account, collection, model, and effort. */key?: string- /** A recognized provider refusal, never raw provider output. */- reason?: 'inference_provider_restricted'+ /** Recognized availability code, never raw native/provider output. */+ reason?: InferenceWaitReasonforegroundBusy?: boolean}export interface LearningLease {@@ -71,7 +72,7 @@ export interface LearningLease {episodes: Array<{ jobId: string; sourceIds: string[]; context: 'complete' | 'bounded' }>}export type ClaimResult = { state: 'claimed'; lease: LearningLease }- | { state: 'idle' | 'learning_off' | 'foreground_busy' | 'waiting_for_model' | 'budget_deferred' | 'source_incomplete'; retryAt?: number }+ | { state: 'idle' | 'learning_off' | 'foreground_busy' | 'waiting_for_model' | 'budget_deferred' | 'source_incomplete'; retryAt?: number; reason?: InferenceWaitReason }export type FinishResult = { state: 'learned' | 'no_useful_memory'; records: MemoryRecord[] }| { state: 'stale' | 'failed'; reason: string }@@ -165,6 +166,18 @@ export class MemoryQueue {return this.nextJob() ? 'ready' : 'idle'}+ /** A deferred job is still waiting, not an empty queue. No native probes or source text. */+ waitingForModel(): { state: 'waiting_for_model'; reason?: InferenceWaitReason } | null {+ if (!this.deps.controls().learn) return null+ const row = this.deps.db.prepare(`SELECT j.last_error FROM memory_jobs j+ WHERE j.state='waiting_for_model' AND j.created_at>?+ AND (j.project_id IS NULL OR j.project_id IN (SELECT id FROM projects WHERE included=1))+ ORDER BY j.priority DESC,j.created_at,j.id LIMIT 1`).get(this.deps.now() - PENDING_RETENTION_MS)+ if (!row) return null+ const reason = inferenceWaitReason(row.last_error)+ return { state: 'waiting_for_model', ...(reason ? { reason } : {}) }+ }+private nextJob(): Record<string, unknown> | undefined {return this.readyJobs(1)[0]}@@ -194,8 +207,9 @@ export class MemoryQueue {if (!job) return { state: 'idle' as const }const jobId = String(job.id)if (target.state !== 'ready' || !target.key) {- this.release(jobId, 'waiting_for_model', target.state === 'unsupported' ? 'model_unsupported' : 'model_unavailable', now() + 60_000)- return { state: 'waiting_for_model' as const }+ const reason = inferenceWaitReason(target.reason)+ this.release(jobId, 'waiting_for_model', reason ?? (target.state === 'unsupported' ? 'model_unsupported' : 'model_unavailable'), now() + 60_000)+ return { state: 'waiting_for_model' as const, ...(reason ? { reason } : {}) }}const usage = memoryCallAllowance(db, now())if (usage.retryAt !== null) {diff --git a/cli/src/pair/intelligence.spec.ts b/cli/src/pair/intelligence.spec.tsindex 071284c4d..45dc02802 100644--- a/cli/src/pair/intelligence.spec.ts+++ b/cli/src/pair/intelligence.spec.ts@@ -122,11 +122,24 @@ describe('the collection DSH supplies its intelligence', () => {finish({ text: 'answer from old account' })expect(await pending).toBeNull()account = null- expect((await brain.extractionStatus()).state).toBe('waiting')+ expect(await brain.extractionStatus()).toMatchObject({ state: 'waiting', reason: 'companion_account_unavailable' })expect(await brain.extract('evidence', { timeoutMs: 1000, signal: new AbortController().signal, contextKey: before! })).toBeNull()expect(w.run).toHaveBeenCalledOnce()})+ it('distinguishes unopened, starting, missing model and unsupported configuration without guessing credentials', async () => {+ const w = world()+ w.set(null)+ expect(w.brain.status()).toEqual({ state: 'unopened', reason: 'companion_unopened' })+ w.set({ agentId: 'collection', engine: 'claude', stopped: false, sessionId: null, profile: null })+ expect(w.brain.status()).toMatchObject({ state: 'waiting', reason: 'companion_starting' })+ w.set({ ...w.get(), sessionId: 'session' })+ expect(w.brain.status()).toMatchObject({ state: 'waiting', reason: 'companion_model_unavailable' })+ w.set({ ...w.get(), customProvider: true })+ expect(w.brain.status()).toMatchObject({ state: 'unsupported', reason: 'companion_configuration_unsupported' })+ expect(w.run).not.toHaveBeenCalled()+ })+it('cancels while the native account lookup is pending without launching extraction', async () => {const w = world()let finish!: (value: string) => void@@ -169,6 +182,17 @@ describe('OpenCode companion request binding', () => {return { ...w, brain, openCodeRun: run, accountIdentity, snapshot: () => snapshot!, setSnapshot: (value: OpenCodeMemorySnapshot | null) => { snapshot = value } }}+ it('distinguishes a stopped companion from an unobserved live connection without starting either', async () => {+ const w = openCodeWorld()+ w.set({ ...w.get(), stopped: true })+ expect(await w.brain.extractionStatus()).toMatchObject({ state: 'waiting', reason: 'companion_stopped' })+ w.set({ ...w.get(), stopped: false })+ w.setSnapshot(null)+ expect(await w.brain.extractionStatus()).toMatchObject({ state: 'waiting', reason: 'companion_connection_unavailable' })+ expect(w.openCodeRun).not.toHaveBeenCalled()+ expect(w.accountIdentity).not.toHaveBeenCalled()+ })+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' })diff --git a/cli/src/pair/intelligence.ts b/cli/src/pair/intelligence.tsindex 414dcbba1..4132479d2 100644--- a/cli/src/pair/intelligence.ts+++ b/cli/src/pair/intelligence.ts@@ -12,6 +12,7 @@ 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 type { InferenceWaitReason } from '../memory/inferenceStatus.js'import { openCodeSnapshotIdentity, runOpenCodeMemoryInference,type OpenCodeMemorySnapshot, type OpenCodeMemoryInferenceOptions } from '../memory/opencodeInference.js'@@ -36,7 +37,7 @@ export interface IntelligenceStatus {model?: stringeffort?: stringcontextKey?: string- reason?: 'inference_provider_restricted'+ reason?: InferenceWaitReason}interface IntelligenceDeps {@@ -136,7 +137,9 @@ export class CompanionIntelligence {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' } }+ if (current.status.contextKey !== target.status.contextKey) return current.status.state !== 'ready' ? current+ : { status: { ...current.status, state: 'waiting', reason: 'inference_context_changed' } }+ if (!identity) return { status: { ...current.status, state: 'waiting', reason: 'companion_account_unavailable' } }return { ...target, status: { ...target.status,contextKey: createHash('sha256').update(JSON.stringify([target.status.contextKey, identity])).digest('hex') } }}@@ -145,14 +148,21 @@ export class CompanionIntelligence {openCodeSnapshot?: OpenCodeMemorySnapshot } {if (!this.deps.enabled()) return { status: { state: 'off' } }const runtime = this.deps.current()- if (!runtime) return { status: { state: 'unopened' } }+ if (!runtime) return { status: { state: 'unopened', reason: 'companion_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', 'opencode'].includes(runtime.engine) || (runtime.customProvider && runtime.engine !== 'opencode')) return { status: { ...status, state: 'unsupported' } }+ if (!['claude', 'codex', 'opencode'].includes(runtime.engine) || (runtime.customProvider && runtime.engine !== 'opencode')) {+ return { status: { ...status, state: 'unsupported', reason: 'companion_configuration_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 }+ if (runtime.engine === 'opencode') {+ if (runtime.stopped) return { status: { ...status, reason: 'companion_stopped' } }+ if (!runtime.sessionId || !runtime.nativeProcessKey) return { status: { ...status, reason: 'companion_starting' } }+ if (!runtime.accountKey || !openCodeSnapshot) return { status: { ...status, reason: 'companion_connection_unavailable' } }+ }+ if (!runtime.sessionId && (runtime.stopped || !runtime.startup)) {+ return { status: { ...status, reason: runtime.stopped ? 'companion_stopped' : 'companion_starting' } }+ }this.load()const cached = this.saved![runtime.agentId]const value = runtime.sessionId@@ -163,8 +173,10 @@ export class CompanionIntelligence {const efforts = runtime.engine === 'claude'? ['auto', 'low', 'medium', 'high', 'xhigh', 'max', 'ultracode']: 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 }+ if (!profile || profile.sessionId !== runtime.agentId || profile.engine !== runtime.engine || !efforts.includes(profile.effort)) {+ return { status: { ...status, reason: 'companion_model_unavailable' } }+ }+ if (openCodeSnapshot && openCodeSnapshot.model !== profile.model) return { status: { ...status, reason: 'inference_context_changed' } }// 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 }diff --git a/desktop/lib/companions/coding_memory_view.dart b/desktop/lib/companions/coding_memory_view.dartindex 9b3738bd9..67c5e76c5 100644--- a/desktop/lib/companions/coding_memory_view.dart+++ b/desktop/lib/companions/coding_memory_view.dart@@ -310,10 +310,7 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {: 'Some recent work could not be read for learning. Your existing memories are still available.';final state = learning['state'];final message = switch (state) {- 'waiting_for_model'- when learning['reason'] == 'inference_provider_restricted' =>- 'Your selected model’s provider declined background learning. Choose another model in the companion terminal to continue. Existing memories are still available.',- 'waiting_for_model' => 'Waiting for your companion’s model. Check that its terminal beside this viewer is running with a model selected, and complete any setup shown there.',+ 'waiting_for_model' => _modelWaitMessage(learning['reason']),'foreground_busy' =>'Your companion is working. Learning waits until it is free.','waiting_for_quiet' =>@@ -345,6 +342,22 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {);}+String _modelWaitMessage(Object? reason) => switch (reason) {+ 'companion_unopened' => 'Start your companion in the terminal beside this viewer to begin learning. Saved memories remain available.',+ 'companion_stopped' => 'Your companion is stopped. Reopen its conversation to continue learning. Saved memories remain available.',+ 'companion_starting' => 'Waiting for your companion’s agent to finish starting. Complete any setup shown in its terminal.',+ 'companion_model_unavailable' => 'Choose a model in the companion terminal so it can review your coding work.',+ 'companion_connection_unavailable' => 'Waiting for the companion’s current model connection. Check its terminal and complete any connection or sign-in setup shown there.',+ 'companion_account_unavailable' => 'Harness could not verify the selected agent’s sign-in for background learning. Check the companion terminal and complete sign-in if needed.',+ 'companion_configuration_unsupported' => 'Background learning is unavailable for this agent or provider configuration. Choose a supported agent in the companion terminal. Saved memories remain available.',+ 'claude_version_uncertified' ||+ 'codex_version_uncertified' ||+ 'opencode_version_uncertified' => 'Background learning is not yet supported with this version of your selected agent. Choose a supported agent in the companion terminal, or wait for a Harness update. Saved memories remain available.',+ 'inference_context_changed' => 'Your companion’s model or connection changed. Learning will check the new selection before reviewing more work.',+ 'inference_provider_restricted' => 'Your selected model’s provider declined background learning. Choose another model in the companion terminal to continue. Existing memories are still available.',+ _ => 'Waiting for your companion’s model. Check that its terminal beside this viewer is running with a model selected, and complete any setup shown there.',+};+Widget _text(String value, {bool small = false}) => Text(value,style: smalldiff --git a/desktop/test/coding_memory_view_test.dart b/desktop/test/coding_memory_view_test.dartindex 1ac7b51f0..77a3e82d0 100644--- a/desktop/test/coding_memory_view_test.dart+++ b/desktop/test/coding_memory_view_test.dart@@ -1189,6 +1189,86 @@ void main() {});}+ for (final reason in [+ ('companion_unopened', 'Start your companion'),+ ('companion_stopped', 'Reopen its conversation'),+ ('companion_starting', 'finish starting'),+ ('companion_model_unavailable', 'Choose a model'),+ ('companion_connection_unavailable', 'current model connection'),+ ('companion_account_unavailable', 'could not verify'),+ ('companion_configuration_unsupported', 'agent or provider configuration'),+ ('claude_version_uncertified', 'this version of your selected agent'),+ ('codex_version_uncertified', 'this version of your selected agent'),+ ('opencode_version_uncertified', 'this version of your selected agent'),+ ('inference_context_changed', 'will check the new selection'),+ (+ 'unknown-private-provider-text',+ 'Check that its terminal beside this viewer',+ ),+ ]) {+ testWidgets('learning shows a recovery step for ${reason.$1}', (+ tester,+ ) async {+ transport.runtime = {+ 'state': 'ready',+ 'learning': {'state': 'waiting_for_model', 'reason': reason.$1},+ };+ await mount(tester);+ expect(find.textContaining(reason.$2), findsOneWidget);+ expect(+ find.textContaining('unknown-private-provider-text'),+ findsNothing,+ );+ await tap(tester, 'Review learning');+ expect(find.textContaining(reason.$2), findsOneWidget);+ expect(transport.learn, isTrue);+ expect(transport.recall, isTrue);+ expect(+ transport.calls.any((p) => ['preview', 'apply'].contains(p['action'])),+ isFalse,+ );+ expect(tester.takeException(), isNull);++ transport.runtime = {+ 'state': 'ready',+ 'learning': {'state': 'learned', 'learned': 1},+ };+ await library.refresh();+ await tester.pumpAndSettle();+ expect(find.textContaining(reason.$2), findsNothing);+ expect(find.textContaining('saved new memories'), findsOneWidget);+ });+ }++ for (final brightness in [Brightness.dark, Brightness.light]) {+ testWidgets(+ 'stopped companion and backlog fit ${brightness.name} at large text',+ (tester) async {+ transport.runtime = {+ 'state': 'ready',+ 'learning': {+ 'state': 'waiting_for_model',+ 'reason': 'companion_stopped',+ },+ 'capture': {'state': 'unavailable', 'reason': 'memory_backlog_full'},+ };+ await mount(+ tester,+ brightness: brightness,+ scale: 2,+ size: const Size(440, 1100),+ );+ expect(find.textContaining('Reopen its conversation'), findsOneWidget);+ expect(find.textContaining('queue is full'), findsOneWidget);+ await capture(+ tester,+ 'companion-stopped-${brightness.name}-large-text',+ );+ expect(tester.takeException(), isNull);+ },+ );+ }+for (final brightness in [Brightness.dark, Brightness.light]) {for (final scale in [1.0, 2.0]) {testWidgets(diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.mdindex 0ab79f5d3..0a7c81237 100644--- a/docs/plans/2026-09-30-coding-memory-review-log.md+++ b/docs/plans/2026-09-30-coding-memory-review-log.md@@ -1044,3 +1044,28 @@ error can surface as `waiting_for_model / inference_unavailable`. That classificneeds a focused follow-up; it does not explain the live provider blockage withoutadditional evidence. Live automatic learning, wider native lifecycles and theplanned quality/benefit gates remain unfinished.++### Explain why continuous learning is waiting — October 3++The collection now carries bounded availability reasons from its observed runtime+through the memory adapter, queue and Memories viewer. A stopped or unopened+companion, incomplete startup, unavailable model/account connection, unsupported+configuration and unverified native version have distinct recovery explanations.+An unavailable account observation does not claim the user is signed out. Native+version refusal remains separate from model quality and provider refusal.++Extraction jobs retain their last recognized reason in existing queue metadata.+During the retry delay, an idle check no longer describes that deferred work as an+empty queue. This survives store/learner restart without another account lookup,+version probe or inference call. Learning-off, excluded/private sources and expired+work suppress the notice; a successful later review clears it. Only fixed reason+codes are retained or shown, never native/provider error text. Notebook claim+failures forward the current reason, but notebook-only delay metadata still lacks+the durable per-job reason used by extraction jobs.++The Desktop points to the existing companion terminal and model controls. Reading+or reviewing the explanation does not reopen an agent or change Learn/Recall.+This improves recovery diagnosis; it does not unblock the installed stopped+conversation, change the selected provider, or establish successful real-user+learning. The separate in-process diagnostic storage-error classification and the+two unsupported private-example memories remain open.