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.

Evaluate the source context delivered by coding memory (#656)

Dee1c3790a5f129
diff --git a/cli/scripts/memory-extraction-eval.ts b/cli/scripts/memory-extraction-eval.ts
index 42af73eff..10a1c0bd1 100644
--- a/cli/scripts/memory-extraction-eval.ts
+++ b/cli/scripts/memory-extraction-eval.ts
@@ -1,5 +1,6 @@
// Dry run: node --import tsx scripts/memory-extraction-eval.ts
// Add --batch for the frozen multi-episode suite. Native run: --run-native --output <report.json>.
+// Recall uses source excerpts by default; --recall-format summary selects the older comparison arm.
// At most six calls, no retries/fallback.
// Synthetic data only. Reads selected companion metadata; never writes the production memory DB.
import { execFile } from 'node:child_process'
@@ -16,26 +17,36 @@ import { evaluateExtractionCase, type ExtractionScenario } from '../src/memory/e
import { EXTRACTION_PROMPT_VERSION } from '../src/memory/learner.js'
import { MEMORY_CONTEXT_VERSION } from '../src/memory/context.js'
import type { MemoryInferenceObservation, MemoryInferenceOptions } from '../src/memory/inferenceProcess.js'
-import { MemoryError } from '../src/memory/types.js'
+import { MemoryError, type RecallRequest } from '../src/memory/types.js'
const exec = promisify(execFile)
const cli = fileURLToPath(new URL('..', import.meta.url))
const root = dirname(cli)
const digest = (value: string) => createHash('sha256').update(value).digest('hex')
const args = process.argv.slice(2)
-const batch = args.includes('--batch')
+const options = new Map<string, string | true>()
+for (let index = 0; index < args.length; index++) {
+ const key = args[index]
+ if (options.has(key)) throw new Error('Duplicate diagnostic option')
+ if (['--batch', '--run-native'].includes(key)) options.set(key, true)
+ else if (['--output', '--recall-format'].includes(key) && args[index + 1] && !args[index + 1].startsWith('--')) {
+ options.set(key, args[++index])
+ } else throw new Error('Use --batch, --run-native --output <report.json>, and/or --recall-format source_excerpts|summary')
+}
+const recallFormat = options.get('--recall-format') ?? 'source_excerpts'
+if (recallFormat !== 'summary' && recallFormat !== 'source_excerpts') throw new MemoryError('invalid_evaluation_recall_format')
+const batch = options.has('--batch')
const suitePath = join(root, batch ? 'docs/research/2026-09-30-memory-batch-extraction-cases.json' : 'docs/research/2026-09-30-memory-extraction-cases.json')
-const native = args.includes('--run-native')
-const outputIndex = args.indexOf('--output')
-const output = outputIndex < 0 ? null : resolve(args[outputIndex + 1] ?? '')
-const allowed = new Set(['--batch', '--run-native', '--output', ...(outputIndex < 0 ? [] : [args[outputIndex + 1]])])
-if (args.some(arg => !allowed.has(arg)) || (native && (!output || !args[outputIndex + 1]))) throw new Error('Use --run-native --output <report.json>')
+const native = options.has('--run-native')
+const output = options.has('--output') ? resolve(options.get('--output') as string) : null
+if (native && !output) throw new Error('Use --run-native --output <report.json>')
const suiteText = await readFile(suitePath, 'utf8')
const suite = JSON.parse(suiteText) as { suite: string; cases: ExtractionScenario[] }
if (!Array.isArray(suite.cases) || suite.cases.length > 6) throw new Error('At most six frozen cases per diagnostic run')
if (!native) {
console.log(JSON.stringify({ suite: suite.suite, sha256: digest(suiteText), cases: suite.cases.map(row => row.id),
- nativeCalls: 0, status: 'not_run', instructions: `Use ${batch ? '--batch ' : ''}--run-native --output <report.json> with the current companion model.` }, null, 2))
+ recallFormat, nativeCalls: 0, status: 'not_run',
+ instructions: `Use ${batch ? '--batch ' : ''}--recall-format ${recallFormat} --run-native --output <report.json> with the current companion model.` }, null, 2))
} else {
try { await run() } catch (error) {
console.error(JSON.stringify({ status: 'not_run', error: error instanceof MemoryError ? error.code : 'evaluation_unavailable' }))
@@ -88,11 +99,11 @@ async function run() {
// A diagnostic rerun must use a new path; preserve the evidence from earlier attempts.
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',
+ const sourceFiles = ['learner.ts', 'context.ts', 'types.ts', 'admission.ts', 'store.ts', 'recallSources.ts', 'queue.ts', 'evaluation.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,
+ promptVersion: EXTRACTION_PROMPT_VERSION, contextVersion: MEMORY_CONTEXT_VERSION, recallFormat,
runnerSha256: digest(await readFile(fileURLToPath(import.meta.url), 'utf8')),
sourceHashes, startedAt: new Date().toISOString(), status: 'running',
selected: { engine: selected.engine, model: selected.model, effort: selected.effort, nativeVersion: selected.nativeVersion },
@@ -116,6 +127,7 @@ async function run() {
const observations: MemoryInferenceObservation[] = []
let promptSha256: string | null = null
const result = await evaluateExtractionCase({ fixture, directory: join(temporary, fixture.id), engine: selected.engine,
+ recallFormat: recallFormat as RecallRequest['format'],
inference: {
target: async () => {
const current = await selection()
diff --git a/cli/scripts/memory-quality-review.ts b/cli/scripts/memory-quality-review.ts
index 39e13b313..582043b14 100644
--- a/cli/scripts/memory-quality-review.ts
+++ b/cli/scripts/memory-quality-review.ts
@@ -29,9 +29,10 @@ try {
const result = files.has('--review') ? scoreEvaluationReview(suite, report, await read(files.get('--review')!))
: prepareEvaluationReview(suite, report)
const hash = async (url: URL) => createHash('sha256').update(await read(fileURLToPath(url))).digest('hex')
- const producer = { protocol: 'coding-memory-quality-review-v1', node: process.version,
+ const producer = { protocol: 'coding-memory-quality-review-v2', node: process.version,
runnerSha256: await hash(new URL(import.meta.url)),
- scorerSha256: await hash(new URL('../src/memory/evaluationReview.ts', import.meta.url)) }
+ scorerSha256: await hash(new URL('../src/memory/evaluationReview.ts', import.meta.url)),
+ contextValidatorSha256: await hash(new URL('../src/memory/evaluationContext.ts', import.meta.url)) }
// Never overwrite an earlier result or print source conversations to the terminal.
await writeFile(files.get('--output')!, `${JSON.stringify({ ...result, producer }, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
console.log(JSON.stringify({ status: 'written', kind: files.has('--review') ? 'review_scores' : 'review_packet',
diff --git a/cli/src/memory/evaluation.spec.ts b/cli/src/memory/evaluation.spec.ts
index 35d711557..a20fd770a 100644
--- a/cli/src/memory/evaluation.spec.ts
+++ b/cli/src/memory/evaluation.spec.ts
@@ -33,12 +33,43 @@ it('runs real admission and scoped recall without leaking its rubric or probes t
expect(result.outcome).toEqual({ state: 'learned', learned: 1 })
expect(result.checks.every(check => check.passed)).toBe(true)
expect(result.semanticReview.status).toBe('pending')
+ expect(result.recallFormat).toBe('source_excerpts')
+ const packet = JSON.parse(result.probes[0].context!.text)
+ expect(packet.type).toBe('coding_memory_sources')
+ expect(packet.sources[0]).toMatchObject({ id: 'synthetic-0', engine: 'claude', role: 'user',
+ excerpts: [{ text: fixture.sources[0].text, fields: draft.evidence[0].paths }] })
+ expect(result.probes[0].context!.text).not.toContain(draft.claim)
+ expect(result.probes[0].context!.text).not.toContain(draft.futureAction)
const prompt = (inference.run.mock.calls[0] as unknown as [string])[0]
expect(prompt).toContain(fixture.sources[0].text)
expect(prompt).not.toContain('SECRET_EXPECTATION_NOT_IN_PROMPT')
expect(prompt).not.toContain('"id":"negative"')
})
+it('retains sanitized captured source metadata even when extraction produces no memory', async () => {
+ const result = await evaluateExtractionCase({ fixture: { ...fixture,
+ sources: [{ role: 'user', text: ' Contact [email protected] about debugging. ' }] },
+ directory, engine: 'codex', inference: provider([]) })
+ expect(result.capturedSources).toEqual([expect.objectContaining({ id: 'synthetic-0', role: 'user',
+ engine: 'codex', projectId: null, text: ' Contact [email] about debugging. ', observedAt: expect.any(Number) })])
+ expect(JSON.stringify(result)).not.toContain('[email protected]')
+})
+
+it('keeps the older summary packet available as an explicit comparison', async () => {
+ const result = await evaluateExtractionCase({ fixture, directory, engine: 'claude',
+ inference: provider([draft]), recallFormat: 'summary' })
+ expect(result.recallFormat).toBe('summary')
+ expect(JSON.parse(result.probes[0].context!.text).type).toBe('coding_memory_context')
+ expect(result.probes[0].context!.text).toContain(draft.claim)
+})
+
+it('rejects an unknown recall format before inference', async () => {
+ const inference = provider([draft])
+ await expect(evaluateExtractionCase({ fixture, directory, engine: 'claude', inference,
+ recallFormat: 'unknown' as 'summary' })).rejects.toThrow('invalid_evaluation_recall_format')
+ expect(inference.run).not.toHaveBeenCalled()
+})
+
it('exposes independently specified condition mismatch instead of copying generated keys into the probe', async () => {
const result = await evaluateExtractionCase({ fixture, directory, engine: 'codex',
inference: provider([{ ...draft, applicability: { task: 'debugging' } }]) })
diff --git a/cli/src/memory/evaluation.ts b/cli/src/memory/evaluation.ts
index 46bc4f9af..4250fe11b 100644
--- a/cli/src/memory/evaluation.ts
+++ b/cli/src/memory/evaluation.ts
@@ -2,7 +2,7 @@
import { MemoryLearner, type MemoryInference } from './learner.js'
import { CodingMemoryStore } from './store.js'
import { QUEUE_OPERATIONS, type Arguments, type MemoryPort, type Operation, type Result } from './operations.js'
-import { MemoryError, type Conditions, type MemoryRecord, type SourceEvent } from './types.js'
+import { MemoryError, type Conditions, type MemoryRecord, type RecallRequest, type SourceEvent } from './types.js'
import { MAX_EPISODES_PER_CALL } from './queue.js'
export interface ExtractionCase {
@@ -27,8 +27,12 @@ export type ExtractionScenario = ExtractionCase | ExtractionBatchCase
/** Expectations and probes are never included in captured text or extraction input. */
export async function evaluateExtractionCase(input: {
fixture: ExtractionScenario; directory: string; inference: MemoryInference; engine: string
+ /** Default to the packet delivered by native prompt recall; summary is an explicit comparison arm. */
+ recallFormat?: RecallRequest['format']
}) {
const { fixture } = input
+ const recallFormat = input.recallFormat ?? 'source_excerpts'
+ if (!['summary', 'source_excerpts'].includes(recallFormat)) throw new MemoryError('invalid_evaluation_recall_format')
const boundary = fixture.boundary ?? 'complete'
if (!['complete', 'bounded'].includes(boundary)) throw new MemoryError('invalid_evaluation_boundary')
const batch = 'episodes' in fixture
@@ -40,6 +44,7 @@ export async function evaluateExtractionCase(input: {
if (!opened.ok) throw new Error(opened.reason)
const store = opened.store
const startedAt = Date.now()
+ const capturedSources: SourceEvent[] = []
try {
const projectIds = [...new Set([fixture.projectId, ...fixture.probes.flatMap(probe => probe.projectIds)].filter((id): id is string => id !== null))]
for (const id of projectIds) store.registerProject(id)
@@ -54,6 +59,10 @@ export async function evaluateExtractionCase(input: {
}))
store.learning.capture({ streamId: id, episodeId: id, engine: input.engine, sessionId,
projectId: fixture.projectId, from: null, to: '1', events: sources, boundary })
+ for (const source of sources) {
+ const captured = store.source(source.id, { profileId, projectIds, includeProfile: true })
+ if (captured) capturedSources.push(captured)
+ }
}
const memory: MemoryPort = { async request<K extends Operation>(operation: K, args: Arguments<K>): Promise<Result<K>> {
const owner = (QUEUE_OPERATIONS as readonly string[]).includes(operation) ? store.learning : store
@@ -71,14 +80,15 @@ export async function evaluateExtractionCase(input: {
return { ...probe, status: 'not_run', returnedIds: [], passed: null, context: null }
}
const maxBytes = 3_000
- const result = store.recall({ query: probe.query, conditions: probe.conditions, maxBytes }, { profileId, projectIds: probe.projectIds, includeProfile: true })
+ const result = store.recall({ query: probe.query, conditions: probe.conditions, maxBytes, format: recallFormat },
+ { profileId, projectIds: probe.projectIds, includeProfile: true })
const passed = result.status === 'ok' && (probe.expected === 'recall' ? result.items.length > 0 : result.items.length === 0)
checks.push({ name: `recall:${probe.id}`, passed })
return { ...probe, status: result.status, returnedIds: result.items.map(item => item.id), passed,
measurement: 'presence_only' as const,
context: { text: result.text, bytes: Buffer.byteLength(result.text, 'utf8'), maxBytes, estimatedTokens: result.estimatedTokens } }
})
- return { id: fixture.id, durationMs: Date.now() - startedAt, outcome, checks, probes, records,
+ return { id: fixture.id, durationMs: Date.now() - startedAt, recallFormat, capturedSources, outcome, checks, probes, records,
episodes: { expected: episodes.length, reviewed, jobs, boundary },
// Mechanical success never claims semantic entailment, usefulness or independent review.
semanticReview: { status: completed ? 'pending' as const : 'not_reviewable' as const, criteria: fixture.expected.review } }
diff --git a/cli/src/memory/evaluationContext.ts b/cli/src/memory/evaluationContext.ts
new file mode 100644
index 000000000..b4e1b3406
--- /dev/null
+++ b/cli/src/memory/evaluationContext.ts
@@ -0,0 +1,67 @@
+/** Validate diagnostic context independently of the serializer that produced it. No inference. */
+import { z } from 'zod'
+import { canonical } from './admission.js'
+import { redact } from '../pair/learn/guard.js'
+import { MemoryError, scopeSchema, verificationSchema, type MemoryRecord, type RecallRequest, type SourceEvent } from './types.js'
+
+const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)
+const count = z.number().int().nonnegative().safe()
+const item = z.object({ id, revision: count.positive() })
+const summaryPacket = z.object({ type: z.literal('coding_memory_context'), items: z.array(item).max(6) })
+const sourcesPacket = z.object({
+ type: z.literal('coding_memory_sources'), version: z.literal(1), notice: z.string().min(1).max(2_000),
+ items: z.array(item.extend({ scope: scopeSchema, sourceIds: z.array(id).min(1).max(16) }).strict()).max(6),
+ sources: z.array(z.object({ id, engine: id, role: z.enum(['user', 'assistant', 'tool', 'reference', 'derived']),
+ observedAt: count, verification: verificationSchema.optional(),
+ excerpts: z.array(z.object({ text: z.string().min(1).max(4_000),
+ fields: z.array(z.string().min(2).max(200)).min(1).max(3_072) }).strict()).min(1).max(96),
+ }).strict()).max(96),
+}).strict()
+const packetSchema = z.discriminatedUnion('type', [summaryPacket, sourcesPacket])
+const fail = (): never => { throw new MemoryError('invalid_recall_context') }
+function unique(values: string[]): void { if (new Set(values).size !== values.length) fail() }
+const sameSet = (left: string[], right: string[]) => canonical([...left].sort()) === canonical([...new Set(right)].sort())
+
+export function reviewRecallContext(input: {
+ text: string; records: MemoryRecord[]; declaredFormat?: RecallRequest['format']; capturedSources?: SourceEvent[]
+ originals: Array<{ id: string; projectId: string | null; role: SourceEvent['role']; text: string }>
+}) {
+ if (!input.text) return { items: [], format: input.declaredFormat ?? null }
+ let packet: z.infer<typeof packetSchema>
+ try { packet = packetSchema.parse(JSON.parse(input.text)) } catch { return fail() }
+ const format = packet.type === 'coding_memory_context' ? 'summary' as const : 'source_excerpts' as const
+ if (input.declaredFormat && input.declaredFormat !== format) fail()
+ unique(packet.items.map(row => row.id))
+ const records = packet.items.map(row => {
+ const record = input.records.find(record => record.id === row.id && record.revision === row.revision)
+ return record ?? fail()
+ })
+ if (packet.type === 'coding_memory_sources') {
+ if (!input.capturedSources) fail()
+ unique(input.capturedSources!.map(row => row.id))
+ unique(packet.sources.map(row => row.id))
+ if (!sameSet(packet.sources.map(row => row.id), records.flatMap(record => record.evidence.map(e => e.sourceEventId)))) fail()
+ for (const row of packet.items) {
+ const record = records.find(record => record.id === row.id)!
+ unique(row.sourceIds)
+ if (canonical(row.scope) !== canonical(record.scope)
+ || !sameSet(row.sourceIds, record.evidence.map(e => e.sourceEventId))) fail()
+ }
+ for (const source of packet.sources) {
+ const captured = input.capturedSources!.find(row => row.id === source.id)
+ const original = input.originals.find(row => row.id === source.id)
+ if (!captured || !original || captured.role !== original.role || captured.projectId !== original.projectId
+ || captured.text !== redact(original.text) || source.role !== captured.role || source.engine !== captured.engine
+ || source.observedAt !== captured.observedAt || canonical(source.verification ?? null) !== canonical(captured.verification ?? null)) fail()
+ const evidence = records.flatMap(record => record.evidence).filter(row => row.sourceEventId === source.id)
+ unique(source.excerpts.map(excerpt => excerpt.text))
+ if (!sameSet(source.excerpts.map(excerpt => excerpt.text), evidence.map(row => row.quote))) fail()
+ for (const excerpt of source.excerpts) {
+ unique(excerpt.fields)
+ if (!captured!.text.includes(excerpt.text)
+ || !sameSet(excerpt.fields, evidence.filter(row => row.quote === excerpt.text).flatMap(row => row.paths))) fail()
+ }
+ }
+ }
+ return { items: packet.items, format }
+}
diff --git a/cli/src/memory/evaluationReview.spec.ts b/cli/src/memory/evaluationReview.spec.ts
index 7d2a6d19f..3f344d1a7 100644
--- a/cli/src/memory/evaluationReview.spec.ts
+++ b/cli/src/memory/evaluationReview.spec.ts
@@ -26,6 +26,7 @@ const report = () => JSON.stringify({ schemaVersion: 1, suite: 'review-test', su
const testing = () => result.records.find(r => r.conflictKey === 'debugging_order')!.id
const release = () => result.records.find(r => r.conflictKey === 'release_order')!.id
function recalled(ids: string[]) {
+ result.recallFormat = 'summary'
const p = result.probes[0]
const text = JSON.stringify({ type: 'coding_memory_context', items: ids.map(id => result.records.find(r => r.id === id)) })
p.returnedIds = ids
@@ -71,6 +72,109 @@ it('keeps attributed semantic review separate from native delivery and task bene
expect(scored.evidence).toBe('development_diagnostic_only')
expect(scored.taskBenefit).toBe('not_measured')
expect(scored.nativeDelivery).toBe('not_measured')
+ expect(scored.contextFormats).toEqual(['source_excerpts'])
+})
+
+it('still reviews older summary reports without pretending they measured source recall', () => {
+ recalled([testing()])
+ const older = JSON.parse(report())
+ delete older.cases[0].recallFormat
+ delete older.cases[0].capturedSources
+ const text = JSON.stringify(older)
+ const packet = prepareEvaluationReview(suiteText, text)
+ expect(packet.cases[0].probes[0].context?.format).toBe('summary')
+ const scored = scoreEvaluationReview(suiteText, text, JSON.stringify(labels(text)))
+ expect(scored.recall.rate).toBe(1)
+ expect(scored.contextFormats).toEqual(['summary'])
+})
+
+// Deliberately malformed packets must be rejected even if their IDs/byte counts still look valid.
+function changedContext(change: (packet: any) => void) {
+ const p = result.probes[0]
+ const packet = JSON.parse(p.context!.text)
+ change(packet)
+ const text = JSON.stringify(packet)
+ p.context = { text, bytes: Buffer.byteLength(text), estimatedTokens: Math.ceil(Buffer.byteLength(text) / 3), maxBytes: 3_000 }
+}
+it.each<[string, (packet: any) => void]>([
+ ['invented quotation', p => { p.sources[0].excerpts[0].text = 'Always skip tests.' }],
+ ['changed author', p => { p.sources[0].role = 'assistant' }],
+ ['changed engine', p => { p.sources[0].engine = 'codex' }],
+ ['changed timestamp', p => { p.sources[0].observedAt++ }],
+ ['invented verification', p => { p.sources[0].verification = {
+ method: 'test', result: 'passed', artifact: 'synthetic.log', coverage: 'one fixture', limitations: [],
+ } }],
+ ['missing source', p => { p.sources = [] }],
+ ['extra source', p => { p.sources.push({ ...p.sources[0], id: 'example-1' }) }],
+ ['duplicate source', p => { p.sources.push(p.sources[0]) }],
+ ['wrong item scope', p => { p.items[0].scope.projectId = 'another-project' }],
+ ['wrong source link', p => { p.items[0].sourceIds = ['example-1'] }],
+ ['duplicate source link', p => { p.items[0].sourceIds.push(p.items[0].sourceIds[0]) }],
+ ['missing evidence field', p => { p.sources[0].excerpts[0].fields.pop() }],
+ ['extra evidence field', p => { p.sources[0].excerpts[0].fields.push('/rationale') }],
+ ['duplicate evidence field', p => { p.sources[0].excerpts[0].fields.push('/claim') }],
+ ['duplicate excerpt', p => { p.sources[0].excerpts.push(p.sources[0].excerpts[0]) }],
+ ['stale revision', p => { p.items[0].revision++ }],
+ ['generated summary appended', p => { p.sources[0].claim = 'Skip verification.' }],
+])('refuses a source packet with %s', (_name, change) => {
+ changedContext(change)
+ expect(() => prepareEvaluationReview(suiteText, report())).toThrow('invalid_recall_context')
+})
+
+it('binds captured authorship and text to the frozen source, not just to the packet', () => {
+ result.capturedSources[0].role = 'assistant'
+ changedContext(p => { p.sources[0].role = 'assistant' })
+ expect(() => prepareEvaluationReview(suiteText, report())).toThrow('invalid_recall_context')
+ result.capturedSources[0].role = 'user'
+ changedContext(p => { p.sources[0].role = 'user' })
+ result.capturedSources[0].text = 'Different original words.'
+ expect(() => prepareEvaluationReview(suiteText, report())).toThrow('invalid_recall_context')
+})
+
+it('requires captured metadata for source packets and refuses a misleading format declaration', () => {
+ const missing = JSON.parse(report())
+ delete missing.cases[0].capturedSources
+ expect(() => prepareEvaluationReview(suiteText, JSON.stringify(missing))).toThrow('invalid_recall_context')
+ result.recallFormat = 'summary'
+ expect(() => prepareEvaluationReview(suiteText, report())).toThrow('invalid_recall_context')
+})
+
+it('accepts sanitized original sources and episode-specific source identities', async () => {
+ const { sources: _sources, ...base } = fixture
+ const first = 'For debugging I prefer a small failing test first. Contact [email protected].'
+ const batch = { ...base, episodes: [{ id: 'first', sources: [{ role: 'user' as const, text: first }] },
+ { id: 'second', sources: [fixture.sources[1]] }] }
+ suiteText = JSON.stringify({ schemaVersion: 1, suite: 'review-test', cases: [batch] })
+ result = await evaluateExtractionCase({ fixture: batch, directory: join(directory, 'batch'), engine: 'codex', inference: {
+ target: async () => ({ state: 'ready', key: 'context' }), run: async () => JSON.stringify({ proposals: drafts.map((d, i) =>
+ ({ ...d, evidence: [{ ...d.evidence[0], sourceEventId: `example-${i ? 'second' : 'first'}-0` }] })) }),
+ } })
+ expect(result.outcome.state).toBe('learned')
+ expect(result.capturedSources[0].text).toContain('Contact [email].')
+ const packet = prepareEvaluationReview(suiteText, report())
+ expect(packet.cases[0].sources.map(source => source.id)).toEqual(['example-first-0', 'example-second-0'])
+ expect(score().recall.rate).toBe(1)
+})
+
+it('checks deduplicated excerpts shared by multiple records without losing their field union', async () => {
+ const sameSource: ExtractionCase = { ...fixture, sources: [fixture.sources[0]], probes: [{ ...fixture.probes[0], conditions: {} }] }
+ suiteText = JSON.stringify({ schemaVersion: 1, suite: 'review-test', cases: [sameSource] })
+ result = await evaluateExtractionCase({ fixture: sameSource, directory: join(directory, 'shared'), engine: 'claude', inference: {
+ target: async () => ({ state: 'ready', key: 'context' }), run: async () => JSON.stringify({ proposals: [
+ { ...drafts[0], applicability: {} },
+ { ...drafts[0], conflictKey: 'related_preference', applicability: {},
+ exceptions: [{ when: { productionIncident: true }, reason: 'Unless fixing a production incident.' }],
+ evidence: [{ ...drafts[0].evidence[0], paths: ['/claim', '/futureAction', '/applicability', '/exceptions'] }] },
+ ] }),
+ } })
+ // This validates transport, not whether the added exception follows from the quote.
+ expect(result.records).toHaveLength(2)
+ expect(result.probes[0].returnedIds).toHaveLength(2)
+ const packet = prepareEvaluationReview(suiteText, report())
+ const source = JSON.parse(packet.cases[0].probes[0].context!.text).sources[0]
+ expect(source.excerpts).toEqual([{ text: fixture.sources[0].text, fields: ['/claim', '/futureAction', '/applicability', '/exceptions'] }])
+ changedContext(p => { p.sources[0].excerpts[0].fields = ['/claim', '/futureAction', '/applicability'] })
+ expect(() => prepareEvaluationReview(suiteText, report())).toThrow('invalid_recall_context')
})
it('shows bounded context to the reviewer and rejects a missing or changed capture boundary', () => {
diff --git a/cli/src/memory/evaluationReview.ts b/cli/src/memory/evaluationReview.ts
index fb411f49d..1ad0c3a05 100644
--- a/cli/src/memory/evaluationReview.ts
+++ b/cli/src/memory/evaluationReview.ts
@@ -2,7 +2,8 @@
import { createHash } from 'node:crypto'
import { z } from 'zod'
import { canonical } from './admission.js'
-import { conditionsSchema, draftSchema, MemoryError } from './types.js'
+import { conditionsSchema, draftSchema, MemoryError, sourceSchema } from './types.js'
+import { reviewRecallContext } from './evaluationContext.js'
const id = z.string().min(1).max(200).regex(/^[A-Za-z0-9_.:-]+$/)
const hash = z.string().regex(/^[a-f0-9]{64}$/)
@@ -19,8 +20,8 @@ const suiteSchema = z.object({ schemaVersion: z.literal(1), suite: id, cases: z.
const recordSchema = draftSchema.safeExtend({ schemaVersion: z.literal(1), id, revision: count.positive(),
state: z.enum(['active', 'tentative', 'needs_verification', 'superseded', 'archived']), createdAt: count, updatedAt: count })
const contextSchema = z.object({ text: z.string().max(16_000), bytes: count, maxBytes: count.max(16_000), estimatedTokens: count })
-const packetSchema = z.object({ type: z.literal('coding_memory_context'), items: z.array(z.object({ id, revision: count.positive() })).max(6) })
const resultSchema = z.object({ id, outcome: z.object({ state: z.string() }),
+ recallFormat: z.enum(['summary', 'source_excerpts']).optional(), capturedSources: z.array(sourceSchema).max(512).optional(),
episodes: z.object({ expected: count, reviewed: count, jobs: z.record(z.string(), count),
boundary: z.enum(['complete', 'bounded']).optional() }).optional(),
checks: z.array(z.object({ name: z.string(), passed: z.boolean().nullable() })),
@@ -58,7 +59,11 @@ export function prepareEvaluationReview(suiteText: string, reportText: string) {
unique(f.probes.map(p => p.id))
const episodes = f.episodes ?? [{ id: f.id, sources: f.sources! }]
unique(episodes.map(e => e.id))
+ const originals = episodes.flatMap(e => e.sources.map((s, index) => ({
+ id: `${f.id}${f.episodes ? `-${e.id}` : ''}-${index}`, projectId: f.projectId,
+ episode: e.id, boundary: f.boundary ?? 'complete', ...s })))
const result = report.cases.find(row => row.id === f.id)
+ const formats = new Map<string, 'summary' | 'source_excerpts' | null>()
if (result) {
// Older diagnostics always captured complete episodes. A bounded fixture must have an
// explicit matching observation; do not grade it as if omitted context had been supplied.
@@ -72,7 +77,10 @@ export function prepareEvaluationReview(suiteText: string, reportText: string) {
unique(p.returnedIds)
if (p.returnedIds.some(id => !result.records.some(record => record.id === id))) throw new MemoryError('unknown_recalled_memory')
if (p.context) {
- const sent = p.context.text ? decode(packetSchema, p.context.text).items : []
+ const reviewed = reviewRecallContext({ text: p.context.text, records: result.records,
+ declaredFormat: result.recallFormat, capturedSources: result.capturedSources, originals })
+ const sent = reviewed.items
+ formats.set(p.id, reviewed.format)
if (p.context.bytes !== Buffer.byteLength(p.context.text, 'utf8') || p.context.bytes > p.context.maxBytes
|| canonical(sent.map(item => item.id)) !== canonical(p.returnedIds)
|| sent.some(item => !result.records.some(record => record.id === item.id && record.revision === item.revision))) {
@@ -88,11 +96,12 @@ export function prepareEvaluationReview(suiteText: string, reportText: string) {
&& result.checks.some(check => check.name === 'completed_extraction' && check.passed === true)
&& result.probes.every(p => p.status === 'ok')
return { id: f.id, projectId: f.projectId, completed, criteria: f.expected.review,
- sources: episodes.flatMap(e => e.sources.map((s, index) => ({
- id: `${f.id}${f.episodes ? `-${e.id}` : ''}-${index}`, episode: e.id, boundary: f.boundary ?? 'complete', ...s }))),
- records: result?.records ?? [], probes: f.probes.map(p => ({ ...p,
- returnedIds: result?.probes.find(actual => actual.id === p.id)?.returnedIds ?? [],
- context: result?.probes.find(actual => actual.id === p.id)?.context ?? null })),
+ sources: originals,
+ records: result?.records ?? [], probes: f.probes.map(p => {
+ const actual = result?.probes.find(actual => actual.id === p.id)
+ return { ...p, returnedIds: actual?.returnedIds ?? [],
+ context: actual?.context ? { ...actual.context, format: formats.get(p.id) ?? null } : null }
+ }),
mechanicalFailures: result?.checks.filter(check => check.passed === false).map(check => check.name) ?? [] }
})
return { schemaVersion: 1 as const, reportSha256, suiteSha256, suite: suite.suite,
@@ -155,10 +164,12 @@ export function scoreEvaluationReview(suiteText: string, reportText: string, rev
})
return { schemaVersion: 1, reportSha256: packet.reportSha256, suiteSha256: packet.suiteSha256,
evidence: packet.evidence, reviewer: review.reviewer,
+ contextFormats: [...new Set(packet.cases.flatMap(row => row.probes.flatMap(p => p.context?.format ? [p.context.format] : [])))],
coverage: { completedCases: packet.cases.filter(row => row.completed).length, expectedCases: packet.cases.length },
memories: metric(memories, packet.completed), recall: metric(recalls, packet.completed), abstention: metric(abstentions, packet.completed),
cases, taskBenefit: 'not_measured', nativeDelivery: 'not_measured',
limitations: ['Ratings are attributed judgements, not authenticated independent review.',
+ 'Exact source and metadata checks do not establish faithful meaning or complete surrounding context.',
'These diagnostics do not satisfy the held-out-history or paired coding-task release gates.',
'Older reports without captured recall context can be reviewed for memory content but receive no recall-quality rate.',
'Empty, unfinished or partially reviewed denominators never receive a passing rate.'] }
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 c4ba3fe8f..0ab79f5d3 100644
--- a/docs/plans/2026-09-30-coding-memory-review-log.md
+++ b/docs/plans/2026-09-30-coding-memory-review-log.md
@@ -1002,3 +1002,45 @@ Code Mode for that model independently of those feature switches. Neither the
execution host nor a different model is enabled to make this test pass, and the
adapter's error rejection remains intact. [Conditions and source identities](../research/2026-10-02-codex-memory-0160/conditions.json)
separate this transport evidence from the still-open quality and usefulness gates.
+
+### Score the source context actually recalled — October 2
+
+Extraction diagnostics now request the source-excerpt format used by native recall.
+`--recall-format summary` retains the earlier format as an explicit comparison arm.
+Reports include sanitized source snapshots captured before maintenance. Review checks
+each packet's exact excerpts, author role, engine, timestamp, verification metadata,
+record revision, scope, source links and evidence-field coverage. The validator does
+not call the production serializer. It binds captured text and role to the frozen
+fixture and rejects missing, duplicated, altered or extra supporting material.
+
+Older summary reports remain reviewable and keep their format label; they do not
+acquire source-validation evidence retroactively. Review scores name the context
+formats inspected, and the offline runner records the validator's source hash.
+Neither exact text nor a matching hash proves semantic support or authentic authorship.
+The attributed reviewer still assesses meaning, qualifications, relevance and missing
+knowledge. Unsupported stored records continue to fail correct-memory recall even
+when their source packet preserves the original words.
+
+A private offline replay used only five previously consented excerpts and their six
+already-generated proposals. It made no new model calls. The original record-quality
+judgements were retained and the new packets inspected against their frozen sources.
+All three positive source contexts preserved the original full excerpt, including
+qualifications, compared with one faithful positive summary context. **Both formats
+still scored four of six supported/useful records and one of three fully correct
+recalls.** All twelve negative probes abstained. The two overbroad records remain
+failures; these results do not establish improved extraction or coding-task outcomes.
+
+The replay preserved project scope, text, source role/engine, bounded context and
+probes. Only disposable profile/source identifiers and generated replay metadata
+changed, with mappings retained privately. Original files and production memory were
+read-only. The OS sandbox denied networking and limited writes to the private test
+folder. An initial SQLite temporary-file failure was preserved; directing temporary
+files into that folder allowed the replay to finish under the same restrictions.
+All excerpts, records, labels, hashes and detailed reports remain local. This is a
+small, attributed development review, not independent or held-out release evidence.
+
+The storage failure also exposed a separate diagnosis problem: an unexpected store
+error can surface as `waiting_for_model / inference_unavailable`. That classification
+needs a focused follow-up; it does not explain the live provider blockage without
+additional evidence. Live automatic learning, wider native lifecycles and the
+planned quality/benefit gates remain unfinished.