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/sessions.py ADDED
@@ -0,0 +1,236 @@
1
+ """Copy Claude Code and Codex transcripts into Markdown notes, reading only the bytes appended since the last run.
2
+
3
+ Memory stays flat however large the transcripts are: files are read line by line from a saved byte offset, and a
4
+ line longer than MAX_LINE is skipped without being held. Only user and assistant text is kept, secrets are scrubbed,
5
+ and each note part stays under ingest.MAX_BYTES so `compile --source obsidian:<out>` can read it.
6
+ """
7
+
8
+ import fcntl
9
+ import hashlib
10
+ import json
11
+ import os
12
+ import re
13
+ import sqlite3
14
+ from datetime import datetime
15
+ from pathlib import Path
16
+
17
+ from .ingest import SKIP_DIRS
18
+ from .redact import scrub
19
+
20
+ MAX_LINE = 8 << 20
21
+ MAX_TEXT = 1_000_000
22
+ MAX_BODY = 256 << 10
23
+ PART_BYTES = 512 << 10
24
+ HEAD = 4096
25
+ TEXT_TYPES = ("text", "input_text", "output_text")
26
+ INJECTED_TAGS = ("system-reminder", "command-name", "command-message", "command-args", "command-contents",
27
+ "local-command-stdout", "local-command-stderr", "local-command-caveat", "bash-input", "bash-stdout",
28
+ "bash-stderr", "task-notification", "user-prompt-submit-hook", "environment_context",
29
+ "user_instructions", "turn_aborted")
30
+ _INJECTED = re.compile(r"(\s*<(%s)(\s[^>]*)?>.*?</\2>)+\s*" % "|".join(INJECTED_TAGS), re.S)
31
+
32
+
33
+ def default_roots():
34
+ return [Path.home() / ".claude" / "projects", Path.home() / ".codex" / "sessions"]
35
+
36
+
37
+ def default_out():
38
+ return Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share") / "coldmemory-sessions"
39
+
40
+
41
+ def _text(content):
42
+ if isinstance(content, str):
43
+ return content
44
+ if not isinstance(content, list):
45
+ return ""
46
+ return "\n".join(item["text"] for item in content
47
+ if isinstance(item, dict) and item.get("type") in TEXT_TYPES and isinstance(item.get("text"), str))
48
+
49
+
50
+ def _injected(text):
51
+ return text.startswith("# AGENTS.md instructions") or (
52
+ text.startswith("<") and text.endswith(">") and _INJECTED.fullmatch(text) is not None)
53
+
54
+
55
+ def message(row):
56
+ """(role, timestamp, text) for a Claude Code or Codex user/assistant text message, else None."""
57
+ if not isinstance(row, dict) or row.get("isMeta"):
58
+ return None
59
+ if row.get("type") in ("user", "assistant") and isinstance(row.get("message"), dict):
60
+ role, content = row["type"], row["message"].get("content")
61
+ elif row.get("type") == "response_item" and isinstance(row.get("payload"), dict) \
62
+ and row["payload"].get("type") == "message" and not row["payload"].get("isMeta"):
63
+ role, content = row["payload"].get("role"), row["payload"].get("content")
64
+ else:
65
+ return None
66
+ text = _text(content).strip()
67
+ if role not in ("user", "assistant") or not text or _injected(text):
68
+ return None
69
+ return role, _when(row.get("timestamp")), text
70
+
71
+
72
+ def _when(value):
73
+ try:
74
+ return datetime.fromisoformat(value).isoformat() if isinstance(value, str) and len(value) <= 40 else ""
75
+ except ValueError:
76
+ return ""
77
+
78
+
79
+ def _lines(stream):
80
+ """Yield (line or None, size) for complete lines; stop at a partial last line so the next run retries it."""
81
+ while True:
82
+ line = stream.readline(MAX_LINE)
83
+ if line.endswith(b"\n"):
84
+ yield line, len(line)
85
+ continue
86
+ if len(line) < MAX_LINE:
87
+ return
88
+ size = len(line)
89
+ while not line.endswith(b"\n"):
90
+ line = stream.readline(MAX_LINE)
91
+ if not line:
92
+ return
93
+ size += len(line)
94
+ yield None, size
95
+
96
+
97
+ def _escape(name):
98
+ """Keep names visible to compile (no leading dot) without letting two names collide."""
99
+ if name in SKIP_DIRS:
100
+ return "_p" + name
101
+ return "_" + {".": "d", "_": "u"}[name[0]] + name[1:] if name[:1] in (".", "_") else name
102
+
103
+
104
+ def _note(out, label, root, path, part):
105
+ rel = [_escape(p) for p in path.relative_to(root).parts]
106
+ return out.joinpath(label, *rel, f"{part}.md")
107
+
108
+
109
+ def _forget(out, label, root, path, first=1):
110
+ part = first
111
+ while (note := _note(out, label, root, path, part)).exists():
112
+ note.unlink()
113
+ part += 1
114
+
115
+
116
+ def _render(role, when, text):
117
+ body = scrub(text[:MAX_TEXT]).encode("utf-8", "replace")
118
+ if len(text) > MAX_TEXT or len(body) > MAX_BODY:
119
+ body = body[:MAX_BODY - 13].decode("utf-8", "ignore").encode() + b"\n\n[truncated]"
120
+ return f"## {role}{' · ' + when if when else ''}\n\n".encode() + body + b"\n\n"
121
+
122
+
123
+ def _parse(line, counts):
124
+ """The Markdown for one transcript line, or None."""
125
+ found = None
126
+ if line is None:
127
+ counts["skipped_lines"] += 1
128
+ elif b'"role"' in line:
129
+ try:
130
+ found = message(json.loads(line))
131
+ except ValueError:
132
+ counts["skipped_lines"] += 1
133
+ return _render(*found) if found else None
134
+
135
+
136
+ def _open_part(out, label, root, path, part, part_bytes):
137
+ """Open a note part cut back to its committed size, so a run that stopped early is replayed, not duplicated."""
138
+ target = _note(out, label, root, path, part)
139
+ _mkdir(target.parent)
140
+ note = open(os.open(target, os.O_WRONLY | os.O_CREAT | os.O_NOFOLLOW, 0o600), "wb")
141
+ note.truncate(part_bytes)
142
+ note.seek(part_bytes)
143
+ if not part_bytes:
144
+ header = f"# {scrub(path.name)}\n\nsource: {scrub(str(path))}\n\n".encode("utf-8", "replace")
145
+ note.write(header)
146
+ part_bytes = len(header)
147
+ return note, part_bytes
148
+
149
+
150
+ def _mkdir(path):
151
+ if not path.is_dir():
152
+ _mkdir(path.parent)
153
+ path.mkdir(mode=0o700, exist_ok=True)
154
+
155
+
156
+ def _seen(stream, offset):
157
+ """Fingerprint of the first and last 4 KiB already read: an append keeps it, most rewrites change it."""
158
+ first = stream.read(min(offset, HEAD))
159
+ stream.seek(max(offset - HEAD, 0))
160
+ return hashlib.sha256(first + stream.read(offset - stream.tell())).hexdigest()
161
+
162
+
163
+ def _state(out):
164
+ db = sqlite3.connect(out / ".sessions.sqlite3")
165
+ db.execute("CREATE TABLE IF NOT EXISTS files (path TEXT PRIMARY KEY, mtime INTEGER, seen TEXT, "
166
+ "offset INTEGER, part INTEGER, part_bytes INTEGER)")
167
+ return db
168
+
169
+
170
+ def ingest(roots=None, out=None):
171
+ out = Path(out or default_out()).expanduser()
172
+ out.parent.mkdir(parents=True, exist_ok=True)
173
+ out.mkdir(mode=0o700, exist_ok=True)
174
+ counts = dict(files=0, changed=0, messages=0, bytes_read=0, skipped_lines=0)
175
+ with open(os.open(out / ".lock", os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)) as lock:
176
+ try:
177
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
178
+ except BlockingIOError:
179
+ raise ValueError(f"another sessions run is writing {out}") from None
180
+ db = _state(out)
181
+ try:
182
+ for root in roots or default_roots():
183
+ root = Path(root).expanduser()
184
+ if not root.is_dir():
185
+ continue
186
+ root = root.resolve()
187
+ digest = hashlib.sha256(os.fsencode(root)).hexdigest()[:12]
188
+ label = f"{digest}-{_escape(root.name or 'root')}"
189
+ for path in root.rglob("*.jsonl"):
190
+ if path.is_symlink() or not path.is_file():
191
+ continue
192
+ counts["files"] += 1
193
+ _ingest_file(db, out, label, root, path, counts)
194
+ finally:
195
+ db.close()
196
+ return counts
197
+
198
+
199
+ def _ingest_file(db, out, label, root, path, counts):
200
+ key = _note(out, label, root, path, 1).parent.relative_to(out).as_posix()
201
+ with path.open("rb") as stream:
202
+ info = os.fstat(stream.fileno())
203
+ saved = db.execute("SELECT mtime, seen, offset, part, part_bytes FROM files WHERE path = ?", (key,)).fetchone()
204
+ if saved and saved[0] == info.st_mtime_ns and saved[2] == info.st_size:
205
+ return
206
+ if saved and (info.st_size < saved[2] or _seen(stream, saved[2]) != saved[1]):
207
+ saved = None
208
+ if not saved:
209
+ _forget(out, label, root, path)
210
+ offset, part, part_bytes = saved[2:] if saved else (0, 1, 0)
211
+ counts["changed"] += 1
212
+ note = None
213
+ stream.seek(offset)
214
+ try:
215
+ for line, size in _lines(stream):
216
+ found = _parse(line, counts)
217
+ if found:
218
+ if part_bytes and part_bytes + len(found) > PART_BYTES:
219
+ if note:
220
+ note.close()
221
+ note, part, part_bytes = None, part + 1, 0
222
+ if note is None:
223
+ note, part_bytes = _open_part(out, label, root, path, part, part_bytes)
224
+ note.write(found)
225
+ part_bytes += len(found)
226
+ counts["messages"] += 1
227
+ offset += size
228
+ counts["bytes_read"] += size
229
+ finally:
230
+ if note:
231
+ note.close()
232
+ _forget(out, label, root, path, part + 1)
233
+ stream.seek(0)
234
+ with db:
235
+ db.execute("INSERT OR REPLACE INTO files VALUES (?, ?, ?, ?, ?, ?)",
236
+ (key, info.st_mtime_ns, _seen(stream, offset), offset, part, part_bytes))