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 recall feedback and fix native memory login and quota handling (#526)

Dee5dd9a58f11e6
diff --git a/cli/scripts/memory-extraction-eval.ts b/cli/scripts/memory-extraction-eval.ts
index 86a1f364c..12b3535ea 100644
--- a/cli/scripts/memory-extraction-eval.ts
+++ b/cli/scripts/memory-extraction-eval.ts
@@ -89,7 +89,7 @@ async function run() {
try { await (await open(output!, 'wx', 0o600)).close() } catch { throw new MemoryError('evaluation_report_unavailable_or_exists') }
const temporary = await mkdtemp(join(tmpdir(), 'memory-extraction-eval-'))
const sourceFiles = ['learner.ts', 'context.ts', 'types.ts', 'admission.ts', 'store.ts', 'queue.ts', 'evaluation.ts',
- 'claudeInference.ts', 'inference.ts', 'inferenceProcess.ts']
+ 'account.ts', 'claudeInference.ts', 'inference.ts', 'inferenceProcess.ts']
const sourceHashes = Object.fromEntries(await Promise.all(sourceFiles.map(async name => [name, digest(await readFile(join(cli, 'src/memory', name), 'utf8'))])))
const report: Record<string, any> = { schemaVersion: 1, suite: suite.suite, suiteSha256: digest(suiteText),
promptVersion: EXTRACTION_PROMPT_VERSION, contextVersion: MEMORY_CONTEXT_VERSION,
diff --git a/cli/src/memory/account.ts b/cli/src/memory/account.ts
index d42727379..7e813f46d 100644
--- a/cli/src/memory/account.ts
+++ b/cli/src/memory/account.ts
@@ -1,7 +1,7 @@
/** Observe native login identity without retaining or returning credentials. No network or refresh. */
import { createHash } from 'node:crypto'
import { open } from 'node:fs/promises'
-import { homedir, tmpdir } from 'node:os'
+import { homedir, tmpdir, userInfo } from 'node:os'
import { isAbsolute, join } from 'node:path'
import { oneShotParentEnv } from '../lib/loginShellEnv.js'
@@ -13,7 +13,11 @@ export function memoryCodexHome(selected?: string | null, home = homedir(), envi
/** Only native login files select the extraction account; ambient keys cannot override it. */
export function nativeMemoryEnvironment(): NodeJS.ProcessEnv {
const parent = oneShotParentEnv()
- return { PATH: parent.PATH, HOME: homedir(), TMPDIR: tmpdir(), LANG: parent.LANG || 'en_US.UTF-8', TERM: 'dumb' }
+ // Claude's native credential lookup needs the OS login name on macOS. Omitting it reports
+ // signed-out despite an existing login. Bind it to the OS user, not a caller's USER/LOGNAME.
+ const username = userInfo().username
+ return { PATH: parent.PATH, HOME: homedir(), USER: username, LOGNAME: username,
+ TMPDIR: tmpdir(), LANG: parent.LANG || 'en_US.UTF-8', TERM: 'dumb' }
}
export async function memoryAccountIdentity(input: { engine: string; codexHome?: string | null },
diff --git a/cli/src/memory/claudeInference.spec.ts b/cli/src/memory/claudeInference.spec.ts
index c99b50c5f..528e3b076 100644
--- a/cli/src/memory/claudeInference.spec.ts
+++ b/cli/src/memory/claudeInference.spec.ts
@@ -34,6 +34,16 @@ it.each(['2.1.285', '2.1.286'])('uses a fresh %s native process with the selecte
expect(launch.tmux).toBeUndefined()
})
+it('lets native credential lookup use the actual OS user, never an inherited claimed identity', async () => {
+ program(`const owner=require('node:os').userInfo().username;
+ if(process.env.USER!==owner || process.env.LOGNAME!==owner) process.exit(7);
+ ${emit({ type: 'system', subtype: 'init', tools: [] })} ${success}`)
+ vi.stubEnv('USER', 'a-different-user')
+ vi.stubEnv('LOGNAME', 'a-different-user')
+ expect(await runClaudeMemoryInference({ cwd: directory, prompt: 'synthetic evidence', model: 'selected-model' }))
+ .toEqual({ text: '{"proposals":[]}' })
+})
+
it.each([
{ type: 'system', subtype: 'init', tools: ['Bash'] },
{ type: 'assistant', message: { content: [{ type: 'tool_use', name: 'Bash', input: { command: 'false' } }] } },
@@ -49,6 +59,30 @@ it('does not treat an error result or partial assistant prose as a completed ext
await expect(runClaudeMemoryInference({ cwd: directory, prompt: 'evidence', model: 'selected-model' })).rejects.toThrow('inference_usage_limit')
})
+// Sanitized native 2.1.286 observations: weekly-limit rejection, assistant.error=rate_limit,
+// and a success-subtype result with is_error=true. Omitted account/session identifiers and prose.
+it.each([
+ { type: 'rate_limit_event', rate_limit_info: { status: 'rejected', rateLimitType: 'seven_day' } },
+ { type: 'assistant', error: 'rate_limit', message: { content: [{ type: 'text', text: 'Usage unavailable' }] } },
+ { type: 'result', subtype: 'success', is_error: true, result: "You've hit your limit" },
+])('defers native usage rejection without accepting a later answer', async event => {
+ program(`${emit(event)} ${success}`)
+ await expect(runClaudeMemoryInference({ cwd: directory, prompt: 'synthetic evidence', model: 'opus' }))
+ .rejects.toThrow('inference_usage_limit')
+})
+
+it.each(['allowed', 'allowed_warning'])('allows %s rate-limit telemetry without inventing a quota failure', async status => {
+ program(`${emit({ type: 'rate_limit_event', rate_limit_info: { status } })} ${success}`)
+ expect(await runClaudeMemoryInference({ cwd: directory, prompt: 'synthetic evidence', model: 'opus' }))
+ .toEqual({ text: '{"proposals":[]}' })
+})
+
+it('rejects a native assistant error even if a later frame claims success', async () => {
+ program(`${emit({ type: 'assistant', error: 'authentication_failed', message: { content: [{ type: 'text', text: 'Unavailable' }] } })} ${success}`)
+ await expect(runClaudeMemoryInference({ cwd: directory, prompt: 'synthetic evidence', model: 'opus' }))
+ .rejects.toThrow('inference_unavailable')
+})
+
it('waits on an uncertified native release', async () => {
program('throw new Error("must not invoke")', '2.99.0')
expect(await claudeMemoryCapability()).toEqual({ supported: false, version: '2.99.0' })
diff --git a/cli/src/memory/claudeInference.ts b/cli/src/memory/claudeInference.ts
index 5cc90b625..644f19d1e 100644
--- a/cli/src/memory/claudeInference.ts
+++ b/cli/src/memory/claudeInference.ts
@@ -37,19 +37,22 @@ export async function runClaudeMemoryInference(options: MemoryInferenceOptions):
return {}
}
if (event.type === 'assistant') {
+ if (event.error) return { error: event.error === 'rate_limit' ? 'inference_usage_limit' : 'inference_unavailable' }
const content = (event.message as { content?: Array<{ type?: string }> } | undefined)?.content
return !Array.isArray(content) || content.some(part => !['text', 'thinking', 'redacted_thinking'].includes(part.type ?? ''))
? { error: 'inference_tool_or_error' } : {}
}
if (event.type === 'result') {
- if (event.is_error || event.subtype !== 'success') return { error: /rate.?limit|quota|usage limit/i.test(JSON.stringify(event.errors))
+ if (event.is_error || event.subtype !== 'success') return { error: /rate.?limit|quota|usage limit|hit.{0,20}limit|limit reached/i.test(JSON.stringify([event.errors, event.result]))
? 'inference_usage_limit' : 'inference_unavailable' }
return typeof event.result === 'string' ? { text: event.result, completed: true,
observation: { usage: nativeMemoryUsage(event.usage),
...(typeof event.total_cost_usd === 'number' && Number.isFinite(event.total_cost_usd) && event.total_cost_usd >= 0
? { reportedCostUsd: event.total_cost_usd } : {}) } } : { error: 'invalid_inference_output' }
}
- if (event.type === 'rate_limit_event') return {}
+ if (event.type === 'rate_limit_event') return {
+ ...((event.rate_limit_info as { status?: string } | undefined)?.status === 'rejected' ? { error: 'inference_usage_limit' } : {}),
+ }
return { error: 'inference_protocol_changed' }
})
}
diff --git a/cli/src/memory/client.spec.ts b/cli/src/memory/client.spec.ts
index 10d28d5dd..61ecec240 100644
--- a/cli/src/memory/client.spec.ts
+++ b/cli/src/memory/client.spec.ts
@@ -53,6 +53,13 @@ it('captures, learns, recalls, and forgets through the bundled worker across res
const page = await reopened.request('libraryPage', ['owner'])
expect(page.items[0].id).toBe(packet.items[0].id)
await expect(reopened.request('libraryDetail', ['foreign', packet.items[0].id])).rejects.toThrow('scope_denied')
+ const prepared = await reopened.request('prepareRecall', [{ query: 'bug', conditions: { taskType: 'debugging' } },
+ { engine: 'codex', sessionId: 'receiving', projectId: 'project', route: 'prompt_hook' }, { ...access, includeProfile: true }])
+ const rating = await reopened.request('libraryPreview', ['owner', { kind: 'feedback', id: packet.items[0].id,
+ revision: 1, receiptId: prepared.receipt!.id, value: 'helpful', expected: 0 }])
+ await reopened.request('libraryApply', ['owner', rating.command, rating.version, true])
+ expect((await reopened.request('libraryDetail', ['owner', packet.items[0].id]))?.recalls[0].feedback.value).toBe('helpful')
+ expect((await reopened.recall({ query: 'bug', conditions: { taskType: 'debugging' } }, access)).items[0]).not.toHaveProperty('feedback')
const preview = await reopened.request('libraryPreview', ['owner', { kind: 'forget', id: packet.items[0].id, revision: packet.items[0].revision }])
expect((await reopened.request('libraryDetail', ['owner', packet.items[0].id]))?.record.id).toBe(packet.items[0].id)
await reopened.request('libraryApply', ['owner', preview.command, preview.version, true])
diff --git a/cli/src/memory/control.spec.ts b/cli/src/memory/control.spec.ts
index 967dc261b..2fda30490 100644
--- a/cli/src/memory/control.spec.ts
+++ b/cli/src/memory/control.spec.ts
@@ -44,6 +44,19 @@ it('routes bounded project search through the verified current owner', async ()
expect(await request({ action: 'projects', query: { limit: 500 } })).toMatchObject({ error: 'INVALID_INPUT' })
})
+it('requires the same owner capability for per-recall feedback and accepts no agent or rating authority', async () => {
+ const feedback = { kind: 'feedback', id: 'memory', revision: 1, receiptId: 'receipt', value: 'helpful', expected: 0 }
+ expect(await request({ action: 'preview', command: feedback, token: 'agent' })).toMatchObject({ error: 'PERSON_ONLY' })
+ expect(await request({ action: 'preview', command: { ...feedback, confirmed: true } })).toMatchObject({ error: 'INVALID_INPUT' })
+ expect(await request({ action: 'preview', command: { ...feedback, value: 'verified_used' } })).toMatchObject({ error: 'INVALID_INPUT' })
+ verify.mockResolvedValue({ ok: false, error: 'INSIDE_HARNESS', detail: 'agent' })
+ expect(await request({ action: 'preview', command: feedback })).toMatchObject({ error: 'INSIDE_HARNESS' })
+ expect(runtime.libraryPreview).not.toHaveBeenCalled()
+ verify.mockResolvedValue({ ok: true, pid: 300 })
+ expect(await request({ action: 'preview', command: feedback })).toMatchObject({ ok: true })
+ expect(runtime.libraryPreview).toHaveBeenCalledExactlyOnceWith('owner', feedback)
+})
+
it('binds a one-use capability to the exact owner, process, connection and server-held command', async () => {
const prepared = await request({ action: 'preview', command })
expect(prepared).toMatchObject({ ok: true, preview, capability: expect.any(String) })
diff --git a/cli/src/memory/feedback.spec.ts b/cli/src/memory/feedback.spec.ts
new file mode 100644
index 000000000..939276af9
--- /dev/null
+++ b/cli/src/memory/feedback.spec.ts
@@ -0,0 +1,224 @@
+import { mkdtempSync, readFileSync, rmSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, expect, it } from 'vitest'
+import { CodingMemoryStore } from './store.js'
+import { builtinSqlite } from '../lib/sqliteRead.js'
+import type { Database } from './database.js'
+import type { LibraryCommand } from './library.js'
+import type { MemoryDeliveryBinding } from './receipts.js'
+import type { Conditions, MemoryAccess, MemoryDraft, MemoryRecord, SourceEvent } from './types.js'
+
+let directory: string, store: CodingMemoryStore, now: number, record: MemoryRecord
+const access = { profileId: 'owner', projectIds: ['project'], includeProfile: true }
+const binding: MemoryDeliveryBinding = { engine: 'codex', sessionId: 'private_receiver_lemur', projectId: 'project', route: 'prompt_hook' }
+const claim = 'For coding changes, keep reviews small. feedback_claim_iguana'
+const source: SourceEvent = { id: 'statement', profileId: 'owner', projectId: null, engine: 'claude', sessionId: 'source_session',
+ nativeEventId: 'statement', role: 'user', eligibility: 'coding', observedAt: 900, rootIds: ['statement'], text: claim }
+const draft: MemoryDraft = { kind: 'working_preference', facet: 'changes', assertionType: 'stated_preference',
+ scope: { profileId: 'owner' }, claim, rationale: null, futureAction: 'Keep coding reviews small.',
+ applicability: {}, exceptions: [], retrievalCues: ['reviews'], evidenceClass: 'user_stated',
+ evidence: [{ sourceEventId: source.id, quote: claim, paths: ['/claim', '/futureAction', '/applicability', '/validity'] }],
+ conflictKey: 'change_size', validity: { validFrom: null, validUntil: null, recheckWhen: [] } }
+
+beforeEach(() => {
+ directory = mkdtempSync(join(tmpdir(), 'memory-feedback-'))
+ now = 1_000
+ const opened = CodingMemoryStore.open({ directory, profileId: 'owner', now: () => now })
+ if (!opened.ok) throw new Error(opened.reason)
+ store = opened.store
+ store.registerProject('project'); store.registerProject('other_project')
+ store.setControls({ learn: true, recall: true })
+ store.ingest(source)
+ record = store.propose(draft, access).record
+})
+afterEach(() => { store.close(); rmSync(directory, { recursive: true, force: true }) })
+
+function recall(next = binding) {
+ now++
+ return store.prepareRecall({ query: 'small reviews private_prompt_capuchin' }, next,
+ { ...access, projectIds: next.projectId ? [next.projectId] : [] }).receipt!
+}
+function command(receiptId: string, value: 'helpful' | 'unhelpful' | null = 'helpful', expected = 0): Extract<LibraryCommand, { kind: 'feedback' }> {
+ return { kind: 'feedback', id: record.id, revision: record.revision, receiptId, value, expected }
+}
+function apply(value: LibraryCommand) {
+ const preview = store.libraryPreview('owner', value)
+ return store.libraryApply('owner', value, preview.version, false)
+}
+function recalls() { return store.libraryDetail('owner', record.id)!.recalls }
+
+it('shows recent recall per receiving session without retaining prompts or raw receiver identity', () => {
+ const first = recall()
+ const latest = recall({ ...binding, route: 'mcp' })
+ recall({ ...binding, sessionId: 'second_session' })
+ expect(recalls()).toHaveLength(2)
+ expect(recalls()[1]).toMatchObject({ receiptId: latest.id, revision: 1, engine: 'codex',
+ route: 'mcp', delivery: 'unverified', preparedAt: latest.preparedAt, emittedAt: null,
+ feedback: { value: null, version: 0, updatedAt: null }, project: { id: 'project' } })
+ expect(recalls().some(item => item.receiptId === first.id)).toBe(false)
+ const bytes = readFileSync(join(directory, 'memory.sqlite'))
+ expect(bytes.includes(Buffer.from(binding.sessionId))).toBe(false)
+ expect(bytes.includes(Buffer.from('private_prompt_capuchin'))).toBe(false)
+ expect(() => store.libraryDetail('other_owner', record.id)).toThrow('scope_denied')
+})
+
+it('records explicit feedback only after apply and never changes the claim, support or delivery claim', () => {
+ const received = recall()
+ const before = store.support(record.id, access)
+ const preview = store.libraryPreview('owner', command(received.id))
+ expect(preview.effects.feedback).toMatchObject({ value: 'helpful', version: 1 })
+ expect(recalls()[0].feedback.value).toBeNull()
+ store.libraryApply('owner', preview.command, preview.version, false)
+ expect(recalls()[0]).toMatchObject({ feedback: { value: 'helpful', version: 1 }, delivery: 'unverified' })
+ expect(store.read(record.id, access)).toEqual(record)
+ expect(store.support(record.id, access)).toEqual(before)
+ expect(store.recallReceipts(binding, access)[0].delivery).toBe('unverified')
+ const repeated = recall({ ...binding, route: 'manual' })
+ expect(recalls()).toHaveLength(1)
+ expect(recalls()[0]).toMatchObject({ receiptId: repeated.id, feedback: { value: 'helpful', version: 1 } })
+ apply(command(repeated.id, 'unhelpful', 1))
+ expect(recalls()[0].feedback).toMatchObject({ value: 'unhelpful', version: 2 })
+ apply(command(repeated.id, null, 2))
+ expect(recalls()[0].feedback).toMatchObject({ value: null, version: 3 })
+ expect(store.support(record.id, access)).toEqual(before)
+})
+
+it('rejects concurrent feedback changes and ignores no-op feedback without inventing extra votes', () => {
+ const receipt = recall()
+ const earlier = store.libraryPreview('owner', command(receipt.id, 'unhelpful'))
+ apply(command(receipt.id))
+ expect(() => store.libraryApply('owner', earlier.command, earlier.version, false)).toThrow('feedback_changed')
+ apply(command(receipt.id, 'helpful', 1))
+ expect(recalls()[0].feedback.version).toBe(1)
+ expect(() => apply(command(receipt.id, null))).toThrow('feedback_changed')
+})
+
+it('binds feedback to the exact selected memory revision and preserves separate task contexts', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ recall({ ...binding, sessionId: 'other_session' })
+ recall({ ...binding, projectId: 'other_project' })
+ expect(recalls().map(item => item.feedback.value)).toEqual([null, null, 'helpful'])
+ expect(() => apply({ ...command(receipt.id), revision: 2 })).toThrow('revision_conflict')
+ expect(() => apply(command('unknown_receipt'))).toThrow('recall_unavailable')
+ const otherSource = { ...source, id: 'other', nativeEventId: 'other', rootIds: ['other'], text: 'For coding changes, review documentation too.' }
+ store.ingest(otherSource)
+ const unrelated = store.propose({ ...draft, conflictKey: 'documentation', claim: otherSource.text,
+ futureAction: 'Review documentation.', evidence: [{ ...draft.evidence[0], sourceEventId: 'other', quote: otherSource.text }] }, access).record
+ expect(() => apply({ ...command(receipt.id), id: unrelated.id })).toThrow('recall_unavailable')
+})
+
+it('does not transfer a rating across different known conditions or explicit task and branch scopes', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ const variants: Array<{ access: MemoryAccess; conditions: Conditions }> = [
+ { access, conditions: { task: 'debugging', platform: 'mac' } },
+ { access: { ...access, taskId: 'second_task' }, conditions: {} },
+ { access: { ...access, branchId: 'second_branch' }, conditions: {} },
+ ]
+ for (const variant of variants) {
+ now++
+ const prepared = store.prepareRecall({ query: 'reviews', conditions: variant.conditions }, binding, variant.access)
+ expect(prepared.receipt).not.toBeNull()
+ expect(recalls()[0]).toMatchObject({ receiptId: prepared.receipt!.id, feedback: { value: null, version: 0 } })
+ }
+ now++
+ store.prepareRecall({ query: 'reviews', conditions: { platform: 'mac', task: 'debugging' } }, binding, access)
+ expect(recalls()).toHaveLength(4)
+ expect(recalls().filter(item => item.feedback.value === 'helpful')).toHaveLength(1)
+})
+
+it('withholds private receiving projects before the history limit, even for a visible personal memory', () => {
+ const visible = recall({ ...binding, projectId: 'other_project' })
+ for (let index = 0; index < 30; index++) recall({ ...binding, sessionId: `hidden_${index}` })
+ store.setProjectIncluded('project', false)
+ expect(store.libraryDetail('owner', record.id)).not.toBeNull()
+ expect(recalls().map(item => item.receiptId)).toEqual([visible.id])
+})
+
+it('withdraws receiver-session feedback on privacy changes without reviving it on reinclusion', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ const preview = store.libraryPreview('owner', command(receipt.id, 'unhelpful', 1))
+ store.setSessionIncluded(binding.engine, binding.sessionId, false)
+ expect(recalls()).toEqual([])
+ expect(() => store.libraryApply('owner', preview.command, preview.version, false)).toThrow('preview_changed')
+ store.setSessionIncluded(binding.engine, binding.sessionId, true)
+ expect(recalls()).toEqual([])
+ expect(() => apply(command(receipt.id, 'unhelpful', 1))).toThrow('recall_unavailable')
+ recall()
+ expect(recalls()[0].feedback).toEqual({ value: null, version: 0, updatedAt: null })
+ expect(store.read(record.id, access)).toEqual(record)
+})
+
+it('withholds source-private memory and does not transfer feedback to a corrected revision', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ store.setSessionIncluded(source.engine, source.sessionId, false)
+ expect(store.libraryDetail('owner', record.id)).toBeNull()
+ expect(() => apply(command(receipt.id, 'unhelpful', 1))).toThrow('not_found')
+ store.setSessionIncluded(source.engine, source.sessionId, true)
+ const { claim: original, rationale, futureAction, applicability, exceptions, retrievalCues, validity } = record
+ record = store.libraryCorrect('owner', record.id, 1, { claim: `${original} Prefer related groups.`,
+ rationale, futureAction, applicability, exceptions, retrievalCues, validity })
+ expect(recalls()).toEqual([])
+ expect(() => apply(command(receipt.id))).toThrow('recall_unavailable')
+ recall()
+ expect(recalls()[0].feedback.value).toBeNull()
+})
+
+it('expires feedback with its receipt and forgetting leaves no deleted claim text', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ now += 30 * 86_400_000
+ expect(recalls()).toEqual([])
+ expect(() => apply(command(receipt.id, 'unhelpful', 1))).toThrow('recall_unavailable')
+ store.maintain()
+ recall()
+ expect(recalls()[0].feedback.value).toBeNull()
+ store.libraryForget('owner', record.id, record.revision)
+ expect(store.libraryDetail('owner', record.id)).toBeNull()
+ expect(readFileSync(join(directory, 'memory.sqlite')).includes(Buffer.from('feedback_claim_iguana'))).toBe(false)
+})
+
+it('expires an older rating even when a newer recall in that session is still retained', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ now += 29 * 86_400_000
+ const newer = recall()
+ now += 2 * 86_400_000
+ expect(recalls()[0]).toMatchObject({ receiptId: newer.id, feedback: { value: null, version: 0 } })
+ apply(command(newer.id, 'unhelpful'))
+ expect(recalls()[0].feedback).toMatchObject({ value: 'unhelpful', version: 1 })
+})
+
+it('honors session privacy written by an earlier daemon without the new activity cleanup hook', () => {
+ const receipt = recall()
+ apply(command(receipt.id))
+ const Sqlite = builtinSqlite() as unknown as new (path: string) => Database
+ const legacy = new Sqlite(join(directory, 'memory.sqlite'))
+ try {
+ legacy.prepare('INSERT INTO memory_session_policy VALUES(?,?,?,?,?)')
+ .run(binding.engine, binding.sessionId, 0, 1, now)
+ } finally { legacy.close() }
+ expect(recalls()).toEqual([])
+ expect(() => apply(command(receipt.id, 'unhelpful', 1))).toThrow('recall_unavailable')
+})
+
+it('does not invent receiver context when opening pre-feedback receipts', () => {
+ const receipt = recall()
+ store.close()
+ const Sqlite = builtinSqlite() as unknown as new (path: string) => Database
+ const legacy = new Sqlite(join(directory, 'memory.sqlite'))
+ try { legacy.exec('DROP TABLE memory_recall_feedback; DROP TABLE memory_receipt_context;') }
+ finally { legacy.close() }
+ const reopened = CodingMemoryStore.open({ directory, profileId: 'owner', now: () => now })
+ if (!reopened.ok) throw new Error(reopened.reason)
+ store = reopened.store
+ expect(store.recallReceipts(binding, access)[0].id).toBe(receipt.id)
+ expect(recalls()).toEqual([])
+ expect(() => apply(command(receipt.id))).toThrow('recall_unavailable')
+ recall()
+ expect(recalls()).toHaveLength(1)
+})
diff --git a/cli/src/memory/library.ts b/cli/src/memory/library.ts
index dbb7511b8..95a463452 100644
--- a/cli/src/memory/library.ts
+++ b/cli/src/memory/library.ts
@@ -1,6 +1,7 @@
/** Owner-facing library contracts. These are not model tools or scope capabilities. */
import { z } from 'zod'
import { conditionsSchema, draftSchema, type MemoryRecord, type MemoryScope, type MemorySupport, type SourceEvent } from './types.js'
+import type { MemoryRecallUse, RecallFeedback } from './receipts.js'
const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)
export const libraryQuerySchema = z.object({
@@ -34,6 +35,7 @@ export interface LibraryDetail {
sources: Array<Pick<SourceEvent, 'id' | 'engine' | 'sessionId' | 'role' | 'observedAt'>>
scopeChanges: ScopeChange[]
project: LibraryProject | null
+ recalls: Array<Omit<MemoryRecallUse, 'projectId'> & { project: LibraryProject | null; canFeedback: boolean }>
}
export interface ScopeChange { revision: number; from: MemoryScope; to: MemoryScope; changedAt: number; actor: 'owner' }
@@ -57,6 +59,8 @@ export const libraryCommandSchema = z.discriminatedUnion('kind', [
supersede: z.array(z.object({ id, revision }).strict()).max(32).optional() }).strict(),
z.object({ kind: z.literal('forget'), id, revision }).strict(),
z.object({ kind: z.literal('narrow'), id, revision, projectId: id }).strict(),
+ z.object({ kind: z.literal('feedback'), id, revision, receiptId: id,
+ value: z.enum(['helpful', 'unhelpful']).nullable(), expected: z.number().int().nonnegative().safe() }).strict(),
z.object({ kind: z.literal('configure'), preferences, expected: preferences }).strict(),
])
export type LibraryCommand = z.infer<typeof libraryCommandSchema>
@@ -73,6 +77,7 @@ export interface LibraryPreview {
scopeChange?: ScopeChange
project?: LibraryProject
conflicts?: MemorySummary[]
+ feedback?: RecallFeedback
}
}
diff --git a/cli/src/memory/receipts.ts b/cli/src/memory/receipts.ts
index 23ab1ff7e..2e78f4f07 100644
--- a/cli/src/memory/receipts.ts
+++ b/cli/src/memory/receipts.ts
@@ -4,7 +4,7 @@ import { z } from 'zod'
import { digest } from './admission.js'
import type { Database } from './database.js'
import { visibleEvidenceSql } from './visibility.js'
-import { parse, type MemoryAccess, type MemoryRecord, type RecallPacket, type RecallRequest } from './types.js'
+import { MemoryError, parse, type MemoryAccess, type MemoryRecord, type RecallPacket, type RecallRequest } from './types.js'
const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)
const bindingSchema = z.object({ engine: z.enum(['claude', 'codex']), sessionId: id, projectId: id.nullable(),
@@ -25,6 +25,14 @@ export interface RecallReceipt {
items: Array<{ id: string; revision: number; current: boolean }>
}
export interface PreparedRecall { packet: RecallPacket; receipt: RecallReceipt | null }
+export type RecallFeedbackValue = 'helpful' | 'unhelpful' | null
+export interface RecallFeedback { value: RecallFeedbackValue; version: number; updatedAt: number | null }
+/** Owner-only context. It must never be included in an agent recall packet or receipt. */
+export interface MemoryRecallUse {
+ receiptId: string; revision: number; engine: MemoryDeliveryBinding['engine']; projectId: string | null
+ route: MemoryDeliveryBinding['route']; preparedAt: number; emittedAt: number | null; delivery: 'unverified'
+ feedback: RecallFeedback
+}
interface Deps {
db: Database; profileId: string; now(): number
transaction<T>(run: () => T): T
@@ -47,6 +55,18 @@ export const RECEIPT_SCHEMA = `
memory_id TEXT NOT NULL, revision INTEGER NOT NULL, PRIMARY KEY(receipt_id,memory_id)
);
CREATE INDEX IF NOT EXISTS memory_receipt_revisions ON memory_receipt_items(memory_id,revision);
+ CREATE TABLE IF NOT EXISTS memory_receipt_context (
+ receipt_id TEXT PRIMARY KEY REFERENCES memory_receipts(id) ON DELETE CASCADE,
+ context_key TEXT NOT NULL, session_key TEXT NOT NULL, engine TEXT NOT NULL, project_id TEXT
+ );
+ CREATE INDEX IF NOT EXISTS memory_receipt_session ON memory_receipt_context(session_key);
+ CREATE TABLE IF NOT EXISTS memory_recall_feedback (
+ memory_id TEXT NOT NULL REFERENCES memories(id) ON DELETE CASCADE, revision INTEGER NOT NULL,
+ context_key TEXT NOT NULL, receipt_id TEXT NOT NULL REFERENCES memory_receipt_context(receipt_id) ON DELETE CASCADE,
+ value TEXT CHECK(value IN ('helpful','unhelpful')), version INTEGER NOT NULL, updated_at INTEGER NOT NULL,
+ PRIMARY KEY(memory_id,revision,context_key)
+ );
+ CREATE INDEX IF NOT EXISTS memory_feedback_receipt ON memory_recall_feedback(receipt_id);
`
export class MemoryReceipts {
@@ -82,6 +102,12 @@ export class MemoryReceipts {
queryDigest, contextDigest, packetDigest, bytes, packet.estimatedTokens)
for (const item of packet.items) this.deps.db.prepare('INSERT INTO memory_receipt_items VALUES(?,?,?)')
.run(receiptId, item.id, item.revision)
+ // A one-way session key lets privacy changes remove owner-visible activity without storing
+ // another copy of native session identity. Route-independent context prevents duplicate votes.
+ this.deps.db.prepare('INSERT INTO memory_receipt_context VALUES(?,?,?,?,?)').run(receiptId,
+ digest([this.deps.profileId, binding.engine, binding.sessionId, binding.projectId,
+ access.taskId ?? null, access.branchId ?? null, request.conditions ?? {}]),
+ this.sessionKey(binding.engine, binding.sessionId), binding.engine, binding.projectId)
this.prune()
return { packet, receipt: { id: receiptId, route: binding.route, preparedAt, emittedAt: null, delivery: 'unverified',
queryDigest, contextDigest, packetDigest, bytes, estimatedTokens: packet.estimatedTokens,
@@ -121,6 +147,59 @@ export class MemoryReceipts {
}))
}
+ /** The caller has already verified the owner and current memory's source visibility. */
+ forMemory(memoryId: string, revision: number): MemoryRecallUse[] {
+ // Receiver privacy applies before deduplication and the limit. Old receipts with no recorded
+ // receiver context stay unavailable; migration must not guess their authority from a hash.
+ return this.deps.transaction(() => this.deps.db.prepare(`WITH recent AS (
+ SELECT r.id,r.route,r.prepared_at,r.emitted_at,c.context_key,c.engine,c.project_id,
+ ROW_NUMBER() OVER (PARTITION BY c.context_key ORDER BY r.prepared_at DESC,r.rowid DESC) AS position
+ FROM memory_receipts r JOIN memory_receipt_context c ON c.receipt_id=r.id
+ JOIN memory_receipt_items i ON i.receipt_id=r.id
+ WHERE i.memory_id=? AND i.revision=? AND r.prepared_at>?
+ AND c.session_key NOT IN (SELECT value FROM json_each(?))
+ AND (c.project_id IS NULL OR EXISTS (SELECT 1 FROM projects p WHERE p.id=c.project_id AND p.included=1)))
+ SELECT r.*,f.value,f.version,f.updated_at FROM recent r LEFT JOIN memory_recall_feedback f
+ ON f.memory_id=? AND f.revision=? AND f.context_key=r.context_key
+ AND EXISTS (SELECT 1 FROM memory_receipts rated WHERE rated.id=f.receipt_id AND rated.prepared_at>?)
+ WHERE r.position=1 ORDER BY r.prepared_at DESC,r.id DESC LIMIT 10`)
+ .all(memoryId, revision, this.deps.now() - RETENTION_MS, this.privateSessionKeys(),
+ memoryId, revision, this.deps.now() - RETENTION_MS).map(row => ({
+ receiptId: String(row.id), revision, engine: row.engine as MemoryDeliveryBinding['engine'],
+ projectId: row.project_id === null ? null : String(row.project_id), route: row.route as MemoryDeliveryBinding['route'],
+ preparedAt: Number(row.prepared_at), emittedAt: row.emitted_at === null ? null : Number(row.emitted_at),
+ delivery: 'unverified', feedback: feedbackFrom(row),
+ })))
+ }
+
+ /** Called only by the owner preview/apply path. A rating is neither truth support nor delivery proof. */
+ feedback(memoryId: string, revision: number, receiptId: string, value: RecallFeedbackValue, expected: number): RecallFeedback {
+ const context = this.deps.db.prepare(`SELECT c.context_key FROM memory_receipt_context c
+ JOIN memory_receipts r ON r.id=c.receipt_id JOIN memory_receipt_items i ON i.receipt_id=r.id
+ WHERE r.id=? AND i.memory_id=? AND i.revision=? AND r.prepared_at>?
+ AND c.session_key NOT IN (SELECT value FROM json_each(?))
+ AND (c.project_id IS NULL OR EXISTS (SELECT 1 FROM projects p WHERE p.id=c.project_id AND p.included=1))`)
+ .get(receiptId, memoryId, revision, this.deps.now() - RETENTION_MS, this.privateSessionKeys())
+ if (!context) throw new MemoryError('recall_unavailable')
+ const previous = feedbackFrom(this.deps.db.prepare(`SELECT f.value,f.version,f.updated_at FROM memory_recall_feedback f
+ JOIN memory_receipts r ON r.id=f.receipt_id
+ WHERE f.memory_id=? AND f.revision=? AND f.context_key=? AND r.prepared_at>?`)
+ .get(memoryId, revision, context.context_key, this.deps.now() - RETENTION_MS))
+ if (previous.version !== expected) throw new MemoryError('feedback_changed')
+ if (previous.value === value) return previous
+ const next = { value, version: previous.version + 1, updatedAt: this.deps.now() }
+ this.deps.db.prepare(`INSERT INTO memory_recall_feedback(memory_id,revision,context_key,receipt_id,value,version,updated_at)
+ VALUES(?,?,?,?,?,?,?) ON CONFLICT(memory_id,revision,context_key) DO UPDATE SET
+ receipt_id=excluded.receipt_id,value=excluded.value,version=excluded.version,updated_at=excluded.updated_at`)
+ .run(memoryId, revision, context.context_key, receiptId, value, next.version, next.updatedAt)
+ return next
+ }
+
+ /** Keep opaque withdrawal receipts, but remove receiver activity and its feedback permanently. */
+ withholdSession(engine: string, sessionId: string): void {
+ this.deps.db.prepare('DELETE FROM memory_receipt_context WHERE session_key=?').run(this.sessionKey(engine, sessionId))
+ }
+
prune(): void {
this.deps.db.prepare('DELETE FROM memory_receipts WHERE prepared_at<=?').run(this.deps.now() - RETENTION_MS)
this.deps.db.prepare(`DELETE FROM memory_receipts WHERE id IN
@@ -142,6 +221,18 @@ export class MemoryReceipts {
}
private key(binding: MemoryDeliveryBinding): string { return digest([this.deps.profileId, binding]) }
+ private sessionKey(engine: string, sessionId: string): string { return digest([this.deps.profileId, engine, sessionId]) }
+ private privateSessionKeys(): string {
+ // Read the original policy, including changes made by an earlier daemon version that does
+ // not know about receipt context. This check and the activity read share a SQLite snapshot.
+ return JSON.stringify(this.deps.db.prepare('SELECT engine,session_id FROM memory_session_policy WHERE included=0').all()
+ .map(row => this.sessionKey(String(row.engine), String(row.session_id))))
+ }
+}
+
+function feedbackFrom(row?: Record<string, unknown>): RecallFeedback {
+ return { value: (row?.value ?? null) as RecallFeedbackValue, version: Number(row?.version ?? 0),
+ updatedAt: row?.updated_at == null ? null : Number(row.updated_at) }
}
function empty(status: RecallPacket['status']): RecallPacket { return { status, items: [], text: '', estimatedTokens: 0 } }
diff --git a/cli/src/memory/store.ts b/cli/src/memory/store.ts
index 7222e4abe..623f7f9fe 100644
--- a/cli/src/memory/store.ts
+++ b/cli/src/memory/store.ts
@@ -299,6 +299,7 @@ export class CodingMemoryStore {
last_error='session_privacy_changed', updated_at=? WHERE stream_id IN
(SELECT id FROM memory_streams WHERE engine=? AND session_id=?) AND state NOT IN ${TERMINAL_JOB_STATES}`)
.run(this.now(), engine, sessionId)
+ if (!included) this.receipts.withholdSession(engine, sessionId)
// Derived input can belong to a different stream while retaining this session's source roots.
if (!included) this.cancelHiddenSources()
else this.reconcileVisibleConflicts()
@@ -569,7 +570,9 @@ export class CodingMemoryStore {
ORDER BY revision DESC LIMIT 20`).all(id).map(row => ({ revision: Number(row.revision),
from: JSON.parse(String(row.from_scope)), to: JSON.parse(String(row.to_scope)), changedAt: Number(row.changed_at), actor: 'owner' }))
return { record, sources, support: this.support(id, access), scopeChanges,
- project: record.scope.projectId ? this.projectLabel(record.scope.projectId) : null }
+ project: record.scope.projectId ? this.projectLabel(record.scope.projectId) : null,
+ recalls: this.receipts.forMemory(record.id, record.revision).map(({ projectId, ...recall }) => ({ ...recall,
+ project: projectId ? this.projectLabel(projectId) : null, canFeedback: record.state === 'active' && this.current(record) })) }
}
libraryProjects(owner: string, input: LibraryProjectQuery = {}): LibraryProjects {
@@ -677,6 +680,13 @@ export class CodingMemoryStore {
case 'correct': return { record: summarize(this.libraryCorrect(owner, command.id, command.revision, command.fields, command.supersede)) }
case 'forget': return this.libraryForget(owner, command.id, command.revision)
case 'narrow': return this.libraryNarrow(owner, command.id, command.revision, command.projectId)
+ case 'feedback': {
+ const access = this.ownerRecordAccess(command.id)
+ if (!access) throw new MemoryError('not_found')
+ const record = this.requireRecord(command.id, command.revision, access)
+ if (record.state !== 'active' || !this.current(record)) throw new MemoryError('recall_unavailable')
+ return { feedback: this.receipts.feedback(record.id, record.revision, command.receiptId, command.value, command.expected) }
+ }
case 'configure': return { preferences: this.changePreferences(command.preferences, command.expected, enabled) }
}
}
diff --git a/desktop/lib/companions/coding_memory_connection.dart b/desktop/lib/companions/coding_memory_connection.dart
index 8e66dc48a..232742b79 100644
--- a/desktop/lib/companions/coding_memory_connection.dart
+++ b/desktop/lib/companions/coding_memory_connection.dart
@@ -133,6 +133,8 @@ String codingMemoryError(Object error) => switch (error) {
CodingMemoryFailure(code: 'PREVIEW_REQUIRED' || 'CONNECTION_CHANGED') => 'This preview expired or the connection changed. Review it again before applying.',
CodingMemoryFailure(code: 'NOT_FOUND') =>
'This memory was removed or is no longer available.',
+ CodingMemoryFailure(code: 'FEEDBACK_CHANGED') => 'Your feedback changed elsewhere. Refresh recent recall before changing it again.',
+ CodingMemoryFailure(code: 'RECALL_UNAVAILABLE') => 'That recall is no longer available. Refresh recent recall to see the current history.',
CodingMemoryFailure(code: 'PROJECT_UNAVAILABLE') =>
'That project is no longer available for memory. Choose another project.',
CodingMemoryFailure(code: 'SCOPE_NARROWING_ONLY' || 'MEMORY_NOT_ACTIVE') => 'This memory can no longer be limited this way. Go back and refresh its details.',
diff --git a/desktop/lib/companions/coding_memory_library.dart b/desktop/lib/companions/coding_memory_library.dart
index 887cc3677..d6c93ff04 100644
--- a/desktop/lib/companions/coding_memory_library.dart
+++ b/desktop/lib/companions/coding_memory_library.dart
@@ -120,6 +120,9 @@ class CodingMemoryLibrary extends ChangeNotifier {
}
preview.used = true;
await _request({'action': 'apply', 'capability': preview.capability});
+ // A session rating does not change memory content. Keep the open detail and
+ // its controls mounted while the caller refreshes the saved feedback.
+ if (memoryMap(preview.data['command'])['kind'] == 'feedback') return;
// Drop old content before refreshing. A failed refresh must not resurrect it.
items = [];
nextCursor = null;
diff --git a/desktop/lib/companions/coding_memory_recall_history.dart b/desktop/lib/companions/coding_memory_recall_history.dart
new file mode 100644
index 000000000..402ee5f62
--- /dev/null
+++ b/desktop/lib/companions/coding_memory_recall_history.dart
@@ -0,0 +1,202 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart';
+import '../shared/theme/app_icons.dart';
+import '../widgets/desktop_chrome.dart';
+import 'coding_memory_library.dart';
+
+/// Feedback belongs to this version in one receiving session, not to its truth.
+class CodingMemoryRecallHistory extends StatefulWidget {
+ const CodingMemoryRecallHistory({
+ super.key,
+ required this.recalls,
+ required this.busy,
+ required this.onFeedback,
+ required this.onRefresh,
+ });
+ final List<Map<String, dynamic>> recalls;
+ final bool busy;
+ final Future<void> Function(Map<String, dynamic> recall, String? value)
+ onFeedback;
+ final VoidCallback onRefresh;
+
+ @override
+ State<CodingMemoryRecallHistory> createState() =>
+ _CodingMemoryRecallHistoryState();
+}
+
+class _CodingMemoryRecallHistoryState extends State<CodingMemoryRecallHistory> {
+ bool expanded = false;
+ final _focus = <String, FocusNode>{};
+
+ FocusNode _node(Map<String, dynamic> recall, String choice) =>
+ _focus.putIfAbsent('${recall['receiptId']}:$choice', () => FocusNode());
+
+ Future<void> _rate(Map<String, dynamic> recall, String? value) async {
+ await widget.onFeedback(recall, value);
+ if (!mounted) return;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted &&
+ widget.recalls.any((r) => r['receiptId'] == recall['receiptId'])) {
+ _node(recall, value ?? 'helpful').requestFocus();
+ }
+ });
+ }
+
+ @override
+ void didUpdateWidget(CodingMemoryRecallHistory oldWidget) {
+ super.didUpdateWidget(oldWidget);
+ final current = widget.recalls.map((r) => '${r['receiptId']}:').toSet();
+ for (final key in _focus.keys.toList()) {
+ if (!current.any(key.startsWith)) _focus.remove(key)!.dispose();
+ }
+ }
+
+ @override
+ void dispose() {
+ for (final node in _focus.values) {
+ node.dispose();
+ }
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) => Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ 'Recent recall',
+ style: AppType.heading(color: AppPalette.textPrimary),
+ ),
+ const SizedBox(height: 8),
+ Text(
+ widget.recalls.isEmpty
+ ? 'No recent recall history is available for this version.'
+ : 'Was this useful in that session? Your feedback stays with this version. Correct the memory separately if the fact is wrong.',
+ style: AppType.caption(color: AppPalette.textSecondary, height: 1.5),
+ ),
+ for (final recall in widget.recalls.take(expanded ? 10 : 3))
+ _recall(context, recall),
+ Wrap(
+ spacing: 8,
+ runSpacing: 4,
+ children: [
+ if (widget.recalls.length > 3)
+ TextButton(
+ onPressed: widget.busy
+ ? null
+ : () => setState(() => expanded = !expanded),
+ child: Text(expanded ? 'Show fewer' : 'Show all recent recalls'),
+ ),
+ TextButton(
+ onPressed: widget.busy ? null : widget.onRefresh,
+ child: const Text('Refresh recent recall'),
+ ),
+ ],
+ ),
+ if (widget.recalls.isNotEmpty)
+ Text(
+ 'Up to 10 recent recalls from the last 30 days. Repeats in the same session and task context share one rating.',
+ style: AppType.caption(color: AppPalette.textSecondary, height: 1.5),
+ ),
+ ],
+ );
+
+ Widget _recall(BuildContext context, Map<String, dynamic> recall) {
+ final feedback = memoryMap(recall['feedback']);
+ final value = feedback['value'];
+ final project = memoryMap(recall['project']);
+ final engine = recall['engine'] == 'claude' ? 'Claude' : 'Codex';
+ final where = project['name'] as String? ?? 'Companion conversation';
+ final millis = recall['preparedAt'];
+ final date = millis is num
+ ? DateTime.fromMillisecondsSinceEpoch(millis.toInt()).toLocal()
+ : null;
+ final local = MaterialLocalizations.of(context);
+ final when = date == null
+ ? 'Date unavailable'
+ : '${local.formatMediumDate(date)} at ${local.formatTimeOfDay(TimeOfDay.fromDateTime(date), alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context))}';
+ final description = '$engine · $where · $when';
+ final enabled = !widget.busy && recall['canFeedback'] == true;
+ return Padding(
+ key: ValueKey(recall['receiptId']),
+ padding: const EdgeInsets.only(top: 16, bottom: 8),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ Text(
+ '$engine · $where',
+ style: AppType.body(
+ color: AppPalette.textPrimary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ Text(
+ when,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.5,
+ ),
+ ),
+ if (project['location'] is String)
+ Text(
+ project['location'] as String,
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.5,
+ ),
+ ),
+ Text(
+ recall['emittedAt'] == null
+ ? 'Selected for recall · Delivery not confirmed'
+ : 'Sent by Harness · Delivery not confirmed',
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.5,
+ ),
+ ),
+ const SizedBox(height: 8),
+ Wrap(
+ spacing: 8,
+ runSpacing: 8,
+ children: [
+ for (final choice in ['helpful', 'unhelpful'])
+ DesktopPill(
+ label: choice == 'helpful' ? 'Helpful' : 'Not helpful',
+ semanticLabel:
+ '${choice == 'helpful' ? 'Helpful' : 'Not helpful'} for $description',
+ selected: value == choice,
+ focusNode: _node(recall, choice),
+ leading: SizedBox(
+ width: 16,
+ child: value == choice
+ ? const Icon(AppIcons.check, size: 16)
+ : null,
+ ),
+ onPressed: enabled
+ ? () async {
+ if (value != choice) await _rate(recall, choice);
+ }
+ : null,
+ ),
+ if (value != null)
+ TextButton(
+ focusNode: _node(recall, 'clear'),
+ onPressed: enabled ? () => _rate(recall, null) : null,
+ child: const Text('Clear feedback'),
+ ),
+ ],
+ ),
+ if (!widget.busy && recall['canFeedback'] != true)
+ Text(
+ 'Feedback is unavailable for this memory’s current state.',
+ style: AppType.caption(
+ color: AppPalette.textSecondary,
+ height: 1.5,
+ ),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/companions/coding_memory_view.dart b/desktop/lib/companions/coding_memory_view.dart
index 7577aa4e1..c63d02d61 100644
--- a/desktop/lib/companions/coding_memory_view.dart
+++ b/desktop/lib/companions/coding_memory_view.dart
@@ -10,6 +10,7 @@ import '../widgets/desktop_prompt_surface.dart';
import 'coding_memory_connection.dart';
import 'coding_memory_library.dart';
import 'coding_memory_project_picker.dart';
+import 'coding_memory_recall_history.dart';
/// The collection's owner library; it does not send chat or terminal input.
class CodingMemoryView extends StatefulWidget {
@@ -547,6 +548,26 @@ class _MemoryDialogState extends State<_MemoryDialog> {
Navigator.of(context).pop();
}
});
+ Future<void> _feedback(Map<String, dynamic> recall, String? value) =>
+ _run(() async {
+ final snapshot = library.changes;
+ final id = record['id'];
+ final prepared = await library.preview({
+ 'kind': 'feedback',
+ 'id': id,
+ 'revision': record['revision'],
+ 'receiptId': recall['receiptId'],
+ 'value': value,
+ 'expected': memoryMap(recall['feedback'])['version'],
+ });
+ if (!mounted || !library.valid || snapshot != library.changes) return;
+ // The explicit rating click is the user action. Spend the bound
+ // capability once; do not retry writes after an uncertain response.
+ await library.apply(prepared);
+ final result = await library.detail(id as String);
+ if (!mounted || !library.valid || snapshot != library.changes) return;
+ detail = result;
+ });
void _close() {
if (!busy) Navigator.of(context).pop();
}
@@ -747,6 +768,15 @@ class _MemoryDialogState extends State<_MemoryDialog> {
'You limited where this memory applies on ${_date(context, memoryMap((detail!['scopeChanges'] as List).first)['changedAt'])}. Its evidence is unchanged.',
small: true,
),
+ if (detail!['recalls'] is List) ...[
+ const SizedBox(height: 20),
+ CodingMemoryRecallHistory(
+ recalls: (detail!['recalls'] as List).map(memoryMap).toList(),
+ busy: busy,
+ onFeedback: _feedback,
+ onRefresh: () => unawaited(_load()),
+ ),
+ ],
const SizedBox(height: 20),
Text(
'Retained evidence',
diff --git a/desktop/test/coding_memory_view_test.dart b/desktop/test/coding_memory_view_test.dart
index b1d9b91ed..50b45cffd 100644
--- a/desktop/test/coding_memory_view_test.dart
+++ b/desktop/test/coding_memory_view_test.dart
@@ -7,7 +7,9 @@ import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness/companions/coding_memory_library.dart';
+import 'package:harness/companions/coding_memory_connection.dart';
import 'package:harness/companions/coding_memory_view.dart';
+import 'package:harness/widgets/desktop_chrome.dart';
import 'package:harness/shared/theme/app_theme.dart';
import 'package:harness/shared/theme/color_palette.dart';
@@ -103,6 +105,193 @@ void main() {
});
}
+ testWidgets(
+ 'feedback rates the exact recall, preserves the open detail and can be changed or cleared',
+ (tester) async {
+ transport.recalls.add(syntheticRecall());
+ await mount(tester);
+ await tap(tester, 'Read memory');
+ expect(find.textContaining('Delivery not confirmed'), findsOneWidget);
+ expect(transport.calls.where((c) => c['action'] == 'apply'), isEmpty);
+ final revision = transport.record['revision'];
+ final evidence = transport.record['evidence'];
+ final changes = library.changes;
+ await tap(tester, 'Helpful');
+ expect(transport.previewed, {
+ 'kind': 'feedback',
+ 'id': 'synthetic-memory',
+ 'revision': 1,
+ 'receiptId': 'synthetic-receipt',
+ 'value': 'helpful',
+ 'expected': 0,
+ });
+ expect(find.text('Your coding memory'), findsNWidgets(2));
+ expect(find.text('Clear feedback'), findsOneWidget);
+ expect(find.textContaining('Delivery not confirmed'), findsOneWidget);
+ final helpful = tester.widget<DesktopPill>(
+ find.widgetWithText(DesktopPill, 'Helpful'),
+ );
+ expect(helpful.selected, isTrue);
+ expect(helpful.focusNode!.hasFocus, isTrue);
+ expect(library.changes, changes);
+ await tap(tester, 'Not helpful');
+ expect(transport.previewed!['expected'], 1);
+ expect(transport.recalls.single['feedback']['value'], 'unhelpful');
+ await tap(tester, 'Clear feedback');
+ expect(transport.previewed!['expected'], 2);
+ expect(transport.recalls.single['feedback']['value'], isNull);
+ expect(find.text('Clear feedback'), findsNothing);
+ expect(transport.record['revision'], revision);
+ expect(transport.record['evidence'], evidence);
+ expect(library.items, hasLength(1));
+ },
+ );
+
+ testWidgets(
+ 'pending feedback disables controls and a changed owner prevents apply',
+ (tester) async {
+ transport.recalls.add(syntheticRecall());
+ await mount(tester);
+ await tap(tester, 'Read memory');
+ final pending = Completer<Map<String, dynamic>>();
+ transport.handle = (p) async =>
+ p['action'] == 'preview' ? pending.future : transport.respond(p);
+ await tester.ensureVisible(find.text('Helpful'));
+ await tester.tap(find.text('Helpful'));
+ await tester.pump();
+ expect(
+ tester
+ .widget<DesktopPill>(
+ find.widgetWithText(DesktopPill, 'Not helpful'),
+ )
+ .onPressed,
+ isNull,
+ );
+ expect(
+ tester
+ .widget<TextButton>(find.widgetWithText(TextButton, 'Close'))
+ .onPressed,
+ isNull,
+ );
+ transport.invalidate();
+ pending.complete({
+ 'ok': true,
+ 'capability': 'a' * 32,
+ 'expiresInMs': 120000,
+ 'preview': {},
+ });
+ await tester.pumpAndSettle();
+ expect(find.textContaining('Delivery not confirmed'), findsNothing);
+ expect(find.text('Helpful'), findsNothing);
+ expect(transport.calls.where((c) => c['action'] == 'apply'), isEmpty);
+ },
+ );
+
+ testWidgets(
+ 'a lost save reply is checked by refreshing without retrying the rating',
+ (tester) async {
+ transport.recalls.add(syntheticRecall());
+ await mount(tester);
+ await tap(tester, 'Read memory');
+ transport.handle = (p) async {
+ final result = transport.respond(p);
+ if (p['action'] == 'apply') throw const CodingMemoryFailure('TIMEOUT');
+ return result;
+ };
+ await tap(tester, 'Helpful');
+ expect(
+ find.textContaining('refresh to check whether it finished'),
+ findsOneWidget,
+ );
+ expect(
+ transport.calls.where((c) => c['action'] == 'apply'),
+ hasLength(1),
+ );
+ transport.handle = null;
+ await tap(tester, 'Refresh recent recall');
+ expect(
+ tester
+ .widget<DesktopPill>(find.widgetWithText(DesktopPill, 'Helpful'))
+ .selected,
+ isTrue,
+ );
+ expect(
+ transport.calls.where((c) => c['action'] == 'apply'),
+ hasLength(1),
+ );
+ },
+ );
+
+ testWidgets(
+ 'stale feedback is refreshed explicitly and a reconnect during preview cannot apply',
+ (tester) async {
+ transport.recalls.add(syntheticRecall());
+ await mount(tester);
+ await tap(tester, 'Read memory');
+ transport.refuseApply = 'FEEDBACK_CHANGED';
+ await tap(tester, 'Helpful');
+ expect(find.textContaining('feedback changed elsewhere'), findsOneWidget);
+ transport.refuseApply = null;
+ transport.recalls.single['feedback'] = {
+ 'value': 'unhelpful',
+ 'version': 5,
+ 'updatedAt': 1790762402000,
+ };
+ await tap(tester, 'Refresh recent recall');
+ expect(
+ tester
+ .widget<DesktopPill>(
+ find.widgetWithText(DesktopPill, 'Not helpful'),
+ )
+ .selected,
+ isTrue,
+ );
+ final count = transport.calls.where((c) => c['action'] == 'apply').length;
+ transport.handle = (p) async {
+ final result = transport.respond(p);
+ if (p['action'] == 'preview') transport.reconnect();
+ return result;
+ };
+ await tap(tester, 'Helpful');
+ expect(find.textContaining('connection changed'), findsOneWidget);
+ expect(
+ transport.calls.where((c) => c['action'] == 'apply'),
+ hasLength(count),
+ );
+ },
+ );
+
+ for (final brightness in Brightness.values) {
+ for (final scale in [1.0, 2.0]) {
+ testWidgets(
+ 'recall feedback wraps long projects in ${brightness.name} at $scale text',
+ (tester) async {
+ transport.recalls.add({
+ ...syntheticRecall(value: 'helpful'),
+ 'project': {
+ 'name': 'Editor accessibility and collaboration research',
+ 'location': '/synthetic/workspaces/very-long-project-directory/desktop-editor',
+ },
+ });
+ await mount(
+ tester,
+ brightness: brightness,
+ scale: scale,
+ size: const Size(620, 850),
+ );
+ await tap(tester, 'Read memory');
+ await tester.ensureVisible(find.text('Recent recall'));
+ await tester.pumpAndSettle();
+ expect(tester.takeException(), isNull);
+ await capture(tester, 'feedback-${brightness.name}-${scale}x');
+ await tap(tester, 'Not helpful');
+ expect(transport.recalls.single['feedback']['value'], 'unhelpful');
+ expect(tester.takeException(), isNull);
+ },
+ );
+ }
+ }
+
testWidgets(
'detail exposes retained evidence; forgetting requires a concrete preview and defaults to cancel',
(tester) async {
diff --git a/desktop/test/support/coding_memory_fixture.dart b/desktop/test/support/coding_memory_fixture.dart
index 291b1f129..f8899010f 100644
--- a/desktop/test/support/coding_memory_fixture.dart
+++ b/desktop/test/support/coding_memory_fixture.dart
@@ -3,6 +3,30 @@ import 'dart:convert';
import 'package:harness/companions/coding_memory_connection.dart';
+Map<String, dynamic> syntheticRecall({
+ String id = 'synthetic-receipt',
+ String? value,
+}) => {
+ 'receiptId': id,
+ 'revision': 1,
+ 'engine': 'codex',
+ 'route': 'prompt_hook',
+ 'delivery': 'unverified',
+ 'preparedAt': 1790762400000,
+ 'emittedAt': 1790762401000,
+ 'canFeedback': true,
+ 'project': {
+ 'id': 'synthetic-project',
+ 'name': 'editor',
+ 'location': '/synthetic/work/editor',
+ },
+ 'feedback': {
+ 'value': value,
+ 'version': value == null ? 0 : 1,
+ 'updatedAt': value == null ? null : 1790762402000,
+ },
+};
+
Map<String, dynamic> syntheticMemory({
int revision = 1,
String? claim,
@@ -62,6 +86,7 @@ class MemoryFixture extends CodingMemoryConnection {
},
];
final scopeChanges = <Map<String, dynamic>>[];
+ final recalls = <Map<String, dynamic>>[];
Map<String, dynamic>? get project => projects
.where((p) => p['id'] == (record['scope'] as Map)['projectId'])
@@ -72,8 +97,13 @@ class MemoryFixture extends CodingMemoryConnection {
calls.add(
Map<String, dynamic>.from(jsonDecode(jsonEncode(payload)) as Map),
);
- if (handle != null) return handle!(payload);
- return respond(payload);
+ // Match the real connection's refusal of replies from an obsolete owner or
+ // connection. The production transport captures this after initial connect.
+ final start = epoch;
+ final result = handle != null ? await handle!(payload) : respond(payload);
+ if (!valid) throw const CodingMemoryFailure('OWNER_CHANGED');
+ if (start != epoch) throw const CodingMemoryFailure('CONNECTION_CHANGED');
+ return result;
}
Map<String, dynamic> respond(Map<String, dynamic> payload) {
@@ -107,6 +137,7 @@ class MemoryFixture extends CodingMemoryConnection {
'support': null,
'project': project,
'scopeChanges': scopeChanges,
+ 'recalls': recalls,
'sources': [
{
'id': 'source-fixture',
@@ -166,6 +197,14 @@ class MemoryFixture extends CodingMemoryConnection {
(p) => p['id'] == previewed!['projectId'],
),
}
+ : previewed!['kind'] == 'feedback'
+ ? {
+ 'feedback': {
+ 'value': previewed!['value'],
+ 'version': (previewed!['expected'] as int) + 1,
+ 'updatedAt': 1790762600000,
+ },
+ }
: {
'record': {...record, ...previewed!['fields'] as Map},
},
@@ -193,6 +232,15 @@ class MemoryFixture extends CodingMemoryConnection {
'changedAt': 1790762400000,
'actor': 'owner',
});
+ } else if (previewed!['kind'] == 'feedback') {
+ final recall = recalls.singleWhere(
+ (r) => r['receiptId'] == previewed!['receiptId'],
+ );
+ recall['feedback'] = {
+ 'value': previewed!['value'],
+ 'version': (previewed!['expected'] as int) + 1,
+ 'updatedAt': 1790762600000,
+ };
} else {
record = {
...record,
diff --git a/docs/plans/2026-09-30-coding-memory-product.md b/docs/plans/2026-09-30-coding-memory-product.md
index 6a1cc5fea..9736f691d 100644
--- a/docs/plans/2026-09-30-coding-memory-product.md
+++ b/docs/plans/2026-09-30-coding-memory-product.md
@@ -4,6 +4,8 @@ Build memory that helps any supported coding agent work like a colleague who und
This document defines the coding-specific product model. The [architecture](2026-09-30-tim-memory.md) defines storage, learning, recall, adapters, and controls. The examples below are illustrative, not a profile inferred about the current user. A development-gated runtime prototype now exists; the [review log](2026-09-30-coding-memory-review-log.md) tracks what has been implemented and tested. An initial owner library is integrated into the companion viewer; native production integration, richer project/receipt views and behavioral evaluation remain incomplete.
+The owner library now connects a memory to its recent recall history and accepts helpful/unhelpful feedback for a specific version and receiving context. That feedback is reversible and separate from the remembered fact. Real-model usefulness, automatic ranking from feedback, and direct navigation back to the receiving task remain unverified or unfinished.
+
The [historical design council](2026-09-30-coding-memory-council.md) applies ten complementary engineering perspectives to this model. Its central addition is memory of engineering judgment: how someone approaches a problem, why a decision made sense, what evidence supports it, and what would warrant changing it. These perspectives inform our design; they are not preset personalities assigned to developers.
The [modern practitioner study](../research/2026-09-30-modern-coding-memory.md) examines Peter Steinberger, Andrej Karpathy, Jeff Dean, Mitchell Hashimoto, Simon Willison, Addy Osmani, and Charity Majors through public 2025–2026 material. It adds memory of workspace resources, task contracts, working examples, experiments, and maintained project explanations. These are complementary examples, not a survey of all programmers.
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 522b25601..1f7e2137b 100644
--- a/docs/plans/2026-09-30-coding-memory-review-log.md
+++ b/docs/plans/2026-09-30-coding-memory-review-log.md
@@ -254,3 +254,21 @@ The owner picker searches bounded pages of known project names and redacted fold
Validation covered **252 backend tests across 21 files** (242 memory checks plus 10 companion-intelligence checks) and **35 distinct desktop tests across four files** over the targeted runs. CLI type checking, scoped Flutter analysis, CLI release bundling and the bundled version smoke check passed. Synthetic light/dark renders cover 100%, 160% and 200% text at short/narrow window sizes with long names and paths; [picker](../research/2026-10-01-memory-scope/project-picker-dark-2.0x.png) and [preview](../research/2026-10-01-memory-scope/scope-preview-light-1.0x.png) examples were visually inspected. The normal macOS debug review build passed with the Apple Silicon renderer and strict deep signature verification. These widget renders do not verify physical native IME or VoiceOver behavior. The installed app and daemon were not changed or launched.
This is still a development-gated prototype. No real provider inference was run during this round; the selected native login was signed out at the last check. Semantic quality, cross-framework task benefit, explicit usefulness feedback, fuller native lifecycle coverage, legacy lesson migration and production rollout remain unfinished. The published-programmer council remains a synthesis of sources, not actual participation or endorsement.
+
+## Round eighteen: collect usefulness feedback without reinforcing a false memory
+
+The owner library now shows up to ten recent recall contexts for a memory revision and supports Helpful, Not helpful and Clear feedback. A context binds the receiving engine/session/project, explicit task/branch scope and known conditions. Repeated prompt-hook, MCP and manual recalls in that context share one rating. Feedback does not change the claim, add independent evidence, prove native delivery or automatically change retrieval ranking. This applies the council's measurement and feedback-loop checks as our own design review; no practitioner participated in or endorsed this review.
+
+The owner capability path previews and applies each explicit rating. Per-context versions reject concurrent changes, including after a cleared rating. The detail stays mounted, preserves keyboard focus and offers a refresh after an uncertain response without retrying the write automatically. Owner/connection changes and a changed knowledge snapshot reject stale work. Long names and paths wrap at 100% and 200% text in both appearances; [dark](../research/2026-10-01-memory-feedback/feedback-dark-2.0x.png) and [light](../research/2026-10-01-memory-feedback/feedback-light-2.0x.png) renders use synthetic data.
+
+Receiver privacy is checked before history deduplication and limits, in addition to source visibility. A private receiving session removes its owner history and feedback without reviving them on reinclusion. The original privacy policy is also checked when an older daemon wrote it without the new cleanup hook. No native receiver ID or prompt is copied into receipt metadata. Feedback expires with its referenced receipt, even when a newer receipt in the same context survives; corrected revisions do not inherit ratings. Deletion uses foreign-key dependencies. Older receipts without recorded receiver authority do not acquire guessed context during migration.
+
+A real extraction attempt exposed a separate native-login defect. Claude's auth check succeeded in the shell but reported signed out with the memory adapter's restricted environment. Read-only A/B checks identified missing OS login names. The adapter now supplies USER and LOGNAME from `os.userInfo()`, ignoring inherited claimed values and continuing to exclude ambient provider credentials. A regression failed before this change and passes afterward. This corrects the interpretation of earlier signed-out checks: the restricted environment could hide an existing native login.
+
+The frozen six-case diagnostic was retried with the unchanged corpus and selected Claude `opus`/`high` on native 2.1.286. It [stopped on its first case](../research/2026-10-01-memory-native-quality-blocked.json) with no completed extraction or semantic credit. A separate synthetic READY probe [identified a rejected seven-day usage limit](../research/2026-10-01-memory-native-quota-diagnostic.json). Native frames included a rejected rate-limit event, an assistant `rate_limit` error, and an error result whose subtype was nevertheless `success`. The adapter now maps these to the existing budget-deferred backoff and refuses any later purported answer; allowed/warning telemetry still permits extraction. No account/model fallback, personal transcript, production memory write, or credential change was used. No more provider attempts were made after identifying the weekly limit. Real-model quality and batch usefulness remain unmeasured.
+
+Final targeted validation passed **272 tests across 22 memory and companion-intelligence files**, **40 guard fuzz checks** run separately, and **43 desktop tests across four files**. Type checking, scoped Flutter analysis, the icon audit, release bundling and the bundled version check passed. The normal macOS debug review build passed with its local signature; it was not opened or installed. Four synthetic feedback renders were visually inspected. A [synthetic benchmark](../research/2026-10-01-memory-feedback-performance.json) at 10,000 memories and 5,000 retained receipts measured warm p95 30.223 ms, fresh-worker p95 67.335 ms and zero timeouts over 310 requests; it is neither model latency nor comparative retrieval-quality evidence.
+
+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.
diff --git a/docs/plans/2026-09-30-tim-memory.md b/docs/plans/2026-09-30-tim-memory.md
index 1cc0ab3ed..b412ca9f8 100644
--- a/docs/plans/2026-09-30-tim-memory.md
+++ b/docs/plans/2026-09-30-tim-memory.md
@@ -121,6 +121,10 @@ Separate `selected`, `delivered`, `read`, `agent_reported_applied`, `outcome_obs
An agent's report of use can link to a diff/test result, but it is not independent proof of causation. Evaluate benefit using controlled tasks and explicit user feedback. Corrections reduce confidence or supersede a claim. Do not reward memory generation or encourage agents to announce every recollection.
+Implementation checkpoint: the owner can inspect recent recall in a memory's detail view and mark one memory revision helpful or unhelpful, change the rating, or clear it. The rating is bound to an actual retained receipt and receiving engine/session/project, explicit task/branch scope and known conditions. Repeated recall across transport routes in that same context shares one rating. It is owner-reported usefulness, not a new source supporting the claim, proof of model-context delivery, or a causal task-outcome measurement. Retrieval ranking does not yet reward these labels automatically.
+
+The owner history uses one-way session/context keys without copying native session IDs or prompt text into receipt metadata. It checks both source visibility and the receiving session/project before limiting results, including privacy changes written by an earlier daemon. Making a receiving session private removes its owner-visible activity and feedback; reinclusion starts new activity. Corrected memory revisions do not inherit old ratings, and forgotten memories lose their feedback through deletion dependencies. Feedback expires with its receipt under the existing thirty-day/5,000-receipt retention bound. Legacy receipts without captured receiver authority remain unavailable for owner feedback rather than having their context guessed.
+
### Continuous learning and improvement
Every eligible coding session supplies an opportunity to learn from its first interaction. A session may add a new fact, corroborate an existing claim, expose a counterexample, narrow a condition, close unfinished work, or produce no useful change. Capture and assessment are continuous; manufacturing a new memory every session is not a success criterion. The collection's selected intelligence supplies extraction and consolidation, with durable waiting states when unavailable.
@@ -285,7 +289,7 @@ Keep the actual DSH terminal on the right. The left viewer's Memories area has t
- **Helping now:** memories selected for the active task, why their conditions match, relevant conflicts/unknowns, and precise delivery status. “Provided to Codex” is distinct from “You confirmed this helped.” Accepted examples open at their reviewed revision with the approved attributes identified.
- **Learning:** quiet status such as caught up, reviewing completed work, waiting for the selected model, or missing source history. Rejected generic candidates are diagnostic detail, not an inbox demanding attention.
-Implementation checkpoint: the viewer currently offers How you work, Project knowledge and Learning, with retained evidence, owner corrections, project scope narrowing, dependent-forget previews and separate Learn/Recall preferences. The project picker and detail view show persisted names and folder paths. The agent terminal remains unchanged. Work-in-progress grouping, Helping now, explicit usefulness feedback and the maintained notebook view remain planned. The legacy approved-lesson list remains available; the 24-hour test action is hidden when the new memory service is available.
+Implementation checkpoint: the viewer currently offers How you work, Project knowledge and Learning, with retained evidence, owner corrections, project scope narrowing, dependent-forget previews and separate Learn/Recall preferences. The project picker and detail view show persisted names and folder paths. Memory details include recent recall and explicit helpful/unhelpful feedback; ratings keep the detail open, support clearing, and offer a fresh read after an uncertain reply without automatically retrying the write. The agent terminal remains unchanged. Work-in-progress grouping, a collection-wide Helping now view, task/session navigation, automatic usefulness-based ranking and the maintained notebook view remain planned. The legacy approved-lesson list remains available; the 24-hour test action is hidden when the new memory service is available.
Tim can answer “Why did you remember that?” using the same evidence API the viewer uses. He must not invent shared experiences. A corrected memory updates its story rather than adding another repetitive lesson. A small optional recent-learning digest replaces repeated interruption, and no memory-count reward is attached to growth.
diff --git a/docs/research/2026-10-01-memory-feedback-performance.json b/docs/research/2026-10-01-memory-feedback-performance.json
new file mode 100644
index 000000000..8e886ccef
--- /dev/null
+++ b/docs/research/2026-10-01-memory-feedback-performance.json
@@ -0,0 +1,30 @@
+{
+ "kind": "synthetic-memory-performance",
+ "mode": "prepare-with-full-receipt-history",
+ "retainedReceipts": 5000,
+ "records": 10000,
+ "projects": 10,
+ "node": "v22.23.2",
+ "platform": "darwin",
+ "arch": "arm64",
+ "seedMs": 57644.669666999995,
+ "cold": {
+ "p50Ms": 58.674334000003,
+ "p95Ms": 67.33458300000348,
+ "maxMs": 67.33458300000348
+ },
+ "warm": {
+ "p50Ms": 23.567708000002312,
+ "p95Ms": 30.22320899999613,
+ "maxMs": 44.904333999998926
+ },
+ "requests": 310,
+ "timeouts": 0,
+ "largestPacketBytes": 2642,
+ "parentEventLoopP95Ms": 1.649663,
+ "limitations": [
+ "Synthetic lexical matches, not a retrieval-quality benchmark.",
+ "Cold means a new worker, not an emptied OS disk cache.",
+ "One local machine; provider extraction and native hook delivery are not measured."
+ ]
+}
diff --git a/docs/research/2026-10-01-memory-feedback/feedback-dark-1.0x.png b/docs/research/2026-10-01-memory-feedback/feedback-dark-1.0x.png
new file mode 100644
index 000000000..cf1f66696
Binary files /dev/null and b/docs/research/2026-10-01-memory-feedback/feedback-dark-1.0x.png differ
diff --git a/docs/research/2026-10-01-memory-feedback/feedback-dark-2.0x.png b/docs/research/2026-10-01-memory-feedback/feedback-dark-2.0x.png
new file mode 100644
index 000000000..ca030e123
Binary files /dev/null and b/docs/research/2026-10-01-memory-feedback/feedback-dark-2.0x.png differ
diff --git a/docs/research/2026-10-01-memory-feedback/feedback-light-1.0x.png b/docs/research/2026-10-01-memory-feedback/feedback-light-1.0x.png
new file mode 100644
index 000000000..667350766
Binary files /dev/null and b/docs/research/2026-10-01-memory-feedback/feedback-light-1.0x.png differ
diff --git a/docs/research/2026-10-01-memory-feedback/feedback-light-2.0x.png b/docs/research/2026-10-01-memory-feedback/feedback-light-2.0x.png
new file mode 100644
index 000000000..b8c11605c
Binary files /dev/null and b/docs/research/2026-10-01-memory-feedback/feedback-light-2.0x.png differ
diff --git a/docs/research/2026-10-01-memory-native-quality-blocked.json b/docs/research/2026-10-01-memory-native-quality-blocked.json
new file mode 100644
index 000000000..3de33ddc9
--- /dev/null
+++ b/docs/research/2026-10-01-memory-native-quality-blocked.json
@@ -0,0 +1,153 @@
+{
+ "schemaVersion": 1,
+ "suite": "synthetic-extraction-diagnostics-v1",
+ "suiteSha256": "135545eb05370bac04fbaf555c36255afd21fbcbd4190b0e21895e17d31273c3",
+ "promptVersion": "coding-memory-v3",
+ "contextVersion": "coding-context-v1",
+ "runnerSha256": "b0d9e55b1f55cd9b5df3e3ae9cf3860c09c6a237d2ff0ae5355fd6e8ed63a68e",
+ "sourceHashes": {
+ "learner.ts": "b09dd22ae878f78c9c7f5d7d658d9a2dbaefc1e7461ca5af2669787bfa6ead08",
+ "context.ts": "d1e5e0797c065c7ce86cf6cfb1158a1702d10be2040a04a700a21d18b2c6fd70",
+ "types.ts": "380a95c563c7c5254f4a2ad8ccf3858d21e88f76ab90a348f1be5e18aa273ec6",
+ "admission.ts": "de6fe82c328763d0daad687373c345fa79dc7a48ae3ef8632de7729b419bb465",
+ "store.ts": "25618892e8db33ec10bf619aa87a6f233377a62d9def0585354ce44e6b8da6fc",
+ "queue.ts": "c01a274865d381736fea23ab0aaf12a3d09450e3b8a08bce68e662f59a6d4ea4",
+ "evaluation.ts": "def8e1d0d96e42fe6f5fb5c69ef9d02248d3887b42c81ff85e9706e5bc9569d1",
+ "account.ts": "c7e95d7c1464ca65ce80961efd42589c2ca827ceefc965ffc4ac5fe52b36498b",
+ "claudeInference.ts": "f7c87315c2e635aea7a2b7cbe2e72a9b1e1e2728726ce4dc5a562a52a4e351c6",
+ "inference.ts": "90ac3238d8a723102a365b809be2936429b31db0ad2fd7d2eaf7bc8ae5de12d5",
+ "inferenceProcess.ts": "995df74135cd42539274e1eac99f1a5b080ff2f5c9e2dafe035a68adc224afe0"
+ },
+ "startedAt": "2026-10-01T08:30:07.277Z",
+ "status": "stopped",
+ "selected": {
+ "engine": "claude",
+ "model": "opus",
+ "effort": "high",
+ "nativeVersion": "2.1.286"
+ },
+ "limits": {
+ "maxCalls": 6,
+ "timeoutPerCallMs": 90000,
+ "retries": 0,
+ "corpus": "synthetic_only",
+ "tools": "restricted_native_adapter"
+ },
+ "limitations": [
+ "Development diagnostics, not held-out release evidence.",
+ "Mechanical checks do not establish faithful meaning or downstream task usefulness.",
+ "Semantic review remains pending until explicitly reviewed.",
+ "A native init model label does not prove that the provider executed that model.",
+ "Native-reported cost is diagnostic metadata, not a subscription invoice.",
+ "No personal transcript was supplied to inference; live reads establish selected companion metadata only."
+ ],
+ "cases": [
+ {
+ "id": "conditional-debugging",
+ "durationMs": 74182,
+ "outcome": {
+ "state": "waiting_for_model",
+ "reason": "inference_unavailable"
+ },
+ "checks": [
+ {
+ "name": "completed_extraction",
+ "passed": false
+ },
+ {
+ "name": "record_count",
+ "passed": null
+ },
+ {
+ "name": "scope",
+ "passed": null
+ },
+ {
+ "name": "no_invented_rationale",
+ "passed": null
+ },
+ {
+ "name": "recall:debugging",
+ "passed": null
+ },
+ {
+ "name": "recall:incident",
+ "passed": null
+ },
+ {
+ "name": "recall:unclassified-task",
+ "passed": null
+ }
+ ],
+ "probes": [
+ {
+ "id": "debugging",
+ "query": "debugging failing test implementation",
+ "projectIds": [
+ "alpha"
+ ],
+ "conditions": {
+ "taskType": "debugging",
+ "productionIncident": false
+ },
+ "expected": "recall",
+ "status": "not_run",
+ "returnedIds": [],
+ "passed": null
+ },
+ {
+ "id": "incident",
+ "query": "debugging failing test implementation",
+ "projectIds": [
+ "alpha"
+ ],
+ "conditions": {
+ "taskType": "debugging",
+ "productionIncident": true
+ },
+ "expected": "abstain",
+ "status": "not_run",
+ "returnedIds": [],
+ "passed": null
+ },
+ {
+ "id": "unclassified-task",
+ "query": "debugging failing test implementation",
+ "projectIds": [
+ "alpha"
+ ],
+ "conditions": {},
+ "expected": "abstain",
+ "status": "not_run",
+ "returnedIds": [],
+ "passed": null
+ }
+ ],
+ "records": [],
+ "episodes": {
+ "expected": 1,
+ "reviewed": 0,
+ "jobs": {
+ "waiting_for_model": 1
+ }
+ },
+ "semanticReview": {
+ "status": "not_reviewable",
+ "criteria": [
+ "Preserves the test-before-implementation preference only for debugging.",
+ "Preserves the production-incident exception without inventing an incident workflow.",
+ "Does not invent a reason for the preference."
+ ]
+ },
+ "promptSha256": "ad9055ff3c38c9d0e139b082a6dd4278def08c3f7fa72b005e3a7c3cc50a9fa6",
+ "observations": [
+ {
+ "model": "claude-opus-5-5"
+ }
+ ]
+ }
+ ],
+ "nativeCalls": 1,
+ "finishedAt": "2026-10-01T08:31:21.465Z",
+ "completedCases": 0
+}
diff --git a/docs/research/2026-10-01-memory-native-quota-diagnostic.json b/docs/research/2026-10-01-memory-native-quota-diagnostic.json
new file mode 100644
index 000000000..fff024f94
--- /dev/null
+++ b/docs/research/2026-10-01-memory-native-quota-diagnostic.json
@@ -0,0 +1,56 @@
+{
+ "durationMs": 5510,
+ "nativeCalls": 1,
+ "exitCode": 1,
+ "rows": [
+ {
+ "type": "init",
+ "tools": 0
+ },
+ {
+ "status": "rejected",
+ "rateLimitType": "seven_day",
+ "type": "rate_limit_event"
+ },
+ {
+ "type": "assistant",
+ "error": true,
+ "errorCode": "rate_limit",
+ "diagnosis": {
+ "categories": [
+ "rate_limit"
+ ],
+ "codes": [],
+ "statuses": []
+ }
+ },
+ {
+ "type": "result",
+ "success": true,
+ "isError": true,
+ "diagnosis": {
+ "categories": [
+ "rate_limit"
+ ],
+ "codes": [],
+ "statuses": []
+ },
+ "ready": false
+ }
+ ],
+ "stderr": {
+ "categories": [],
+ "codes": [],
+ "statuses": []
+ },
+ "sameAccount": true,
+ "provenance": {
+ "engine": "claude",
+ "nativeVersion": "2.1.286",
+ "requestedModel": "opus",
+ "effort": "high",
+ "input": "synthetic READY diagnostic; no personal history or tools",
+ "sanitization": "Only recognized error categories/status values were recorded. Rate-event type field normalized to separate event kind from rateLimitType. No credentials, account/session IDs, raw messages or stderr retained.",
+ "qualityCredit": false
+ }
+}