pantheon-opencode 1.6.2-beta.1 → 1.6.2-beta.11

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.
Files changed (145) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/README.md +236 -60
  3. package/README.pt-BR.md +19 -1
  4. package/bin/pantheon-init.mjs +195 -13
  5. package/package.json +11 -3
  6. package/plugin.json +1 -1
  7. package/prompts/README.md +58 -0
  8. package/prompts/debug-issue.prompt.md +46 -0
  9. package/prompts/dynamic/agora-generated.txt +38 -0
  10. package/prompts/dynamic/orchestrate-generated.txt +51 -0
  11. package/prompts/focus.prompt.md +42 -0
  12. package/prompts/implement-feature.prompt.md +39 -0
  13. package/prompts/optimize-database.prompt.md +58 -0
  14. package/prompts/orchestrate-with-zeus.prompt.md +441 -0
  15. package/prompts/plan-architecture.prompt.md +59 -0
  16. package/prompts/quick-discovery-large-codebase.prompt.md +294 -0
  17. package/prompts/quick-plan-large-feature.prompt.md +197 -0
  18. package/prompts/semantic-summarize.md +50 -0
  19. package/prompts/sketch.prompt.md +91 -0
  20. package/prompts/subtask.prompt.md +131 -0
  21. package/pyproject.toml +1 -1
  22. package/scripts/decision-router-budget.mjs +780 -0
  23. package/scripts/decision-router-v2-budget.mjs +218 -0
  24. package/scripts/decision-router-v2-egress.mjs +272 -0
  25. package/scripts/decision-router.mjs +758 -0
  26. package/scripts/docs-check-changelog.mjs +5 -3
  27. package/scripts/install/component-selection.mjs +9 -4
  28. package/scripts/install/decision-layer-preview.mjs +376 -0
  29. package/scripts/install/decision-router-config.mjs +560 -0
  30. package/scripts/install/health-check.mjs +20 -11
  31. package/scripts/install/interactive.mjs +103 -14
  32. package/scripts/install/interrupt.mjs +4 -3
  33. package/scripts/install/migrate.mjs +123 -72
  34. package/scripts/install/opencode.mjs +178 -122
  35. package/scripts/install/plan.mjs +8 -1
  36. package/scripts/install/plugin.mjs +4 -3
  37. package/scripts/install/state.mjs +12 -0
  38. package/scripts/install/strings.mjs +22 -0
  39. package/scripts/install/venv.mjs +34 -17
  40. package/scripts/mcp_resources.py +11 -9
  41. package/scripts/release-gates.mjs +6 -82
  42. package/scripts/release-notes.mjs +30 -7
  43. package/scripts/restore.mjs +22 -10
  44. package/scripts/sync-tui.mjs +3 -3
  45. package/scripts/test-opencode-v2-sandbox.sh +10 -6
  46. package/scripts/versioning.mjs +41 -5
  47. package/src/agents/aphrodite.md +6 -1
  48. package/src/agents/apollo.md +1 -0
  49. package/src/agents/athena.md +1 -0
  50. package/src/agents/demeter.md +1 -1
  51. package/src/agents/gaia.md +1 -0
  52. package/src/agents/hephaestus.md +1 -1
  53. package/src/agents/hermes.md +8 -10
  54. package/src/agents/iris.md +1 -1
  55. package/src/agents/mnemosyne.md +1 -0
  56. package/src/agents/nyx.md +1 -1
  57. package/src/agents/prometheus.md +1 -1
  58. package/src/agents/talos.md +6 -1
  59. package/src/agents/themis.md +1 -1
  60. package/src/agents/zeus.md +52 -62
  61. package/src/mcp/eval_store.py +11 -4
  62. package/src/mcp/mcp_resources.py +11 -9
  63. package/src/mcp/memory_mcp.py +293 -150
  64. package/src/pantheon/cost-command.ts +30 -133
  65. package/src/pantheon/jev-decision-tool.ts +359 -0
  66. package/src/pantheon/jev-decisions.ts +625 -0
  67. package/src/pantheon/local-decision-agents.ts +170 -0
  68. package/src/pantheon/local-decision-budget.ts +1046 -0
  69. package/src/pantheon/local-decision-egress-gate.ts +144 -0
  70. package/src/pantheon/local-decision-prompt.ts +256 -0
  71. package/src/pantheon/local-decision-provider-matrix.ts +44 -0
  72. package/src/pantheon/local-decision-router.ts +225 -0
  73. package/src/pantheon/local-decision-skills.ts +281 -0
  74. package/src/pantheon/local-decision-tool.ts +160 -0
  75. package/src/pantheon/local-decision-turn.ts +101 -0
  76. package/src/pantheon/local-decision-usage-evidence.internal.ts +168 -0
  77. package/src/pantheon/local-orchestration.ts +322 -0
  78. package/src/pantheon/model-pricing.ts +1 -536
  79. package/src/pantheon/pantheon-decision-catalog.ts +101 -0
  80. package/src/pantheon/v2-decision-budget.ts +456 -0
  81. package/src/pantheon/v2-decision-contracts.ts +300 -0
  82. package/src/pantheon/v2-decision-egress.ts +203 -0
  83. package/src/pantheon/v2-decision-events.ts +180 -0
  84. package/src/pantheon/v2-decision-heuristic.ts +121 -0
  85. package/src/pantheon/v2-decision-points/p1-agent.ts +91 -0
  86. package/src/pantheon/v2-decision-points/p10-claims.ts +243 -0
  87. package/src/pantheon/v2-decision-points/p11-catalog.ts +220 -0
  88. package/src/pantheon/v2-decision-points/p2-skill.ts +83 -0
  89. package/src/pantheon/v2-decision-points/p3-complexity.ts +108 -0
  90. package/src/pantheon/v2-decision-points/p4-memory.ts +137 -0
  91. package/src/pantheon/v2-decision-points/p5-themis-verify.ts +190 -0
  92. package/src/pantheon/v2-decision-points/p6-council.ts +161 -0
  93. package/src/pantheon/v2-decision-points/p7-loop.ts +263 -0
  94. package/src/pantheon/v2-decision-points/p8-guardrail.ts +367 -0
  95. package/src/pantheon/v2-decision-points/p9-memory-compaction.ts +304 -0
  96. package/src/pantheon/v2-decision-points.ts +242 -0
  97. package/src/pantheon/v2-decision-policy.ts +166 -0
  98. package/src/pantheon/v2-decision-premises.ts +146 -0
  99. package/src/pantheon/v2-decision-prompt-surface.ts +115 -0
  100. package/src/pantheon/v2-decision-rank.ts +91 -0
  101. package/src/pantheon/v2-decision-registry.ts +391 -0
  102. package/src/pantheon/v2-decision-resource-ids.ts +127 -0
  103. package/src/pantheon/v2-decision-shadow.ts +123 -0
  104. package/src/pantheon/v2-decision-telemetry.ts +214 -0
  105. package/src/pantheon/v2-decision-verify.ts +51 -0
  106. package/src/pantheon/v2-hook-engine.ts +307 -0
  107. package/src/pantheon/v2-native-decisions.ts +365 -0
  108. package/src/pantheon/v2-shell-hooks.ts +66 -2
  109. package/src/pantheon/v2-tools.ts +38 -15
  110. package/src/plugin-v2.ts +419 -26
  111. package/src/plugin.ts +4 -0
  112. package/src/plugins/tui/THIRD_PARTY_NOTICES.md +24 -0
  113. package/src/plugins/tui/dist/server-v2.d.ts +19 -11
  114. package/src/plugins/tui/dist/server-v2.d.ts.map +1 -1
  115. package/src/plugins/tui/dist/server-v2.js +19 -666
  116. package/src/plugins/tui/dist/server-v2.js.map +1 -1
  117. package/src/plugins/tui/dist/tui-v2.d.ts +11 -203
  118. package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
  119. package/src/plugins/tui/dist/tui-v2.js +187 -1917
  120. package/src/plugins/tui/dist/tui-v2.js.map +1 -1
  121. package/src/plugins/tui/dist/tui.js +1 -1
  122. package/src/plugins/tui/package-lock.json +17 -2
  123. package/src/plugins/tui/package.json +4 -2
  124. package/src/plugins/tui/src/cost-data.ts +607 -0
  125. package/src/plugins/tui/src/index-v2.tsx +213 -54
  126. package/src/plugins/tui/src/model-pricing.ts +536 -0
  127. package/src/plugins/tui/src/server-v2.ts +18 -838
  128. package/src/plugins/tui/tsdown.config.ts +28 -6
  129. package/src/plugins/tui/dist/quota-adapters.d.ts +0 -89
  130. package/src/plugins/tui/dist/quota-adapters.d.ts.map +0 -1
  131. package/src/plugins/tui/dist/quota-adapters.js +0 -1142
  132. package/src/plugins/tui/dist/quota-adapters.js.map +0 -1
  133. package/src/plugins/tui/dist/quota-cli.d.ts +0 -17
  134. package/src/plugins/tui/dist/quota-cli.d.ts.map +0 -1
  135. package/src/plugins/tui/dist/quota-cli.js +0 -184
  136. package/src/plugins/tui/dist/quota-cli.js.map +0 -1
  137. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js +0 -390
  138. package/src/plugins/tui/dist/quota-rpc-UL2HuFRJ.js.map +0 -1
  139. package/src/plugins/tui/src/go-key-diagnostic-ui.ts +0 -100
  140. package/src/plugins/tui/src/go-key-diagnostic.ts +0 -125
  141. package/src/plugins/tui/src/quota-adapters.ts +0 -1598
  142. package/src/plugins/tui/src/quota-cli.ts +0 -237
  143. package/src/plugins/tui/src/quota-rpc.ts +0 -209
  144. package/src/plugins/tui/src/quota-v2-model.ts +0 -1032
  145. package/src/plugins/tui/src/quota-v2.tsx +0 -986
