The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Show the latest coding memory recall for open sessions (#553)
Dee1e9352c80220
diff --git a/cli/scripts/memory-benchmark.ts b/cli/scripts/memory-benchmark.tsindex 232e678a1..9814ed8ce 100644--- a/cli/scripts/memory-benchmark.ts+++ b/cli/scripts/memory-benchmark.ts@@ -13,14 +13,28 @@ import type { RecallPacket, RecallRequest } from '../src/memory/types.js'const receiptMode = process.argv.includes('--receipts')const notebookMode = process.argv.includes('--notebooks')const feedbackMode = process.argv.includes('--feedback')-if ([receiptMode, notebookMode, feedbackMode].filter(Boolean).length > 1) throw new Error('Choose one benchmark mode')+const activityMode = process.argv.includes('--activity')+if ([receiptMode, notebookMode, feedbackMode, activityMode].filter(Boolean).length > 1) throw new Error('Choose one benchmark mode')const directory = await mkdtemp(join(tmpdir(), 'harness-memory-benchmark-'))const binding = { engine: 'codex' as const, sessionId: 'synthetic_session', projectId: 'project_1', route: 'prompt_hook' as const }-const access = { profileId: 'benchmark', projectIds: ['project_1'], includeProfile: receiptMode || feedbackMode }+const access = { profileId: 'benchmark', projectIds: ['project_1'], includeProfile: receiptMode || feedbackMode || activityMode }const query = { query: 'fixture_5321', conditions: { taskType: 'debugging' } }let client: MemoryClient | undefined+const activitySamples: number[] = []+let largestActivityBytes = 0+const receivers = [{ agentId: 'active', engine: binding.engine, sessionId: binding.sessionId },+ ...Array.from({ length: 127 }, (_, i) => ({ agentId: `open_${i}`, engine: binding.engine, sessionId: `receiver_${4_000 + i}` }))]+async function activity(): Promise<void> {+ if (!activityMode) return+ const started = performance.now()+ const result = await client!.request('libraryActivity', ['benchmark', receivers, { agentId: 'active' }])+ activitySamples.push(performance.now() - started)+ if (result.sessions.length !== 128 || result.selectedAgentId !== 'active' || !result.items.length+ || result.items.some(item => item.record.scope.projectId !== 'project_1')) throw new Error('activity_mismatch')+ largestActivityBytes = Math.max(largestActivityBytes, Buffer.byteLength(JSON.stringify(result)))+}async function recall(request: RecallRequest): Promise<RecallPacket> {- if (!receiptMode) return client!.recall(request, access)+ if (!receiptMode && !activityMode) return client!.recall(request, access)try { return (await client!.request('prepareRecall', [request, binding, access], 200)).packet }catch (error) { if ((error as { code?: string }).code !== 'memory_deadline') throw errorreturn { status: 'timeout', items: [], text: '', estimatedTokens: 0 } }@@ -48,9 +62,10 @@ try {validity: { validFrom: null, validUntil: null, recheckWhen: [] } }store.propose(draft, { profileId: 'benchmark', projectIds: [projectId], includeProfile: false })}- if (receiptMode) {+ if (receiptMode || activityMode) {const first = store.prepareRecall(query, binding, access).receipt!- for (let i = 0; i < 5_000; i++) store.prepareRecall(query, binding, access)+ for (let i = 0; i < 5_000; i++) store.prepareRecall(query,+ activityMode ? { ...binding, sessionId: `receiver_${i}` } : binding, access)if (store.recallEmitted(first.id, binding, access)) throw new Error('receipt_cap_not_applied')}if (feedbackMode) {@@ -132,6 +147,7 @@ try {cold.push(performance.now() - start)if (packet.status === 'timeout') timeouts++else if (packet.status !== 'ok' || !packet.items.some(item => item.claim.includes('fixture_5321'))) throw new Error('cold_recall_mismatch')+ if (packet.status === 'ok') await activity()await client.close(); client = undefined}client = new MemoryClient({ directory, profileId: 'benchmark', source: workerSource })@@ -147,16 +163,19 @@ try {if (packet.status === 'timeout') timeouts++else if (packet.status !== 'ok' || !packet.items.length || packet.items.some(item => item.scope.projectId !== 'project_1')) throw new Error('warm_recall_mismatch')largestPacket = Math.max(largestPacket, Buffer.byteLength(packet.text))+ if (packet.status === 'ok') await activity()}} finally { lag.disable() }const summary = (values: number[]) => {values.sort((a, b) => a - b)return { p50Ms: values[Math.ceil(values.length * .5) - 1], p95Ms: values[Math.ceil(values.length * .95) - 1], maxMs: values.at(-1) }}- console.log(JSON.stringify({ kind: 'synthetic-memory-performance', mode: feedbackMode ? 'recall-with-contextual-feedback' : receiptMode ? 'prepare-with-full-receipt-history' : 'recall',- retainedReceipts: receiptMode || feedbackMode ? 5_000 : 0, ratedContexts: feedbackMode ? 5_000 : 0, records: count, projects: 10, node: process.version,+ console.log(JSON.stringify({ kind: 'synthetic-memory-performance', mode: activityMode ? 'prepare-and-owner-activity' : feedbackMode ? 'recall-with-contextual-feedback' : receiptMode ? 'prepare-with-full-receipt-history' : 'recall',+ retainedReceipts: receiptMode || feedbackMode || activityMode ? 5_000 : 0, ratedContexts: feedbackMode ? 5_000 : 0, records: count, projects: 10, node: process.version,platform: platform(), arch: arch(), seedMs, cold: summary(cold), warm: summary(warm), requests: cold.length + warm.length,timeouts, largestPacketBytes: largestPacket, parentEventLoopP95Ms: lag.percentile(95) / 1e6,+ ...(activityMode ? { latestAttempts: 5_000, openSessions: receivers.length,+ activityAfterRecall: summary(activitySamples), activityRequests: activitySamples.length, largestActivityBytes } : {}),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.'] }, null, 2))}diff --git a/cli/src/memory/activity.spec.ts b/cli/src/memory/activity.spec.tsnew file mode 100644index 000000000..0a0052a5f--- /dev/null+++ b/cli/src/memory/activity.spec.ts@@ -0,0 +1,127 @@+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 { MemoryRecord, MemoryDraft, SourceEvent } from './types.js'+import type { ActivityReceiver } from './receipts.js'++let directory: string, store: CodingMemoryStore, now: number, memory: MemoryRecord+const receiver: ActivityReceiver = { agentId: 'working-agent', engine: 'codex', sessionId: 'private_receiver_lemur' }+const source: SourceEvent = { id: 'source', profileId: 'owner', projectId: null, engine: 'claude',+ sessionId: 'source-session', nativeEventId: 'source', role: 'user', eligibility: 'coding', observedAt: 900,+ rootIds: ['source'], text: 'For regression fixes, start with a small failing test.' }+const draft: MemoryDraft = { kind: 'working_preference', facet: 'testing', assertionType: 'stated_preference',+ scope: { profileId: 'owner' }, claim: source.text, rationale: null, futureAction: 'Start with a small failing test.',+ applicability: { task: 'bug_fix' }, exceptions: [], retrievalCues: ['regression'], evidenceClass: 'user_stated',+ evidence: [{ sourceEventId: 'source', quote: source.text, paths: ['/claim', '/futureAction', '/applicability'] }],+ conflictKey: 'test-first', validity: { validFrom: null, validUntil: null, recheckWhen: [] } }+const access = { profileId: 'owner', projectIds: ['project'], includeProfile: true }+const activity = (selected = receiver.agentId, receivers = [receiver]) => store.libraryActivity('owner', receivers, { agentId: selected })+function recall(query = 'regression', recipient = receiver, route: 'mcp' | 'prompt_hook' = 'prompt_hook') {+ ++now+ return store.prepareRecall({ query, conditions: { task: 'bug_fix' } },+ { engine: recipient.engine, sessionId: recipient.sessionId, projectId: 'project', route }, access)+}+function sql(run: (db: Database) => void) {+ const DB = builtinSqlite() as unknown as new(path: string) => Database+ const db = new DB(join(directory, 'memory.sqlite'))+ try { run(db) } finally { db.close() }+}+beforeEach(() => {+ directory = mkdtempSync(join(tmpdir(), 'memory-activity-')); 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.setControls({ learn: true, recall: true })+ store.ingest(source); memory = store.propose(draft, access).record+})+afterEach(() => { store.close(); rmSync(directory, { recursive: true, force: true }) })++it('shows the exact current selection and conditions without claiming model delivery', () => {+ const prepared = recall('regression private_prompt_capuchin')+ expect(activity()).toMatchObject({ selectedAgentId: receiver.agentId,+ sessions: [{ preparedAt: now, selectedCount: 1, delivery: 'unverified', emittedAt: null }],+ items: [{ record: { id: memory.id, revision: 1, applicability: { task: 'bug_fix' } },+ recall: { receiptId: prepared.receipt!.id, canFeedback: true, delivery: 'unverified' } }] })+ expect(store.recallEmitted(prepared.receipt!.id, { engine: receiver.engine, sessionId: receiver.sessionId,+ projectId: 'project', route: 'prompt_hook' }, access)).toBe(true)+ expect(activity().sessions[0]).toMatchObject({ emittedAt: now, delivery: 'unverified' })+})++it('replaces a positive selection with the latest empty recall without inventing a new history receipt', () => {+ const earlier = recall()+ const empty = recall('orchids', receiver, 'mcp')+ expect(empty.receipt).toBeNull()+ expect(activity()).toMatchObject({ sessions: [{ status: 'ok', selectedCount: 0, receiptId: null, preparedAt: now }], items: [] })+ expect(store.libraryDetail('owner', memory.id)!.recalls[0].receiptId).toBe(earlier.receipt!.id)+ const bytes = readFileSync(join(directory, 'memory.sqlite'))+ expect(bytes.includes(Buffer.from(receiver.sessionId))).toBe(false)+ expect(bytes.includes(Buffer.from('orchids'))).toBe(false)+})++it('separates receiving sessions and engines and does not silently switch a selected session', () => {+ recall()+ const other = { ...receiver, agentId: 'other', engine: 'claude' as const }+ recall('orchids', other)+ expect(activity(receiver.agentId, [receiver, other]).items).toHaveLength(1)+ expect(activity('other', [receiver, other]).items).toEqual([])+ expect(activity('missing', [receiver, other])).toMatchObject({ selectedAgentId: 'missing', items: [] })+ expect(activity(receiver.agentId, [{ ...receiver, sessionId: 'resumed-conversation' }]).sessions).toEqual([])+ expect(() => store.libraryActivity('another-owner', [receiver])).toThrow('scope_denied')+ expect(() => store.libraryActivity('owner', Array(129).fill(receiver))).toThrow('invalid_input')+})++it.each(['source', 'receiver', 'project'] as const)('withholds %s privacy changes and does not resurrect receiver activity', which => {+ recall()+ if (which === 'source') store.setSessionIncluded('claude', source.sessionId, false)+ if (which === 'receiver') store.setSessionIncluded(receiver.engine, receiver.sessionId, false)+ if (which === 'project') store.setProjectIncluded('project', false)+ expect(activity().items).toEqual([])+ if (which !== 'source') {+ expect(activity().sessions).toEqual([])+ if (which === 'receiver') store.setSessionIncluded(receiver.engine, receiver.sessionId, true)+ else store.setProjectIncluded('project', true)+ expect(activity().sessions).toEqual([])+ }+})++it('honors privacy set by an earlier writer and clears the old activity when reincluded', () => {+ recall()+ sql(db => db.prepare('UPDATE projects SET included=0 WHERE id=?').run('project'))+ expect(activity().sessions).toEqual([])+ store.setProjectIncluded('project', true)+ expect(activity().sessions).toEqual([])+})++it('never displays a corrected revision as if it were the version recalled earlier', () => {+ recall()+ const preview = store.libraryPreview('owner', { kind: 'narrow', id: memory.id, revision: 1, projectId: 'project' })+ store.libraryApply('owner', preview.command, preview.version, false)+ expect(activity()).toMatchObject({ sessions: [{ selectedCount: 1 }], items: [] })+ recall()+ expect(activity().items[0].record.revision).toBe(2)+ store.libraryForget('owner', memory.id, 2)+ expect(activity().items).toEqual([])+})++it('keeps feedback available for an exact selection outside the per-memory ten-session history', () => {+ const prepared = recall()+ for (let i = 0; i < 15; i++) recall('regression', { ...receiver, agentId: `agent-${i}`, sessionId: `session-${i}` })+ expect(store.libraryDetail('owner', memory.id)!.recalls.some(r => r.receiptId === prepared.receipt!.id)).toBe(false)+ expect(activity().items[0].recall.receiptId).toBe(prepared.receipt!.id)+ const preview = store.libraryPreview('owner', { kind: 'feedback', id: memory.id, revision: 1,+ receiptId: prepared.receipt!.id, value: 'helpful', expected: 0 })+ store.libraryApply('owner', preview.command, preview.version, false)+ expect(activity().items[0].recall.feedback.value).toBe('helpful')+})++it('does not infer current activity from legacy positive-only history or expired attempts', () => {+ recall()+ sql(db => db.prepare('DELETE FROM memory_recall_latest').run())+ expect(store.libraryDetail('owner', memory.id)!.recalls).toHaveLength(1)+ expect(activity().sessions).toEqual([])+ recall(); now += 30 * 86_400_000+ expect(activity().sessions).toEqual([])+})diff --git a/cli/src/memory/control.spec.ts b/cli/src/memory/control.spec.tsindex c298c9869..60aaeb6d2 100644--- a/cli/src/memory/control.spec.ts+++ b/cli/src/memory/control.spec.ts@@ -5,7 +5,7 @@ import type { CallerVerdict } from '../pair/learn/approval.js'import { isOwnerProcess } from './ownerProcess.js'let owner: string | null, now: number, control: MemoryControl-let runtime: Pick<CodingMemoryRuntime, 'ownerKey' | 'libraryStatus' | 'libraryPage' | 'libraryProjects' | 'libraryNotebooks' | 'libraryNotebook' | 'libraryDetail' | 'libraryPreview' | 'libraryApply'>+let runtime: Pick<CodingMemoryRuntime, 'ownerKey' | 'libraryStatus' | 'libraryPage' | 'libraryProjects' | 'libraryActivity' | 'libraryNotebooks' | 'libraryNotebook' | 'libraryDetail' | 'libraryPreview' | 'libraryApply'>let verify: ReturnType<typeof vi.fn<(id: string) => Promise<CallerVerdict>>>const command = { kind: 'forget' as const, id: 'memory', revision: 1 }const preview = { command, version: { generation: 1, knowledge: 1, preferences: 'hash' }, effects: { deletedIds: ['memory'] } }@@ -15,6 +15,7 @@ beforeEach(() => {libraryStatus: vi.fn(async () => ({ runtime: { state: 'ready' as const }, preferences: { learn: true, recall: true }, queue: {} as never })),libraryPage: vi.fn(async () => ({ items: [], nextCursor: null, version: preview.version })),libraryProjects: vi.fn(async () => ({ items: [], nextBefore: null })),+ libraryActivity: vi.fn(async () => ({ sessions: [], selectedAgentId: null, items: [], version: preview.version })),libraryNotebooks: vi.fn(async () => ({ items: [], nextCursor: null, version: preview.version })),libraryNotebook: vi.fn(async () => null),libraryDetail: vi.fn(async () => null), libraryPreview: vi.fn(async () => structuredClone(preview)),@@ -46,6 +47,13 @@ it('routes bounded project search through the verified current owner', async ()expect(await request({ action: 'projects', query: { limit: 500 } })).toMatchObject({ error: 'INVALID_INPUT' })})+it('keeps activity owner-only and derives native receiver identity from the host', async () => {+ expect(await request({ action: 'activity', token: 'agent' })).toMatchObject({ error: 'PERSON_ONLY' })+ expect(await request({ action: 'activity', query: { sessionId: 'claimed-native' } })).toMatchObject({ error: 'INVALID_INPUT' })+ expect(await request({ action: 'activity', query: { agentId: 'open-agent' } })).toMatchObject({ ok: true, items: [] })+ expect(runtime.libraryActivity).toHaveBeenCalledExactlyOnceWith('owner', { agentId: 'open-agent' })+})+it('keeps notebook browsing owner-only and bounded, including direct page requests', async () => {for (const payload of [{ action: 'notebooks' }, { action: 'notebook', id: 'notebook:one' }]) {expect(await request({ ...payload, token: 'agent' })).toMatchObject({ error: 'PERSON_ONLY' })diff --git a/cli/src/memory/control.ts b/cli/src/memory/control.tsindex 0c24ddf76..0779382d6 100644--- a/cli/src/memory/control.ts+++ b/cli/src/memory/control.ts@@ -1,7 +1,7 @@/** Local owner controls. Agent tools get a different, host-scoped recall path. */import { randomBytes } from 'node:crypto'import { z } from 'zod'-import { libraryCommandSchema, libraryQuerySchema, libraryProjectQuerySchema, notebookQuerySchema, type LibraryPreview } from './library.js'+import { libraryCommandSchema, libraryQuerySchema, libraryProjectQuerySchema, notebookQuerySchema, libraryActivityQuerySchema, type LibraryPreview } from './library.js'import { MemoryError, parse } from './types.js'import type { CodingMemoryRuntime } from './runtime.js'import type { CallerVerdict } from '../pair/learn/approval.js'@@ -13,13 +13,14 @@ const requestSchema = z.discriminatedUnion('action', [z.object({ action: z.literal('configure_experiment'), enabled: z.boolean(), expected: z.number().int().nonnegative().safe() }).strict(),z.object({ action: z.literal('list'), query: libraryQuerySchema.optional() }).strict(),z.object({ action: z.literal('projects'), query: libraryProjectQuerySchema.optional() }).strict(),+ z.object({ action: z.literal('activity'), query: libraryActivityQuerySchema.optional() }).strict(),z.object({ action: z.literal('notebooks'), query: notebookQuerySchema.optional() }).strict(),z.object({ action: z.literal('notebook'), id: z.string().min(1).max(200) }).strict(),z.object({ action: z.literal('show'), id: z.string().min(1).max(200) }).strict(),z.object({ action: z.literal('preview'), command: libraryCommandSchema }).strict(),z.object({ action: z.literal('apply'), capability: z.string().regex(/^[0-9a-f]{32}$/) }).strict(),])-type Runtime = Pick<CodingMemoryRuntime, 'ownerKey' | 'libraryStatus' | 'libraryPage' | 'libraryProjects' | 'libraryNotebooks' | 'libraryNotebook' | 'libraryDetail' | 'libraryPreview' | 'libraryApply'>+type Runtime = Pick<CodingMemoryRuntime, 'ownerKey' | 'libraryStatus' | 'libraryPage' | 'libraryProjects' | 'libraryActivity' | 'libraryNotebooks' | 'libraryNotebook' | 'libraryDetail' | 'libraryPreview' | 'libraryApply'>interface Deps {runtime(): Runtime | null/** Must verify the OS owner as well as rejecting a process inside an agent's harness. */@@ -71,6 +72,7 @@ export class MemoryControl {case 'status': return { ok: true, ...await runtime.libraryStatus(owner) }case 'list': return { ok: true, ...await runtime.libraryPage(owner, request.query) }case 'projects': return { ok: true, ...await runtime.libraryProjects(owner, request.query) }+ case 'activity': return { ok: true, ...await runtime.libraryActivity(owner, request.query) }case 'notebooks': return { ok: true, ...await runtime.libraryNotebooks(owner, request.query) }case 'notebook': {const detail = await runtime.libraryNotebook(owner, request.id)diff --git a/cli/src/memory/hostSessions.spec.ts b/cli/src/memory/hostSessions.spec.tsindex bb824e64a..370b9f908 100644--- a/cli/src/memory/hostSessions.spec.ts+++ b/cli/src/memory/hostSessions.spec.ts@@ -20,9 +20,10 @@ it('admits coding processes and bundled coding DSHs while excluding other domainit('retains a recently exited process long enough to capture its final native reply, without archive discovery', () => {let now = 1_000const roster = new MemorySessionRoster('/home/person', () => now)- roster.refresh([session], () => true, no)+ expect(roster.refresh([{ ...session, title: 'Parser fixes' }], () => true, no))+ .toMatchObject([{ present: true, name: 'Parser fixes' }])now += 10_000- expect(roster.refresh([], no, no)).toMatchObject([{ sessionId: 'native', busy: false }])+ expect(roster.refresh([], no, no)).toMatchObject([{ sessionId: 'native', busy: false, present: false }])now += 120_001expect(roster.refresh([], no, no)).toEqual([])})diff --git a/cli/src/memory/hostSessions.ts b/cli/src/memory/hostSessions.tsindex 17e7c5839..adc614342 100644--- a/cli/src/memory/hostSessions.ts+++ b/cli/src/memory/hostSessions.ts@@ -12,6 +12,7 @@ export function hasMemoryForegroundActivity(events: readonly Pick<LiveEvent, 'tyinterface RegisteredMemorySession {agentId: string; engine: string; sessionId: string; cwd: string | null; transcriptPath: string | nulldsh?: string | null; forkedFrom?: unknown; registeredAt: number; cliVersion?: string | null+ title?: string | null; defaultName?: string}// These bundled DSHs have explicit software-development workflows. A package's arbitrary category// string, viewer, or use of a coding CLI cannot opt a general-domain DSH into personal coding memory.@@ -34,6 +35,7 @@ export class MemorySessionRoster {|| resolve(session.cwd) === parse(resolve(session.cwd)).root) continuecurrent.add(session.agentId)this.recent.set(session.agentId, { seenAt: this.now(), session: { agentId: session.agentId,+ name: session.title || session.defaultName, present: true,engine: session.engine as 'claude' | 'codex', sessionId: session.sessionId, workspace: session.cwd,transcriptPath: session.transcriptPath, coding: true, busy: busy(session.sessionId), scope: companion ? 'profile' : 'project',...(session.cliVersion ? { cliVersion: session.cliVersion } : {}),@@ -42,7 +44,7 @@ export class MemorySessionRoster {for (const [agentId, row] of this.recent) {if ((row.session.scope === 'profile' && agentId !== collectionAgentId)|| (observed.has(agentId) && !current.has(agentId)) || this.now() - row.seenAt > 120_000) this.recent.delete(agentId)- else if (!current.has(agentId)) row.session = { ...row.session, busy: false }+ else if (!current.has(agentId)) row.session = { ...row.session, busy: false, present: false }}while (this.recent.size > 128) this.recent.delete(this.recent.keys().next().value!)return [...this.recent.values()].map(row => ({ ...row.session }))diff --git a/cli/src/memory/library.ts b/cli/src/memory/library.tsindex 23cbdc1cd..f403292f7 100644--- a/cli/src/memory/library.ts+++ b/cli/src/memory/library.ts@@ -1,7 +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'+import type { MemoryRecallUse, RecallFeedback, RecallActivity } from './receipts.js'import type { NotebookState } from './notebook.js'import type { TopicPage } from './types.js'@@ -15,6 +15,15 @@ export const libraryQuerySchema = z.object({state: z.enum(['active', 'tentative', 'needs_verification', 'superseded', 'archived']).optional(),}).strict()export type LibraryQuery = z.infer<typeof libraryQuerySchema>+export const libraryActivityQuerySchema = z.object({ agentId: id.optional() }).strict()+export type LibraryActivityQuery = z.infer<typeof libraryActivityQuerySchema>+export interface LibraryActivity {+ sessions: Array<Omit<RecallActivity, 'projectId'> & { project: LibraryProject | null }>+ selectedAgentId: string | null+ items: Array<{ record: MemorySummary & Pick<MemoryRecord, 'applicability' | 'rationale' | 'futureAction' | 'exceptions'>+ recall: LibraryDetail['recalls'][number] }>+ version: LibraryPage['version']+}export const libraryProjectQuerySchema = z.object({search: z.string().trim().max(200).optional(),before: z.number().int().positive().safe().optional(),diff --git a/cli/src/memory/operations.ts b/cli/src/memory/operations.tsindex 662a6fdac..347e20a27 100644--- a/cli/src/memory/operations.ts+++ b/cli/src/memory/operations.ts@@ -6,7 +6,7 @@ export type MemoryOperations = Pick<CodingMemoryStore,'controls' | 'setControls' | 'preferences' | 'setPreferences' | 'changePreferences' | 'maintain' | 'registerProject' | 'projectForLocator' | 'linkProjectLocator' | 'setProjectIncluded'| 'sessionPolicy' | 'setSessionIncluded' | 'capturePolicy'| 'ingest' | 'source' | 'propose' | 'revise' | 'correctFromUser' | 'read' | 'history' | 'support' | 'list' | 'recall'- | 'libraryPage' | 'libraryProjects' | 'libraryDetail' | 'libraryCorrect' | 'libraryForget' | 'libraryPreview' | 'libraryApply'+ | 'libraryPage' | 'libraryProjects' | 'libraryActivity' | 'libraryDetail' | 'libraryCorrect' | 'libraryForget' | 'libraryPreview' | 'libraryApply'| 'notebookPending' | 'notebookClaim' | 'notebookFinish' | 'notebookDefer' | 'libraryNotebooks' | 'libraryNotebook'| 'prepareRecall' | 'recallEmitted' | 'recallReceipts' | 'putTopic' | 'topic' | 'forget'>& Pick<MemoryQueue, 'capture' | 'checkpoint' | 'pendingReview' | 'claim' | 'finish' | 'defer' | 'cursor' | 'episodeOpen' | 'status'>@@ -18,7 +18,7 @@ export type MemoryPort = { request<K extends Operation>(operation: K, args: Arguexport const STORE_OPERATIONS = ['controls', 'setControls', 'preferences', 'setPreferences', 'changePreferences', 'maintain', 'registerProject', 'projectForLocator', 'linkProjectLocator', 'setProjectIncluded','sessionPolicy', 'setSessionIncluded', 'capturePolicy','ingest', 'source', 'propose', 'revise', 'correctFromUser', 'read', 'history', 'support', 'list', 'recall',- 'libraryPage', 'libraryProjects', 'libraryDetail', 'libraryCorrect', 'libraryForget', 'libraryPreview', 'libraryApply',+ 'libraryPage', 'libraryProjects', 'libraryActivity', 'libraryDetail', 'libraryCorrect', 'libraryForget', 'libraryPreview', 'libraryApply','notebookPending', 'notebookClaim', 'notebookFinish', 'notebookDefer', 'libraryNotebooks', 'libraryNotebook','prepareRecall', 'recallEmitted', 'recallReceipts', 'putTopic', 'topic', 'forget'] as constexport const QUEUE_OPERATIONS = ['capture', 'checkpoint', 'pendingReview', 'claim', 'finish', 'defer', 'cursor', 'episodeOpen', 'status'] as constdiff --git a/cli/src/memory/receipts.ts b/cli/src/memory/receipts.tsindex f842cd178..3204cab2a 100644--- a/cli/src/memory/receipts.ts+++ b/cli/src/memory/receipts.ts@@ -34,6 +34,15 @@ export interface MemoryRecallUse {feedback: RecallFeedbackcanGuideRecall: boolean}+/** Ephemeral host identities are supplied by the runtime, never persisted in activity rows. */+export const activityReceiversSchema = z.array(z.object({ agentId: id,+ engine: z.enum(['claude', 'codex']), sessionId: id }).strict()).max(128)+export type ActivityReceiver = z.infer<typeof activityReceiversSchema>[number]+export interface RecallActivity {+ agentId: string; engine: MemoryDeliveryBinding['engine']; projectId: string | null+ preparedAt: number; status: RecallPacket['status']; selectedCount: number+ receiptId: string | null; emittedAt: number | null; delivery: 'unverified'+}interface Deps {db: Database; profileId: string; now(): numbertransaction<T>(run: () => T): T@@ -72,6 +81,12 @@ export const RECEIPT_SCHEMA = `PRIMARY KEY(memory_id,revision,context_key));CREATE INDEX IF NOT EXISTS memory_feedback_receipt ON memory_recall_feedback(receipt_id);+ CREATE TABLE IF NOT EXISTS memory_recall_latest (+ session_key TEXT PRIMARY KEY, engine TEXT NOT NULL, project_id TEXT,+ prepared_at INTEGER NOT NULL, status TEXT NOT NULL, selected_count INTEGER NOT NULL,+ receipt_id TEXT REFERENCES memory_receipts(id) ON DELETE SET NULL+ );+ CREATE INDEX IF NOT EXISTS memory_recall_latest_age ON memory_recall_latest(prepared_at);`export class MemoryReceipts {@@ -81,6 +96,17 @@ export class MemoryReceipts {const binding = parse(bindingSchema, input)return this.deps.transaction(() => {if (!this.deps.allowed(binding, access)) return { packet: empty('denied'), receipt: null }+ const finish = (packet: RecallPacket, receipt: RecallReceipt | null): PreparedRecall => {+ // One content-free latest attempt per native session, including empty/off recalls.+ // Without this marker a later empty result would leave an earlier selection looking current.+ this.deps.db.prepare(`INSERT INTO memory_recall_latest VALUES(?,?,?,?,?,?,?)+ ON CONFLICT(session_key) DO UPDATE SET engine=excluded.engine,project_id=excluded.project_id,+ prepared_at=excluded.prepared_at,status=excluded.status,selected_count=excluded.selected_count,+ receipt_id=excluded.receipt_id`).run(this.sessionKey(binding.engine, binding.sessionId), binding.engine,+ binding.projectId, this.deps.now(), packet.status, packet.items.length, receipt?.id ?? null)+ this.prune()+ return { packet, receipt }+ }// Reserve the receipt field inside the same byte budget as the actual context. Empty recalls// do not allocate audit rows, and neither raw prompts nor recalled claims are stored here.const budget = typeof request.maxBytes === 'number' && Number.isFinite(request.maxBytes)@@ -90,12 +116,12 @@ export class MemoryReceipts {withdrawalNotice: 'These previously supplied memory revisions are no longer current. Do not rely on them. If more is true, use only newly supplied memory. Earlier native conversation content has not been erased.' } : {}const reserved = 64 + Buffer.byteLength(JSON.stringify(withdrawal))const packet = this.deps.recall({ ...request, maxBytes: Math.max(0, budget - reserved) }, access)- if (packet.status !== 'ok' || (!packet.items.length && !withdrawn.references.length) || reserved > budget) return { packet, receipt: null }+ if (packet.status !== 'ok' || (!packet.items.length && !withdrawn.references.length) || reserved > budget) return finish(packet, null)const receiptId = randomUUID()packet.text = JSON.stringify({ ...(packet.text ? JSON.parse(packet.text) : { type: 'coding_memory_context', items: [] }),...withdrawal, receiptId })const bytes = Buffer.byteLength(packet.text)- if (bytes > budget) return { packet: empty('ok'), receipt: null }+ if (bytes > budget) return finish(empty('ok'), null)packet.estimatedTokens = Math.ceil(bytes / 3)const queryDigest = digest([this.deps.profileId, request.query])const contextDigest = digest([this.deps.profileId, binding, access, request.conditions ?? {}])@@ -117,10 +143,9 @@ export class MemoryReceipts {// This key excludes engine/session/route but keeps the exact receiving project and context.const relevance = this.relevanceKey(access, request.conditions ?? {})if (relevance) this.deps.db.prepare('INSERT INTO memory_receipt_relevance VALUES(?,?)').run(receiptId, relevance)- this.prune()- return { packet, receipt: { id: receiptId, route: binding.route, preparedAt, emittedAt: null, delivery: 'unverified',+ return finish(packet, { id: receiptId, route: binding.route, preparedAt, emittedAt: null, delivery: 'unverified',queryDigest, contextDigest, packetDigest, bytes, estimatedTokens: packet.estimatedTokens,- items: packet.items.map(item => ({ id: item.id, revision: item.revision, current: true })) } }+ items: packet.items.map(item => ({ id: item.id, revision: item.revision, current: true })) })})}@@ -157,7 +182,7 @@ export class MemoryReceipts {}/** The caller has already verified the owner and current memory's source visibility. */- forMemory(memoryId: string, revision: number): MemoryRecallUse[] {+ forMemory(memoryId: string, revision: number, receiptId?: string): 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 (@@ -165,7 +190,7 @@ export class MemoryReceipts {ROW_NUMBER() OVER (PARTITION BY c.context_key ORDER BY r.prepared_at DESC,r.rowid DESC) AS positionFROM memory_receipts r JOIN memory_receipt_context c ON c.receipt_id=r.idJOIN memory_receipt_items i ON i.receipt_id=r.id- WHERE i.memory_id=? AND i.revision=? AND r.prepared_at>?+ WHERE i.memory_id=? AND i.revision=? AND r.prepared_at>? ${receiptId ? 'AND r.id=?' : ''}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,@@ -175,7 +200,7 @@ export class MemoryReceipts {ON f.memory_id=? AND f.revision=? AND f.context_key=r.context_keyAND 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(),+ .all(memoryId, revision, this.deps.now() - RETENTION_MS, ...(receiptId ? [receiptId] : []), 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'],@@ -237,16 +262,52 @@ export class MemoryReceipts {/** 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))+ this.deps.db.prepare('DELETE FROM memory_recall_latest WHERE session_key=?').run(this.sessionKey(engine, sessionId))}withholdProject(projectId: string): void {this.deps.db.prepare('DELETE FROM memory_receipt_context WHERE project_id=?').run(projectId)+ this.deps.db.prepare('DELETE FROM memory_recall_latest WHERE project_id=?').run(projectId)}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(SELECT id FROM memory_receipts ORDER BY prepared_at DESC,rowid DESC LIMIT -1 OFFSET ?)`).run(MAX_RECEIPTS)+ this.deps.db.prepare('DELETE FROM memory_recall_latest WHERE prepared_at<=?').run(this.deps.now() - RETENTION_MS)+ this.deps.db.prepare(`DELETE FROM memory_recall_latest WHERE session_key IN+ (SELECT session_key FROM memory_recall_latest ORDER BY prepared_at DESC,rowid DESC LIMIT -1 OFFSET ?)`).run(MAX_RECEIPTS)+ }++ /** Verified owner only. Latest attempts are never reconstructed from older positive receipts. */+ activity(input: ActivityReceiver[]): RecallActivity[] {+ const receivers = parse(activityReceiversSchema, input)+ if (new Set(receivers.map(r => r.agentId)).size !== receivers.length) throw new MemoryError('invalid_input')+ const live = receivers.map(r => ({ agentId: r.agentId, key: this.sessionKey(r.engine, r.sessionId) }))+ return this.deps.db.prepare(`SELECT l.*,json_extract(live.value,'$.agentId') AS agent_id,r.emitted_at+ FROM json_each(?) live JOIN memory_recall_latest l ON l.session_key=json_extract(live.value,'$.key')+ LEFT JOIN memory_receipts r ON r.id=l.receipt_id+ WHERE l.prepared_at>? AND l.prepared_at<=?+ AND l.session_key NOT IN (SELECT value FROM json_each(?))+ AND (l.project_id IS NULL OR EXISTS (SELECT 1 FROM projects p WHERE p.id=l.project_id AND p.included=1))+ ORDER BY l.prepared_at DESC,l.session_key`).all(JSON.stringify(live), this.deps.now() - RETENTION_MS,+ this.deps.now(), this.privateSessionKeys()).map(row => ({ agentId: String(row.agent_id),+ engine: row.engine as MemoryDeliveryBinding['engine'], projectId: row.project_id === null ? null : String(row.project_id),+ preparedAt: Number(row.prepared_at), status: row.status as RecallPacket['status'], selectedCount: Number(row.selected_count),+ receiptId: row.receipt_id === null ? null : String(row.receipt_id),+ emittedAt: row.emitted_at == null ? null : Number(row.emitted_at), delivery: 'unverified' }))+ }++ /** Current visible revisions only; corrections and privacy never expose old packet contents. */+ activityItems(receiptId: string): Array<{ id: string; revision: number }> {+ return this.deps.db.prepare(`SELECT i.memory_id,i.revision FROM memory_receipt_items i+ JOIN memories m ON m.id=i.memory_id AND m.revision=i.revision+ WHERE i.receipt_id=? AND m.state='active' AND ${visibleEvidenceSql()}+ AND (m.project_id IS NULL OR EXISTS (SELECT 1 FROM projects p WHERE p.id=m.project_id AND p.included=1))+ AND (json_extract(m.data,'$.validity.validFrom') IS NULL OR json_extract(m.data,'$.validity.validFrom')<=?)+ AND (json_extract(m.data,'$.validity.validUntil') IS NULL OR json_extract(m.data,'$.validity.validUntil')>?)+ ORDER BY i.rowid LIMIT 6`).all(receiptId, this.deps.now(), this.deps.now())+ .map(row => ({ id: String(row.memory_id), revision: Number(row.revision) }))}private withdrawn(binding: MemoryDeliveryBinding): { references: Array<{ id: string; revision: number }>; more: boolean } {diff --git a/cli/src/memory/runtime.spec.ts b/cli/src/memory/runtime.spec.tsindex d40a5286a..68e84ea9b 100644--- a/cli/src/memory/runtime.spec.ts+++ b/cli/src/memory/runtime.spec.ts@@ -96,6 +96,29 @@ it('opens no store and invokes no model while experimental, watching consent orexpect(inference.run).not.toHaveBeenCalled()})+it.each(['replace', 'mutate'] as const)('binds activity to open host sessions and rejects a native-session %s during the read', async mode => {+ await learn()+ sessions[0].name = 'Parser fixes'+ const prepared = await runtime.preparePromptRecall('agent', { query: 'coding' })+ expect(prepared.receipt).not.toBeNull()+ const calls = vi.mocked(inference.run).mock.calls.length+ expect(await runtime.libraryActivity('owner_a')).toMatchObject({+ sessions: [{ agentId: 'agent', name: 'Parser fixes' }], items: [{ record: { claim: preference } }] })+ expect(vi.mocked(inference.run).mock.calls.length).toBe(calls)+ sessions[0].present = false+ expect((await runtime.libraryActivity('owner_a')).sessions).toEqual([])+ await expect(runtime.libraryActivity('owner_a', { agentId: 'agent' })).rejects.toThrow('session_unavailable')+ sessions[0].present = true+ intercept = async operation => {+ if (operation !== 'libraryActivity') return+ if (mode === 'replace') sessions[0] = { ...sessions[0], sessionId: 'replacement' }+ else sessions[0].sessionId = 'replacement'+ }+ await expect(runtime.libraryActivity('owner_a')).rejects.toThrow('session_changed')+ intercept = undefined+ expect((await runtime.libraryActivity('owner_a')).items).toEqual([])+})+it('lets the explicit owner inspect and change saved preferences with watching off without starting capture', async () => {context.watching = falseexpect(runtime.ownerKey()).toBe('owner_a')diff --git a/cli/src/memory/runtime.ts b/cli/src/memory/runtime.tsindex 1e1e88e5b..07c4dc3ad 100644--- a/cli/src/memory/runtime.ts+++ b/cli/src/memory/runtime.ts@@ -1,5 +1,6 @@/** Local host lifecycle. Session authority and coding eligibility must come from the daemon. */import { join } from 'node:path'+import { redact } from '../pair/learn/guard.js'import { z } from 'zod'import { digest } from './admission.js'import { NativeMemoryCapture, type CaptureOutcome } from './capture.js'@@ -9,6 +10,7 @@ import { locateProject, type ProjectContext } from './project.js'import type { Arguments, MemoryPort, Operation, Result } from './operations.js'import type { MemoryPreferences } from './store.js'import type { LibraryQuery, LibraryProjectQuery, LibraryCommand, LibraryPreview, NotebookQuery } from './library.js'+import { libraryActivityQuerySchema, type LibraryActivityQuery } from './library.js'import type { PreparedRecall, RecallReceipt } from './receipts.js'import { conditionsSchema, MemoryError, parse, type RecallPacket, type RecallRequest } from './types.js'@@ -22,6 +24,9 @@ export interface MemoryHostContext {}export interface MemoryHostSession {agentId: string+ name?: string+ /** Exited sessions can remain briefly for capture, but never appear as open activity. */+ present?: booleanengine: 'claude' | 'codex'cliVersion?: string | nullsessionId: string@@ -129,6 +134,27 @@ export class CodingMemoryRuntime {return this.withOwner(owner, port => port.request('libraryProjects', [owner, query]))}+ async libraryActivity(owner: string, input: LibraryActivityQuery = {}) {+ const query = parse(libraryActivityQuerySchema, input)+ return this.withOwner(owner, async port => {+ const sessions = this.deps.sessions().filter(s => s.coding && s.sessionId && s.present !== false)+ .slice(0, 128).map(s => ({ ...s }))+ if (query.agentId && !sessions.some(s => s.agentId === query.agentId)) throw new MemoryError('session_unavailable')+ const result = await port.request('libraryActivity', [owner,+ sessions.map(({ agentId, engine, sessionId }) => ({ agentId, engine, sessionId })), query])+ // A resumed/replaced session must not inherit another native conversation's selections.+ const current = this.deps.sessions()+ if (sessions.some(s => !current.some(c => c.present !== false && c.coding && c.agentId === s.agentId+ && c.engine === s.engine && c.sessionId === s.sessionId && c.workspace === s.workspace+ && c.transcriptPath === s.transcriptPath && c.scope === s.scope && c.liveFrom === s.liveFrom))) {+ throw new MemoryError('session_changed')+ }+ return { ...result, sessions: result.sessions.map(row => ({ ...row,+ name: redact((sessions.find(s => s.agentId === row.agentId)?.name ||+ `${row.engine === 'claude' ? 'Claude' : 'Codex'} session`).slice(0, 200)) })) }+ })+ }+async libraryNotebooks(owner: string, query: NotebookQuery = {}) {return this.withOwner(owner, port => port.request('libraryNotebooks', [owner, query]))}diff --git a/cli/src/memory/store.ts b/cli/src/memory/store.tsindex 1b215dc0d..390cd3115 100644--- a/cli/src/memory/store.ts+++ b/cli/src/memory/store.ts@@ -11,7 +11,8 @@ import { admission, assertSafe, canonical, digest, proposalFingerprint } from '.import type { ProjectLocator } from './project.js'import type { Database } from './database.js'import { MemoryQueue, PENDING_RETENTION_MS, QUEUE_SCHEMA, TERMINAL_JOB_STATES } from './queue.js'-import { MemoryReceipts, RECEIPT_SCHEMA, type MemoryDeliveryBinding, type PreparedRecall, type RecallReceipt } from './receipts.js'+import { MemoryReceipts, RECEIPT_SCHEMA, type MemoryDeliveryBinding, type PreparedRecall, type RecallReceipt, type ActivityReceiver } from './receipts.js'+import { libraryActivityQuerySchema, type LibraryActivity, type LibraryActivityQuery } from './library.js'import { MemoryNotebook, NOTEBOOK_SCHEMA, type NotebookInput, type NotebookLease, type NotebookProposal } from './notebook.js'import type { InferenceTarget } from './queue.js'import { visibleEvidenceSql } from './visibility.js'@@ -607,6 +608,31 @@ export class CodingMemoryStore {nextBefore: rows.length > limit ? Number(rows[limit - 1].rowid) : null }}+ /** Host-supplied open sessions; only the verified owner may inspect their latest selections. */+ libraryActivity(owner: string, receivers: ActivityReceiver[], input: LibraryActivityQuery = {}): LibraryActivity {+ this.requireOwner(owner)+ const query = parse(libraryActivityQuerySchema, input)+ return this.transaction(() => {+ const sessions = this.receipts.activity(receivers).map(({ projectId, ...row }) => ({ ...row,+ project: projectId ? this.projectLabel(projectId) : null }))+ const selectedAgentId = query.agentId ?? sessions[0]?.agentId ?? null+ const selection = sessions.find(row => row.agentId === selectedAgentId)+ const items: LibraryActivity['items'] = []+ for (const item of selection?.receiptId ? this.receipts.activityItems(selection.receiptId) : []) {+ const access = this.ownerRecordAccess(item.id)+ const record = access && this.read(item.id, access)+ if (!record || record.revision !== item.revision || record.state !== 'active' || !this.current(record)) continue+ const recall = this.receipts.forMemory(item.id, item.revision, selection!.receiptId!)[0]+ if (!recall) continue+ const { projectId, ...use } = recall+ items.push({ record: { ...summarize(record), applicability: record.applicability,+ rationale: record.rationale, futureAction: record.futureAction, exceptions: record.exceptions },+ recall: { ...use, canFeedback: true, project: projectId ? this.projectLabel(projectId) : null } })+ }+ return { sessions, selectedAgentId, items, version: this.libraryVersion() }+ })+ }+private projectLabel(id: string): LibraryProject {const row = this.db.prepare('SELECT name,location FROM memory_project_names WHERE project_id=?').get(id)return { id, name: row ? String(row.name) : `Project ${id}`, location: row ? String(row.location) : null }diff --git a/desktop/integration_test/coding_memory_activity_native_test.dart b/desktop/integration_test/coding_memory_activity_native_test.dartnew file mode 100644index 000000000..734330860--- /dev/null+++ b/desktop/integration_test/coding_memory_activity_native_test.dart@@ -0,0 +1,121 @@+import 'dart:io';+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+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_view.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness/shared/theme/color_palette.dart';+import 'package:harness/widgets/desktop_chrome.dart';+import 'package:integration_test/integration_test.dart';+import 'package:window_manager/window_manager.dart';++import '../test/support/coding_memory_fixture.dart';++// Synthetic owner replies only. No CLI, real conversations, provider or memory database.+// This exercises Flutter's native renderer and key handling, not physical AppKit IME/VoiceOver.+void main() {+ if (!kUnderTest) throw StateError('Memory fixtures require FLUTTER_TEST=1');+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;+ setUpAll(() async {+ await windowManager.ensureInitialized();+ await windowManager.setSize(const Size(860, 900));+ await windowManager.show();+ });++ for (final brightness in [Brightness.dark, Brightness.light]) {+ testWidgets(+ 'native activity ${brightness.name} rates a selection and removes it after empty recall',+ (tester) async {+ final connection = MemoryFixture()..recalls.add(syntheticRecall());+ final library = CodingMemoryLibrary(connection);+ final boundary = GlobalKey();+ await library.refresh();+ final oldPalette = AppTheme.palette.value,+ oldBrightness = AppTheme.brightness.value;+ AppTheme.palette.value = brightness == Brightness.dark+ ? HarnessPalette.graphite+ : HarnessPalette.paper;+ AppTheme.brightness.value = brightness;+ addTearDown(() {+ library.dispose();+ AppTheme.palette.value = oldPalette;+ AppTheme.brightness.value = oldBrightness;+ });+ await tester.pumpWidget(+ RepaintBoundary(+ key: boundary,+ child: MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: buildAppTheme(brightness: brightness),+ home: Scaffold(+ body: SingleChildScrollView(+ padding: const EdgeInsets.all(24),+ child: CodingMemoryView(library: library),+ ),+ ),+ ),+ ),+ );+ await tester.pumpAndSettle();+ await tester.tap(find.text('Helping now'));+ await tester.pumpAndSettle();+ expect(+ find.text('Sent by Harness · Delivery not confirmed'),+ findsOneWidget,+ );+ await tester.ensureVisible(find.text('Helpful'));+ final helpful = tester+ .widgetList<DesktopPill>(find.byType(DesktopPill))+ .singleWhere((p) => p.label == 'Helpful');+ helpful.focusNode!.requestFocus();+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pumpAndSettle();+ expect(+ connection.calls.where((p) => p['action'] == 'apply'),+ hasLength(1),+ );+ expect(+ (connection.recalls.single['feedback'] as Map)['value'],+ 'helpful',+ );+ expect(helpful.focusNode!.hasFocus, isTrue);+ final directory =+ Platform.environment['HARNESS_MEMORY_NATIVE_CAPTURE_DIR'];+ if (directory != null) {+ final shot =+ await (boundary.currentContext!.findRenderObject()+ as RenderRepaintBoundary)+ .toImage(pixelRatio: 1);+ try {+ final bytes = await shot.toByteData(format: ui.ImageByteFormat.png);+ final output = File(+ '$directory/activity-native-${brightness.name}.png',+ );+ await output.parent.create(recursive: true);+ await output.writeAsBytes(bytes!.buffer.asUint8List());+ } finally {+ shot.dispose();+ }+ }+ connection.handle = (p) async => p['action'] == 'activity'+ ? syntheticActivity(connection.record, empty: true)+ : connection.respond(p);+ await library.refresh();+ await tester.pumpAndSettle();+ expect(find.text(connection.record['claim'] as String), findsNothing);+ expect(+ find.text('No memories were selected for the last recorded request.'),+ findsOneWidget,+ );+ expect(tester.takeException(), isNull);+ },+ );+ }+}diff --git a/desktop/lib/companions/coding_memory_activity.dart b/desktop/lib/companions/coding_memory_activity.dartnew file mode 100644index 000000000..a501ead9c--- /dev/null+++ b/desktop/lib/companions/coding_memory_activity.dart@@ -0,0 +1,168 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++import 'coding_memory_connection.dart';+import 'coding_memory_library.dart';++/// Owner-only inspection of the last recorded recall for an open native session.+class CodingMemoryActivity extends ChangeNotifier {+ CodingMemoryActivity(this.library)+ : _changes = library.changes,+ _libraryBusy = library.busy {+ library.addListener(_libraryChanged);+ }+ final CodingMemoryLibrary library;+ List<Map<String, dynamic>> sessions = [], items = [];+ String? selectedAgentId, error;+ bool busy = false, writing = false;+ bool? available;+ bool _disposed = false, _libraryBusy;+ int _generation = 0, _changes;+ bool get valid => !_disposed && library.valid;+ Map<String, dynamic>? get selection =>+ sessions.where((row) => row['agentId'] == selectedAgentId).firstOrNull;++ void _notify() {+ if (!_disposed) notifyListeners();+ }++ void _clear() {+ ++_generation;+ sessions = [];+ items = [];+ busy = false;+ }++ void _libraryChanged() {+ if (_disposed) return;+ var refreshNeeded = _libraryBusy && !library.busy;+ _libraryBusy = library.busy;+ if (!valid || library.available == false || library.error != null) {+ _clear();+ if (!valid) selectedAgentId = null;+ error = library.error;+ _notify();+ return;+ }+ if (_changes != library.changes) {+ _changes = library.changes;+ _clear();+ refreshNeeded = true;+ _notify();+ }+ if (refreshNeeded && !library.busy && !writing) unawaited(refresh());+ }++ Future<void> select(String? agentId) async {+ if (!valid || writing) return;+ ++_generation;+ busy = false;+ items = [];+ if (agentId == null) sessions = [];+ selectedAgentId = agentId;+ await refresh();+ }++ void _accept(Map<String, dynamic> result, String? requested) {+ final nextSessions = (result['sessions'] as List).map(memoryMap).toList();+ final nextItems = (result['items'] as List).map(memoryMap).toList();+ final selected = result['selectedAgentId'] as String?;+ if ((requested != null && requested != selected) ||+ nextSessions.any((row) => row['agentId'] is! String) ||+ nextItems.any((row) => memoryMap(row['record'])['id'] is! String) ||+ (nextItems.isNotEmpty &&+ !nextSessions.any((row) => row['agentId'] == selected))) {+ throw const CodingMemoryFailure('PAGE_CHANGED');+ }+ sessions = nextSessions;+ items = nextItems;+ selectedAgentId = selected;+ available = true;+ }++ void _failed(Object failure) {+ sessions = [];+ items = [];+ if (failure is CodingMemoryFailure &&+ ['UNSUPPORTED', 'INVALID_INPUT'].contains(failure.code)) {+ available = false;+ error = null;+ } else if (failure is CodingMemoryFailure &&+ ['SESSION_CHANGED', 'SESSION_UNAVAILABLE'].contains(failure.code)) {+ error = 'This coding session changed or closed. Choose an open session to continue.';+ } else {+ error = codingMemoryError(failure);+ }+ }++ Future<void> refresh() async {+ if (!valid || busy || writing || library.busy) return;+ final generation = ++_generation, requested = selectedAgentId;+ busy = true;+ error = null;+ _notify();+ try {+ final result = await library.activity(agentId: requested);+ if (!valid || generation != _generation) return;+ _accept(result, requested);+ } catch (failure) {+ if (!valid || generation != _generation) return;+ _failed(failure);+ } finally {+ if (!_disposed && generation == _generation) {+ busy = false;+ _notify();+ }+ }+ }++ Future<void> rate(Map<String, dynamic> item, String? value) async {+ if (!valid || busy || writing || library.busy || !items.contains(item)) {+ return;+ }+ final generation = ++_generation, requested = selectedAgentId;+ final record = memoryMap(item['record']),+ recall = memoryMap(item['recall']);+ writing = busy = true;+ error = null;+ _notify();+ try {+ final preview = await library.preview({+ 'kind': 'feedback',+ 'id': record['id'],+ 'revision': record['revision'],+ 'receiptId': recall['receiptId'],+ 'value': value,+ 'expected': memoryMap(recall['feedback'])['version'],+ });+ if (!valid || generation != _generation) return;+ // The explicit rating click authorizes this bound, one-use write. Never retry it.+ await library.apply(preview);+ if (!valid || generation != _generation) return;+ final result = await library.activity(agentId: requested);+ if (!valid || generation != _generation) return;+ _accept(result, requested);+ } catch (failure) {+ if (valid && generation == _generation) _failed(failure);+ } finally {+ writing = false;+ if (!_disposed) {+ if (generation == _generation) busy = false;+ _notify();+ if (generation != _generation && valid && !library.busy) {+ unawaited(refresh());+ }+ }+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _clear();+ selectedAgentId = null;+ library.removeListener(_libraryChanged);+ super.dispose();+ }+}diff --git a/desktop/lib/companions/coding_memory_activity_view.dart b/desktop/lib/companions/coding_memory_activity_view.dartnew file mode 100644index 000000000..2f213aed2--- /dev/null+++ b/desktop/lib/companions/coding_memory_activity_view.dart@@ -0,0 +1,285 @@+part of 'coding_memory_view.dart';++class _CodingMemoryActivityView extends StatefulWidget {+ const _CodingMemoryActivityView({+ required this.library,+ required this.onOpen,+ });+ final CodingMemoryLibrary library;+ final Future<void> Function(String) onOpen;+ @override+ State<_CodingMemoryActivityView> createState() =>+ _CodingMemoryActivityViewState();+}++class _CodingMemoryActivityViewState extends State<_CodingMemoryActivityView> {+ late CodingMemoryActivity activity;+ final _ratingFocus = <String, FocusNode>{};+ String _identity(Map<String, dynamic> item) =>+ '${memoryMap(item['record'])['id']}:${memoryMap(item['record'])['revision']}:${memoryMap(item['recall'])['receiptId']}';+ FocusNode _node(Map<String, dynamic> item, String choice) =>+ _ratingFocus.putIfAbsent('${_identity(item)}:$choice', () => FocusNode());++ void _changed() {+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (!mounted) return;+ final prefixes = activity.items+ .map((item) => '${_identity(item)}:')+ .toSet();+ for (final key in _ratingFocus.keys.toList()) {+ if (!prefixes.any(key.startsWith)) _ratingFocus.remove(key)!.dispose();+ }+ });+ }++ Future<void> _rate(Map<String, dynamic> item, String? value) async {+ await activity.rate(item, value);+ if (!mounted) return;+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted &&+ activity.items.any(+ (current) => _identity(current) == _identity(item),+ )) {+ _node(item, value ?? 'helpful').requestFocus();+ }+ });+ }++ @override+ void initState() {+ super.initState();+ activity = CodingMemoryActivity(widget.library)+ ..addListener(_changed)+ ..refresh();+ }++ @override+ void didUpdateWidget(_CodingMemoryActivityView oldWidget) {+ super.didUpdateWidget(oldWidget);+ if (oldWidget.library != widget.library) {+ activity.dispose();+ activity = CodingMemoryActivity(widget.library)+ ..addListener(_changed)+ ..refresh();+ }+ }++ @override+ void dispose() {+ activity.dispose();+ for (final node in _ratingFocus.values) {+ node.dispose();+ }+ super.dispose();+ }++ String _where(Map<String, dynamic> session) =>+ '${session['engine'] == 'claude' ? 'Claude' : 'Codex'} · ${memoryMap(session['project'])['name'] ?? 'Companion conversation'}';++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: activity,+ builder: (context, _) {+ final selection = activity.selection;+ final busy = activity.busy || widget.library.busy;+ return Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _text(+ 'See the last recorded recall for an open coding session. You can check each memory and tell your companion whether it helped.',+ ),+ const SizedBox(height: 16),+ if (activity.available == false)+ _text(+ 'Recall activity is not available in this local service yet. You can still read individual memories and their evidence.',+ ),+ if (activity.sessions.isNotEmpty) ...[+ Semantics(+ enabled: !activity.writing,+ child: ExcludeSemantics(+ excluding: activity.writing,+ child: ExcludeFocus(+ excluding: activity.writing,+ child: IgnorePointer(+ ignoring: activity.writing,+ child: AppSelectField<String>(+ key: const ValueKey('memory-activity-session'),+ semanticLabel: 'Coding session',+ value: activity.selectedAgentId ?? '',+ filterable: true,+ options: [+ for (final session in activity.sessions)+ SelectOption(+ value: session['agentId'] as String,+ label:+ session['name'] as String? ?? 'Coding session',+ note: _where(session),+ detail:+ memoryMap(session['project'])['location']+ as String?,+ ),+ ],+ onChanged: (id) => unawaited(activity.select(id)),+ ),+ ),+ ),+ ),+ ),+ const SizedBox(height: 16),+ ],+ if (activity.error != null) ...[+ Semantics(liveRegion: true, child: _text(activity.error!)),+ TextButton(+ onPressed: busy ? null : () => activity.select(null),+ child: const Text('Show open sessions'),+ ),+ ],+ if (activity.busy && activity.sessions.isEmpty)+ _memorySurface(+ Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ SkeletonText(style: AppType.body(), widthFactor: .7),+ const SizedBox(height: 8),+ SkeletonText(style: AppType.caption(), widthFactor: .5),+ ],+ ),+ ),+ if (!busy &&+ activity.error == null &&+ activity.available == true &&+ activity.sessions.isEmpty)+ _text(+ 'No recall activity for open coding sessions yet. New activity appears when a supported agent requests memory.',+ ),+ if (selection != null) ...[+ _text(_where(selection)),+ _text(_time(context, selection['preparedAt']), small: true),+ if (memoryMap(selection['project'])['location']+ case final String location)+ _text(location, small: true),+ const SizedBox(height: 8),+ _text(+ selection['status'] == 'off'+ ? 'Recall was paused for this request.'+ : selection['selectedCount'] == 0+ ? 'No memories were selected for the last recorded request.'+ : selection['emittedAt'] == null+ ? 'Selected for recall · Delivery not confirmed'+ : 'Sent by Harness · Delivery not confirmed',+ small: true,+ ),+ if (!busy &&+ (selection['selectedCount'] as num? ?? 0) >+ activity.items.length)+ _text(+ 'Some earlier selections have changed or are no longer available. Only current memory versions are shown.',+ small: true,+ ),+ const SizedBox(height: 16),+ for (final item in activity.items) _item(item, busy),+ _text(+ 'This records context prepared by Harness. It does not establish that the model received or used it. The time above may precede the current turn.',+ small: true,+ ),+ ],+ const SizedBox(height: 8),+ TextButton(+ onPressed: busy ? null : () => widget.library.refresh(),+ child: const Text('Refresh recall activity'),+ ),+ ],+ );+ },+ );++ Widget _item(Map<String, dynamic> item, bool busy) {+ final record = memoryMap(item['record']),+ recall = memoryMap(item['recall']);+ final feedback = memoryMap(recall['feedback'])['value'];+ final conditions = memoryMap(record['applicability']);+ return KeyedSubtree(+ key: ValueKey(+ '${record['id']}:${record['revision']}:${recall['receiptId']}',+ ),+ child: _memorySurface(+ Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ _text(_scopeLabel(record), small: true),+ const SizedBox(height: 8),+ Text(+ record['claim'] as String,+ style: AppType.body(color: AppPalette.textPrimary, height: 1.5),+ ),+ if (record['rationale'] case final String reason) ...[+ const SizedBox(height: 8),+ _text(reason),+ ],+ const SizedBox(height: 8),+ _text(+ conditions.isEmpty+ ? 'Applies across matching coding work.'+ : 'Applies when ${conditions.entries.map((e) => '${_label(e.key)}: ${_label('${e.value}')}').join(', ')}.',+ small: true,+ ),+ if ((record['exceptions'] as List? ?? []).isNotEmpty)+ _fields(record['exceptions'], label: 'Exceptions'),+ const SizedBox(height: 8),+ Wrap(+ spacing: 8,+ runSpacing: 8,+ children: [+ TextButton(+ onPressed: busy+ ? null+ : () => widget.onOpen(record['id'] as String),+ child: const Text('Read memory'),+ ),+ for (final choice in ['helpful', 'unhelpful'])+ DesktopPill(+ label: choice == 'helpful' ? 'Helpful' : 'Not helpful',+ semanticLabel:+ '${choice == 'helpful' ? 'Helpful' : 'Not helpful'}: ${record['claim']}',+ selected: feedback == choice,+ focusNode: _node(item, choice),+ leading: SizedBox(+ width: 16,+ child: feedback == choice+ ? const Icon(AppIcons.check, size: 16)+ : null,+ ),+ onPressed: busy || recall['canFeedback'] != true+ ? null+ : () {+ if (feedback != choice) {+ unawaited(_rate(item, choice));+ }+ },+ ),+ if (feedback != null)+ TextButton(+ focusNode: _node(item, 'clear'),+ onPressed: busy ? null : () => _rate(item, null),+ child: const Text('Clear feedback'),+ ),+ ],+ ),+ if (recall['canGuideRecall'] == true)+ _text(+ 'Your feedback helps choose memories for matching work. Correct the memory separately if the fact is wrong.',+ small: true,+ ),+ ],+ ),+ ),+ );+ }++ String _time(BuildContext context, Object? millis) {+ if (millis is! num) return 'Recall time unavailable';+ final date = DateTime.fromMillisecondsSinceEpoch(millis.toInt()).toLocal();+ final local = MaterialLocalizations.of(context);+ return 'Last recorded recall: ${local.formatMediumDate(date)} at ${local.formatTimeOfDay(TimeOfDay.fromDateTime(date), alwaysUse24HourFormat: MediaQuery.alwaysUse24HourFormatOf(context))}';+ }+}diff --git a/desktop/lib/companions/coding_memory_library.dart b/desktop/lib/companions/coding_memory_library.dartindex a10fe4144..287e72573 100644--- a/desktop/lib/companions/coding_memory_library.dart+++ b/desktop/lib/companions/coding_memory_library.dart@@ -98,6 +98,11 @@ class CodingMemoryLibrary extends ChangeNotifier {Future<Map<String, dynamic>> detail(String id) =>_request({'action': 'show', 'id': id});+ Future<Map<String, dynamic>> activity({String? agentId}) => _request({+ 'action': 'activity',+ 'query': {'agentId': ?agentId},+ });+Future<Map<String, dynamic>> notebooks({String? cursor}) => _request({'action': 'notebooks','query': {'limit': 12, 'cursor': ?cursor},diff --git a/desktop/lib/companions/coding_memory_view.dart b/desktop/lib/companions/coding_memory_view.dartindex 69cd93176..ce12f4674 100644--- a/desktop/lib/companions/coding_memory_view.dart+++ b/desktop/lib/companions/coding_memory_view.dart@@ -5,15 +5,20 @@ import 'package:flutter/services.dart';import '../shared/theme/app_theme.dart';import '../shared/widgets/app_dialog.dart';+import '../shared/widgets/app_select_field.dart';+import '../shared/widgets/skeleton.dart';+import '../shared/theme/app_icons.dart';import '../widgets/desktop_chrome.dart';import '../widgets/desktop_prompt_surface.dart';import 'coding_memory_connection.dart';import 'coding_memory_library.dart';+import 'coding_memory_activity.dart';import 'coding_memory_notebooks.dart';import 'coding_memory_project_picker.dart';import 'coding_memory_recall_history.dart';part 'coding_memory_notebook_view.dart';+part 'coding_memory_activity_view.dart';/// The collection's owner library; it does not send chat or terminal input.class CodingMemoryView extends StatefulWidget {@@ -67,6 +72,7 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {for (final name in ['How you work','Project knowledge',+ 'Helping now','Learning',])ChoiceChip(@@ -97,6 +103,11 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {if (library.available == true && library.valid)if (section == 'Learning')_learning()+ else if (section == 'Helping now')+ _CodingMemoryActivityView(+ library: library,+ onOpen: (id) => _open(id: id),+ )else if (section == 'Project knowledge')_ProjectMemoryView(library: library,@@ -123,12 +134,13 @@ class _CodingMemoryViewState extends State<CodingMemoryView> {),],const SizedBox(height: 8),- TextButton(- onPressed: library.busy || !library.valid- ? null- : () => library.refresh(),- child: const Text('Refresh coding memory'),- ),+ if (section != 'Helping now')+ TextButton(+ onPressed: library.busy || !library.valid+ ? null+ : () => library.refresh(),+ child: const Text('Refresh coding memory'),+ ),const SizedBox(height: 28),],),diff --git a/desktop/test/coding_memory_activity_test.dart b/desktop/test/coding_memory_activity_test.dartnew file mode 100644index 000000000..92687ef9e--- /dev/null+++ b/desktop/test/coding_memory_activity_test.dart@@ -0,0 +1,178 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/companions/coding_memory_activity.dart';+import 'package:harness/companions/coding_memory_library.dart';++import 'support/coding_memory_fixture.dart';++void main() {+ late MemoryFixture connection;+ late CodingMemoryLibrary library;+ late CodingMemoryActivity activity;+ setUp(() async {+ connection = MemoryFixture()..recalls.add(syntheticRecall());+ library = CodingMemoryLibrary(connection);+ await library.refresh();+ activity = CodingMemoryActivity(library);+ });+ tearDown(() {+ activity.dispose();+ library.dispose();+ });++ test(+ 'reads current session selections and replaces them with an empty result',+ () async {+ await activity.refresh();+ expect(activity.items, hasLength(1));+ expect(connection.calls.last, {'action': 'activity', 'query': {}});+ connection.handle = (p) async => p['action'] == 'activity'+ ? syntheticActivity(connection.record, empty: true)+ : connection.respond(p);+ await library.refresh();+ await Future<void>.delayed(Duration.zero);+ expect(activity.items, isEmpty);+ expect(activity.selection?['selectedCount'], 0);+ expect(+ connection.calls.any((p) => ['preview', 'apply'].contains(p['action'])),+ isFalse,+ );+ },+ );++ test(+ 'changing session discards a late reply without switching back',+ () async {+ final pending = Completer<Map<String, dynamic>>();+ connection.handle = (p) => (p['query'] as Map?)?['agentId'] == 'second'+ ? Future.value(+ syntheticActivity(+ connection.record,+ agentId: 'second',+ empty: true,+ ),+ )+ : pending.future;+ final old = activity.refresh();+ await activity.select('second');+ pending.complete(syntheticActivity(connection.record));+ await old;+ expect(activity.selectedAgentId, 'second');+ expect(activity.items, isEmpty);+ },+ );++ test(+ 'account change removes selected content and rejects an in-flight reply',+ () async {+ await activity.refresh();+ final pending = Completer<Map<String, dynamic>>();+ connection.handle = (_) => pending.future;+ final read = activity.refresh();+ connection.invalidate();+ expect(activity.items, isEmpty);+ expect(activity.sessions, isEmpty);+ expect(activity.selectedAgentId, isNull);+ pending.complete(syntheticActivity(connection.record));+ await read;+ expect(activity.items, isEmpty);+ },+ );++ test('a corrected library clears the old selected version before the next read completes', () async {+ await activity.refresh();+ final pending = Completer<Map<String, dynamic>>();+ connection.record = syntheticMemory(revision: 2);+ connection.handle = (p) => p['action'] == 'activity'+ ? pending.future+ : Future.value(connection.respond(p));+ await library.refresh();+ expect(activity.items, isEmpty);+ pending.complete(syntheticActivity(connection.record, empty: true));+ await Future<void>.delayed(Duration.zero);+ expect(activity.items, isEmpty);+ });++ test(+ 'rates the exact selected revision once and rereads saved feedback',+ () async {+ await activity.refresh();+ await activity.rate(activity.items.single, 'helpful');+ expect(connection.previewed, {+ 'kind': 'feedback',+ 'id': 'synthetic-memory',+ 'revision': 1,+ 'receiptId': 'synthetic-receipt',+ 'value': 'helpful',+ 'expected': 0,+ });+ expect(+ connection.calls.where((p) => p['action'] == 'apply'),+ hasLength(1),+ );+ expect(+ ((activity.items.single['recall'] as Map)['feedback'] as Map)['value'],+ 'helpful',+ );+ await activity.rate(activity.items.single, null);+ expect(+ ((activity.items.single['recall'] as Map)['feedback'] as Map)['value'],+ isNull,+ );+ },+ );++ test(+ 'uncertain feedback never retries the write and exposes a refresh path',+ () async {+ await activity.refresh();+ connection.refuseApply = 'TIMEOUT';+ await activity.rate(activity.items.single, 'helpful');+ expect(+ connection.calls.where((p) => p['action'] == 'apply'),+ hasLength(1),+ );+ expect(activity.error, contains('refresh to check'));+ expect(activity.items, isEmpty);+ await activity.refresh();+ expect(+ connection.calls.where((p) => p['action'] == 'apply'),+ hasLength(1),+ );+ },+ );++ test(+ 'does not apply a prepared rating after the owner library changes',+ () async {+ await activity.refresh();+ final pending = Completer<Map<String, dynamic>>();+ connection.handle = (p) => p['action'] == 'preview'+ ? pending.future+ : Future.value(connection.respond(p));+ final rating = activity.rate(activity.items.single, 'helpful');+ connection.record = syntheticMemory(revision: 2);+ await library.refresh();+ pending.complete(+ connection.respond({+ 'action': 'preview',+ 'command': {'kind': 'feedback', 'expected': 0, 'value': 'helpful'},+ }),+ );+ await rating;+ expect(connection.calls.where((p) => p['action'] == 'apply'), isEmpty);+ expect(activity.writing, isFalse);+ },+ );++ test('handles older services and refuses a response for a different selected session', () async {+ connection.handle = (_) async => {'ok': false, 'error': 'INVALID_INPUT'};+ await activity.refresh();+ expect(activity.available, isFalse);+ connection.handle = (_) async => syntheticActivity(connection.record);+ await activity.select('another-session');+ expect(activity.items, isEmpty);+ expect(activity.error, contains('changed'));+ });+}diff --git a/desktop/test/coding_memory_view_test.dart b/desktop/test/coding_memory_view_test.dartindex 39da25111..29699d6d2 100644--- a/desktop/test/coding_memory_view_test.dart+++ b/desktop/test/coding_memory_view_test.dart@@ -12,6 +12,7 @@ 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';+import 'package:harness/shared/widgets/skeleton.dart';import 'support/coding_memory_fixture.dart';import 'support/real_fonts.dart';@@ -105,6 +106,161 @@ void main() {});}+ testWidgets(+ 'Helping now explains a selection and preserves rating focus and source controls',+ (tester) async {+ transport.recalls.add(syntheticRecall());+ await mount(tester);+ await tap(tester, 'Helping now');+ expect(+ find.text('Sent by Harness · Delivery not confirmed'),+ findsOneWidget,+ );+ expect(find.text('Applies when task: bug fix.'), findsOneWidget);+ await tap(tester, 'Helpful');+ final helpful = tester+ .widgetList<DesktopPill>(find.byType(DesktopPill))+ .singleWhere((p) => p.label == 'Helpful');+ expect(helpful.selected, isTrue);+ expect(helpful.focusNode!.hasFocus, isTrue);+ expect(transport.previewed!['receiptId'], 'synthetic-receipt');+ await tap(tester, 'Clear feedback');+ expect(+ transport.calls.where((p) => p['action'] == 'apply'),+ hasLength(2),+ );+ await tap(tester, 'Read memory');+ expect(find.text('Correct memory'), findsOneWidget);+ expect(find.text('Forget…'), findsOneWidget);+ },+ );++ testWidgets(+ 'Helping now shows an empty latest recall without an earlier positive memory',+ (tester) async {+ transport.handle = (p) async => p['action'] == 'activity'+ ? syntheticActivity(transport.record, empty: true)+ : transport.respond(p);+ await mount(tester);+ await tap(tester, 'Helping now');+ expect(+ find.text('No memories were selected for the last recorded request.'),+ findsOneWidget,+ );+ expect(find.text(transport.record['claim'] as String), findsNothing);+ expect(find.text('Helpful'), findsNothing);+ },+ );++ testWidgets(+ 'Helping now distinguishes loading, empty activity and lost identity',+ (tester) async {+ final pending = Completer<Map<String, dynamic>>();+ transport.handle = (p) => p['action'] == 'activity'+ ? pending.future+ : Future.value(transport.respond(p));+ await mount(tester);+ await tap(tester, 'Helping now');+ expect(find.byType(SkeletonText), findsNWidgets(2));+ expect(find.textContaining('No recall activity'), findsNothing);+ pending.complete({+ 'ok': true,+ 'sessions': [],+ 'items': [],+ 'selectedAgentId': null,+ });+ await tester.pumpAndSettle();+ expect(find.textContaining('No recall activity'), findsOneWidget);+ transport.invalidate();+ await tester.pumpAndSettle();+ expect(find.textContaining('No recall activity'), findsNothing);+ },+ );++ testWidgets(+ 'Helping now session picker switches the inspected task without writing or sending input',+ (tester) async {+ transport.handle = (p) async {+ if (p['action'] != 'activity') return transport.respond(p);+ final selected =+ (p['query'] as Map)['agentId'] as String? ?? 'synthetic-agent';+ final result = syntheticActivity(+ transport.record,+ agentId: selected,+ empty: selected == 'second',+ );+ final session = (result['sessions'] as List).single as Map;+ return {+ ...result,+ 'sessions': [+ {+ ...session,+ 'agentId': 'synthetic-agent',+ 'name': 'First coding task',+ 'selectedCount': 1,+ },+ {+ ...session,+ 'agentId': 'second',+ 'name': 'Second coding task',+ 'selectedCount': 0,+ },+ ],+ };+ };+ await mount(tester);+ await tap(tester, 'Helping now');+ await tester.tap(find.byKey(const ValueKey('memory-activity-session')));+ await tester.pumpAndSettle();+ await tap(tester, 'Second coding task');+ expect(+ find.text('No memories were selected for the last recorded request.'),+ findsOneWidget,+ );+ expect(+ transport.calls.where((p) => p['action'] == 'activity').last['query'],+ {'agentId': 'second'},+ );+ expect(+ transport.calls.any((p) => ['preview', 'apply'].contains(p['action'])),+ isFalse,+ );+ },+ );++ for (final brightness in [Brightness.dark, Brightness.light]) {+ for (final scale in [1.0, 2.0]) {+ testWidgets(+ 'Helping now fits ${brightness.name} at ${scale}x with a long session name',+ (tester) async {+ transport.recalls.add(syntheticRecall());+ transport.handle = (p) async {+ final result = transport.respond(p);+ if (p['action'] == 'activity') {+ ((result['sessions'] as List).first as Map)['name'] = 'Fix the editor regression while preserving keyboard navigation and project context';+ }+ return result;+ };+ await mount(+ tester,+ brightness: brightness,+ scale: scale,+ size: Size(scale == 1 ? 760 : 480, 920),+ );+ await tap(tester, 'Helping now');+ expect(tester.takeException(), isNull);+ await capture(tester, 'activity-${brightness.name}-${scale}x');+ await tap(tester, 'Helpful');+ expect(tester.takeException(), isNull);+ await capture(+ tester,+ 'activity-feedback-${brightness.name}-${scale}x',+ );+ },+ );+ }+ }+testWidgets('project notebooks preserve source conditions, scope and source controls',(tester) async {diff --git a/desktop/test/support/coding_memory_fixture.dart b/desktop/test/support/coding_memory_fixture.dartindex 2b3207893..6baeceb1b 100644--- a/desktop/test/support/coding_memory_fixture.dart+++ b/desktop/test/support/coding_memory_fixture.dart@@ -62,6 +62,39 @@ Map<String, dynamic> syntheticMemory({],};+Map<String, dynamic> syntheticActivity(+ Map<String, dynamic> record, {+ Map<String, dynamic>? recall,+ String agentId = 'synthetic-agent',+ bool empty = false,+}) {+ final use = recall ?? syntheticRecall();+ return {+ 'ok': true,+ 'sessions': [+ {+ ...use,+ 'agentId': agentId,+ 'name': 'Fix the editor regression',+ 'selectedCount': empty ? 0 : 1,+ 'status': 'ok',+ 'receiptId': empty ? null : use['receiptId'],+ },+ ],+ 'selectedAgentId': agentId,+ 'items': empty+ ? []+ : [+ {'record': record, 'recall': use},+ ],+ 'version': {+ 'generation': 1,+ 'knowledge': record['revision'],+ 'preferences': 'true:true',+ },+ };+}+Map<String, dynamic> syntheticNotebook(Map<String, dynamic> memory, {bool ready = true,@@ -185,6 +218,8 @@ class MemoryFixture extends CodingMemoryConnection {Map<String, dynamic> respond(Map<String, dynamic> payload) {switch (payload['action']) {+ case 'activity':+ return syntheticActivity(record, recall: recalls.firstOrNull);case 'status':return {'ok': true,diff --git a/docs/plans/2026-09-30-coding-memory-review-log.md b/docs/plans/2026-09-30-coding-memory-review-log.mdindex 4eac12728..f12c5e6e3 100644--- a/docs/plans/2026-09-30-coding-memory-review-log.md+++ b/docs/plans/2026-09-30-coding-memory-review-log.md@@ -446,3 +446,63 @@ same path was refused and the original report hash remained unchanged. The scoreagainst the source file. No native inference, private history scan, production memory write, appreplacement, firmware change or release occurred. Real model quality and the full release evidenceremain unproven; a reviewed synthetic diagnostic will not substitute for them.++## Round 23 — inspect what was prepared for the current coding session++Bret Victor's [Learnable Programming](https://worrydream.com/LearnableProgramming/) argues for+making program state and behavior visible in context. Our application of that principle is to+show the owner which memory versions Harness prepared for an open coding session, when that+happened, and the conditions attached to them. This is our engineering interpretation of a+published source; Victor did not participate in or endorse this review.++Companions → Memories now includes Helping now. Its session picker uses the live host roster,+including framework, project and known session name. Each selected memory offers Read memory+for the existing evidence/correction/forget editor, plus exact-version Helpful / Not helpful+feedback and clearing. A transport emission remains explicitly unverified delivery. The timestamp+describes the last recorded store preparation, which may precede the current turn; failed host+requests and actual model use are not inferred.++Review found that positive-only receipt history could leave an earlier selection looking current+after a newer empty recall. An additive, content-free latest-attempt row now records empty/off+results too, without creating a full history receipt. The row keeps a one-way receiver key and+bounded metadata, never prompt text, claims or native session IDs. Retention is 30 days and at+most 5,000 receivers. Earlier histories are not backfilled. Reads recheck source and receiver+privacy, current revisions and validity; closed capture-grace sessions are excluded. Receiver+exclusion removes activity, and reinclusion does not resurrect it.++The owner endpoint accepts an optional host agent ID, derives native identities itself and rejects+an identity change during the worker request. A regression test exposed an in-place mutation of+the supplied session object: the check incorrectly accepted the old result before the fix.+The runtime now copies the session snapshot before awaiting. Desktop reads reject late replies,+preserve an explicit session choice, clear invalidated content and never retry a feedback write+after an uncertain response. A library change while previewing feedback prevents application.++All **92 focused CLI tests** passed, as did CLI type checking, strict benchmark-runner checking,+scoped Flutter analysis and the icon audit. The full local CLI run had **8,238 passed, 5 failed+and 39 skipped** in 677 seconds. The five failures are the unchanged OpenCode help checks: the+installed binary emits its help to stderr while those tests inspect stdout. The full desktop run+had **5,232 passed, 4 failed and 15 skipped**. All four failures were reproduced in a disposable+copy of the unchanged base `cf69f796d`: a pending activity timer in `bios_navigation_test`, two+stale Search harnesses/Open Harness tooltip expectations in `search_workspace_test`, and the+watchdog expectation in `workspace_event_isolation_test`. Neither full local run is recorded as+passing. The PR records final rebased checks and the exact-commit manual CI result.++Both native macOS fixture cases passed on Apple Silicon. They exercise keyboard feedback once,+focus return and removal of a previous memory after an empty recall. The actual renderer's+[dark](../research/2026-10-01-memory-activity/activity-native-dark.png) and+[light](../research/2026-10-01-memory-activity/activity-native-light.png) captures were inspected.+Headless widget fixtures also cover narrow windows and 200% text, loading, emptiness, errors and+identity changes. Flutter logged a failure to foreground the native fixture, although both tests+and captures completed; physical AppKit input, IME and VoiceOver remain unverified.++The [synthetic performance diagnostic](../research/2026-10-01-memory-activity-performance.json)+used 10,000 memories, 5,000 retained receivers and 128 open-session identities. Across 310 recalls+and activity reads, warm recall p95 was **23.061 ms**, fresh-worker recall p95 **49.793 ms**, and+the activity read p95 **3.682 ms**, with no recall timeouts. Reproduce with+`cd cli && node --import tsx scripts/memory-benchmark.ts --activity`. These are local lexical+performance measurements, not semantic quality, native delivery or coding-task benefit.++No private history was scanned, native model called, production memory seeded, installed review+app replaced or release published. Real extraction and notebook faithfulness, cross-framework+task benefit, native lifecycle coverage, task/session navigation and the held-out rollout gates+remain open. This change makes existing recall inspectable; it does not establish those outcomes.diff --git a/docs/plans/2026-09-30-tim-memory.md b/docs/plans/2026-09-30-tim-memory.mdindex 07cb32587..dc22e9d02 100644--- a/docs/plans/2026-09-30-tim-memory.md+++ b/docs/plans/2026-09-30-tim-memory.md@@ -296,7 +296,27 @@ 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. 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. Project knowledge now includes a maintained notebook index and topic pages with source links, conditions, unresolved records and correction/forget controls. Individual memories remain available while notebook synthesis is queued or paused. Feedback-based ranking is implemented as an experimental bounded adjustment. Work-in-progress grouping, a collection-wide Helping now view and task/session navigation 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 offers How you work, Project knowledge, Helping now 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. Project knowledge includes a maintained notebook index and topic pages with source links, conditions, unresolved records and correction/forget controls. Individual memories remain available while notebook synthesis is queued or paused. Feedback-based ranking is an experimental bounded adjustment. Work-in-progress grouping and navigation from a memory to the working agent's task/session remain planned. The legacy approved-lesson list remains available; the 24-hour test action is hidden when the new memory service is available.++Helping now lets the owner select an open coding session and inspect its last recorded recall,+including an empty result. It shows the known session name, project, timestamp, current selected+memory versions, applicability and exceptions, delivery uncertainty, and exact-version feedback.+Read memory opens the existing evidence/correction/forget editor. The ordinary Memories refresh+updates activity too; changing sessions never launches an agent or sends terminal input.++An additive, content-free latest-attempt row per native session prevents an old positive recall+from appearing current after a newer empty result. It retains a one-way session key, engine,+receiving project, time, outcome, selected count and optional receipt pointer, bounded to 5,000+sessions and 30 days. It keeps no prompt, claim, conditions or native session ID. Source/receiver+privacy, current revisions and validity are checked again on reads. Receiver exclusion removes+the row; reinclusion does not restore it. The owner endpoint binds at most 128 receivers from the+host roster and rechecks immutable session identities after the worker reply. Exited sessions+retained briefly for final transcript capture do not appear as open sessions.++This is the last recorded store preparation, not an assertion about the latest user turn, every+failed host request, actual model-context delivery or use. The time and uncertainty stay visible.+Older positive-only histories are not backfilled as current activity. These inspection controls+do not satisfy the real-model quality and coding-task benefit gates below.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-activity-performance.json b/docs/research/2026-10-01-memory-activity-performance.jsonnew file mode 100644index 000000000..040af2079--- /dev/null+++ b/docs/research/2026-10-01-memory-activity-performance.json@@ -0,0 +1,40 @@+{+ "kind": "synthetic-memory-performance",+ "mode": "prepare-and-owner-activity",+ "retainedReceipts": 5000,+ "ratedContexts": 0,+ "records": 10000,+ "projects": 10,+ "node": "v22.23.2",+ "platform": "darwin",+ "arch": "arm64",+ "seedMs": 41453.811708,+ "cold": {+ "p50Ms": 48.41275000000314,+ "p95Ms": 49.79349999999977,+ "maxMs": 49.79349999999977+ },+ "warm": {+ "p50Ms": 20.006792000000132,+ "p95Ms": 23.060583999998926,+ "maxMs": 45.331167000003916+ },+ "requests": 310,+ "timeouts": 0,+ "largestPacketBytes": 2642,+ "parentEventLoopP95Ms": 1.377279,+ "latestAttempts": 5000,+ "openSessions": 128,+ "activityAfterRecall": {+ "p50Ms": 1.8244580000027781,+ "p95Ms": 3.682042000000365,+ "maxMs": 4.828499999995984+ },+ "activityRequests": 310,+ "largestActivityBytes": 37401,+ "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-activity/activity-native-dark.png b/docs/research/2026-10-01-memory-activity/activity-native-dark.pngnew file mode 100644index 000000000..235e32c41Binary files /dev/null and b/docs/research/2026-10-01-memory-activity/activity-native-dark.png differdiff --git a/docs/research/2026-10-01-memory-activity/activity-native-light.png b/docs/research/2026-10-01-memory-activity/activity-native-light.pngnew file mode 100644index 000000000..f117edb62Binary files /dev/null and b/docs/research/2026-10-01-memory-activity/activity-native-light.png differ