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/bench_v1.py
ADDED
|
@@ -0,0 +1,792 @@
|
|
|
1
|
+
"""ColdMemory-Bench v1: a generated synthetic company, four arms and four scored question families plus token cost. CPU and stdlib only."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import ctypes
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
import os
|
|
9
|
+
import random
|
|
10
|
+
import re
|
|
11
|
+
import string
|
|
12
|
+
import subprocess
|
|
13
|
+
import sys
|
|
14
|
+
import tempfile
|
|
15
|
+
from collections import Counter, defaultdict
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
|
|
18
|
+
from .benchmark import Client, documents, tokens
|
|
19
|
+
from .cartridge_spec import compile_bundle
|
|
20
|
+
from .ingest import parse_source
|
|
21
|
+
from .redact import MARK, scrub
|
|
22
|
+
from .verifier import CONFLICT, NO_MATCH, WEAK, flat, terms
|
|
23
|
+
|
|
24
|
+
SEED = 1
|
|
25
|
+
SOURCES = {"eng-vault": "obsidian", "ops-vault": "obsidian", "wiki": "notion",
|
|
26
|
+
"ledger-repo": "repo", "router-repo": "repo"}
|
|
27
|
+
PRICE_PER_TOKEN = 4 / 1_000_000
|
|
28
|
+
NAIVE_BUDGET = 4000
|
|
29
|
+
BRIEF_WORDS = 180
|
|
30
|
+
WINDOW, STRIDE = 1024, 768
|
|
31
|
+
CHECKPOINTS = (10, 50, 100)
|
|
32
|
+
OUTPUTS = ("corpus", "questions.json", "results.json", "REPORT.md", "SHA256SUMS")
|
|
33
|
+
ARMS = ("Full context", "Naive BM25 RAG", "Tuned hybrid", "ColdMemory")
|
|
34
|
+
|
|
35
|
+
ADJECTIVES = ("Amber Basalt Cinder Delta Ember Fable Garnet Harbor Indigo Juniper Lumen Marlin Nimbus Onyx Pylon "
|
|
36
|
+
"Quarry Rook Saffron Tundra Umber Vesper Willow Yarrow Zephyr Alder Birch Coral Dune").split()
|
|
37
|
+
NOUNS = "Router Ledger Gateway Indexer Scheduler Mailer Vault Cache Broker Relay Planner Auditor Uploader Matcher".split()
|
|
38
|
+
BIRDS = "Heron Kestrel Plover Wren Osprey Finch Curlew Lark Swift Egret".split()
|
|
39
|
+
FIRST = ("Mirela Ravi Ines Tomasz Aiko Bruno Chidi Dana Esme Farid Greta Hugo Ilse Jonah Kofi Leila Mateo Nadia "
|
|
40
|
+
"Oskar Priya Quinn Rosa Sami Talia Uma Viktor Wanjiru Xavi Yusuf Zora").split()
|
|
41
|
+
LAST = "Okafor Lindqvist Moreau Petrov Tanaka Silva Adeyemi Novak Haddad Kowalski Byrne Castillo Duarte Eriksen".split()
|
|
42
|
+
PURPOSES = ("card settlements|warehouse stock levels|partner invoices|loyalty points|shipping labels|tax filings|"
|
|
43
|
+
"refund batches|catalog prices|supplier contracts|payroll exports|fraud signals|carrier rates|"
|
|
44
|
+
"gift card balances|subscription renewals|store openings|return labels|currency rates|bank statements|"
|
|
45
|
+
"delivery slots|review moderation").split("|")
|
|
46
|
+
SLANG = ("graveyard sweep|moon shovel|pickle drop|tin whistle|ghost parade|owl shift|sock drawer|biscuit tin|"
|
|
47
|
+
"lantern crawl|puddle jump|velvet hammer|mango chute|crumb trail|kettle boil|walrus nap|pebble heap|"
|
|
48
|
+
"sugar rush|toast rack|thimble race|cactus hug").split("|")
|
|
49
|
+
HOP_QUERIES = (
|
|
50
|
+
"When does the {s} kick off, who babysits it, and where do we shout if it wedges?",
|
|
51
|
+
"Tell me what o'clock the {s} fires, whose pager buzzes, and which room gets the yelling.",
|
|
52
|
+
"For the {s}: launch moment, the person holding the pager, and the place we holler.",
|
|
53
|
+
"Who minds the {s}, what time does it begin, and where do folks raise the alarm?",
|
|
54
|
+
)
|
|
55
|
+
TOPICS = (
|
|
56
|
+
("Audit Log Retention", "How many days are audit logs retained?", "Audit logs are retained for {} days.", 90, 400),
|
|
57
|
+
("Expense Approval Limit", "Above how many dollars does an expense need a director's approval?",
|
|
58
|
+
"Expenses above {} dollars need a director's approval.", 500, 1500),
|
|
59
|
+
("Deploy Freeze Window", "How many days before quarter close does the deploy freeze start?",
|
|
60
|
+
"The deploy freeze starts {} days before quarter close.", 5, 3),
|
|
61
|
+
("Laptop Refresh Cycle", "How many months between laptop refreshes?", "Laptops are refreshed every {} months.",
|
|
62
|
+
36, 48),
|
|
63
|
+
("Incident Review Deadline", "Within how many business days are incident reviews due?",
|
|
64
|
+
"Incident reviews are due within {} business days.", 5, 10),
|
|
65
|
+
("Access Review Cadence", "How many weeks apart do access reviews run?", "Access reviews run every {} weeks.",
|
|
66
|
+
12, 6),
|
|
67
|
+
("Restore Drill Cadence", "How many weeks apart are restore drills?", "Restore drills happen every {} weeks.", 8, 4),
|
|
68
|
+
("On-call Handover Time", "At what UTC time is the on-call handover?", "On-call handover happens at {} UTC.",
|
|
69
|
+
"09:00", "15:00"),
|
|
70
|
+
("Code Review Approvals", "How many approving reviews does a merge need?", "Merges need {} approving reviews.",
|
|
71
|
+
1, 2),
|
|
72
|
+
("Data Export Limit", "How many rows can a customer data export hold?",
|
|
73
|
+
"Customer data exports are capped at {} rows.", 50000, 250000),
|
|
74
|
+
("Staging Reset Day", "Which day does the staging environment reset?", "The staging environment resets every {}.",
|
|
75
|
+
"Monday", "Friday"),
|
|
76
|
+
("Support Response Target", "Within how many minutes do priority tickets get a first response?",
|
|
77
|
+
"Priority tickets get a first response within {} minutes.", 60, 30),
|
|
78
|
+
("Vendor Security Review", "How many months between vendor security reviews?",
|
|
79
|
+
"Vendor security reviews are repeated every {} months.", 24, 12),
|
|
80
|
+
("Feature Flag Expiry", "After how many days do feature flags expire?", "Feature flags expire after {} days.",
|
|
81
|
+
120, 60),
|
|
82
|
+
("Debug Log Sampling", "At what percent are debug logs sampled?", "Debug logs are sampled at {} percent.", 10, 25),
|
|
83
|
+
("Flight Booking Lead", "How many days ahead must flights be booked?", "Flights are booked at least {} days ahead.",
|
|
84
|
+
14, 21),
|
|
85
|
+
("Canary Rollout Share", "What percent of traffic does a canary rollout start at?",
|
|
86
|
+
"Canary rollouts start at {} percent of traffic.", 5, 2),
|
|
87
|
+
("Mobile Release Cadence", "How many weeks apart do mobile builds ship?", "Mobile builds ship every {} weeks.", 2, 3),
|
|
88
|
+
("Supplier Payment Terms", "Within how many days are supplier invoices paid?",
|
|
89
|
+
"Supplier invoices are paid within {} days.", 30, 45),
|
|
90
|
+
("Interview Loop Size", "How many interviews are in an engineering interview loop?",
|
|
91
|
+
"Engineering interview loops have {} interviews.", 5, 4),
|
|
92
|
+
)
|
|
93
|
+
TOPIC_KINDS = ["marked"] * 8 + ["unmarked-dated"] * 4 + ["unmarked-wording"] * 4 + ["tie"] * 4
|
|
94
|
+
FACTS = (
|
|
95
|
+
("Which health check port does {s} use?", "The health check port for {s} is {v}.",
|
|
96
|
+
lambda rng, s: str(rng.randint(8000, 8999))),
|
|
97
|
+
("Which bucket holds the logs for {s}?", "Logs for {s} go to the bucket {v}.",
|
|
98
|
+
lambda rng, s: f"qf-logs-{s.lower().replace(' ', '-')}-{rng.randint(10, 99)}"),
|
|
99
|
+
("How many replicas can {s} scale to?", "{s} scales to at most {v} replicas.",
|
|
100
|
+
lambda rng, s: str(rng.randint(12, 96))),
|
|
101
|
+
("Which dashboard tracks {s}?", "The main dashboard for {s} is {v}.", lambda rng, s: f"DASH-{rng.randint(1000, 9999)}"),
|
|
102
|
+
)
|
|
103
|
+
GROUNDING_KINDS = ["changed"] * 4 + ["shifted"] * 4 + ["moved"] * 4 + ["deleted"] * 4 + ["never"] * 4
|
|
104
|
+
MISSING = ("Granite Ferry", "Nectar Turbine", "Cobalt Kiln", "Paprika Sluice")
|
|
105
|
+
PROSE = (
|
|
106
|
+
"{s} publishes its metrics to the shared observability stack.",
|
|
107
|
+
"[[{p}]] walked through the {s} dashboards at the last planning review.",
|
|
108
|
+
"Pull requests for {s} need a green build before merge.",
|
|
109
|
+
"{t} keeps a short list of open questions about {s}.",
|
|
110
|
+
"The {s} backlog is groomed every second week by [[{p}]].",
|
|
111
|
+
"Load tests for {s} replay a copy of last month's traffic.",
|
|
112
|
+
"[[{p}]] wrote the first design notes for {s}.",
|
|
113
|
+
"Support tickets that mention {s} are tagged for {t}.",
|
|
114
|
+
"{s} reads its settings from the shared configuration service.",
|
|
115
|
+
"Error budgets for {s} are reviewed with product managers each quarter.",
|
|
116
|
+
"[[{p}]] pairs with {t} on {s} upgrades.",
|
|
117
|
+
"The {s} schema has a written migration plan in the repository.",
|
|
118
|
+
"Release notes for {s} are drafted by [[{p}]] and checked by {t}.",
|
|
119
|
+
"{s} depends on the internal identity service for sign-in.",
|
|
120
|
+
"A tabletop exercise for {s} is planned with {t}.",
|
|
121
|
+
"[[{p}]] keeps the {s} architecture diagram up to date.",
|
|
122
|
+
)
|
|
123
|
+
LOCATIONS = ["repo-config"] * 8 + ["ops-access"] * 4 + ["notion-access"] * 4 + ["meeting"] * 2 + ["adr"] * 2
|
|
124
|
+
UPPER = string.ascii_uppercase + string.digits
|
|
125
|
+
ALNUM = string.ascii_letters + string.digits
|
|
126
|
+
B64 = ALNUM + "+/"
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _chars(rng, size, alphabet=ALNUM):
|
|
130
|
+
return "".join(rng.choice(alphabet) for _ in range(size))
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _secrets(rng, host):
|
|
134
|
+
"""Return (label, canary, line) for the 20 planted secrets, in placement order."""
|
|
135
|
+
word = lambda: rng.choice(("otter", "harbour", "maple", "quartz", "lantern", "meadow", "falcon", "pepper"))
|
|
136
|
+
pem = _chars(rng, 64, B64)
|
|
137
|
+
pw = f"{word().title()}{rng.randint(10, 99)}-{word()}"
|
|
138
|
+
return [
|
|
139
|
+
("AWS access key id", key := "AK" + "IA" + _chars(rng, 16, UPPER), f"aws_access_key_id = {key}"),
|
|
140
|
+
("AWS secret access key", key := _chars(rng, 40, B64), f"aws_secret_access_key = {key}"),
|
|
141
|
+
("GitHub token", key := "gh" + "p_" + _chars(rng, 36), f"export GITHUB_TOKEN={key}"),
|
|
142
|
+
("Stripe secret key", key := "sk" + "_live_" + _chars(rng, 24), f"STRIPE_SECRET_KEY={key}"),
|
|
143
|
+
("OpenAI project key", key := "sk-" + "proj-" + _chars(rng, 32), f"OPENAI_API_KEY={key}"),
|
|
144
|
+
("npm publish token", key := "np" + "m_" + _chars(rng, 36), f"//registry.npmjs.org/:_authToken={key}"),
|
|
145
|
+
("session signing JWT", key := "ey" + "J" + _chars(rng, 20) + "." + _chars(rng, 30) + "." + _chars(rng, 22),
|
|
146
|
+
f"SESSION_JWT={key}"),
|
|
147
|
+
("container registry token", key := _chars(rng, 28), f"REGISTRY_TOKEN={key}"),
|
|
148
|
+
("Slack alert webhook", key := "https://hooks.sl" + "ack.com/services/T" + _chars(rng, 8, UPPER) + "/B"
|
|
149
|
+
+ _chars(rng, 8, UPPER) + "/" + _chars(rng, 24), f"Alerts post to {key}"),
|
|
150
|
+
("database password in the connection string", pw,
|
|
151
|
+
"DATABASE_URL=postgres:" f"//svc_app:{pw}@{host}:5432/app"),
|
|
152
|
+
("staging database password", key := f"{word()}{rng.randint(100, 999)}{word().title()}", f"password: {key}"),
|
|
153
|
+
("deploy machine password", key := f"{word()}-{rng.randint(1000, 9999)}-{word()}",
|
|
154
|
+
f"machine deploy.quillfern.internal login deployer password {key}"),
|
|
155
|
+
("OAuth client secret", key := _chars(rng, 32, "0123456789abcdef"), f"Client secret: {key}"),
|
|
156
|
+
("Notion API key", key := "sec" + "ret_" + _chars(rng, 43), f"API Key: {key}"),
|
|
157
|
+
("Google Maps API key", key := "AI" + "za" + _chars(rng, 35, ALNUM + "-_"), f"Maps key: {key}"),
|
|
158
|
+
("storage account key", key := _chars(rng, 86, B64) + "==",
|
|
159
|
+
f"Connection: DefaultEndpointsProtocol=https;AccountName=qfstore;AccountKey={key};EndpointSuffix=core.windows.net"),
|
|
160
|
+
("guest Wi-Fi password", key := f"{word()}-{word()}-{rng.randint(10, 99)}",
|
|
161
|
+
f"The guest Wi-Fi password is {key} until the office move."),
|
|
162
|
+
("server room door PIN", key := f"{rng.randint(1000, 9999)}-{rng.randint(10, 99)}",
|
|
163
|
+
f"The server room door PIN is {key}."),
|
|
164
|
+
("API bearer token", key := _chars(rng, 32), f'curl -H "Authorization: Bearer {key}" https://api.quillfern.internal'),
|
|
165
|
+
("request signing private key", pem,
|
|
166
|
+
"\n".join(["-----BEGIN " + "PRIVATE KEY-----", pem, _chars(rng, 64, B64), "-----END " + "PRIVATE KEY-----"])),
|
|
167
|
+
]
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
class World:
|
|
171
|
+
def __init__(self, root, seed):
|
|
172
|
+
self.root, self.rng, self.files = Path(root), random.Random(seed), {}
|
|
173
|
+
rng = self.rng
|
|
174
|
+
combos = [f"{a} {n}" for a in ADJECTIVES for n in NOUNS]
|
|
175
|
+
rng.shuffle(combos)
|
|
176
|
+
self.hop_services, self.ground_services = combos[:20], combos[20:36]
|
|
177
|
+
self.secret_services, self.background = combos[36:56], combos[56:84]
|
|
178
|
+
self.people = [f"{first} {rng.choice(LAST)}" for first in FIRST]
|
|
179
|
+
self.teams = [f"Team {bird}" for bird in BIRDS]
|
|
180
|
+
|
|
181
|
+
def write(self, rel, text):
|
|
182
|
+
self.files[rel] = text.rstrip("\n") + "\n"
|
|
183
|
+
|
|
184
|
+
def prose(self, count, services=None):
|
|
185
|
+
rng, pool = self.rng, services or self.background
|
|
186
|
+
return [rng.choice(PROSE).format(s=f"[[{rng.choice(pool)}]]", p=rng.choice(self.people),
|
|
187
|
+
t=rng.choice(self.teams)) for _ in range(count)]
|
|
188
|
+
|
|
189
|
+
def paragraphs(self, count, size=3):
|
|
190
|
+
return "\n\n".join(" ".join(self.prose(size)) for _ in range(count))
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def generate(root, seed=SEED):
|
|
194
|
+
"""Write the corpus under root and return its question set and the edits made after compile."""
|
|
195
|
+
world, questions, edits = World(root, seed), [], []
|
|
196
|
+
rng, write = world.rng, world.write
|
|
197
|
+
hop, teams, people = world.hop_services, world.teams, world.people
|
|
198
|
+
|
|
199
|
+
owned = defaultdict(list)
|
|
200
|
+
for number, service in enumerate([*hop, *world.background]):
|
|
201
|
+
owned[teams[number % len(teams)]].append(service)
|
|
202
|
+
for number, team in enumerate(teams):
|
|
203
|
+
bird = team.split()[1].lower()
|
|
204
|
+
write(f"eng-vault/Teams/{team}.md", f"# {team}\n\nPrimary on-call for {team} is [[{people[number]}]].\n"
|
|
205
|
+
f"{team} owns " + ", ".join(f"[[{s}]]" for s in owned[team]) + ".")
|
|
206
|
+
write(f"ops-vault/Escalation/{team} escalation.md",
|
|
207
|
+
f"# {team} escalation\n\n{team} problems go to #{bird}-alerts, then to the duty manager.")
|
|
208
|
+
for number, service in enumerate(world.background):
|
|
209
|
+
write(f"eng-vault/Services/{service}.md", f"# {service}\n\n{service} handles {rng.choice(PURPOSES)}. Owner: "
|
|
210
|
+
f"[[{teams[(number + len(hop)) % len(teams)]}]].\n\n{world.paragraphs(1)}")
|
|
211
|
+
for number, (service, slang) in enumerate(zip(hop, SLANG)):
|
|
212
|
+
team = teams[number % len(teams)]
|
|
213
|
+
clock = f"{rng.randint(0, 23):02d}:{rng.choice((0, 15, 30, 45)):02d}"
|
|
214
|
+
write(f"eng-vault/Services/{service}.md",
|
|
215
|
+
f"# {service}\n\n{service} starts at {clock} UTC on weekdays.\nIt handles {PURPOSES[number]}.\n"
|
|
216
|
+
f"Owner: [[{team}]]")
|
|
217
|
+
write(f"eng-vault/Slang/{slang}.md",
|
|
218
|
+
f"# {slang}\n\nWorked example from the team glossary: when people say \"{slang}\" they mean "
|
|
219
|
+
f"[[{service}]].\n[[{team}]] looks after it, and [[{team} escalation]] lists where trouble goes.")
|
|
220
|
+
targets = [f"eng-vault/Services/{service}.md", f"eng-vault/Teams/{team}.md",
|
|
221
|
+
f"ops-vault/Escalation/{team} escalation.md"]
|
|
222
|
+
bird = team.split()[1].lower()
|
|
223
|
+
questions.append({"family": "multi-hop", "kind": "paraphrase", "query": HOP_QUERIES[number % 4].format(s=slang),
|
|
224
|
+
"targets": targets, "spans": [f"{service} starts at {clock} UTC",
|
|
225
|
+
f"Primary on-call for {team} is [[{people[number % 10]}]]",
|
|
226
|
+
f"{team} problems go to #{bird}-alerts"]})
|
|
227
|
+
write("eng-vault/Glossary.md", "# Team slang glossary\n\nNicknames people use in chat, with a worked example each.\n\n"
|
|
228
|
+
+ "\n".join(f"- [[{slang}]]" for slang in SLANG))
|
|
229
|
+
|
|
230
|
+
for (title, query, template, old, new), kind in zip(TOPICS, TOPIC_KINDS):
|
|
231
|
+
filler = world.paragraphs(1, 2)
|
|
232
|
+
current, stale = template.format(new), template.format(old)
|
|
233
|
+
hexid = f"{rng.getrandbits(128):032x}"
|
|
234
|
+
if kind == "marked":
|
|
235
|
+
write(f"eng-vault/Decisions/Archive/{title} 2024.md",
|
|
236
|
+
f"---\nstatus: superseded\nsuperseded_by: \"[[{title}]]\"\n---\n# {title} 2024\n\n{stale}\n\n{filler}")
|
|
237
|
+
write(f"eng-vault/Decisions/{title}.md",
|
|
238
|
+
f"---\nsupersedes: \"[[{title} 2024]]\"\n---\n# {title}\n\n{current}\n\n{world.paragraphs(1, 2)}")
|
|
239
|
+
else:
|
|
240
|
+
created = "Created: March 4, 2025\n" if kind == "unmarked-dated" else ""
|
|
241
|
+
write(f"wiki/Policies/{title} {hexid}.md",
|
|
242
|
+
f"# {title}\n\nOwner: People Ops\n{created}\n{stale}\n\n{filler}")
|
|
243
|
+
front = "---\ndate: 2026-02-10\n---\n" if kind == "unmarked-dated" else ""
|
|
244
|
+
note = f"{current} This changed from the earlier rule." if kind == "unmarked-wording" else current
|
|
245
|
+
write(f"ops-vault/Policies/{title}.md", f"{front}# {title}\n\n{note}\n\n{world.paragraphs(1, 2)}")
|
|
246
|
+
question = {"family": "supersession", "kind": kind, "query": query, "current": current, "stale": stale}
|
|
247
|
+
questions.append(question)
|
|
248
|
+
|
|
249
|
+
for number, kind in enumerate(GROUNDING_KINDS):
|
|
250
|
+
ask, fact, value = FACTS[number % 4]
|
|
251
|
+
if kind == "never":
|
|
252
|
+
questions.append({"family": "grounding", "kind": kind, "query": ask.format(s=MISSING[number - 16])})
|
|
253
|
+
continue
|
|
254
|
+
service = world.ground_services[number]
|
|
255
|
+
rel = f"eng-vault/Runbooks/{service} runbook.md"
|
|
256
|
+
first = fact.format(s=service, v=value(rng, service))
|
|
257
|
+
write(rel, f"# {service} runbook\n\n{service} handles {rng.choice(PURPOSES)}. See [[{rng.choice(teams)}]] "
|
|
258
|
+
f"for ownership.\n\n## Settings\n\n{first}\n\n## Restarts\n\n{world.paragraphs(2)}")
|
|
259
|
+
question = {"family": "grounding", "kind": kind, "query": ask.format(s=service), "evidence": first}
|
|
260
|
+
if kind == "changed":
|
|
261
|
+
question["stale"], question["evidence"] = first, fact.format(s=service, v=value(rng, service))
|
|
262
|
+
if kind == "deleted":
|
|
263
|
+
question["stale"], question["evidence"] = first, ""
|
|
264
|
+
edits.append({"kind": kind, "rel": rel, "old": first, "new": question["evidence"],
|
|
265
|
+
"to": rel.replace("eng-vault/Runbooks", "ops-vault/Runbooks")})
|
|
266
|
+
questions.append(question)
|
|
267
|
+
|
|
268
|
+
hosts = [f"{s.lower().replace(' ', '-')}-db-{rng.randint(1, 9)}.quillfern.internal" for s in world.secret_services]
|
|
269
|
+
secrets = _secrets(rng, hosts[9])
|
|
270
|
+
for number, (service, host, (label, canary, line), where) in enumerate(
|
|
271
|
+
zip(world.secret_services, hosts, secrets, LOCATIONS)):
|
|
272
|
+
control = f"The primary database host for {service} is {host}."
|
|
273
|
+
intro = f"{service} handles {rng.choice(PURPOSES)}."
|
|
274
|
+
if where == "repo-config":
|
|
275
|
+
repo = ("ledger-repo", "router-repo")[number % 2]
|
|
276
|
+
write(f"{repo}/docs/config/{service}.md",
|
|
277
|
+
f"# {service} configuration\n\n{intro}\n\n{control}\n\n## Environment\n\n```bash\n{line}\n```\n\n"
|
|
278
|
+
f"## Notes\n\n{world.paragraphs(1)}")
|
|
279
|
+
elif where == "ops-access":
|
|
280
|
+
write(f"ops-vault/Access/{service} access.md",
|
|
281
|
+
f"# {service} access\n\n{intro} Ask [[{rng.choice(people)}]] before changing anything.\n\n"
|
|
282
|
+
f"{control}\n\n```\n{line}\n```\n\n{world.paragraphs(1)}")
|
|
283
|
+
elif where == "notion-access":
|
|
284
|
+
write(f"wiki/Access/{service} access {rng.getrandbits(128):032x}.md",
|
|
285
|
+
f"# {service} access\n\nOwner: {rng.choice(teams)}\nStatus: Active\n\n{control}\n\n{line}\n\n"
|
|
286
|
+
f"{world.paragraphs(1)}")
|
|
287
|
+
elif where == "meeting":
|
|
288
|
+
write(f"eng-vault/Meetings/2026-03-{10 + number} {service} sync.md",
|
|
289
|
+
f"# {service} sync\n\nAttendees: [[{rng.choice(people)}]], [[{rng.choice(people)}]]\n\n"
|
|
290
|
+
f"- {control}\n- {line}\n- " + "\n- ".join(world.prose(3)))
|
|
291
|
+
else:
|
|
292
|
+
write(f"ledger-repo/docs/adr/{number + 20:04d}-{service.lower().replace(' ', '-')}-signing.md",
|
|
293
|
+
f"# ADR {number + 20:04d}: {service} request signing\n\nStatus: Accepted\nDate: 2025-09-{number:02d}\n\n"
|
|
294
|
+
f"## Context\n\n{intro} {control}\n\n## Decision\n\nRequests are signed with this key:\n\n"
|
|
295
|
+
f"```\n{line}\n```\n\n## Consequences\n\n{world.paragraphs(1)}")
|
|
296
|
+
questions += [{"family": "secrets", "kind": "probe", "query": f"What is the {label} for {service}?",
|
|
297
|
+
"canary": canary},
|
|
298
|
+
{"family": "secrets", "kind": "control",
|
|
299
|
+
"query": f"What is the primary database host for {service}?", "control": control}]
|
|
300
|
+
|
|
301
|
+
for number, person in enumerate(people):
|
|
302
|
+
team = teams[number % len(teams)]
|
|
303
|
+
write(f"eng-vault/People/{person}.md", f"# {person}\n\n{person} works in [[{team}]].\n\n{world.paragraphs(3)}")
|
|
304
|
+
for number in range(22):
|
|
305
|
+
service = world.background[number]
|
|
306
|
+
write(f"eng-vault/Meetings/2025-{number % 12 + 1:02d}-{number + 3:02d} {service} review.md",
|
|
307
|
+
f"# {service} review\n\nAttendees: [[{rng.choice(people)}]], [[{rng.choice(people)}]]\n\n"
|
|
308
|
+
+ "\n".join(f"- {line}" for line in world.prose(9, [service, *world.background])))
|
|
309
|
+
for number in range(24):
|
|
310
|
+
service = rng.choice(world.background)
|
|
311
|
+
write(f"ops-vault/Incidents/INC-{4100 + number} {service}.md",
|
|
312
|
+
f"# INC-{4100 + number} {service}\n\nSeverity: {rng.choice(('SEV2', 'SEV3', 'SEV4'))}\n\n## Summary\n\n"
|
|
313
|
+
f"{world.paragraphs(2)}\n\n## Follow-ups\n\n" + "\n".join(f"- {line}" for line in world.prose(3)))
|
|
314
|
+
for number in range(14):
|
|
315
|
+
topic = rng.choice(("Onboarding", "Travel", "Security basics", "Writing style", "Hiring", "Office life",
|
|
316
|
+
"Tooling", "Benefits", "Vendors", "Design reviews"))
|
|
317
|
+
write(f"wiki/Handbook/{topic} {number + 1} {rng.getrandbits(128):032x}.md",
|
|
318
|
+
f"# {topic} {number + 1}\n\nOwner: {rng.choice(teams)}\nStatus: Published\n\n{world.paragraphs(5)}")
|
|
319
|
+
for repo, count in (("ledger-repo", 10), ("router-repo", 10)):
|
|
320
|
+
write(f"{repo}/README.md", f"# {repo}\n\n{world.paragraphs(4)}")
|
|
321
|
+
for number in range(count):
|
|
322
|
+
service = rng.choice(world.background)
|
|
323
|
+
write(f"{repo}/docs/adr/{number + 1:04d}-{service.lower().replace(' ', '-')}.md",
|
|
324
|
+
f"# ADR {number + 1:04d}: {service} layout\n\nStatus: Accepted\nDate: 2025-{number % 12 + 1:02d}-15\n\n"
|
|
325
|
+
f"## Context\n\n{world.paragraphs(1)}\n\n## Decision\n\n{world.paragraphs(2)}\n\n## Consequences\n\n"
|
|
326
|
+
f"{world.paragraphs(1)}")
|
|
327
|
+
for number in range(7):
|
|
328
|
+
service = world.background[(number * 3 + len(repo)) % len(world.background)]
|
|
329
|
+
write(f"{repo}/docs/services/{service.lower().replace(' ', '-')}.md",
|
|
330
|
+
f"# {service}\n\n{world.paragraphs(5)}")
|
|
331
|
+
|
|
332
|
+
for rel, text in sorted(world.files.items()):
|
|
333
|
+
path = Path(root) / rel
|
|
334
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
335
|
+
path.write_text(text)
|
|
336
|
+
for number, question in enumerate(questions):
|
|
337
|
+
question["id"] = f"q{number + 1:03d}"
|
|
338
|
+
return {"questions": questions, "edits": edits, "canaries": [s[1] for s in secrets]}
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def make_repos(root):
|
|
342
|
+
env = {k: v for k, v in os.environ.items() if not k.startswith("GIT_")}
|
|
343
|
+
for name, kind in SOURCES.items():
|
|
344
|
+
if kind == "repo":
|
|
345
|
+
for command in (["init", "-q"], ["add", "-f", "."]):
|
|
346
|
+
subprocess.run(["git", "-C", str(Path(root) / name), *command], check=True, capture_output=True,
|
|
347
|
+
env=env)
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
def apply_edits(root, edits, people):
|
|
351
|
+
root = Path(root)
|
|
352
|
+
for number, edit in enumerate(edits):
|
|
353
|
+
path = root / edit["rel"]
|
|
354
|
+
if edit["kind"] == "changed":
|
|
355
|
+
path.write_text(path.read_text().replace(edit["old"], edit["new"]))
|
|
356
|
+
elif edit["kind"] == "shifted":
|
|
357
|
+
lines = path.read_text().split("\n")
|
|
358
|
+
lines[2:2] = ["## Review notes", ""] + [f"- Reviewed by [[{p}]] in November."
|
|
359
|
+
for p in people[number:number + 6]]
|
|
360
|
+
path.write_text("\n".join(lines))
|
|
361
|
+
elif edit["kind"] == "moved":
|
|
362
|
+
target = root / edit["to"]
|
|
363
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
364
|
+
path.rename(target)
|
|
365
|
+
elif edit["kind"] == "deleted":
|
|
366
|
+
path.unlink()
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _windows(root, rels):
|
|
370
|
+
out = []
|
|
371
|
+
for rel in rels:
|
|
372
|
+
lines = (Path(root) / rel).read_text().split("\n")
|
|
373
|
+
start = 0
|
|
374
|
+
while start < len(lines):
|
|
375
|
+
end, size = start, 0
|
|
376
|
+
while end < len(lines) and (size < WINDOW or end == start):
|
|
377
|
+
size, end = size + len(lines[end]) + 1, end + 1
|
|
378
|
+
out.append((rel, start + 1, end, "\n".join(lines[start:end])))
|
|
379
|
+
if end >= len(lines):
|
|
380
|
+
break
|
|
381
|
+
step, following = 0, start
|
|
382
|
+
while following < end - 1 and step < STRIDE:
|
|
383
|
+
step, following = step + len(lines[following]) + 1, following + 1
|
|
384
|
+
start = max(following, start + 1)
|
|
385
|
+
return out
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
class Bm25:
|
|
389
|
+
def __init__(self, texts):
|
|
390
|
+
self.counts = [Counter(terms(text)) for text in texts]
|
|
391
|
+
self.average = sum(c.total() for c in self.counts) / len(self.counts)
|
|
392
|
+
self.found = Counter(term for counts in self.counts for term in counts)
|
|
393
|
+
|
|
394
|
+
def idf(self, term):
|
|
395
|
+
return math.log(1 + (len(self.counts) - self.found[term] + 0.5) / (self.found[term] + 0.5))
|
|
396
|
+
|
|
397
|
+
def scores(self, weights):
|
|
398
|
+
return [sum(weight * self.idf(t) * counts[t] * 2.2 / (counts[t] + 1.2 * (0.25 + 0.75 * counts.total()
|
|
399
|
+
/ self.average))
|
|
400
|
+
for t, weight in weights.items() if counts[t]) for counts in self.counts]
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _rank(scores):
|
|
404
|
+
return sorted(range(len(scores)), key=lambda i: (-scores[i], i))
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _fuse(*rankings):
|
|
408
|
+
fused = defaultdict(float)
|
|
409
|
+
for ranking in rankings:
|
|
410
|
+
for place, item in enumerate(ranking):
|
|
411
|
+
fused[item] += 1 / (60 + place)
|
|
412
|
+
return sorted(fused, key=lambda i: (-fused[i], i))
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
class NaiveRag:
|
|
416
|
+
"""BM25 over 1024-character line windows at a 768-character stride, indexed once and packed to 4,000 tokens."""
|
|
417
|
+
|
|
418
|
+
def __init__(self, root, rels):
|
|
419
|
+
self.windows = _windows(root, rels)
|
|
420
|
+
self.bm25 = Bm25([f"{rel}\n{text}" for rel, _, _, text in self.windows])
|
|
421
|
+
|
|
422
|
+
def ask(self, query):
|
|
423
|
+
parts, cites, used = [], [], 0
|
|
424
|
+
for i in _rank(self.bm25.scores(Counter(terms(query)))):
|
|
425
|
+
rel, first, last, text = self.windows[i]
|
|
426
|
+
part = f"[{rel}:{first}-{last}]\n{text}"
|
|
427
|
+
if used + tokens(part) > NAIVE_BUDGET:
|
|
428
|
+
break
|
|
429
|
+
parts.append(part)
|
|
430
|
+
cites.append((rel, first, last, text))
|
|
431
|
+
used += tokens(part)
|
|
432
|
+
return "\n\n".join(parts), cites
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
class TunedHybrid(NaiveRag):
|
|
436
|
+
"""BM25 plus character-trigram TF-IDF, pseudo-relevance expansion and one wikilink hop, packed to 180 words."""
|
|
437
|
+
|
|
438
|
+
def __init__(self, root, rels):
|
|
439
|
+
super().__init__(root, rels)
|
|
440
|
+
self.grams = [self._grams(text) for _, _, _, text in self.windows]
|
|
441
|
+
found = Counter(g for grams in self.grams for g in grams)
|
|
442
|
+
self.gram_idf = {g: math.log(len(self.grams) / n) for g, n in found.items()}
|
|
443
|
+
self.vectors = [self._vector(grams) for grams in self.grams]
|
|
444
|
+
self.by_name = {}
|
|
445
|
+
for number, (rel, _, _, _) in enumerate(self.windows):
|
|
446
|
+
name = re.sub(r"\s+[0-9a-f]{32}$", "", Path(rel).stem).lower()
|
|
447
|
+
self.by_name.setdefault(name, []).append(number)
|
|
448
|
+
|
|
449
|
+
@staticmethod
|
|
450
|
+
def _grams(text):
|
|
451
|
+
text = " ".join(re.findall(r"[a-z0-9]+", text.lower()))
|
|
452
|
+
return Counter(text[i:i + 3] for i in range(len(text) - 2))
|
|
453
|
+
|
|
454
|
+
def _vector(self, grams):
|
|
455
|
+
vector = {g: (1 + math.log(n)) * self.gram_idf.get(g, 0) for g, n in grams.items()}
|
|
456
|
+
norm = math.sqrt(sum(v * v for v in vector.values())) or 1
|
|
457
|
+
return {g: v / norm for g, v in vector.items()}
|
|
458
|
+
|
|
459
|
+
def ask(self, query):
|
|
460
|
+
wanted = Counter(terms(query))
|
|
461
|
+
lexical = _rank(self.bm25.scores(wanted))
|
|
462
|
+
probe = self._vector(self._grams(query))
|
|
463
|
+
trigram = _rank([sum(probe.get(g, 0) * v for g, v in vector.items()) for vector in self.vectors])
|
|
464
|
+
expansion = Counter()
|
|
465
|
+
for i in _fuse(lexical, trigram)[:3]:
|
|
466
|
+
for term, count in self.bm25.counts[i].items():
|
|
467
|
+
if term not in wanted:
|
|
468
|
+
expansion[term] += count * self.bm25.idf(term)
|
|
469
|
+
weights = wanted | {term: 0.5 for term, _ in expansion.most_common(8)}
|
|
470
|
+
order = _fuse(lexical, trigram, _rank(self.bm25.scores(weights)))
|
|
471
|
+
chosen = []
|
|
472
|
+
for i in order[:6]:
|
|
473
|
+
chosen.append(i)
|
|
474
|
+
for name in re.findall(r"\[\[([^\]|#\n]+)", self.windows[i][3]):
|
|
475
|
+
chosen += self.by_name.get(name.strip().lower(), [])[:1]
|
|
476
|
+
lines, cites, used, seen = [], [], 0, set()
|
|
477
|
+
for i in dict.fromkeys(chosen):
|
|
478
|
+
rel, first, _, text = self.windows[i]
|
|
479
|
+
rows = [(n, line) for n, line in enumerate(text.split("\n"), first) if line.strip()
|
|
480
|
+
and not line.startswith(("#", "---"))]
|
|
481
|
+
if not rows:
|
|
482
|
+
continue
|
|
483
|
+
number, line = max(rows, key=lambda row: (sum(weights[t] * self.bm25.idf(t) for t in set(terms(row[1]))
|
|
484
|
+
if t in weights), -row[0]))
|
|
485
|
+
if (rel, number) in seen:
|
|
486
|
+
continue
|
|
487
|
+
part = f"- {rel}:{number} {line.strip()}"
|
|
488
|
+
if used + len(part.split()) > BRIEF_WORDS and lines:
|
|
489
|
+
break
|
|
490
|
+
seen.add((rel, number))
|
|
491
|
+
lines.append(part)
|
|
492
|
+
cites.append((rel, number, number, line))
|
|
493
|
+
used += len(part.split())
|
|
494
|
+
return "\n".join(lines), cites
|
|
495
|
+
|
|
496
|
+
|
|
497
|
+
def full_pack(root, rels):
|
|
498
|
+
texts = {rel: (Path(root) / rel).read_text() for rel in rels}
|
|
499
|
+
pack = "\n\n".join(f"=== {rel} ===\n{text}" for rel, text in texts.items())
|
|
500
|
+
return pack, [(rel, 1, len(text.split("\n")), text) for rel, text in texts.items()]
|
|
501
|
+
|
|
502
|
+
|
|
503
|
+
_STATE = r"(?:current(?:, (?:new|changed) since compile)?|STALE, no current replacement found)(?:, proposed by recall)?"
|
|
504
|
+
_CITE = re.compile(rf'^- (.+?):(\d+)(?:-(\d+))? \[{_STATE}\]\n "(.*)"$', re.M)
|
|
505
|
+
_WARNING = re.compile(r"^- (?:Possible conflict: |.+ (?:is out of date\. Replaced by|may be out of date \(not marked\)): )")
|
|
506
|
+
|
|
507
|
+
|
|
508
|
+
def cold_answer(client, root, query):
|
|
509
|
+
text = client.call("memory_ask", query=query, max_words=BRIEF_WORDS)
|
|
510
|
+
prefix = f"{root}/"
|
|
511
|
+
sources = text.split("\nSynthesized Context", 1)[0]
|
|
512
|
+
cites = [(m[1].removeprefix(prefix), int(m[2]), int(m[3] or m[2]), m[4]) for m in _CITE.finditer(sources)]
|
|
513
|
+
heads = [line for line in sources.split("\n") if line.startswith("- ") and not _WARNING.match(line)]
|
|
514
|
+
cites += [("", 0, 0, "")] * (len(heads) - len(cites))
|
|
515
|
+
return text.replace(prefix, ""), cites
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def verified(root, cite, inventory=None):
|
|
519
|
+
"""A citation is real only when its file exists now and the shown text is on the cited lines."""
|
|
520
|
+
rel, first, last, shown = cite
|
|
521
|
+
if rel not in (inventory if inventory is not None else _documents(root)):
|
|
522
|
+
return False
|
|
523
|
+
path = Path(root) / rel
|
|
524
|
+
if path.is_symlink() or not path.resolve().is_relative_to(Path(root).resolve()) or not path.is_file():
|
|
525
|
+
return False
|
|
526
|
+
lines = path.read_text().split("\n")
|
|
527
|
+
if not 1 <= first <= last <= len(lines):
|
|
528
|
+
return False
|
|
529
|
+
disk, place = flat("\n".join(lines[first - 1:last])), 0
|
|
530
|
+
parts = [part for part in map(flat, shown.split(MARK)) if part]
|
|
531
|
+
if not parts:
|
|
532
|
+
return False
|
|
533
|
+
for part in parts:
|
|
534
|
+
place = disk.find(part, place)
|
|
535
|
+
if place < 0:
|
|
536
|
+
return False
|
|
537
|
+
place += len(part)
|
|
538
|
+
return True
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _present(value, text):
|
|
542
|
+
return bool(value) and flat(value) in flat(text)
|
|
543
|
+
|
|
544
|
+
|
|
545
|
+
def _documents(root):
|
|
546
|
+
return [str(p.relative_to(root)) for p in documents(Path(root))]
|
|
547
|
+
|
|
548
|
+
|
|
549
|
+
def run(seed=SEED):
|
|
550
|
+
with tempfile.TemporaryDirectory(dir="/tmp" if os.access("/tmp", os.W_OK) else None) as work:
|
|
551
|
+
root = Path(work) / "corpus"
|
|
552
|
+
spec = generate(root, seed)
|
|
553
|
+
make_repos(root)
|
|
554
|
+
rels = _documents(root)
|
|
555
|
+
store = Path(work) / "store"
|
|
556
|
+
bundle = compile_bundle(store, "bench", [parse_source(f"{kind}:{root / name}")
|
|
557
|
+
for name, kind in SOURCES.items()])
|
|
558
|
+
compiled = "\n".join(p.read_text() for p in sorted(bundle.path.iterdir()))
|
|
559
|
+
naive, hybrid = NaiveRag(root, rels), TunedHybrid(root, rels)
|
|
560
|
+
corpus_tokens = tokens(full_pack(root, rels)[0])
|
|
561
|
+
observed, extra = {arm: {} for arm in ARMS}, {arm: [] for arm in ARMS}
|
|
562
|
+
with Client(store, "--backend", "disk") as client:
|
|
563
|
+
setup = client.info["instructions"] + json.dumps(client.request("tools/list")["tools"])
|
|
564
|
+
for phase in ("compiled", "edited"):
|
|
565
|
+
if phase == "edited":
|
|
566
|
+
apply_edits(root, spec["edits"], World(root, seed).people)
|
|
567
|
+
phase_docs = _documents(root)
|
|
568
|
+
inventory = set(phase_docs)
|
|
569
|
+
pack = full_pack(root, phase_docs)
|
|
570
|
+
asks = {"Full context": lambda q: pack, "Naive BM25 RAG": naive.ask, "Tuned hybrid": hybrid.ask,
|
|
571
|
+
"ColdMemory": lambda q: cold_answer(client, root, q)}
|
|
572
|
+
for question in spec["questions"]:
|
|
573
|
+
if (question["family"] == "grounding") != (phase == "edited"):
|
|
574
|
+
continue
|
|
575
|
+
for arm, ask in asks.items():
|
|
576
|
+
text, cites = ask(question["query"])
|
|
577
|
+
checks = [verified(root, cite, inventory) for cite in cites]
|
|
578
|
+
observed[arm][question["id"]] = {
|
|
579
|
+
"text": text, "tokens": tokens(text), "fabricated": checks.count(False),
|
|
580
|
+
"grounded": [cite[3] for cite, ok in zip(cites, checks) if ok]}
|
|
581
|
+
extra["ColdMemory"] = [compiled, client.call("memory_status")]
|
|
582
|
+
extra["ColdMemory"] += [client.call("memory_locate", topic=q["query"]) for q in spec["questions"]]
|
|
583
|
+
return score(spec, observed, extra, tokens(setup), corpus_tokens, len(rels), seed)
|
|
584
|
+
|
|
585
|
+
|
|
586
|
+
def _passes(question, seen):
|
|
587
|
+
text, family, kind = seen["text"], question["family"], question["kind"]
|
|
588
|
+
if family == "multi-hop":
|
|
589
|
+
found = sum(_present(span, text) for span in question["spans"])
|
|
590
|
+
return found == len(question["spans"]), found / len(question["spans"])
|
|
591
|
+
if family == "supersession":
|
|
592
|
+
if kind == "tie":
|
|
593
|
+
ok = _present(question["current"], text) and _present(question["stale"], text)
|
|
594
|
+
else:
|
|
595
|
+
ok = _present(question["current"], text) and not _present(question["stale"], text)
|
|
596
|
+
return ok, float(ok)
|
|
597
|
+
if family == "grounding":
|
|
598
|
+
clean = seen["fabricated"] == 0
|
|
599
|
+
if kind == "never":
|
|
600
|
+
ok = clean and text.startswith(NO_MATCH)
|
|
601
|
+
elif kind == "deleted":
|
|
602
|
+
ok = clean and not _present(question["stale"], text)
|
|
603
|
+
else:
|
|
604
|
+
ok = (clean and any(_present(question["evidence"], shown) for shown in seen["grounded"])
|
|
605
|
+
and not _present(question.get("stale", ""), text))
|
|
606
|
+
return ok, float(ok)
|
|
607
|
+
if kind == "probe":
|
|
608
|
+
ok = question["canary"] not in text
|
|
609
|
+
else:
|
|
610
|
+
ok = _present(question["control"], text)
|
|
611
|
+
return ok, float(ok)
|
|
612
|
+
|
|
613
|
+
|
|
614
|
+
def score(spec, observed, extra, setup_tokens, corpus_tokens, files, seed=SEED):
|
|
615
|
+
questions = spec["questions"]
|
|
616
|
+
order = [q["id"] for q in questions]
|
|
617
|
+
random.Random(seed).shuffle(order)
|
|
618
|
+
by_id = {q["id"]: q for q in questions}
|
|
619
|
+
arms = {}
|
|
620
|
+
for arm, seen in observed.items():
|
|
621
|
+
passed = {qid: _passes(by_id[qid], seen[qid]) for qid in seen}
|
|
622
|
+
families = defaultdict(Counter)
|
|
623
|
+
for question in questions:
|
|
624
|
+
ok, credit = passed[question["id"]]
|
|
625
|
+
row = families[question["family"]]
|
|
626
|
+
row["total"] += 1
|
|
627
|
+
row["passed"] += ok
|
|
628
|
+
row["credit"] += credit
|
|
629
|
+
row[f"{question['kind']} total"] += 1
|
|
630
|
+
row[f"{question['kind']} passed"] += ok
|
|
631
|
+
if question["family"] == "grounding":
|
|
632
|
+
row["fabricated citations"] += seen[question["id"]]["fabricated"]
|
|
633
|
+
if question["family"] == "supersession":
|
|
634
|
+
row["current shown"] += _present(question["current"], seen[question["id"]]["text"])
|
|
635
|
+
row["stale shown"] += _present(question["stale"], seen[question["id"]]["text"])
|
|
636
|
+
row[f"{question['kind']} flagged"] += CONFLICT in seen[question["id"]]["text"]
|
|
637
|
+
if question["kind"] == "never":
|
|
638
|
+
row["never weak"] += seen[question["id"]]["text"].startswith(WEAK)
|
|
639
|
+
outputs = "\n".join(dict.fromkeys([*(s["text"] for s in seen.values()), *extra[arm]]))
|
|
640
|
+
scrubbed = scrub(outputs)
|
|
641
|
+
once = setup_tokens if arm == "ColdMemory" else 0
|
|
642
|
+
spent = [seen[qid]["tokens"] for qid in order]
|
|
643
|
+
checkpoints = {}
|
|
644
|
+
for n in CHECKPOINTS:
|
|
645
|
+
total = once + sum(spent[:n])
|
|
646
|
+
wins = sum(passed[qid][0] for qid in order[:n])
|
|
647
|
+
checkpoints[str(n)] = {"tokens": total, "passed": wins, "usd": round(total * PRICE_PER_TOKEN, 4),
|
|
648
|
+
"usd_per_success": round(total * PRICE_PER_TOKEN / wins, 5) if wins else None}
|
|
649
|
+
arms[arm] = {
|
|
650
|
+
"families": {name: {k: round(v, 3) for k, v in sorted(row.items())} for name, row in families.items()},
|
|
651
|
+
"passed": sum(ok for ok, _ in passed.values()),
|
|
652
|
+
"canaries_blocked": sum(c not in outputs for c in spec["canaries"]),
|
|
653
|
+
"canaries_blocked_if_scrubbed": sum(c not in scrubbed for c in spec["canaries"]),
|
|
654
|
+
"setup_tokens": once, "mean_tokens": round(sum(spent) / len(spent), 1), "checkpoints": checkpoints}
|
|
655
|
+
full = arms["Full context"]["checkpoints"]
|
|
656
|
+
for arm in arms.values():
|
|
657
|
+
arm["savings_vs_full"] = {n: round(1 - c["tokens"] / full[n]["tokens"], 4)
|
|
658
|
+
for n, c in arm["checkpoints"].items()}
|
|
659
|
+
return {"seed": seed, "corpus": {"files": files, "tokens": corpus_tokens, "questions": len(questions),
|
|
660
|
+
"canaries": len(spec["canaries"])}, "arms": arms}
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
def report(results):
|
|
664
|
+
arms, corpus = results["arms"], results["corpus"]
|
|
665
|
+
names = list(arms)
|
|
666
|
+
lines = [
|
|
667
|
+
"# ColdMemory-Bench v1 results", "",
|
|
668
|
+
f"Corpus: {corpus['files']} synthetic files, about {corpus['tokens']:,} tokens, {corpus['questions']} "
|
|
669
|
+
f"questions, {corpus['canaries']} planted canary secrets. Seed {results['seed']}.",
|
|
670
|
+
"Tokens are estimates (characters / 4, rounded up). Prices use $4 per million input tokens.",
|
|
671
|
+
"Scoring checks what evidence reaches the agent. No language model answers or grades anything.", "",
|
|
672
|
+
"## Token compression (Full context is the whole corpus on every question)", "",
|
|
673
|
+
"| Arm | Tokens per question | 10 questions | 50 questions | 100 questions | Saved vs full at 100 "
|
|
674
|
+
"| Passed (of 100) | Cost at 100 | Cost per pass |", "|---|---:|---:|---:|---:|---:|---:|---:|---:|"]
|
|
675
|
+
for name, arm in arms.items():
|
|
676
|
+
points = arm["checkpoints"]
|
|
677
|
+
each = points["100"]["usd_per_success"]
|
|
678
|
+
lines.append(f"| {name} | {arm['mean_tokens']:,} | {points['10']['tokens']:,} | {points['50']['tokens']:,} | "
|
|
679
|
+
f"{points['100']['tokens']:,} | {arm['savings_vs_full']['100']:.1%} | {arm['passed']} | "
|
|
680
|
+
f"${points['100']['usd']:.2f} | " + (f"${each:.4f}" if each else "n/a") + " |")
|
|
681
|
+
|
|
682
|
+
def row(label, value):
|
|
683
|
+
return f"| {label} | " + " | ".join(value(arms[n]) for n in names) + " |"
|
|
684
|
+
|
|
685
|
+
def part(family, key, total):
|
|
686
|
+
return lambda arm: f"{int(arm['families'][family].get(key, 0))}/{int(arm['families'][family].get(total, 0))}"
|
|
687
|
+
|
|
688
|
+
lines += ["", "## Scores by family", "", "| Measure | " + " | ".join(names) + " |", "|---|" + "---:|" * len(names),
|
|
689
|
+
row("1. Paraphrase multi-hop: all 3 facts", part("multi-hop", "passed", "total")),
|
|
690
|
+
row("1. Paraphrase multi-hop: facts found (mean)",
|
|
691
|
+
lambda a: f"{a['families']['multi-hop']['credit'] / a['families']['multi-hop']['total']:.2f}"),
|
|
692
|
+
row("2. Marked supersession", part("supersession", "marked passed", "marked total")),
|
|
693
|
+
row("2. Unmarked, dated", part("supersession", "unmarked-dated passed", "unmarked-dated total")),
|
|
694
|
+
row("2. Unmarked, wording says it changed",
|
|
695
|
+
part("supersession", "unmarked-wording passed", "unmarked-wording total")),
|
|
696
|
+
row("2. Tie: both sides shown", part("supersession", "tie passed", "tie total")),
|
|
697
|
+
row("2. Tie: flagged as a possible conflict", part("supersession", "tie flagged", "tie total")),
|
|
698
|
+
row("3. Grounding: value changed after compile", part("grounding", "changed passed", "changed total")),
|
|
699
|
+
row("3. Grounding: lines shifted", part("grounding", "shifted passed", "shifted total")),
|
|
700
|
+
row("3. Grounding: file moved", part("grounding", "moved passed", "moved total")),
|
|
701
|
+
row("3. Grounding: file deleted", part("grounding", "deleted passed", "deleted total")),
|
|
702
|
+
row("3. Grounding: never written (says no match)", part("grounding", "never passed", "never total")),
|
|
703
|
+
row("3. Grounding: never written (weak match instead)", part("grounding", "never weak", "never total")),
|
|
704
|
+
row("3. Fabricated citations", lambda a: str(int(a["families"]["grounding"].get("fabricated citations", 0)))),
|
|
705
|
+
row("5. Canaries never shown (gate 20/20)", lambda a: f"{a['canaries_blocked']}/20"),
|
|
706
|
+
row("5. Canaries blocked if scrub() were added", lambda a: f"{a['canaries_blocked_if_scrubbed']}/20"),
|
|
707
|
+
row("5. Permitted controls answered", part("secrets", "control passed", "control total"))]
|
|
708
|
+
gate = arms["ColdMemory"]["canaries_blocked"] == 20
|
|
709
|
+
lines += ["", f"Red-team gate (ColdMemory): {'PASS' if gate else 'FAIL'}, "
|
|
710
|
+
f"{arms['ColdMemory']['canaries_blocked']}/20 canaries kept out of every answer, locate result, "
|
|
711
|
+
"status report and compiled bundle file.", "",
|
|
712
|
+
"## How each arm works", "",
|
|
713
|
+
"- Full context: every corpus file, read from disk for each question (fresh, but sends everything).",
|
|
714
|
+
"- Naive BM25 RAG: BM25 over 1024-character line windows (768 stride), indexed at compile time, "
|
|
715
|
+
"packed to 4,000 tokens with `path:first-last` labels.",
|
|
716
|
+
"- Tuned hybrid: BM25 + character-trigram TF-IDF fused by reciprocal rank, 8-term pseudo-relevance "
|
|
717
|
+
"expansion, one wikilink hop, best line per window, packed to the same 180 words as ColdMemory. "
|
|
718
|
+
"Indexed at compile time.",
|
|
719
|
+
"- ColdMemory: the real MCP server over stdio (`memory_ask`, disk backend, 180 words), which "
|
|
720
|
+
"re-reads changed files at question time.", "",
|
|
721
|
+
"## Scoring rules", "",
|
|
722
|
+
"- Multi-hop: the question shares no word stem with its 3 target notes; only a slang note links them. "
|
|
723
|
+
"Pass needs all 3 fact spans in the output.",
|
|
724
|
+
"- Supersession: pass needs the current sentence and not the stale one; a tie needs both sides. "
|
|
725
|
+
"The flagged row counts tie answers that also carry the possible-conflict warning.",
|
|
726
|
+
"- Grounding (after edits made post-compile): every citation must point at an existing file and "
|
|
727
|
+
"lines that hold the shown text now. One fabricated citation fails the question. Never-written "
|
|
728
|
+
"facts pass only when the arm says no match; a weak match that still shows evidence is counted "
|
|
729
|
+
"separately and does not pass (baselines have no way to abstain).",
|
|
730
|
+
"- Secrets: a probe passes when its canary is absent; a control passes when the permitted fact is "
|
|
731
|
+
"shown. The gate scans every output of the arm.",
|
|
732
|
+
"- Full context and the BM25 arms show raw text, so they fail stale-exclusion and secret checks "
|
|
733
|
+
"by design; the 'if scrub() were added' row shows what ColdMemory's redactor would recover."]
|
|
734
|
+
return "\n".join(lines) + "\n"
|
|
735
|
+
|
|
736
|
+
|
|
737
|
+
def _owned(out):
|
|
738
|
+
sums = out / "SHA256SUMS"
|
|
739
|
+
entries = [out, *out.rglob("*")]
|
|
740
|
+
if any(p.is_symlink() or not (p.is_file() or p.is_dir()) for p in entries):
|
|
741
|
+
return False
|
|
742
|
+
listed = dict(reversed(line.split(" ", 1)) for line in sums.read_text().splitlines()) if sums.is_file() else {}
|
|
743
|
+
return all(listed.get(str(p.relative_to(out))) == hashlib.sha256(p.read_bytes()).hexdigest()
|
|
744
|
+
for p in out.rglob("*") if p.is_file() and p != sums)
|
|
745
|
+
|
|
746
|
+
|
|
747
|
+
def write_outputs(out, seed=SEED):
|
|
748
|
+
out = Path(out).absolute()
|
|
749
|
+
if out.is_symlink() or (out.exists() and ({p.name for p in out.iterdir()} - set(OUTPUTS) or not _owned(out))):
|
|
750
|
+
raise SystemExit(f"{out} holds files this benchmark did not write; choose an empty folder")
|
|
751
|
+
out.parent.mkdir(parents=True, exist_ok=True)
|
|
752
|
+
with tempfile.TemporaryDirectory(dir=out.parent) as work:
|
|
753
|
+
staged = Path(work) / "output"
|
|
754
|
+
results = _generate_outputs(staged, seed)
|
|
755
|
+
if out.exists() and any(out.iterdir()):
|
|
756
|
+
libc = ctypes.CDLL(None, use_errno=True)
|
|
757
|
+
# Linux renameat2 with RENAME_EXCHANGE swaps two populated directories atomically.
|
|
758
|
+
status = libc.renameat2(-100, os.fsencode(staged), -100, os.fsencode(out), 2)
|
|
759
|
+
if status:
|
|
760
|
+
error = ctypes.get_errno()
|
|
761
|
+
raise OSError(error, os.strerror(error), str(out))
|
|
762
|
+
else:
|
|
763
|
+
os.replace(staged, out)
|
|
764
|
+
return results
|
|
765
|
+
|
|
766
|
+
|
|
767
|
+
def _generate_outputs(out, seed):
|
|
768
|
+
corpus = out / "corpus"
|
|
769
|
+
spec = generate(corpus, seed)
|
|
770
|
+
results = run(seed)
|
|
771
|
+
blob = json.dumps(results, indent=2, sort_keys=True) + "\n"
|
|
772
|
+
results["results_sha256"] = hashlib.sha256(blob.encode()).hexdigest()
|
|
773
|
+
(out / "questions.json").write_text(json.dumps(spec, indent=2, sort_keys=True) + "\n")
|
|
774
|
+
(out / "results.json").write_text(json.dumps(results, indent=2, sort_keys=True) + "\n")
|
|
775
|
+
(out / "REPORT.md").write_text(report(results) + f"\nResults hash: `{results['results_sha256']}`\n")
|
|
776
|
+
files = sorted([*(p for p in corpus.rglob("*") if p.is_file()), *(out / name for name in OUTPUTS[1:-1])])
|
|
777
|
+
(out / "SHA256SUMS").write_text("".join(f"{hashlib.sha256(p.read_bytes()).hexdigest()} {p.relative_to(out)}\n"
|
|
778
|
+
for p in files))
|
|
779
|
+
return results
|
|
780
|
+
|
|
781
|
+
|
|
782
|
+
def main(argv=None):
|
|
783
|
+
parser = argparse.ArgumentParser(prog="python -m coldmemory.bench_v1")
|
|
784
|
+
parser.add_argument("--out", help="write corpus, questions, results, report and SHA256SUMS here")
|
|
785
|
+
parser.add_argument("--seed", type=int, default=SEED)
|
|
786
|
+
options = parser.parse_args(argv)
|
|
787
|
+
results = write_outputs(options.out, options.seed) if options.out else run(options.seed)
|
|
788
|
+
sys.stdout.write(report(results))
|
|
789
|
+
|
|
790
|
+
|
|
791
|
+
if __name__ == "__main__":
|
|
792
|
+
main()
|