agentforge-memory-sqlite 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,17 @@
1
+ """AgentForge — SQLite memory + vector drivers.
2
+
3
+ Implements `MemoryStore` (claim audit log) and `VectorStore` (semantic
4
+ search) over SQLite via `aiosqlite`. Zero external services required.
5
+
6
+ Per ADR-0014 every code path is async — uses `aiosqlite`, never the
7
+ blocking stdlib `sqlite3`, in agent code paths.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from agentforge_memory_sqlite.memory import SqliteMemoryStore
13
+ from agentforge_memory_sqlite.vector import SqliteVectorStore
14
+
15
+ __version__ = "0.2.1"
16
+
17
+ __all__ = ["SqliteMemoryStore", "SqliteVectorStore", "__version__"]
@@ -0,0 +1,144 @@
1
+ """`SqliteMigrator` — SQLite-side implementation of the feat-024
2
+ :class:`agentforge_core.Migrator` Protocol.
3
+
4
+ Migrations ship at
5
+ ``agentforge_memory_sqlite/migrations/NNNN_<name>.sql``. The
6
+ migrator runs each pending migration via
7
+ :meth:`aiosqlite.Connection.executescript` so multi-statement files
8
+ work as written. Each migration is wrapped in an explicit
9
+ transaction so a partial failure rolls back cleanly.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import aiosqlite
19
+ from agentforge_core.contracts.migrator import (
20
+ Migration,
21
+ MigrationChecksumError,
22
+ MigrationStatus,
23
+ )
24
+ from agentforge_core.migrations import discover_migrations, render_migration_up
25
+
26
+
27
+ def _default_migrations_path() -> Path:
28
+ return Path(__file__).parent / "migrations"
29
+
30
+
31
+ class SqliteMigrator:
32
+ """SQLite implementation of :class:`agentforge_core.Migrator`."""
33
+
34
+ def __init__(
35
+ self,
36
+ connection: aiosqlite.Connection,
37
+ *,
38
+ variables: dict[str, str] | None = None,
39
+ migrations_path: Path | None = None,
40
+ ) -> None:
41
+ self._db = connection
42
+ self._path = migrations_path or _default_migrations_path()
43
+ self._variables = variables
44
+ self._migrations: list[Migration] = discover_migrations(self._path, suffix="sql")
45
+
46
+ @property
47
+ def migrations(self) -> list[Migration]:
48
+ return list(self._migrations)
49
+
50
+ async def current_version(self) -> str | None:
51
+ if not await self._tracking_table_exists():
52
+ return None
53
+ async with self._db.execute("SELECT MAX(id) AS latest FROM agentforge_migrations") as cur:
54
+ row = await cur.fetchone()
55
+ if row is None or row["latest"] is None:
56
+ return None
57
+ return str(row["latest"])
58
+
59
+ async def status(self) -> list[MigrationStatus]:
60
+ applied = await self._fetch_applied()
61
+ out: list[MigrationStatus] = []
62
+ for migration in self._migrations:
63
+ record = applied.get(migration.id)
64
+ if record is None:
65
+ out.append(
66
+ MigrationStatus(
67
+ migration=migration,
68
+ applied=False,
69
+ applied_at=None,
70
+ checksum_match=False,
71
+ )
72
+ )
73
+ continue
74
+ out.append(
75
+ MigrationStatus(
76
+ migration=migration,
77
+ applied=True,
78
+ applied_at=_parse_iso(record["applied_at"]),
79
+ checksum_match=record["checksum"] == migration.checksum,
80
+ )
81
+ )
82
+ return out
83
+
84
+ async def apply_pending(self) -> list[Migration]:
85
+ applied = await self._fetch_applied()
86
+
87
+ for migration in self._migrations:
88
+ record = applied.get(migration.id)
89
+ if record is not None and record["checksum"] != migration.checksum:
90
+ msg = (
91
+ f"SQLite migration {migration.id}_{migration.name} "
92
+ f"checksum drift: recorded {record['checksum']!r} but "
93
+ f"file is now {migration.checksum!r}."
94
+ )
95
+ raise MigrationChecksumError(msg)
96
+
97
+ new_applied: list[Migration] = []
98
+ for migration in self._migrations:
99
+ if migration.id in applied:
100
+ continue
101
+ # `executescript` handles multi-statement migrations.
102
+ # It implicitly commits, so we explicitly BEGIN before
103
+ # and rely on the script's final state for the row write.
104
+ rendered = render_migration_up(migration.up, self._variables)
105
+ await self._db.executescript(rendered)
106
+ await self._db.execute(
107
+ "INSERT INTO agentforge_migrations(id, name, checksum) VALUES (?, ?, ?)",
108
+ (migration.id, migration.name, migration.checksum),
109
+ )
110
+ await self._db.commit()
111
+ new_applied.append(migration)
112
+ return new_applied
113
+
114
+ async def _tracking_table_exists(self) -> bool:
115
+ async with self._db.execute(
116
+ "SELECT name FROM sqlite_master WHERE type='table' AND name='agentforge_migrations'"
117
+ ) as cur:
118
+ row = await cur.fetchone()
119
+ return row is not None
120
+
121
+ async def _fetch_applied(self) -> dict[str, dict[str, Any]]:
122
+ if not await self._tracking_table_exists():
123
+ return {}
124
+ async with self._db.execute(
125
+ "SELECT id, name, checksum, applied_at FROM agentforge_migrations"
126
+ ) as cur:
127
+ rows = await cur.fetchall()
128
+ return {
129
+ str(row["id"]): {
130
+ "name": row["name"],
131
+ "checksum": row["checksum"],
132
+ "applied_at": row["applied_at"],
133
+ }
134
+ for row in rows
135
+ }
136
+
137
+
138
+ def _parse_iso(value: Any) -> datetime | None:
139
+ if not value:
140
+ return None
141
+ try:
142
+ return datetime.fromisoformat(str(value))
143
+ except ValueError:
144
+ return None
@@ -0,0 +1,244 @@
1
+ """`SqliteMemoryStore` — `MemoryStore` over SQLite via aiosqlite.
2
+
3
+ Single-table schema: every claim is stored as one row keyed by `id`
4
+ with project / agent / category / run_id / supersedes columns and
5
+ the JSON payload as a TEXT blob. Queries hit composite indices on
6
+ the common filter combinations.
7
+
8
+ Schema is created on first connect via `CREATE TABLE IF NOT EXISTS`.
9
+ No migrations in v0.1 — the table shape is fixed.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import json
15
+ from collections.abc import AsyncIterator
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+ from types import TracebackType
19
+ from typing import Any
20
+
21
+ import aiosqlite
22
+ from agentforge_core.contracts.memory import MemoryStore
23
+ from agentforge_core.production.exceptions import ModuleError
24
+ from agentforge_core.values.claim import Claim
25
+
26
+ from agentforge_memory_sqlite._migrator import SqliteMigrator
27
+
28
+
29
+ class SqliteMemoryStore(MemoryStore):
30
+ """Persistent `MemoryStore` backed by a single SQLite file.
31
+
32
+ Use `from_path(path)` for ergonomic construction; the bare
33
+ constructor accepts an already-opened `aiosqlite.Connection` for
34
+ callers who manage the connection themselves.
35
+ """
36
+
37
+ def __init__(self, *, connection: aiosqlite.Connection) -> None:
38
+ self._db = connection
39
+
40
+ # ------------------------------------------------------------------
41
+ # Construction / lifecycle
42
+ # ------------------------------------------------------------------
43
+
44
+ @classmethod
45
+ async def from_path(cls, path: str | Path) -> SqliteMemoryStore:
46
+ """Open or create a SQLite database at `path` and return a store.
47
+
48
+ `path` may be `":memory:"` for an ephemeral in-process database,
49
+ or a filesystem path (the parent directory must exist).
50
+ """
51
+ connection = await aiosqlite.connect(str(path))
52
+ connection.row_factory = aiosqlite.Row
53
+ # feat-024: schema bootstrap is now versioned via the
54
+ # migration framework. Idempotent: re-opening an existing
55
+ # database is a no-op after migrations are applied.
56
+ await SqliteMigrator(connection).apply_pending()
57
+ return cls(connection=connection)
58
+
59
+ def migrator(self) -> SqliteMigrator:
60
+ """Return a `SqliteMigrator` configured against the
61
+ package's bundled migrations directory (feat-024)."""
62
+ return SqliteMigrator(self._db)
63
+
64
+ async def init_schema(self) -> None:
65
+ """Apply every bundled migration (idempotent). Opt-in.
66
+
67
+ Delegates to the feat-024 migration framework. `from_path`
68
+ already calls this implicitly; standalone callers (or
69
+ tests that construct the store from a raw connection) can
70
+ invoke it directly.
71
+ """
72
+ await self.migrator().apply_pending()
73
+
74
+ async def __aenter__(self) -> SqliteMemoryStore:
75
+ return self
76
+
77
+ async def __aexit__(
78
+ self,
79
+ exc_type: type[BaseException] | None,
80
+ exc: BaseException | None,
81
+ tb: TracebackType | None,
82
+ ) -> None:
83
+ await self.close()
84
+
85
+ async def close(self) -> None:
86
+ await self._db.close()
87
+
88
+ # ------------------------------------------------------------------
89
+ # MemoryStore contract
90
+ # ------------------------------------------------------------------
91
+
92
+ async def put(self, claim: Claim) -> str:
93
+ await self._db.execute(
94
+ """INSERT OR REPLACE INTO claims
95
+ (id, project, agent, run_id, category, payload, supersedes, created_at)
96
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)""",
97
+ (
98
+ claim.id,
99
+ claim.project,
100
+ claim.agent,
101
+ claim.run_id,
102
+ claim.category,
103
+ json.dumps(claim.payload),
104
+ claim.supersedes,
105
+ claim.created_at.isoformat(),
106
+ ),
107
+ )
108
+ await self._db.commit()
109
+ return claim.id
110
+
111
+ async def get(self, claim_id: str) -> Claim | None:
112
+ async with self._db.execute(
113
+ "SELECT * FROM claims WHERE id = ?",
114
+ (claim_id,),
115
+ ) as cur:
116
+ row = await cur.fetchone()
117
+ if row is None:
118
+ return None
119
+ return _row_to_claim(row)
120
+
121
+ async def query(
122
+ self,
123
+ *,
124
+ project: str | None = None,
125
+ agent: str | None = None,
126
+ category: str | None = None,
127
+ run_id: str | None = None,
128
+ limit: int = 100,
129
+ ) -> list[Claim]:
130
+ sql, params = _build_filter_sql(project, agent, category, run_id, limit)
131
+ async with self._db.execute(sql, params) as cur:
132
+ rows = await cur.fetchall()
133
+ return [_row_to_claim(row) for row in rows]
134
+
135
+ async def supersede(self, old_id: str, new_claim: Claim) -> str:
136
+ existing = await self.get(old_id)
137
+ if existing is None:
138
+ raise ModuleError(f"Cannot supersede unknown claim id: {old_id!r}")
139
+ if new_claim.supersedes is None:
140
+ new_claim = new_claim.model_copy(update={"supersedes": old_id})
141
+ elif new_claim.supersedes != old_id:
142
+ raise ModuleError(
143
+ f"new_claim.supersedes={new_claim.supersedes!r} does not match old_id={old_id!r}"
144
+ )
145
+ return await self.put(new_claim)
146
+
147
+ def stream(
148
+ self,
149
+ *,
150
+ project: str | None = None,
151
+ agent: str | None = None,
152
+ category: str | None = None,
153
+ run_id: str | None = None,
154
+ ) -> AsyncIterator[Claim]:
155
+ sql, params = _build_filter_sql(project, agent, category, run_id, limit=None)
156
+
157
+ async def _agen() -> AsyncIterator[Claim]:
158
+ async with self._db.execute(sql, params) as cur:
159
+ async for row in cur:
160
+ yield _row_to_claim(row)
161
+
162
+ return _agen()
163
+
164
+ async def delete(
165
+ self,
166
+ *,
167
+ run_id: str | None = None,
168
+ older_than: datetime | None = None,
169
+ category: str | None = None,
170
+ ) -> int:
171
+ if run_id is None and older_than is None and category is None:
172
+ raise ModuleError(
173
+ "delete() requires at least one filter; refusing to wipe every claim."
174
+ )
175
+ where: list[str] = []
176
+ params: list[Any] = []
177
+ if run_id is not None:
178
+ where.append("run_id = ?")
179
+ params.append(run_id)
180
+ if category is not None:
181
+ where.append("category = ?")
182
+ params.append(category)
183
+ if older_than is not None:
184
+ where.append("created_at < ?")
185
+ params.append(older_than.isoformat())
186
+ sql = "DELETE FROM claims WHERE " + " AND ".join(where) # noqa: S608 # nosec B608
187
+ cur = await self._db.execute(sql, tuple(params))
188
+ await self._db.commit()
189
+ return cur.rowcount or 0
190
+
191
+
192
+ # ----------------------------------------------------------------------
193
+ # Helpers
194
+ # ----------------------------------------------------------------------
195
+
196
+
197
+ def _row_to_claim(row: Any) -> Claim:
198
+ """Convert an `aiosqlite.Row` into a `Claim`."""
199
+ return Claim(
200
+ id=row["id"],
201
+ project=row["project"],
202
+ agent=row["agent"],
203
+ run_id=row["run_id"],
204
+ category=row["category"],
205
+ payload=json.loads(row["payload"]),
206
+ supersedes=row["supersedes"],
207
+ created_at=datetime.fromisoformat(row["created_at"]),
208
+ )
209
+
210
+
211
+ def _build_filter_sql(
212
+ project: str | None,
213
+ agent: str | None,
214
+ category: str | None,
215
+ run_id: str | None,
216
+ limit: int | None,
217
+ ) -> tuple[str, tuple[Any, ...]]:
218
+ """Compose a SELECT with conjunctive filters and an optional LIMIT."""
219
+ where: list[str] = []
220
+ params: list[Any] = []
221
+ if project is not None:
222
+ where.append("project = ?")
223
+ params.append(project)
224
+ if agent is not None:
225
+ where.append("agent = ?")
226
+ params.append(agent)
227
+ if category is not None:
228
+ where.append("category = ?")
229
+ params.append(category)
230
+ if run_id is not None:
231
+ where.append("run_id = ?")
232
+ params.append(run_id)
233
+
234
+ sql = "SELECT * FROM claims"
235
+ if where:
236
+ sql += " WHERE " + " AND ".join(where)
237
+ sql += " ORDER BY created_at"
238
+ if limit is not None:
239
+ sql += " LIMIT ?"
240
+ params.append(limit)
241
+ return sql, tuple(params)
242
+
243
+
244
+ __all__ = ["SqliteMemoryStore"]
@@ -0,0 +1,6 @@
1
+ CREATE TABLE IF NOT EXISTS agentforge_migrations (
2
+ id TEXT PRIMARY KEY,
3
+ name TEXT NOT NULL,
4
+ checksum TEXT NOT NULL,
5
+ applied_at TEXT NOT NULL DEFAULT (datetime('now'))
6
+ );
@@ -0,0 +1,27 @@
1
+ CREATE TABLE IF NOT EXISTS claims (
2
+ id TEXT PRIMARY KEY,
3
+ project TEXT NOT NULL,
4
+ agent TEXT NOT NULL,
5
+ run_id TEXT NOT NULL,
6
+ category TEXT NOT NULL,
7
+ payload TEXT NOT NULL,
8
+ supersedes TEXT,
9
+ created_at TEXT NOT NULL
10
+ );
11
+ CREATE INDEX IF NOT EXISTS idx_claims_project_agent
12
+ ON claims(project, agent);
13
+ CREATE INDEX IF NOT EXISTS idx_claims_run_id
14
+ ON claims(run_id);
15
+ CREATE INDEX IF NOT EXISTS idx_claims_category
16
+ ON claims(category);
17
+
18
+ CREATE TABLE IF NOT EXISTS vectors (
19
+ id TEXT PRIMARY KEY,
20
+ vector BLOB NOT NULL,
21
+ text TEXT NOT NULL,
22
+ metadata TEXT NOT NULL
23
+ );
24
+ CREATE TABLE IF NOT EXISTS vector_meta (
25
+ key TEXT PRIMARY KEY,
26
+ value TEXT NOT NULL
27
+ );
@@ -0,0 +1,18 @@
1
+ CREATE VIRTUAL TABLE IF NOT EXISTS vectors_fts USING fts5(
2
+ text,
3
+ content='vectors',
4
+ content_rowid='rowid',
5
+ tokenize='unicode61'
6
+ );
7
+ CREATE TRIGGER IF NOT EXISTS vectors_ai AFTER INSERT ON vectors BEGIN
8
+ INSERT INTO vectors_fts(rowid, text) VALUES (new.rowid, new.text);
9
+ END;
10
+ CREATE TRIGGER IF NOT EXISTS vectors_ad AFTER DELETE ON vectors BEGIN
11
+ INSERT INTO vectors_fts(vectors_fts, rowid, text)
12
+ VALUES ('delete', old.rowid, old.text);
13
+ END;
14
+ CREATE TRIGGER IF NOT EXISTS vectors_au AFTER UPDATE ON vectors BEGIN
15
+ INSERT INTO vectors_fts(vectors_fts, rowid, text)
16
+ VALUES ('delete', old.rowid, old.text);
17
+ INSERT INTO vectors_fts(rowid, text) VALUES (new.rowid, new.text);
18
+ END;
File without changes
@@ -0,0 +1,257 @@
1
+ """`SqliteVectorStore` — `VectorStore` over SQLite via aiosqlite.
2
+
3
+ Vectors are stored as fixed-width BLOBs (8 bytes per float64, packed
4
+ big-endian). On search the entire table is loaded and cosine
5
+ similarity is computed in Python — O(N) per query. Fine for
6
+ ~10k vectors; v0.2 will add an opt-in `sqlite-vec` extension path.
7
+
8
+ Schema is created on first connect via `CREATE TABLE IF NOT EXISTS`
9
+ and `dimensions` are pinned per database. Re-opening with a
10
+ different dimensions value raises at construction.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import math
17
+ import struct
18
+ from pathlib import Path
19
+ from types import TracebackType
20
+ from typing import Any
21
+
22
+ import aiosqlite
23
+ from agentforge_core.contracts.vector_store import VectorStore
24
+ from agentforge_core.values.vector import VectorItem, VectorMatch
25
+
26
+ from agentforge_memory_sqlite._migrator import SqliteMigrator
27
+
28
+
29
+ class SqliteVectorStore(VectorStore):
30
+ """Persistent `VectorStore` backed by a SQLite file.
31
+
32
+ Use `from_path(path, dimensions)` for ergonomic construction. The
33
+ bare constructor accepts an opened connection plus dimensions for
34
+ callers who manage their own connection.
35
+ """
36
+
37
+ def __init__(self, *, connection: aiosqlite.Connection, dimensions: int) -> None:
38
+ if dimensions < 1:
39
+ raise ValueError(f"dimensions must be >= 1, got {dimensions}")
40
+ self._db = connection
41
+ self._dim = dimensions
42
+
43
+ @classmethod
44
+ async def from_path(cls, path: str | Path, *, dimensions: int) -> SqliteVectorStore:
45
+ """Open or create a vector store at `path` with `dimensions`.
46
+
47
+ If the file already contains a vector index with a different
48
+ dimension, raises `ValueError` — dimensions are pinned per
49
+ database to prevent silent corruption.
50
+ """
51
+ if dimensions < 1:
52
+ raise ValueError(f"dimensions must be >= 1, got {dimensions}")
53
+ connection = await aiosqlite.connect(str(path))
54
+ connection.row_factory = aiosqlite.Row
55
+ # feat-024: schema bootstrap via the migration framework.
56
+ await SqliteMigrator(connection).apply_pending()
57
+ # Pin dimensions on first use; verify on re-open.
58
+ async with connection.execute(
59
+ "SELECT value FROM vector_meta WHERE key = 'dimensions'"
60
+ ) as cur:
61
+ existing = await cur.fetchone()
62
+ if existing is None:
63
+ await connection.execute(
64
+ "INSERT INTO vector_meta(key, value) VALUES ('dimensions', ?)",
65
+ (str(dimensions),),
66
+ )
67
+ await connection.commit()
68
+ else:
69
+ stored = int(existing["value"])
70
+ if stored != dimensions:
71
+ await connection.close()
72
+ raise ValueError(
73
+ f"vector store at {path!s} has dimensions={stored} "
74
+ f"but caller asked for dimensions={dimensions}"
75
+ )
76
+ return cls(connection=connection, dimensions=dimensions)
77
+
78
+ async def __aenter__(self) -> SqliteVectorStore:
79
+ return self
80
+
81
+ async def __aexit__(
82
+ self,
83
+ exc_type: type[BaseException] | None,
84
+ exc: BaseException | None,
85
+ tb: TracebackType | None,
86
+ ) -> None:
87
+ await self.close()
88
+
89
+ def dimensions(self) -> int:
90
+ return self._dim
91
+
92
+ def migrator(self) -> SqliteMigrator:
93
+ """Return a `SqliteMigrator` configured against the
94
+ package's bundled migrations directory (feat-024)."""
95
+ return SqliteMigrator(self._db)
96
+
97
+ async def upsert(self, items: list[VectorItem]) -> None:
98
+ rows: list[tuple[str, bytes, str, str]] = []
99
+ for item in items:
100
+ if len(item.vector) != self._dim:
101
+ raise ValueError(
102
+ f"vector for id={item.id!r} has length {len(item.vector)} "
103
+ f"but store dimensions={self._dim}"
104
+ )
105
+ normalised = _l2_normalise(item.vector)
106
+ rows.append(
107
+ (
108
+ item.id,
109
+ _pack_vector(normalised),
110
+ item.text,
111
+ json.dumps(item.metadata),
112
+ )
113
+ )
114
+ await self._db.executemany(
115
+ "INSERT OR REPLACE INTO vectors(id, vector, text, metadata) VALUES (?, ?, ?, ?)",
116
+ rows,
117
+ )
118
+ await self._db.commit()
119
+
120
+ async def search(
121
+ self,
122
+ query_vector: tuple[float, ...],
123
+ *,
124
+ limit: int = 5,
125
+ filter_metadata: dict[str, Any] | None = None,
126
+ ) -> list[VectorMatch]:
127
+ if limit < 1:
128
+ raise ValueError(f"limit must be >= 1, got {limit}")
129
+ if len(query_vector) != self._dim:
130
+ raise ValueError(
131
+ f"query vector has length {len(query_vector)} but store dimensions={self._dim}"
132
+ )
133
+
134
+ query = _l2_normalise(query_vector)
135
+ scored: list[tuple[float, str, str, dict[str, Any]]] = []
136
+ async with self._db.execute("SELECT * FROM vectors") as cur:
137
+ async for row in cur:
138
+ metadata = json.loads(row["metadata"])
139
+ if filter_metadata is not None and not _matches_filter(metadata, filter_metadata):
140
+ continue
141
+ vec = _unpack_vector(row["vector"], self._dim)
142
+ similarity = sum(a * b for a, b in zip(query, vec, strict=True))
143
+ clamped = max(0.0, min(1.0, similarity))
144
+ scored.append((clamped, row["id"], row["text"], metadata))
145
+
146
+ scored.sort(key=lambda r: r[0], reverse=True)
147
+ return [
148
+ VectorMatch(id=item_id, text=text, metadata=meta, score=score)
149
+ for score, item_id, text, meta in scored[:limit]
150
+ ]
151
+
152
+ async def lexical_search(
153
+ self,
154
+ query: str,
155
+ *,
156
+ limit: int = 5,
157
+ filter_metadata: dict[str, Any] | None = None,
158
+ ) -> list[VectorMatch]:
159
+ if limit < 1:
160
+ raise ValueError(f"limit must be >= 1, got {limit}")
161
+ escaped = _escape_fts_query(query)
162
+ if not escaped:
163
+ return []
164
+ # Over-fetch when metadata filter is set so post-filter has
165
+ # room to work; the in-memory store uses the same pattern.
166
+ over_fetch = limit if filter_metadata is None else limit * 4
167
+ async with self._db.execute(
168
+ "SELECT v.id, v.text, v.metadata, "
169
+ " -bm25(vectors_fts) AS raw "
170
+ " FROM vectors_fts "
171
+ " JOIN vectors v ON v.rowid = vectors_fts.rowid "
172
+ " WHERE vectors_fts MATCH ? "
173
+ " ORDER BY raw DESC "
174
+ " LIMIT ?",
175
+ (escaped, max(over_fetch, 1)),
176
+ ) as cur:
177
+ rows = list(await cur.fetchall())
178
+ if not rows:
179
+ return []
180
+
181
+ top_raw = float(rows[0]["raw"])
182
+ matches: list[VectorMatch] = []
183
+ for row in rows:
184
+ metadata = json.loads(row["metadata"])
185
+ if filter_metadata is not None and not _matches_filter(metadata, filter_metadata):
186
+ continue
187
+ raw = float(row["raw"])
188
+ score = raw / top_raw if top_raw > 0 else 0.0
189
+ matches.append(
190
+ VectorMatch(
191
+ id=str(row["id"]),
192
+ text=str(row["text"]),
193
+ metadata=metadata,
194
+ score=score,
195
+ )
196
+ )
197
+ if len(matches) >= limit:
198
+ break
199
+ return matches
200
+
201
+ def capabilities(self) -> set[str]:
202
+ """SQLite ships native FTS5; hybrid_search is always available
203
+ once the schema is set up in `from_path()`."""
204
+ return {"hybrid_search"}
205
+
206
+ async def delete(self, ids: list[str]) -> int:
207
+ if not ids:
208
+ return 0
209
+ # `placeholders` is a string of `?` characters, never user
210
+ # input — `tuple(ids)` is the parametrised payload.
211
+ placeholders = ",".join("?" for _ in ids)
212
+ sql = f"DELETE FROM vectors WHERE id IN ({placeholders})" # noqa: S608 # nosec B608
213
+ async with self._db.execute(sql, tuple(ids)) as cur:
214
+ removed = cur.rowcount
215
+ await self._db.commit()
216
+ # rowcount is -1 when undefined; coerce to 0 for safety.
217
+ return max(0, removed)
218
+
219
+ async def close(self) -> None:
220
+ await self._db.close()
221
+
222
+
223
+ # ----------------------------------------------------------------------
224
+ # Helpers
225
+ # ----------------------------------------------------------------------
226
+
227
+
228
+ def _pack_vector(vector: tuple[float, ...]) -> bytes:
229
+ """Pack a float tuple into a fixed-width float64 BLOB."""
230
+ return struct.pack(f"<{len(vector)}d", *vector)
231
+
232
+
233
+ def _unpack_vector(blob: bytes, dim: int) -> tuple[float, ...]:
234
+ """Reverse of `_pack_vector`."""
235
+ return struct.unpack(f"<{dim}d", blob)
236
+
237
+
238
+ def _l2_normalise(vector: tuple[float, ...]) -> tuple[float, ...]:
239
+ norm = math.sqrt(sum(x * x for x in vector))
240
+ if norm == 0.0:
241
+ return vector
242
+ return tuple(x / norm for x in vector)
243
+
244
+
245
+ def _matches_filter(metadata: dict[str, Any], filter_md: dict[str, Any]) -> bool:
246
+ return all(metadata.get(k) == v for k, v in filter_md.items())
247
+
248
+
249
+ def _escape_fts_query(query: str) -> str:
250
+ """Wrap every term in double-quotes so user input that contains
251
+ FTS5 special syntax (``AND`` / ``OR`` / ``*`` / parens / colons)
252
+ is treated literally. Empty input yields an empty string."""
253
+ terms = ['"' + term.replace('"', '""') + '"' for term in query.split() if term]
254
+ return " ".join(terms)
255
+
256
+
257
+ __all__ = ["SqliteVectorStore"]
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: agentforge-memory-sqlite
3
+ Version: 0.2.1
4
+ Summary: SQLite-backed MemoryStore and VectorStore for AgentForge
5
+ Project-URL: Homepage, https://github.com/Scaffoldic/agentforge-py
6
+ Project-URL: Repository, https://github.com/Scaffoldic/agentforge-py
7
+ Project-URL: Documentation, https://github.com/Scaffoldic/agentforge-py
8
+ Project-URL: Changelog, https://github.com/Scaffoldic/agentforge-py/blob/main/CHANGELOG.md
9
+ Project-URL: Issues, https://github.com/Scaffoldic/agentforge-py/issues
10
+ Author: The AgentForge Authors
11
+ License-Expression: Apache-2.0
12
+ License-File: LICENSE
13
+ Keywords: agent,ai,memory,rag,sqlite,vector
14
+ Classifier: Development Status :: 2 - Pre-Alpha
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Database
20
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.13
23
+ Requires-Dist: agentforge-core~=0.2.1
24
+ Requires-Dist: aiosqlite>=0.20
25
+ Description-Content-Type: text/markdown
26
+
27
+ # agentforge-memory-sqlite
28
+
29
+ SQLite-backed `MemoryStore` and `VectorStore` for [AgentForge](https://github.com/Scaffoldic/agentforge-py).
30
+
31
+ Zero external services required — the database lives in a single file
32
+ (or `:memory:` for tests). Suitable for development, single-host
33
+ deployments, and small-to-medium RAG corpora (~10k vectors).
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ uv add agentforge-memory-sqlite
39
+ ```
40
+
41
+ ## Usage
42
+
43
+ ```python
44
+ from agentforge_memory_sqlite import SqliteMemoryStore, SqliteVectorStore
45
+
46
+ # Claim audit log
47
+ async with SqliteMemoryStore.from_path("agent.db") as memory:
48
+ await memory.put(claim)
49
+
50
+ # Semantic search
51
+ async with SqliteVectorStore.from_path("agent.db", dimensions=1024) as store:
52
+ await store.upsert(items)
53
+ matches = await store.search(query_vector, limit=5)
54
+ ```
55
+
56
+ Both classes pass `agentforge_core.testing.run_memory_conformance` /
57
+ `run_vector_conformance` so they're drop-in replacements for the
58
+ in-memory defaults.
59
+
60
+ ## Performance
61
+
62
+ `SqliteVectorStore` does brute-force cosine search in Python: O(N) per
63
+ query. Fine for ~10k vectors; sluggish past that. v0.2 will add an
64
+ opt-in `sqlite-vec` extension path declared via the `"native_ann"`
65
+ capability flag.
@@ -0,0 +1,13 @@
1
+ agentforge_memory_sqlite/__init__.py,sha256=4JIJYH0d-n1cmqRG04dcORbrkCGIvoI_8tmzxwPEwQ0,568
2
+ agentforge_memory_sqlite/_migrator.py,sha256=rRPCPnFFmzVRJfthq3glh3x6kWAD4wk5R96Q2PqF5Us,5076
3
+ agentforge_memory_sqlite/memory.py,sha256=30d_Q2PU4tM2NVjAlD9-BVWbWdu5P6-oAzGA_khcfh0,8262
4
+ agentforge_memory_sqlite/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ agentforge_memory_sqlite/vector.py,sha256=v0GZmIBYgKMobizausF91TieoLJ60ohA3CM2l6ei6AE,9532
6
+ agentforge_memory_sqlite/migrations/0000_migrations_table.sql,sha256=Hj8lxWPizGOTsAQloRrmKoDHyCkechdHfOcU3FZlDS0,206
7
+ agentforge_memory_sqlite/migrations/0001_initial.sql,sha256=0GRCe90lRCkgomALxUpqbUsckpAPJU8vGacknMgvhQI,778
8
+ agentforge_memory_sqlite/migrations/0002_fts5.sql,sha256=b27HLnhAoDfdQvxVOoc-fvroqAdGbx-RoavaVK0nJTM,718
9
+ agentforge_memory_sqlite-0.2.1.dist-info/METADATA,sha256=6UC-lz8XeQTHeFjFgbHGfoG1iQreS29cP7fbNbyb3zw,2330
10
+ agentforge_memory_sqlite-0.2.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
11
+ agentforge_memory_sqlite-0.2.1.dist-info/entry_points.txt,sha256=_KNwjwkvm11_3J9_W0X2_d-VTnz17LEMBVR8rKds9JM,166
12
+ agentforge_memory_sqlite-0.2.1.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
13
+ agentforge_memory_sqlite-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,5 @@
1
+ [agentforge.memory]
2
+ sqlite = agentforge_memory_sqlite.memory:SqliteMemoryStore
3
+
4
+ [agentforge.vector_stores]
5
+ sqlite = agentforge_memory_sqlite.vector:SqliteVectorStore
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.