Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 11 additions & 4 deletions src/services/user-profile/ai-cleanup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 loadOpencodeProvider();
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",
Expand All @@ -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,
Expand Down
99 changes: 73 additions & 26 deletions tests/ai-cleanup.test.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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
Expand All @@ -74,6 +76,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);
Expand All @@ -82,6 +86,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";

Expand All @@ -104,7 +119,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",
Expand All @@ -123,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}) {
Expand Down Expand Up @@ -203,6 +223,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();
Expand Down Expand Up @@ -265,4 +286,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);
});
});
Loading