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
Enforce project scope boundaries in memory storage and retrieval
David4272e4ccdcd4
diff --git a/e2e/memory-scope.spec.ts b/e2e/memory-scope.spec.tsnew file mode 100644index 00000000..381dc3a2--- /dev/null+++ b/e2e/memory-scope.spec.ts@@ -0,0 +1,22 @@+import { expect, test } from '@playwright/test'++test('imported project memories retain visible scope and stay out of unscoped requests', async ({ page }) => {+ await page.goto('/e2e/memory-sensitive-proof.html')+ const entries = [+ { title: 'Alpha', content: 'Private Alpha fixture', scope: 'project-a' },+ { title: 'Beta', content: 'Private Beta fixture', scope: 'project-b' },+ { title: 'Global', content: 'Private global fixture' },+ ]+ await page.locator('input[type=file]').setInputFiles({+ name: 'memory.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify({ entries })),+ })+ await expect(page.getByText('Imported 3 memories.')).toBeVisible()+ await expect(page.getByText('Project: project-a', { exact: true })).toBeVisible()+ await expect(page.getByText('Project: project-b', { exact: true })).toBeVisible()+ await page.reload()+ await expect(page.getByText('Project: project-a', { exact: true })).toBeVisible()+ await page.getByRole('button', { name: 'Preview AI memory context' }).click()+ await expect(page.locator('#result')).toContainText('Private global fixture')+ await expect(page.locator('#result')).not.toContainText('Alpha')+ await expect(page.locator('#result')).not.toContainText('Beta')+})diff --git a/src/components/settings/MemorySettings.tsx b/src/components/settings/MemorySettings.tsxindex 9ddabeda..fedb20c9 100644--- a/src/components/settings/MemorySettings.tsx+++ b/src/components/settings/MemorySettings.tsx@@ -273,7 +273,7 @@ export function MemorySettings() {</div>{/* Search */}- <p className="text-xs text-gray-500">Mark sensitive memories to exclude them from AI requests and embeddings. This does not detect secrets automatically or erase earlier requests. Markdown export omits marked entries; JSON export includes them and their sensitivity flags.</p>+ <p className="text-xs text-gray-500">Mark sensitive memories to exclude them from AI requests and embeddings. This does not detect secrets automatically or erase earlier requests. Markdown export omits sensitive and project-scoped entries; JSON export preserves their flags and scope.</p><div className="relative"><Search size={12} className="absolute left-2.5 top-1/2 -translate-y-1/2 text-gray-500" /><input@@ -397,6 +397,7 @@ export function MemorySettings() {)}</div><p className="text-[0.6rem] text-gray-500 break-words line-clamp-2">{entry.content}</p>+ {entry.scope !== undefined && <p className="text-xs text-gray-500 break-words">Project: {entry.scope}</p>}<label className="flex gap-2 text-xs text-gray-500"><input type="checkbox" checked={entry.sensitive === true}onChange={e => updateMemory(entry.id, { sensitive: e.target.checked })} />diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.tsindex 650e9aa1..d9b7eb26 100644--- a/src/hooks/useMemory.ts+++ b/src/hooks/useMemory.ts@@ -200,7 +200,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: str// Same-type, non-stale existing memories are the only merge candidates —// a "user" fact never merges into a "reference", etc.const sameType: MemoryFile[] = memState.entries.filter(- (e) => e.type === memory.type && e.stale !== true && !e.sensitive,+ (e) => e.type === memory.type && e.stale !== true && !e.sensitive && e.scope === undefined,)if (sameType.length === 0) {addPlain()@@ -272,7 +272,7 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strif (!call) returnconst { provider, modelId } = callconst currentEntries = useMemoryStore.getState().entries- if (topK.some(candidate => !currentEntries.some(entry => entry.id === candidate.id && !entry.sensitive && entry.content === candidate.content))) return+ if (topK.some(candidate => !currentEntries.some(entry => entry.id === candidate.id && !entry.sensitive && entry.scope === undefined && entry.content === candidate.content))) returnconst messages = buildResolutionPrompt({ title: memory.title, content: memory.content },topK,diff --git a/src/stores/__tests__/memory-scope.test.ts b/src/stores/__tests__/memory-scope.test.tsnew file mode 100644index 00000000..f31389bb--- /dev/null+++ b/src/stores/__tests__/memory-scope.test.ts@@ -0,0 +1,66 @@+import { afterEach, beforeEach, expect, it } from 'vitest'+import { useMemoryStore, __setMemoryEmbedFn, memoryMatchesScope } from '../memoryStore'++beforeEach(() => {+ useMemoryStore.setState({ entries: [] })+ __setMemoryEmbedFn(async () => [])+})+afterEach(() => __setMemoryEmbedFn())+const add = (scope?: string, content = 'Project fixture') => useMemoryStore.getState().addMemory({+ type: 'project', title: content, description: content, content, tags: [], source: 'manual', scope,+})++it('includes global and exact-project entries without crossing project boundaries', async () => {+ add(undefined, 'Global fixture')+ add('A', 'Alpha fixture')+ add('B', 'Beta fixture')+ const store = useMemoryStore.getState()+ expect(store.getMemoriesForPrompt('fixture', 8192)).toContain('Global fixture')+ expect(store.getMemoriesForPrompt('fixture', 8192)).not.toMatch(/Alpha|Beta/)+ expect(store.getMemoriesForPrompt('fixture', 8192, { scope: 'A' })).toContain('Alpha fixture')+ expect(await store.getMemoriesForPromptAsync('fixture', 8192, { scope: 'A' })).not.toContain('Beta fixture')+})+it('does not deduplicate the same fact across projects', () => {+ expect(add('A')).not.toBe('')+ expect(add('B')).not.toBe('')+ expect(add('A')).toBe('')+})+it('preserves JSON scope and never promotes malformed scope to global', () => {+ add('A')+ const json = useMemoryStore.getState().exportAsJSON()+ useMemoryStore.getState().clearAll()+ expect(useMemoryStore.getState().importFromJSON(json)).toBe(1)+ expect(useMemoryStore.getState().entries[0].scope).toBe('A')+ for (const scope of [null, 12, '', ' ']) {+ expect(useMemoryStore.getState().importFromJSON(JSON.stringify([{ content: 'bad scope', scope }]))).toBe(0)+ }+ expect(useMemoryStore.getState().exportAsMarkdown()).not.toContain('Project fixture')+})+it('rejects cross-project automatic merges and accepts matching scopes', () => {+ const targetId = add('A')+ const wrongId = add('B')+ const decision = { action: 'UPDATE' as const, targetId, mergedContent: 'Merged fixture' }+ useMemoryStore.getState().applyWriteDecision(decision, { newId: wrongId })+ expect(useMemoryStore.getState().entries[0].content).toBe('Project fixture')+ const newId = add('A', 'New fixture')+ useMemoryStore.getState().applyWriteDecision(decision, { newId })+ expect(useMemoryStore.getState().entries[0].content).toBe('Merged fixture')+})+it('pins the requested scope across asynchronous fallback', async () => {+ add('A', 'Alpha fixture')+ add('B', 'Beta fixture')+ let finish!: (value: number[][]) => void+ __setMemoryEmbedFn(() => new Promise(resolve => { finish = resolve }))+ const opts = { scope: 'A' }+ const pending = useMemoryStore.getState().getMemoriesForPromptAsync('fixture', 8192, opts)+ opts.scope = 'B'+ finish([])+ const result = await pending+ expect(result).toContain('Alpha fixture')+ expect(result).not.toContain('Beta fixture')+})+it('does not match absent or blank project IDs to scoped entries', () => {+ expect(memoryMatchesScope({ scope: 'A' })).toBe(false)+ expect(memoryMatchesScope({ scope: ' ' }, ' ')).toBe(false)+ expect(memoryMatchesScope({ scope: 'A' }, 'a')).toBe(false)+})diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.tsindex 7e693ed0..a32c10f7 100644--- a/src/stores/memoryStore.ts+++ b/src/stores/memoryStore.ts@@ -32,6 +32,8 @@ function embedText(m: Pick<MemoryFile, 'title' | 'content'>): string {// ── Injection options ──────────────────────────────────────────────export interface MemoryInjectOpts {+ /** A scoped memory is eligible only for this exact nonempty project ID. */+ scope?: string/*** Drop memories that are raw TOOL RESULTS (extracted from agent sessions as* "web_search result: web_search({...}) → …"). Injected into a PLAIN chat@@ -55,6 +57,11 @@ export function isToolResultMemory(m: Pick<MemoryFile, 'title' | 'content'>): boconst probe = `${m.title || ''}\n${m.content || ''}`return /\b[a-z][a-z0-9_]* result:/i.test(probe)}++export function memoryMatchesScope(memory: Pick<MemoryFile, 'scope'>, scope?: string): boolean {+ return memory.scope === undefined ||+ (typeof memory.scope === 'string' && memory.scope.trim().length > 0 && memory.scope === scope)+}function hashContent(s: string): string {let h = 5381for (let i = 0; i < s.length; i++) h = (h * 33) ^ s.charCodeAt(i)@@ -253,7 +260,7 @@ interface MemoryState {// CRUDaddMemory: (memory: Omit<MemoryFile, 'id' | 'createdAt' | 'updatedAt'>) => string- updateMemory: (id: string, updates: Partial<Pick<MemoryFile, 'title' | 'description' | 'content' | 'type' | 'tags' | 'sensitive'>>) => void+ updateMemory: (id: string, updates: Partial<Pick<MemoryFile, 'title' | 'description' | 'content' | 'type' | 'tags' | 'sensitive' | 'scope'>>) => voidremoveMemory: (id: string) => voidclearAll: () => void@@ -376,6 +383,7 @@ function migrateV2toV3(oldState: unknown): unknown {*/function asMemoryFile(v: unknown): MemoryFile | null {if (!isRecord(v)) return null+ if (v.scope !== undefined && (typeof v.scope !== 'string' || !v.scope.trim())) return nullconst content = asString(v.content)if (!content) return nullconst now = Date.now()@@ -391,6 +399,7 @@ function asMemoryFile(v: unknown): MemoryFile | null {updatedAt: asNumber(v.updatedAt) ?? asNumber(v.createdAt) ?? now,source: asString(v.source) ?? 'migration',sensitive: v.sensitive === true,+ scope: asString(v.scope),supersededBy: asString(v.supersededBy),supersedesId: asString(v.supersedesId),stale: v.stale === true,@@ -485,12 +494,13 @@ export const useMemoryStore = create<MemoryState>()(// ── CRUD ────────────────────────────────────────────────addMemory: (memory) => {+ if (memory.scope !== undefined && !memory.scope.trim()) return ''const trimmedContent = memory.content.trim()if (!trimmedContent) return ''// Deduplicate: don't add if exact same content + type existsconst existing = get().entries- if (existing.some(e => e.content === trimmedContent && e.type === memory.type)) return ''+ if (existing.some(e => e.content === trimmedContent && e.type === memory.type && e.scope === memory.scope)) return ''const id = uuid()set((state) => ({@@ -512,6 +522,7 @@ export const useMemoryStore = create<MemoryState>()(},updateMemory: (id, updates) => {+ if (updates.scope !== undefined && !updates.scope.trim()) returnset((state) => ({entries: state.entries.map((e) =>e.id === id ? { ...e, ...updates, updatedAt: Date.now() } : e@@ -574,7 +585,7 @@ export const useMemoryStore = create<MemoryState>()(if (budget.budgetTokens === 0 || budget.maxMemories === 0) return ''const words = query.toLowerCase().split(/\s+/).filter(w => w.length > 2)- let candidates = get().entries.filter(e => !e.sensitive && !isStale(e))+ let candidates = get().entries.filter(e => !e.sensitive && !isStale(e) && memoryMatchesScope(e, opts?.scope))if (opts?.excludeToolResults) {candidates = candidates.filter(e => !isToolResultMemory(e))}@@ -605,7 +616,8 @@ export const useMemoryStore = create<MemoryState>()(// back to the keyword result. Offline correctness invariant: this never// returns empty/incorrect when the sync path would have returned text.getMemoriesForPromptAsync: async (query, contextTokens, opts) => {- const fallback = () => get().getMemoriesForPrompt(query, contextTokens, opts)+ const requestOpts = opts ? { ...opts } : undefined+ const fallback = () => get().getMemoriesForPrompt(query, contextTokens, requestOpts)const snapshot = get().entriestry {const budget = effectiveMemoryBudget(contextTokens, get().settings.maxMemoriesOverride)@@ -615,8 +627,8 @@ export const useMemoryStore = create<MemoryState>()(// stubbed sync method in tests is honoured).if (budget.budgetTokens === 0 || budget.maxMemories === 0) return fallback()- let candidates = get().entries.filter(e => !e.sensitive && !isStale(e))- if (opts?.excludeToolResults) {+ let candidates = get().entries.filter(e => !e.sensitive && !isStale(e) && memoryMatchesScope(e, requestOpts?.scope))+ if (requestOpts?.excludeToolResults) {candidates = candidates.filter(e => !isToolResultMemory(e))}if (budget.typesAllowed !== 'all') {@@ -688,6 +700,8 @@ export const useMemoryStore = create<MemoryState>()(if (!targetId || !mergedContent) returnconst target = get().entries.find((e) => e.id === targetId)if (!target || target.sensitive) return+ const candidate = ctx?.newId ? get().entries.find(e => e.id === ctx.newId) : undefined+ if (target.scope !== candidate?.scope) returnconst merged = mergedContent.trim()if (!merged) return@@ -770,7 +784,7 @@ export const useMemoryStore = create<MemoryState>()(// ── Export / Import ─────────────────────────────────────exportAsMarkdown: () => {- const entries = get().entries.filter(e => !e.sensitive)+ const entries = get().entries.filter(e => !e.sensitive && e.scope === undefined)if (entries.length === 0) return '# Memory\n\nNo entries yet.\n'const typeOrder: MemoryType[] = ['user', 'feedback', 'project', 'reference']@@ -874,6 +888,8 @@ export const useMemoryStore = create<MemoryState>()(const now = Date.now()const newEntries: MemoryFile[] = []for (const e of arr) {+ const scope = prop(e, 'scope')+ if (scope !== undefined && (typeof scope !== 'string' || !scope.trim())) continue// `content` may also arrive as `text` / `value` — a foreign export's// spelling. Only a real string counts: the old String(...) turned an// object into the literal "[object Object]" and imported that.@@ -893,6 +909,7 @@ export const useMemoryStore = create<MemoryState>()(updatedAt: now,source: asString(prop(e, 'source')) ?? 'import',sensitive: prop(e, 'sensitive') === true,+ scope: asString(scope),})}if (newEntries.length > 0) {diff --git a/src/types/agent-mode.ts b/src/types/agent-mode.tsindex af7137cb..893b4d3c 100644--- a/src/types/agent-mode.ts+++ b/src/types/agent-mode.ts@@ -166,6 +166,8 @@ export interface MemoryFile {source: string // conversationId | 'manual' | 'auto:extraction'/** User-marked sensitive entries stay out of AI requests and embeddings. */sensitive?: boolean+ /** Stable project ID. Undefined retains legacy global memory behavior. */+ scope?: string// ── Staleness / supersession (Feature FF, v2.5.0) ─────────────// All OPTIONAL so pre-v2.5 persisted memories rehydrate unchanged; the// store's migrate() leaves them undefined and the retrieval layer treats