keepfold 0.6.4__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.
- keepfold/__init__.py +1 -0
- keepfold/_proc.py +102 -0
- keepfold/access.py +154 -0
- keepfold/agent_eval.py +162 -0
- keepfold/agent_text.py +56 -0
- keepfold/anki.py +285 -0
- keepfold/app/__init__.py +5 -0
- keepfold/app/actions.py +690 -0
- keepfold/app/desktop.py +677 -0
- keepfold/app/exports.py +254 -0
- keepfold/app/hello.py +79 -0
- keepfold/app/launch.py +114 -0
- keepfold/app/news.py +60 -0
- keepfold/app/server.py +3142 -0
- keepfold/app/status.py +811 -0
- keepfold/app/targets.py +1374 -0
- keepfold/app/winpath.py +54 -0
- keepfold/app/wizard.py +506 -0
- keepfold/ask.py +475 -0
- keepfold/askfile.py +322 -0
- keepfold/assets/LICENSE-d3.txt +13 -0
- keepfold/assets/agent_eval.json +235 -0
- keepfold/assets/app/app.css +611 -0
- keepfold/assets/app/app.js +2712 -0
- keepfold/assets/app/capture.html +16 -0
- keepfold/assets/app/capture.js +91 -0
- keepfold/assets/app/index.html +149 -0
- keepfold/assets/brain3d.js +3730 -0
- keepfold/assets/chat_eval.json +454 -0
- keepfold/assets/d3.v7.min.js +2 -0
- keepfold/assets/dashboard.css +774 -0
- keepfold/assets/dashboard.html.tmpl +170 -0
- keepfold/assets/dashboard.js +4262 -0
- keepfold/assets/help/GUIDE.md +544 -0
- keepfold/assets/help/help.md +83 -0
- keepfold/assets/keepfold.ico +0 -0
- keepfold/assets/whats_new.json +162 -0
- keepfold/backup.py +100 -0
- keepfold/brainmap.py +1382 -0
- keepfold/browse/__init__.py +10 -0
- keepfold/browse/build.py +1320 -0
- keepfold/browse/forget.py +510 -0
- keepfold/browse/legacy.py +95 -0
- keepfold/browse/lists.py +285 -0
- keepfold/browse/privacy.py +391 -0
- keepfold/browse/selftest.py +166 -0
- keepfold/browse/sites.py +1068 -0
- keepfold/browse/sources.py +329 -0
- keepfold/browse/store.py +991 -0
- keepfold/browse/takeout.py +312 -0
- keepfold/browse/titles.py +127 -0
- keepfold/browse/vectors.py +326 -0
- keepfold/browse_serve.py +332 -0
- keepfold/catalog.py +564 -0
- keepfold/chat.py +1464 -0
- keepfold/chat_archive.py +165 -0
- keepfold/chat_eval.py +583 -0
- keepfold/chat_facts.py +721 -0
- keepfold/chat_import.py +1045 -0
- keepfold/chat_pages.py +291 -0
- keepfold/chat_study.py +371 -0
- keepfold/chats.py +669 -0
- keepfold/claims.py +650 -0
- keepfold/cli.py +3254 -0
- keepfold/clients.py +96 -0
- keepfold/cloudllm.py +135 -0
- keepfold/contract.py +43 -0
- keepfold/corrections.py +134 -0
- keepfold/dashboard.py +959 -0
- keepfold/dates.py +202 -0
- keepfold/delta.py +146 -0
- keepfold/digest.py +72 -0
- keepfold/doctor.py +565 -0
- keepfold/duplicates.py +145 -0
- keepfold/egress.py +68 -0
- keepfold/eval_history.py +109 -0
- keepfold/events.py +554 -0
- keepfold/export_context.py +109 -0
- keepfold/fact_harvest.py +578 -0
- keepfold/forget.py +720 -0
- keepfold/harvest.py +334 -0
- keepfold/home.py +714 -0
- keepfold/importers.py +627 -0
- keepfold/index.py +733 -0
- keepfold/know.py +40 -0
- keepfold/learning_eval.py +261 -0
- keepfold/levels.py +595 -0
- keepfold/life_sources.py +747 -0
- keepfold/lint.py +241 -0
- keepfold/localllm.py +699 -0
- keepfold/loops.py +316 -0
- keepfold/mcp_server.py +4464 -0
- keepfold/migrate.py +552 -0
- keepfold/more_sources.py +709 -0
- keepfold/packs.py +148 -0
- keepfold/people.py +99 -0
- keepfold/planner.py +819 -0
- keepfold/prime.py +630 -0
- keepfold/prime_hook.py +265 -0
- keepfold/profiles.py +118 -0
- keepfold/quarantine.py +123 -0
- keepfold/recall_log.py +93 -0
- keepfold/redteam.py +393 -0
- keepfold/reflect.py +164 -0
- keepfold/relink.py +477 -0
- keepfold/render.py +406 -0
- keepfold/review.py +1181 -0
- keepfold/rollups.py +412 -0
- keepfold/safety_net.py +571 -0
- keepfold/sample.py +103 -0
- keepfold/sample_vault/areas/programming.algorithms.md +11 -0
- keepfold/sample_vault/areas/programming.basics.md +11 -0
- keepfold/sample_vault/concepts/big-o-notation.md +13 -0
- keepfold/sample_vault/concepts/functions.md +13 -0
- keepfold/sample_vault/concepts/loops.md +14 -0
- keepfold/sample_vault/concepts/recursion.md +13 -0
- keepfold/sample_vault/domains/programming.md +10 -0
- keepfold/sample_vault/journal/2026-01-12.md +9 -0
- keepfold/sample_vault/me/goals.md +17 -0
- keepfold/sample_vault/me/profile.md +19 -0
- keepfold/sample_vault/mistakes/programming.off-by-one-loop.md +16 -0
- keepfold/sample_vault/notes/recursion-needs-a-base-case.md +18 -0
- keepfold/sample_vault/problems/fizzbuzz.md +12 -0
- keepfold/sample_vault/projects/text-adventure.md +15 -0
- keepfold/sample_vault/resources/python-tutorial.md +16 -0
- keepfold/semantic.py +1254 -0
- keepfold/session.py +764 -0
- keepfold/share.py +69 -0
- keepfold/sources.py +612 -0
- keepfold/sync_copies.py +83 -0
- keepfold/tags.py +230 -0
- keepfold/taint.py +301 -0
- keepfold/tonight.py +195 -0
- keepfold/topics.py +1072 -0
- keepfold/update.py +300 -0
- keepfold/vault.py +942 -0
- keepfold/vecstore.py +218 -0
- keepfold/voice.py +260 -0
- keepfold/voice_memos.py +280 -0
- keepfold/watch.py +303 -0
- keepfold/where.py +119 -0
- keepfold/xray.py +516 -0
- keepfold/zotero.py +303 -0
- keepfold-0.6.4.dist-info/METADATA +644 -0
- keepfold-0.6.4.dist-info/RECORD +148 -0
- keepfold-0.6.4.dist-info/WHEEL +4 -0
- keepfold-0.6.4.dist-info/entry_points.txt +6 -0
- keepfold-0.6.4.dist-info/licenses/LICENSE +21 -0
keepfold/chats.py
ADDED
|
@@ -0,0 +1,669 @@
|
|
|
1
|
+
"""Past conversations, read-only, for /keepfold history and /keepfold save.
|
|
2
|
+
|
|
3
|
+
Claude Code transcripts are `<root>/<project-dir>/<session-id>.jsonl` (root: ~/.claude/projects,
|
|
4
|
+
or KEEPFOLD_CHATS_DIR). Chats from claude.ai, ChatGPT, Gemini and Perplexity come from their data
|
|
5
|
+
exports, which `import_export` converts into the same line format under
|
|
6
|
+
`export_root()/<source folder>/` (EXPORT_DIRS; claude.ai's source is `claude-chat`). A chat
|
|
7
|
+
in a Claude app with no transcript of its own (Claude Desktop's Chat tab) is logged there live
|
|
8
|
+
over MCP (`log_live`, folder and source LIVE). Only user/assistant text survives: tool calls and
|
|
9
|
+
results, sidechains, meta lines and system-reminder/command wrappers are dropped.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import hashlib
|
|
15
|
+
import html
|
|
16
|
+
import json
|
|
17
|
+
import os
|
|
18
|
+
import re
|
|
19
|
+
import time
|
|
20
|
+
import zipfile
|
|
21
|
+
from collections.abc import Iterator
|
|
22
|
+
from datetime import UTC, date, datetime, timedelta
|
|
23
|
+
from itertools import chain, islice
|
|
24
|
+
from pathlib import Path
|
|
25
|
+
|
|
26
|
+
from keepfold.events import live
|
|
27
|
+
from keepfold.vault import SECRET_RES, VaultError
|
|
28
|
+
|
|
29
|
+
PART_CHARS, LINE_CHARS, FIRST_LINE_CHARS, MAX_LIMIT = 12_000, 1_500, 120, 50
|
|
30
|
+
LIVE_SECONDS = 120 # the newest transcript touched this recently is the chat being written
|
|
31
|
+
_WRAPPER = re.compile(r"<(system-reminder|task-notification|command-[\w-]+|local-command-[\w-]+)"
|
|
32
|
+
r"\b[^>]*>.*?</\1>", re.S)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def root() -> Path:
|
|
36
|
+
return Path(os.environ.get("KEEPFOLD_CHATS_DIR") or Path.home() / ".claude" / "projects")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def export_root() -> Path:
|
|
40
|
+
"""Where imported chat-export conversations live (outside the vault and the repo)."""
|
|
41
|
+
return Path(os.environ.get("KEEPFOLD_CHAT_EXPORT_DIR")
|
|
42
|
+
or Path.home() / ".keepfold" / "claude-chat")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
EXPORT_PROJECT = "claude-ai"
|
|
46
|
+
# import source -> (its folder under export_root(), the source list_chats reports)
|
|
47
|
+
EXPORT_DIRS = {"claude": (EXPORT_PROJECT, "claude-chat"), "chatgpt": ("chatgpt", "chatgpt"),
|
|
48
|
+
"gemini": ("gemini", "gemini"), "perplexity": ("perplexity", "perplexity")}
|
|
49
|
+
LIVE = "claude-live" # chats a Claude app logs over MCP (keepfold_prime, keepfold_log chat_turn)
|
|
50
|
+
LIVE_ID = re.compile(r"[0-9A-HJKMNP-TV-Z]{26}") # a live chat's id: a ULID the server made
|
|
51
|
+
SOURCES = ("claude-code", *(s for _, s in EXPORT_DIRS.values()), LIVE)
|
|
52
|
+
_UUID = re.compile(r"^[A-Za-z0-9-]{8,64}$")
|
|
53
|
+
EXPECTED = ("Expected a claude.ai or ChatGPT export (the .zip, or its conversations.json), a "
|
|
54
|
+
"Google Takeout of Gemini Apps activity (My Activity/Gemini Apps/MyActivity.json or "
|
|
55
|
+
".html), a Perplexity data export (conversations-*.json), or "
|
|
56
|
+
"Perplexity threads exported as Markdown (.md files, a folder or a zip of them).")
|
|
57
|
+
|
|
58
|
+
# How to get each export, for the app's guided import and docs/GUIDE.md ("google-activity"
|
|
59
|
+
# feeds keepfold.browse.takeout, not import-chats).
|
|
60
|
+
GUIDES = {
|
|
61
|
+
"claude": {
|
|
62
|
+
"name": "Claude (claude.ai)",
|
|
63
|
+
"link": "https://support.claude.com/en/articles/9450526-how-can-i-export-my-claude-ai-data",
|
|
64
|
+
"steps": ["On claude.ai (web or desktop app, not the phone app) open Settings > Privacy.",
|
|
65
|
+
"Click Export data.",
|
|
66
|
+
"Open the email from Anthropic and download the .zip (the link works for "
|
|
67
|
+
"24 hours)."],
|
|
68
|
+
"wait": "a few minutes",
|
|
69
|
+
"pick": "the downloaded .zip, as it is"},
|
|
70
|
+
"chatgpt": {
|
|
71
|
+
"name": "ChatGPT",
|
|
72
|
+
"link": "https://chatgpt.com/#settings/DataControls",
|
|
73
|
+
"steps": ["On chatgpt.com click your profile picture > Settings > Data controls.",
|
|
74
|
+
"Next to Export data click Export, then Confirm export.",
|
|
75
|
+
"Open the email from OpenAI and download the .zip (the link works for "
|
|
76
|
+
"24 hours)."],
|
|
77
|
+
"wait": "minutes to a few hours (OpenAI says up to 7 days)",
|
|
78
|
+
"pick": "the downloaded .zip, as it is (it holds conversations.json)"},
|
|
79
|
+
"gemini": {
|
|
80
|
+
"name": "Gemini",
|
|
81
|
+
"link": "https://takeout.google.com",
|
|
82
|
+
"steps": ["Open takeout.google.com and click Deselect all.",
|
|
83
|
+
"Tick My Activity, click All activity data included, click Deselect all, "
|
|
84
|
+
"tick Gemini Apps, then OK.",
|
|
85
|
+
"Leave Activity records as HTML (the default) or set them to JSON under "
|
|
86
|
+
"Multiple formats; Keepfold reads both.",
|
|
87
|
+
"Click Next step, keep 'Send download link via email' and .zip, then "
|
|
88
|
+
"Create export.",
|
|
89
|
+
"Download the .zip from Google's email (the link works for 7 days)."],
|
|
90
|
+
"wait": "usually the same day; up to a few days",
|
|
91
|
+
"pick": "the Takeout .zip, as it is"},
|
|
92
|
+
"perplexity": {
|
|
93
|
+
"name": "Perplexity",
|
|
94
|
+
"link": "https://www.perplexity.ai/account/details",
|
|
95
|
+
"steps": ["On perplexity.ai open Settings > Account (perplexity.ai/account/details).",
|
|
96
|
+
"Click Export my data. If Settings > Account has no such button, ask "
|
|
97
|
+
"Perplexity's privacy contact (named in its privacy policy) for your data.",
|
|
98
|
+
"Download the .zip from Perplexity's email soon: the link expires.",
|
|
99
|
+
"For a few threads only: open each one, choose Export > Markdown from its "
|
|
100
|
+
"menu, and save the .md files in one folder."],
|
|
101
|
+
"wait": "minutes to a day for the account export; instant for one thread",
|
|
102
|
+
"pick": "the export .zip as it is (it holds conversations-*.json), or the .md files "
|
|
103
|
+
"or their folder"},
|
|
104
|
+
"google-activity": {
|
|
105
|
+
"name": "Google activity (Search, YouTube, Chrome)",
|
|
106
|
+
"link": "https://takeout.google.com",
|
|
107
|
+
"steps": ["Open takeout.google.com and click Deselect all.",
|
|
108
|
+
"Tick My Activity, click All activity data included, click Deselect all, "
|
|
109
|
+
"tick Search, YouTube and Chrome, then OK.",
|
|
110
|
+
"Leave Activity records as HTML (the default) or set them to JSON under "
|
|
111
|
+
"Multiple formats; Keepfold reads both.",
|
|
112
|
+
"Click Next step, keep 'Send download link via email' and .zip, then "
|
|
113
|
+
"Create export.",
|
|
114
|
+
"Download the .zip from Google's email (the link works for 7 days)."],
|
|
115
|
+
"wait": "usually the same day; up to a few days",
|
|
116
|
+
"pick": "the Takeout .zip, as it is; it lands private, under the browse rules"},
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
class Got(tuple):
|
|
121
|
+
"""import_export's result; `skipped` counts Takeout HTML rows whose date was unreadable.
|
|
122
|
+
The import report (importers.report_line): `files` read, conversations `read`,
|
|
123
|
+
`duplicate` (one id twice in the export: the latest kept) and `empty` (no text or id)."""
|
|
124
|
+
skipped = files = read = duplicate = empty = 0
|
|
125
|
+
|
|
126
|
+
def report(self) -> dict:
|
|
127
|
+
n = self[1] if len(self) == 2 else self[1] + self[2]
|
|
128
|
+
return {"read": self.read, "imported": n, "private": 0, "duplicate": self.duplicate,
|
|
129
|
+
"reasons": {"no text or no id": self.empty,
|
|
130
|
+
"unreadable date": self.skipped}, "files": self.files}
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _stamp(t) -> float:
|
|
134
|
+
"""A conversation's update time as a number, for picking the latest copy (0 if unreadable)."""
|
|
135
|
+
try:
|
|
136
|
+
return float(t) if isinstance(t, int | float) else \
|
|
137
|
+
datetime.fromisoformat(str(t).replace("Z", "+00:00")).timestamp()
|
|
138
|
+
except (ValueError, OverflowError, TypeError):
|
|
139
|
+
return 0.0
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _latest(convs, got: Got) -> list:
|
|
143
|
+
"""C6: one copy per conversation id (a split export may hold one twice): the most recently
|
|
144
|
+
updated, in first-seen order. Counts `read` and `duplicate` on `got`."""
|
|
145
|
+
best: dict = {}
|
|
146
|
+
for cid, updated, turns in convs:
|
|
147
|
+
got.read += 1
|
|
148
|
+
k = cid if isinstance(cid, str) else ("", got.read) # no id: kept, _save skips it
|
|
149
|
+
if k in best:
|
|
150
|
+
got.duplicate += 1
|
|
151
|
+
if _stamp(updated) <= _stamp(best[k][1]):
|
|
152
|
+
continue
|
|
153
|
+
best[k] = (cid, updated, turns)
|
|
154
|
+
return list(best.values())
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
def import_export(src: Path, source: str | None = None, dry_run: bool = False) -> tuple:
|
|
158
|
+
"""Convert a chat export (claude.ai, ChatGPT, Gemini Takeout or Perplexity Markdown; the
|
|
159
|
+
.zip, a folder or one file) into one redacted transcript per conversation under
|
|
160
|
+
export_root()/<source folder>/; re-importing overwrites (dedupe on source and id).
|
|
161
|
+
`source` forces the service when detection fails. Returns (source, conversations); with
|
|
162
|
+
`dry_run`, writes nothing and returns (source, new, already imported)."""
|
|
163
|
+
src = Path(src)
|
|
164
|
+
if source is not None and source not in EXPORT_DIRS:
|
|
165
|
+
raise VaultError("invalid_argument", f"--source must be one of {', '.join(EXPORT_DIRS)}.")
|
|
166
|
+
from keepfold.browse import takeout
|
|
167
|
+
from keepfold.importers import _files, json_value # importers imports this module
|
|
168
|
+
files = _files(src)
|
|
169
|
+
if src.suffix.lower() == ".zip" or src.is_dir():
|
|
170
|
+
files = [f for f in files if _wanted(f[0])]
|
|
171
|
+
if not files:
|
|
172
|
+
raise VaultError("invalid_argument", f"Found no chat export in {src.name}. {EXPECTED}")
|
|
173
|
+
js = [f for f in files if not f[0].lower().endswith(".md")]
|
|
174
|
+
pplx = not js or (source == "perplexity" and len(js) < len(files)) # Markdown threads
|
|
175
|
+
name = src.name if pplx or len(js) > 1 else js[0][0]
|
|
176
|
+
skipped, parts, got = 0, [], Got()
|
|
177
|
+
try:
|
|
178
|
+
if pplx:
|
|
179
|
+
mds = [(n, read().decode("utf-8"), mtime) for n, _, mtime, read in files
|
|
180
|
+
if n.lower().endswith(".md")]
|
|
181
|
+
# C6: every JSON (or Takeout HTML) file of the export, not only the first one
|
|
182
|
+
for name, _, _, read in [] if pplx else js:
|
|
183
|
+
html_file = name.lower().endswith((".html", ".htm")) # Takeout's HTML Gemini rows
|
|
184
|
+
part, n = takeout.html_rows(read(), name) if html_file else (json_value(read), 0)
|
|
185
|
+
skipped += n
|
|
186
|
+
if isinstance(part, dict) and isinstance(part.get("conversations"), list):
|
|
187
|
+
part = part["conversations"] # Perplexity's account export wraps its threads
|
|
188
|
+
if not isinstance(part, list | Iterator):
|
|
189
|
+
raise VaultError("invalid_argument", f"{name} should hold a list. {EXPECTED}")
|
|
190
|
+
parts.append(part if isinstance(part, list) else _named(name, part))
|
|
191
|
+
got.files += 1
|
|
192
|
+
except (OSError, ValueError, zipfile.BadZipFile) as e:
|
|
193
|
+
raise VaultError("invalid_argument", f"Cannot read {name}: {e}") from None
|
|
194
|
+
name = name if len(js) == 1 else src.name
|
|
195
|
+
if pplx:
|
|
196
|
+
got.files = len(mds)
|
|
197
|
+
out = Got(_save("perplexity", _latest(_perplexity(mds), got), dry_run, got))
|
|
198
|
+
out.__dict__.update(got.__dict__)
|
|
199
|
+
return out
|
|
200
|
+
rows = chain.from_iterable(parts) # C11: a big file's rows stream in as they convert
|
|
201
|
+
head = list(islice(rows, 1))
|
|
202
|
+
data = chain(head, rows)
|
|
203
|
+
source = source or _detect(head)
|
|
204
|
+
if source is None:
|
|
205
|
+
raise VaultError("invalid_argument", f"Cannot tell which service {name} comes from "
|
|
206
|
+
f"(is it empty?); add --source {'|'.join(EXPORT_DIRS)}. {EXPECTED}")
|
|
207
|
+
if source == "gemini":
|
|
208
|
+
data = list(data) # _gemini keeps each of its rows anyway
|
|
209
|
+
if source == "gemini" and data and not any(map(_is_gemini, data)):
|
|
210
|
+
raise VaultError("invalid_argument", f"{name} holds no Gemini Apps activity (Search, "
|
|
211
|
+
"YouTube or Chrome rows are browsing, not chats); import it as "
|
|
212
|
+
"google-activity instead.")
|
|
213
|
+
convs = {"claude": _claude, "chatgpt": _chatgpt, "gemini": _gemini,
|
|
214
|
+
"perplexity": _perplexity_json}[source](data)
|
|
215
|
+
out = Got(_save(source, _latest(convs, got), dry_run, got))
|
|
216
|
+
out.__dict__.update(got.__dict__, skipped=skipped)
|
|
217
|
+
return out
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
def _named(name: str, rows):
|
|
221
|
+
"""A streamed file's rows: an error midway names the file, as for one read whole."""
|
|
222
|
+
try:
|
|
223
|
+
yield from rows
|
|
224
|
+
except (OSError, ValueError, zipfile.BadZipFile) as e:
|
|
225
|
+
raise VaultError("invalid_argument", f"Cannot read {name}: {e}") from None
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def _wanted(name: str) -> bool:
|
|
229
|
+
"""Chat files in a zip or folder; a top-level MyActivity.json counts, as in
|
|
230
|
+
`importers.detect`, which checks it is Gemini's."""
|
|
231
|
+
from keepfold.browse import takeout
|
|
232
|
+
n = name.replace("\\", "/").lower()
|
|
233
|
+
base = n.rsplit("/", 1)[-1]
|
|
234
|
+
return (base.startswith("conversations") and base.endswith(".json")) or base.endswith(".md") \
|
|
235
|
+
or (bool(takeout.activity_file(n)) and ("gemini" in n or "/" not in n))
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _is_gemini(e) -> bool:
|
|
239
|
+
"""A Gemini row in any language: "Gemini Apps", "Apps de Gemini", "Gemini-Apps"..."""
|
|
240
|
+
return isinstance(e, dict) and ("Gemini" in str(e.get("header", "")) or any(
|
|
241
|
+
"Gemini" in str(p) for p in e.get("products") or ()))
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _detect(data: list) -> str | None:
|
|
245
|
+
d = data[0] if data and isinstance(data[0], dict) else {}
|
|
246
|
+
if "mapping" in d:
|
|
247
|
+
return "chatgpt"
|
|
248
|
+
if "chat_messages" in d:
|
|
249
|
+
return "claude"
|
|
250
|
+
if "entries" in d and "context_uuid" in d:
|
|
251
|
+
return "perplexity"
|
|
252
|
+
if _is_gemini(d):
|
|
253
|
+
return "gemini"
|
|
254
|
+
return None
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
def _iso(t) -> str:
|
|
258
|
+
return datetime.fromtimestamp(t, UTC).isoformat() if isinstance(t, int | float) \
|
|
259
|
+
else str(t or "")
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _claude(data):
|
|
263
|
+
for c in data:
|
|
264
|
+
if not isinstance(c, dict):
|
|
265
|
+
continue
|
|
266
|
+
turns = []
|
|
267
|
+
for m in c.get("chat_messages") or []:
|
|
268
|
+
role = {"human": "user", "assistant": "assistant"}.get(m.get("sender"))
|
|
269
|
+
blocks = [b.get("text") for b in m.get("content") or []
|
|
270
|
+
if isinstance(b, dict) and b.get("type") == "text"
|
|
271
|
+
and isinstance(b.get("text"), str)]
|
|
272
|
+
if role:
|
|
273
|
+
turns.append((role, str(m.get("created_at") or ""),
|
|
274
|
+
"\n".join(blocks) or m.get("text") or ""))
|
|
275
|
+
yield c.get("uuid"), c.get("updated_at"), turns
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _chatgpt(data):
|
|
279
|
+
"""Walks `mapping` from current_node up to the root: the branch the user last saw."""
|
|
280
|
+
for c in data:
|
|
281
|
+
nodes = c.get("mapping") if isinstance(c, dict) else None
|
|
282
|
+
if not isinstance(nodes, dict):
|
|
283
|
+
continue
|
|
284
|
+
turns, seen = [], set()
|
|
285
|
+
nid = c.get("current_node") or next(reversed(nodes), None)
|
|
286
|
+
while isinstance(nid, str) and nid in nodes and nid not in seen:
|
|
287
|
+
seen.add(nid)
|
|
288
|
+
node = nodes[nid] if isinstance(nodes[nid], dict) else {}
|
|
289
|
+
m = node.get("message") or {}
|
|
290
|
+
role = (m.get("author") or {}).get("role")
|
|
291
|
+
if role in ("user", "assistant") and not (m.get("metadata") or {}).get(
|
|
292
|
+
"is_visually_hidden_from_conversation"):
|
|
293
|
+
parts = (m.get("content") or {}).get("parts") or []
|
|
294
|
+
turns.append((role, _iso(m.get("create_time")),
|
|
295
|
+
"\n".join(p for p in parts if isinstance(p, str))))
|
|
296
|
+
nid = node.get("parent")
|
|
297
|
+
yield c.get("conversation_id") or c.get("id"), c.get("update_time"), turns[::-1]
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
# shortcut: unconfirmed wording for non-English prompt labels, verify with a real export: the
|
|
301
|
+
# label is "Prompted " in English, else any "<label>: " (or full-width ":") up to 40
|
|
302
|
+
# characters; a non-prompt row with a colon slips in as a user line. Add labels if seen.
|
|
303
|
+
_PROMPT = re.compile(r"(?:Prompted |[^::\n]{1,40}(?:: |:))(.+)", re.S)
|
|
304
|
+
_GEMINI_CHAT = re.compile(r"/app/(?:c/)?([A-Za-z0-9-]{8,64})")
|
|
305
|
+
_TAG = re.compile(r"<[^>]+>")
|
|
306
|
+
# a heuristic, the usual web-analytics session timeout, not a measured boundary
|
|
307
|
+
GEMINI_SESSION_GAP = timedelta(minutes=30)
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _gemini(data):
|
|
311
|
+
"""One My Activity row per prompt. Rows carry no conversation id in the exports seen, so
|
|
312
|
+
a row joins its titleUrl's chat when it has one; the other prompts form a chat until
|
|
313
|
+
GEMINI_SESSION_GAP passes between two of them. Such a chat's id is its first prompt's UTC
|
|
314
|
+
minute, `YYYY-MM-DD-HHMM` (unique: chats start more than the gap apart)."""
|
|
315
|
+
convs: dict[str, list] = {}
|
|
316
|
+
loose = [] # (time, row, prompt match) of rows without a chat id
|
|
317
|
+
for e in data:
|
|
318
|
+
if not _is_gemini(e) or not isinstance(e.get("time"), str):
|
|
319
|
+
continue # Search, YouTube and Chrome rows are browsing, never chat lines
|
|
320
|
+
m = _PROMPT.match(str(e.get("title") or ""))
|
|
321
|
+
if not m:
|
|
322
|
+
continue
|
|
323
|
+
if chat := _GEMINI_CHAT.search(str(e.get("titleUrl") or "")):
|
|
324
|
+
convs.setdefault(chat.group(1), []).extend(_gemini_turns(e, m))
|
|
325
|
+
continue
|
|
326
|
+
try:
|
|
327
|
+
t = datetime.fromisoformat(e["time"].replace("Z", "+00:00"))
|
|
328
|
+
except ValueError:
|
|
329
|
+
continue
|
|
330
|
+
loose.append((t if t.tzinfo else t.replace(tzinfo=UTC), e, m))
|
|
331
|
+
loose.sort(key=lambda x: x[0])
|
|
332
|
+
cid = prev = None
|
|
333
|
+
for t, e, m in loose:
|
|
334
|
+
if prev is None or t - prev > GEMINI_SESSION_GAP:
|
|
335
|
+
cid = t.astimezone(UTC).strftime("%Y-%m-%d-%H%M")
|
|
336
|
+
prev = t
|
|
337
|
+
convs.setdefault(cid, []).extend(_gemini_turns(e, m))
|
|
338
|
+
for cid, turns in convs.items():
|
|
339
|
+
turns.sort(key=lambda t: t[1]) # newest-first rows; stable, so a prompt stays first
|
|
340
|
+
yield cid, turns[-1][1], turns
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _gemini_turns(e, m) -> list:
|
|
344
|
+
answer = " ".join(html.unescape(_TAG.sub(" ", h["html"]))
|
|
345
|
+
for h in e.get("safeHtmlItem") or []
|
|
346
|
+
if isinstance(h, dict) and isinstance(h.get("html"), str))
|
|
347
|
+
return [("user", e["time"], m.group(1)), ("assistant", e["time"], answer)]
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
_PPLX_SKIP = re.compile(r"\s*(<.*>|\[\^[^\]]+\]:.*|---)\s*$") # logo, ⁂ divider, footnotes
|
|
351
|
+
_CITE = re.compile(r"\[\^[^\]]+\]")
|
|
352
|
+
# a JSON answer's [1]: a 1-3 digit number in brackets right after a word, punctuation or marker
|
|
353
|
+
_NUM_CITE = re.compile(r"(?<=[\w.,;:!?)\]'\"])\[\d{1,3}\](?![\d(])")
|
|
354
|
+
_CODE = re.compile(r"(```.*?(?:```|\Z)|`[^`\n]*`)", re.S) # fences (even unclosed), inline code
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
def _perplexity(files):
|
|
358
|
+
"""A thread's Markdown export: each `# ` line is a question, the lines up to the next one
|
|
359
|
+
its answer. A thread's id is a hash of its whole text: threads that open with the same
|
|
360
|
+
question stay apart, and the same file renamed or imported again is the same thread (a
|
|
361
|
+
re-export after follow-ups is a new one)."""
|
|
362
|
+
for _, text, mtime in files:
|
|
363
|
+
ts, turns = _iso(mtime), []
|
|
364
|
+
for line in text.splitlines():
|
|
365
|
+
if line.startswith("# "):
|
|
366
|
+
turns.append(("user", ts, line[2:].strip()))
|
|
367
|
+
elif turns and not _PPLX_SKIP.match(line):
|
|
368
|
+
if turns[-1][0] == "user":
|
|
369
|
+
turns.append(("assistant", ts, ""))
|
|
370
|
+
turns[-1] = (*turns[-1][:2], turns[-1][2] + _CITE.sub("", line) + "\n")
|
|
371
|
+
yield hashlib.sha1(text.encode("utf-8")).hexdigest()[:16], mtime, turns
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _uncite(text: str) -> str:
|
|
375
|
+
"""`text` without citation markers like [1], except inside inline code and code fences."""
|
|
376
|
+
return "".join(part if i % 2 else _NUM_CITE.sub("", part)
|
|
377
|
+
for i, part in enumerate(_CODE.split(text)))
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _perplexity_json(data):
|
|
381
|
+
"""Perplexity's account export (conversations-<stamp>.json): a thread's entries are its
|
|
382
|
+
question/answer turns, oldest first. Ids are context_uuid; `_save` keeps the id of the same
|
|
383
|
+
thread imported before as Markdown (hashed id)."""
|
|
384
|
+
for c in data:
|
|
385
|
+
if not isinstance(c, dict):
|
|
386
|
+
continue
|
|
387
|
+
turns = []
|
|
388
|
+
for e in c.get("entries") or []:
|
|
389
|
+
if isinstance(e, dict):
|
|
390
|
+
ts = str(e.get("created_at") or "")
|
|
391
|
+
a = e.get("answer")
|
|
392
|
+
turns += [("user", ts, e.get("query")),
|
|
393
|
+
("assistant", ts, _uncite(a) if isinstance(a, str) else a)]
|
|
394
|
+
yield c.get("context_uuid"), c.get("updated_at"), turns
|
|
395
|
+
|
|
396
|
+
|
|
397
|
+
def _pplx_key(turns) -> str | None:
|
|
398
|
+
"""A thread's every question and its whole first answer, from (role, text) pairs,
|
|
399
|
+
lowercased letters and digits only, so its Markdown and JSON exports match; threads that
|
|
400
|
+
only open the same way ("hi") get different keys."""
|
|
401
|
+
turns = [(r, re.sub(r"\W+", "", t.lower())) for r, t in turns]
|
|
402
|
+
qs = [t for r, t in turns if r == "user"]
|
|
403
|
+
a = next((t for r, t in turns if r == "assistant"), "")
|
|
404
|
+
return "\0".join([a, *qs]) if qs and qs[0] else None
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _save(source: str, convs, dry_run: bool = False, got: Got | None = None) -> tuple:
|
|
408
|
+
out = export_root() / EXPORT_DIRS[source][0]
|
|
409
|
+
if not dry_run:
|
|
410
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
411
|
+
n = old = 0
|
|
412
|
+
seen = set() # a conversation twice in one export is written and counted once
|
|
413
|
+
known = {} # Perplexity: a thread stored from the other export form (Markdown or JSON)
|
|
414
|
+
if source == "perplexity" and out.is_dir():
|
|
415
|
+
for p in out.glob("*.jsonl"):
|
|
416
|
+
known.setdefault(_pplx_key((r, t) for r, _, t in _turns(p)), p.stem)
|
|
417
|
+
known.pop(None, None)
|
|
418
|
+
for cid, updated, turns in convs:
|
|
419
|
+
lines = [json.dumps({"type": r, "message": {"content": redact(t)}, "timestamp": ts})
|
|
420
|
+
for r, ts, t in turns if isinstance(t, str) and t.strip()]
|
|
421
|
+
if known and isinstance(cid, str):
|
|
422
|
+
key = _pplx_key((r, redact(t)) for r, _, t in turns
|
|
423
|
+
if isinstance(t, str) and t.strip())
|
|
424
|
+
had = known.get(key)
|
|
425
|
+
if had and (len(had) == 16) != (len(cid) == 16): # Markdown ids are 16-hex hashes
|
|
426
|
+
cid = had
|
|
427
|
+
del known[key] # a stored thread takes at most one incoming thread
|
|
428
|
+
if not isinstance(cid, str) or not _UUID.match(cid) or not lines or cid in seen:
|
|
429
|
+
if got is not None:
|
|
430
|
+
got.empty += not (isinstance(cid, str) and cid in seen)
|
|
431
|
+
continue
|
|
432
|
+
seen.add(cid)
|
|
433
|
+
p = out / f"{cid}.jsonl"
|
|
434
|
+
if dry_run:
|
|
435
|
+
old += p.is_file()
|
|
436
|
+
n += not p.is_file()
|
|
437
|
+
continue
|
|
438
|
+
tmp = p.with_suffix(".tmp")
|
|
439
|
+
tmp.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
|
440
|
+
os.replace(tmp, p)
|
|
441
|
+
try: # list order follows file times, so give each file its conversation's time
|
|
442
|
+
t = updated if isinstance(updated, int | float) else \
|
|
443
|
+
datetime.fromisoformat(str(updated).replace("Z", "+00:00")).timestamp()
|
|
444
|
+
os.utime(p, (t, t))
|
|
445
|
+
except (ValueError, OverflowError, OSError):
|
|
446
|
+
pass
|
|
447
|
+
n += 1
|
|
448
|
+
return (source, n, old) if dry_run else (source, n)
|
|
449
|
+
|
|
450
|
+
|
|
451
|
+
PRIVATE = "[private]"
|
|
452
|
+
_PRIVATE_TAG = re.compile(r"<\s*(/?)\s*private\s*>", re.I)
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
def drop_private(text: str) -> str:
|
|
456
|
+
"""`text` with each `<private>…</private>` span (any case, across lines, nested or
|
|
457
|
+
repeated) replaced by PRIVATE: what a person marks private is never saved. An unclosed
|
|
458
|
+
`<private>` drops everything after it, the safe reading; a stray `</private>` stays."""
|
|
459
|
+
out, depth, pos = [], 0, 0
|
|
460
|
+
for m in _PRIVATE_TAG.finditer(text):
|
|
461
|
+
if not m[1]:
|
|
462
|
+
if not depth:
|
|
463
|
+
out.append(text[pos:m.start()])
|
|
464
|
+
depth += 1
|
|
465
|
+
elif depth:
|
|
466
|
+
depth -= 1
|
|
467
|
+
if not depth:
|
|
468
|
+
out.append(PRIVATE)
|
|
469
|
+
pos = m.end()
|
|
470
|
+
return "".join([*out, PRIVATE if depth else text[pos:]])
|
|
471
|
+
|
|
472
|
+
|
|
473
|
+
def redact(text: str) -> str:
|
|
474
|
+
"""`text` with private spans dropped (drop_private) and secrets masked: every copy of chat
|
|
475
|
+
text Keepfold keeps (live logs, imported exports, chat pages, the recall log) goes through
|
|
476
|
+
here."""
|
|
477
|
+
text = drop_private(text)
|
|
478
|
+
for rx in SECRET_RES:
|
|
479
|
+
text = rx.sub("[redacted]", text)
|
|
480
|
+
return text
|
|
481
|
+
|
|
482
|
+
|
|
483
|
+
def turns(path: Path) -> list[tuple[str, str, str]]:
|
|
484
|
+
"""(role, timestamp, text) per conversation turn with text left after cleaning."""
|
|
485
|
+
return list(_turns(path))
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _turns(path: Path):
|
|
489
|
+
with path.open(encoding="utf-8", errors="replace") as f:
|
|
490
|
+
for line in f:
|
|
491
|
+
try:
|
|
492
|
+
d = json.loads(line)
|
|
493
|
+
except ValueError:
|
|
494
|
+
continue
|
|
495
|
+
if text := _text(d):
|
|
496
|
+
yield d["type"], str(d.get("timestamp") or ""), text
|
|
497
|
+
|
|
498
|
+
|
|
499
|
+
def _text(d) -> str:
|
|
500
|
+
"""The cleaned text of one transcript line's user or assistant turn; '' for anything else
|
|
501
|
+
(a sidechain or meta line, a tool call or result, thinking, an image)."""
|
|
502
|
+
if (not isinstance(d, dict) or d.get("type") not in ("user", "assistant")
|
|
503
|
+
or d.get("isSidechain") or d.get("isMeta")
|
|
504
|
+
or not isinstance(d.get("message"), dict)):
|
|
505
|
+
return ""
|
|
506
|
+
content = d["message"].get("content")
|
|
507
|
+
if isinstance(content, str):
|
|
508
|
+
blocks = [content]
|
|
509
|
+
elif isinstance(content, list): # tool_use, tool_result, thinking, image: dropped
|
|
510
|
+
blocks = [b.get("text") for b in content
|
|
511
|
+
if isinstance(b, dict) and b.get("type") == "text"]
|
|
512
|
+
else:
|
|
513
|
+
return ""
|
|
514
|
+
return "\n".join(_WRAPPER.sub("", b) for b in blocks if isinstance(b, str)).strip()
|
|
515
|
+
|
|
516
|
+
|
|
517
|
+
def path_for(chat_id: str) -> Path:
|
|
518
|
+
"""The transcript for `<project-dir>/<session-id>`, refused outside the two roots."""
|
|
519
|
+
for base in (root().resolve(), export_root().resolve()):
|
|
520
|
+
p = (base / f"{chat_id}.jsonl").resolve()
|
|
521
|
+
if str(chat_id).count("/") != 1 or p.parent.parent != base:
|
|
522
|
+
raise VaultError("invalid_id", "A chat id looks like <project-dir>/<session-id>, "
|
|
523
|
+
"as keepfold_chats list returns it.")
|
|
524
|
+
if p.is_file():
|
|
525
|
+
return p
|
|
526
|
+
raise VaultError("unknown_id", f"No chat '{chat_id}'; use an id from keepfold_chats list.")
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def source_of(p: Path) -> str:
|
|
530
|
+
if p.parent.parent.resolve() != export_root().resolve():
|
|
531
|
+
return "claude-code"
|
|
532
|
+
return next((s for d, s in [*EXPORT_DIRS.values(), (LIVE, LIVE)] if d == p.parent.name),
|
|
533
|
+
"claude-chat")
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
def log_live(cid: str, turns: list[tuple[str, str]], now: datetime) -> None:
|
|
537
|
+
"""Append (role, text) turns, redacted, to the live chat log `cid` as transcript lines
|
|
538
|
+
stamped `now`; chat_import makes the page."""
|
|
539
|
+
out = export_root() / LIVE
|
|
540
|
+
out.mkdir(parents=True, exist_ok=True)
|
|
541
|
+
lines = "".join(json.dumps({"type": r, "message": {"content": redact(t)},
|
|
542
|
+
"timestamp": now.isoformat()}) + "\n"
|
|
543
|
+
for r, t in turns if t.strip())
|
|
544
|
+
with (out / f"{cid}.jsonl").open("a", encoding="utf-8") as f:
|
|
545
|
+
f.write(lines) # one write: a reader sees whole lines (chat_import waits for quiet)
|
|
546
|
+
|
|
547
|
+
|
|
548
|
+
def cowork_files() -> Iterator[Path]:
|
|
549
|
+
"""Claude Code transcripts of Claude Desktop's Cowork sessions, in the app's own data
|
|
550
|
+
folders (Windows; shortcut: no macOS path yet, add it when someone runs Cowork there)."""
|
|
551
|
+
for var, sub in (("LOCALAPPDATA", "Claude-Data/*"), ("APPDATA", "Claude")):
|
|
552
|
+
if base := os.environ.get(var):
|
|
553
|
+
for d in Path(base).glob(f"{sub}/local-agent-mode-sessions"):
|
|
554
|
+
yield from d.glob("**/.claude/projects/*/*.jsonl")
|
|
555
|
+
|
|
556
|
+
|
|
557
|
+
def codex_files() -> Iterator[Path]:
|
|
558
|
+
"""OpenAI Codex CLI session rollouts: $CODEX_HOME (default ~/.codex)/sessions/YYYY/MM/DD/
|
|
559
|
+
rollout-<time>-<id>.jsonl (openai/codex codex-rs/rollout/src/lib.rs SESSIONS_SUBDIR and
|
|
560
|
+
rollout_file_name.rs, https://github.com/openai/codex). Shortcut: a cold rollout Codex
|
|
561
|
+
compressed (.jsonl.zst) or moved to archived_sessions/ is not read (the stdlib has no zstd
|
|
562
|
+
before Python 3.14); its page, if written before, stays."""
|
|
563
|
+
base = Path(os.environ.get("CODEX_HOME") or Path.home() / ".codex")
|
|
564
|
+
return (base / "sessions").glob("*/*/*/rollout-*.jsonl")
|
|
565
|
+
|
|
566
|
+
|
|
567
|
+
def gemini_files() -> Iterator[Path]:
|
|
568
|
+
"""Google Gemini CLI chat sessions: ($GEMINI_CLI_HOME or ~)/.gemini/tmp/<project>/chats/
|
|
569
|
+
session-*.jsonl, and a legacy session-*.json that has no .jsonl of the same name (Gemini CLI
|
|
570
|
+
copies one to the other when it is resumed) (google-gemini/gemini-cli packages/core/src/
|
|
571
|
+
services/chatRecordingService.ts and config/storage.ts,
|
|
572
|
+
https://github.com/google-gemini/gemini-cli). Sub-agent sessions (a folder under chats/)
|
|
573
|
+
and the other files in tmp/ are not read."""
|
|
574
|
+
base = Path(os.environ.get("GEMINI_CLI_HOME") or Path.home()) / ".gemini" / "tmp"
|
|
575
|
+
for p in base.glob("*/chats/session-*.json*"):
|
|
576
|
+
if p.suffix == ".jsonl" or p.suffix == ".json" and not p.with_suffix(".jsonl").exists():
|
|
577
|
+
yield p
|
|
578
|
+
|
|
579
|
+
|
|
580
|
+
def copilot_files() -> Iterator[Path]:
|
|
581
|
+
"""GitHub Copilot CLI sessions: $COPILOT_HOME (default ~/.copilot)/session-state/<session
|
|
582
|
+
id>/events.jsonl (https://docs.github.com/en/copilot/reference/copilot-cli-reference/
|
|
583
|
+
cli-config-dir-reference, `session-state/`)."""
|
|
584
|
+
base = Path(os.environ.get("COPILOT_HOME") or Path.home() / ".copilot")
|
|
585
|
+
return (base / "session-state").glob("*/events.jsonl")
|
|
586
|
+
|
|
587
|
+
|
|
588
|
+
def _files() -> list[Path]:
|
|
589
|
+
"""Transcripts of both sources, newest mtime first, without the Claude Code one being
|
|
590
|
+
written right now (G3)."""
|
|
591
|
+
code = sorted(root().glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime, reverse=True)
|
|
592
|
+
if code and time.time() - code[0].stat().st_mtime < LIVE_SECONDS:
|
|
593
|
+
code = code[1:]
|
|
594
|
+
return sorted(code + [p for d in [*(d for d, _ in EXPORT_DIRS.values()), LIVE]
|
|
595
|
+
for p in export_root().glob(f"{d}/*.jsonl")],
|
|
596
|
+
key=lambda p: p.stat().st_mtime, reverse=True)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _cid(p: Path) -> str:
|
|
600
|
+
return f"{p.parent.name}/{p.stem}"
|
|
601
|
+
|
|
602
|
+
|
|
603
|
+
def unlearned_count(learned: set[str]) -> int:
|
|
604
|
+
"""Listable chats (2+ user turns) not in `learned`; each file is read only up to its
|
|
605
|
+
second user turn."""
|
|
606
|
+
return sum(1 for p in _files() if _cid(p) not in learned and len(list(islice(
|
|
607
|
+
(t for t in _turns(p) if t[0] == "user"), 2))) == 2)
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def list_chats(saved: set[str], since: str | None = None, limit: int = 20,
|
|
611
|
+
learned: set[str] = frozenset(), unlearned: bool = False) -> list[dict]:
|
|
612
|
+
if not 1 <= limit <= MAX_LIMIT:
|
|
613
|
+
raise VaultError("invalid_argument", f"limit must be from 1 to {MAX_LIMIT}.")
|
|
614
|
+
if since is not None:
|
|
615
|
+
try:
|
|
616
|
+
date.fromisoformat(since)
|
|
617
|
+
except ValueError:
|
|
618
|
+
raise VaultError("invalid_argument", "since must be a date like 2026-11-13.") \
|
|
619
|
+
from None
|
|
620
|
+
out = []
|
|
621
|
+
# shortcut: files are parsed newest-mtime first and parsing stops at `limit`; a file
|
|
622
|
+
# touched after its last turn can shift the order slightly
|
|
623
|
+
for p in _files():
|
|
624
|
+
if len(out) >= limit:
|
|
625
|
+
break
|
|
626
|
+
cid = _cid(p)
|
|
627
|
+
if unlearned and cid in learned:
|
|
628
|
+
continue
|
|
629
|
+
ts = turns(p)
|
|
630
|
+
users = [t for r, _, t in ts if r == "user"]
|
|
631
|
+
if len(users) < 2:
|
|
632
|
+
continue
|
|
633
|
+
updated = ts[-1][1]
|
|
634
|
+
if since and updated[:10] < since:
|
|
635
|
+
continue
|
|
636
|
+
out.append({"id": cid, "source": source_of(p), "project": p.parent.name,
|
|
637
|
+
"started": ts[0][1],
|
|
638
|
+
"updated": updated, "turns": len(ts),
|
|
639
|
+
"first_user_line": redact(users[0].strip().splitlines()[0])
|
|
640
|
+
[:FIRST_LINE_CHARS], "saved": cid in saved, "learned": cid in learned})
|
|
641
|
+
return sorted(out, key=lambda c: c["updated"], reverse=True)
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def read_parts(chat_id: str, who: str = "all") -> list[str]:
|
|
645
|
+
"""The condensed `User:`/`Assistant:` text (only `User:` lines when who="user") in parts
|
|
646
|
+
of at most PART_CHARS."""
|
|
647
|
+
parts, cur = [], ""
|
|
648
|
+
for role, _, text in turns(path_for(chat_id)):
|
|
649
|
+
if who == "user" and role != "user":
|
|
650
|
+
continue
|
|
651
|
+
line = f"{role.capitalize()}: {' '.join(redact(text).split())}"
|
|
652
|
+
if len(line) > LINE_CHARS:
|
|
653
|
+
line = line[:LINE_CHARS - 1] + "…"
|
|
654
|
+
if cur and len(cur) + 1 + len(line) > PART_CHARS:
|
|
655
|
+
parts.append(cur)
|
|
656
|
+
cur = ""
|
|
657
|
+
cur = f"{cur}\n{line}" if cur else line
|
|
658
|
+
return [*parts, cur]
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def saved_ids(events, kind: str = "chat_saved") -> set[tuple[str, str]]:
|
|
662
|
+
"""(source, chat_id) of every `kind` log event (chat_saved, or chat_learned: read for what
|
|
663
|
+
it says about the user) that is not voided."""
|
|
664
|
+
out = set()
|
|
665
|
+
for e in live(events):
|
|
666
|
+
p = e.get("payload")
|
|
667
|
+
if e.get("kind") == "log" and isinstance(p, dict) and p.get("kind") == kind:
|
|
668
|
+
out.add((p.get("source"), p.get("chat_id")))
|
|
669
|
+
return out
|