The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
Validate and compare memory synchronization snapshots
David980ea61f7933
diff --git a/e2e/memory-sync-plan.spec.ts b/e2e/memory-sync-plan.spec.tsnew file mode 100644index 00000000..ab3a049d--- /dev/null+++ b/e2e/memory-sync-plan.spec.ts@@ -0,0 +1,22 @@+import { expect, test } from '@playwright/test'++test('browser WebCrypto plans conflicts and forgetting without retaining private copies', async ({ page }) => {+ await page.goto('/e2e/memory-sensitive-proof.html')+ const result = await page.evaluate(async () => {+ const modulePath = '/src/lib/memory-sync-plan.ts'+ const { planMemorySync, syncMemoryHash } = await import(modulePath)+ const memory = { id: 'one', type: 'user', title: 'Fact', description: '', content: 'Original', tags: [], source: 'manual', createdAt: 1, updatedAt: 1 }+ const baseline = { one: { revision: 1, hash: await syncMemoryHash(memory) } }+ const local = { ...memory, content: 'Private local edit' }+ const remote = { memory_id: 'one', revision: 2, deleted: false, payload: { ...memory, content: 'Private remote edit' }, updated_at: '2026-09-09T00:00:00Z' }+ const conflict = await planMemorySync([local], baseline, [remote])+ const deletion = await planMemorySync([local], baseline, [{ ...remote, deleted: true, payload: null }])+ const pull = await planMemorySync([memory], baseline, [remote])+ return { hash: baseline.one.hash, conflict, deletion, pulledContent: pull.pull[0].memory.content }+ })+ expect(result.hash).toMatch(/^[a-f0-9]{64}$/)+ expect(result.conflict.conflicts).toEqual([{ id: 'one', reason: 'both-edited' }])+ expect(result.deletion.remove).toEqual([{ id: 'one', baseline: { revision: 2, hash: null } }])+ expect(JSON.stringify([result.conflict, result.deletion])).not.toContain('Private')+ expect(result.pulledContent).toBe('Private remote edit')+})diff --git a/src/lib/__tests__/memory-sync-plan.test.ts b/src/lib/__tests__/memory-sync-plan.test.tsnew file mode 100644index 00000000..c0227b4c--- /dev/null+++ b/src/lib/__tests__/memory-sync-plan.test.ts@@ -0,0 +1,69 @@+import { expect, it } from 'vitest'+import { decodeSyncMemory, planMemorySync, syncMemoryHash } from '../memory-sync-plan'+import type { MemoryFile } from '../../types/agent-mode'+const memory = (content = 'Original fact'): MemoryFile => ({ id: 'one', type: 'user', title: 'Fact', description: '', content, tags: [], source: 'manual', createdAt: 1, updatedAt: 1 })+const row = (payload: MemoryFile | null, revision = 1) => ({ memory_id: 'one', revision, deleted: payload === null, payload: payload ? { ...payload } : null, updated_at: '2026-09-09T00:00:00Z' })+const baseline = async () => ({ one: { revision: 1, hash: await syncMemoryHash(memory()) } })++it('uploads new local records and downloads new remote records without a fictitious acknowledgement', async () => {+ const outbound = await planMemorySync([memory()], {}, [])+ expect(outbound.push).toEqual([{ id: 'one', expectedRevision: 0, payload: decodeSyncMemory(memory()) }])+ expect(outbound.acknowledge).toEqual([])+ const inbound = await planMemorySync([], {}, [row(memory())])+ expect(inbound.pull[0].memory).toEqual(decodeSyncMemory(memory()))+})+it('uses a stable hash independent of key order and absent false flags', async () => {+ const reordered = Object.fromEntries(Object.entries(memory()).reverse()) as unknown as MemoryFile+ expect(await syncMemoryHash(reordered)).toBe(await syncMemoryHash({ ...memory(), sensitive: false, stale: false }))+ const plan = await planMemorySync([memory()], {}, [row(reordered)])+ expect(plan.acknowledge).toHaveLength(1)+ expect(plan.push).toEqual([])+})+it('pulls remote-only edits and pushes local-only edits against the observed revision', async () => {+ const base = await baseline()+ expect((await planMemorySync([memory()], base, [row(memory('Remote edit'), 2)])).pull).toHaveLength(1)+ const plan = await planMemorySync([memory('Local edit')], base, [row(memory())])+ expect(plan.push[0]).toMatchObject({ expectedRevision: 1, payload: { content: 'Local edit' } })+})+it('does not silently merge both-edited records or store private content in conflict metadata', async () => {+ const plan = await planMemorySync([memory('Private local edit')], await baseline(), [row(memory('Private remote edit'), 2)])+ expect(plan.conflicts).toEqual([{ id: 'one', reason: 'both-edited' }])+ expect(plan.push).toEqual([])+ expect(plan.pull).toEqual([])+ expect(JSON.stringify(plan)).not.toContain('Private')+})+it('remote forgetting wins over pending local edits without retaining the old content', async () => {+ const plan = await planMemorySync([memory('Private pending edit')], await baseline(), [row(null, 2)])+ expect(plan.remove).toEqual([{ id: 'one', baseline: { revision: 2, hash: null } }])+ expect(JSON.stringify(plan)).not.toContain('Private')+ expect(plan.push).toEqual([])+})+it('propagates local deletion using the current remote revision', async () => {+ const plan = await planMemorySync([], await baseline(), [row(memory('Remote edit'), 2)])+ expect(plan.push).toEqual([{ id: 'one', expectedRevision: 2, payload: null }])+})+it('does not recreate missing remote records or accept a revived tombstone', async () => {+ expect((await planMemorySync([memory()], await baseline(), [])).conflicts[0].reason).toBe('missing-remote')+ expect((await planMemorySync([], { one: { revision: 1, hash: null } }, [row(memory(), 2)])).conflicts[0].reason).toBe('deleted-baseline')+})+it('rejects revision rollback and content changes under an unchanged revision', async () => {+ await expect(planMemorySync([memory()], await baseline(), [row(memory('Undocumented edit'))])).rejects.toThrow('Invalid synchronized memory data')+ await expect(planMemorySync([memory()], { one: { revision: 2, hash: await syncMemoryHash(memory()) } }, [row(memory())])).rejects.toThrow()+})+it('rejects malformed privacy, scope, provenance, duplicate IDs and unknown fields', async () => {+ for (const extra of [{ sensitive: 'true' }, { scope: null }, { sourceKind: 'unknown' }, { syncOwnerId: 'another' }, { confirmedAt: -1 }]) {+ expect(() => decodeSyncMemory({ ...memory(), ...extra })).toThrow()+ }+ await expect(planMemorySync([memory(), memory()], {}, [])).rejects.toThrow()+ await expect(planMemorySync([], {}, [row(memory()), row(memory())])).rejects.toThrow()+})+it('snapshots local, remote and baseline inputs before hashing yields', async () => {+ const local = memory('Local edit')+ const base = await baseline()+ const remote = row(memory())+ const planned = planMemorySync([local], base, [remote])+ local.content = 'Changed after start'+ remote.payload!.content = 'Changed server snapshot'+ base.one.revision = 100+ expect((await planned).push[0].payload?.content).toBe('Local edit')+})diff --git a/src/lib/memory-sync-plan.ts b/src/lib/memory-sync-plan.tsnew file mode 100644index 00000000..52640d22--- /dev/null+++ b/src/lib/memory-sync-plan.ts@@ -0,0 +1,116 @@+import type { MemoryFile } from '../types/agent-mode'+import { isRecord } from '../types/json-guards'+import type { SyncedMemoryRecord } from '../api/cloud/memory-sync'++export interface MemorySyncBaseline { revision: number; hash: string | null }+export interface MemorySyncPlan {+ pull: Array<{ memory: MemoryFile; baseline: MemorySyncBaseline }>+ remove: Array<{ id: string; baseline: MemorySyncBaseline }>+ push: Array<{ id: string; expectedRevision: number; payload: MemoryFile | null }>+ acknowledge: Array<{ id: string; baseline: MemorySyncBaseline }>+ conflicts: Array<{ id: string; reason: 'both-edited' | 'missing-remote' | 'deleted-baseline' }>+}+const fields = new Set(['id', 'type', 'title', 'description', 'content', 'tags', 'source', 'createdAt', 'updatedAt',+ 'sensitive', 'scope', 'sourceKind', 'confirmedAt', 'stale', 'supersededBy', 'supersedesId', 'validFrom'])+const invalid = () => new Error('Invalid synchronized memory data')+const identifier = (v: unknown): v is string => typeof v === 'string' && v.length > 0 && v.length <= 128 && v.trim() === v+const stamp = (v: unknown): v is number => typeof v === 'number' && Number.isSafeInteger(v) && v >= 0++/** Strict boundary for both cloud records and local data before upload. */+export function decodeSyncMemory(raw: unknown): MemoryFile {+ if (!isRecord(raw) || Object.keys(raw).some(key => !fields.has(key)) || !identifier(raw.id) ||+ typeof raw.type !== 'string' || !['user', 'feedback', 'project', 'reference'].includes(raw.type) ||+ typeof raw.title !== 'string' || raw.title.length > 200 ||+ typeof raw.description !== 'string' || raw.description.length > 1000 ||+ typeof raw.content !== 'string' || !raw.content.trim() || raw.content.length > 16000 ||+ typeof raw.source !== 'string' || raw.source.length > 256 ||+ !Array.isArray(raw.tags) || raw.tags.length > 50 || raw.tags.some(tag => typeof tag !== 'string' || tag.length > 100) ||+ !stamp(raw.createdAt) || !stamp(raw.updatedAt)) throw invalid()+ for (const key of ['scope', 'supersededBy', 'supersedesId']) if (raw[key] !== undefined && !identifier(raw[key])) throw invalid()+ for (const key of ['sensitive', 'stale']) if (raw[key] !== undefined && typeof raw[key] !== 'boolean') throw invalid()+ for (const key of ['confirmedAt', 'validFrom']) if (raw[key] !== undefined && !stamp(raw[key])) throw invalid()+ if (raw.sourceKind !== undefined && (typeof raw.sourceKind !== 'string' || !['chat', 'voice', 'screen'].includes(raw.sourceKind))) throw invalid()+ // Fixed key order produces stable hashes, independent of JSON key order.+ const memory: MemoryFile = {+ id: raw.id, type: raw.type as MemoryFile['type'], title: raw.title, description: raw.description,+ content: raw.content, tags: [...raw.tags] as string[], source: raw.source,+ createdAt: raw.createdAt, updatedAt: raw.updatedAt, sensitive: raw.sensitive === true, stale: raw.stale === true,+ scope: raw.scope as string | undefined, sourceKind: raw.sourceKind as MemoryFile['sourceKind'],+ confirmedAt: raw.confirmedAt as number | undefined, supersededBy: raw.supersededBy as string | undefined,+ supersedesId: raw.supersedesId as string | undefined, validFrom: raw.validFrom as number | undefined,+ }+ if (new TextEncoder().encode(JSON.stringify(memory)).length > 32768) throw invalid()+ return memory+}++async function fingerprint(memory: MemoryFile): Promise<string> {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(JSON.stringify(memory)))+ return Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')+}++export async function syncMemoryHash(memory: MemoryFile): Promise<string> {+ return fingerprint(decodeSyncMemory(memory))+}++/** Pure three-way comparison. Nothing is persisted, uploaded or applied here.+ * Acknowledgements may be saved only with the corresponding local state.+ * Push revisions must be acknowledged only after the server accepts them. */+export async function planMemorySync(+ localInput: MemoryFile[], baselineInput: Record<string, MemorySyncBaseline>, remoteInput: SyncedMemoryRecord[],+): Promise<MemorySyncPlan> {+ // Snapshot before the first await; concurrent local edits cannot change a plan.+ const local = new Map<string, MemoryFile>()+ for (const raw of localInput) {+ const memory = decodeSyncMemory(raw)+ if (local.has(memory.id)) throw invalid()+ local.set(memory.id, memory)+ }+ const baseline = new Map(Object.entries(baselineInput).map(([id, value]) => {+ if (!identifier(id) || !value || !Number.isSafeInteger(value.revision) || value.revision < 1 ||+ (value.hash !== null && (typeof value.hash !== 'string' || !/^[a-f0-9]{64}$/.test(value.hash)))) throw invalid()+ return [id, { ...value }] as const+ }))+ const remote = new Map<string, { revision: number; memory: MemoryFile | null }>()+ for (const row of remoteInput) {+ if (!identifier(row.memory_id) || remote.has(row.memory_id) || !Number.isSafeInteger(row.revision) || row.revision < 1 ||+ typeof row.deleted !== 'boolean' || (row.deleted && row.payload !== null)) throw invalid()+ const memory = row.deleted ? null : decodeSyncMemory(row.payload)+ if (memory && memory.id !== row.memory_id) throw invalid()+ remote.set(row.memory_id, { revision: row.revision, memory })+ }+ const plan: MemorySyncPlan = { pull: [], remove: [], push: [], acknowledge: [], conflicts: [] }+ for (const id of new Set([...local.keys(), ...baseline.keys(), ...remote.keys()])) {+ const current = local.get(id)+ const base = baseline.get(id)+ const server = remote.get(id)+ const localHash = current ? await fingerprint(current) : null+ if (!server) {+ if (base) plan.conflicts.push({ id, reason: 'missing-remote' })+ else if (current) plan.push.push({ id, expectedRevision: 0, payload: current })+ continue+ }+ if (base && server.revision < base.revision) throw invalid()+ const remoteHash = server.memory ? await fingerprint(server.memory) : null+ if (base && server.revision === base.revision && remoteHash !== base.hash) throw invalid()+ const next = { revision: server.revision, hash: remoteHash }+ if (!server.memory) {+ // Forget wins over pending local edits. Never retain a content copy in+ // conflict metadata for a record the account has explicitly forgotten.+ plan.remove.push({ id, baseline: next })+ } else if (base?.hash === null) {+ plan.conflicts.push({ id, reason: 'deleted-baseline' })+ } else if (!current) {+ if (base) plan.push.push({ id, expectedRevision: server.revision, payload: null })+ else plan.pull.push({ memory: server.memory, baseline: next })+ } else if (localHash === remoteHash) {+ plan.acknowledge.push({ id, baseline: next })+ } else if (base && localHash === base.hash) {+ plan.pull.push({ memory: server.memory, baseline: next })+ } else if (base && remoteHash === base.hash) {+ plan.push.push({ id, expectedRevision: server.revision, payload: current })+ } else {+ plan.conflicts.push({ id, reason: 'both-edited' })+ }+ }+ return plan+}