Skip to content

Use Claude Code, Codex, VSCode, Pi, and OpenCode (and 6 other harnesses) for free (1.3B+ free tokens) from your terminal, app, IDE, or phone, and now from the browser with native browser sessions (multi-harness + multi-model) like OpenClaw (voice supported + ToS friendly)

Python

patch: Consolidate Code storage into fcc.db with numbered migrations (#1913)

Ali Khokhar2e730696b6a7
diff --git a/e2e/test_code_sessions.py b/e2e/test_code_sessions.py
index 10d1825b..550f094c 100644
--- a/e2e/test_code_sessions.py
+++ b/e2e/test_code_sessions.py
@@ -1726,7 +1726,13 @@ def test_off_clears_effort_when_reasoning_becomes_unavailable(
):
url = create_session(page, admin_base_url, tmp_path)
effort = page.locator("#codeReasoning")
- effort.select_option("high")
+ with page.expect_response(
+ lambda response: (
+ response.request.method == "PATCH" and "/api/code/sessions/" in response.url
+ )
+ ) as changed:
+ effort.select_option("high")
+ assert changed.value.json()["reasoning_effort"] == "high"
expect(effort).to_be_enabled()
page.locator("#codeComposer").fill("Preserve this draft")
code_control.harness.efforts = ("off",)
diff --git a/smoke/product/test_codex_modes_product_live.py b/smoke/product/test_codex_modes_product_live.py
index a69d5675..046c80d7 100644
--- a/smoke/product/test_codex_modes_product_live.py
+++ b/smoke/product/test_codex_modes_product_live.py
@@ -22,6 +22,7 @@ from free_claude_code.config.env_migrations import (
atomic_write_managed_config,
settings_env_keys,
)
+from free_claude_code.config.paths import FCC_DATABASE_FILENAME
from free_claude_code.config.provider_catalog import PROVIDER_CATALOG
from smoke.lib.child_process import run_captured_text
from smoke.lib.config import SmokeConfig
@@ -554,7 +555,11 @@ def test_codex_child_review_local_e2e(
)
assert marker.read_text().strip() == "smoke"
with closing(
- sqlite3.connect(tmp_path / "home" / ".fcc" / "code" / "code.db")
+ sqlite3.connect(
+ (tmp_path / "home" / ".fcc" / FCC_DATABASE_FILENAME).as_uri()
+ + "?mode=ro",
+ uri=True,
+ )
) as database:
root = database.execute(
"SELECT native_thread_id FROM code_sessions WHERE id = ?",
diff --git a/src/free_claude_code/config/paths.py b/src/free_claude_code/config/paths.py
index cefcf75f..7e353bb1 100644
--- a/src/free_claude_code/config/paths.py
+++ b/src/free_claude_code/config/paths.py
@@ -17,6 +17,7 @@ CONFIG_LOCK_FILENAME = "config.lock"
FCC_TEMP_DIRNAME = "tmp"
LAUNCHER_TEMP_DIRNAME = "launchers"
CODE_STATE_DIRNAME = "code"
+FCC_DATABASE_FILENAME = "fcc.db"
CODE_DATABASE_FILENAME = "code.db"
CODE_LOCK_FILENAME = "code.lock"
@@ -45,8 +46,13 @@ def launcher_temp_dir_path() -> Path:
return config_dir_path() / FCC_TEMP_DIRNAME / LAUNCHER_TEMP_DIRNAME
-def code_database_path() -> Path:
- """Return the managed Code sessions database path."""
+def fcc_database_path() -> Path:
+ """Return the shared FCC database path."""
+ return config_dir_path() / FCC_DATABASE_FILENAME
+
+
+def legacy_code_database_path() -> Path:
+ """Return the former Code database path for startup relocation."""
return config_dir_path() / CODE_STATE_DIRNAME / CODE_DATABASE_FILENAME
diff --git a/src/free_claude_code/runtime/bootstrap.py b/src/free_claude_code/runtime/bootstrap.py
index 3972ee20..b8c66111 100644
--- a/src/free_claude_code/runtime/bootstrap.py
+++ b/src/free_claude_code/runtime/bootstrap.py
@@ -11,8 +11,9 @@ from free_claude_code.application.code_sessions import CodeService
from free_claude_code.config.loader import ManagedConfigStore
from free_claude_code.config.logging_config import configure_logging
from free_claude_code.config.paths import (
- code_database_path,
code_lock_path,
+ fcc_database_path,
+ legacy_code_database_path,
server_log_path,
)
from free_claude_code.config.settings import Settings
@@ -73,7 +74,11 @@ def build_asgi_app(
model_catalog_publisher=CodexModelCatalogPublisher(),
)
code_service = CodeService(
- SQLiteCodeStore(code_database_path(), code_lock_path()),
+ SQLiteCodeStore(
+ fcc_database_path(),
+ code_lock_path(),
+ legacy_database_path=legacy_code_database_path(),
+ ),
CodexHarnessFactory(provider_manager),
)
runtime = ApplicationRuntime(
diff --git a/src/free_claude_code/runtime/code_sessions_sqlite.py b/src/free_claude_code/runtime/code_sessions_sqlite.py
index 036efc48..eddb9f92 100644
--- a/src/free_claude_code/runtime/code_sessions_sqlite.py
+++ b/src/free_claude_code/runtime/code_sessions_sqlite.py
@@ -25,6 +25,8 @@ from free_claude_code.application.code_sessions.models import (
)
from free_claude_code.core.interprocess_lock import InterprocessFileLock
+from .sqlite_database import initialize_database
+
_JSON_FIELDS = frozenset(
{"raw", "form", "error_details", "request_id", "native_permission_defaults"}
)
@@ -299,58 +301,16 @@ def _write_prompt(connection: sqlite3.Connection, prompt: CodePrompt) -> None:
)
-def _migrate_prompt_entries(connection: sqlite3.Connection) -> None:
- """Give old prompts a permanent run-end position without rewriting history."""
- for row in connection.execute(
- "SELECT * FROM code_prompts ORDER BY rowid"
- ).fetchall():
- prompt = _record(CodePrompt, row)
- run = connection.execute(
- "SELECT id FROM code_runs WHERE session_id = ? AND native_turn_id = ?",
- (prompt.session_id, prompt.native_turn_id),
- ).fetchone()
- if run is None and prompt.native_item_id is not None:
- matches = connection.execute(
- "SELECT DISTINCT run_id AS id FROM code_items WHERE session_id = ? AND native_item_id = ?",
- (prompt.session_id, prompt.native_item_id),
- ).fetchall()
- if len(matches) == 1:
- run = matches[0]
- if run is None:
- run = connection.execute(
- "SELECT id FROM code_runs WHERE session_id = ? ORDER BY ordinal DESC LIMIT 1",
- (prompt.session_id,),
- ).fetchone()
- if run is None:
- raise CodeUnavailableError("A saved prompt has no saved conversation turn.")
- sequence = connection.execute(
- "SELECT COALESCE(MAX(sequence), 0) + 1 FROM code_items WHERE session_id = ?",
- (prompt.session_id,),
- ).fetchone()[0]
- _insert(
- connection,
- "code_items",
- CodeItem(
- id=prompt.id,
- session_id=prompt.session_id,
- run_id=run["id"],
- sequence=sequence,
- kind="prompt",
- complete=True,
- ),
- )
- connection.execute("CREATE TABLE code_prompts_new" + _PROMPT_COLUMNS)
- connection.execute("INSERT INTO code_prompts_new SELECT * FROM code_prompts")
- connection.execute("DROP TABLE code_prompts")
- connection.execute("ALTER TABLE code_prompts_new RENAME TO code_prompts")
- if connection.execute("PRAGMA foreign_key_check").fetchone() is not None:
- raise CodeUnavailableError("Code session history has an invalid record link.")
- connection.execute("PRAGMA user_version = 1")
-
-
class SQLiteCodeStore:
- def __init__(self, database_path: Path, lock_path: Path) -> None:
+ def __init__(
+ self,
+ database_path: Path,
+ lock_path: Path,
+ *,
+ legacy_database_path: Path | None = None,
+ ) -> None:
self._path = database_path
+ self._legacy_path = legacy_database_path
self._lock = InterprocessFileLock(lock_path)
self._started = False
self._lifecycle = asyncio.Lock()
@@ -371,14 +331,28 @@ class SQLiteCodeStore:
self._started = True
def _initialize(self) -> None:
- self._path.parent.mkdir(parents=True, exist_ok=True)
if not self._lock.acquire():
raise CodeUnavailableError(
"Code sessions is already owned by another FCC server."
)
- if os.name != "nt":
- self._path.parent.chmod(0o700)
- self._execute(self._initialize_schema)
+ try:
+ self._path.parent.mkdir(parents=True, exist_ok=True)
+ if os.name != "nt":
+ self._path.parent.chmod(0o700)
+ initialize_database(self._path, self._legacy_path)
+ except sqlite3.IntegrityError as exc:
+ raise CodeConflictError(
+ "Saved Code history conflicts with its schema."
+ ) from exc
+ except sqlite3.Error as exc:
+ raise CodeUnavailableError(
+ f"Code storage initialization failed: {exc}"
+ ) from exc
+ except OSError as exc:
+ raise CodeUnavailableError(
+ "Code database files could not be initialized or moved."
+ ) from exc
+ self._execute(self._recover)
if os.name != "nt":
for path in (
self._path,
@@ -412,30 +386,7 @@ class SQLiteCodeStore:
raise CodeUnavailableError("Code session storage is closed.")
return await anyio.to_thread.run_sync(self._execute, operation)
- def _initialize_schema(self, connection: sqlite3.Connection) -> None:
- connection.execute("PRAGMA journal_mode = WAL")
- connection.executescript(_SCHEMA)
- connection.execute("BEGIN IMMEDIATE")
- if connection.execute("PRAGMA user_version").fetchone()[0] == 0:
- _migrate_prompt_entries(connection)
- if connection.execute("PRAGMA user_version").fetchone()[0] == 1:
- for table in ("code_sessions", "code_runs"):
- connection.execute(
- f"ALTER TABLE {table} ADD COLUMN mode TEXT NOT NULL DEFAULT 'config' "
- "CHECK(mode IN ('config','ask','auto_review','full_access'))"
- )
- connection.execute(
- "ALTER TABLE code_sessions ADD COLUMN native_permission_defaults TEXT "
- "CHECK(native_permission_defaults IS NULL OR "
- "(json_valid(native_permission_defaults) AND json_type(native_permission_defaults) = 'object'))"
- )
- connection.execute("PRAGMA user_version = 2")
- if connection.execute("PRAGMA user_version").fetchone()[0] == 2:
- connection.execute(
- "ALTER TABLE code_sessions ADD COLUMN context_used_tokens INTEGER "
- "CHECK(context_used_tokens IS NULL OR context_used_tokens >= 0)"
- )
- connection.execute("PRAGMA user_version = 3")
+ def _recover(self, connection: sqlite3.Connection) -> None:
connection.execute(
"UPDATE code_runs SET status = 'interrupted', finished_at = ?, error = ? "
"WHERE status IN ('preparing','running','stopping')",
@@ -735,51 +686,3 @@ class SQLiteCodeStore:
connection.execute("DELETE FROM code_sessions WHERE id = ?", (session_id,))
await self._run(operation)
-
-
-_PROMPT_COLUMNS = """(
- session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
- generation TEXT NOT NULL, request_id TEXT NOT NULL, native_turn_id TEXT, native_item_id TEXT,
- kind TEXT NOT NULL, form TEXT NOT NULL, raw TEXT NOT NULL,
- status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')), response_id TEXT, error TEXT,
- PRIMARY KEY(session_id,id), UNIQUE(session_id,generation,request_id), UNIQUE(session_id,response_id),
- FOREIGN KEY(session_id,id) REFERENCES code_items(session_id,id) ON DELETE CASCADE
-)"""
-
-_SCHEMA = (
- """
-CREATE TABLE IF NOT EXISTS code_sessions(
- id TEXT PRIMARY KEY NOT NULL, cwd TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
- harness TEXT NOT NULL CHECK(harness = 'codex'), title TEXT NOT NULL, title_search TEXT NOT NULL,
- cwd_search TEXT NOT NULL, auto_title INTEGER NOT NULL CHECK(auto_title IN (0,1)), native_thread_id TEXT,
- native_may_have_input INTEGER NOT NULL CHECK(native_may_have_input IN (0,1)),
- revision INTEGER NOT NULL CHECK(revision > 0), status TEXT NOT NULL CHECK(status IN ('ready','deleting','delete_uncertain')),
- error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
-);
-CREATE INDEX IF NOT EXISTS code_sessions_recent ON code_sessions(updated_at DESC, id DESC);
-CREATE TABLE IF NOT EXISTS code_runs(
- session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
- ordinal INTEGER NOT NULL CHECK(ordinal > 0), text TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
- status TEXT NOT NULL CHECK(status IN ('preparing','running','stopping','completed','interrupted','failed')),
- submission_started INTEGER NOT NULL CHECK(submission_started IN (0,1)), native_turn_id TEXT,
- stop_requested INTEGER NOT NULL CHECK(stop_requested IN (0,1)), error TEXT, error_details TEXT NOT NULL,
- created_at INTEGER NOT NULL, finished_at INTEGER,
- PRIMARY KEY(session_id,id), UNIQUE(session_id,ordinal), UNIQUE(session_id,native_turn_id)
-);
-CREATE UNIQUE INDEX IF NOT EXISTS code_one_active_run ON code_runs(session_id)
- WHERE status IN ('preparing','running','stopping');
-CREATE TABLE IF NOT EXISTS code_items(
- session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
- run_id TEXT NOT NULL, sequence INTEGER NOT NULL CHECK(sequence > 0), native_turn_id TEXT, native_item_id TEXT,
- kind TEXT NOT NULL, title TEXT NOT NULL, text TEXT NOT NULL, detail TEXT NOT NULL,
- complete INTEGER NOT NULL CHECK(complete IN (0,1)), raw TEXT NOT NULL,
- PRIMARY KEY(session_id,id), FOREIGN KEY(session_id,run_id) REFERENCES code_runs(session_id,id) ON DELETE CASCADE,
- UNIQUE(session_id,sequence), UNIQUE(session_id,native_turn_id,native_item_id)
-);
-CREATE INDEX IF NOT EXISTS code_items_run ON code_items(session_id,run_id,sequence);
-CREATE TABLE IF NOT EXISTS code_deleted(id TEXT PRIMARY KEY NOT NULL);
-"""
- + "CREATE TABLE IF NOT EXISTS code_prompts"
- + _PROMPT_COLUMNS
- + ";"
-)
diff --git a/src/free_claude_code/runtime/sqlite_database.py b/src/free_claude_code/runtime/sqlite_database.py
new file mode 100644
index 00000000..1997171d
--- /dev/null
+++ b/src/free_claude_code/runtime/sqlite_database.py
@@ -0,0 +1,163 @@
+"""Offline relocation and transactional schema initialization of FCC's database.
+
+The caller must hold the Code owner lock until the store closes. Connections
+opened here never escape initialization, including when migration fails.
+"""
+
+import sqlite3
+from contextlib import closing
+from pathlib import Path
+
+from .sqlite_migrations import MIGRATIONS
+
+# Historical columns identify supported files without depending on live models.
+_BASE_COLUMNS = {
+ "code_sessions": "id cwd model reasoning_effort harness title title_search cwd_search "
+ "auto_title native_thread_id native_may_have_input revision status error created_at updated_at",
+ "code_runs": "session_id id ordinal text model reasoning_effort status submission_started "
+ "native_turn_id stop_requested error error_details created_at finished_at",
+ "code_items": "session_id id run_id sequence native_turn_id native_item_id kind title text detail complete raw",
+ "code_prompts": "session_id id generation request_id native_turn_id native_item_id kind form raw status response_id error",
+ "code_deleted": "id",
+}
+_SIDECARS = ("-wal", "-shm", "-journal")
+
+
+def _connect(path: Path, *, existing: bool = False) -> sqlite3.Connection:
+ connection = sqlite3.connect(
+ path.as_uri() + ("?mode=rw" if existing else "?mode=rwc"),
+ uri=True,
+ timeout=10,
+ autocommit=True,
+ )
+ connection.row_factory = sqlite3.Row
+ connection.execute("PRAGMA foreign_keys = ON")
+ return connection
+
+
+def _schema_version(connection: sqlite3.Connection) -> int:
+ version = connection.execute("PRAGMA user_version").fetchone()[0]
+ if not 0 <= version <= MIGRATIONS[-1][0]:
+ raise sqlite3.DatabaseError(f"Unsupported FCC database version {version}.")
+ tables = {
+ row[0]
+ for row in connection.execute(
+ "SELECT name FROM sqlite_schema WHERE type IN ('table','view') AND name NOT LIKE 'sqlite_%'"
+ )
+ }
+ if version == 0 and not tables:
+ return version
+ if tables != _BASE_COLUMNS.keys():
+ raise sqlite3.DatabaseError(
+ "Unrecognized FCC database schema. Saved data was preserved."
+ )
+ for table, baseline in _BASE_COLUMNS.items():
+ expected = set(baseline.split())
+ if version >= 2 and table in ("code_sessions", "code_runs"):
+ expected.add("mode")
+ if version >= 2 and table == "code_sessions":
+ expected.add("native_permission_defaults")
+ if version >= 3 and table == "code_sessions":
+ expected.add("context_used_tokens")
+ actual = {row[1] for row in connection.execute(f"PRAGMA table_info({table})")}
+ if not expected <= actual:
+ raise sqlite3.DatabaseError(f"Incomplete FCC database schema in {table}.")
+ return version
+
+
+def _sidecars(path: Path) -> bool:
+ return any(
+ Path(f"{path}{suffix}").exists() or Path(f"{path}{suffix}").is_symlink()
+ for suffix in _SIDECARS
+ )
+
+
+def _check_path(path: Path) -> None:
+ if path.is_symlink():
+ raise sqlite3.DatabaseError(
+ "FCC database path is redirected. Saved data was preserved."
+ )
+ if not path.exists() and _sidecars(path):
+ raise sqlite3.DatabaseError(
+ "FCC database has orphan journal files. Saved data was preserved."
+ )
+
+
+def _relocate(source: Path, destination: Path) -> None:
+ with closing(_connect(source, existing=True)) as connection:
+ _schema_version(connection)
+ if connection.execute("PRAGMA journal_mode").fetchone()[0] == "wal":
+ busy, pages, checkpointed = connection.execute(
+ "PRAGMA wal_checkpoint(TRUNCATE)"
+ ).fetchone()
+ if busy or pages != checkpointed:
+ raise sqlite3.DatabaseError(
+ "FCC database checkpoint is busy. Stop FCC before updating."
+ )
+ if connection.execute("PRAGMA journal_mode=DELETE").fetchone()[0] != "delete":
+ raise sqlite3.DatabaseError(
+ "FCC database journals are still in use. Stop FCC before updating."
+ )
+ if _sidecars(source):
+ raise sqlite3.DatabaseError(
+ "FCC database journal files remain. Saved data was preserved."
+ )
+ _check_path(destination)
+ if destination.exists():
+ raise sqlite3.DatabaseError(
+ "FCC has both legacy and current databases. Resolve the file conflict before starting Code."
+ )
+ source.rename(destination)
+
+
+def initialize_database(path: Path, legacy_path: Path | None = None) -> None:
+ """Apply pending migrations, relocating the legacy file first if present."""
+ if tuple(version for version, _ in MIGRATIONS) != tuple(
+ range(1, len(MIGRATIONS) + 1)
+ ):
+ raise sqlite3.DatabaseError(
+ "FCC database migration versions must be contiguous."
+ )
+ path = path.parent.resolve() / path.name
+ _check_path(path)
+ if legacy_path is not None:
+ legacy_path = (
+ legacy_path.parent.parent.resolve()
+ / legacy_path.parent.name
+ / legacy_path.name
+ )
+ if legacy_path.parent.resolve() != legacy_path.parent:
+ raise sqlite3.DatabaseError(
+ "Legacy Code directory is redirected. Saved data was preserved."
+ )
+ _check_path(legacy_path)
+ if legacy_path.exists() and path.exists():
+ raise sqlite3.DatabaseError(
+ "FCC has both legacy and current databases. Resolve the file conflict before starting Code."
+ )
+ path.parent.mkdir(parents=True, exist_ok=True)
+ if legacy_path is not None and legacy_path.exists():
+ _relocate(legacy_path, path)
+ with closing(_connect(path)) as connection:
+ version = _schema_version(connection)
+ if connection.execute("PRAGMA journal_mode=WAL").fetchone()[0] != "wal":
+ raise sqlite3.DatabaseError("FCC database could not enable WAL.")
+ for next_version, upgrade in MIGRATIONS:
+ if next_version <= version:
+ continue
+ connection.execute("BEGIN IMMEDIATE")
+ try:
+ upgrade(connection)
+ if (
+ connection.execute("PRAGMA foreign_key_check").fetchone()
+ is not None
+ ):
+ raise sqlite3.DatabaseError(
+ "FCC database has an invalid record link."
+ )
+ connection.execute(f"PRAGMA user_version={next_version}")
+ connection.execute("COMMIT")
+ except BaseException:
+ if connection.in_transaction:
+ connection.execute("ROLLBACK")
+ raise
diff --git a/src/free_claude_code/runtime/sqlite_migrations/__init__.py b/src/free_claude_code/runtime/sqlite_migrations/__init__.py
new file mode 100644
index 00000000..186b3ac5
--- /dev/null
+++ b/src/free_claude_code/runtime/sqlite_migrations/__init__.py
@@ -0,0 +1,17 @@
+"""Ordered FCC database history. Published migrations are immutable.
+
+Add the next numbered module and append its upgrade function here. The runner
+owns transactions and user_version. Migrations use explicit execute statements,
+never executescript, and must not import mutable domain models or serializers.
+"""
+
+import sqlite3
+from collections.abc import Callable
+
+from . import v0001_code_schema, v0002_code_permissions, v0003_code_context_usage
+
+MIGRATIONS: tuple[tuple[int, Callable[[sqlite3.Connection], None]], ...] = (
+ (1, v0001_code_schema.upgrade),
+ (2, v0002_code_permissions.upgrade),
+ (3, v0003_code_context_usage.upgrade),
+)
diff --git a/src/free_claude_code/runtime/sqlite_migrations/v0001_code_schema.py b/src/free_claude_code/runtime/sqlite_migrations/v0001_code_schema.py
new file mode 100644
index 00000000..0e0a2112
--- /dev/null
+++ b/src/free_claude_code/runtime/sqlite_migrations/v0001_code_schema.py
@@ -0,0 +1,97 @@
+"""Version 1: baseline Code tables and permanent transcript entries for prompts."""
+
+import sqlite3
+
+_PROMPT_COLUMNS = """(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ generation TEXT NOT NULL, request_id TEXT NOT NULL, native_turn_id TEXT, native_item_id TEXT,
+ kind TEXT NOT NULL, form TEXT NOT NULL, raw TEXT NOT NULL,
+ status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')), response_id TEXT, error TEXT,
+ PRIMARY KEY(session_id,id), UNIQUE(session_id,generation,request_id), UNIQUE(session_id,response_id),
+ FOREIGN KEY(session_id,id) REFERENCES code_items(session_id,id) ON DELETE CASCADE
+)"""
+
+_SCHEMA = (
+ """CREATE TABLE IF NOT EXISTS code_sessions(
+ id TEXT PRIMARY KEY NOT NULL, cwd TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
+ harness TEXT NOT NULL CHECK(harness = 'codex'), title TEXT NOT NULL, title_search TEXT NOT NULL,
+ cwd_search TEXT NOT NULL, auto_title INTEGER NOT NULL CHECK(auto_title IN (0,1)), native_thread_id TEXT,
+ native_may_have_input INTEGER NOT NULL CHECK(native_may_have_input IN (0,1)),
+ revision INTEGER NOT NULL CHECK(revision > 0), status TEXT NOT NULL CHECK(status IN ('ready','deleting','delete_uncertain')),
+ error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
+)""",
+ """CREATE INDEX IF NOT EXISTS code_sessions_recent ON code_sessions(updated_at DESC, id DESC)""",
+ """CREATE TABLE IF NOT EXISTS code_runs(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ ordinal INTEGER NOT NULL CHECK(ordinal > 0), text TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
+ status TEXT NOT NULL CHECK(status IN ('preparing','running','stopping','completed','interrupted','failed')),
+ submission_started INTEGER NOT NULL CHECK(submission_started IN (0,1)), native_turn_id TEXT,
+ stop_requested INTEGER NOT NULL CHECK(stop_requested IN (0,1)), error TEXT, error_details TEXT NOT NULL,
+ created_at INTEGER NOT NULL, finished_at INTEGER,
+ PRIMARY KEY(session_id,id), UNIQUE(session_id,ordinal), UNIQUE(session_id,native_turn_id)
+)""",
+ """CREATE UNIQUE INDEX IF NOT EXISTS code_one_active_run ON code_runs(session_id)
+ WHERE status IN ('preparing','running','stopping')""",
+ """CREATE TABLE IF NOT EXISTS code_items(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ run_id TEXT NOT NULL, sequence INTEGER NOT NULL CHECK(sequence > 0), native_turn_id TEXT, native_item_id TEXT,
+ kind TEXT NOT NULL, title TEXT NOT NULL, text TEXT NOT NULL, detail TEXT NOT NULL,
+ complete INTEGER NOT NULL CHECK(complete IN (0,1)), raw TEXT NOT NULL,
+ PRIMARY KEY(session_id,id), FOREIGN KEY(session_id,run_id) REFERENCES code_runs(session_id,id) ON DELETE CASCADE,
+ UNIQUE(session_id,sequence), UNIQUE(session_id,native_turn_id,native_item_id)
+)""",
+ """CREATE INDEX IF NOT EXISTS code_items_run ON code_items(session_id,run_id,sequence)""",
+ """CREATE TABLE IF NOT EXISTS code_deleted(id TEXT PRIMARY KEY NOT NULL)""",
+ """CREATE TABLE IF NOT EXISTS code_prompts(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ generation TEXT NOT NULL, request_id TEXT NOT NULL, native_turn_id TEXT, native_item_id TEXT,
+ kind TEXT NOT NULL, form TEXT NOT NULL, raw TEXT NOT NULL,
+ status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')), response_id TEXT, error TEXT,
+ PRIMARY KEY(session_id,id), UNIQUE(session_id,generation,request_id), UNIQUE(session_id,response_id),
+ FOREIGN KEY(session_id,id) REFERENCES code_items(session_id,id) ON DELETE CASCADE
+)""",
+)
+
+
+def upgrade(connection: sqlite3.Connection) -> None:
+ for statement in _SCHEMA:
+ connection.execute(statement)
+ for prompt in connection.execute(
+ "SELECT * FROM code_prompts ORDER BY rowid"
+ ).fetchall():
+ run = connection.execute(
+ "SELECT id FROM code_runs WHERE session_id = ? AND native_turn_id = ?",
+ (prompt["session_id"], prompt["native_turn_id"]),
+ ).fetchone()
+ if run is None and prompt["native_item_id"] is not None:
+ matches = connection.execute(
+ "SELECT DISTINCT run_id AS id FROM code_items WHERE session_id = ? AND native_item_id = ?",
+ (prompt["session_id"], prompt["native_item_id"]),
+ ).fetchall()
+ if len(matches) == 1:
+ run = matches[0]
+ if run is None:
+ run = connection.execute(
+ "SELECT id FROM code_runs WHERE session_id = ? ORDER BY ordinal DESC LIMIT 1",
+ (prompt["session_id"],),
+ ).fetchone()
+ if run is None:
+ raise sqlite3.DatabaseError(
+ "A saved prompt has no saved conversation turn."
+ )
+ sequence = connection.execute(
+ "SELECT COALESCE(MAX(sequence), 0) + 1 FROM code_items WHERE session_id = ?",
+ (prompt["session_id"],),
+ ).fetchone()[0]
+ connection.execute(
+ "INSERT INTO code_items (session_id,id,run_id,sequence,kind,title,text,detail,complete,raw) "
+ "VALUES (?,?,?,?,'prompt','','','',1,'{}')",
+ (prompt["session_id"], prompt["id"], run["id"], sequence),
+ )
+ connection.execute("CREATE TABLE code_prompts_new" + _PROMPT_COLUMNS)
+ columns = "session_id,id,generation,request_id,native_turn_id,native_item_id,kind,form,raw,status,response_id,error"
+ connection.execute(
+ f"INSERT INTO code_prompts_new ({columns}) SELECT {columns} FROM code_prompts"
+ )
+ connection.execute("DROP TABLE code_prompts")
+ connection.execute("ALTER TABLE code_prompts_new RENAME TO code_prompts")
diff --git a/src/free_claude_code/runtime/sqlite_migrations/v0002_code_permissions.py b/src/free_claude_code/runtime/sqlite_migrations/v0002_code_permissions.py
new file mode 100644
index 00000000..04dde1ee
--- /dev/null
+++ b/src/free_claude_code/runtime/sqlite_migrations/v0002_code_permissions.py
@@ -0,0 +1,16 @@
+"""Version 2: persisted permission mode and original native defaults."""
+
+import sqlite3
+
+
+def upgrade(connection: sqlite3.Connection) -> None:
+ for table in ("code_sessions", "code_runs"):
+ connection.execute(
+ f"ALTER TABLE {table} ADD COLUMN mode TEXT NOT NULL DEFAULT 'config' "
+ "CHECK(mode IN ('config','ask','auto_review','full_access'))"
+ )
+ connection.execute(
+ "ALTER TABLE code_sessions ADD COLUMN native_permission_defaults TEXT "
+ "CHECK(native_permission_defaults IS NULL OR "
+ "(json_valid(native_permission_defaults) AND json_type(native_permission_defaults) = 'object'))"
+ )
diff --git a/src/free_claude_code/runtime/sqlite_migrations/v0003_code_context_usage.py b/src/free_claude_code/runtime/sqlite_migrations/v0003_code_context_usage.py
new file mode 100644
index 00000000..d6b029db
--- /dev/null
+++ b/src/free_claude_code/runtime/sqlite_migrations/v0003_code_context_usage.py
@@ -0,0 +1,10 @@
+"""Version 3: optional model context usage for Code sessions."""
+
+import sqlite3
+
+
+def upgrade(connection: sqlite3.Connection) -> None:
+ connection.execute(
+ "ALTER TABLE code_sessions ADD COLUMN context_used_tokens INTEGER "
+ "CHECK(context_used_tokens IS NULL OR context_used_tokens >= 0)"
+ )
diff --git a/tests/contracts/test_codex_smoke_storage.py b/tests/contracts/test_codex_smoke_storage.py
new file mode 100644
index 00000000..075f90fc
--- /dev/null
+++ b/tests/contracts/test_codex_smoke_storage.py
@@ -0,0 +1,58 @@
+"""Exercise the live smoke's SQL assertion without launching a harness."""
+
+import sqlite3
+from contextlib import closing, nullcontext
+from types import SimpleNamespace
+from unittest.mock import MagicMock
+
+import pytest
+
+from free_claude_code.config.paths import FCC_DATABASE_FILENAME
+from smoke.product import test_codex_modes_product_live as smoke
+
+
[email protected]("database_exists", [False, True])
+def test_child_review_smoke_reads_canonical_database_without_creating_files(
+ tmp_path, monkeypatch, database_exists
+):
+ home = tmp_path / "home/.fcc"
+ home.mkdir(parents=True)
+ (home / "code").mkdir()
+ database_path = home / FCC_DATABASE_FILENAME
+ if database_exists:
+ with closing(sqlite3.connect(database_path)) as connection, connection:
+ connection.execute("CREATE TABLE code_sessions(id, native_thread_id)")
+ connection.execute("INSERT INTO code_sessions VALUES ('session','parent')")
+ connection.execute("CREATE TABLE code_items(session_id,kind,raw)")
+ connection.execute(
+ "INSERT INTO code_items VALUES ('session','subagent_auto_review',?)",
+ ('{"threadId":"child"}',),
+ )
+ (tmp_path / "codex-home").mkdir()
+ (tmp_path / "child-marker.txt").write_text("smoke")
+ monkeypatch.setattr(smoke, "_environment", lambda *_: ({}, set()))
+ monkeypatch.setattr(
+ smoke,
+ "_canned_provider",
+ lambda *_: nullcontext(("http://provider.invalid", {"reviews": 1})),
+ )
+ monkeypatch.setattr(
+ smoke,
+ "SmokeServerDriver",
+ lambda *args, **kwargs: SimpleNamespace(
+ run=lambda: nullcontext(SimpleNamespace(base_url="http://server.invalid"))
+ ),
+ )
+
+ async def completed_review(*_):
+ return "session"
+
+ monkeypatch.setattr(smoke, "_exercise_child_review", completed_review)
+ config = MagicMock(spec=smoke.SmokeConfig, timeout_s=1)
+ if database_exists:
+ smoke.test_codex_child_review_local_e2e(config, tmp_path)
+ else:
+ with pytest.raises(sqlite3.OperationalError, match="unable to open"):
+ smoke.test_codex_child_review_local_e2e(config, tmp_path)
+ assert not (home / "code/code.db").exists()
+ assert database_path.exists() == database_exists
diff --git a/tests/runtime/fixtures/code_schema_v0.sql b/tests/runtime/fixtures/code_schema_v0.sql
new file mode 100644
index 00000000..c36e6a45
--- /dev/null
+++ b/tests/runtime/fixtures/code_schema_v0.sql
@@ -0,0 +1,39 @@
+-- Frozen pre-version-1 Code schema, independent of production migrations.
+
+CREATE TABLE IF NOT EXISTS code_sessions(
+ id TEXT PRIMARY KEY NOT NULL, cwd TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
+ harness TEXT NOT NULL CHECK(harness = 'codex'), title TEXT NOT NULL, title_search TEXT NOT NULL,
+ cwd_search TEXT NOT NULL, auto_title INTEGER NOT NULL CHECK(auto_title IN (0,1)), native_thread_id TEXT,
+ native_may_have_input INTEGER NOT NULL CHECK(native_may_have_input IN (0,1)),
+ revision INTEGER NOT NULL CHECK(revision > 0), status TEXT NOT NULL CHECK(status IN ('ready','deleting','delete_uncertain')),
+ error TEXT, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL
+);
+CREATE INDEX IF NOT EXISTS code_sessions_recent ON code_sessions(updated_at DESC, id DESC);
+CREATE TABLE IF NOT EXISTS code_runs(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ ordinal INTEGER NOT NULL CHECK(ordinal > 0), text TEXT NOT NULL, model TEXT NOT NULL, reasoning_effort TEXT,
+ status TEXT NOT NULL CHECK(status IN ('preparing','running','stopping','completed','interrupted','failed')),
+ submission_started INTEGER NOT NULL CHECK(submission_started IN (0,1)), native_turn_id TEXT,
+ stop_requested INTEGER NOT NULL CHECK(stop_requested IN (0,1)), error TEXT, error_details TEXT NOT NULL,
+ created_at INTEGER NOT NULL, finished_at INTEGER,
+ PRIMARY KEY(session_id,id), UNIQUE(session_id,ordinal), UNIQUE(session_id,native_turn_id)
+);
+CREATE UNIQUE INDEX IF NOT EXISTS code_one_active_run ON code_runs(session_id)
+ WHERE status IN ('preparing','running','stopping');
+CREATE TABLE IF NOT EXISTS code_items(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ run_id TEXT NOT NULL, sequence INTEGER NOT NULL CHECK(sequence > 0), native_turn_id TEXT, native_item_id TEXT,
+ kind TEXT NOT NULL, title TEXT NOT NULL, text TEXT NOT NULL, detail TEXT NOT NULL,
+ complete INTEGER NOT NULL CHECK(complete IN (0,1)), raw TEXT NOT NULL,
+ PRIMARY KEY(session_id,id), FOREIGN KEY(session_id,run_id) REFERENCES code_runs(session_id,id) ON DELETE CASCADE,
+ UNIQUE(session_id,sequence), UNIQUE(session_id,native_turn_id,native_item_id)
+);
+CREATE INDEX IF NOT EXISTS code_items_run ON code_items(session_id,run_id,sequence);
+CREATE TABLE IF NOT EXISTS code_deleted(id TEXT PRIMARY KEY NOT NULL);
+CREATE TABLE IF NOT EXISTS code_prompts(
+ session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, id TEXT NOT NULL,
+ generation TEXT NOT NULL, request_id TEXT NOT NULL, native_turn_id TEXT, native_item_id TEXT,
+ kind TEXT NOT NULL, form TEXT NOT NULL, raw TEXT NOT NULL,
+ status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')), response_id TEXT, error TEXT,
+ PRIMARY KEY(session_id,id), UNIQUE(session_id,generation,request_id), UNIQUE(session_id,response_id)
+);
\ No newline at end of file
diff --git a/tests/runtime/test_sqlite_database.py b/tests/runtime/test_sqlite_database.py
new file mode 100644
index 00000000..6f10791f
--- /dev/null
+++ b/tests/runtime/test_sqlite_database.py
@@ -0,0 +1,472 @@
+import asyncio
+import os
+import sqlite3
+import subprocess
+import sys
+import threading
+from contextlib import closing
+from pathlib import Path
+
+import httpx
+import pytest
+
+from free_claude_code.application.code_sessions.models import CodeUnavailableError
+from free_claude_code.runtime import sqlite_database
+from free_claude_code.runtime.code_sessions_sqlite import SQLiteCodeStore
+from free_claude_code.runtime.sqlite_database import initialize_database
+
+
+def historical_database(path: Path, version: int) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ schema = (Path(__file__).parent / "fixtures/code_schema_v0.sql").read_text()
+ with closing(sqlite3.connect(path)) as connection, connection:
+ connection.executescript(schema)
+ if version >= 1:
+ connection.execute("DROP TABLE code_prompts")
+ connection.execute(
+ "CREATE TABLE code_prompts("
+ "session_id TEXT NOT NULL REFERENCES code_sessions(id) ON DELETE CASCADE, "
+ "id TEXT NOT NULL, generation TEXT NOT NULL, request_id TEXT NOT NULL, "
+ "native_turn_id TEXT, native_item_id TEXT, kind TEXT NOT NULL, "
+ "form TEXT NOT NULL, raw TEXT NOT NULL, "
+ "status TEXT NOT NULL CHECK(status IN ('pending','answering','resolved','expired')), "
+ "response_id TEXT, error TEXT, PRIMARY KEY(session_id,id), "
+ "UNIQUE(session_id,generation,request_id), UNIQUE(session_id,response_id), "
+ "FOREIGN KEY(session_id,id) REFERENCES code_items(session_id,id) ON DELETE CASCADE)"
+ )
+ if version >= 2:
+ for table in ("code_sessions", "code_runs"):
+ connection.execute(
+ f"ALTER TABLE {table} ADD COLUMN mode TEXT NOT NULL DEFAULT 'config' "
+ "CHECK(mode IN ('config','ask','auto_review','full_access'))"
+ )
+ connection.execute(
+ "ALTER TABLE code_sessions ADD COLUMN native_permission_defaults TEXT "
+ "CHECK(native_permission_defaults IS NULL OR "
+ "(json_valid(native_permission_defaults) AND json_type(native_permission_defaults) = 'object'))"
+ )
+ if version >= 3:
+ connection.execute(
+ "ALTER TABLE code_sessions ADD COLUMN context_used_tokens INTEGER "
+ "CHECK(context_used_tokens IS NULL OR context_used_tokens >= 0)"
+ )
+ connection.execute(f"PRAGMA user_version={version}")
+ connection.execute(
+ "INSERT INTO code_sessions (id,cwd,model,harness,title,title_search,cwd_search,"
+ "auto_title,native_thread_id,native_may_have_input,revision,status,created_at,updated_at) "
+ "VALUES ('s','/work','provider/model','codex','Saved','saved','/work',0,'thread',1,7,'ready',100,200)"
+ )
+ connection.execute(
+ "INSERT INTO code_runs (session_id,id,ordinal,text,model,status,submission_started,"
+ "native_turn_id,stop_requested,error_details,created_at,finished_at) "
+ "VALUES ('s','r',1,'User input','provider/model','completed',1,'turn',0,'{}',100,150)"
+ )
+ connection.execute(
+ "INSERT INTO code_items VALUES ('s','i','r',1,'turn','native-item',"
+ "'assistant','Title','Saved answer','Detail',1,'{\"payload\": true}')"
+ )
+ if version >= 1:
+ connection.execute(
+ "INSERT INTO code_items VALUES ('s','p','r',2,NULL,NULL,'prompt','','','',1,'{}')"
+ )
+ connection.execute(
+ "INSERT INTO code_prompts VALUES ('s','p','g','42','turn',NULL,'questions',"
+ "'{\"question\": \"Continue?\"}','{\"saved\": true}','resolved','response',NULL)"
+ )
+ connection.execute("INSERT INTO code_deleted VALUES ('deleted-session')")
+ if version >= 2:
+ connection.execute(
+ "UPDATE code_sessions SET mode='full_access', native_permission_defaults='{\"original\": true}'"
+ )
+ if version >= 3:
+ connection.execute("UPDATE code_sessions SET context_used_tokens=1234")
+
+
+def snapshot(path: Path) -> dict[str, list[dict]]:
+ with closing(sqlite3.connect(path)) as connection:
+ connection.row_factory = sqlite3.Row
+ return {
+ table: [dict(row) for row in connection.execute(f"SELECT * FROM {table}")]
+ for table in (
+ "code_sessions",
+ "code_runs",
+ "code_items",
+ "code_prompts",
+ "code_deleted",
+ )
+ }
+
+
[email protected]("version", [0, 1, 2, 3])
+def test_historical_database_moves_and_upgrades_without_losing_records(
+ tmp_path, version
+):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, version)
+ before = snapshot(old)
+ for _ in range(2):
+ initialize_database(target, old)
+ assert not old.exists()
+ after = snapshot(target)
+ for table, rows in before.items():
+ for previous, saved in zip(
+ rows, after[table], strict=table != "code_items" or version != 0
+ ):
+ assert {key: saved[key] for key in previous} == previous
+ assert len(after["code_items"]) == 2
+ assert after["code_items"][-1]["kind"] == "prompt"
+ with closing(sqlite3.connect(target)) as connection:
+ assert connection.execute("PRAGMA user_version").fetchone() == (3,)
+ assert connection.execute("PRAGMA journal_mode").fetchone() == ("wal",)
+ assert connection.execute("PRAGMA foreign_key_check").fetchall() == []
+
+
+def test_fresh_database_uses_only_destination_and_is_repeatable(tmp_path):
+ target, old = tmp_path / "fcc.db", tmp_path / "code/code.db"
+ initialize_database(target, old)
+ initialize_database(target, old)
+ assert not old.exists()
+ assert all(not rows for rows in snapshot(target).values())
+
+
+def test_two_databases_are_preserved_without_choosing_a_winner(tmp_path):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 1)
+ historical_database(target, 3)
+ before = [path.read_bytes() for path in (old, target)]
+ with pytest.raises(sqlite3.DatabaseError, match="both"):
+ initialize_database(target, old)
+ assert [path.read_bytes() for path in (old, target)] == before
+
+
[email protected]("suffix", ["-wal", "-shm", "-journal"])
[email protected]("location", ["fcc.db", "code/code.db"])
+def test_orphan_journals_are_not_treated_as_a_fresh_database(
+ tmp_path, suffix, location
+):
+ orphan = tmp_path / (location + suffix)
+ orphan.parent.mkdir(parents=True, exist_ok=True)
+ orphan.write_bytes(b"preserve")
+ with pytest.raises(sqlite3.DatabaseError, match="journal"):
+ initialize_database(tmp_path / "fcc.db", tmp_path / "code/code.db")
+ assert orphan.read_bytes() == b"preserve"
+ assert not (tmp_path / "fcc.db").exists()
+
+
[email protected]("version", [-1, 4])
+def test_unsupported_version_is_not_moved_or_mutated(tmp_path, version):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 3)
+ with closing(sqlite3.connect(old)) as connection:
+ connection.execute(f"PRAGMA user_version={version}")
+ before = old.read_bytes()
+ with pytest.raises(sqlite3.DatabaseError, match="version"):
+ initialize_database(target, old)
+ assert old.read_bytes() == before
+ assert not target.exists()
+
+
+ "statement", ["CREATE TABLE unrelated(id)", "CREATE TABLE code_sessions(id)"]
+)
+def test_unrecognized_schema_is_not_blessed_or_moved(tmp_path, statement):
+ old, target = tmp_path / "code.db", tmp_path / "fcc.db"
+ with closing(sqlite3.connect(old)) as connection:
+ connection.execute(statement)
+ with pytest.raises(sqlite3.DatabaseError, match="schema"):
+ initialize_database(target, old)
+ assert old.exists() and not target.exists()
+
+
+def test_committed_wal_survives_unclean_exit_and_relocation(tmp_path):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 3)
+ subprocess.run(
+ [
+ sys.executable,
+ "-c",
+ """
+import os, sqlite3, sys
+c = sqlite3.connect(sys.argv[1])
+c.execute('PRAGMA journal_mode=WAL')
+c.execute("UPDATE code_items SET text='Committed in WAL' WHERE id='i'")
+c.commit()
+os._exit(0)
+""",
+ str(old),
+ ],
+ check=True,
+ timeout=10,
+ )
+ assert Path(f"{old}-wal").stat().st_size > 0
+ initialize_database(target, old)
+ assert snapshot(target)["code_items"][0]["text"] == "Committed in WAL"
+ assert not any(old.parent.glob("code.db*"))
+
+
+def test_failed_rename_preserves_source_and_can_retry(tmp_path, monkeypatch):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 3)
+ before = snapshot(old)
+ with monkeypatch.context() as patch:
+
+ def fail_rename(self, target):
+ raise PermissionError("move blocked")
+
+ patch.setattr(Path, "rename", fail_rename)
+ with pytest.raises(PermissionError):
+ initialize_database(target, old)
+ assert old.exists() and not target.exists()
+ assert snapshot(old) == before
+ initialize_database(target, old)
+ assert snapshot(target) == before
+
+
[email protected]("failing_version", [1, 2])
+def test_migration_failure_after_move_rolls_back_and_retries_at_destination(
+ tmp_path, monkeypatch, failing_version
+):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 0)
+ migrations = sqlite_database.MIGRATIONS
+ original = migrations[failing_version - 1][1]
+
+ def fail_upgrade(connection):
+ original(connection)
+ connection.execute("CREATE TABLE must_rollback(id)")
+ raise sqlite3.DatabaseError("injected migration failure")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(
+ sqlite_database,
+ "MIGRATIONS",
+ tuple(
+ (version, fail_upgrade if version == failing_version else upgrade)
+ for version, upgrade in migrations
+ ),
+ )
+ with pytest.raises(sqlite3.DatabaseError, match="injected"):
+ initialize_database(target, old)
+ assert target.exists() and not old.exists()
+ with closing(sqlite3.connect(target)) as connection:
+ assert connection.execute("PRAGMA user_version").fetchone() == (
+ failing_version - 1,
+ )
+ assert not connection.execute(
+ "SELECT name FROM sqlite_schema WHERE name='must_rollback'"
+ ).fetchall()
+ columns = {
+ row[1] for row in connection.execute("PRAGMA table_info(code_sessions)")
+ }
+ assert "mode" not in columns
+ assert (
+ connection.execute("SELECT count(*) FROM code_items").fetchone()[0]
+ == failing_version
+ )
+ initialize_database(target, old)
+ assert len(snapshot(target)["code_items"]) == 2
+
+
+def test_fresh_schema_failure_rolls_back_all_ddl(tmp_path, monkeypatch):
+ target = tmp_path / "fcc.db"
+ original = sqlite_database.MIGRATIONS[0][1]
+
+ def fail_upgrade(connection):
+ original(connection)
+ raise sqlite3.DatabaseError("injected fresh failure")
+
+ with monkeypatch.context() as patch:
+ patch.setattr(sqlite_database, "MIGRATIONS", ((1, fail_upgrade),))
+ with pytest.raises(sqlite3.DatabaseError, match="injected"):
+ initialize_database(target)
+ with closing(sqlite3.connect(target)) as connection:
+ assert connection.execute("PRAGMA user_version").fetchone() == (0,)
+ assert not connection.execute("SELECT name FROM sqlite_schema").fetchall()
+ initialize_database(target)
+ assert all(not rows for rows in snapshot(target).values())
+
+
+def test_current_schema_does_not_execute_historical_migrations(tmp_path, monkeypatch):
+ target = tmp_path / "fcc.db"
+ historical_database(target, 3)
+
+ def already_applied(connection):
+ pytest.fail("An applied migration was executed again")
+
+ monkeypatch.setattr(
+ sqlite_database,
+ "MIGRATIONS",
+ tuple((version, already_applied) for version in (1, 2, 3)),
+ )
+ initialize_database(target)
+
+
+def test_busy_wal_is_not_renamed_and_retries_after_reader_closes(tmp_path, monkeypatch):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 3)
+ connect = sqlite_database._connect
+
+ def no_wait(*args, **kwargs):
+ connection = connect(*args, **kwargs)
+ connection.execute("PRAGMA busy_timeout=0")
+ return connection
+
+ monkeypatch.setattr(sqlite_database, "_connect", no_wait)
+ with (
+ closing(sqlite3.connect(old)) as writer,
+ closing(sqlite3.connect(old)) as reader,
+ ):
+ writer.execute("PRAGMA journal_mode=WAL")
+ reader.execute("BEGIN")
+ reader.execute("SELECT * FROM code_items").fetchall()
+ writer.execute("UPDATE code_items SET text='newest committed' WHERE id='i'")
+ writer.commit()
+ with pytest.raises(sqlite3.DatabaseError, match="checkpoint is busy"):
+ initialize_database(target, old)
+ assert old.exists() and not target.exists()
+ initialize_database(target, old)
+ assert snapshot(target)["code_items"][0]["text"] == "newest committed"
+
+
[email protected]("redirect", ["directory", "database"])
+def test_redirected_legacy_storage_is_not_moved(tmp_path, redirect):
+ elsewhere = tmp_path / "elsewhere/code.db"
+ historical_database(elsewhere, 3)
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ try:
+ if redirect == "directory":
+ old.parent.symlink_to(elsewhere.parent, target_is_directory=True)
+ else:
+ old.parent.mkdir()
+ old.symlink_to(elsewhere)
+ except OSError:
+ pytest.skip("Symlink creation is unavailable")
+ before = elsewhere.read_bytes()
+ with pytest.raises(sqlite3.DatabaseError, match="redirected"):
+ initialize_database(target, old)
+ assert elsewhere.read_bytes() == before
+ assert not target.exists()
+
+
+async def test_restart_recovery_runs_after_current_schema_relocation(tmp_path):
+ old, target, lock = (
+ tmp_path / "code/code.db",
+ tmp_path / "fcc.db",
+ tmp_path / "code/code.lock",
+ )
+ historical_database(old, 3)
+ for iteration in range(2):
+ current = old if iteration == 0 else target
+ with closing(sqlite3.connect(current)) as connection, connection:
+ connection.execute(
+ "UPDATE code_runs SET status='running', finished_at=NULL"
+ )
+ connection.execute("UPDATE code_prompts SET status='answering'")
+ store = SQLiteCodeStore(target, lock, legacy_database_path=old)
+ try:
+ await store.start()
+ run = await store.get_run("s", "r")
+ assert run is not None
+ assert run.status == "interrupted" and run.finished_at is not None
+ assert (await store.prompts("s"))[0].status == "expired"
+ finally:
+ await store.close()
+
+
+async def test_old_owner_blocks_move_and_new_owner_uses_same_lock(tmp_path):
+ old, target, lock = (
+ tmp_path / "code/code.db",
+ tmp_path / "fcc.db",
+ tmp_path / "code/code.lock",
+ )
+ historical_database(old, 3)
+ first = SQLiteCodeStore(old, lock)
+ second = SQLiteCodeStore(target, lock, legacy_database_path=old)
+ await first.start()
+ try:
+ with pytest.raises(CodeUnavailableError, match="another FCC"):
+ await second.start()
+ assert old.exists() and not target.exists()
+ finally:
+ await first.close()
+ await second.start()
+ try:
+ assert (await second.get_session("s")).title == "Saved"
+ assert lock.exists() and not old.exists()
+ finally:
+ await second.close()
+
+
[email protected](os.name == "nt", reason="POSIX permission contract")
+def test_relocated_database_keeps_private_permissions(tmp_path):
+ old, target = tmp_path / "code/code.db", tmp_path / "fcc.db"
+ historical_database(old, 3)
+ old.chmod(0o600)
+ initialize_database(target, old)
+ assert target.stat().st_mode & 0o777 == 0o600
+
+
[email protected]("fail_migration", [False, True])
+async def test_production_startup_keeps_http_available_and_chat_cleanup_independent(
+ monkeypatch, fail_migration
+):
+ from free_claude_code.config import paths
+ from free_claude_code.config.settings import Settings
+ from free_claude_code.core.interprocess_lock import InterprocessFileLock
+ from free_claude_code.runtime import bootstrap, code_sessions_sqlite
+ from free_claude_code.runtime.provider_manager import ProviderRuntimeManager
+ from free_claude_code.runtime.retired_chat import remove_retired_chat_history
+
+ old, target = paths.legacy_code_database_path(), paths.fcc_database_path()
+ historical_database(old, 3)
+ chat = paths.config_dir_path() / "chat/chat.db"
+ chat.parent.mkdir()
+ chat.write_bytes(b"retired history")
+ chat_lock = InterprocessFileLock(chat.parent / "chat.lock")
+ assert chat_lock.acquire()
+ entered, release = threading.Event(), threading.Event()
+
+ def gated_migration(*args):
+ entered.set()
+ assert release.wait(10)
+ if fail_migration:
+ raise sqlite3.DatabaseError("injected migration failure")
+ initialize_database(*args)
+
+ monkeypatch.setattr(code_sessions_sqlite, "initialize_database", gated_migration)
+ monkeypatch.setattr(bootstrap, "configure_logging", lambda *args, **kwargs: None)
+ monkeypatch.setattr(
+ ProviderRuntimeManager, "start_model_list_refresh", lambda _: None
+ )
+ app = bootstrap.build_asgi_app(
+ Settings().model_copy(update={"messaging_platform": "none"})
+ )
+ code = app.runtime._code_service
+ assert code is not None
+ try:
+ await asyncio.wait_for(app.runtime.start(), 3)
+ assert await asyncio.to_thread(entered.wait, 3)
+ assert code.storage_status()["state"] == "starting"
+ async with httpx.AsyncClient(
+ transport=httpx.ASGITransport(app=app), base_url="http://127.0.0.1"
+ ) as client:
+ assert (await client.get("/health")).status_code == 200
+ release.set()
+ await asyncio.wait_for(asyncio.gather(*app.runtime._startup_tasks), 5)
+ assert code.storage_status()["state"] == (
+ "failed" if fail_migration else "ready"
+ )
+ assert (await client.get("/health")).status_code == 200
+ assert chat.exists()
+ assert old.exists() == fail_migration
+ assert target.exists() != fail_migration
+ finally:
+ release.set()
+ chat_lock.release()
+ await app.runtime.close()
+ remove_retired_chat_history()
+ assert not chat.exists()
+ assert (old if fail_migration else target).exists()