pantheon-opencode 1.6.2-beta.3 → 1.6.2-beta.5
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.
- package/CHANGELOG.md +42 -0
- package/README.md +209 -1
- package/bin/pantheon-init.mjs +22 -0
- package/package.json +9 -3
- package/plugin.json +1 -1
- package/pyproject.toml +1 -1
- package/scripts/decision-router-budget.mjs +781 -0
- package/scripts/decision-router-v2-budget.mjs +218 -0
- package/scripts/decision-router-v2-egress.mjs +272 -0
- package/scripts/decision-router.mjs +519 -0
- package/scripts/docs-check-changelog.mjs +5 -3
- package/scripts/install/decision-layer-preview.mjs +376 -0
- package/scripts/install/decision-router-config.mjs +579 -0
- package/scripts/install/interactive.mjs +76 -5
- package/scripts/install/opencode.mjs +12 -0
- package/scripts/install/state.mjs +5 -0
- package/scripts/install/strings.mjs +4 -0
- package/scripts/mcp_resources.py +11 -9
- package/scripts/release-notes.mjs +30 -7
- package/scripts/versioning.mjs +41 -5
- package/src/agents/zeus.md +12 -0
- package/src/mcp/eval_store.py +11 -4
- package/src/mcp/mcp_resources.py +11 -9
- package/src/mcp/memory_mcp.py +293 -150
- package/src/pantheon/local-decision-agents.ts +170 -0
- package/src/pantheon/local-decision-budget.ts +1043 -0
- package/src/pantheon/local-decision-egress-gate.ts +264 -0
- package/src/pantheon/local-decision-prompt.ts +268 -0
- package/src/pantheon/local-decision-provider-matrix.ts +92 -0
- package/src/pantheon/local-decision-provider-protocol.ts +335 -0
- package/src/pantheon/local-decision-provider.internal.ts +260 -0
- package/src/pantheon/local-decision-router.ts +225 -0
- package/src/pantheon/local-decision-skills.ts +281 -0
- package/src/pantheon/local-decision-tool.ts +160 -0
- package/src/pantheon/local-decision-turn.ts +338 -0
- package/src/pantheon/local-decision-usage-evidence.internal.ts +207 -0
- package/src/pantheon/local-orchestration.ts +322 -0
- package/src/pantheon/pantheon-decision-catalog.ts +101 -0
- package/src/pantheon/v2-decision-budget.ts +456 -0
- package/src/pantheon/v2-decision-contracts.ts +300 -0
- package/src/pantheon/v2-decision-egress.ts +203 -0
- package/src/pantheon/v2-decision-events.ts +180 -0
- package/src/pantheon/v2-decision-heuristic.ts +121 -0
- package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
- package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
- package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
- package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
- package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
- package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
- package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
- package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
- package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
- package/src/pantheon/v2-decision-points/p8-guardrail.ts +366 -0
- package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
- package/src/pantheon/v2-decision-points.ts +242 -0
- package/src/pantheon/v2-decision-policy.ts +166 -0
- package/src/pantheon/v2-decision-premises.ts +146 -0
- package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
- package/src/pantheon/v2-decision-rank.ts +91 -0
- package/src/pantheon/v2-decision-registry.ts +391 -0
- package/src/pantheon/v2-decision-resource-ids.ts +127 -0
- package/src/pantheon/v2-decision-shadow.ts +123 -0
- package/src/pantheon/v2-decision-telemetry.ts +214 -0
- package/src/pantheon/v2-decision-verify.ts +51 -0
- package/src/pantheon/v2-tools.ts +35 -15
- package/src/plugin-v2.ts +357 -22
- package/src/plugin.ts +4 -0
- package/src/plugins/tui/dist/tui-v2.js +3 -3
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +2 -2
- package/src/plugins/tui/package.json +1 -1
package/src/mcp/memory_mcp.py
CHANGED
|
@@ -34,12 +34,13 @@ Usage:
|
|
|
34
34
|
from __future__ import annotations
|
|
35
35
|
|
|
36
36
|
import contextlib
|
|
37
|
-
import functools
|
|
38
37
|
import json
|
|
39
38
|
import logging
|
|
40
39
|
import os
|
|
41
40
|
import sqlite3
|
|
41
|
+
import threading
|
|
42
42
|
import time
|
|
43
|
+
from collections.abc import Iterator
|
|
43
44
|
from datetime import UTC, datetime
|
|
44
45
|
from pathlib import Path
|
|
45
46
|
from typing import Annotated, Any, Literal
|
|
@@ -76,8 +77,13 @@ def _set_memory_dir(path: str | Path) -> None:
|
|
|
76
77
|
|
|
77
78
|
|
|
78
79
|
def _reset_test_state() -> None:
|
|
79
|
-
"""
|
|
80
|
-
|
|
80
|
+
"""Close the cached connection and drop it for test isolation."""
|
|
81
|
+
global _DB_CONN
|
|
82
|
+
with _DB_LOCK:
|
|
83
|
+
previous, _DB_CONN = _DB_CONN, None
|
|
84
|
+
if previous is not None:
|
|
85
|
+
with contextlib.suppress(sqlite3.Error):
|
|
86
|
+
previous.close()
|
|
81
87
|
|
|
82
88
|
|
|
83
89
|
# ── Store Limits ─────────────────────────────────────────────────────────────
|
|
@@ -145,6 +151,15 @@ mcp = FastMCP(
|
|
|
145
151
|
)
|
|
146
152
|
_LOGGER = logging.getLogger(__name__)
|
|
147
153
|
|
|
154
|
+
# Returned when the store cannot be opened. A write that did not reach SQLite
|
|
155
|
+
# must never be dressed up as ``status: stored``: the memory policy says an
|
|
156
|
+
# entry is durable only after ``memory_store`` reports success.
|
|
157
|
+
STORE_UNAVAILABLE_ERROR = (
|
|
158
|
+
"Failed to store memory: the memory database could not be opened, so "
|
|
159
|
+
"nothing was written. Check its configured location and permissions, then "
|
|
160
|
+
"retry."
|
|
161
|
+
)
|
|
162
|
+
|
|
148
163
|
# TypedDict comes from typing_extensions, not typing: pydantic only builds a
|
|
149
164
|
# schema for typing.TypedDict on Python >= 3.12, and FastMCP builds the output
|
|
150
165
|
# schema during @mcp.tool registration (see _SUPPORTS_TYPEDDICT in pydantic).
|
|
@@ -201,26 +216,65 @@ def _ensure_entry_lifecycle_schema(conn: sqlite3.Connection) -> bool:
|
|
|
201
216
|
return added
|
|
202
217
|
|
|
203
218
|
|
|
204
|
-
|
|
219
|
+
# One connection is shared by every tool call (FastMCP runs synchronous tools
|
|
220
|
+
# in a threadpool), so the connection is also the unit of serialization:
|
|
221
|
+
# ``lastrowid``, ``commit()`` and ``rollback()`` are connection-scoped, not
|
|
222
|
+
# call-scoped. Without this lock one call reads another call's row id, and one
|
|
223
|
+
# call's rollback discards another call's write while reporting success.
|
|
224
|
+
# Reentrant because a tool may re-enter through a helper.
|
|
225
|
+
_DB_LOCK = threading.RLock()
|
|
226
|
+
_DB_CONN: sqlite3.Connection | None = None
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _open_db() -> sqlite3.Connection:
|
|
230
|
+
"""Open and initialize the memory database (caller holds ``_DB_LOCK``).
|
|
231
|
+
|
|
232
|
+
``isolation_level=None`` puts the connection in autocommit mode so every
|
|
233
|
+
write path controls its own transaction explicitly (``BEGIN IMMEDIATE`` …
|
|
234
|
+
``COMMIT``). With the implicit-transaction mode a failure between a write
|
|
235
|
+
and its ``commit()`` would leave a transaction open on the shared handle,
|
|
236
|
+
and the next ``BEGIN IMMEDIATE`` would fail with "cannot start a
|
|
237
|
+
transaction within a transaction".
|
|
238
|
+
|
|
239
|
+
A failed initialization closes the candidate connection before raising, so
|
|
240
|
+
a retry does not leak handles.
|
|
241
|
+
"""
|
|
242
|
+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
243
|
+
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False, isolation_level=None)
|
|
244
|
+
try:
|
|
245
|
+
conn.row_factory = sqlite3.Row
|
|
246
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
247
|
+
conn.execute("PRAGMA busy_timeout=5000")
|
|
248
|
+
conn.execute("PRAGMA foreign_keys=ON")
|
|
249
|
+
conn.executescript(SCHEMA_SQL)
|
|
250
|
+
_ensure_entry_lifecycle_schema(conn)
|
|
251
|
+
if _codemap is not None:
|
|
252
|
+
with contextlib.suppress(Exception):
|
|
253
|
+
_codemap.ensure_codemap_schema(conn)
|
|
254
|
+
except BaseException:
|
|
255
|
+
conn.close()
|
|
256
|
+
raise
|
|
257
|
+
return conn
|
|
258
|
+
|
|
259
|
+
|
|
205
260
|
def _get_db() -> sqlite3.Connection:
|
|
206
261
|
"""Get or create the SQLite connection singleton.
|
|
207
262
|
|
|
208
|
-
|
|
209
|
-
|
|
263
|
+
Double-checked locking makes construction single-shot: concurrent first
|
|
264
|
+
touches wait for the winner instead of each opening a connection. Before
|
|
265
|
+
this guard five parallel first calls created five connections, four of them
|
|
266
|
+
orphaned, and a racing ``PRAGMA journal_mode=WAL`` failed with "database is
|
|
267
|
+
locked". The ``code_*`` tools share this connection, so the codemap schema
|
|
210
268
|
is applied on the same handle.
|
|
211
269
|
"""
|
|
212
|
-
|
|
213
|
-
conn =
|
|
214
|
-
conn
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
if _codemap is not None:
|
|
221
|
-
with contextlib.suppress(Exception):
|
|
222
|
-
_codemap.ensure_codemap_schema(conn)
|
|
223
|
-
return conn
|
|
270
|
+
global _DB_CONN # noqa: PLW0603
|
|
271
|
+
conn = _DB_CONN
|
|
272
|
+
if conn is not None:
|
|
273
|
+
return conn
|
|
274
|
+
with _DB_LOCK:
|
|
275
|
+
if _DB_CONN is None:
|
|
276
|
+
_DB_CONN = _open_db()
|
|
277
|
+
return _DB_CONN
|
|
224
278
|
|
|
225
279
|
|
|
226
280
|
def _get_conn() -> sqlite3.Connection:
|
|
@@ -228,6 +282,39 @@ def _get_conn() -> sqlite3.Connection:
|
|
|
228
282
|
return _get_db()
|
|
229
283
|
|
|
230
284
|
|
|
285
|
+
@contextlib.contextmanager
|
|
286
|
+
def _write_transaction(db: sqlite3.Connection) -> Iterator[None]:
|
|
287
|
+
"""Run the block as one ``BEGIN IMMEDIATE`` transaction under ``_DB_LOCK``.
|
|
288
|
+
|
|
289
|
+
``BEGIN IMMEDIATE`` takes the write lock up front instead of on the first
|
|
290
|
+
mutating statement, so two writers cannot both read a state and then race
|
|
291
|
+
to change it. The block — including the read of ``lastrowid`` and the
|
|
292
|
+
``COMMIT`` — runs while the lock is held, which is what makes a reported
|
|
293
|
+
success mean a persisted row.
|
|
294
|
+
|
|
295
|
+
Args:
|
|
296
|
+
db: The shared connection.
|
|
297
|
+
|
|
298
|
+
Yields:
|
|
299
|
+
None; the caller performs its statements inside the ``with`` body.
|
|
300
|
+
|
|
301
|
+
Raises:
|
|
302
|
+
Exception: Whatever the block raised, after rolling the transaction
|
|
303
|
+
back. Callers turn it into a visible tool error.
|
|
304
|
+
"""
|
|
305
|
+
with _DB_LOCK:
|
|
306
|
+
db.execute("BEGIN IMMEDIATE")
|
|
307
|
+
try:
|
|
308
|
+
yield
|
|
309
|
+
db.execute("COMMIT")
|
|
310
|
+
except BaseException:
|
|
311
|
+
# A failed COMMIT can leave the transaction open; ROLLBACK is the
|
|
312
|
+
# only way back to a usable connection.
|
|
313
|
+
with contextlib.suppress(sqlite3.Error):
|
|
314
|
+
db.execute("ROLLBACK")
|
|
315
|
+
raise
|
|
316
|
+
|
|
317
|
+
|
|
231
318
|
# ── FTS Query Building ────────────────────────────────────────────────────────
|
|
232
319
|
|
|
233
320
|
# Function words carry no retrieval signal but prefix-match a large slice of
|
|
@@ -785,7 +872,6 @@ def memory_store(
|
|
|
785
872
|
return {"error": _format_store_violations(violations, examples)}
|
|
786
873
|
|
|
787
874
|
value = value.strip()
|
|
788
|
-
db = _get_conn()
|
|
789
875
|
now = _now_iso()
|
|
790
876
|
expires_at = (
|
|
791
877
|
None
|
|
@@ -797,20 +883,33 @@ def memory_store(
|
|
|
797
883
|
|
|
798
884
|
metadata_str = metadata if metadata else "{}"
|
|
799
885
|
|
|
886
|
+
# Opening the store is part of the write: a connection that cannot be
|
|
887
|
+
# opened must be reported, never skipped into a success.
|
|
800
888
|
try:
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
889
|
+
db = _get_conn()
|
|
890
|
+
except Exception:
|
|
891
|
+
_LOGGER.warning("memory_store failed: memory database could not be opened")
|
|
892
|
+
return {"error": STORE_UNAVAILABLE_ERROR}
|
|
893
|
+
|
|
894
|
+
try:
|
|
895
|
+
with _write_transaction(db):
|
|
896
|
+
cur = db.execute(
|
|
897
|
+
"""INSERT INTO memories (namespace, key, value, metadata,
|
|
898
|
+
created_at, updated_at, expires_at)
|
|
899
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)""",
|
|
900
|
+
[namespace, key, value, metadata_str, now, now, expires_at],
|
|
901
|
+
)
|
|
902
|
+
# Read under the lock, before COMMIT: lastrowid is connection
|
|
903
|
+
# state, so reading it later can return another call's row.
|
|
904
|
+
entry_id = cur.lastrowid
|
|
905
|
+
if entry_id is None:
|
|
906
|
+
# No id means no proof the row exists; refusing to report
|
|
907
|
+
# success is the whole point of this block.
|
|
908
|
+
raise RuntimeError("the store returned no row id for the insert")
|
|
809
909
|
except sqlite3.IntegrityError as e:
|
|
810
|
-
db.rollback()
|
|
811
910
|
return {"error": f"Duplicate key or constraint violation: {e}"}
|
|
812
911
|
except Exception as e:
|
|
813
|
-
|
|
912
|
+
_LOGGER.warning("memory_store failed: %s", e)
|
|
814
913
|
return {"error": f"Failed to store memory: {e}"}
|
|
815
914
|
|
|
816
915
|
return {
|
|
@@ -881,43 +980,50 @@ def memory_search(
|
|
|
881
980
|
}
|
|
882
981
|
|
|
883
982
|
try:
|
|
884
|
-
#
|
|
885
|
-
#
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
id_list,
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
983
|
+
# Reads take the same lock as writes: the connection is shared, so a
|
|
984
|
+
# SELECT interleaved with an open write transaction observes rows that
|
|
985
|
+
# may still be rolled back, and FTS5 shadow-table reads can fail with
|
|
986
|
+
# SQLITE_LOCKED while the writer holds the table.
|
|
987
|
+
with _DB_LOCK:
|
|
988
|
+
# Over-fetch 2x: freshness decay can promote a candidate that BM25
|
|
989
|
+
# ranked outside top_k, and ranking happens after the fetch.
|
|
990
|
+
hits = _search_candidates(
|
|
991
|
+
db, fts_query, namespace, top_k * 2, include_expired
|
|
992
|
+
)
|
|
993
|
+
if not hits:
|
|
994
|
+
return []
|
|
995
|
+
|
|
996
|
+
candidate_ids = [doc_id for doc_id, _ in hits]
|
|
997
|
+
created_at_map = (
|
|
998
|
+
_fetch_created_at_map(db, candidate_ids)
|
|
999
|
+
if decay_days is not None and decay_days > 0
|
|
1000
|
+
else {}
|
|
1001
|
+
)
|
|
1002
|
+
ranked = _score_hits(hits, top_k, created_at_map, decay_days)
|
|
1003
|
+
|
|
1004
|
+
results: list[dict[str, Any]] = []
|
|
1005
|
+
if ranked:
|
|
1006
|
+
# 5. Fetch full entries
|
|
1007
|
+
id_list = [doc_id for doc_id, _ in ranked]
|
|
1008
|
+
score_map = {doc_id: score for doc_id, score in ranked}
|
|
1009
|
+
placeholders = ",".join("?" * len(id_list))
|
|
1010
|
+
rows = db.execute(
|
|
1011
|
+
f"""SELECT id, namespace, key, value, metadata, created_at,
|
|
1012
|
+
expires_at
|
|
1013
|
+
FROM memories WHERE id IN ({placeholders})""",
|
|
1014
|
+
id_list,
|
|
1015
|
+
).fetchall()
|
|
1016
|
+
|
|
1017
|
+
# Preserve ranking order
|
|
1018
|
+
row_map = {r["id"]: r for r in rows}
|
|
1019
|
+
for doc_id in id_list:
|
|
1020
|
+
row = row_map.get(doc_id)
|
|
1021
|
+
if row is None:
|
|
1022
|
+
continue
|
|
1023
|
+
entry = dict(row)
|
|
1024
|
+
entry = _parse_metadata(entry)
|
|
1025
|
+
entry["score"] = round(score_map.get(doc_id, 0.0), 4)
|
|
1026
|
+
results.append(entry)
|
|
921
1027
|
except Exception:
|
|
922
1028
|
_LOGGER.warning("memory_search failed: FTS or stored-entry read failed")
|
|
923
1029
|
return {
|
|
@@ -957,12 +1063,17 @@ def memory_recall(
|
|
|
957
1063
|
if not key or not key.strip():
|
|
958
1064
|
return None
|
|
959
1065
|
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
1066
|
+
try:
|
|
1067
|
+
db = _get_conn()
|
|
1068
|
+
with _DB_LOCK:
|
|
1069
|
+
row = db.execute(
|
|
1070
|
+
"SELECT id, namespace, key, value, metadata, created_at, updated_at, "
|
|
1071
|
+
"expires_at FROM memories WHERE namespace = ? AND key = ?",
|
|
1072
|
+
[namespace, key.strip()],
|
|
1073
|
+
).fetchone()
|
|
1074
|
+
except Exception as e:
|
|
1075
|
+
_LOGGER.warning("memory_recall failed: %s", e)
|
|
1076
|
+
return {"error": f"Failed to recall memory: {e}"}
|
|
966
1077
|
|
|
967
1078
|
if row is None:
|
|
968
1079
|
return None
|
|
@@ -985,14 +1096,14 @@ def _purge_expired(db: sqlite3.Connection) -> dict[str, Any]:
|
|
|
985
1096
|
Dict with ``deleted``, ``purged`` (row count), and ``expired_only``.
|
|
986
1097
|
"""
|
|
987
1098
|
try:
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
1099
|
+
with _write_transaction(db):
|
|
1100
|
+
cur = db.execute(
|
|
1101
|
+
"DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at <= ?",
|
|
1102
|
+
[_now_iso()],
|
|
1103
|
+
)
|
|
1104
|
+
purged = cur.rowcount
|
|
994
1105
|
except Exception as e:
|
|
995
|
-
|
|
1106
|
+
_LOGGER.warning("memory_forget failed to purge expired entries: %s", e)
|
|
996
1107
|
return {"error": f"Failed to purge expired entries: {e}"}
|
|
997
1108
|
return {"deleted": purged > 0, "purged": purged, "expired_only": True}
|
|
998
1109
|
|
|
@@ -1033,7 +1144,13 @@ def memory_forget(
|
|
|
1033
1144
|
"error": "expired_only cannot be combined with id or key; call "
|
|
1034
1145
|
"it alone to purge every expired entry"
|
|
1035
1146
|
}
|
|
1036
|
-
|
|
1147
|
+
try:
|
|
1148
|
+
return _purge_expired(_get_conn())
|
|
1149
|
+
except Exception:
|
|
1150
|
+
_LOGGER.warning("memory_forget failed: memory database could not be opened")
|
|
1151
|
+
return {
|
|
1152
|
+
"error": "Failed to delete: the memory database could not be opened"
|
|
1153
|
+
}
|
|
1037
1154
|
|
|
1038
1155
|
if id is not None:
|
|
1039
1156
|
identifier = id
|
|
@@ -1047,22 +1164,24 @@ def memory_forget(
|
|
|
1047
1164
|
else:
|
|
1048
1165
|
return {"error": "Provide either id or key"}
|
|
1049
1166
|
|
|
1050
|
-
db = _get_conn()
|
|
1051
1167
|
try:
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
return {"deleted": False, "error": "Entry not found"}
|
|
1060
|
-
|
|
1061
|
-
return {"deleted": True, col: identifier, "namespace": namespace}
|
|
1168
|
+
db = _get_conn()
|
|
1169
|
+
with _write_transaction(db):
|
|
1170
|
+
if col == "id":
|
|
1171
|
+
cur = db.execute("DELETE FROM memories WHERE id = ?", [id])
|
|
1172
|
+
else:
|
|
1173
|
+
cur = db.execute(sql, params)
|
|
1174
|
+
deleted = cur.rowcount
|
|
1062
1175
|
except Exception as e:
|
|
1063
|
-
|
|
1176
|
+
_LOGGER.warning("memory_forget failed: %s", e)
|
|
1064
1177
|
return {"error": f"Failed to delete: {e}"}
|
|
1065
1178
|
|
|
1179
|
+
if deleted == 0:
|
|
1180
|
+
result: dict[str, Any] = {"deleted": False, "error": "Entry not found"}
|
|
1181
|
+
else:
|
|
1182
|
+
result = {"deleted": True, col: identifier, "namespace": namespace}
|
|
1183
|
+
return result
|
|
1184
|
+
|
|
1066
1185
|
|
|
1067
1186
|
@mcp.tool(
|
|
1068
1187
|
description="List memory entries chronologically with optional "
|
|
@@ -1084,7 +1203,6 @@ def memory_list(
|
|
|
1084
1203
|
List of memory entries sorted by created_at descending.
|
|
1085
1204
|
"""
|
|
1086
1205
|
limit = max(1, min(500, int(limit)))
|
|
1087
|
-
db = _get_conn()
|
|
1088
1206
|
|
|
1089
1207
|
conditions: list[str] = []
|
|
1090
1208
|
params: list[Any] = []
|
|
@@ -1100,12 +1218,15 @@ def memory_list(
|
|
|
1100
1218
|
where = " AND ".join(conditions) if conditions else "1"
|
|
1101
1219
|
|
|
1102
1220
|
try:
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1221
|
+
db = _get_conn()
|
|
1222
|
+
with _DB_LOCK:
|
|
1223
|
+
rows = db.execute(
|
|
1224
|
+
f"SELECT id, namespace, key, value, metadata, created_at, expires_at "
|
|
1225
|
+
f"FROM memories WHERE {where} ORDER BY created_at DESC LIMIT ?",
|
|
1226
|
+
[*params, limit],
|
|
1227
|
+
).fetchall()
|
|
1108
1228
|
except Exception as e:
|
|
1229
|
+
_LOGGER.warning("memory_list failed: %s", e)
|
|
1109
1230
|
return [{"error": f"List failed: {e}"}]
|
|
1110
1231
|
|
|
1111
1232
|
results = []
|
|
@@ -1134,60 +1255,67 @@ def memory_stats() -> dict[str, Any]:
|
|
|
1134
1255
|
Returns:
|
|
1135
1256
|
Dict with count, namespaces, storage info, and size accounting.
|
|
1136
1257
|
"""
|
|
1137
|
-
|
|
1258
|
+
try:
|
|
1259
|
+
db = _get_conn()
|
|
1260
|
+
except Exception as e:
|
|
1261
|
+
_LOGGER.warning("memory_stats failed: %s", e)
|
|
1262
|
+
return {"status": "error", "error": f"Failed to read statistics: {e}"}
|
|
1138
1263
|
|
|
1139
1264
|
stats: dict[str, Any] = {"status": "ok"}
|
|
1140
1265
|
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1266
|
+
# The connection is shared with writers; reading under the same lock keeps
|
|
1267
|
+
# each aggregate on one committed state instead of a half-applied write.
|
|
1268
|
+
with _DB_LOCK:
|
|
1269
|
+
try:
|
|
1270
|
+
stats["total_entries"] = db.execute(
|
|
1271
|
+
"SELECT COUNT(*) AS c FROM memories"
|
|
1272
|
+
).fetchone()["c"]
|
|
1273
|
+
except Exception:
|
|
1274
|
+
stats["total_entries"] = 0
|
|
1147
1275
|
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1276
|
+
try:
|
|
1277
|
+
ns_rows = db.execute(
|
|
1278
|
+
"SELECT namespace, COUNT(*) AS c FROM memories GROUP BY namespace "
|
|
1279
|
+
"ORDER BY c DESC"
|
|
1280
|
+
).fetchall()
|
|
1281
|
+
stats["namespaces"] = [
|
|
1282
|
+
{"namespace": r["namespace"], "count": r["c"]} for r in ns_rows
|
|
1283
|
+
]
|
|
1284
|
+
except Exception:
|
|
1285
|
+
stats["namespaces"] = []
|
|
1158
1286
|
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1287
|
+
cap = _max_entry_bytes()
|
|
1288
|
+
warning_threshold = max(1, cap // 2)
|
|
1289
|
+
stats["max_entry_bytes"] = cap
|
|
1290
|
+
stats["warning_threshold_bytes"] = warning_threshold
|
|
1163
1291
|
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1292
|
+
try:
|
|
1293
|
+
stats["total_bytes"] = db.execute(
|
|
1294
|
+
f"SELECT coalesce(sum({_ENTRY_BYTES_SQL}), 0) AS b FROM memories"
|
|
1295
|
+
).fetchone()["b"]
|
|
1296
|
+
except Exception:
|
|
1297
|
+
stats["total_bytes"] = 0
|
|
1170
1298
|
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1299
|
+
try:
|
|
1300
|
+
over_rows = db.execute(
|
|
1301
|
+
f"SELECT COUNT(*) AS c FROM memories WHERE ({_ENTRY_BYTES_SQL}) > ?",
|
|
1302
|
+
[warning_threshold],
|
|
1303
|
+
).fetchone()
|
|
1304
|
+
stats["oversized_entries"] = over_rows["c"]
|
|
1305
|
+
except Exception:
|
|
1306
|
+
stats["oversized_entries"] = 0
|
|
1179
1307
|
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1308
|
+
try:
|
|
1309
|
+
largest = db.execute(
|
|
1310
|
+
f"SELECT namespace, key, ({_ENTRY_BYTES_SQL}) AS bytes FROM memories "
|
|
1311
|
+
"ORDER BY bytes DESC, id ASC LIMIT 5"
|
|
1312
|
+
).fetchall()
|
|
1313
|
+
stats["largest_entries"] = [
|
|
1314
|
+
{"namespace": r["namespace"], "key": r["key"], "bytes": r["bytes"]}
|
|
1315
|
+
for r in largest
|
|
1316
|
+
]
|
|
1317
|
+
except Exception:
|
|
1318
|
+
stats["largest_entries"] = []
|
|
1191
1319
|
|
|
1192
1320
|
try:
|
|
1193
1321
|
db_size = DB_PATH.stat().st_size if DB_PATH.exists() else 0
|
|
@@ -1238,8 +1366,13 @@ def code_index(
|
|
|
1238
1366
|
"indexed": 0,
|
|
1239
1367
|
"skipped": 0,
|
|
1240
1368
|
}
|
|
1241
|
-
|
|
1242
|
-
|
|
1369
|
+
try:
|
|
1370
|
+
db = _get_conn()
|
|
1371
|
+
with _DB_LOCK:
|
|
1372
|
+
return _codemap.code_index(db, path, force, project_root=project_root)
|
|
1373
|
+
except Exception as e:
|
|
1374
|
+
_LOGGER.warning("code_index failed: %s", e)
|
|
1375
|
+
return {"error": f"Failed to index code: {e}"}
|
|
1243
1376
|
|
|
1244
1377
|
|
|
1245
1378
|
@mcp.tool(
|
|
@@ -1264,8 +1397,13 @@ def code_query(
|
|
|
1264
1397
|
"""
|
|
1265
1398
|
if _codemap is None:
|
|
1266
1399
|
return [{"error": "codemap module not available"}]
|
|
1267
|
-
|
|
1268
|
-
|
|
1400
|
+
try:
|
|
1401
|
+
db = _get_conn()
|
|
1402
|
+
with _DB_LOCK:
|
|
1403
|
+
return _codemap.code_query(db, query, type, limit)
|
|
1404
|
+
except Exception as e:
|
|
1405
|
+
_LOGGER.warning("code_query failed: %s", e)
|
|
1406
|
+
return [{"error": f"Failed to query code: {e}"}]
|
|
1269
1407
|
|
|
1270
1408
|
|
|
1271
1409
|
@mcp.tool(
|
|
@@ -1286,8 +1424,13 @@ def code_neighbors(
|
|
|
1286
1424
|
"""
|
|
1287
1425
|
if _codemap is None:
|
|
1288
1426
|
return {"error": "codemap module not available"}
|
|
1289
|
-
|
|
1290
|
-
|
|
1427
|
+
try:
|
|
1428
|
+
db = _get_conn()
|
|
1429
|
+
with _DB_LOCK:
|
|
1430
|
+
return _codemap.code_neighbors(db, entity_id, depth)
|
|
1431
|
+
except Exception as e:
|
|
1432
|
+
_LOGGER.warning("code_neighbors failed: %s", e)
|
|
1433
|
+
return {"error": f"Failed to read code neighbors: {e}"}
|
|
1291
1434
|
|
|
1292
1435
|
|
|
1293
1436
|
# ── Main Entrypoint ───────────────────────────────────────────────────────────
|