pantheon-opencode 1.6.0-beta.9 → 1.6.1
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/AGENTS.global.md +118 -0
- package/AGENTS.md +18 -168
- package/CHANGELOG.md +144 -365
- package/README.md +124 -607
- package/README.pt-BR.md +120 -345
- package/bin/pantheon-init.mjs +504 -141
- package/commands/pantheon-deepwork.md +14 -3
- package/commands/pantheon-vision.md +61 -12
- package/package.json +22 -13
- package/plugin.json +1 -1
- package/pyproject.toml +6 -2
- package/scripts/_pantheon_paths.py +24 -0
- package/scripts/build-agents-md.mjs +368 -69
- package/scripts/changelog-merge.mjs +161 -0
- package/scripts/check-plugin-v2-coverage.mjs +11 -8
- package/scripts/docs-check-changelog.mjs +204 -0
- package/scripts/docs-link-check.mjs +314 -0
- package/scripts/docs-media.mjs +157 -0
- package/scripts/doctor.mjs +850 -45
- package/scripts/install/agents-md.mjs +2 -2
- package/scripts/install/backup.mjs +648 -0
- package/scripts/install/cli-ui.mjs +303 -72
- package/scripts/install/component-selection.mjs +61 -0
- package/scripts/install/config-migration.mjs +583 -27
- package/scripts/install/exit-codes.mjs +26 -0
- package/scripts/install/file-inventory.mjs +555 -0
- package/scripts/install/health-check.mjs +31 -25
- package/scripts/install/interactive.mjs +99 -383
- package/scripts/install/interrupt.mjs +78 -0
- package/scripts/install/migrate.mjs +49 -25
- package/scripts/install/model-picker.mjs +218 -250
- package/scripts/install/opencode-state.mjs +91 -0
- package/scripts/install/opencode-version.mjs +83 -21
- package/scripts/install/opencode.mjs +1675 -187
- package/scripts/install/plan-artifact.mjs +517 -0
- package/scripts/install/plan.mjs +475 -0
- package/scripts/install/plugin.mjs +214 -27
- package/scripts/install/prompt-result.mjs +2 -0
- package/scripts/install/run-record.mjs +115 -0
- package/scripts/install/shared.mjs +256 -99
- package/scripts/install/state.mjs +63 -8
- package/scripts/install/strings.mjs +93 -8
- package/scripts/install/v2-capabilities.mjs +205 -0
- package/scripts/install/venv.mjs +90 -47
- package/scripts/install/verify.mjs +128 -0
- package/scripts/install/vision-prompt.mjs +173 -0
- package/scripts/install-mcp.mjs +2 -2
- package/scripts/manifest-inventory.mjs +49 -3
- package/scripts/mcp_persistence.py +1535 -1050
- package/scripts/memory_mcp.py +12 -843
- package/scripts/node-engine-policy.mjs +85 -0
- package/scripts/package-evidence.mjs +10 -2
- package/scripts/postinstall.mjs +26 -26
- package/scripts/probe-pantheon-cost.mjs +118 -19
- package/scripts/prune.mjs +9 -3
- package/scripts/reconcile.mjs +325 -0
- package/scripts/release-gates.mjs +687 -0
- package/scripts/restore.mjs +222 -0
- package/scripts/run-node-tests.mjs +24 -8
- package/scripts/sync-artifacts.mjs +19 -7
- package/scripts/sync-tui.mjs +5 -1
- package/scripts/test-opencode-v2-sandbox.sh +36 -123
- package/scripts/uninstall.mjs +369 -34
- package/scripts/update.mjs +164 -0
- package/scripts/validate-node-engine-policy.mjs +13 -0
- package/scripts/version-check.mjs +34 -1
- package/scripts/versioning.mjs +23 -3
- package/scripts/vision-status.mjs +682 -0
- package/skills-lock.json +8 -8
- package/src/agents/aphrodite.md +13 -10
- package/src/agents/apollo.md +4 -5
- package/src/agents/athena.md +74 -46
- package/src/agents/demeter.md +10 -7
- package/src/agents/gaia.md +0 -1
- package/src/agents/hephaestus.md +4 -3
- package/src/agents/hermes.md +10 -9
- package/src/agents/iris.md +6 -1
- package/src/agents/mnemosyne.md +10 -4
- package/src/agents/nyx.md +4 -4
- package/src/agents/prometheus.md +12 -11
- package/src/agents/talos.md +6 -0
- package/src/agents/zeus.md +84 -56
- package/src/instructions/agent-return-format.instructions.md +12 -41
- package/src/instructions/memory-protocol.instructions.md +5 -11
- package/src/instructions/test-economy.instructions.md +12 -0
- package/src/instructions/yagni.instructions.md +6 -15
- package/src/instructions/zeus-anti-stall.instructions.md +6 -6
- package/src/instructions/zeus-communication-rules.instructions.md +6 -6
- package/src/instructions/zeus-council-synthesis.instructions.md +11 -12
- package/src/instructions/zeus-memory-operations.instructions.md +13 -7
- package/src/instructions/zeus-timeout-retry.instructions.md +36 -10
- package/src/mcp/_pantheon_paths.py +24 -0
- package/src/mcp/mcp_codemap_module.py +86 -18
- package/src/mcp/mcp_persistence.py +1535 -1050
- package/src/mcp/memory_mcp.py +444 -94
- package/src/mcp/pantheon_vision.py +285 -41
- package/src/mcp/requirements-mcp.txt +6 -1
- package/src/mcp/requirements-vision.txt +1 -1
- package/src/pantheon/context-pruner.ts +541 -0
- package/src/pantheon/cost-command.ts +901 -60
- package/src/pantheon/delegation-enforce.ts +160 -23
- package/src/pantheon/goal-loop.ts +11 -8
- package/src/pantheon/guard-path.ts +162 -0
- package/src/pantheon/memory-context.ts +1017 -0
- package/src/pantheon/model-agents.ts +19 -0
- package/src/pantheon/model-command.ts +218 -56
- package/src/pantheon/model-pricing.ts +536 -0
- package/src/pantheon/presets.mjs +2 -0
- package/src/pantheon/task-result-guard.ts +50 -14
- package/src/pantheon/v2-bounded-read.ts +654 -0
- package/src/pantheon/v2-bridge.ts +27 -0
- package/src/pantheon/v2-delegation-enforce.ts +133 -6
- package/src/pantheon/v2-execute-after.ts +135 -24
- package/src/pantheon/v2-model-overrides.ts +275 -0
- package/src/pantheon/v2-shell-hooks.ts +260 -0
- package/src/pantheon/v2-tools.ts +89 -35
- package/src/pantheon/v2-unsupported.mjs +34 -7
- package/src/pantheon/v2-vision.ts +622 -0
- package/src/pantheon/vision-local.ts +531 -0
- package/src/pantheon/vision.ts +1166 -116
- package/src/plugin-v2.ts +1039 -171
- package/src/plugin.ts +37 -13
- package/src/plugins/tui/dist/tui-v2.d.ts +1029 -2
- package/src/plugins/tui/dist/tui-v2.d.ts.map +1 -1
- package/src/plugins/tui/dist/tui-v2.js +3742 -85
- package/src/plugins/tui/dist/tui.js +1 -1
- package/src/plugins/tui/package-lock.json +15 -15
- package/src/plugins/tui/package.json +7 -5
- package/src/plugins/tui/src/index-v2.tsx +4314 -50
- package/src/plugins/tui/tsconfig.typecheck.json +5 -0
- package/src/routing.yml +50 -5
- package/src/skills/agent-coordination/SKILL.md +7 -2
- package/src/skills/artifact-management/SKILL.md +5 -1
- package/src/skills/auto-continue/SKILL.md +14 -6
- package/src/skills/codemap/SKILL.md +1 -1
- package/src/skills/memory-bank/SKILL.md +21 -13
- package/src/skills/session-goal/SKILL.md +12 -22
- package/src/skills/spec-driven-development/SKILL.md +3 -1
- package/src/skills/worktrees/SKILL.md +30 -11
- package/scripts/probe-context-rehydrate.mjs +0 -263
package/scripts/memory_mcp.py
CHANGED
|
@@ -1,855 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env python3
|
|
2
|
-
"""
|
|
2
|
+
"""Compatibility entrypoint for the canonical Memory MCP server.
|
|
3
3
|
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
half was compensating for a query bug rather than adding recall. See
|
|
8
|
-
``_build_fts_query`` for the query form that replaced it.
|
|
9
|
-
|
|
10
|
-
Recall is therefore purely lexical. A query that shares no token with a
|
|
11
|
-
stored document will not retrieve it; there is no embedding to fall back on.
|
|
12
|
-
|
|
13
|
-
Tools:
|
|
14
|
-
memory_store — Store a value (auto-indexed into FTS5 by trigger)
|
|
15
|
-
memory_search — FTS5 BM25 keyword search with optional freshness decay
|
|
16
|
-
memory_recall — Exact recall by key
|
|
17
|
-
memory_forget — Delete by ID or key
|
|
18
|
-
memory_list — Chronological listing
|
|
19
|
-
memory_stats — DB statistics
|
|
20
|
-
|
|
21
|
-
Usage:
|
|
22
|
-
python scripts/memory_mcp.py
|
|
4
|
+
The installer copies ``src/mcp/memory_mcp.py`` into the installed scripts
|
|
5
|
+
directory. This source-tree entrypoint remains for ``install-mcp.mjs``'s local
|
|
6
|
+
fallback and delegates to that canonical implementation.
|
|
23
7
|
"""
|
|
24
8
|
|
|
25
9
|
from __future__ import annotations
|
|
26
10
|
|
|
27
|
-
import
|
|
28
|
-
import json
|
|
29
|
-
import sqlite3
|
|
30
|
-
import time
|
|
31
|
-
from datetime import UTC, datetime
|
|
11
|
+
import sys
|
|
32
12
|
from pathlib import Path
|
|
33
|
-
from typing import Annotated, Any
|
|
34
|
-
|
|
35
|
-
from _pantheon_paths import pantheon_home
|
|
36
|
-
from fastmcp import FastMCP
|
|
37
|
-
from pydantic import BeforeValidator, Field
|
|
38
|
-
|
|
39
|
-
# ── Paths ─────────────────────────────────────────────────────────────────────
|
|
40
|
-
|
|
41
|
-
DB_PATH = pantheon_home() / "memory" / "memory.db"
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
_BYTE_UNIT = 1024
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
def _set_memory_dir(path: str | Path) -> None:
|
|
48
|
-
"""Override the memory db path for testing."""
|
|
49
|
-
global DB_PATH # noqa: PLW0603
|
|
50
|
-
DB_PATH = Path(path) / "memory.db"
|
|
51
|
-
_reset_test_state()
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
def _reset_test_state() -> None:
|
|
55
|
-
"""Reset cached state for test isolation."""
|
|
56
|
-
_get_db.cache_clear()
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
SCHEMA_SQL = """
|
|
60
|
-
CREATE TABLE IF NOT EXISTS memories (
|
|
61
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
62
|
-
namespace TEXT NOT NULL DEFAULT 'default',
|
|
63
|
-
key TEXT,
|
|
64
|
-
value TEXT NOT NULL,
|
|
65
|
-
metadata TEXT NOT NULL DEFAULT '{}',
|
|
66
|
-
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
67
|
-
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
68
|
-
);
|
|
69
|
-
|
|
70
|
-
CREATE UNIQUE INDEX IF NOT EXISTS idx_memories_ns_key
|
|
71
|
-
ON memories(namespace, key);
|
|
72
|
-
|
|
73
|
-
CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
|
|
74
|
-
namespace, key, value, metadata,
|
|
75
|
-
content='memories', content_rowid='id',
|
|
76
|
-
tokenize='porter unicode61'
|
|
77
|
-
);
|
|
78
|
-
|
|
79
|
-
-- FTS sync: INSERT
|
|
80
|
-
CREATE TRIGGER IF NOT EXISTS memories_ai AFTER INSERT ON memories BEGIN
|
|
81
|
-
INSERT INTO memories_fts(rowid, namespace, key, value, metadata)
|
|
82
|
-
VALUES (new.id, new.namespace, new.key, new.value, new.metadata);
|
|
83
|
-
END;
|
|
84
|
-
|
|
85
|
-
-- FTS sync: DELETE
|
|
86
|
-
CREATE TRIGGER IF NOT EXISTS memories_ad AFTER DELETE ON memories BEGIN
|
|
87
|
-
INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value, metadata)
|
|
88
|
-
VALUES ('delete', old.id, old.namespace, old.key, old.value, old.metadata);
|
|
89
|
-
END;
|
|
90
|
-
|
|
91
|
-
-- FTS sync: UPDATE
|
|
92
|
-
CREATE TRIGGER IF NOT EXISTS memories_au AFTER UPDATE ON memories BEGIN
|
|
93
|
-
INSERT INTO memories_fts(memories_fts, rowid, namespace, key, value, metadata)
|
|
94
|
-
VALUES ('delete', old.id, old.namespace, old.key, old.value, old.metadata);
|
|
95
|
-
INSERT INTO memories_fts(rowid, namespace, key, value, metadata)
|
|
96
|
-
VALUES (new.id, new.namespace, new.key, new.value, new.metadata);
|
|
97
|
-
END;
|
|
98
|
-
"""
|
|
99
|
-
|
|
100
|
-
# ── FastMCP App ───────────────────────────────────────────────────────────────
|
|
101
|
-
|
|
102
|
-
mcp = FastMCP(
|
|
103
|
-
"pantheon-memory",
|
|
104
|
-
instructions=(
|
|
105
|
-
"Lightweight memory with FTS5 (SQLite BM25) keyword search across "
|
|
106
|
-
"namespaces. Lexical retrieval only — there is no embedding or vector "
|
|
107
|
-
"index, so a query must share a token with the stored text to match."
|
|
108
|
-
),
|
|
109
|
-
)
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
# ── Database ──────────────────────────────────────────────────────────────────
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
@functools.cache
|
|
116
|
-
def _get_db() -> sqlite3.Connection:
|
|
117
|
-
"""Get or create the SQLite connection singleton.
|
|
118
|
-
|
|
119
|
-
Creates DB directory, applies WAL/performance pragmas and runs schema init.
|
|
120
|
-
"""
|
|
121
|
-
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
|
122
|
-
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)
|
|
123
|
-
conn.row_factory = sqlite3.Row
|
|
124
|
-
conn.execute("PRAGMA journal_mode=WAL")
|
|
125
|
-
conn.execute("PRAGMA busy_timeout=5000")
|
|
126
|
-
conn.execute("PRAGMA foreign_keys=ON")
|
|
127
|
-
conn.executescript(SCHEMA_SQL)
|
|
128
|
-
return conn
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
def _get_conn() -> sqlite3.Connection:
|
|
132
|
-
"""Alias for _get_db — shorthand for tool use."""
|
|
133
|
-
return _get_db()
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
# ── FTS Query Building ────────────────────────────────────────────────────────
|
|
137
|
-
|
|
138
|
-
# Function words carry no retrieval signal but prefix-match a large slice of
|
|
139
|
-
# the corpus, so OR-ing them in dilutes BM25 ranking with noise instead of
|
|
140
|
-
# narrowing the candidate pool. The list is deliberately limited to English
|
|
141
|
-
# function words and auxiliaries — no domain vocabulary.
|
|
142
|
-
_STOPWORDS = frozenset(
|
|
143
|
-
[
|
|
144
|
-
"a",
|
|
145
|
-
"about",
|
|
146
|
-
"above",
|
|
147
|
-
"after",
|
|
148
|
-
"again",
|
|
149
|
-
"against",
|
|
150
|
-
"all",
|
|
151
|
-
"am",
|
|
152
|
-
"an",
|
|
153
|
-
"and",
|
|
154
|
-
"any",
|
|
155
|
-
"are",
|
|
156
|
-
"as",
|
|
157
|
-
"at",
|
|
158
|
-
"be",
|
|
159
|
-
"because",
|
|
160
|
-
"been",
|
|
161
|
-
"before",
|
|
162
|
-
"being",
|
|
163
|
-
"below",
|
|
164
|
-
"between",
|
|
165
|
-
"both",
|
|
166
|
-
"but",
|
|
167
|
-
"by",
|
|
168
|
-
"can",
|
|
169
|
-
"cannot",
|
|
170
|
-
"could",
|
|
171
|
-
"did",
|
|
172
|
-
"do",
|
|
173
|
-
"does",
|
|
174
|
-
"doing",
|
|
175
|
-
"done",
|
|
176
|
-
"down",
|
|
177
|
-
"during",
|
|
178
|
-
"each",
|
|
179
|
-
"few",
|
|
180
|
-
"for",
|
|
181
|
-
"from",
|
|
182
|
-
"further",
|
|
183
|
-
"had",
|
|
184
|
-
"has",
|
|
185
|
-
"have",
|
|
186
|
-
"having",
|
|
187
|
-
"he",
|
|
188
|
-
"her",
|
|
189
|
-
"here",
|
|
190
|
-
"hers",
|
|
191
|
-
"him",
|
|
192
|
-
"his",
|
|
193
|
-
"how",
|
|
194
|
-
"i",
|
|
195
|
-
"if",
|
|
196
|
-
"in",
|
|
197
|
-
"into",
|
|
198
|
-
"is",
|
|
199
|
-
"it",
|
|
200
|
-
"its",
|
|
201
|
-
"itself",
|
|
202
|
-
"just",
|
|
203
|
-
"me",
|
|
204
|
-
"more",
|
|
205
|
-
"most",
|
|
206
|
-
"my",
|
|
207
|
-
"no",
|
|
208
|
-
"nor",
|
|
209
|
-
"not",
|
|
210
|
-
"now",
|
|
211
|
-
"of",
|
|
212
|
-
"off",
|
|
213
|
-
"on",
|
|
214
|
-
"once",
|
|
215
|
-
"only",
|
|
216
|
-
"or",
|
|
217
|
-
"other",
|
|
218
|
-
"our",
|
|
219
|
-
"ours",
|
|
220
|
-
"out",
|
|
221
|
-
"over",
|
|
222
|
-
"own",
|
|
223
|
-
"same",
|
|
224
|
-
"she",
|
|
225
|
-
"should",
|
|
226
|
-
"so",
|
|
227
|
-
"some",
|
|
228
|
-
"such",
|
|
229
|
-
"than",
|
|
230
|
-
"that",
|
|
231
|
-
"the",
|
|
232
|
-
"their",
|
|
233
|
-
"theirs",
|
|
234
|
-
"them",
|
|
235
|
-
"then",
|
|
236
|
-
"there",
|
|
237
|
-
"these",
|
|
238
|
-
"they",
|
|
239
|
-
"this",
|
|
240
|
-
"those",
|
|
241
|
-
"through",
|
|
242
|
-
"to",
|
|
243
|
-
"too",
|
|
244
|
-
"under",
|
|
245
|
-
"until",
|
|
246
|
-
"up",
|
|
247
|
-
"very",
|
|
248
|
-
"was",
|
|
249
|
-
"we",
|
|
250
|
-
"were",
|
|
251
|
-
"what",
|
|
252
|
-
"when",
|
|
253
|
-
"where",
|
|
254
|
-
"which",
|
|
255
|
-
"while",
|
|
256
|
-
"who",
|
|
257
|
-
"whom",
|
|
258
|
-
"why",
|
|
259
|
-
"will",
|
|
260
|
-
"with",
|
|
261
|
-
"would",
|
|
262
|
-
"you",
|
|
263
|
-
"your",
|
|
264
|
-
"yours",
|
|
265
|
-
]
|
|
266
|
-
)
|
|
267
|
-
|
|
268
|
-
# A prefix query on a token this short is broader than the token itself
|
|
269
|
-
# ("in*" matches ingest/input/install/...), so short terms match exactly.
|
|
270
|
-
_MIN_PREFIX_LEN = 4
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
def _build_fts_query(query: str) -> str:
|
|
274
|
-
"""Build an FTS5 ``MATCH`` expression from free-text search input.
|
|
275
|
-
|
|
276
|
-
Replaces the previous ``" OR ".join(f'"{w}"*' for w in query.split())``
|
|
277
|
-
form, which prefix-matched *every* token, stopwords included. Measured on
|
|
278
|
-
the live store (1,553 memories) that form OR-ed in terms like ``the``,
|
|
279
|
-
``is`` and ``how`` whose prefixes match most of the corpus, so a query for
|
|
280
|
-
``purge threshold checkpoint`` pulled 1,001 documents as candidates and
|
|
281
|
-
1,524 of them were noise. Two corrections:
|
|
282
|
-
|
|
283
|
-
- Stopwords are dropped rather than OR-ed in.
|
|
284
|
-
- Tokens shorter than ``_MIN_PREFIX_LEN`` characters match exactly instead
|
|
285
|
-
of by prefix, which removes the 3-character prefix blowups (``"com"*``
|
|
286
|
-
alone matched 1,235 of 1,550 documents).
|
|
287
|
-
|
|
288
|
-
Tokens surviving both filters are still prefix-matched, so a query term
|
|
289
|
-
retrieves documents containing a longer word that starts with it. If every
|
|
290
|
-
token is a stopword the unfiltered tokens are matched exactly, so an
|
|
291
|
-
all-stopword query degrades to a literal lookup rather than to no results.
|
|
292
|
-
|
|
293
|
-
Args:
|
|
294
|
-
query: Raw, user-supplied search text.
|
|
295
|
-
|
|
296
|
-
Returns:
|
|
297
|
-
An FTS5 expression (terms joined with ``OR``), or ``""`` for an empty
|
|
298
|
-
query.
|
|
299
|
-
"""
|
|
300
|
-
words = [word for word in query.split() if word]
|
|
301
|
-
if not words:
|
|
302
|
-
return ""
|
|
303
|
-
content = [word for word in words if word.lower() not in _STOPWORDS]
|
|
304
|
-
if not content:
|
|
305
|
-
content = words
|
|
306
|
-
return " OR ".join(
|
|
307
|
-
f'"{word}"*' if len(word) >= _MIN_PREFIX_LEN else f'"{word}"'
|
|
308
|
-
for word in content
|
|
309
|
-
)
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
# ── Helpers ───────────────────────────────────────────────────────────────────
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
def _dict_from_row(row: sqlite3.Row | None) -> dict[str, Any] | None:
|
|
316
|
-
"""Convert a sqlite3.Row to a plain dict, or return None."""
|
|
317
|
-
if row is None:
|
|
318
|
-
return None
|
|
319
|
-
return dict(row)
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
def _now_iso() -> str:
|
|
323
|
-
"""Return current UTC time as ISO 8601 string."""
|
|
324
|
-
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
def _parse_metadata(row: dict[str, Any]) -> dict[str, Any]:
|
|
328
|
-
"""Parse the metadata JSON field of a memory row."""
|
|
329
|
-
try:
|
|
330
|
-
row["metadata"] = json.loads(row["metadata"])
|
|
331
|
-
except (json.JSONDecodeError, TypeError):
|
|
332
|
-
row["metadata"] = {}
|
|
333
|
-
return row
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
# ── Ranking ───────────────────────────────────────────────────────────────────
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
def _parse_iso_ts(value: str) -> float:
|
|
340
|
-
"""Parse an ISO 8601 UTC timestamp to epoch seconds.
|
|
341
|
-
|
|
342
|
-
Handles both aware ISO strings (``2026-08-21T10:00:00Z`` /
|
|
343
|
-
``...+00:00``) and legacy naive rows from ``DEFAULT (datetime('now'))``
|
|
344
|
-
(``YYYY-MM-DD HH:MM:SS``, space separator, no TZ). Naive timestamps are
|
|
345
|
-
assumed UTC — SQLite's ``datetime('now')`` is UTC, so interpreting them
|
|
346
|
-
in the local timezone would skew freshness decay.
|
|
347
|
-
"""
|
|
348
|
-
dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
|
|
349
|
-
if dt.tzinfo is None:
|
|
350
|
-
dt = dt.replace(tzinfo=UTC)
|
|
351
|
-
return dt.timestamp()
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
def _fetch_created_at_map(db: sqlite3.Connection, ids: list[int]) -> dict[int, str]:
|
|
355
|
-
"""Fetch created_at timestamps for the given memory IDs.
|
|
356
|
-
|
|
357
|
-
Args:
|
|
358
|
-
db: Active SQLite connection.
|
|
359
|
-
ids: Memory row IDs to look up.
|
|
360
|
-
|
|
361
|
-
Returns:
|
|
362
|
-
Mapping of id -> created_at ISO string. Empty on failure.
|
|
363
|
-
"""
|
|
364
|
-
created_at_map: dict[int, str] = {}
|
|
365
|
-
if not ids:
|
|
366
|
-
return created_at_map
|
|
367
|
-
try:
|
|
368
|
-
placeholders = ",".join("?" * len(ids))
|
|
369
|
-
rows = db.execute(
|
|
370
|
-
f"SELECT id, created_at FROM memories WHERE id IN ({placeholders})",
|
|
371
|
-
ids,
|
|
372
|
-
).fetchall()
|
|
373
|
-
created_at_map = {r["id"]: r["created_at"] for r in rows}
|
|
374
|
-
except Exception:
|
|
375
|
-
created_at_map = {}
|
|
376
|
-
return created_at_map
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
def _score_hits(
|
|
380
|
-
hits: list[tuple[int, float]],
|
|
381
|
-
top_k: int,
|
|
382
|
-
created_at_map: dict[int, str] | None = None,
|
|
383
|
-
decay_days: float | None = None,
|
|
384
|
-
) -> list[tuple[int, float]]:
|
|
385
|
-
"""Rank FTS5 hits by BM25 relevance, optionally freshness-decayed.
|
|
386
|
-
|
|
387
|
-
This replaces the vector+BM25 Reciprocal Rank Fusion: with a single ranked
|
|
388
|
-
list there is nothing left to fuse, so each hit keeps its own BM25 score
|
|
389
|
-
instead of a rank-derived one.
|
|
390
|
-
|
|
391
|
-
Args:
|
|
392
|
-
hits: ``(id, bm25)`` pairs from FTS5, most relevant first. ``bm25`` is
|
|
393
|
-
``-rank`` (FTS5 reports ``rank`` negated, lower = better).
|
|
394
|
-
top_k: Maximum number of results to return.
|
|
395
|
-
created_at_map: Optional mapping of doc_id -> created_at ISO string,
|
|
396
|
-
used to compute freshness when ``decay_days`` is set.
|
|
397
|
-
decay_days: Optional freshness half-life in days. When set, each score
|
|
398
|
-
is multiplied by ``2^(-days_since_created/decay_days)`` so older
|
|
399
|
-
entries rank lower. Default None = no decay.
|
|
400
|
-
|
|
401
|
-
Returns:
|
|
402
|
-
List of ``(id, score)`` tuples sorted by descending score, ties broken
|
|
403
|
-
by ascending id so ranking is deterministic.
|
|
404
|
-
"""
|
|
405
|
-
scores: dict[int, float] = {doc_id: bm25 for doc_id, bm25 in hits}
|
|
406
|
-
|
|
407
|
-
if decay_days is not None and decay_days > 0 and created_at_map:
|
|
408
|
-
now = time.time()
|
|
409
|
-
for doc_id in list(scores):
|
|
410
|
-
created = created_at_map.get(doc_id)
|
|
411
|
-
if not created:
|
|
412
|
-
continue
|
|
413
|
-
try:
|
|
414
|
-
days = max(0.0, (now - _parse_iso_ts(created)) / 86400.0)
|
|
415
|
-
except (ValueError, TypeError):
|
|
416
|
-
continue
|
|
417
|
-
scores[doc_id] *= 2.0 ** (-days / decay_days)
|
|
418
|
-
|
|
419
|
-
ranked = sorted(scores.items(), key=lambda x: (-x[1], x[0]))
|
|
420
|
-
return ranked[:top_k]
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
# ── Tools ─────────────────────────────────────────────────────────────────────
|
|
424
|
-
|
|
425
|
-
# ── Argument Validation ─────────────────────────────────────────────────────────
|
|
426
|
-
# One call must surface EVERY invalid argument. ``metadata`` is a JSON object
|
|
427
|
-
# encoded as a STRING, and the natural mistake is to pass the object itself,
|
|
428
|
-
# which used to surface as pydantic's bare "Input should be a valid string" —
|
|
429
|
-
# no path, no received type, no example. The validator below names all three,
|
|
430
|
-
# and pydantic still accumulates it alongside every other invalid argument in
|
|
431
|
-
# the same call.
|
|
432
|
-
|
|
433
|
-
METADATA_EXAMPLE: str = """metadata='{"type": "decision", "score": 0.9}'"""
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
def _json_type_name(value: object) -> str:
|
|
437
|
-
"""Name a value's JSON type for error messages (ints read as ``number``)."""
|
|
438
|
-
if value is None:
|
|
439
|
-
type_name = "null"
|
|
440
|
-
elif isinstance(value, bool):
|
|
441
|
-
type_name = "boolean"
|
|
442
|
-
elif isinstance(value, str):
|
|
443
|
-
type_name = "string"
|
|
444
|
-
elif isinstance(value, int | float):
|
|
445
|
-
type_name = "number"
|
|
446
|
-
elif isinstance(value, list):
|
|
447
|
-
type_name = "array"
|
|
448
|
-
elif isinstance(value, dict):
|
|
449
|
-
type_name = "object"
|
|
450
|
-
else:
|
|
451
|
-
type_name = type(value).__name__
|
|
452
|
-
return type_name
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
def _metadata_must_be_json_string(value: Any) -> Any:
|
|
456
|
-
"""Accept only a JSON object encoded as a string, with an actionable error.
|
|
457
|
-
|
|
458
|
-
Runs before pydantic's own ``str`` check so the failure names the received
|
|
459
|
-
type and a correct example instead of leaking a raw type error.
|
|
460
|
-
"""
|
|
461
|
-
if isinstance(value, str):
|
|
462
|
-
return value
|
|
463
|
-
raise ValueError(
|
|
464
|
-
"metadata must be a JSON object encoded as a string "
|
|
465
|
-
f"(got {_json_type_name(value)}). json.dumps it first. "
|
|
466
|
-
f"Example: {METADATA_EXAMPLE}"
|
|
467
|
-
)
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
def _collect_store_violations(value: str, metadata: str) -> tuple[list[str], list[str]]:
|
|
471
|
-
"""Collect every in-body ``memory_store`` violation, plus any examples.
|
|
472
|
-
|
|
473
|
-
Returns ``(violations, examples)`` so the caller reports all of them in one
|
|
474
|
-
message instead of returning on the first problem it happens to notice.
|
|
475
|
-
"""
|
|
476
|
-
violations: list[str] = []
|
|
477
|
-
examples: list[str] = []
|
|
478
|
-
if not value or not value.strip():
|
|
479
|
-
violations.append("value is required and must be a non-empty string")
|
|
480
|
-
if metadata and metadata != "{}":
|
|
481
|
-
try:
|
|
482
|
-
json.loads(metadata)
|
|
483
|
-
except (json.JSONDecodeError, TypeError, ValueError) as exc:
|
|
484
|
-
violations.append(
|
|
485
|
-
"metadata must be a JSON object encoded as a valid JSON string "
|
|
486
|
-
f"(got invalid JSON: {exc})"
|
|
487
|
-
)
|
|
488
|
-
examples.append(METADATA_EXAMPLE)
|
|
489
|
-
return violations, examples
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
def _format_store_violations(violations: list[str], examples: list[str]) -> str:
|
|
493
|
-
"""Render stored-error text: one line per violation, then one example block."""
|
|
494
|
-
lines = [f"memory_store: {violation}" for violation in violations]
|
|
495
|
-
if len(violations) > 1:
|
|
496
|
-
lines.insert(0, f"memory_store: {len(violations)} invalid arguments")
|
|
497
|
-
deduped = list(dict.fromkeys(examples))
|
|
498
|
-
if deduped:
|
|
499
|
-
lines.append("example: " + " ".join(deduped))
|
|
500
|
-
return "\n".join(lines)
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
@mcp.tool(
|
|
504
|
-
description="Store a memory entry. The FTS5 index is updated automatically "
|
|
505
|
-
"by database trigger. Returns the entry ID and status. "
|
|
506
|
-
"metadata is a JSON object encoded as a STRING (not an object) and value "
|
|
507
|
-
"must be non-empty; every invalid argument is reported together in one "
|
|
508
|
-
f"message. Example: {METADATA_EXAMPLE}",
|
|
509
|
-
)
|
|
510
|
-
def memory_store(
|
|
511
|
-
value: str = "",
|
|
512
|
-
namespace: str = "default",
|
|
513
|
-
key: str | None = None,
|
|
514
|
-
metadata: Annotated[
|
|
515
|
-
str,
|
|
516
|
-
BeforeValidator(_metadata_must_be_json_string),
|
|
517
|
-
Field(
|
|
518
|
-
default="{}",
|
|
519
|
-
description="JSON object encoded as a STRING, not an object. "
|
|
520
|
-
'Example: \'{"type": "decision", "score": 0.9}\'.',
|
|
521
|
-
),
|
|
522
|
-
] = "{}",
|
|
523
|
-
) -> dict[str, Any]:
|
|
524
|
-
"""Store a value and index it for FTS5 keyword search.
|
|
525
|
-
|
|
526
|
-
Args:
|
|
527
|
-
value: Text content to store (required, non-empty).
|
|
528
|
-
namespace: Namespace for isolation (default: "default").
|
|
529
|
-
key: Optional unique key within namespace.
|
|
530
|
-
metadata: Optional JSON object encoded as a string.
|
|
531
|
-
|
|
532
|
-
Returns:
|
|
533
|
-
Dict with id, namespace, key, status.
|
|
534
|
-
"""
|
|
535
|
-
violations, examples = _collect_store_violations(value, metadata)
|
|
536
|
-
if violations:
|
|
537
|
-
return {"error": _format_store_violations(violations, examples)}
|
|
538
|
-
|
|
539
|
-
value = value.strip()
|
|
540
|
-
db = _get_conn()
|
|
541
|
-
now = _now_iso()
|
|
542
|
-
|
|
543
|
-
metadata_str = metadata if metadata else "{}"
|
|
544
|
-
|
|
545
|
-
try:
|
|
546
|
-
cur = db.execute(
|
|
547
|
-
"""INSERT INTO memories (namespace, key, value, metadata,
|
|
548
|
-
created_at, updated_at)
|
|
549
|
-
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
550
|
-
[namespace, key, value, metadata_str, now, now],
|
|
551
|
-
)
|
|
552
|
-
entry_id = cur.lastrowid
|
|
553
|
-
db.commit()
|
|
554
|
-
except sqlite3.IntegrityError as e:
|
|
555
|
-
db.rollback()
|
|
556
|
-
return {"error": f"Duplicate key or constraint violation: {e}"}
|
|
557
|
-
except Exception as e:
|
|
558
|
-
db.rollback()
|
|
559
|
-
return {"error": f"Failed to store memory: {e}"}
|
|
560
|
-
|
|
561
|
-
return {"id": entry_id, "namespace": namespace, "key": key, "status": "stored"}
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
@mcp.tool(
|
|
565
|
-
description="Lexical keyword search across memories using SQLite FTS5 "
|
|
566
|
-
"BM25 ranking. Stopwords are ignored and terms of 4+ characters are "
|
|
567
|
-
"prefix-matched, so a query must share a token with the stored text — "
|
|
568
|
-
"there is no semantic/vector retrieval. Optional decay_days applies a "
|
|
569
|
-
"freshness half-life (2^(-days/decay_days)) so recent entries rank "
|
|
570
|
-
"higher; default None keeps the raw BM25 order.",
|
|
571
|
-
)
|
|
572
|
-
def memory_search(
|
|
573
|
-
query: str,
|
|
574
|
-
namespace: str | None = None,
|
|
575
|
-
top_k: int = 5,
|
|
576
|
-
decay_days: float | None = None,
|
|
577
|
-
) -> list[dict[str, Any]]:
|
|
578
|
-
"""Search memories with FTS5 BM25.
|
|
579
|
-
|
|
580
|
-
Args:
|
|
581
|
-
query: Search query text.
|
|
582
|
-
namespace: Optional namespace filter.
|
|
583
|
-
top_k: Maximum results (default 5, max 50).
|
|
584
|
-
decay_days: Optional freshness half-life in days. When set, BM25
|
|
585
|
-
scores are multiplied by ``2^(-days_since_created/decay_days)``
|
|
586
|
-
so older entries rank lower. Default None = no decay.
|
|
587
|
-
|
|
588
|
-
Returns:
|
|
589
|
-
List of memory entries with a ``score`` (BM25, higher is better,
|
|
590
|
-
freshness-decayed when ``decay_days`` is set) and parsed metadata.
|
|
591
|
-
"""
|
|
592
|
-
if not query or not query.strip():
|
|
593
|
-
return []
|
|
594
|
-
|
|
595
|
-
top_k = max(1, min(50, int(top_k)))
|
|
596
|
-
db = _get_conn()
|
|
597
|
-
fts_query = _build_fts_query(query)
|
|
598
|
-
if not fts_query:
|
|
599
|
-
return []
|
|
600
|
-
|
|
601
|
-
try:
|
|
602
|
-
params: list[Any] = [fts_query]
|
|
603
|
-
namespace_clause = ""
|
|
604
|
-
if namespace:
|
|
605
|
-
namespace_clause = " AND namespace = ?"
|
|
606
|
-
params.append(namespace)
|
|
607
|
-
# Over-fetch 2x: freshness decay can promote a candidate that BM25
|
|
608
|
-
# ranked outside top_k, and ranking happens after the fetch.
|
|
609
|
-
params.append(top_k * 2)
|
|
610
|
-
# ``rank`` is BM25 negated by FTS5 (lower = better), so -rank is the
|
|
611
|
-
# relevance score. It is selected explicitly so the value is available
|
|
612
|
-
# for scoring rather than only for ordering.
|
|
613
|
-
rows = db.execute(
|
|
614
|
-
f"""SELECT rowid, -rank AS bm25 FROM memories_fts
|
|
615
|
-
WHERE memories_fts MATCH ?{namespace_clause}
|
|
616
|
-
ORDER BY rank LIMIT ?""",
|
|
617
|
-
params,
|
|
618
|
-
).fetchall()
|
|
619
|
-
hits = [(r["rowid"], r["bm25"]) for r in rows]
|
|
620
|
-
except Exception:
|
|
621
|
-
return []
|
|
622
|
-
|
|
623
|
-
if not hits:
|
|
624
|
-
return []
|
|
625
|
-
|
|
626
|
-
candidate_ids = [doc_id for doc_id, _ in hits]
|
|
627
|
-
created_at_map = (
|
|
628
|
-
_fetch_created_at_map(db, candidate_ids)
|
|
629
|
-
if decay_days is not None and decay_days > 0
|
|
630
|
-
else {}
|
|
631
|
-
)
|
|
632
|
-
ranked = _score_hits(hits, top_k, created_at_map, decay_days)
|
|
633
|
-
|
|
634
|
-
results: list[dict[str, Any]] = []
|
|
635
|
-
if ranked:
|
|
636
|
-
# 5. Fetch full entries
|
|
637
|
-
id_list = [doc_id for doc_id, _ in ranked]
|
|
638
|
-
score_map = {doc_id: score for doc_id, score in ranked}
|
|
639
|
-
|
|
640
|
-
try:
|
|
641
|
-
placeholders = ",".join("?" * len(id_list))
|
|
642
|
-
rows = db.execute(
|
|
643
|
-
f"""SELECT id, namespace, key, value, metadata, created_at
|
|
644
|
-
FROM memories WHERE id IN ({placeholders})""",
|
|
645
|
-
id_list,
|
|
646
|
-
).fetchall()
|
|
647
|
-
except Exception:
|
|
648
|
-
return []
|
|
649
|
-
|
|
650
|
-
# Preserve ranking order
|
|
651
|
-
row_map = {r["id"]: r for r in rows}
|
|
652
|
-
for doc_id in id_list:
|
|
653
|
-
row = row_map.get(doc_id)
|
|
654
|
-
if row is None:
|
|
655
|
-
continue
|
|
656
|
-
entry = dict(row)
|
|
657
|
-
entry = _parse_metadata(entry)
|
|
658
|
-
entry["score"] = round(score_map.get(doc_id, 0.0), 4)
|
|
659
|
-
results.append(entry)
|
|
660
|
-
|
|
661
|
-
return results
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
@mcp.tool(
|
|
665
|
-
description="Recall a specific memory entry by its key within a namespace. "
|
|
666
|
-
"Returns the full entry including parsed metadata.",
|
|
667
|
-
)
|
|
668
|
-
def memory_recall(
|
|
669
|
-
key: str,
|
|
670
|
-
namespace: str = "default",
|
|
671
|
-
) -> dict[str, Any] | None:
|
|
672
|
-
"""Exact-match lookup by namespace + key.
|
|
673
|
-
|
|
674
|
-
Args:
|
|
675
|
-
key: The unique key of the entry.
|
|
676
|
-
namespace: Namespace scope (default: "default").
|
|
677
|
-
|
|
678
|
-
Returns:
|
|
679
|
-
The memory entry dict, or None if not found.
|
|
680
|
-
"""
|
|
681
|
-
if not key or not key.strip():
|
|
682
|
-
return None
|
|
683
|
-
|
|
684
|
-
db = _get_conn()
|
|
685
|
-
row = db.execute(
|
|
686
|
-
"SELECT id, namespace, key, value, metadata, created_at, updated_at "
|
|
687
|
-
"FROM memories WHERE namespace = ? AND key = ?",
|
|
688
|
-
[namespace, key.strip()],
|
|
689
|
-
).fetchone()
|
|
690
|
-
|
|
691
|
-
if row is None:
|
|
692
|
-
return None
|
|
693
|
-
|
|
694
|
-
entry = _dict_from_row(row)
|
|
695
|
-
return _parse_metadata(entry)
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
@mcp.tool(
|
|
699
|
-
description="Delete a memory entry by ID or by key. "
|
|
700
|
-
"The FTS5 index entry is removed automatically by trigger.",
|
|
701
|
-
)
|
|
702
|
-
def memory_forget(
|
|
703
|
-
id: int | None = None,
|
|
704
|
-
key: str | None = None,
|
|
705
|
-
namespace: str = "default",
|
|
706
|
-
) -> dict[str, Any]:
|
|
707
|
-
"""Delete a memory entry and its FTS5 index entry.
|
|
708
|
-
|
|
709
|
-
Provide either ``id`` (exact rowid) or ``key`` (within namespace)
|
|
710
|
-
to identify the entry. The FTS sync trigger handles index cleanup.
|
|
711
|
-
|
|
712
|
-
Args:
|
|
713
|
-
id: Exact row ID of the entry to delete.
|
|
714
|
-
key: Key of the entry to delete (requires namespace).
|
|
715
|
-
namespace: Namespace scope when using key (default: "default").
|
|
716
|
-
|
|
717
|
-
Returns:
|
|
718
|
-
Dict with deleted status and entry identifier.
|
|
719
|
-
"""
|
|
720
|
-
if id is not None:
|
|
721
|
-
identifier = id
|
|
722
|
-
col = "id"
|
|
723
|
-
params: list[Any] = [id]
|
|
724
|
-
elif key and key.strip():
|
|
725
|
-
identifier = key
|
|
726
|
-
col = "key"
|
|
727
|
-
params = [key.strip(), namespace]
|
|
728
|
-
sql = "DELETE FROM memories WHERE key = ? AND namespace = ?"
|
|
729
|
-
else:
|
|
730
|
-
return {"error": "Provide either id or key"}
|
|
731
|
-
|
|
732
|
-
db = _get_conn()
|
|
733
|
-
try:
|
|
734
|
-
if col == "id":
|
|
735
|
-
cur = db.execute("DELETE FROM memories WHERE id = ?", [id])
|
|
736
|
-
else:
|
|
737
|
-
cur = db.execute(sql, params)
|
|
738
|
-
db.commit()
|
|
739
|
-
|
|
740
|
-
if cur.rowcount == 0:
|
|
741
|
-
return {"deleted": False, "error": "Entry not found"}
|
|
742
|
-
|
|
743
|
-
return {"deleted": True, col: identifier, "namespace": namespace}
|
|
744
|
-
except Exception as e:
|
|
745
|
-
db.rollback()
|
|
746
|
-
return {"error": f"Failed to delete: {e}"}
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
@mcp.tool(
|
|
750
|
-
description="List memory entries chronologically with optional "
|
|
751
|
-
"namespace and key-prefix filters.",
|
|
752
|
-
)
|
|
753
|
-
def memory_list(
|
|
754
|
-
namespace: str | None = None,
|
|
755
|
-
prefix: str = "",
|
|
756
|
-
limit: int = 50,
|
|
757
|
-
) -> list[dict[str, Any]]:
|
|
758
|
-
"""List memory entries, newest first.
|
|
759
|
-
|
|
760
|
-
Args:
|
|
761
|
-
namespace: Optional namespace filter.
|
|
762
|
-
prefix: Optional key prefix filter.
|
|
763
|
-
limit: Maximum entries (default 50, max 500).
|
|
764
|
-
|
|
765
|
-
Returns:
|
|
766
|
-
List of memory entries sorted by created_at descending.
|
|
767
|
-
"""
|
|
768
|
-
limit = max(1, min(500, int(limit)))
|
|
769
|
-
db = _get_conn()
|
|
770
|
-
|
|
771
|
-
conditions: list[str] = []
|
|
772
|
-
params: list[Any] = []
|
|
773
|
-
|
|
774
|
-
if namespace:
|
|
775
|
-
conditions.append("namespace = ?")
|
|
776
|
-
params.append(namespace)
|
|
777
|
-
|
|
778
|
-
if prefix:
|
|
779
|
-
conditions.append("key LIKE ?")
|
|
780
|
-
params.append(f"{prefix}%")
|
|
781
|
-
|
|
782
|
-
where = " AND ".join(conditions) if conditions else "1"
|
|
783
|
-
|
|
784
|
-
try:
|
|
785
|
-
rows = db.execute(
|
|
786
|
-
f"SELECT id, namespace, key, value, metadata, created_at "
|
|
787
|
-
f"FROM memories WHERE {where} ORDER BY created_at DESC LIMIT ?",
|
|
788
|
-
[*params, limit],
|
|
789
|
-
).fetchall()
|
|
790
|
-
except Exception as e:
|
|
791
|
-
return [{"error": f"List failed: {e}"}]
|
|
792
|
-
|
|
793
|
-
results = []
|
|
794
|
-
for row in rows:
|
|
795
|
-
entry = _dict_from_row(row)
|
|
796
|
-
results.append(_parse_metadata(entry))
|
|
797
|
-
|
|
798
|
-
return results
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
@mcp.tool(
|
|
802
|
-
description="Memory database statistics: total entries, per-namespace "
|
|
803
|
-
"breakdown, and file size on disk.",
|
|
804
|
-
)
|
|
805
|
-
def memory_stats() -> dict[str, Any]:
|
|
806
|
-
"""Return aggregate statistics about the memory database.
|
|
807
|
-
|
|
808
|
-
Includes total count, namespace breakdown, and file size on disk.
|
|
809
|
-
|
|
810
|
-
Returns:
|
|
811
|
-
Dict with count, namespaces, and storage info.
|
|
812
|
-
"""
|
|
813
|
-
db = _get_conn()
|
|
814
|
-
|
|
815
|
-
stats: dict[str, Any] = {"status": "ok"}
|
|
816
|
-
|
|
817
|
-
try:
|
|
818
|
-
stats["total_entries"] = db.execute(
|
|
819
|
-
"SELECT COUNT(*) AS c FROM memories"
|
|
820
|
-
).fetchone()["c"]
|
|
821
|
-
except Exception:
|
|
822
|
-
stats["total_entries"] = 0
|
|
823
|
-
|
|
824
|
-
try:
|
|
825
|
-
ns_rows = db.execute(
|
|
826
|
-
"SELECT namespace, COUNT(*) AS c FROM memories GROUP BY namespace "
|
|
827
|
-
"ORDER BY c DESC"
|
|
828
|
-
).fetchall()
|
|
829
|
-
stats["namespaces"] = [
|
|
830
|
-
{"namespace": r["namespace"], "count": r["c"]} for r in ns_rows
|
|
831
|
-
]
|
|
832
|
-
except Exception:
|
|
833
|
-
stats["namespaces"] = []
|
|
834
|
-
|
|
835
|
-
try:
|
|
836
|
-
db_size = DB_PATH.stat().st_size if DB_PATH.exists() else 0
|
|
837
|
-
stats["db_size_bytes"] = db_size
|
|
838
|
-
for unit in ("B", "KB", "MB", "GB"):
|
|
839
|
-
if db_size < _BYTE_UNIT:
|
|
840
|
-
stats["db_size_human"] = f"{db_size:.2f} {unit}"
|
|
841
|
-
break
|
|
842
|
-
db_size /= 1024.0
|
|
843
|
-
else:
|
|
844
|
-
stats["db_size_human"] = f"{db_size:.2f} TB"
|
|
845
|
-
except Exception:
|
|
846
|
-
stats["db_size_bytes"] = 0
|
|
847
|
-
stats["db_size_human"] = "unknown"
|
|
848
|
-
|
|
849
|
-
return stats
|
|
850
13
|
|
|
14
|
+
_CANONICAL_MCP_DIR = Path(__file__).resolve().parents[1] / "src" / "mcp"
|
|
15
|
+
sys.path.insert(0, str(_CANONICAL_MCP_DIR))
|
|
16
|
+
try:
|
|
17
|
+
import memory_mcp as _canonical_memory_mcp
|
|
18
|
+
finally:
|
|
19
|
+
sys.path.remove(str(_CANONICAL_MCP_DIR))
|
|
851
20
|
|
|
852
|
-
|
|
21
|
+
mcp = _canonical_memory_mcp.mcp
|
|
853
22
|
|
|
854
23
|
if __name__ == "__main__":
|
|
855
24
|
mcp.run()
|