From 06d73ce6293a495510a6fad7ef086883e9fc00fc Mon Sep 17 00:00:00 2001 From: ptitan Date: Tue, 17 Nov 2026 15:58:43 +0100 Subject: [PATCH 1/2] fix(ai): resolve opencodeModel "inherit" in profile cleanup Profile cleanup passed the configured model verbatim to session.prompt, so `opencodeModel: "inherit"` reached OpenCode as a literal model id and failed with `Generate.ModelNotFoundError: Model not found: /inherit`. Auto-capture is unaffected because it resolves "inherit" from the prompt record; cleanup has no prompt of its own. Resolve the model with resolveOpencodeModelRef before creating the transient session, so an unresolvable "inherit" fails with an explicit message and no session is created. Drop the unreachable hardcoded fallbacks (bs-aigw / deepseek-v4-flash): callAICleanup only takes this path when both settings are configured. --- src/services/user-profile/ai-cleanup.ts | 15 ++++++--- tests/ai-cleanup.test.ts | 44 +++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 6 deletions(-) diff --git a/src/services/user-profile/ai-cleanup.ts b/src/services/user-profile/ai-cleanup.ts index 1be0a2edc..2a06cfbfa 100644 --- a/src/services/user-profile/ai-cleanup.ts +++ b/src/services/user-profile/ai-cleanup.ts @@ -337,6 +337,16 @@ async function callViaOpencodeWithClient( const systemPrompt = "You are a user profile cleanup assistant. Merge duplicate entries and return only JSON without markdown wrapping."; + // Resolve `opencodeModel: "inherit"` before creating the session, so the + // literal "inherit" never reaches session.prompt. callAICleanup only routes + // here when both opencodeProvider and opencodeModel are set. + const { resolveOpencodeModelRef } = await import("../ai/opencode-provider.js"); + const model = resolveOpencodeModelRef({ + providerID: CONFIG.opencodeProvider!, + modelID: CONFIG.opencodeModel!, + }); + log("AI cleanup: model resolved", model); + const created = (await raceWithTimeout( v2Client.session.create({ title: "opencode-mem profile cleanup", @@ -362,10 +372,7 @@ async function callViaOpencodeWithClient( const promptResult = await raceWithTimeout( v2Client.session.prompt({ sessionID, - model: { - providerID: CONFIG.opencodeProvider || "bs-aigw", - modelID: CONFIG.opencodeModel || "deepseek-v4-flash", - }, + model, // V1 prompt body: variant is a sibling of `model`, not inside it. ...(CONFIG.opencodeVariant ? { variant: CONFIG.opencodeVariant } : {}), system: systemPrompt, diff --git a/tests/ai-cleanup.test.ts b/tests/ai-cleanup.test.ts index a998c675a..af3639c3d 100644 --- a/tests/ai-cleanup.test.ts +++ b/tests/ai-cleanup.test.ts @@ -1,5 +1,5 @@ import { afterEach, describe, expect, it } from "bun:test"; -import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { extractTextFromPromptResult } from "../src/services/user-profile/ai-cleanup.js"; @@ -74,6 +74,8 @@ function runCleanupScenario(opts: { promptThrows?: boolean; clientAvailable?: boolean; withExternalApi?: boolean; + opencodeModel?: string; + recentOpencodeModel?: { providerID: string; modelID: string }; }) { const dir = mkdtempSync(join(tmpdir(), "opencode-mem-ai-cleanup-")); tempDirs.push(dir); @@ -82,6 +84,17 @@ function runCleanupScenario(opts: { const clientAvailable = opts.clientAvailable ?? true; const withExternalApi = opts.withExternalApi ?? false; + // Isolated OpenCode state: `opencodeModel: "inherit"` reads the recent model + // list from there, so a developer's own model.json cannot leak into a test. + const stateDir = join(dir, "state"); + if (opts.recentOpencodeModel) { + mkdirSync(join(stateDir, "opencode"), { recursive: true }); + writeFileSync( + join(stateDir, "opencode", "model.json"), + JSON.stringify({ recent: [opts.recentOpencodeModel] }) + ); + } + const script = ` import { mock } from "bun:test"; @@ -104,7 +117,7 @@ const cleanupJson = JSON.stringify({ mock.module(${JSON.stringify(configUrl)}, () => ({ CONFIG: { opencodeProvider: "openai", - opencodeModel: "gpt-test", + opencodeModel: ${JSON.stringify(opts.opencodeModel ?? "gpt-test")}, memoryModel: ${withExternalApi ? '"gpt-ext"' : "undefined"}, memoryApiUrl: ${withExternalApi ? '"http://example.test/v1"' : "undefined"}, memoryApiKey: "test-key", @@ -203,6 +216,7 @@ console.log( cmd: [process.execPath, scriptPath], stdout: "pipe", stderr: "pipe", + env: { ...process.env, XDG_STATE_HOME: stateDir }, }); const stdout = Buffer.from(spawned.stdout).toString("utf8").trim(); @@ -265,4 +279,30 @@ describe("AI cleanup opencode provider path (#177)", () => { expect(result.parsed?.externalRequestBody?.stream).toBeUndefined(); expect(result.parsed?.externalRequestBody?.messages).toHaveLength(2); }); + + it('resolves opencodeModel "inherit" to a concrete model before prompting', () => { + // Differs from the configured provider, so the resolved pair is what gets sent. + const result = runCleanupScenario({ + opencodeModel: "inherit", + recentOpencodeModel: { providerID: "test-provider", modelID: "test-model" }, + }); + + expect(result.exitCode).toBe(0); + expect(result.parsed?.errorMessage).toBeNull(); + expect(result.parsed?.promptCalls[0]?.model).toEqual({ + providerID: "test-provider", + modelID: "test-model", + }); + expect(result.parsed?.kept).toEqual(["Prefer concise answers"]); + }); + + it('reports an explicit error when "inherit" cannot be resolved', () => { + const result = runCleanupScenario({ opencodeModel: "inherit" }); + + expect(result.exitCode).toBe(0); + expect(result.parsed?.errorMessage).toContain("opencodeModel is 'inherit'"); + expect(result.parsed?.errorMessage).toContain("no session model was recorded"); + // Resolution happens before session.create: nothing is prompted. + expect(result.parsed?.promptCalls).toHaveLength(0); + }); }); From e5ad1aac17cc79bbfd6ed82628a8031ce4c05977 Mon Sep 17 00:00:00 2001 From: EyJunge1 <149941075+EyJunge1@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:43:02 +0100 Subject: [PATCH 2/2] refactor(ai): resolve inherit via loadOpencodeProvider in cleanup Use the existing loader instead of a direct dynamic import, and extend the cleanup test mock so resolveOpencodeModelRef still comes from the real opencode-provider module. --- src/services/user-profile/ai-cleanup.ts | 2 +- tests/ai-cleanup.test.ts | 55 ++++++++++++++----------- 2 files changed, 32 insertions(+), 25 deletions(-) diff --git a/src/services/user-profile/ai-cleanup.ts b/src/services/user-profile/ai-cleanup.ts index 2a06cfbfa..0904da7bc 100644 --- a/src/services/user-profile/ai-cleanup.ts +++ b/src/services/user-profile/ai-cleanup.ts @@ -340,7 +340,7 @@ async function callViaOpencodeWithClient( // Resolve `opencodeModel: "inherit"` before creating the session, so the // literal "inherit" never reaches session.prompt. callAICleanup only routes // here when both opencodeProvider and opencodeModel are set. - const { resolveOpencodeModelRef } = await import("../ai/opencode-provider.js"); + const { resolveOpencodeModelRef } = await loadOpencodeProvider(); const model = resolveOpencodeModelRef({ providerID: CONFIG.opencodeProvider!, modelID: CONFIG.opencodeModel!, diff --git a/tests/ai-cleanup.test.ts b/tests/ai-cleanup.test.ts index af3639c3d..f83186508 100644 --- a/tests/ai-cleanup.test.ts +++ b/tests/ai-cleanup.test.ts @@ -65,6 +65,8 @@ describe("extractTextFromPromptResult", () => { const aiCleanupUrl = new URL("../src/services/user-profile/ai-cleanup.js", import.meta.url).href; const configUrl = new URL("../src/config.js", import.meta.url).href; const loggerUrl = new URL("../src/services/logger.js", import.meta.url).href; +const opencodeProviderUrl = new URL("../src/services/ai/opencode-provider.js", import.meta.url) + .href; const opencodeProviderLoaderUrl = new URL( "../src/services/ai/opencode-provider-loader.js", import.meta.url @@ -136,31 +138,36 @@ mock.module(${JSON.stringify(configUrl)}, () => ({ mock.module(${JSON.stringify(loggerUrl)}, () => ({ log: () => {}, safeLog: () => {}, serializeError: (error) => ({ error: error instanceof Error ? error.message : String(error) }) })); mock.module(${JSON.stringify(opencodeProviderLoaderUrl)}, () => ({ - loadOpencodeProvider: async () => ({ - getV2Client: () => - ${clientAvailable} - ? { - session: { - create: async () => ({ data: { id: "sess-cleanup-1" } }), - prompt: async (args) => { - promptCalls.push(args); - if (${promptThrows}) { - throw new Error("prompt failed for test"); - } - return { - data: { - info: {}, - parts: [{ type: "text", text: cleanupJson }], - }, - }; - }, - delete: async (args) => { - deleteCalls.push(args); + loadOpencodeProvider: async () => { + // Keep real helpers (e.g. resolveOpencodeModelRef for "inherit"); only stub the client. + const real = await import(${JSON.stringify(opencodeProviderUrl)}); + return { + ...real, + getV2Client: () => + ${clientAvailable} + ? { + session: { + create: async () => ({ data: { id: "sess-cleanup-1" } }), + prompt: async (args) => { + promptCalls.push(args); + if (${promptThrows}) { + throw new Error("prompt failed for test"); + } + return { + data: { + info: {}, + parts: [{ type: "text", text: cleanupJson }], + }, + }; + }, + delete: async (args) => { + deleteCalls.push(args); + }, }, - }, - } - : null, - }), + } + : null, + }; + }, })); if (${withExternalApi}) {