Skip to content

The agent that grows with you

fix(tools): a SQLite sidecar path is refused even when no sidecar file exists yet

kshitijk4poord219e5755a29
diff --git a/tests/tools/test_binary_document_write_guard.py b/tests/tools/test_binary_document_write_guard.py
index ce6abca3d62..7ab7d809d91 100644
--- a/tests/tools/test_binary_document_write_guard.py
+++ b/tests/tools/test_binary_document_write_guard.py
@@ -11,6 +11,8 @@ import sqlite3
import zipfile
from pathlib import Path
+import pytest
+
from tools.binary_extensions import (
has_opaque_document_extension,
is_pdf_path,
@@ -135,20 +137,28 @@ class TestWriteFileToolGuard:
assert not result.get("error")
assert pdf.exists()
- def test_write_file_rejects_sqlite_wal_sidecar(self, tmp_path: Path):
+ @pytest.mark.parametrize("sidecar_exists", [True, False])
+ def test_write_file_rejects_sqlite_wal_sidecar(self, tmp_path: Path, sidecar_exists: bool):
# ".db-wal" is not a suffix in BINARY_EXTENSIONS; the sidecar must still
- # count as its database's extension or text lands in the WAL.
+ # count as its database's extension or text lands in the WAL. A
+ # checkpointed db has no sidecar on disk, so the absent case must be
+ # refused too — otherwise a garbage WAL lands next to a live database.
db = tmp_path / "state.db"
- wal = _make_wal_db(db)
- original = wal.read_bytes()
+ if sidecar_exists:
+ wal = _make_wal_db(db)
+ original = wal.read_bytes()
+ else:
+ sqlite3.connect(db).close()
+ wal = Path(str(db) + "-wal")
+ assert not wal.exists()
result = json.loads(write_file_tool(str(wal), "CREATE TABLE x(y);"))
# The no-baseline overwrite guard would also refuse; pin the binary
# refusal so the message steers the model to sqlite3, not to read_file.
assert "binary" in result.get("error", ""), result
- assert wal.read_bytes() == original
- conn = sqlite3.connect(db)
- assert conn.execute("PRAGMA integrity_check;").fetchone()[0] == "ok"
- conn.close()
+ if sidecar_exists:
+ assert wal.read_bytes() == original
+ else:
+ assert not wal.exists()
def test_write_file_plain_text_unaffected(self, tmp_path: Path):
target = tmp_path / "notes.txt"
diff --git a/tools/binary_extensions.py b/tools/binary_extensions.py
index a45b73251b3..f15f1708a40 100644
--- a/tools/binary_extensions.py
+++ b/tools/binary_extensions.py
@@ -36,21 +36,46 @@ OPAQUE_DOCUMENT_EXTENSIONS = frozenset({
# write guard would treat the raw page bytes as text.
_SQLITE_SIDECAR_MARKERS = ("-wal", "-shm", "-journal")
+# Only these suffixes take a sidecar marker; ``report.docx-wal`` is not a
+# document and must not be treated as one.
+_SQLITE_EXTENSIONS = frozenset({".db", ".sqlite", ".sqlite3", ".db3"}) & BINARY_EXTENSIONS
+
+
+def _strip_sidecar_marker(suffix: str) -> str | None:
+ """Return the database suffix a lower-cased sidecar suffix hangs off
+ (``.db-wal`` -> ``.db``), or None when ``suffix`` is not a SQLite sidecar."""
+ for marker in _SQLITE_SIDECAR_MARKERS:
+ if suffix.endswith(marker):
+ base = suffix[: -len(marker)]
+ if base in _SQLITE_EXTENSIONS:
+ return base
+ return None
+
def _has_extension_in(path: str, extensions: frozenset) -> bool:
"""Case-insensitive check on the final ``.suffix``; pure string, no I/O.
- A SQLite sidecar counts as its database's extension."""
+ A SQLite sidecar counts as its database's extension (only SQLite suffixes
+ are stripped, so ``x.docx-wal`` stays unrecognised)."""
dot = path.rfind(".")
if dot == -1:
return False
suffix = path[dot:].lower()
- for marker in _SQLITE_SIDECAR_MARKERS:
- if suffix.endswith(marker):
- suffix = suffix[: -len(marker)]
- break
+ base = _strip_sidecar_marker(suffix)
+ if base is not None:
+ suffix = base
return suffix in extensions
+def is_sqlite_sidecar(path: str) -> bool:
+ """True for ``x.db-wal`` / ``x.sqlite3-shm`` / ``x.db-journal`` paths.
+ Pure string, no I/O — a sidecar path is never a legitimate text target
+ even when no sidecar exists on disk (a checkpointed db has none)."""
+ dot = path.rfind(".")
+ if dot == -1:
+ return False
+ return _strip_sidecar_marker(path[dot:].lower()) is not None
+
+
def has_binary_extension(path: str) -> bool:
return _has_extension_in(path, BINARY_EXTENSIONS)
diff --git a/tools/file_tools_write_guards.py b/tools/file_tools_write_guards.py
index f032903a786..df40d2905b2 100644
--- a/tools/file_tools_write_guards.py
+++ b/tools/file_tools_write_guards.py
@@ -20,6 +20,7 @@ from tools.binary_extensions import (
has_binary_extension,
has_opaque_document_extension,
is_pdf_path,
+ is_sqlite_sidecar,
)
from tools.file_tools_paths import _expand_tilde, _resolve_path_for_task
from tools.file_tools_read_tracking import _has_full_write_baseline, _read_mtime_drifted
@@ -438,19 +439,30 @@ def _check_binary_document_write(filepath: str, task_id: str = "default") -> str
"bytes). Use the docx/xlsx/powerpoint skills or a library like "
"python-docx/openpyxl/python-pptx via the terminal to create or edit "
"this document.")
- # Overwriting an existing binary (PDF, image, archive, SQLite db or its
- # -wal/-shm sidecar, ...) with text destroys it — the model only ever saw
- # extracted or mojibake text. Creating a NEW file with such an extension
- # stays allowed: raw PDF syntax is text-authorable and text fixtures
- # named ``*.db`` exist.
- if is_pdf_path(filepath) or has_binary_extension(filepath):
+ # A -wal/-shm/-journal path is never a legitimate text target, even when
+ # no sidecar exists yet: a checkpointed db has none on disk, and a garbage
+ # WAL dropped next to a live database is picked up on the next open.
+ if is_sqlite_sidecar(filepath):
+ ext = filepath[filepath.rfind("."):].lower()
+ return (
+ f"Refusing to write plain text to binary SQLite sidecar '{filepath}' ({ext}). "
+ "A -wal/-shm/-journal file holds raw database pages that SQLite "
+ "reads on the next open; text there corrupts the database. Use the "
+ "sqlite3 CLI or a SQLite library via the terminal to modify the "
+ "database instead.")
+ # Overwriting an existing binary (PDF, image, archive, SQLite db, ...)
+ # with text destroys it — the model only ever saw extracted or mojibake
+ # text. Creating a NEW file with such an extension stays allowed: raw PDF
+ # syntax is text-authorable and text fixtures named ``*.db`` exist.
+ pdf = is_pdf_path(filepath)
+ if pdf or has_binary_extension(filepath):
try:
resolved = Path(_resolve_path_for_task(filepath, task_id))
except Exception:
resolved = Path(_expand_tilde(filepath))
try:
if resolved.is_file():
- if is_pdf_path(filepath):
+ if pdf:
return (
f"Refusing to overwrite existing PDF '{filepath}' with plain text. "
"read_file showed you EXTRACTED text, not the real bytes — writing "
@@ -463,9 +475,8 @@ def _check_binary_document_write(filepath: str, task_id: str = "default") -> str
"with plain text — read_file showed you extracted or mojibake "
"text, not the real bytes, and writing text back would destroy "
"the file. Use a binary-aware tool via the terminal to modify it "
- "(for SQLite databases and their -wal/-shm sidecars, the sqlite3 "
- "CLI or a SQLite library). (Creating a NEW file with this "
- "extension is allowed.)")
+ "(for SQLite databases, the sqlite3 CLI or a SQLite library). "
+ "(Creating a NEW file with this extension is allowed.)")
except OSError:
pass
return None