@@ -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
- """Reset cached state for test isolation."""
80
- _get_db.cache_clear()
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
- @functools.cache
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
- Creates DB directory, applies WAL/performance pragmas, and runs schema
209
- init. The ``code_*`` tools share this connection, so the codemap schema
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
- DB_PATH.parent.mkdir(parents=True, exist_ok=True)
213
- conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)
214
- conn.row_factory = sqlite3.Row
215
- conn.execute("PRAGMA journal_mode=WAL")
216
- conn.execute("PRAGMA busy_timeout=5000")
217
- conn.execute("PRAGMA foreign_keys=ON")
218
- conn.executescript(SCHEMA_SQL)
219
- _ensure_entry_lifecycle_schema(conn)
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
- cur = db.execute(
802
- """INSERT INTO memories (namespace, key, value, metadata,
803
- created_at, updated_at, expires_at)
804
- VALUES (?, ?, ?, ?, ?, ?, ?)""",
805
- [namespace, key, value, metadata_str, now, now, expires_at],
806
- )
807
- entry_id = cur.lastrowid
808
- db.commit()
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
- db.rollback()
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
- # Over-fetch 2x: freshness decay can promote a candidate that BM25
885
- # ranked outside top_k, and ranking happens after the fetch.
886
- hits = _search_candidates(db, fts_query, namespace, top_k * 2, include_expired)
887
- if not hits:
888
- return []
889
-
890
- candidate_ids = [doc_id for doc_id, _ in hits]
891
- created_at_map = (
892
- _fetch_created_at_map(db, candidate_ids)
893
- if decay_days is not None and decay_days > 0
894
- else {}
895
- )
896
- ranked = _score_hits(hits, top_k, created_at_map, decay_days)
897
-
898
- results: list[dict[str, Any]] = []
899
- if ranked:
900
- # 5. Fetch full entries
901
- id_list = [doc_id for doc_id, _ in ranked]
902
- score_map = {doc_id: score for doc_id, score in ranked}
903
- placeholders = ",".join("?" * len(id_list))
904
- rows = db.execute(
905
- f"""SELECT id, namespace, key, value, metadata, created_at,
906
- expires_at
907
- FROM memories WHERE id IN ({placeholders})""",
908
- id_list,
909
- ).fetchall()
910
-
911
- # Preserve ranking order
912
- row_map = {r["id"]: r for r in rows}
913
- for doc_id in id_list:
914
- row = row_map.get(doc_id)
915
- if row is None:
916
- continue
917
- entry = dict(row)
918
- entry = _parse_metadata(entry)
919
- entry["score"] = round(score_map.get(doc_id, 0.0), 4)
920
- results.append(entry)
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
- db = _get_conn()
961
- row = db.execute(
962
- "SELECT id, namespace, key, value, metadata, created_at, updated_at, "
963
- "expires_at FROM memories WHERE namespace = ? AND key = ?",
964
- [namespace, key.strip()],
965
- ).fetchone()
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
- cur = db.execute(
989
- "DELETE FROM memories WHERE expires_at IS NOT NULL AND expires_at <= ?",
990
- [_now_iso()],
991
- )
992
- purged = cur.rowcount
993
- db.commit()
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
- db.rollback()
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
- return _purge_expired(_get_conn())
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
- if col == "id":
1053
- cur = db.execute("DELETE FROM memories WHERE id = ?", [id])
1054
- else:
1055
- cur = db.execute(sql, params)
1056
- db.commit()
1057
-
1058
- if cur.rowcount == 0:
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
- db.rollback()
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
- rows = db.execute(
1104
- f"SELECT id, namespace, key, value, metadata, created_at, expires_at "
1105
- f"FROM memories WHERE {where} ORDER BY created_at DESC LIMIT ?",
1106
- [*params, limit],
1107
- ).fetchall()
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
- db = _get_conn()
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
- try:
1142
- stats["total_entries"] = db.execute(
1143
- "SELECT COUNT(*) AS c FROM memories"
1144
- ).fetchone()["c"]
1145
- except Exception:
1146
- stats["total_entries"] = 0
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
- try:
1149
- ns_rows = db.execute(
1150
- "SELECT namespace, COUNT(*) AS c FROM memories GROUP BY namespace "
1151
- "ORDER BY c DESC"
1152
- ).fetchall()
1153
- stats["namespaces"] = [
1154
- {"namespace": r["namespace"], "count": r["c"]} for r in ns_rows
1155
- ]
1156
- except Exception:
1157
- stats["namespaces"] = []
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
- cap = _max_entry_bytes()
1160
- warning_threshold = max(1, cap // 2)
1161
- stats["max_entry_bytes"] = cap
1162
- stats["warning_threshold_bytes"] = warning_threshold
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
- try:
1165
- stats["total_bytes"] = db.execute(
1166
- f"SELECT coalesce(sum({_ENTRY_BYTES_SQL}), 0) AS b FROM memories"
1167
- ).fetchone()["b"]
1168
- except Exception:
1169
- stats["total_bytes"] = 0
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
- try:
1172
- over_rows = db.execute(
1173
- f"SELECT COUNT(*) AS c FROM memories WHERE ({_ENTRY_BYTES_SQL}) > ?",
1174
- [warning_threshold],
1175
- ).fetchone()
1176
- stats["oversized_entries"] = over_rows["c"]
1177
- except Exception:
1178
- stats["oversized_entries"] = 0
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
- try:
1181
- largest = db.execute(
1182
- f"SELECT namespace, key, ({_ENTRY_BYTES_SQL}) AS bytes FROM memories "
1183
- "ORDER BY bytes DESC, id ASC LIMIT 5"
1184
- ).fetchall()
1185
- stats["largest_entries"] = [
1186
- {"namespace": r["namespace"], "key": r["key"], "bytes": r["bytes"]}
1187
- for r in largest
1188
- ]
1189
- except Exception:
1190
- stats["largest_entries"] = []
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
- db = _get_conn()
1242
- return _codemap.code_index(db, path, force, project_root=project_root)
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
- db = _get_conn()
1268
- return _codemap.code_query(db, query, type, limit)
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
- db = _get_conn()
1290
- return _codemap.code_neighbors(db, entity_id, depth)
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 ───────────────────────────────────────────────────────────