xonecas.io
64875
Mc

mini-coder / commit 946aa5f

fix: rotate mismatched dbs and scope anthropic oauth identity

xonecas2026-03-25 946aa5f8966d08ee5093df863d6158ff14a507a2 parent 3b67e42

5 files changed

docs/KNOWN_ISSUES.md+1−0
@@ -4,6 +4,7 @@
44
55 - AI SDK expands `claude-3-5-haiku` → dated variant that Zen doesn't serve (404).
66 - Shell tool: model can `tmux kill-session` the host tmux session if names collide (e.g. audit skill creates session named "audit" matching the user's). Not a code bug — the skill/model just picks a conflicting name. Mitigate via skill wording or session name prefixing.
7+- Shell tool output truncation only stops reading stdout/stderr; it does not terminate the underlying process yet. Commands that emit a lot of output and then keep running can still block until they exit or hit timeout.
78
89 ## Features
910
src/llm-api/turn-prepare-messages.test.ts+105−0
@@ -0,0 +1,105 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join } from "node:path";
5+
6+const connectionModuleUrl = new URL(
7+ "../session/db/connection.ts",
8+ import.meta.url,
9+).href;
10+const prepareModuleUrl = new URL("./turn-prepare-messages.ts", import.meta.url)
11+ .href;
12+
13+function runInHome(
14+ home: string,
15+ script: string,
16+): {
17+ exitCode: number;
18+ stdout: string;
19+ stderr: string;
20+} {
21+ const scriptPath = join(
22+ tmpdir(),
23+ `mc-turn-prepare-test-${process.pid}-${Date.now()}.mjs`,
24+ );
25+ writeFileSync(scriptPath, script);
26+ try {
27+ const result = Bun.spawnSync([process.execPath, scriptPath], {
28+ env: { ...process.env, HOME: home },
29+ stdout: "pipe",
30+ stderr: "pipe",
31+ });
32+ return {
33+ exitCode: result.exitCode,
34+ stdout: result.stdout.toString(),
35+ stderr: result.stderr.toString(),
36+ };
37+ } finally {
38+ rmSync(scriptPath, { force: true });
39+ }
40+}
41+
42+describe("prepareTurnMessages Anthropic OAuth identity handling", () => {
43+ let fakeHome = "";
44+
45+ beforeEach(() => {
46+ fakeHome = mkdtempSync(join(tmpdir(), "mc-turn-prepare-home-"));
47+ mkdirSync(join(fakeHome, ".config", "mini-coder"), { recursive: true });
48+ });
49+
50+ afterEach(() => {
51+ rmSync(fakeHome, { recursive: true, force: true });
52+ });
53+
54+ test("keeps Claude Code identity on direct Anthropic OAuth, but not on zen/claude", () => {
55+ const result = runInHome(
56+ fakeHome,
57+ `
58+ import { getDb } from ${JSON.stringify(connectionModuleUrl)};
59+ import { prepareTurnMessages } from ${JSON.stringify(prepareModuleUrl)};
60+
61+ const db = getDb();
62+ db.run(
63+ "INSERT INTO oauth_tokens (provider, access_token, refresh_token, expires_at, updated_at) VALUES (?, ?, ?, ?, ?)",
64+ ["anthropic", "token", "refresh", ${Date.now() + 60_000}, ${Date.now()}],
65+ );
66+
67+ const anthropic = prepareTurnMessages({
68+ messages: [{ role: "user", content: "hi" }],
69+ modelString: "anthropic/claude-sonnet-4-6",
70+ toolCount: 0,
71+ systemPrompt: "sys",
72+ });
73+ const zen = prepareTurnMessages({
74+ messages: [{ role: "user", content: "hi" }],
75+ modelString: "zen/claude-sonnet-4-6",
76+ toolCount: 0,
77+ systemPrompt: "sys",
78+ });
79+
80+ console.log(JSON.stringify({
81+ anthropicMessages: anthropic.messages,
82+ anthropicSystemPrompt: anthropic.systemPrompt,
83+ zenMessages: zen.messages,
84+ zenSystemPrompt: zen.systemPrompt,
85+ }));
86+ `,
87+ );
88+
89+ expect(result.exitCode).toBe(0);
90+ expect(result.stderr).toBe("");
91+ expect(JSON.parse(result.stdout)).toEqual({
92+ anthropicMessages: [
93+ {
94+ role: "system",
95+ content: "You are Claude Code, Anthropic's official CLI for Claude.",
96+ },
97+ { role: "system", content: "sys" },
98+ { role: "user", content: "hi" },
99+ ],
100+ anthropicSystemPrompt: undefined,
101+ zenMessages: [{ role: "user", content: "hi" }],
102+ zenSystemPrompt: "sys",
103+ });
104+ });
105+});
src/llm-api/turn-prepare-messages.ts+3−2
@@ -5,7 +5,7 @@ import {
55 stripOpenAIHistoryTransforms,
66 stripToolRuntimeInputFields,
77 } from "./history-transforms.ts";
8-import { isAnthropicModelFamily } from "./model-routing.ts";
8+import { parseModelString } from "./model-routing.ts";
99 import { isAnthropicOAuth } from "./providers.ts";
1010 import type { CoreMessage } from "./turn.ts";
1111 import {
@@ -110,8 +110,9 @@ export function prepareTurnMessages(input: {
110110 // SDK sends them in the correct order on the wire.
111111 let finalMessages = compacted;
112112 let finalSystemPrompt = systemPrompt;
113+ const { provider } = parseModelString(modelString);
113114
114- if (isAnthropicModelFamily(modelString) && isAnthropicOAuth()) {
115+ if (provider === "anthropic" && isAnthropicOAuth()) {
115116 const ccIdentity =
116117 "You are Claude Code, Anthropic's official CLI for Claude.";
117118 const systemMessages: CoreMessage[] = [
src/session/db/connection.test.ts+98−1
@@ -1,6 +1,48 @@
1-import { describe, expect, test } from "bun:test";
1+import { Database } from "bun:sqlite";
2+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
3+import {
4+ existsSync,
5+ mkdirSync,
6+ mkdtempSync,
7+ readdirSync,
8+ rmSync,
9+ writeFileSync,
10+} from "node:fs";
11+import { tmpdir } from "node:os";
12+import { join } from "node:path";
213 import { isSqliteBusyError } from "./connection.ts";
314
15+const connectionModuleUrl = new URL("./connection.ts", import.meta.url).href;
16+
17+function runInHome(
18+ home: string,
19+ script: string,
20+): {
21+ exitCode: number;
22+ stdout: string;
23+ stderr: string;
24+} {
25+ const scriptPath = join(
26+ tmpdir(),
27+ `mc-connection-test-${process.pid}-${Date.now()}.mjs`,
28+ );
29+ writeFileSync(scriptPath, script);
30+ try {
31+ const result = Bun.spawnSync([process.execPath, scriptPath], {
32+ env: { ...process.env, HOME: home },
33+ stdout: "pipe",
34+ stderr: "pipe",
35+ });
36+ return {
37+ exitCode: result.exitCode,
38+ stdout: result.stdout.toString(),
39+ stderr: result.stderr.toString(),
40+ };
41+ } finally {
42+ rmSync(scriptPath, { force: true });
43+ }
44+}
45+
446 describe("isSqliteBusyError", () => {
547 test("matches sqlite busy messages", () => {
648 expect(
@@ -16,3 +58,58 @@ describe("isSqliteBusyError", () => {
1658 expect(isSqliteBusyError("database is locked")).toBe(false);
1759 });
1860 });
61+
62+describe("getDb schema version handling", () => {
63+ let fakeHome = "";
64+
65+ beforeEach(() => {
66+ fakeHome = mkdtempSync(join(tmpdir(), "mc-db-home-"));
67+ });
68+
69+ afterEach(() => {
70+ rmSync(fakeHome, { recursive: true, force: true });
71+ });
72+
73+ test("rotates old database files aside and creates a fresh DB", () => {
74+ const configDir = join(fakeHome, ".config", "mini-coder");
75+ mkdirSync(configDir, { recursive: true });
76+ const dbPath = join(configDir, "sessions.db");
77+
78+ const db = new Database(dbPath, { create: true });
79+ db.exec("PRAGMA journal_mode=WAL;");
80+ db.exec(`CREATE TABLE sessions (
81+ id TEXT PRIMARY KEY,
82+ title TEXT NOT NULL DEFAULT '',
83+ cwd TEXT NOT NULL,
84+ model TEXT NOT NULL,
85+ created_at INTEGER NOT NULL,
86+ updated_at INTEGER NOT NULL
87+ );`);
88+ db.exec(
89+ "INSERT INTO sessions (id, cwd, model, created_at, updated_at) VALUES ('keepme', '/tmp', 'x/y', 1, 1);",
90+ );
91+ db.exec("PRAGMA user_version = 5;");
92+ db.close();
93+
94+ const result = runInHome(
95+ fakeHome,
96+ `
97+ import { getDb } from ${JSON.stringify(connectionModuleUrl)};
98+ const db = getDb();
99+ const currentCount = db.query("SELECT COUNT(*) AS c FROM sessions").get()?.c ?? 0;
100+ console.log(JSON.stringify({ currentCount }));
101+ `,
102+ );
103+
104+ expect(result.exitCode).toBe(0);
105+ expect(result.stderr).toBe("");
106+ expect(JSON.parse(result.stdout)).toEqual({ currentCount: 0 });
107+ expect(existsSync(dbPath)).toBe(true);
108+
109+ const files = readdirSync(configDir).sort();
110+ const backupBase = files.find((file) =>
111+ file.startsWith("sessions.db.bak-v5-"),
112+ );
113+ expect(backupBase).toBeString();
114+ });
115+});
src/session/db/connection.ts+15−9
@@ -1,5 +1,5 @@
11 import { Database } from "bun:sqlite";
2-import { existsSync, mkdirSync, unlinkSync } from "node:fs";
2+import { existsSync, mkdirSync, renameSync } from "node:fs";
33 import { homedir } from "node:os";
44 import { join } from "node:path";
55
@@ -138,31 +138,37 @@ function configureDb(db: Database): void {
138138 db.exec("PRAGMA busy_timeout=1000;");
139139 }
140140
141+function rotateDbFiles(dbPath: string, version: number): void {
142+ const backupBase = `${dbPath}.bak-v${version}-${Date.now()}`;
143+ for (const suffix of ["", "-wal", "-shm"]) {
144+ const path = `${dbPath}${suffix}`;
145+ if (!existsSync(path)) continue;
146+ renameSync(path, `${backupBase}${suffix}`);
147+ }
148+}
149+
141150 export function getDb(): Database {
142151 if (!_db) {
143152 const dbPath = getDbPath();
153+ const dbExists = existsSync(dbPath);
144154 let db = new Database(dbPath, { create: true });
145155 configureDb(db);
146156
147157 const version =
148158 db.query<{ user_version: number }, []>("PRAGMA user_version").get()
149159 ?.user_version ?? 0;
150- if (version !== DB_VERSION) {
160+ if (dbExists && version !== DB_VERSION) {
151161 try {
152162 db.close();
153163 } catch {
154164 // ignore
155165 }
156- for (const path of [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]) {
157- if (existsSync(path)) unlinkSync(path);
158- }
166+ rotateDbFiles(dbPath, version);
159167 db = new Database(dbPath, { create: true });
160168 configureDb(db);
161- db.exec(SCHEMA);
162- db.exec(`PRAGMA user_version = ${DB_VERSION};`);
163- } else {
164- db.exec(SCHEMA);
165169 }
170+ db.exec(SCHEMA);
171+ db.exec(`PRAGMA user_version = ${DB_VERSION};`);
166172 _db = db;
167173 }
168174 return _db;