coldmemory 0.3.6__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- coldmemory/__init__.py +15 -0
- coldmemory/__main__.py +135 -0
- coldmemory/adversarial_ingest_bench.py +137 -0
- coldmemory/bench_v1.py +792 -0
- coldmemory/benchmark.py +292 -0
- coldmemory/cartridge_spec.py +559 -0
- coldmemory/citations.py +27 -0
- coldmemory/disk_index.py +3553 -0
- coldmemory/hermes_provider.py +135 -0
- coldmemory/hooks_snippet.py +161 -0
- coldmemory/hybrid.py +430 -0
- coldmemory/ingest.py +742 -0
- coldmemory/ingest_policy.py +46 -0
- coldmemory/init_cmd.py +2279 -0
- coldmemory/ledger.py +417 -0
- coldmemory/mcp_server.py +677 -0
- coldmemory/multihop_retriever.py +429 -0
- coldmemory/push.py +351 -0
- coldmemory/redact.py +133 -0
- coldmemory/scope_keys.py +95 -0
- coldmemory/sessions.py +236 -0
- coldmemory/verifier.py +1696 -0
- coldmemory-0.3.6.data/data/share/coldmemory/integrations/hermes/coldmemory/__init__.py +10 -0
- coldmemory-0.3.6.data/data/share/coldmemory/integrations/hermes/coldmemory/plugin.yaml +3 -0
- coldmemory-0.3.6.data/data/share/coldmemory/skills/coldmemory/SKILL.md +53 -0
- coldmemory-0.3.6.dist-info/METADATA +320 -0
- coldmemory-0.3.6.dist-info/RECORD +31 -0
- coldmemory-0.3.6.dist-info/WHEEL +5 -0
- coldmemory-0.3.6.dist-info/entry_points.txt +5 -0
- coldmemory-0.3.6.dist-info/licenses/LICENSE +202 -0
- coldmemory-0.3.6.dist-info/top_level.txt +1 -0
coldmemory/benchmark.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
"""CPU benchmark on a synthetic company. It measures what evidence reaches an agent, not an LLM's answers."""
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import os
|
|
8
|
+
import shutil
|
|
9
|
+
import statistics
|
|
10
|
+
import subprocess
|
|
11
|
+
import sys
|
|
12
|
+
import tempfile
|
|
13
|
+
import time
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
from .cartridge_spec import compile_bundle
|
|
18
|
+
from .ingest import SUFFIXES, parse_source
|
|
19
|
+
from .verifier import NO_MATCH, WEAK, flat, terms
|
|
20
|
+
|
|
21
|
+
PROJECT = Path(__file__).resolve().parent.parent
|
|
22
|
+
FIXTURES = PROJECT / "tests/fixtures"
|
|
23
|
+
KINDS = {"engineering-vault": "obsidian", "operations-vault": "obsidian", "company-wiki": "notion",
|
|
24
|
+
"atlas-service": "repo", "beacon-app": "repo"}
|
|
25
|
+
CANARIES = {
|
|
26
|
+
"AWS_KEY": "AKIA" + "Q7ZP4MXW2LTN8VRB",
|
|
27
|
+
"AWS_SECRET": base64.b64encode(hashlib.sha256(b"synthetic aws canary").digest()[:30]).decode("ascii"),
|
|
28
|
+
"PASSWORD": "Fjord-4471-lamp",
|
|
29
|
+
"DB_PASSWORD": "cobalt7Heron",
|
|
30
|
+
"SLACK_HOOK": "https://hooks.slack.com/" + "services/T0CANARY0/B0CANARY0/q8Zr2Lw6Xc4Vb1Nm",
|
|
31
|
+
"BEARER": "canary." + "7fQ2mZx9LkT4vB8nW3rY",
|
|
32
|
+
"WIFI": "otter-harbour-93",
|
|
33
|
+
"GITHUB": "ghp_" + "c4N4rY7Zq2Lm9Xv5Bn8Rs3Yd6Hc1Jf0Gp4Ka",
|
|
34
|
+
"PRIVATE_KEY": "synthetic private key body",
|
|
35
|
+
"ENV": "sk_live_" + "c4N4rY51HzQ8tW2pL6",
|
|
36
|
+
}
|
|
37
|
+
EDITS = (
|
|
38
|
+
("Decisions/Travel Time Cache.md", "two hours at night", "five hours at night",
|
|
39
|
+
"How long do we cache travel times at night?", "What did we decide in Travel Time Cache?"),
|
|
40
|
+
("Areas/Release Train.md", "every Tuesday at eleven", "every Thursday at nine",
|
|
41
|
+
"When does the release train leave?", "What is Release Train?"),
|
|
42
|
+
("Decisions/Payment Retries.md", "days three, seven and fourteen", "days two, five and ten",
|
|
43
|
+
"On which days do we retry failed payments?", "What did we decide in Payment Retries?"),
|
|
44
|
+
)
|
|
45
|
+
DELETED = ("Areas/Glossary.md", "What is a dead leg?", "What is Glossary?")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def materialize(target):
|
|
49
|
+
"""Copy the fixture, plant canary secrets and make its repos real git repos. Return the source specs."""
|
|
50
|
+
root = Path(target) / "synthetic_company"
|
|
51
|
+
shutil.copytree(FIXTURES / "synthetic_company", root)
|
|
52
|
+
values = CANARIES | {"PRIVATE_KEY": "-----BEGIN " + f"PRIVATE KEY-----\n{CANARIES['PRIVATE_KEY']}\n"
|
|
53
|
+
"-----END " + "PRIVATE KEY-----",
|
|
54
|
+
"DB_URL": "postgres:" + f"//harbor:{CANARIES['DB_PASSWORD']}@db.internal:5432/events"}
|
|
55
|
+
for path in documents(root):
|
|
56
|
+
text = path.read_text()
|
|
57
|
+
for name, value in values.items():
|
|
58
|
+
text = text.replace("{{" + name + "}}", value)
|
|
59
|
+
path.write_text(text)
|
|
60
|
+
(root / "atlas-service/.env").write_text(f"PAYMENTS={CANARIES['ENV']}\n")
|
|
61
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
|
62
|
+
for name, kind in KINDS.items():
|
|
63
|
+
if kind == "repo":
|
|
64
|
+
for command in (["init", "-q"], ["add", "-f", "."]):
|
|
65
|
+
subprocess.run(["git", "-C", str(root / name), *command], check=True, capture_output=True, env=env)
|
|
66
|
+
return root, [f"{kind}:{root / name}" for name, kind in KINDS.items()]
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def documents(root):
|
|
70
|
+
return sorted(p for p in root.rglob("*") if p.is_file() and p.suffix in SUFFIXES and ".git" not in p.parts)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class Client:
|
|
74
|
+
"""A small MCP client that talks to the real server process."""
|
|
75
|
+
|
|
76
|
+
def __init__(self, store, *options):
|
|
77
|
+
env = os.environ | {"PYTHONPATH": str(PROJECT), "PYTHONDONTWRITEBYTECODE": "1"}
|
|
78
|
+
self.process = subprocess.Popen(
|
|
79
|
+
[sys.executable, "-m", "coldmemory.mcp_server", "--store", str(store), "--local-unsigned", *options],
|
|
80
|
+
stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True, env=env)
|
|
81
|
+
self.count = 0
|
|
82
|
+
self.info = self.request("initialize", protocolVersion="2025-06-18", capabilities={},
|
|
83
|
+
clientInfo={"name": "test", "version": "0"})
|
|
84
|
+
self.send({"jsonrpc": "2.0", "method": "notifications/initialized"})
|
|
85
|
+
|
|
86
|
+
def send(self, message):
|
|
87
|
+
self.process.stdin.write(json.dumps(message) + "\n")
|
|
88
|
+
self.process.stdin.flush()
|
|
89
|
+
|
|
90
|
+
def request(self, method, **params):
|
|
91
|
+
self.count += 1
|
|
92
|
+
self.send({"jsonrpc": "2.0", "id": self.count, "method": method, "params": params})
|
|
93
|
+
response = json.loads(self.process.stdout.readline())
|
|
94
|
+
if response["id"] != self.count:
|
|
95
|
+
raise RuntimeError("response id does not match the request")
|
|
96
|
+
return response["result"]
|
|
97
|
+
|
|
98
|
+
def call(self, name, **arguments):
|
|
99
|
+
result = self.request("tools/call", name=name, arguments=arguments)
|
|
100
|
+
return result["content"][0]["text"]
|
|
101
|
+
|
|
102
|
+
def __enter__(self):
|
|
103
|
+
return self
|
|
104
|
+
|
|
105
|
+
def __exit__(self, *_):
|
|
106
|
+
self.process.stdin.close()
|
|
107
|
+
self.process.wait(timeout=10)
|
|
108
|
+
self.process.stdout.close()
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class NaiveRag:
|
|
112
|
+
"""Raw 800-character chunks with 100 characters of overlap, ranked by BM25. Returns the top five."""
|
|
113
|
+
|
|
114
|
+
def __init__(self, texts, root):
|
|
115
|
+
self.chunks = [f"{name}\n{text[start:start + 800]}" for name, text in texts
|
|
116
|
+
for start in range(0, max(1, len(text) - 100), 700)]
|
|
117
|
+
self.counts = [Counter(terms(chunk.replace(str(root), ""))) for chunk in self.chunks]
|
|
118
|
+
self.average = sum(c.total() for c in self.counts) / len(self.counts)
|
|
119
|
+
self.found = Counter(term for counts in self.counts for term in counts)
|
|
120
|
+
|
|
121
|
+
def ask(self, query):
|
|
122
|
+
def score(counts):
|
|
123
|
+
return sum(
|
|
124
|
+
math.log(1 + (len(self.counts) - self.found[t] + 0.5) / (self.found[t] + 0.5)) * counts[t] * 2.2
|
|
125
|
+
/ (counts[t] + 1.2 * (0.25 + 0.75 * counts.total() / self.average)) for t in sorted(set(terms(query))))
|
|
126
|
+
order = sorted(range(len(self.chunks)), key=lambda i: (-score(self.counts[i]), i))
|
|
127
|
+
return "\n\n".join(self.chunks[i] for i in order[:5])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def tokens(text):
|
|
131
|
+
return math.ceil(len(text) / 4)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def leaks(text):
|
|
135
|
+
return sorted(name for name, value in CANARIES.items() if value in text)
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def grade(cases, answers, root, setup, extra=""):
|
|
139
|
+
"""Score one arm. `setup` is the text an agent pays for once per session."""
|
|
140
|
+
result = Counter()
|
|
141
|
+
for case, answer in zip(cases, answers):
|
|
142
|
+
kind = case["kind"]
|
|
143
|
+
seen = flat(setup + "\n" + answer)
|
|
144
|
+
result[f"{kind} total"] += 1
|
|
145
|
+
if kind == "no-answer":
|
|
146
|
+
result["abstained"] += answer.startswith(NO_MATCH)
|
|
147
|
+
result["warned"] += answer.startswith((NO_MATCH, WEAK))
|
|
148
|
+
continue
|
|
149
|
+
result["answerable"] += 1
|
|
150
|
+
file = str(root / case["key"])
|
|
151
|
+
evidence = case["evidence"] in seen
|
|
152
|
+
result["file"] += flat(file) in seen
|
|
153
|
+
result["evidence"] += evidence
|
|
154
|
+
result["doubted"] += answer.startswith((NO_MATCH, WEAK))
|
|
155
|
+
if "old" in case:
|
|
156
|
+
group = "unmarked" if kind == "stale-unmarked" else "marked"
|
|
157
|
+
result[f"{group} total"] += 1
|
|
158
|
+
result[f"{group} caught"] += evidence and case["old_text"] not in seen
|
|
159
|
+
|
|
160
|
+
def short(text):
|
|
161
|
+
return text.replace(str(root), "/memory")
|
|
162
|
+
|
|
163
|
+
per_question = statistics.mean(tokens(short(a)) for a in answers)
|
|
164
|
+
once = tokens(short(setup)) if setup else 0
|
|
165
|
+
found = leaks("\n".join([setup, *answers, extra]))
|
|
166
|
+
return dict(result) | {
|
|
167
|
+
"setup_tokens": once, "question_tokens": round(per_question, 1), "one_question": round(once + per_question),
|
|
168
|
+
"ten_questions": round(once + 10 * per_question), "leaked": found}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def live_edits(store, root):
|
|
172
|
+
"""Check edits and deletes made after compile. The first checks prove that recall was shown beforehand."""
|
|
173
|
+
vault, result = root / "engineering-vault", Counter()
|
|
174
|
+
recalls = [edit[4] for edit in EDITS] + [DELETED[2]]
|
|
175
|
+
with Client(store, "--backend", "mock") as client:
|
|
176
|
+
def shown(query):
|
|
177
|
+
return "Synthesized Context (mock recall" in client.call("memory_ask", query=query, max_words=400)
|
|
178
|
+
|
|
179
|
+
result["recall shown before edits"] = sum(map(shown, recalls))
|
|
180
|
+
for name, old, new, _, _ in EDITS:
|
|
181
|
+
path = vault / name
|
|
182
|
+
text = path.read_text()
|
|
183
|
+
if old not in text:
|
|
184
|
+
raise RuntimeError(f"{name} does not contain the text to edit")
|
|
185
|
+
path.write_text(text.replace(old, new))
|
|
186
|
+
(vault / DELETED[0]).unlink()
|
|
187
|
+
for _, old, new, query, _ in EDITS:
|
|
188
|
+
answer = flat(client.call("memory_ask", query=query))
|
|
189
|
+
result["new text returned"] += new in answer and old not in answer and "changed since compile" in answer
|
|
190
|
+
result["recall shown after edits"] = sum(map(shown, recalls))
|
|
191
|
+
result["deleted file cited"] = int(DELETED[0] in client.call("memory_ask", query=DELETED[1]))
|
|
192
|
+
status = client.call("memory_status")
|
|
193
|
+
result["status reports changes"] = int("changed (3)" in status and "deleted (1)" in status)
|
|
194
|
+
return dict(result)
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def run():
|
|
198
|
+
sets = {name: json.loads((FIXTURES / f"benchmark_{name}.json").read_text()) for name in ("cases", "holdout")}
|
|
199
|
+
queries = [case["query"] for cases in sets.values() for case in cases]
|
|
200
|
+
results, times = {name: {} for name in sets}, {}
|
|
201
|
+
|
|
202
|
+
def score(label, answers, setup, extra=""):
|
|
203
|
+
start = 0
|
|
204
|
+
for name, cases in sets.items():
|
|
205
|
+
part = answers[start:start + len(cases)]
|
|
206
|
+
start += len(cases)
|
|
207
|
+
results[name][label] = grade(cases, part, root, setup, extra)
|
|
208
|
+
|
|
209
|
+
with tempfile.TemporaryDirectory() as work:
|
|
210
|
+
root, specs = materialize(work)
|
|
211
|
+
store = Path(work) / "store"
|
|
212
|
+
bundle = compile_bundle(store, "company", [parse_source(s) for s in specs])
|
|
213
|
+
compiled = "\n".join(p.read_text() for p in sorted(bundle.path.iterdir()))
|
|
214
|
+
|
|
215
|
+
texts = [(str(path), path.read_text()) for path in documents(root)]
|
|
216
|
+
full = "\n\n".join(f"{name}\n{text}" for name, text in texts)
|
|
217
|
+
rag = NaiveRag(texts, root)
|
|
218
|
+
score("Full context", [""] * len(queries), full)
|
|
219
|
+
score("Naive RAG (BM25, top 5)", [rag.ask(q) for q in queries], "")
|
|
220
|
+
for label, backend in (("ColdMemory (disk only)", "disk"), ("ColdMemory (disk + mock recall)", "mock")):
|
|
221
|
+
began = time.perf_counter()
|
|
222
|
+
with Client(store, "--backend", backend) as client:
|
|
223
|
+
times[f"{backend} start"] = [time.perf_counter() - began]
|
|
224
|
+
setup = client.info["instructions"] + json.dumps(client.request("tools/list")["tools"])
|
|
225
|
+
answers, spent = [], []
|
|
226
|
+
for query in queries:
|
|
227
|
+
began = time.perf_counter()
|
|
228
|
+
answers.append(client.call("memory_ask", query=query))
|
|
229
|
+
spent.append(time.perf_counter() - began)
|
|
230
|
+
times[f"{backend} first ask"], times[f"{backend} later asks"] = spent[:1], spent[1:]
|
|
231
|
+
other = [client.call("memory_locate", topic=q) for q in queries]
|
|
232
|
+
other += [client.call("memory_status"), client.call("memory_list_cartridges")]
|
|
233
|
+
score(label, answers, setup, "\n".join([compiled, *other]))
|
|
234
|
+
shown = sum("Synthesized Context (" in a for a in answers)
|
|
235
|
+
edits = live_edits(store, root)
|
|
236
|
+
metrics = {"corpus": {"files": len(texts), "notes": bundle.manifest["counts"]["notes"],
|
|
237
|
+
"train_rows": bundle.manifest["counts"]["train"], "val_rows": bundle.manifest["counts"]["val"],
|
|
238
|
+
"canaries": len(CANARIES)},
|
|
239
|
+
"sets": results, "live_edits": edits, "mock_recall_shown": shown, "questions": len(queries)}
|
|
240
|
+
return metrics, times
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
def report(metrics, times):
|
|
244
|
+
corpus = metrics["corpus"]
|
|
245
|
+
lines = [
|
|
246
|
+
f"Corpus: {corpus['files']} documents, {corpus['canaries']} planted secrets, "
|
|
247
|
+
f"{corpus['train_rows']} train rows and {corpus['val_rows']} validation rows.",
|
|
248
|
+
"Token counts are estimates (characters / 4, rounded up). They exclude the agent's tool-call text."]
|
|
249
|
+
titles = {"cases": "Development questions (used to fix the search)",
|
|
250
|
+
"holdout": "Holdout questions (written before the fixes ran, then not tuned)"}
|
|
251
|
+
|
|
252
|
+
for name, arms in metrics["sets"].items():
|
|
253
|
+
def row(label, value):
|
|
254
|
+
return f"| {label} | " + " | ".join(str(value(arm)) for arm in arms.values()) + " |"
|
|
255
|
+
|
|
256
|
+
def part(done, total):
|
|
257
|
+
return lambda arm: f"{arm.get(done, 0)}/{arm.get(total, 0)}"
|
|
258
|
+
|
|
259
|
+
lines += [
|
|
260
|
+
"", f"### {titles[name]}", "", "| Measure | " + " | ".join(arms) + " |", "|---|" + "---:|" * len(arms),
|
|
261
|
+
row("Setup tokens per session", lambda a: a["setup_tokens"]),
|
|
262
|
+
row("Mean tokens per question", lambda a: a["question_tokens"]),
|
|
263
|
+
row("Total tokens, 1 question", lambda a: a["one_question"]),
|
|
264
|
+
row("Total tokens, 10 questions", lambda a: a["ten_questions"]),
|
|
265
|
+
row("Right file reached the agent", part("file", "answerable")),
|
|
266
|
+
row("Right evidence reached the agent", part("evidence", "answerable")),
|
|
267
|
+
row("Answer exists, but said \"no match\" or \"weak match\"", part("doubted", "answerable"))]
|
|
268
|
+
if name == "cases":
|
|
269
|
+
lines += [
|
|
270
|
+
row("Marked old decisions: new one shown, old claim kept out", part("marked caught", "marked total")),
|
|
271
|
+
row("Unmarked contradictions: new one shown, old claim kept out",
|
|
272
|
+
part("unmarked caught", "unmarked total"))]
|
|
273
|
+
lines += [
|
|
274
|
+
row("No answer exists: said \"no match\"", part("abstained", "no-answer total")),
|
|
275
|
+
row("No answer exists: said \"no match\" or \"weak match\"", part("warned", "no-answer total")),
|
|
276
|
+
row("Planted secrets kept out", lambda a: f"{corpus['canaries'] - len(a['leaked'])}/{corpus['canaries']}")]
|
|
277
|
+
|
|
278
|
+
lines += [
|
|
279
|
+
"", "Edits made after compile (ColdMemory, mock recall): "
|
|
280
|
+
+ "; ".join(f"{name}: {value}" for name, value in metrics["live_edits"].items()) + ".",
|
|
281
|
+
f"Mock recall shown: {metrics['mock_recall_shown']}/{metrics['questions']} questions.",
|
|
282
|
+
"", "| Timing (real MCP process) | p50 ms | p95 ms | max ms | n |", "|---|---:|---:|---:|---:|"]
|
|
283
|
+
for name, values in times.items():
|
|
284
|
+
ordered = sorted(v * 1000 for v in values)
|
|
285
|
+
p95 = ordered[math.ceil(0.95 * len(ordered)) - 1]
|
|
286
|
+
lines.append(f"| {name} | {statistics.median(ordered):.1f} | {p95:.1f} | {ordered[-1]:.1f} | {len(ordered)} |")
|
|
287
|
+
digest = hashlib.sha256(json.dumps(metrics, sort_keys=True).encode()).hexdigest()
|
|
288
|
+
return "\n".join([*lines, "", f"Results SHA-256 without timings: `{digest}`"])
|
|
289
|
+
|
|
290
|
+
|
|
291
|
+
if __name__ == "__main__":
|
|
292
|
+
print(report(*run()))
|