Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

fix(sqlite): escape database paths in one shared file URI builder (#850)

Rudy Mizrahi Celekli9b2aafd102a7
diff --git a/cli/beacon/internal/cursorsession/store.go b/cli/beacon/internal/cursorsession/store.go
index 95bdf661..4b357327 100644
--- a/cli/beacon/internal/cursorsession/store.go
+++ b/cli/beacon/internal/cursorsession/store.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"
"io/fs"
"net/url"
"os"
@@ -432,16 +433,7 @@ func openSQLiteReadOnly(path string) (*sql.DB, error) {
if err != nil {
return nil, err
}
- uriPath := filepath.ToSlash(path)
- if !strings.HasPrefix(uriPath, "/") {
- uriPath = "/" + uriPath
- }
- u := url.URL{Scheme: "file", Path: uriPath}
- q := u.Query()
- q.Set("mode", "ro")
- q.Set("_pragma", "busy_timeout(1000)")
- u.RawQuery = q.Encode()
- return sql.Open("sqlite", u.String())
+ return sql.Open("sqlite", sqliteuri.File(path, url.Values{"mode": {"ro"}, "_pragma": {"busy_timeout(1000)"}}))
}
func fileExists(path string) bool {
diff --git a/cli/beacon/internal/endpoint/dashboard/history_literal_path_test.go b/cli/beacon/internal/endpoint/dashboard/history_literal_path_test.go
new file mode 100644
index 00000000..ee964111
--- /dev/null
+++ b/cli/beacon/internal/endpoint/dashboard/history_literal_path_test.go
@@ -0,0 +1,36 @@
+package dashboard
+
+import (
+ endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestHistoryOpensLiteralURICharacters(t *testing.T) {
+ for _, name := range []string{"plain", "project#draft", "project%25name"} {
+ t.Run(name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), name, "history.db")
+ t.Setenv(endpointconfig.HistoryStoreEnv, path)
+ e := testSchemaEvent("2026-10-13T12:00:00Z", "claude_code", "prompt.submitted", "prompt", "")
+ e.Session = &schema.SessionInfo{ID: "literal-path"}
+ log := newTestLog(t, marshalEvents(t, e))
+ got, err := EnableHistoryStore(log, HistoryOptions{RetentionDays: 36500})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !got.Enabled || got.Path != path || got.Traces != 1 || got.Events != 1 {
+ t.Fatalf("history: %+v", got)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Size() == 0 {
+ t.Fatalf("literal database not populated: stat%v info%v", err, info)
+ }
+ again, err := TraceStoreStatus(log)
+ if err != nil || again.Traces != 1 || again.Events != 1 {
+ t.Fatalf("reopen: %+v %v", again, err)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/endpoint/dashboard/history_store.go b/cli/beacon/internal/endpoint/dashboard/history_store.go
index 59629658..dc477b39 100644
--- a/cli/beacon/internal/endpoint/dashboard/history_store.go
+++ b/cli/beacon/internal/endpoint/dashboard/history_store.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"math"
+ "net/url"
"os"
"path/filepath"
"strconv"
@@ -16,6 +17,7 @@ import (
endpointconfig "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/config"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve/filelock"
)
@@ -216,7 +218,7 @@ func openHistoryStore(create bool) (*historyStore, error) {
_ = f.Close()
}
}
- db, err := sql.Open("sqlite", historyURI(path))
+ db, err := sql.Open("sqlite", sqliteuri.File(path, url.Values{"_pragma": {"busy_timeout(10000)", "journal_mode(WAL)", "synchronous(NORMAL)"}}))
if err != nil {
return nil, err
}
@@ -228,14 +230,6 @@ func openHistoryStore(create bool) (*historyStore, error) {
return store, nil
}
-func historyURI(path string) string {
- abs, err := filepath.Abs(path)
- if err != nil {
- abs = path
- }
- return "file:" + filepath.ToSlash(abs) + "?_pragma=busy_timeout(10000)&_pragma=journal_mode(WAL)&_pragma=synchronous(NORMAL)"
-}
-
func (s *historyStore) close() {
_ = s.db.Close()
}
diff --git a/cli/beacon/internal/hermessession/collect.go b/cli/beacon/internal/hermessession/collect.go
index 5e74f05d..8370ec19 100644
--- a/cli/beacon/internal/hermessession/collect.go
+++ b/cli/beacon/internal/hermessession/collect.go
@@ -22,6 +22,7 @@ import (
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/schema"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/endpoint/writer"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionwindow"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
_ "modernc.org/sqlite"
)
@@ -589,16 +590,7 @@ func openSQLiteReadOnly(path string) (*sql.DB, error) {
if err != nil {
return nil, err
}
- uriPath := filepath.ToSlash(path)
- if !strings.HasPrefix(uriPath, "/") {
- uriPath = "/" + uriPath
- }
- u := url.URL{Scheme: "file", Path: uriPath}
- q := u.Query()
- q.Set("mode", "ro")
- q.Set("_pragma", "busy_timeout(1000)")
- u.RawQuery = q.Encode()
- return sql.Open("sqlite", u.String())
+ return sql.Open("sqlite", sqliteuri.File(path, url.Values{"mode": {"ro"}, "_pragma": {"busy_timeout(1000)"}}))
}
// MapSession maps one session's new messages into endpoint events. It also returns the tool calls
diff --git a/cli/beacon/internal/learning/store.go b/cli/beacon/internal/learning/store.go
index 478dd1cb..9faf1a9a 100644
--- a/cli/beacon/internal/learning/store.go
+++ b/cli/beacon/internal/learning/store.go
@@ -6,6 +6,7 @@ import (
"encoding/hex"
"encoding/json"
"fmt"
+ "net/url"
"os"
"path/filepath"
"strings"
@@ -13,6 +14,7 @@ import (
_ "modernc.org/sqlite"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"
"github.com/asymptote-labs/agent-beacon/pkg/asymptoteobserve"
)
@@ -69,7 +71,7 @@ func (s *Store) db() (*sql.DB, error) {
if err := os.MkdirAll(filepath.Dir(s.dbPath), 0700); err != nil && filepath.Dir(s.dbPath) != "." {
return nil, err
}
- db, err := sql.Open("sqlite", sqliteURI(s.dbPath))
+ db, err := sql.Open("sqlite", sqliteuri.File(s.dbPath, url.Values{"_pragma": {"busy_timeout(5000)"}}))
if err != nil {
return nil, err
}
@@ -84,14 +86,6 @@ func (s *Store) db() (*sql.DB, error) {
return db, nil
}
-func sqliteURI(path string) string {
- abs, err := filepath.Abs(path)
- if err != nil {
- abs = path
- }
- return "file:" + filepath.ToSlash(abs) + "?_pragma=busy_timeout(5000)"
-}
-
func ensureSchema(db *sql.DB) error {
var version int
if err := db.QueryRow(`PRAGMA user_version`).Scan(&version); err != nil {
diff --git a/cli/beacon/internal/learning/store_literal_path_test.go b/cli/beacon/internal/learning/store_literal_path_test.go
new file mode 100644
index 00000000..963f96fb
--- /dev/null
+++ b/cli/beacon/internal/learning/store_literal_path_test.go
@@ -0,0 +1,30 @@
+package learning
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+)
+
+func TestStoreOpensLiteralURICharacters(t *testing.T) {
+ for _, name := range []string{"plain", "project#draft", "project%25name"} {
+ t.Run(name, func(t *testing.T) {
+ path := filepath.Join(t.TempDir(), name, "memory.db")
+ store := Open(path)
+ got, err := store.Status()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got.Path != path {
+ t.Fatalf("path%q want%q", got.Path, path)
+ }
+ info, err := os.Stat(path)
+ if err != nil || info.Size() == 0 {
+ t.Fatalf("literal database not populated: stat%v info%v", err, info)
+ }
+ if _, err = Open(path).Status(); err != nil {
+ t.Fatal(err)
+ }
+ })
+ }
+}
diff --git a/cli/beacon/internal/opencodesession/store.go b/cli/beacon/internal/opencodesession/store.go
index 4828b449..fd74efdd 100644
--- a/cli/beacon/internal/opencodesession/store.go
+++ b/cli/beacon/internal/opencodesession/store.go
@@ -6,6 +6,7 @@ import (
"errors"
"fmt"
"github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sessionfs"
+ "github.com/asymptote-labs/agent-beacon/cli/beacon/internal/sqliteuri"
"io/fs"
"net/url"
"os"
@@ -634,54 +635,14 @@ func legacyProjectDirectory(path string) string {
return firstNonEmpty(stringFromMap(raw, "worktree"), stringFromMap(raw, "directory"), stringFromMap(raw, "name"))
}
+// openSQLiteReadOnly opens OpenCode's store read-only. modernc.org/sqlite opens every database
+// READWRITE|CREATE, so mode=ro in the URI is the one thing keeping this read from writing to it.
func openSQLiteReadOnly(path string) (*sql.DB, error) {
path, err := sessionfs.SQLitePath(path)
if err != nil {
return nil, err
}
- return sql.Open("sqlite", sqliteFileURI(path))
-}
-
-// sqliteFileURI renders an OS path as the file: URI the driver needs to honour mode=ro.
-//
-// The URI form is not optional: modernc.org/sqlite only forwards query parameters to SQLite when
-// the DSN starts with "file:", and it opens every database with READWRITE|CREATE flags, so mode=ro
-// is the one thing keeping a read of OpenCode's store from writing to it.
-//
-// Handing url.URL a raw OS path does not produce that URI on Windows. A path like
-// C:\Users\me\opencode.db has no leading slash, so URL.String emits "file://C:%5CUsers%5C..." and
-// SQLite reads "C:" as the URI's authority -- every list and read then fails, and OpenCode sync
-// collects nothing. The path is made absolute, switched to forward slashes, and split into the host
-// and path a file: URI actually has.
-func sqliteFileURI(path string) string {
- abs := path
- if resolved, err := filepath.Abs(path); err == nil {
- abs = resolved
- }
- u := fileURL(filepath.ToSlash(abs))
- q := u.Query()
- q.Set("mode", "ro")
- q.Set("_pragma", "query_only(1)")
- u.RawQuery = q.Encode()
- return u.String()
-}
-
-// fileURL splits an already slash-separated path into the host and path of a file: URL.
-//
-// A UNC path (\\server\share\opencode.db, slashed to //server/share/opencode.db) names a host, and
-// is the one case where a file: URI has one. Everything else is a plain local path and gets the
-// leading slash that keeps a Windows drive letter inside the path instead of in the authority.
-func fileURL(slashed string) url.URL {
- if rest, ok := strings.CutPrefix(slashed, "//"); ok {
- host, remainder, _ := strings.Cut(rest, "/")
- if host != "" {
- return url.URL{Scheme: "file", Host: host, Path: "/" + remainder}
- }
- }
- if !strings.HasPrefix(slashed, "/") {
- slashed = "/" + slashed
- }
- return url.URL{Scheme: "file", Path: slashed}
+ return sql.Open("sqlite", sqliteuri.File(path, url.Values{"mode": {"ro"}, "_pragma": {"query_only(1)"}}))
}
func sqliteTableExists(db *sql.DB, table string) bool {
diff --git a/cli/beacon/internal/opencodesession/store_test.go b/cli/beacon/internal/opencodesession/store_test.go
index 6826af36..8af88532 100644
--- a/cli/beacon/internal/opencodesession/store_test.go
+++ b/cli/beacon/internal/opencodesession/store_test.go
@@ -3,10 +3,8 @@ package opencodesession
import (
"database/sql"
"encoding/json"
- "net/url"
"os"
"path/filepath"
- "strings"
"testing"
_ "modernc.org/sqlite"
@@ -108,44 +106,6 @@ func insertJSON(t *testing.T, db *sql.DB, query string, args ...interface{}) {
mustExec(t, db, query, args...)
}
-func TestFileURLKeepsAWindowsDriveLetterOutOfTheAuthority(t *testing.T) {
- // The inputs are already slash-separated, which is what filepath.ToSlash hands fileURL, so the
- // Windows shapes are exercised on every platform rather than only on the Windows runner.
- for _, tc := range []struct {
- name, slashed, want string
- }{
- {"windows drive", "C:/Users/me/AppData/Roaming/opencode/opencode.db", "file:///C:/Users/me/AppData/Roaming/opencode/opencode.db"},
- {"posix", "/home/me/.config/opencode/opencode.db", "file:///home/me/.config/opencode/opencode.db"},
- {"unc share", "//server/share/opencode/opencode.db", "file://server/share/opencode/opencode.db"},
- } {
- t.Run(tc.name, func(t *testing.T) {
- u := fileURL(tc.slashed)
- if got := u.String(); got != tc.want {
- t.Fatalf("fileURL(%q) = %q, want %q", tc.slashed, got, tc.want)
- }
- })
- }
-}
-
-func TestSQLiteFileURIAsksForReadOnly(t *testing.T) {
- uri := sqliteFileURI(filepath.Join(t.TempDir(), "opencode.db"))
- if !strings.HasPrefix(uri, "file:///") {
- // Without the file: prefix modernc.org/sqlite drops the query, and the driver's own flags
- // would open the store READWRITE|CREATE.
- t.Fatalf("uri = %q, want a file:// URI", uri)
- }
- parsed, err := url.Parse(uri)
- if err != nil {
- t.Fatal(err)
- }
- if parsed.Host != "" {
- t.Fatalf("uri host = %q, want none", parsed.Host)
- }
- if mode := parsed.Query().Get("mode"); mode != "ro" {
- t.Fatalf("mode = %q, want ro", mode)
- }
-}
-
func TestOpenSQLiteReadOnlyDoesNotCreateTheDatabase(t *testing.T) {
missing := filepath.Join(t.TempDir(), "opencode.db")
db, err := openSQLiteReadOnly(missing)
diff --git a/cli/beacon/internal/sqliteuri/sqliteuri.go b/cli/beacon/internal/sqliteuri/sqliteuri.go
new file mode 100644
index 00000000..b7768590
--- /dev/null
+++ b/cli/beacon/internal/sqliteuri/sqliteuri.go
@@ -0,0 +1,43 @@
+// Package sqliteuri builds the file: URIs Beacon hands modernc.org/sqlite.
+package sqliteuri
+
+import (
+ "net/url"
+ "path/filepath"
+ "strings"
+)
+
+// File renders an OS path as a file: URI carrying query as its parameters.
+//
+// The URI form is not optional: modernc.org/sqlite forwards query parameters such as mode=ro and
+// _pragma to SQLite only when the DSN starts with "file:". The path is made absolute,
+// slash-separated and percent-escaped, so a '#', '?' or '%' in a directory name stays part of the
+// filename instead of starting a fragment, a query or an escape that opens a different file.
+func File(path string, query url.Values) string {
+ abs := path
+ if resolved, err := filepath.Abs(path); err == nil {
+ abs = resolved
+ }
+ u := fileURL(filepath.ToSlash(abs))
+ u.RawQuery = query.Encode()
+ return u.String()
+}
+
+// fileURL splits an already slash-separated path into the host and path of a file: URL.
+//
+// Handing url.URL a raw Windows path does not produce a usable URI: C:/Users/me/x.db has no leading
+// slash, so SQLite would read "C:" as the URI's authority. A UNC path (\\server\share\x.db, slashed
+// to //server/share/x.db) names a host, and is the one case where a file: URI has one. Everything
+// else is a plain local path and gets the leading slash that keeps a drive letter inside the path.
+func fileURL(slashed string) url.URL {
+ if rest, ok := strings.CutPrefix(slashed, "//"); ok {
+ host, remainder, _ := strings.Cut(rest, "/")
+ if host != "" {
+ return url.URL{Scheme: "file", Host: host, Path: "/" + remainder}
+ }
+ }
+ if !strings.HasPrefix(slashed, "/") {
+ slashed = "/" + slashed
+ }
+ return url.URL{Scheme: "file", Path: slashed}
+}
diff --git a/cli/beacon/internal/sqliteuri/sqliteuri_test.go b/cli/beacon/internal/sqliteuri/sqliteuri_test.go
new file mode 100644
index 00000000..e2c6719a
--- /dev/null
+++ b/cli/beacon/internal/sqliteuri/sqliteuri_test.go
@@ -0,0 +1,23 @@
+package sqliteuri
+
+import "testing"
+
+func TestFileURLKeepsAWindowsDriveLetterOutOfTheAuthority(t *testing.T) {
+ // The inputs are already slash-separated, which is what filepath.ToSlash hands fileURL, so the
+ // Windows shapes are exercised on every platform rather than only on the Windows runner.
+ for _, tc := range []struct {
+ name, slashed, want string
+ }{
+ {"windows drive", "C:/Users/me/AppData/Roaming/opencode/opencode.db", "file:///C:/Users/me/AppData/Roaming/opencode/opencode.db"},
+ {"posix", "/home/me/.config/opencode/opencode.db", "file:///home/me/.config/opencode/opencode.db"},
+ {"unc share", "//server/share/opencode/opencode.db", "file://server/share/opencode/opencode.db"},
+ {"uri delimiters", "/home/me/C#/100%/a?b/x.db", "file:///home/me/C%23/100%25/a%3Fb/x.db"},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ u := fileURL(tc.slashed)
+ if got := u.String(); got != tc.want {
+ t.Fatalf("fileURL(%q) = %q, want %q", tc.slashed, got, tc.want)
+ }
+ })
+ }
+}