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.
@@ -0,0 +1,559 @@
1
+ """Private, versioned memory bundles. Trained weights sit in a strict signed v2 `.cold` folder.
2
+
3
+ <store>/<id>/current.json which revision is live
4
+ <store>/<id>/queue.jsonl notes agents recorded and the owner's approvals
5
+ <store>/<id>/<revision>/memory.json base pin, source hashes, scope, build time
6
+ <store>/<id>/<revision>/graph.json file hashes, links and replacements at compile time
7
+ <store>/<id>/<revision>/{train,val}.jsonl
8
+ <store>/<id>/<revision>/SHA256SUMS
9
+ <store>/<id>/<revision>/<id>.cold/ present only after weights are attached
10
+ """
11
+
12
+ import fcntl
13
+ import hashlib
14
+ import json
15
+ import os
16
+ import re
17
+ import shutil
18
+ import stat
19
+ import subprocess
20
+ import tempfile
21
+ import time
22
+ from collections.abc import Mapping
23
+ from contextlib import contextmanager
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ from .ingest import Corpus, Source, compile_dataset
28
+ from .redact import scrub
29
+ from . import scope_keys
30
+ from .ingest_policy import check_release
31
+
32
+ BASE = {"model": "Qwen/Qwen3.5-9B", "revision": "c202236235762e1c871ad0ccb60c8ee5ba337b9a"}
33
+ SLUG = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
34
+ HEX = re.compile(r"[0-9a-f]{64}")
35
+ PAYLOAD = ("adapter.gguf", "LICENSE.txt", "NOTICE.txt")
36
+ COLD = {"manifest.v2.json", "manifest.v2.sig", *PAYLOAD}
37
+ FILES = {"memory.json", "graph.json", "train.jsonl", "val.jsonl"}
38
+ PRIVATE = "private-local"
39
+ OPEN_LICENSES = ("Apache-2.0", "MIT", "BSD-2-Clause", "BSD-3-Clause")
40
+ PRIVATE_NOTICE = (
41
+ "Private memory cartridge (license: private-local). It may contain facts from its owner's notes.\n"
42
+ "Use it only on the owner's machines. Do not share, publish or sell it.\n")
43
+
44
+
45
+ _LAZY_GRAPH_BYTES = 256 * 1024
46
+
47
+
48
+ class LazyGraph(Mapping):
49
+ """On-demand view over a verified graph.json; delegates to DiskIndex.bundle_graph when attached."""
50
+
51
+ def __init__(self, path, expected_sha256):
52
+ self._path = Path(path)
53
+ self._sha256 = expected_sha256
54
+ self._disk_index = None
55
+ self._data = None
56
+
57
+ def attach_disk_index(self, disk_index):
58
+ if disk_index is not None and disk_index.has_bundle_graph and not getattr(disk_index, "_closed", False):
59
+ self._disk_index = disk_index
60
+ self._data = None
61
+
62
+ def detach_disk_index(self, disk_index):
63
+ if self._disk_index is disk_index:
64
+ self._disk_index = None
65
+
66
+ def _backing(self):
67
+ idx = self._disk_index
68
+ if idx is not None and idx.has_bundle_graph and not getattr(idx, "_closed", False):
69
+ return idx.bundle_graph
70
+ if self._data is None:
71
+ raw = self._path.read_bytes()
72
+ if hashlib.sha256(raw).hexdigest() != self._sha256:
73
+ raise ValueError("graph.json changed during load")
74
+ self._data = json.loads(raw)
75
+ return self._data
76
+
77
+ def __contains__(self, key):
78
+ return key in self._backing()
79
+
80
+ def __getitem__(self, key):
81
+ return self._backing()[key]
82
+
83
+ def get(self, key, default=None):
84
+ return self._backing().get(key, default)
85
+
86
+ def __len__(self):
87
+ return len(self._backing())
88
+
89
+ def __iter__(self):
90
+ return iter(self._backing())
91
+
92
+
93
+ @dataclass(frozen=True)
94
+ class Bundle:
95
+ id: str
96
+ revision: str
97
+ path: Path
98
+ manifest: dict
99
+ graph: Mapping
100
+
101
+ @property
102
+ def sources(self):
103
+ return [Source(s["kind"], s["label"], s["root"]) for s in self.manifest["sources"]]
104
+
105
+ @property
106
+ def trained(self):
107
+ return self.manifest["cartridge"] is not None
108
+
109
+
110
+ def encode(value):
111
+ return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False).encode()
112
+
113
+
114
+ def sha256_file(path):
115
+ with open(path, "rb") as stream:
116
+ return hashlib.file_digest(stream, "sha256").hexdigest()
117
+
118
+
119
+ def slug(value):
120
+ if not isinstance(value, str) or not SLUG.fullmatch(value):
121
+ raise ValueError("names use lowercase letters, digits and hyphens, up to 64 characters")
122
+ return value
123
+
124
+
125
+ def _hex(value):
126
+ if not isinstance(value, str) or not HEX.fullmatch(value):
127
+ raise ValueError("expected a SHA-256 value")
128
+ return value
129
+
130
+
131
+ def _write(path, data):
132
+ with open(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600), "wb") as out:
133
+ out.write(data)
134
+ out.flush()
135
+ os.fsync(out.fileno())
136
+
137
+
138
+ def _check_private(path, directory=False):
139
+ info = os.lstat(path)
140
+ kind, mode = (stat.S_ISDIR, 0o700) if directory else (stat.S_ISREG, 0o600)
141
+ if not kind(info.st_mode) or stat.S_IMODE(info.st_mode) != mode or info.st_uid != os.getuid():
142
+ raise ValueError(f"{Path(path).name} must be your own {'0700 folder' if directory else '0600 file'}")
143
+
144
+
145
+ def _home(store, ident, create=False):
146
+ home = Path(store).expanduser().absolute() / slug(ident)
147
+ if create:
148
+ home.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
149
+ home.mkdir(mode=0o700, exist_ok=True)
150
+ _check_private(home.parent, directory=True)
151
+ _check_private(home, directory=True)
152
+ return home
153
+
154
+
155
+ @contextmanager
156
+ def _locked(home):
157
+ with open(os.open(home / "lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), "r+") as lock:
158
+ fcntl.flock(lock, fcntl.LOCK_EX)
159
+ yield
160
+
161
+
162
+ def _pointer(home):
163
+ try:
164
+ _check_private(home / "current.json")
165
+ state = json.loads((home / "current.json").read_bytes())
166
+ except FileNotFoundError:
167
+ return {"active": None, "previous": None}
168
+ if not isinstance(state, dict) or state.keys() != {"active", "previous"}:
169
+ raise ValueError("invalid revision pointer")
170
+ for revision in state.values():
171
+ if revision is not None:
172
+ _hex(revision)
173
+ return state
174
+
175
+
176
+ def _swap(home, active, previous):
177
+ pending = home / ".current.new"
178
+ pending.unlink(missing_ok=True)
179
+ _write(pending, encode({"active": active, "previous": previous}))
180
+ os.replace(pending, home / "current.json")
181
+ _sync(home)
182
+
183
+
184
+ def _sync(folder):
185
+ handle = os.open(folder, os.O_RDONLY | os.O_DIRECTORY)
186
+ try:
187
+ os.fsync(handle)
188
+ finally:
189
+ os.close(handle)
190
+
191
+
192
+ def check(path, weights=True):
193
+ """Check exact members, private modes and SHA256SUMS. Skip the large adapter when weights is False."""
194
+ _check_private(path, directory=True)
195
+ expected = set(FILES)
196
+ colds = [p for p in path.iterdir() if p.suffix == ".cold"]
197
+ for cold in colds:
198
+ _check_private(cold, directory=True)
199
+ expected |= {f"{cold.name}/{name}" for name in COLD}
200
+ found = {str(p.relative_to(path)) for p in path.rglob("*") if p.is_symlink() or not p.is_dir()}
201
+ _check_private(path / "SHA256SUMS")
202
+ rows = (line.split(" ", 1) for line in (path / "SHA256SUMS").read_text().splitlines())
203
+ sums = {name: digest for digest, name in rows}
204
+ if len(colds) > 1 or found != expected | {"SHA256SUMS"} or sums.keys() != expected:
205
+ raise ValueError("the bundle has missing or unexpected files")
206
+ for name in found:
207
+ _check_private(path / name)
208
+ for name, digest in sums.items():
209
+ if (weights or not name.endswith("/adapter.gguf")) and sha256_file(path / name) != digest:
210
+ raise ValueError(f"{name} does not match SHA256SUMS")
211
+ return sums
212
+
213
+
214
+ def load(store, ident, revision=None, weights=False, *, trusted=None):
215
+ home = _home(store, ident)
216
+ revision = _hex(revision or _pointer(home)["active"])
217
+ path = home / revision
218
+ sums = check(path, weights)
219
+ raw = (path / "memory.json").read_bytes()
220
+ manifest = json.loads(raw)
221
+ if not isinstance(manifest, dict):
222
+ raise ValueError("invalid memory manifest")
223
+ if trusted is not None:
224
+ scope_keys.verify(manifest, trusted)
225
+ if hashlib.sha256(raw).hexdigest() != revision or manifest["id"] != ident:
226
+ raise ValueError("the bundle does not match its revision name")
227
+ if manifest["type"] != "coldmemory" or manifest["version"] not in (1, 2):
228
+ raise ValueError("unsupported bundle version")
229
+ if set(manifest["files"]) != FILES - {"memory.json"}:
230
+ raise ValueError("unexpected manifest files")
231
+ if trusted is not None and manifest["version"] != 2:
232
+ raise ValueError("unsupported signed bundle version")
233
+ if manifest["cartridge"]:
234
+ cold = path / f"{ident}.cold"
235
+ cartridge = (cold / "manifest.v2.json").read_bytes()
236
+ if hashlib.sha256(cartridge).hexdigest() != manifest["cartridge"]:
237
+ raise ValueError("the weights do not belong to this revision")
238
+ if trusted is not None:
239
+ payload = json.loads(cartridge)["files"]
240
+ if set(payload) != set(PAYLOAD) or any(
241
+ sha256_file(cold / name) != payload[name]["sha256"] for name in PAYLOAD):
242
+ raise ValueError("signed cartridge payload mismatch")
243
+ graph_path = path / "graph.json"
244
+ if any(sums[name] != manifest["files"][name] for name in ("graph.json", "train.jsonl", "val.jsonl")):
245
+ raise ValueError("the data does not belong to this revision")
246
+ if graph_path.stat().st_size <= _LAZY_GRAPH_BYTES:
247
+ raw_graph = graph_path.read_bytes()
248
+ if hashlib.sha256(raw_graph).hexdigest() != manifest["files"]["graph.json"]:
249
+ raise ValueError("the data does not belong to this revision")
250
+ graph = json.loads(raw_graph)
251
+ else:
252
+ graph = LazyGraph(graph_path, manifest["files"]["graph.json"])
253
+ return Bundle(ident, revision, path, manifest, graph)
254
+
255
+
256
+ def _stamp(home):
257
+ """Stat of the bundle folder, its pointer, and the live revision with every file in it.
258
+ Any write or chmod changes ctime, even one that keeps mtime."""
259
+ revision = home / _hex(_pointer(home)["active"])
260
+ stamp = []
261
+ for path in [home, home / "current.json", revision, *sorted(revision.rglob("*"))]:
262
+ info = os.lstat(path)
263
+ stamp.append((str(path), info.st_mode, info.st_ino, info.st_size, info.st_mtime_ns, info.st_ctime_ns))
264
+ return stamp
265
+
266
+
267
+ def list_bundles(store, scopes, *, trusted=None, cache=None):
268
+ """Return the bundles these scopes may see, and how many bundles could not be read.
269
+
270
+ With a cache dict, a bundle whose files and trust anchors are unchanged since its last full check is reused."""
271
+ root = Path(store).expanduser().absolute()
272
+ _check_private(root, directory=True)
273
+ bundles, broken = [], 0
274
+ for home in sorted(root.iterdir()):
275
+ if not SLUG.fullmatch(home.name):
276
+ continue
277
+ try:
278
+ if not os.path.lexists(home / "current.json") and home.is_dir() and not home.is_symlink():
279
+ _check_private(home, directory=True)
280
+ entries = list(home.iterdir())
281
+ if len(entries) == 1 and entries[0].name == "lock" and not entries[0].is_symlink() and entries[0].is_file():
282
+ continue
283
+ stamp = (_stamp(home), trusted) if cache is not None else None
284
+ if stamp is not None and home.name in cache and cache[home.name][0] == stamp:
285
+ bundle = cache[home.name][1]
286
+ else:
287
+ bundle = load(store, home.name, trusted=trusted)
288
+ if cache is not None:
289
+ cache[home.name] = (stamp, bundle)
290
+ if trusted is None and bundle.manifest["version"] == 2:
291
+ raise ValueError("signed bundle requires a trust anchor")
292
+ except (OSError, ValueError, KeyError, TypeError):
293
+ broken += 1
294
+ continue
295
+ if bundle.manifest["scope"] in scopes:
296
+ bundles.append(bundle)
297
+ return bundles, broken
298
+
299
+
300
+ def _publish(home, manifest, files, cold=None):
301
+ raw = encode(manifest)
302
+ revision = hashlib.sha256(raw).hexdigest()
303
+ stage = Path(tempfile.mkdtemp(prefix=".stage-", dir=home))
304
+ try:
305
+ for name, data in {"memory.json": raw, **files}.items():
306
+ _write(stage / name, data)
307
+ if cold:
308
+ os.rename(cold, stage / cold.name)
309
+ names = sorted(str(p.relative_to(stage)) for p in stage.rglob("*") if p.is_file())
310
+ _write(stage / "SHA256SUMS", "".join(f"{sha256_file(stage / n)} {n}\n" for n in names).encode())
311
+ check(stage)
312
+ _sync(stage)
313
+ if not (home / revision).exists():
314
+ os.rename(stage, home / revision)
315
+ _sync(home)
316
+ finally:
317
+ shutil.rmtree(stage, ignore_errors=True)
318
+ return revision
319
+
320
+
321
+ def source_hashes(graph, sources):
322
+ return {s.label: hashlib.sha256("".join(
323
+ f"{entry['sha256']} {key}\n" for key, entry in sorted(graph.items())
324
+ if key.startswith(s.label + "/")).encode()).hexdigest() for s in sources}
325
+
326
+
327
+ def _compile_bundle_locked(store, ident, sources, scope="private", *, sign_key=None, policy=None, allow_overwrite=True,
328
+ verify=None, corpus=None):
329
+ """Build a revision while caller holds _locked(_home(store, ident, create=True))."""
330
+ home = _home(store, ident, create=True)
331
+ if not allow_overwrite:
332
+ existing_state = _pointer(home)
333
+ if existing_state["active"] is not None:
334
+ existing_live = load(store, ident, existing_state["active"])
335
+ expected_version = 2 if sign_key is not None else 1
336
+ if (existing_live.manifest.get("scope") != scope
337
+ or existing_live.manifest.get("version") != expected_version
338
+ or [(s.kind, s.root) for s in existing_live.sources] != [(s.kind, s.root) for s in sources]):
339
+ raise ValueError(f"bundle ID '{ident}' already exists for different sources or signing mode")
340
+ if corpus is None:
341
+ corpus = Corpus(sources)
342
+ corpus.refresh()
343
+ if not corpus.notes:
344
+ raise ValueError("no readable notes found")
345
+ graph = corpus.graph()
346
+ approved, outdated = [], 0
347
+ for entry in _read_queue(home):
348
+ if not entry["approved"]:
349
+ continue
350
+ if all(graph.get(s["key"], {}).get("sha256") == s["sha256"]
351
+ and not corpus.notes[s["key"]].stale for s in entry["sources"]):
352
+ approved.append(entry)
353
+ else:
354
+ outdated += 1
355
+ if scope != "private" or policy is not None:
356
+ check_release(corpus, approved, scope, policy)
357
+ train, val = compile_dataset(corpus, approved)
358
+ files = {"graph.json": encode(graph)}
359
+ files |= {f"{name}.jsonl": b"".join(encode(row) + b"\n" for row in rows)
360
+ for name, rows in (("train", train), ("val", val))}
361
+ hashes = source_hashes(graph, sources)
362
+ manifest = {
363
+ "type": "coldmemory", "version": 1, "id": ident, "scope": scope, "base": BASE,
364
+ "built_at": int(time.time()), "cartridge": None,
365
+ "sources": [{"kind": s.kind, "label": s.label, "root": s.root, "sha256": hashes[s.label]}
366
+ for s in sources],
367
+ "files": {name: hashlib.sha256(data).hexdigest() for name, data in files.items()},
368
+ "counts": {"notes": len(graph), "train": len(train), "val": len(val),
369
+ "approved_notes": len(approved), "outdated_approved_notes": outdated},
370
+ "skipped": dict(corpus.skipped)}
371
+ if sign_key is not None:
372
+ manifest["version"] = 2
373
+ manifest["scope_signature"] = scope_keys.sign(manifest, sign_key)
374
+ existed_before = (home / hashlib.sha256(encode(manifest)).hexdigest()).exists()
375
+ revision = _publish(home, manifest, files)
376
+ candidate = load(store, ident, revision)
377
+ state = _pointer(home)
378
+ if verify is not None:
379
+ try:
380
+ verify(candidate, corpus)
381
+ except Exception:
382
+ if not existed_before and revision not in state.values():
383
+ shutil.rmtree(home / revision, ignore_errors=True)
384
+ raise
385
+ live = load(store, ident) if state["active"] else None
386
+ if state["active"] != revision and not (live and live.trained):
387
+ _swap(home, revision, state["active"])
388
+ _prune(home)
389
+ return candidate
390
+
391
+
392
+ def compile_bundle(store, ident, sources, scope="private", *, sign_key=None, policy=None, allow_overwrite=True,
393
+ verify=None):
394
+ """Build a revision. It goes live at once unless that would replace live weights with none."""
395
+ slug(scope)
396
+ if scope != "private" and sign_key is None:
397
+ raise ValueError("non-private compilation requires a scope signing key")
398
+ home = _home(store, ident, create=True)
399
+ if any(Path(s.root) in (home, *home.parents) for s in sources):
400
+ raise ValueError("the store must be outside every source folder")
401
+ with _locked(home):
402
+ return _compile_bundle_locked(store, ident, sources, scope, sign_key=sign_key, policy=policy,
403
+ allow_overwrite=allow_overwrite, verify=verify)
404
+
405
+
406
+ def attach(store, ident, revision, trained, key, creator, release="1.0.0", license=PRIVATE, *, scope_key=None):
407
+ """Sign trained weights into a new revision. Activating it is a separate step.
408
+
409
+ The default `private-local` license marks a `memory` cartridge that must not leave the owner's machines.
410
+ An open license name makes a shareable `expert` cartridge that today's v2 hosts accept."""
411
+ home = _home(store, ident)
412
+ trained = Path(trained)
413
+ if not re.fullmatch(r"(0|[1-9]\d*)(\.(0|[1-9]\d*)){2}", release):
414
+ raise ValueError("release must look like 1.0.0")
415
+ if license != PRIVATE and license not in OPEN_LICENSES:
416
+ raise ValueError(f"license must be {PRIVATE} or one of {', '.join(OPEN_LICENSES)}")
417
+ kind, notice = ("memory", PRIVATE_NOTICE) if license == PRIVATE else ("expert", f"Adapter license: {license}.\n")
418
+ with _locked(home):
419
+ source = load(store, ident, revision)
420
+ if source.manifest["version"] == 2:
421
+ if scope_key is None:
422
+ raise ValueError("signed revision requires its scope signing key")
423
+ scope_keys.verify(source.manifest, {source.manifest["scope"]: scope_keys.public_der(scope_key, private=True)})
424
+ receipt = json.loads((trained / "receipt.json").read_bytes())
425
+ if receipt["train_sha256"] != source.manifest["files"]["train.jsonl"]:
426
+ raise ValueError("these weights were trained on a different revision")
427
+ if receipt["base_model"] != source.manifest["base"]:
428
+ raise ValueError("these weights use a different base model")
429
+ base = receipt["base"]
430
+ if base.keys() != {"sha256", "runtime_sha256", "architecture"}:
431
+ raise ValueError("the receipt needs base, runtime and architecture pins")
432
+ _hex(base["sha256"]), _hex(base["runtime_sha256"])
433
+
434
+ stage = Path(tempfile.mkdtemp(prefix=".stage-", dir=home))
435
+ try:
436
+ cold = stage / f"{ident}.cold"
437
+ cold.mkdir(mode=0o700)
438
+ with open(trained / "adapter.gguf", "rb") as inp, \
439
+ open(os.open(cold / "adapter.gguf", os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as out:
440
+ shutil.copyfileobj(inp, out, 1 << 20)
441
+ out.flush()
442
+ os.fsync(out.fileno())
443
+ if sha256_file(cold / "adapter.gguf") != receipt["adapter_sha256"]:
444
+ raise ValueError("adapter.gguf does not match its receipt")
445
+ _write(cold / "LICENSE.txt", notice.encode())
446
+ _write(cold / "NOTICE.txt", f"Base model: {BASE['model']} (Apache-2.0).\n{notice}".encode())
447
+ _write(cold / "manifest.v2.json", encode({
448
+ "type": "coldvoice-cartridge", "version": 2, "id": ident, "release": release,
449
+ "creator": slug(creator), "kind": kind, "parent_sha256": None,
450
+ "registers": ["memory"], "plugins": [], "base": base,
451
+ "license": {"adapter": license, "base": "Apache-2.0", "commercial_safe": False,
452
+ "rights_sha256": sha256_file(cold / "NOTICE.txt")},
453
+ "files": {name: {"bytes": (cold / name).stat().st_size, "sha256": sha256_file(cold / name)}
454
+ for name in PAYLOAD}}))
455
+ signature = subprocess.run(
456
+ ["openssl", "pkeyutl", "-sign", "-rawin", "-inkey", str(Path(key).absolute()),
457
+ "-in", str(cold / "manifest.v2.json")], capture_output=True)
458
+ if signature.returncode or len(signature.stdout) != 64:
459
+ raise ValueError("openssl could not sign with that Ed25519 key")
460
+ _write(cold / "manifest.v2.sig", signature.stdout)
461
+ manifest = source.manifest | {"cartridge": sha256_file(cold / "manifest.v2.json")}
462
+ if source.manifest["version"] == 2:
463
+ manifest["scope_signature"] = scope_keys.sign(manifest, scope_key)
464
+ files = {name: (source.path / name).read_bytes() for name in FILES - {"memory.json"}}
465
+ return load(store, ident, _publish(home, manifest, files, cold), weights=True)
466
+ finally:
467
+ shutil.rmtree(stage, ignore_errors=True)
468
+
469
+
470
+ def activate(store, ident, revision=None):
471
+ """Make a revision live after a full check. With no revision, go back to the previous one."""
472
+ home = _home(store, ident)
473
+ with _locked(home):
474
+ state = _pointer(home)
475
+ revision = revision or state["previous"]
476
+ if not revision:
477
+ raise ValueError("there is no previous revision")
478
+ bundle = load(store, ident, revision, weights=True)
479
+ if revision != state["active"]:
480
+ _swap(home, revision, state["active"])
481
+ _prune(home)
482
+ return bundle
483
+
484
+
485
+ def _prune(home):
486
+ built = {p.name: json.loads((p / "memory.json").read_bytes())["built_at"]
487
+ for p in home.iterdir() if HEX.fullmatch(p.name)}
488
+ cutoff = min(built[r] for r in _pointer(home).values() if r)
489
+ pruned = []
490
+ for name, when in built.items():
491
+ if when < cutoff:
492
+ shutil.rmtree(home / name)
493
+ pruned.append(name)
494
+ if pruned:
495
+ from .disk_index import prune_bundle_indexes
496
+ prune_bundle_indexes(home, pruned)
497
+
498
+
499
+ def freshness(bundle, corpus):
500
+ now, then = {k: n.sha256 for k, n in corpus.notes.items()}, bundle.graph
501
+ return {"added": sorted(now.keys() - then.keys()), "deleted": sorted(then.keys() - now.keys()),
502
+ "changed": sorted(k for k in now.keys() & then.keys() if now[k] != then[k]["sha256"])}
503
+
504
+
505
+ def _read_queue(home):
506
+ entries = {}
507
+ try:
508
+ _check_private(home / "queue.jsonl")
509
+ lines = (home / "queue.jsonl").read_text().splitlines()
510
+ except FileNotFoundError:
511
+ return []
512
+ for line in lines:
513
+ row = json.loads(line)
514
+ if "approve" in row:
515
+ entries[row["approve"]]["approved"] = True
516
+ else:
517
+ entries[row["id"]] = row | {"approved": False}
518
+ return list(entries.values())
519
+
520
+
521
+ def _append(home, row):
522
+ with open(os.open(home / "queue.jsonl", os.O_WRONLY | os.O_CREAT | os.O_APPEND | os.O_NOFOLLOW, 0o600), "ab") as out:
523
+ _check_private(home / "queue.jsonl")
524
+ out.write(encode(row) + b"\n")
525
+ out.flush()
526
+ os.fsync(out.fileno())
527
+
528
+
529
+ def read_queue(store, ident):
530
+ home = _home(store, ident)
531
+ with _locked(home):
532
+ return _read_queue(home)
533
+
534
+
535
+ def record_note(store, ident, title, decision, sources):
536
+ """Queue a note. It cannot reach training until the owner approves it."""
537
+ home = _home(store, ident)
538
+ entry = {"title": " ".join(scrub(title).split()), "decision": " ".join(scrub(decision).split()),
539
+ "sources": sources}
540
+ entry["id"] = hashlib.sha256(encode(entry)).hexdigest()[:16]
541
+ with _locked(home):
542
+ known = _read_queue(home)
543
+ if any(e["id"] == entry["id"] for e in known):
544
+ return entry["id"]
545
+ if sum(not e["approved"] for e in known) >= 500:
546
+ raise ValueError("500 notes are waiting for review; approve some first")
547
+ _append(home, entry | {"recorded_at": int(time.time())})
548
+ return entry["id"]
549
+
550
+
551
+ def approve(store, ident, entry_id):
552
+ home = _home(store, ident)
553
+ with _locked(home):
554
+ entry = next((e for e in _read_queue(home) if e["id"] == entry_id), None)
555
+ if entry is None:
556
+ raise ValueError("no recorded note has that id")
557
+ if not entry["approved"]:
558
+ _append(home, {"approve": entry_id})
559
+ return entry
@@ -0,0 +1,27 @@
1
+ """Read the file:line citations that memory_ask, ledger_answer and disk_brief print.
2
+
3
+ Each citation is two lines: `- <path>:<line>[-<end>] [<state>]` and ` "<quote>"`."""
4
+
5
+ import re
6
+ from typing import NamedTuple
7
+
8
+ REF = r"\S.*?:\d+(?:-\d+)?"
9
+ _ITEM = re.compile(rf'^- ({REF})(?: \[([^\]\n]*)\])?\n "(.*)"$', re.M)
10
+ _CURRENT = re.compile(r"(?:current|in force)\b|\d{4}-\d\d-\d\d \d\d:\d\d$")
11
+ _STALE_NOTES = re.compile(r"^Stale notes$", re.M)
12
+
13
+
14
+ class Citation(NamedTuple):
15
+ ref: str
16
+ state: str
17
+ quote: str
18
+ is_current: bool
19
+
20
+
21
+ def parse_citations(text):
22
+ """Every quoted citation in a brief, in order. A citation is current only when its state says current, in force,
23
+ or is a turn's timestamp, and it is not listed under Stale notes; an archive, stale or missing state is not."""
24
+ stale = _STALE_NOTES.search(text)
25
+ stale_from = stale.start() if stale else len(text)
26
+ return [Citation(m[1], m[2] or "", m[3], m.start() < stale_from and bool(_CURRENT.match(m[2] or "")))
27
+ for m in _ITEM.finditer(text)]