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/ledger.py ADDED
@@ -0,0 +1,417 @@
1
+ """Keyed decision ledger: one owner decision per file, the same key supersedes, `rm` forgets.
2
+
3
+ Each scope has its own ledger, <store>/_ledger/<scope> (a "book"); the public scope has none. `<key>.md` holds
4
+ the decision in force for that key in the owner's words, with secrets redacted and whitespace collapsed to one
5
+ line. Updating a key moves the old file to history/ and links the two with supersedes/superseded_by, so a
6
+ superseded decision is never served as current. Each option the owner ruled out is one `why not:` line after
7
+ the words, so it keeps its own file:line. turns.jsonl keeps each owner turn, with secrets redacted, the
8
+ moment it is said, so the query tool finds it at once; short confirmations ("yes, do it") keep the end of the
9
+ proposal they answered and feed NOW's 48 hour recent list.
10
+ """
11
+
12
+ import argparse
13
+ import contextlib
14
+ import fcntl
15
+ import json
16
+ import os
17
+ import re
18
+ import sys
19
+ import time
20
+ from dataclasses import dataclass
21
+ from datetime import datetime, timezone
22
+ from pathlib import Path
23
+
24
+ from .cartridge_spec import _check_private
25
+ from .redact import scrub
26
+
27
+ KEY = re.compile(r"[a-z0-9][a-z0-9-]{0,63}")
28
+ CAPTURE = re.compile(r"^\s*(remember|decided|decision|rule)\s*:\s*(.+)$", re.I | re.M)
29
+ WHY_NOT = re.compile(r"^\s*(?:why[ -]?not|rejected)\s*:\s*(.+)$", re.I)
30
+ WHY_NOT_LINE = "why not: "
31
+ WHY_NOT_MAX = 8
32
+ CONFIRM = re.compile(r"^\s*(yes|yep|yeah|ok|okay|go|go ahead|do it|approved|agreed|sounds good|ship it|lgtm|"
33
+ r"launch it|merge it)\b", re.I)
34
+ RELAYED = "sent this message, not the user"
35
+ OPENBOT_MESSAGE = "\n--- current message ---\n"
36
+ RECENT_SECONDS = 48 * 3600
37
+ SAME_TURN_SECONDS = 120
38
+ STOP = set("a an and are as at be but by can did do does for from has have how i in is it its me my of on or our "
39
+ "should so that the their them then there this to us was we were what when where which who why will "
40
+ "with would you your now current currently".split())
41
+
42
+
43
+ @dataclass
44
+ class Decision:
45
+ key: str
46
+ quote: str
47
+ decided: str
48
+ author: str
49
+ source: str
50
+ supersedes: str
51
+ path: Path
52
+ line: int
53
+ why_not: tuple = ()
54
+ why_not_lines: tuple = ()
55
+ locked: bool = False
56
+
57
+ def cite(self, base):
58
+ return f"{os.path.relpath(self.path, base)}:{self.line}"
59
+
60
+
61
+ def book(store, scope="private"):
62
+ """The ledger folder of one scope. Owner decisions are never public."""
63
+ if scope == "public" or not KEY.fullmatch(scope):
64
+ raise ValueError("the ledger is for non-public scopes only")
65
+ return Path(store).expanduser().absolute() / "_ledger" / scope
66
+
67
+
68
+ def store_of(folder):
69
+ return Path(folder).parent.parent
70
+
71
+
72
+ def now_iso():
73
+ return datetime.now(timezone.utc).replace(microsecond=0).isoformat()
74
+
75
+
76
+ def _mkdir(path):
77
+ path.mkdir(mode=0o700, parents=True, exist_ok=True)
78
+ _check_private(path, directory=True)
79
+
80
+
81
+ def _write(path, text):
82
+ tmp = path.with_name(f".{path.name}.{os.getpid()}.tmp")
83
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
84
+ with os.fdopen(fd, "w", encoding="utf-8") as out:
85
+ out.write(text)
86
+ os.replace(tmp, path)
87
+
88
+
89
+ def _one_line(text, limit=1500):
90
+ return " ".join(scrub(text).split())[:limit]
91
+
92
+
93
+ def _read(path):
94
+ """Parse one decision file; None for anything that is not a private regular file in the expected shape."""
95
+ try:
96
+ _check_private(path)
97
+ lines = path.read_text(encoding="utf-8").splitlines()
98
+ except (OSError, ValueError, UnicodeDecodeError):
99
+ return None
100
+ if not lines or lines[0] != "---" or "---" not in lines[1:]:
101
+ return None
102
+ end = lines.index("---", 1)
103
+ meta = dict(line.partition(": ")[::2] for line in lines[1:end])
104
+ body = [(n, text) for n, text in enumerate(lines[end + 1:], end + 2) if text.strip()]
105
+ if not body or not KEY.fullmatch(meta.get("key", "")):
106
+ return None
107
+ rejected = [(n, text[len(WHY_NOT_LINE):]) for n, text in body[1:] if text.startswith(WHY_NOT_LINE)]
108
+ return Decision(meta["key"], body[0][1], meta.get("decided", ""), meta.get("author", "owner"),
109
+ meta.get("source", ""), meta.get("supersedes", ""), path, body[0][0],
110
+ tuple(text for _, text in rejected), tuple(n for n, _ in rejected), meta.get("locked") == "true")
111
+
112
+
113
+ def load(folder):
114
+ """Decisions in force, newest first."""
115
+ folder = Path(folder)
116
+ if not folder.is_dir():
117
+ return []
118
+ found = [d for p in folder.glob("*.md") if (d := _read(p)) and d.key == p.stem]
119
+ return sorted(found, key=lambda d: (d.decided, d.key), reverse=True)
120
+
121
+
122
+ def history(folder, key):
123
+ if not KEY.fullmatch(key):
124
+ raise ValueError("no such decision key")
125
+ folder = Path(folder) / "history"
126
+ found = [d for p in folder.glob(f"{key}@*.md") if (d := _read(p))] if folder.is_dir() else []
127
+ return sorted(found, key=lambda d: d.decided, reverse=True)
128
+
129
+
130
+ def _why_not(why_not):
131
+ items = [why_not] if isinstance(why_not, str) else why_not or ()
132
+ found = []
133
+ for item in items:
134
+ text = _one_line(item, 300)
135
+ if text and text not in found:
136
+ found.append(text)
137
+ return tuple(found[:WHY_NOT_MAX])
138
+
139
+
140
+ def decide(folder, key, quote, *, source="", author="owner", decided=None, why_not=(), locked=None):
141
+ """Write the decision for key, with the options the owner ruled out. An existing decision for the key moves to
142
+ history/ and is superseded; the new one carries only its own why_not. Writing what is already in force changes
143
+ nothing. A locked decision wins over the same key in every other scope of a server's stack; with locked left as
144
+ None, a new version keeps the lock of the decision it replaces."""
145
+ key = key.strip().lower()
146
+ if not KEY.fullmatch(key):
147
+ raise ValueError("a decision key is lowercase letters, digits and dashes, at most 64 characters")
148
+ quote = _one_line(quote)
149
+ if not quote:
150
+ raise ValueError("a decision needs the owner's words")
151
+ folder = Path(folder)
152
+ with _locked(folder):
153
+ return _decide(folder, key, quote, source, author, decided, _why_not(why_not), locked)
154
+
155
+
156
+ @contextlib.contextmanager
157
+ def _locked(folder):
158
+ _mkdir(folder)
159
+ fd = os.open(folder / ".lock", os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600)
160
+ try:
161
+ fcntl.flock(fd, fcntl.LOCK_EX)
162
+ yield
163
+ finally:
164
+ os.close(fd)
165
+
166
+
167
+ def _decide(folder, key, quote, source, author, decided, why_not, locked=None):
168
+ path, supersedes = folder / f"{key}.md", ""
169
+ old = _read(path) if path.exists() else None
170
+ locked = bool(old and old.locked) if locked is None else bool(locked)
171
+ if old and ((old.quote, old.why_not, old.locked) == (quote, why_not, locked) or (decided and _seconds(decided) < _seconds(old.decided))):
172
+ return old
173
+ if old:
174
+ _mkdir(folder / "history")
175
+ supersedes = stamp = f"{key}@{re.sub(r'[^0-9]', '', old.decided)[:14] or int(time.time())}"
176
+ number = 1
177
+ while (folder / "history" / f"{supersedes}.md").exists():
178
+ number += 1
179
+ supersedes = f"{stamp}-{number}"
180
+ text = path.read_text(encoding="utf-8").replace("\n---\n", f"\nsuperseded_by: {key}\n---\n", 1)
181
+ _write(folder / "history" / f"{supersedes}.md", text)
182
+ meta = [f"key: {key}", f"decided: {decided or now_iso()}", f"author: {author}"]
183
+ meta += [f"source: {_one_line(source, 300)}"] if source else []
184
+ meta += [f"supersedes: {supersedes}"] if supersedes else []
185
+ meta += ["locked: true"] if locked else []
186
+ _write(path, "---\n" + "\n".join(meta) + "\n---\n" + "".join(f"{line}\n" for line in
187
+ (quote, *(WHY_NOT_LINE + w for w in why_not))))
188
+ return _read(path)
189
+
190
+
191
+ def forget(folder, key):
192
+ """`rm` for one key. Running sessions get a retraction line on their next turn."""
193
+ if not KEY.fullmatch(key):
194
+ raise ValueError("no such decision key")
195
+ (Path(folder) / f"{key}.md").unlink()
196
+
197
+
198
+ def words(text):
199
+ found = set()
200
+ for word in re.findall(r"[a-z0-9]+(?:\.[0-9]+)?", text.lower()):
201
+ if word not in STOP:
202
+ found.add(word[:-1] if len(word) > 3 and word.endswith("s") and not word.endswith("ss") else word)
203
+ return found
204
+
205
+
206
+ def family(folder, d):
207
+ """The content words of a decision and of every version it replaced."""
208
+ return words(" ".join([d.key.replace("-", " "), d.quote, *(old.quote for old in history(folder, d.key))]))
209
+
210
+
211
+ def match(folder, decisions, query, limit=3):
212
+ """Decisions whose words, or the words of a version they replaced, share enough with the query, best first."""
213
+ asked = words(query) - {"not"}
214
+ if not asked:
215
+ return []
216
+ scored = [(len(asked & (family(folder, d) | words(" ".join(d.why_not)))), i, d) for i, d in enumerate(decisions)]
217
+ need = min(2, len(asked))
218
+ return [d for score, _, d in sorted(scored, key=lambda s: (-s[0], s[1])) if score >= need][:limit]
219
+
220
+
221
+ def _turns(folder, last=None):
222
+ """Rows of turns.jsonl with their line numbers; with last, only rows in the final `last` bytes, numbered 0."""
223
+ path = Path(folder) / "turns.jsonl"
224
+ try:
225
+ _check_private(path)
226
+ with path.open("rb") as stream:
227
+ stream.seek(max(os.fstat(stream.fileno()).st_size - last, 0) if last else 0)
228
+ first = 0 if last else 1
229
+ lines = stream.read().decode("utf-8", "ignore").splitlines()
230
+ except (OSError, ValueError):
231
+ return []
232
+ rows = []
233
+ for number, line in enumerate(lines, first):
234
+ try:
235
+ rows.append(dict(json.loads(line), line=number))
236
+ except (ValueError, TypeError):
237
+ continue
238
+ return rows
239
+
240
+
241
+ def recent(folder, seconds=RECENT_SECONDS):
242
+ """Owner confirmations from the last 48 hours with the proposal each answered, newest first."""
243
+ cutoff = datetime.now(timezone.utc).timestamp() - seconds
244
+ return [r for r in _turns(folder)[::-1]
245
+ if r.get("context") and datetime.fromisoformat(r["when"]).timestamp() >= cutoff]
246
+
247
+
248
+ def search_turns(folder, query, limit=3):
249
+ """Owner turns that share enough content words with the query, newest first. Every turn stays searchable."""
250
+ asked = words(query)
251
+ need = min(2, len(asked))
252
+ found = [r for r in _turns(folder)[::-1] if asked and len(asked & words(r["quote"] + " " + r.get("context", ""))) >= need]
253
+ return found[:limit]
254
+
255
+
256
+ def _seconds(when):
257
+ try:
258
+ stamp = datetime.fromisoformat(when)
259
+ except (TypeError, ValueError):
260
+ return 0.0
261
+ return (stamp if stamp.tzinfo else stamp.replace(tzinfo=timezone.utc)).timestamp()
262
+
263
+
264
+ def remember_turn(folder, text, *, source="", previous="", when=None):
265
+ """Append one owner turn to turns.jsonl, where the query tool finds it at once. A short confirmation keeps the
266
+ end of the proposal it answered. Returns False for a relayed turn, or one this session already recorded with
267
+ the same proposal within two minutes (the hook and the tailer can both see a turn). Writers take the lock."""
268
+ if not text.strip() or RELAYED in text:
269
+ return False
270
+ folder = Path(folder)
271
+ row = {"when": when or now_iso(), "quote": scrub(text.strip()), "source": source}
272
+ if len(text) <= 80 and CONFIRM.match(text) and previous.strip():
273
+ row["context"] = _one_line(previous[-400:], 400)
274
+ same, at = ("quote", "source", "context"), _seconds(row["when"])
275
+ with _locked(folder):
276
+ if any(all(r.get(k) == row.get(k) for k in same) and abs(_seconds(r["when"]) - at) <= SAME_TURN_SECONDS
277
+ for r in _turns(folder, last=65536)):
278
+ return False
279
+ fd = os.open(folder / "turns.jsonl", os.O_WRONLY | os.O_APPEND | os.O_CREAT | os.O_NOFOLLOW, 0o600)
280
+ with os.fdopen(fd, "a", encoding="utf-8") as out:
281
+ out.write(json.dumps(row) + "\n")
282
+ return True
283
+
284
+
285
+ def owner_words(text):
286
+ """The owner's message without the context OpenBot puts in front of it."""
287
+ return (text or "").rpartition(OPENBOT_MESSAGE)[2]
288
+
289
+
290
+ def marked(text):
291
+ """(words, ruled-out options) for each `remember:`/`decided:`/`decision:`/`rule:` line of a turn. A `why not:`
292
+ or `rejected:` line belongs to the marked line above it."""
293
+ found = []
294
+ for line in text.splitlines():
295
+ if mark := CAPTURE.match(line):
296
+ found.append((mark[2], []))
297
+ elif (why := WHY_NOT.match(line)) and found:
298
+ found[-1][1].append(why[1])
299
+ return found
300
+
301
+
302
+ def capture(folder, text, *, source="", previous="", when=None):
303
+ """Keep one owner turn: append it to turns.jsonl and write each marked line (see marked) as a decision.
304
+
305
+ `decided: some-key: words` sets that key; without a key the first content words name it. Messages relayed
306
+ from another agent are not the owner's words and are not kept. A turn already recorded is not applied again,
307
+ and an older turn never replaces a newer decision."""
308
+ text = owner_words(text)
309
+ if not remember_turn(folder, text, source=source, previous=previous, when=when):
310
+ return []
311
+ written = []
312
+ for rest, why_not in marked(text):
313
+ head, sep, tail = rest.partition(":")
314
+ if sep and KEY.fullmatch(head.strip().lower()) and tail.strip():
315
+ key, quote = head.strip().lower(), tail
316
+ else:
317
+ named = "-".join(sorted(words(rest), key=rest.lower().find)[:5])
318
+ key, quote = re.sub(r"[^a-z0-9]+", "-", named)[:64].strip("-"), rest
319
+ try:
320
+ written.append(decide(folder, key, quote, source=source, decided=when, why_not=why_not))
321
+ except ValueError:
322
+ continue
323
+ return written
324
+
325
+
326
+ def tail(folder, roots=None, every=0):
327
+ """Copy new owner turns from Claude Code and Codex transcripts into turns.jsonl, reading only appended bytes.
328
+
329
+ For clients without a per-turn hook. The first run starts at the end of each file (older turns are in the
330
+ sessions archive); files that appear later are read from their start. Turns found in one pass are applied
331
+ oldest first, each with the assistant text before it. With every > 0 it polls that often."""
332
+ from .sessions import _lines, default_roots, message
333
+ folder = Path(folder)
334
+ _mkdir(folder)
335
+ offsets_path = folder / "tail-offsets.json"
336
+ try:
337
+ offsets, first_run = json.loads(offsets_path.read_text(encoding="utf-8")), False
338
+ except (OSError, ValueError):
339
+ offsets, first_run = {}, True
340
+ while True:
341
+ found_turns = []
342
+ for root in roots or default_roots():
343
+ for path in sorted(Path(root).expanduser().rglob("*.jsonl")) if Path(root).expanduser().is_dir() else ():
344
+ if path.is_symlink() or not path.is_file():
345
+ continue
346
+ key, size = str(path), path.stat().st_size
347
+ start, previous = offsets.get(key, [size if first_run else 0, ""])
348
+ start = start if start <= size else 0
349
+ with path.open("rb") as stream:
350
+ stream.seek(start)
351
+ for line, length in _lines(stream):
352
+ start += length
353
+ try:
354
+ found = message(json.loads(line)) if line else None
355
+ except ValueError:
356
+ found = None
357
+ if found and found[0] == "user":
358
+ found_turns.append((found[1] or now_iso(), path.stem, found[2], previous))
359
+ elif found:
360
+ previous = scrub(found[2])[-400:]
361
+ offsets[key] = [start, previous]
362
+ for when, source, text, previous in sorted(found_turns, key=lambda t: t[0]):
363
+ capture(folder, text, source=source, previous=previous, when=when)
364
+ _write(offsets_path, json.dumps(offsets))
365
+ first_run = False
366
+ if every <= 0:
367
+ return len(found_turns)
368
+ time.sleep(every)
369
+
370
+
371
+ def main(argv=None):
372
+ parser = argparse.ArgumentParser(prog="coldmemory.ledger", description=__doc__)
373
+ commands = parser.add_subparsers(dest="command", required=True)
374
+
375
+ def command(name, text, *positional):
376
+ sub = commands.add_parser(name, help=text)
377
+ sub.add_argument("--store", required=True)
378
+ sub.add_argument("--scope", default="private", help="the scope whose ledger to use (not public)")
379
+ for arg in positional:
380
+ sub.add_argument(arg)
381
+ return sub
382
+
383
+ sub = command("decide", "record or replace the owner's decision for a key", "key", "text")
384
+ sub.add_argument("--source", default="", help="file:line the words came from")
385
+ sub.add_argument("--why-not", action="append", default=[], metavar="OPTION",
386
+ help="an option the owner ruled out, with the reason; repeat for each")
387
+ sub.add_argument("--locked", action="store_true",
388
+ help="an org law: no other scope in a server's stack can override this key")
389
+ command("list", "decisions in force, newest first")
390
+ command("forget", "delete a decision (same as rm)", "key")
391
+ command("history", "superseded decisions for a key", "key")
392
+ sub = command("tail", "copy new owner turns from transcripts, for clients without a hook")
393
+ sub.add_argument("--every", type=float, default=0, help="keep polling every N seconds")
394
+ sub.add_argument("root", nargs="*", type=Path, help="default: ~/.claude/projects and ~/.codex/sessions")
395
+ args = parser.parse_args(argv)
396
+ try:
397
+ folder = book(args.store, args.scope)
398
+ if args.command == "decide":
399
+ d = decide(folder, args.key, args.text, source=args.source, why_not=args.why_not, locked=args.locked or None)
400
+ print(f"{d.key}: {d.quote}" + (" [locked]" if d.locked else "")
401
+ + (f" (supersedes {d.supersedes})" if d.supersedes else "")
402
+ + "".join(f"\n why not: {w}" for w in d.why_not))
403
+ elif args.command == "tail":
404
+ print(f"{tail(folder, args.root or None, args.every)} owner turns read")
405
+ elif args.command == "forget":
406
+ forget(folder, args.key)
407
+ print(f"forgot {args.key}")
408
+ else:
409
+ for d in load(folder) if args.command == "list" else history(folder, args.key):
410
+ print(f"{d.key} {d.decided} {d.cite(store_of(folder))}: {d.quote}"
411
+ + "".join(f"\n why not: {w}" for w in d.why_not))
412
+ except (OSError, ValueError) as error:
413
+ sys.exit(f"coldmemory: {error}")
414
+
415
+
416
+ if __name__ == "__main__":
417
+ main()