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
feat(cost): the silent memory call asks first, then takes the cheap model
Davidf1f06bf3b95b
diff --git a/src/hooks/__tests__/memory-silent-call-gate.test.ts b/src/hooks/__tests__/memory-silent-call-gate.test.tsnew file mode 100644index 00000000..646e8d12--- /dev/null+++ b/src/hooks/__tests__/memory-silent-call-gate.test.ts@@ -0,0 +1,189 @@+/**+ * A7: the auto-memory extraction is a PAID call on lu-cloud, so it only fires+ * with the explicit opt-in, and then on the cheapest catalogue model instead of+ * the active one.+ *+ * These run the real `extractMemoriesFromPair` with mocked stores/providers, so+ * the assertion is "did a request leave the app", not "does the source contain+ * a guard". The gate sits inside the extraction function, one level below every+ * caller (useChat, useCodex, the remote listener), which is what makes it+ * inheritable — a new call site cannot forget it.+ *+ * NEGATIVE CONTROL (verified by hand, documented so the next reader can redo+ * it): drop the `if (!call) return` in useMemory.ts's extractMemoriesFromPair,+ * or make silentCallAllowed return true unconditionally, and+ * "fires no request on lu-cloud without the opt-in" goes red.+ *+ * Run: npx vitest run src/hooks/__tests__/memory-silent-call-gate.test.ts+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'++// ── Mocked module graph ────────────────────────────────────────+// Everything the extraction touches, kept dumb so the only interesting+// question is whether chatStream was reached and with which model.++const chatStream = vi.fn()+const addMemory = vi.fn(() => 'mem-1')++let activeModel = 'qwen3:8b'+let models: Array<{ name: string; type: string }> = []+let memoryCloudOptIn = false+let memorySettings = { autoExtractEnabled: true, autoExtractInAllModes: false }++vi.mock('../../stores/modelStore', () => ({+ useModelStore: { getState: () => ({ activeModel, models }) },+}))++vi.mock('../../stores/memoryStore', () => ({+ useMemoryStore: {+ getState: () => ({+ settings: memorySettings,+ entries: [],+ addMemory,+ removeMemory: vi.fn(),+ applyWriteDecision: vi.fn(),+ }),+ },+}))++vi.mock('../../stores/providerStore', () => ({+ useProviderStore: {+ getState: () => ({+ providers: {+ openai: { enabled: true, isLocal: true },+ anthropic: { enabled: false },+ },+ }),+ },+}))++vi.mock('../../stores/settingsStore', () => ({+ useSettingsStore: {+ getState: () => ({ settings: { memoryCloudOptIn, contextWindowOverride: 0 } }),+ },+}))++vi.mock('../../api/providers', () => ({+ getProviderForModel: (name: string) => ({+ provider: { chatStream },+ modelId: name.includes('::') ? name.split('::')[1] : name,+ }),+ getProviderIdFromModel: (name: string) =>+ name.includes('::') ? name.split('::')[0] : 'ollama',+}))++vi.mock('../../lib/agent-num-ctx', () => ({+ resolveAgentNumCtx: vi.fn(async () => 8192),+}))++vi.mock('../../api/rag', () => ({+ generateEmbeddings: vi.fn(async () => [[]]),+ cosineSimilarity: vi.fn(() => 0),+}))++vi.mock('../../lib/memoryEmbedDB', () => ({+ loadVectors: vi.fn(async () => new Map()),+}))++const { extractMemoriesFromPair } = await import('../useMemory')++// The extraction is rate-limited to every 3rd turn (module counter). Three+// consecutive calls therefore contain EXACTLY one attempt, whatever the+// counter's starting value — so each scenario drives three turns.+const RATE_LIMIT = 3+const LONG_REPLY = 'x'.repeat(200)++async function threeTurns() {+ for (let i = 0; i < RATE_LIMIT; i++) {+ await extractMemoriesFromPair('what do I do for work?', LONG_REPLY, 'conv-1')+ }+}++/** One empty stream, so the extraction completes without parsing anything. */+function emptyStream() {+ return (async function* () {+ yield { content: '', done: true }+ })()+}++beforeEach(() => {+ chatStream.mockReset()+ chatStream.mockImplementation(() => emptyStream())+ addMemory.mockClear()+ memorySettings = { autoExtractEnabled: true, autoExtractInAllModes: false }+ models = [+ { name: 'lu-cloud::Qwen/Qwen3-Coder-480B-A35B-Instruct', type: 'text' },+ { name: 'lu-cloud::meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo', type: 'text' },+ { name: 'qwen3:8b', type: 'text' },+ ]+})++describe('lu-cloud', () => {+ it('fires no request without the opt-in (the shipped default)', async () => {+ activeModel = 'lu-cloud::Qwen/Qwen3-Coder-480B-A35B-Instruct'+ memoryCloudOptIn = false++ await threeTurns()++ expect(chatStream).not.toHaveBeenCalled()+ })++ it('fires on the cheapest catalogue model once the user opts in', async () => {+ activeModel = 'lu-cloud::Qwen/Qwen3-Coder-480B-A35B-Instruct'+ memoryCloudOptIn = true++ await threeTurns()++ expect(chatStream).toHaveBeenCalledTimes(1)+ expect(chatStream.mock.calls[0][0]).toBe('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo')+ // and never the flagship the visible chat is running on+ expect(chatStream.mock.calls[0][0]).not.toContain('480B')+ })+})++describe('local and BYOK stay ungated', () => {+ it('a local model extracts with the opt-in off', async () => {+ activeModel = 'qwen3:8b'+ memoryCloudOptIn = false++ await threeTurns()++ expect(chatStream).toHaveBeenCalledTimes(1)+ expect(chatStream.mock.calls[0][0]).toBe('qwen3:8b')+ })++ it('a BYOK Anthropic model extracts on the active model, opt-in off', async () => {+ activeModel = 'anthropic::claude-sonnet-4-20250514'+ memoryCloudOptIn = false+ // BYOK keeps its own switch (memory settings), which the audit left alone.+ memorySettings = { autoExtractEnabled: true, autoExtractInAllModes: true }++ await threeTurns()++ expect(chatStream).toHaveBeenCalledTimes(1)+ expect(chatStream.mock.calls[0][0]).toBe('claude-sonnet-4-20250514')+ })+})++describe('the existing guards still hold', () => {+ it('extracts nothing when auto-extract is switched off', async () => {+ activeModel = 'qwen3:8b'+ memoryCloudOptIn = true+ memorySettings = { autoExtractEnabled: false, autoExtractInAllModes: true }++ await threeTurns()++ expect(chatStream).not.toHaveBeenCalled()+ })++ it('skips a reply too short to hold a fact', async () => {+ activeModel = 'qwen3:8b'+ memoryCloudOptIn = true++ for (let i = 0; i < RATE_LIMIT; i++) {+ await extractMemoriesFromPair('hi', 'ok', 'conv-1')+ }++ expect(chatStream).not.toHaveBeenCalled()+ })+})diff --git a/src/hooks/useMemory.ts b/src/hooks/useMemory.tsindex 1fc76312..88b0e720 100644--- a/src/hooks/useMemory.ts+++ b/src/hooks/useMemory.ts@@ -23,6 +23,7 @@ import {} from '../lib/memory-extraction'import { generateEmbeddings, cosineSimilarity } from '../api/rag'import { loadVectors } from '../lib/memoryEmbedDB'+import { silentCallAllowed, pickSilentCallModel } from '../lib/silent-model-calls'import type { MemoryFile } from '../types/agent-mode'// Rate limit: only extract every Nth turn to reduce cost@@ -42,10 +43,37 @@ const NOOP_THRESHOLD = 0.92// How many similar existing memories to show the resolver.const RESOLUTION_TOP_K = 3+/**+ * The provider + model a SILENT memory call may run on, or null when the cost+ * policy forbids the call outright (plan 2.6.6 A7).+ *+ * Resolving it HERE, one level below every extraction path, is the point: the+ * gate and the cheap-model choice apply to `extractMemoriesFromPair` and to+ * the write-decision resolution alike, so no hook, listener or background job+ * has to remember them. Adding a caller cannot add a silent cloud call.+ *+ * lu-cloud without the opt-in → null → no request leaves the app.+ * lu-cloud with the opt-in → the cheapest catalogue model, not the active one.+ * Local / BYOK → the active model, ungated, exactly as before.+ */+function resolveSilentCall(+ activeModel: string,+): { provider: ReturnType<typeof getProviderForModel>['provider']; modelId: string; callModel: string } | null {+ const providerId = getProviderIdFromModel(activeModel)+ const { memoryCloudOptIn } = useSettingsStore.getState().settings+ if (!silentCallAllowed(providerId, memoryCloudOptIn)) return null+ const callModel = pickSilentCallModel(activeModel, providerId, useModelStore.getState().models)+ const { provider, modelId } = getProviderForModel(callModel)+ return { provider, modelId, callModel }+}+/*** Pure extraction routine — safe to call from anywhere (hooks, Tauri listeners,* background jobs). Fire-and-forget: never throws, errors are swallowed.*+ * The A7 cost policy lives INSIDE (see resolveSilentCall), so every caller+ * below inherits it without a line of its own.+ ** Used by:* - useMemory().extractAndSave (LU chat)* - useAgentChat (agent loop)@@ -85,18 +113,24 @@ export async function extractMemoriesFromPair(const messages = buildExtractionPrompt(userMessage, assistantResponse, existingSummary)- // Use active provider for extraction call- const { provider, modelId } = getProviderForModel(activeModel)+ // Cost gate + cheapest suitable model (plan A7). Null = this call is not+ // allowed to happen at all; on lu-cloud without the opt-in that is the+ // default, and the turn ends here with no request on the wire.+ const call = resolveSilentCall(activeModel)+ if (!call) return+ const { provider, modelId, callModel } = call// Same num_ctx as the chat that just ran on this model. Ollama reloads the// model whenever num_ctx changes between requests, so an options-less// extraction call silently dropped the user's context back to the default- // and paid a second model load per turn.+ // and paid a second model load per turn. Resolved for the model this call+ // ACTUALLY runs on — on lu-cloud that is the cheap one, whose window has+ // nothing to do with the active model's.const numCtx = await resolveAgentNumCtx(modelId,- getProviderIdFromModel(activeModel),+ getProviderIdFromModel(callModel),useSettingsStore.getState().settings.contextWindowOverride,- activeModel,+ callModel,)// Collect full response via streaming@@ -232,7 +266,12 @@ async function resolveAndSaveMemory(memory: ExtractedMemory, conversationId: strtry {const { activeModel } = useModelStore.getState()if (!activeModel) return // candidate already added; leave as ADD- const { provider, modelId } = getProviderForModel(activeModel)+ // Second silent call of the turn — same cost policy as the extraction+ // itself (plan A7). Gated out means the candidate simply stays a plain+ // ADD, which is the same outcome a failed resolution already produces.+ const call = resolveSilentCall(activeModel)+ if (!call) return+ const { provider, modelId } = callconst messages = buildResolutionPrompt({ title: memory.title, content: memory.content },topK,diff --git a/src/lib/__tests__/silent-model-calls.test.ts b/src/lib/__tests__/silent-model-calls.test.tsnew file mode 100644index 00000000..ac6427d9--- /dev/null+++ b/src/lib/__tests__/silent-model-calls.test.ts@@ -0,0 +1,135 @@+/**+ * A7/R5 cost policy for silent model calls.+ *+ * Run: npx vitest run src/lib/__tests__/silent-model-calls.test.ts+ */+import { describe, it, expect } from 'vitest'+import {+ silentCallAllowed,+ pickSilentCallModel,+ paramSizeB,+ CHEAP_CLOUD_TEXT_MODELS,+} from '../silent-model-calls'++const cloudModel = (id: string) => ({ name: `lu-cloud::${id}`, type: 'text' })++describe('silentCallAllowed', () => {+ it('blocks lu-cloud while the opt-in is off (the default)', () => {+ expect(silentCallAllowed('lu-cloud', false)).toBe(false)+ })++ it('allows lu-cloud once the user opts in', () => {+ expect(silentCallAllowed('lu-cloud', true)).toBe(true)+ })++ it('never gates a local or BYOK provider, opt-in or not', () => {+ for (const id of ['ollama', 'openai', 'anthropic']) {+ expect(silentCallAllowed(id, false)).toBe(true)+ expect(silentCallAllowed(id, true)).toBe(true)+ }+ })+})++describe('pickSilentCallModel', () => {+ const catalogue = [+ cloudModel('Qwen/Qwen3-Coder-480B-A35B-Instruct'),+ cloudModel('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'),+ cloudModel('deepseek-ai/DeepSeek-V4'),+ ]++ it('leaves a local run on the active model (a second model = a second load)', () => {+ expect(pickSilentCallModel('qwen3:8b', 'ollama', catalogue)).toBe('qwen3:8b')+ })++ it('leaves a BYOK run on the active model', () => {+ expect(+ pickSilentCallModel('anthropic::claude-sonnet-4-20250514', 'anthropic', catalogue),+ ).toBe('anthropic::claude-sonnet-4-20250514')+ })++ it('swaps a cloud flagship for the cheapest catalogue model', () => {+ expect(+ pickSilentCallModel('lu-cloud::Qwen/Qwen3-Coder-480B-A35B-Instruct', 'lu-cloud', catalogue),+ ).toBe('lu-cloud::meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo')+ })++ it('follows the preference order, not the catalogue order', () => {+ const reordered = [+ cloudModel('meta-llama/Llama-3.3-70B-Instruct-Turbo'),+ cloudModel('Sao10K/L3-8B-Lunaris-v1-Turbo'),+ cloudModel('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'),+ ]+ expect(pickSilentCallModel('lu-cloud::whatever', 'lu-cloud', reordered)).toBe(+ 'lu-cloud::meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',+ )+ })++ it('takes the second choice when the first is not served to this account', () => {+ const hostedOnly = [+ cloudModel('Sao10K/L3-8B-Lunaris-v1-Turbo'),+ cloudModel('Qwen/Qwen3-Coder-480B-A35B-Instruct'),+ ]+ expect(pickSilentCallModel('lu-cloud::whatever', 'lu-cloud', hostedOnly)).toBe(+ 'lu-cloud::Sao10K/L3-8B-Lunaris-v1-Turbo',+ )+ })++ it('falls back to the smallest model when the catalogue moved on entirely', () => {+ const unknown = [+ cloudModel('vendor/Giant-405B-Instruct'),+ cloudModel('vendor/Small-12B-Instruct'),+ cloudModel('vendor/Middle-70B-Instruct'),+ ]+ expect(pickSilentCallModel('lu-cloud::vendor/Giant-405B-Instruct', 'lu-cloud', unknown)).toBe(+ 'lu-cloud::vendor/Small-12B-Instruct',+ )+ })++ it('keeps the active model when nothing recognisable is available', () => {+ expect(pickSilentCallModel('lu-cloud::x/mystery', 'lu-cloud', [cloudModel('x/mystery')])).toBe(+ 'lu-cloud::x/mystery',+ )+ expect(pickSilentCallModel('lu-cloud::x/mystery', 'lu-cloud', [])).toBe('lu-cloud::x/mystery')+ })++ it('ignores image and video entries sharing the model list', () => {+ const mixed = [+ { name: 'lu-cloud::some/image-model', type: 'image' },+ cloudModel('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo'),+ ]+ expect(pickSilentCallModel('lu-cloud::flagship', 'lu-cloud', mixed)).toBe(+ 'lu-cloud::meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo',+ )+ })++ it('never picks a local model for a cloud run', () => {+ const withLocal = [{ name: 'qwen3:0.6b', type: 'text' }, cloudModel('vendor/Small-12B-Instruct')]+ expect(pickSilentCallModel('lu-cloud::flagship', 'lu-cloud', withLocal)).toBe(+ 'lu-cloud::vendor/Small-12B-Instruct',+ )+ })+})++describe('paramSizeB', () => {+ it('reads the total size, not the active-parameter suffix', () => {+ expect(paramSizeB('Qwen/Qwen3-30B-A3B')).toBe(30)+ expect(paramSizeB('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo')).toBe(8)+ expect(paramSizeB('openai/gpt-oss-120b')).toBe(120)+ expect(paramSizeB('NousResearch/Hermes-3-Llama-3.1-405B')).toBe(405)+ })++ it('returns null when the id says nothing about size', () => {+ expect(paramSizeB('deepseek-ai/DeepSeek-V4-Flash-0731')).toBeNull()+ expect(paramSizeB('inclusionAI/Ling-3.0-flash')).toBeNull()+ })+})++describe('the preference list itself', () => {+ it('leads with the catalogue entry that is on every plan and cheapest', () => {+ expect(CHEAP_CLOUD_TEXT_MODELS[0]).toBe('meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo')+ })++ it('has no duplicates', () => {+ expect(new Set(CHEAP_CLOUD_TEXT_MODELS).size).toBe(CHEAP_CLOUD_TEXT_MODELS.length)+ })+})diff --git a/src/lib/silent-model-calls.ts b/src/lib/silent-model-calls.tsnew file mode 100644index 00000000..4c3bab54--- /dev/null+++ b/src/lib/silent-model-calls.ts@@ -0,0 +1,140 @@+/**+ * Cost policy for SILENT model calls (plan 2.6.6 A7 + R5).+ *+ * A silent call is any inference request that does NOT produce the visible+ * assistant reply: memory extraction, the memory write-decision resolution,+ * and anything a future hidden agent adds. opencode's hidden agents+ * (compaction, title, summary) are the warning example — silent model calls+ * are silent money, and on lu-cloud they are billed exactly like a chat turn.+ *+ * Two rules, defined ONCE here so every caller inherits them by construction+ * instead of each call site re-deciding:+ *+ * 1. GATE — on lu-cloud a silent call needs `settings.memoryCloudOptIn`.+ * Default off means a cloud conversation fires NO hidden request at all.+ * Local backends (Ollama, built-in engine, LM Studio) and BYOK keys are+ * not gated: those calls cost the user nothing we bill for, and BYOK+ * already has its own switch (memory settings `autoExtractInAllModes`).+ *+ * 2. MODEL — when a silent call does run on lu-cloud it runs on the cheapest+ * suitable catalogue model, never the active one. The active model may be+ * a flagship at ~20x the price of the entry model, and a hidden JSON+ * extraction has no use for it. Locally the active model stays: a second+ * local model would mean a second VRAM load, which is the expensive+ * option there.+ *+ * This module is PURE — no stores, no providers, no network. Callers pass the+ * resolved provider id and the model list in.+ */++/**+ * lu-cloud text models ranked cheapest-first, restricted to plain instruct+ * models (no reasoner burns hidden output tokens, no vision surcharge).+ *+ * Derived from the server catalogue (`lib/chat/tier-models.ts`, wholesale+ * $/1M in + out, refreshed 2026-08-09). The first two are on EVERY plan; the+ * rest are the Pro-catalogue fallbacks for the (impossible today, possible+ * tomorrow) case that the hosted shortlist changes under us.+ *+ * NOT a pin: this list is a PREFERENCE, intersected with the models the+ * server actually serves this account right now. Nothing here is required to+ * exist — an id that vanishes from the catalogue is skipped, and if none of+ * them survive, `pickSilentCallModel` falls back to the live size heuristic+ * and finally to the active model. Prices drift daily (see the price-drift+ * guard on the server side), so treat the ORDER as the durable part.+ */+export const CHEAP_CLOUD_TEXT_MODELS: readonly string[] = [+ 'meta-llama/Meta-Llama-3.1-8B-Instruct-Turbo', // $0.02 / $0.04, hosted+ 'Sao10K/L3-8B-Lunaris-v1-Turbo', // $0.04 / $0.05, hosted+ 'mistralai/Mistral-Small-3.2-24B-Instruct-2506', // $0.075 / $0.20, pro+ 'meta-llama/Llama-4-Scout-17B-16E-Instruct', // $0.10 / $0.30, pro+ 'meta-llama/Llama-3.3-70B-Instruct-Turbo', // $0.10 / $0.32, pro+]++/** Provider ids that bill against the user's LU Cloud credits. */+const METERED_PROVIDERS: ReadonlySet<string> = new Set(['lu-cloud'])++/**+ * May a silent (non-visible) model call fire on this provider?+ *+ * @param providerId provider of the model the call would run on+ * @param cloudOptIn `settings.memoryCloudOptIn`+ */+export function silentCallAllowed(providerId: string, cloudOptIn: boolean): boolean {+ if (!METERED_PROVIDERS.has(providerId)) return true+ return cloudOptIn === true+}++/**+ * Parameter count in billions parsed out of a model id ("…-8B-Instruct" → 8,+ * "gpt-oss-120b" → 120). The FIRST match wins, which is the total size on+ * every catalogue id that also names its active params ("Qwen3-30B-A3B" → 30).+ * Returns null when the id says nothing about size.+ *+ * Only a fallback ordering signal: the catalogue carries no price field on the+ * client (`/api/inference/v1/models` ships id, context, modalities, think and+ * tools, never $), and size is the one live, self-describing proxy for cost.+ */+export function paramSizeB(modelId: string): number | null {+ const m = /(\d+(?:\.\d+)?)\s*b(?![a-z0-9])/i.exec(modelId)+ if (!m) return null+ const n = Number(m[1])+ return Number.isFinite(n) && n > 0 ? n : null+}++/** The shape `pickSilentCallModel` needs out of the model store. */+export interface SilentCallCandidate {+ /** Prefixed store name, e.g. `lu-cloud::meta-llama/Meta-Llama-3.1-8B…`. */+ name: string+ type?: string+ provider?: string+}++const CLOUD_PREFIX = 'lu-cloud::'++/**+ * Which model a silent call should run on.+ *+ * lu-cloud → the cheapest catalogue text model that is actually available:+ * the preference list first, then the smallest model by parsed parameter+ * count, then (nothing recognisable) the active model unchanged.+ * Every other provider → the active model, unchanged.+ *+ * @param activeModel the prefixed model the visible chat is running on+ * @param providerId provider of `activeModel`+ * @param models the model store's list (any non-text entries ignored)+ */+export function pickSilentCallModel(+ activeModel: string,+ providerId: string,+ models: readonly SilentCallCandidate[],+): string {+ if (!METERED_PROVIDERS.has(providerId)) return activeModel++ const available = models.filter(+ (m) =>+ typeof m.name === 'string' &&+ m.name.startsWith(CLOUD_PREFIX) &&+ (m.type === undefined || m.type === 'text'),+ )+ if (available.length === 0) return activeModel++ const ids = new Set(available.map((m) => m.name.slice(CLOUD_PREFIX.length)))+ for (const preferred of CHEAP_CLOUD_TEXT_MODELS) {+ if (ids.has(preferred)) return `${CLOUD_PREFIX}${preferred}`+ }++ // Nothing from the preference list is served — fall back to the smallest+ // model the catalogue names a size for.+ let bestId: string | null = null+ let bestSize = Infinity+ for (const id of ids) {+ const size = paramSizeB(id)+ if (size === null) continue+ if (size < bestSize) {+ bestSize = size+ bestId = id+ }+ }+ return bestId ? `${CLOUD_PREFIX}${bestId}` : activeModel+}diff --git a/src/stores/__tests__/memory-context-cap.test.ts b/src/stores/__tests__/memory-context-cap.test.tsnew file mode 100644index 00000000..bfa29237--- /dev/null+++ b/src/stores/__tests__/memory-context-cap.test.ts@@ -0,0 +1,79 @@+/**+ * A7: the remembered-context block that rides in EVERY system prompt is capped+ * at ~1k tokens.+ *+ * The budget tiers hand out 2000 tokens at 128k context and 4000 above it, and+ * that block is re-sent on every step of every agent turn. The cap sits in+ * renderRememberedContext, the one place the string is built, so all four+ * injection sites (useChat, useAgentChat, useCodex, the remote dispatcher)+ * inherit it. Under the cap nothing changes: a small memory set is still+ * injected whole.+ *+ * NEGATIVE CONTROL (verified by hand): drop the `Math.min(budgetTokens,+ * MEMORY_CONTEXT_TOKEN_CAP)` line in memoryStore.ts and "caps a big memory set"+ * goes red at ~8000 chars.+ *+ * Run: npx vitest run src/stores/__tests__/memory-context-cap.test.ts+ */+import { describe, it, expect, beforeEach } from 'vitest'+import { useMemoryStore, MEMORY_CONTEXT_TOKEN_CAP } from '../memoryStore'++// The tier for a 128k model: 2000 tokens, 15 memories — double the cap.+const BIG_CONTEXT = 131072+const CAP_CHARS = MEMORY_CONTEXT_TOKEN_CAP * 4++function seed(count: number, contentLength: number) {+ const store = useMemoryStore.getState()+ store.clearAll()+ for (let i = 0; i < count; i++) {+ store.addMemory({+ type: 'user',+ title: `Fact ${i} about deployment`,+ description: 'deployment note',+ content: `deployment ${i} ${'detail '.repeat(Math.ceil(contentLength / 7)).slice(0, contentLength)}`,+ tags: ['deployment'],+ } as never)+ }+}++beforeEach(() => {+ useMemoryStore.getState().clearAll()+})++describe('memory context cap', () => {+ it('caps a big memory set at the 1k-token ceiling', () => {+ // 15 entries x ~400 injected chars is ~6000 chars, well past the cap and+ // inside the tier's own 8000-char budget, so only the cap can trim it.+ seed(15, 400)+ const block = useMemoryStore.getState().getMemoriesForPrompt('deployment', BIG_CONTEXT)++ expect(block).not.toBe('')+ expect(block.length).toBeLessThanOrEqual(CAP_CHARS + 64) // + the wrapper tags+ })++ it('leaves a small set fully injected', () => {+ seed(3, 60)+ const block = useMemoryStore.getState().getMemoriesForPrompt('deployment', BIG_CONTEXT)++ for (let i = 0; i < 3; i++) {+ expect(block).toContain(`Fact ${i} about deployment`)+ }+ expect(block.length).toBeLessThan(CAP_CHARS)+ })++ it('never raises a tier that already budgets less than the cap', () => {+ // The 8k tier budgets 800 tokens; the cap must not become a floor.+ seed(8, 400)+ const small = useMemoryStore.getState().getMemoriesForPrompt('deployment', 8192)+ expect(small.length).toBeLessThanOrEqual(800 * 4 + 64)+ })++ it('applies on the async (embedding-blended) path too', async () => {+ seed(15, 400)+ const block = await useMemoryStore+ .getState()+ .getMemoriesForPromptAsync('deployment', BIG_CONTEXT)++ expect(block.length).toBeLessThanOrEqual(CAP_CHARS + 64)+ })+})diff --git a/src/stores/memoryStore.ts b/src/stores/memoryStore.tsindex 8e4a30ef..ad829e73 100644--- a/src/stores/memoryStore.ts+++ b/src/stores/memoryStore.ts@@ -181,15 +181,32 @@ const TYPE_SECTION_HEADERS: Record<MemoryType, string> = {const TYPE_ORDER: MemoryType[] = ['user', 'feedback', 'project', 'reference']+/**+ * Hard ceiling for the injected memory block, in tokens (plan 2.6.6 A7).+ *+ * The budget tiers hand out up to 4000 tokens of memory on a large-context+ * model, and that block rides along in EVERY request of EVERY turn — it is+ * paid for again on each step of an agent run, forever, whether or not a+ * single memory was relevant. 1k is the ceiling; a block that already fits+ * under it is injected in full and unchanged, so the cap only ever bites the+ * oversized case.+ */+export const MEMORY_CONTEXT_TOKEN_CAP = 1000+/*** Render an ALREADY-ORDERED, ALREADY-FILTERED list of memories into the* grouped <remembered_context> block, respecting the tier's char budget and* sanitizing every injected line. Shared by the sync (keyword) and async* (embedding-blended) retrieval paths — ONLY the candidate ordering differs* between them, so the output formatting lives here once.+ *+ * The A7 cap is applied HERE, at the one place the string is built, so every+ * injection site (useChat, useAgentChat, useCodex, the remote dispatcher)+ * inherits it and none of them can drift.*/function renderRememberedContext(ordered: MemoryFile[], budgetTokens: number): string {if (ordered.length === 0) return ''+ const cappedTokens = Math.min(budgetTokens, MEMORY_CONTEXT_TOKEN_CAP)// Group by type for structured output (preserve incoming order within type).const grouped: Record<MemoryType, MemoryFile[]> = {@@ -197,7 +214,7 @@ function renderRememberedContext(ordered: MemoryFile[], budgetTokens: number): s}for (const entry of ordered) grouped[entry.type].push(entry)- const maxChars = budgetTokens * 4+ const maxChars = cappedTokens * 4let result = ''for (const type of TYPE_ORDER) {