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/chat_import.py
ADDED
|
@@ -0,0 +1,1045 @@
|
|
|
1
|
+
"""Automatic chat import (the app every EVERY_S, `keepfold import-chats --auto`): one chat page
|
|
2
|
+
per past conversation, written with no model.
|
|
3
|
+
|
|
4
|
+
Claude Code transcripts (chats.root(), the desktop app's Code tab included, and its Cowork
|
|
5
|
+
sessions: chats.cowork_files()), Codex, Gemini CLI and Copilot CLI sessions (chats.codex_files,
|
|
6
|
+
gemini_files, copilot_files; one reader each turns them into the same Chat), imported chat
|
|
7
|
+
exports (chats.export_root()) and the chats a Claude app logged live over MCP (chats.LIVE) not
|
|
8
|
+
saved yet, or changed since their page was written, become `resource` pages whose `Timeline:`
|
|
9
|
+
line names their `Source:` app (semantic.is_chat), new ones in the git-ignored archive/chats/
|
|
10
|
+
(keepfold.chat_archive). An ordinary chat keeps the user's own turns only, redacted and capped
|
|
11
|
+
(chats.LINE_CHARS a turn, chats.PART_CHARS a page); assistant text is never copied. A coding
|
|
12
|
+
session (file edits or shell commands) becomes a short summary: project, dates, the user's
|
|
13
|
+
requests (first lines), files touched (relative paths) and commit subjects, never code, diffs,
|
|
14
|
+
tool output or file contents.
|
|
15
|
+
|
|
16
|
+
Each page written gets a `chat_saved` log event (payload `auto: true` and the body's `hash`).
|
|
17
|
+
A page is rewritten only while its body (less a `Topics:` line) is still what was written: an
|
|
18
|
+
owner's edit or deletion and a chat saved by hand are left alone. A chat in a category the
|
|
19
|
+
owner set to skip (browse privacy settings) is never written; a local-only one is written
|
|
20
|
+
private. Sidechains, transcripts with no user text, transcripts touched in the last
|
|
21
|
+
chats.LIVE_SECONDS and sessions run in an `exclude:` folder are skipped.
|
|
22
|
+
|
|
23
|
+
Transcripts are append-only, and some are tens of MB. STATE (SQLite under `.keepfold/`, a
|
|
24
|
+
git-ignored cache) keeps per transcript its (mtime, size), the byte offset read so far, a hash of
|
|
25
|
+
its first line and the bounded running summary (Chat): a pass with nothing new only lists and
|
|
26
|
+
stats files, a grown transcript is read from its offset only, and one that shrank or whose first
|
|
27
|
+
line changed is read again from the start. Newest transcripts go first; work runs in short
|
|
28
|
+
slices (SLICE_S) with a rest between them so the app stays responsive. Nothing here embeds:
|
|
29
|
+
pages are bounded and the index embeds them later.
|
|
30
|
+
|
|
31
|
+
A Chat-tab chat logged live and the same conversation in a claude.ai export are one chat
|
|
32
|
+
(Ctx.partner: the same first message, started within SAME_CHAT, and no other candidate either
|
|
33
|
+
way). They share one page and both ledger keys: the export's turns (complete; a model can forget
|
|
34
|
+
a chat_turn) plus the live turns after its last message (_merged), whichever came first.
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
from __future__ import annotations
|
|
38
|
+
|
|
39
|
+
import hashlib
|
|
40
|
+
import json
|
|
41
|
+
import logging
|
|
42
|
+
import os
|
|
43
|
+
import re
|
|
44
|
+
import sqlite3
|
|
45
|
+
import time
|
|
46
|
+
from collections import Counter
|
|
47
|
+
from collections.abc import Callable
|
|
48
|
+
from contextlib import closing
|
|
49
|
+
from dataclasses import asdict, dataclass, field, replace
|
|
50
|
+
from datetime import UTC, date, datetime, timedelta
|
|
51
|
+
from pathlib import Path
|
|
52
|
+
|
|
53
|
+
from keepfold import chat_archive, chats, quarantine, render, tags, taint, topics
|
|
54
|
+
from keepfold.browse import privacy
|
|
55
|
+
from keepfold.catalog import slugify
|
|
56
|
+
from keepfold.events import EventLog, live, local_day
|
|
57
|
+
from keepfold.vault import (
|
|
58
|
+
Vault,
|
|
59
|
+
VaultError,
|
|
60
|
+
_dump_fm,
|
|
61
|
+
_load_fm,
|
|
62
|
+
_newline,
|
|
63
|
+
_split,
|
|
64
|
+
is_private,
|
|
65
|
+
truthy,
|
|
66
|
+
)
|
|
67
|
+
|
|
68
|
+
log = logging.getLogger(__name__)
|
|
69
|
+
|
|
70
|
+
FIRST_S, EVERY_S = 60, 300 # the app's first pass a minute after start, then every 5 minutes
|
|
71
|
+
STATE, LOCK = ".keepfold/chat-import.sqlite", ".keepfold/chat-import.lock"
|
|
72
|
+
BUSY = "A chat import is already running."
|
|
73
|
+
LABELS = {"claude-code": "Claude Code", "claude-chat": "Claude", "chatgpt": "ChatGPT",
|
|
74
|
+
"gemini": "Gemini", "perplexity": "Perplexity", chats.LIVE: "Claude",
|
|
75
|
+
"codex": "Codex", "gemini-cli": "Gemini CLI", "copilot-cli": "Copilot CLI"}
|
|
76
|
+
AGENTS = ("claude-code", "codex", "gemini-cli", "copilot-cli") # coding agents' own sessions
|
|
77
|
+
MINE = "My turns only" # on the Timeline line: harvest.user_turns ends a turn at `### `
|
|
78
|
+
CODING = {"Edit", "MultiEdit", "Write", "NotebookEdit", "Bash"}
|
|
79
|
+
REQUESTS, FILES, COMMITS, TITLE_CHARS = 12, 30, 20, 80
|
|
80
|
+
# what a summary keeps (the page shows fewer; the category check reads the requests)
|
|
81
|
+
ASKED, PATHS, SUBJECTS = 100, 1000, 200
|
|
82
|
+
MAX_LINE = 4 << 20 # a longer JSON line (a tool's output) is skipped unparsed
|
|
83
|
+
HEAD = 64 << 10 # the first line's first bytes, hashed: a change means a new file
|
|
84
|
+
SLICE_S, REST_S = 0.2, 0.02 # work at most this long, then rest this long
|
|
85
|
+
FEW = 5 # more chats than this: the progress line shows a percent and the time left
|
|
86
|
+
TRANSIENT = ("vault_locked", "busy") # retried next pass; other failures wait for a change
|
|
87
|
+
_ESCAPE = re.compile(r"^(?=#|Timeline: |Topics: |\*\*Me:\*\*)", re.M) # no fake page lines
|
|
88
|
+
_COMMIT = re.compile(r"\bgit\b[^\n;&|]*?\bcommit\b")
|
|
89
|
+
_MSG = re.compile(r"""\s(?:-[a-zA-Z]*m|--message)(?:=|\s+)"""
|
|
90
|
+
r"""(?:"((?:[^"\\]|\\.)*)"|'([^']*)'|([^\s;&|]+))""")
|
|
91
|
+
_ABS = re.compile(r"^(?:/|~|[A-Za-z]:/)")
|
|
92
|
+
_ME = re.compile(r"^\*\*Me:\*\*(.*)$", re.M)
|
|
93
|
+
_SOURCE = re.compile(r"Source: ([^·\r\n]+?)\s*(?:·|$)")
|
|
94
|
+
_DATE = re.compile(r"Date: (\d{4}-\d{2}-\d{2})")
|
|
95
|
+
EXPORT = chats.EXPORT_DIRS["claude"] # (folder, source) of claude.ai export conversations
|
|
96
|
+
# the live log starts at keepfold_prime, seconds after the first message; 15 minutes allows a slow
|
|
97
|
+
# first call or a skewed clock, while two chats opening alike that close are rare (and ambiguous)
|
|
98
|
+
SAME_CHAT = timedelta(minutes=15)
|
|
99
|
+
OPENING = 200 # characters of the first message compared
|
|
100
|
+
TAGS = 50 # //tags kept per chat (R3-5)
|
|
101
|
+
# R6: a model's thinking trace in a turn (a pasted DeepSeek or Qwen answer): a closed <think> or
|
|
102
|
+
# <thinking> block anywhere, or an unclosed one that opens the turn; never indexed or harvested
|
|
103
|
+
_THINK = re.compile(r"<(think|thinking)>.*?</\1\s*>|\A\s*<(?:think|thinking)>(?!.*</think).*",
|
|
104
|
+
re.S | re.I)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def strip_thinking(text: str) -> str:
|
|
108
|
+
"""`text` without its model thinking traces (`_THINK`)."""
|
|
109
|
+
return _THINK.sub("", text).strip() if "<think" in text.lower() else text
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def enabled() -> bool:
|
|
113
|
+
"""`app.chat_import` in ~/.keepfold/config.yaml: on unless set to false, or off while the
|
|
114
|
+
file cannot be read (`taint.config_error`)."""
|
|
115
|
+
cfg, err = taint._read()
|
|
116
|
+
a = cfg.get("app")
|
|
117
|
+
return not err and not (isinstance(a, dict) and a.get("chat_import") is False)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
# ---- which transcripts ------------------------------------------------------------------------
|
|
121
|
+
|
|
122
|
+
def _transcripts():
|
|
123
|
+
"""(source, path) of every Claude Code transcript (Cowork's run Claude Code too), Codex,
|
|
124
|
+
Gemini CLI and Copilot CLI session, imported export conversation and live-logged chat."""
|
|
125
|
+
yield from (("claude-code", p) for p in chats.root().glob("*/*.jsonl"))
|
|
126
|
+
yield from (("claude-code", p) for p in chats.cowork_files())
|
|
127
|
+
yield from (("codex", p) for p in chats.codex_files())
|
|
128
|
+
yield from (("gemini-cli", p) for p in chats.gemini_files())
|
|
129
|
+
yield from (("copilot-cli", p) for p in chats.copilot_files())
|
|
130
|
+
for d, s in [*chats.EXPORT_DIRS.values(), (chats.LIVE, chats.LIVE)]:
|
|
131
|
+
yield from ((s, p) for p in (chats.export_root() / d).glob("*.jsonl"))
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _key(source: str, p: Path) -> str:
|
|
135
|
+
return f"{source}:{chats._cid(p)}"
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
class State:
|
|
139
|
+
"""STATE: per transcript key, its (mtime_ns, size) when handled and a JSON record (offset,
|
|
140
|
+
head, chat). WAL with synchronous=NORMAL: a commit per transcript costs no fsync, and a lost
|
|
141
|
+
one only means that transcript is read again. A damaged one (quick_check at the first open
|
|
142
|
+
in a process) is moved aside (keepfold.quarantine) and started again: the next pass reads
|
|
143
|
+
every transcript from its start, the event log's chat_saved ledger still knows each page
|
|
144
|
+
written (kept, edited or deleted ones stay so) and a forgotten chat's ledger page is
|
|
145
|
+
"[forgotten]", which never makes a page; only the time to read them again is lost."""
|
|
146
|
+
|
|
147
|
+
def __init__(self, vault: Vault):
|
|
148
|
+
p = vault.root / STATE
|
|
149
|
+
p.parent.mkdir(parents=True, exist_ok=True)
|
|
150
|
+
try:
|
|
151
|
+
self._open(p)
|
|
152
|
+
except sqlite3.DatabaseError as e: # a damaged cache starts over; a locked one waits
|
|
153
|
+
if not quarantine.torn(e) or not quarantine.heal(
|
|
154
|
+
p, e, "every chat is read again from its start", vault):
|
|
155
|
+
raise
|
|
156
|
+
self._open(p)
|
|
157
|
+
|
|
158
|
+
def _open(self, p: Path) -> None:
|
|
159
|
+
self.db = sqlite3.connect(p, timeout=10, check_same_thread=False)
|
|
160
|
+
try:
|
|
161
|
+
self.db.execute("PRAGMA journal_mode=WAL")
|
|
162
|
+
self.db.execute("PRAGMA synchronous=NORMAL")
|
|
163
|
+
self.db.execute("CREATE TABLE IF NOT EXISTS files (key TEXT PRIMARY KEY, "
|
|
164
|
+
"mtime_ns INTEGER, size INTEGER, data TEXT)")
|
|
165
|
+
quarantine.check(self.db, p, "files", ["key", "mtime_ns", "size", "data"])
|
|
166
|
+
except BaseException:
|
|
167
|
+
self.db.close()
|
|
168
|
+
raise
|
|
169
|
+
|
|
170
|
+
def close(self) -> None:
|
|
171
|
+
self.db.close()
|
|
172
|
+
|
|
173
|
+
def sigs(self) -> dict:
|
|
174
|
+
return {k: (m, s) for k, m, s in self.db.execute("SELECT key, mtime_ns, size FROM files")}
|
|
175
|
+
|
|
176
|
+
def get(self, key: str) -> dict:
|
|
177
|
+
row = self.db.execute("SELECT data FROM files WHERE key = ?", (key,)).fetchone()
|
|
178
|
+
try:
|
|
179
|
+
d = json.loads(row[0]) if row else {}
|
|
180
|
+
except (TypeError, ValueError):
|
|
181
|
+
return {}
|
|
182
|
+
return d if isinstance(d, dict) else {}
|
|
183
|
+
|
|
184
|
+
def put(self, key: str, sig: tuple, record: dict) -> None:
|
|
185
|
+
with self.db:
|
|
186
|
+
self.db.execute("INSERT OR REPLACE INTO files VALUES (?, ?, ?, ?)",
|
|
187
|
+
(key, sig[0], sig[1], json.dumps(record, separators=(",", ":"))))
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def pending(vault: Vault, now: float | None = None, sigs: dict | None = None) -> list:
|
|
191
|
+
"""(source, path, (mtime_ns, size)) of each transcript to look at, newest first: not
|
|
192
|
+
handled at this (mtime, size) and not touched in the last chats.LIVE_SECONDS. A directory
|
|
193
|
+
listing and stats only."""
|
|
194
|
+
if sigs is None:
|
|
195
|
+
with closing(State(vault)) as st:
|
|
196
|
+
sigs = st.sigs()
|
|
197
|
+
now = time.time() if now is None else now
|
|
198
|
+
out = []
|
|
199
|
+
for source, p in _transcripts():
|
|
200
|
+
try:
|
|
201
|
+
s = p.stat()
|
|
202
|
+
except OSError:
|
|
203
|
+
continue
|
|
204
|
+
sig = (s.st_mtime_ns, s.st_size)
|
|
205
|
+
if now - s.st_mtime >= chats.LIVE_SECONDS and sigs.get(_key(source, p)) != sig:
|
|
206
|
+
out.append((source, p, sig))
|
|
207
|
+
return sorted(out, key=lambda x: x[2][0], reverse=True)
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
# ---- reading a transcript ---------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
@dataclass
|
|
213
|
+
class Chat:
|
|
214
|
+
"""The bounded running summary of one transcript, kept in STATE between passes."""
|
|
215
|
+
n: int = 0 # user turns
|
|
216
|
+
head: str = "" # the first turn's first line: the title
|
|
217
|
+
kept: list = field(default_factory=list) # [timestamp, text] of the turns the page shows
|
|
218
|
+
full: bool = False # kept reached chats.PART_CHARS: later turns are only counted
|
|
219
|
+
asked: list = field(default_factory=list) # each turn's first line, up to ASKED
|
|
220
|
+
n_asked: int = 0
|
|
221
|
+
first: str = "" # timestamps
|
|
222
|
+
last: str = ""
|
|
223
|
+
cwd: str = ""
|
|
224
|
+
coding: bool = False
|
|
225
|
+
files: dict = field(default_factory=dict) # each path a tool wrote, in order, up to PATHS
|
|
226
|
+
commits: dict = field(default_factory=dict) # each commit subject, in order, up to SUBJECTS
|
|
227
|
+
tags: list = field(default_factory=list) # [tag, text, day] of the user's //tags, up to TAGS
|
|
228
|
+
sub: bool = False # a Codex sub-agent's or internal session: never a page
|
|
229
|
+
|
|
230
|
+
def dump(self) -> dict:
|
|
231
|
+
return {**asdict(self), "files": list(self.files), "commits": list(self.commits)}
|
|
232
|
+
|
|
233
|
+
@classmethod
|
|
234
|
+
def load(cls, d: dict) -> Chat:
|
|
235
|
+
c = cls(**{k: d[k] for k in cls.__dataclass_fields__ if k in d})
|
|
236
|
+
c.files, c.commits = dict.fromkeys(c.files), dict.fromkeys(c.commits)
|
|
237
|
+
return c
|
|
238
|
+
|
|
239
|
+
def turn(self, ts: str, text: str) -> None:
|
|
240
|
+
r = chats.redact(strip_thinking(text))
|
|
241
|
+
t = r[:chats.LINE_CHARS + 1] # redact, then cut
|
|
242
|
+
w = _when(ts)
|
|
243
|
+
# R3-5: the owner's own words; `one` acts on them. Only a tag that starts a line: one
|
|
244
|
+
# mid-line in an old chat is usually quoted or pasted text
|
|
245
|
+
typed = "\n".join(x for x in r.splitlines() if x.lstrip().startswith("//"))
|
|
246
|
+
for tag, x in tags.find(typed):
|
|
247
|
+
item = [tag, x, local_day(w) if w else ""]
|
|
248
|
+
if len(self.tags) < TAGS and item not in self.tags:
|
|
249
|
+
self.tags.append(item)
|
|
250
|
+
self.n += 1
|
|
251
|
+
self.first = self.first or ts
|
|
252
|
+
if self.n == 1:
|
|
253
|
+
self.head = _first(t)[:500]
|
|
254
|
+
if not self.full:
|
|
255
|
+
t2 = chats.redact(t)
|
|
256
|
+
t2 = t2 if len(t2) <= chats.LINE_CHARS else t2[:chats.LINE_CHARS - 1] + "…"
|
|
257
|
+
if self.kept and sum(len(x) for _, x in self.kept) + len(t2) > chats.PART_CHARS:
|
|
258
|
+
self.full = True
|
|
259
|
+
else:
|
|
260
|
+
self.kept.append([ts, t2])
|
|
261
|
+
if r := _line(_first(t)):
|
|
262
|
+
self.n_asked += 1
|
|
263
|
+
if len(self.asked) < ASKED:
|
|
264
|
+
self.asked.append(r)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class _Stop(Exception):
|
|
268
|
+
pass
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class Pace:
|
|
272
|
+
"""Call it often: past SLICE_S of work it rests REST_S (the app's threads get the GIL) and
|
|
273
|
+
raises _Stop once `cancelled()`."""
|
|
274
|
+
|
|
275
|
+
def __init__(self, cancelled: Callable[[], bool] | None = None):
|
|
276
|
+
self.cancelled, self.t = cancelled, time.perf_counter()
|
|
277
|
+
|
|
278
|
+
def __call__(self) -> None:
|
|
279
|
+
if time.perf_counter() - self.t >= SLICE_S:
|
|
280
|
+
time.sleep(REST_S)
|
|
281
|
+
if self.cancelled is not None and self.cancelled():
|
|
282
|
+
raise _Stop
|
|
283
|
+
self.t = time.perf_counter()
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _lines(f):
|
|
287
|
+
"""(line, offset after it) of each line from f's position. A line over MAX_LINE comes back
|
|
288
|
+
as b"" without being kept in memory; an unterminated last line only when it is whole JSON
|
|
289
|
+
(else it is still being written and is read next time)."""
|
|
290
|
+
off = f.tell()
|
|
291
|
+
while b := f.readline(MAX_LINE):
|
|
292
|
+
if b.endswith(b"\n"):
|
|
293
|
+
off += len(b)
|
|
294
|
+
yield b, off
|
|
295
|
+
elif len(b) < MAX_LINE: # the end of the file, no newline
|
|
296
|
+
try:
|
|
297
|
+
json.loads(b)
|
|
298
|
+
except ValueError:
|
|
299
|
+
return
|
|
300
|
+
yield b, off + len(b)
|
|
301
|
+
return
|
|
302
|
+
else:
|
|
303
|
+
off += len(b)
|
|
304
|
+
while (b := f.readline(MAX_LINE)) and not b.endswith(b"\n"):
|
|
305
|
+
off += len(b)
|
|
306
|
+
off += len(b)
|
|
307
|
+
yield b"", off
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def read(path: Path, prev: dict | None = None, pace: Callable[[], None] = lambda: None,
|
|
311
|
+
source: str = "claude-code") -> tuple[Chat, dict]:
|
|
312
|
+
"""Stream a transcript from where `prev` (its STATE record) stopped, on top of prev's
|
|
313
|
+
summary; from the start when there is none, or the file shrank or its first line changed.
|
|
314
|
+
Keeps the user's turns (sidechain, meta and compaction-summary lines dropped) and, from
|
|
315
|
+
coding tool calls, the paths written and commit subjects; tool inputs and outputs never.
|
|
316
|
+
Each line goes to `source`'s reader (_READERS; Claude Code's and the exports' format by
|
|
317
|
+
default); a Gemini CLI session is replayed whole (_gemini). Returns the summary and the new
|
|
318
|
+
record."""
|
|
319
|
+
if source == "gemini-cli":
|
|
320
|
+
return _gemini(path, pace), {}
|
|
321
|
+
add = _READERS.get(source, _add)
|
|
322
|
+
prev = prev or {}
|
|
323
|
+
with path.open("rb") as f:
|
|
324
|
+
head = hashlib.sha1(f.readline(HEAD)).hexdigest()[:16]
|
|
325
|
+
off = prev.get("offset")
|
|
326
|
+
c = None
|
|
327
|
+
if prev.get("head") == head and isinstance(off, int) \
|
|
328
|
+
and 0 < off <= os.fstat(f.fileno()).st_size and isinstance(prev.get("chat"), dict):
|
|
329
|
+
try:
|
|
330
|
+
c = Chat.load(prev["chat"])
|
|
331
|
+
except (TypeError, ValueError):
|
|
332
|
+
c = None
|
|
333
|
+
if c is None:
|
|
334
|
+
c, off = Chat(), 0
|
|
335
|
+
f.seek(off)
|
|
336
|
+
for b, off in _lines(f): # noqa: B007 (the last offset is the record's)
|
|
337
|
+
pace()
|
|
338
|
+
if b:
|
|
339
|
+
try:
|
|
340
|
+
d = json.loads(b.decode("utf-8", "replace"))
|
|
341
|
+
except ValueError:
|
|
342
|
+
continue
|
|
343
|
+
add(c, d)
|
|
344
|
+
return c, {"offset": off, "head": head, "chat": c.dump()}
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _add(c: Chat, d) -> None:
|
|
348
|
+
if not isinstance(d, dict) or d.get("isSidechain"):
|
|
349
|
+
return
|
|
350
|
+
kind, ts = d.get("type"), str(d.get("timestamp") or "")
|
|
351
|
+
if not c.cwd and isinstance(d.get("cwd"), str):
|
|
352
|
+
c.cwd = d["cwd"][:1000]
|
|
353
|
+
if kind == "user" and not d.get("isCompactSummary") and (t := chats._text(d)) \
|
|
354
|
+
and not t.startswith("[Request interrupted"):
|
|
355
|
+
c.turn(ts, t)
|
|
356
|
+
if kind in ("user", "assistant") and ts:
|
|
357
|
+
c.last = ts
|
|
358
|
+
msg = d.get("message")
|
|
359
|
+
if kind == "assistant" and isinstance(msg, dict) and isinstance(msg.get("content"), list):
|
|
360
|
+
for b in msg["content"]:
|
|
361
|
+
if isinstance(b, dict) and b.get("type") == "tool_use" and b.get("name") in CODING:
|
|
362
|
+
_tool(c, b)
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _tool(c: Chat, b: dict) -> None:
|
|
366
|
+
c.coding = True
|
|
367
|
+
inp = b.get("input") if isinstance(b.get("input"), dict) else {}
|
|
368
|
+
p = inp.get("file_path") or inp.get("notebook_path")
|
|
369
|
+
# shortcut: past PATHS files (SUBJECTS commits) the count stops; raise them if pages say so
|
|
370
|
+
if isinstance(p, str) and p and len(c.files) < PATHS:
|
|
371
|
+
c.files.setdefault(p[:1000], None)
|
|
372
|
+
if b.get("name") == "Bash" and isinstance(inp.get("command"), str):
|
|
373
|
+
for s in commits(inp["command"]):
|
|
374
|
+
if (s := _line(s)) and len(c.commits) < SUBJECTS:
|
|
375
|
+
c.commits.setdefault(s, None)
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _edited(c: Chat, path) -> None:
|
|
379
|
+
"""A file a tool wrote, summarised as _tool does."""
|
|
380
|
+
if isinstance(path, str) and path:
|
|
381
|
+
_tool(c, {"name": "Edit", "input": {"file_path": path}})
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def _ran(c: Chat, cmd) -> None:
|
|
385
|
+
"""A shell command a tool ran (a list is an argv), summarised as _tool does."""
|
|
386
|
+
if isinstance(cmd, list):
|
|
387
|
+
cmd = " ".join(x for x in cmd if isinstance(x, str))
|
|
388
|
+
_tool(c, {"name": "Bash", "input": {"command": cmd if isinstance(cmd, str) else ""}})
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
# ---- other coding agents' sessions ------------------------------------------------------------
|
|
392
|
+
# Each reader takes one parsed record and skips a type it does not know. Formats as their
|
|
393
|
+
# open-source code defines them; fixtures are hand-written from it, never copied from a session.
|
|
394
|
+
|
|
395
|
+
# Codex puts its own context in user-role messages: a whole message in one tag
|
|
396
|
+
# (<environment_context>, <user_instructions>, <turn_aborted>...) or AGENTS.md's text (openai/codex
|
|
397
|
+
# codex-rs/core/src/context/contextual_user_message.rs)
|
|
398
|
+
_CODEX_CONTEXT = re.compile(r"\A\s*(?:<([\w-]+)\b[^>]*>.*</\1>\s*\Z|# AGENTS\.md instructions\b)",
|
|
399
|
+
re.S)
|
|
400
|
+
_PATCH_FILE = re.compile(r"^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$", re.M)
|
|
401
|
+
|
|
402
|
+
|
|
403
|
+
def _add_codex(c: Chat, d) -> None:
|
|
404
|
+
"""One Codex rollout line {timestamp, type, payload} (openai/codex codex-rs/history/src/
|
|
405
|
+
rollout_payload.rs RolloutItemWire, codex-rs/protocol/src/models.rs ResponseItem): the cwd
|
|
406
|
+
from session_meta and turn_context, the user's messages and the shell and apply_patch
|
|
407
|
+
calls. A sub-agent's or internal session (session_meta source) is never a page."""
|
|
408
|
+
p = d.get("payload") if isinstance(d, dict) else None
|
|
409
|
+
if not isinstance(p, dict) or c.sub:
|
|
410
|
+
return
|
|
411
|
+
kind, ts = d.get("type"), str(d.get("timestamp") or "")
|
|
412
|
+
if kind in ("session_meta", "turn_context"):
|
|
413
|
+
src = p.get("source")
|
|
414
|
+
c.sub = c.sub or isinstance(src, dict) and ("subagent" in src or "internal" in src)
|
|
415
|
+
if not c.cwd and isinstance(p.get("cwd"), str):
|
|
416
|
+
c.cwd = p["cwd"][:1000]
|
|
417
|
+
return
|
|
418
|
+
if kind != "response_item":
|
|
419
|
+
return
|
|
420
|
+
t = p.get("type")
|
|
421
|
+
if t == "message" and p.get("role") in ("user", "assistant"):
|
|
422
|
+
if ts:
|
|
423
|
+
c.last = ts
|
|
424
|
+
if p["role"] == "user" and isinstance(p.get("content"), list):
|
|
425
|
+
text = "\n".join(b["text"] for b in p["content"] if isinstance(b, dict)
|
|
426
|
+
and b.get("type") == "input_text" and isinstance(b.get("text"), str)
|
|
427
|
+
and not _CODEX_CONTEXT.match(b["text"])).strip()
|
|
428
|
+
if text:
|
|
429
|
+
c.turn(ts, text)
|
|
430
|
+
elif t in ("function_call", "custom_tool_call", "local_shell_call"):
|
|
431
|
+
args = p.get("action") if t == "local_shell_call" else p.get("input")
|
|
432
|
+
if t == "function_call":
|
|
433
|
+
try:
|
|
434
|
+
args = json.loads(p.get("arguments") or "")
|
|
435
|
+
except (TypeError, ValueError):
|
|
436
|
+
args = None
|
|
437
|
+
patch = args if isinstance(args, str) else \
|
|
438
|
+
args.get("input") if isinstance(args, dict) else None
|
|
439
|
+
if isinstance(patch, str) and "*** Begin Patch" in patch:
|
|
440
|
+
for f in _PATCH_FILE.findall(patch):
|
|
441
|
+
_edited(c, f.strip())
|
|
442
|
+
elif isinstance(args, dict) and (cmd := args.get("command") or args.get("cmd")):
|
|
443
|
+
_ran(c, cmd)
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _add_copilot(c: Chat, d) -> None:
|
|
447
|
+
"""One Copilot CLI events.jsonl line {id, parentId, timestamp, type, data, agentId?,
|
|
448
|
+
checkpoint?} (the session events of microsoft/copilot-sdk nodejs/src/generated/
|
|
449
|
+
session-events.ts, https://github.com/microsoft/copilot-sdk): the cwd from session.start
|
|
450
|
+
and session.resume, the user's messages, the files tools edited and the shell commands.
|
|
451
|
+
A sub-agent's event, a replayed checkpoint and a message an agent wrote are skipped."""
|
|
452
|
+
if not isinstance(d, dict) or d.get("agentId") or d.get("checkpoint") \
|
|
453
|
+
or not isinstance(x := d.get("data"), dict):
|
|
454
|
+
return
|
|
455
|
+
kind, ts = d.get("type"), str(d.get("timestamp") or "")
|
|
456
|
+
if kind in ("session.start", "session.resume"):
|
|
457
|
+
ctx = x.get("context")
|
|
458
|
+
if not c.cwd and isinstance(ctx, dict) and isinstance(ctx.get("cwd"), str):
|
|
459
|
+
c.cwd = ctx["cwd"][:1000]
|
|
460
|
+
elif kind == "user.message" and isinstance(x.get("content"), str) \
|
|
461
|
+
and not x.get("agentAuthored") and not x.get("isAutopilotContinuation"):
|
|
462
|
+
c.turn(ts, x["content"])
|
|
463
|
+
elif kind == "tool.execution_complete" and isinstance(x.get("fileEdits"), list):
|
|
464
|
+
for e in x["fileEdits"]:
|
|
465
|
+
_edited(c, e.get("path") if isinstance(e, dict) else None)
|
|
466
|
+
elif kind == "tool.execution_start" and isinstance(info := x.get("shellToolInfo"), dict):
|
|
467
|
+
args = x.get("arguments")
|
|
468
|
+
_ran(c, args.get("command") if isinstance(args, dict) and isinstance(
|
|
469
|
+
args.get("command"), str) else info.get("displayCommand"))
|
|
470
|
+
if kind in ("user.message", "assistant.message") and ts:
|
|
471
|
+
c.last = ts
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
_READERS = {"codex": _add_codex, "copilot-cli": _add_copilot}
|
|
475
|
+
|
|
476
|
+
|
|
477
|
+
def _parts(x) -> str:
|
|
478
|
+
"""The text of a Gemini PartListUnion: a string, a part {text} or a list of them."""
|
|
479
|
+
if isinstance(x, str):
|
|
480
|
+
return x
|
|
481
|
+
if isinstance(x, dict):
|
|
482
|
+
return x["text"] if isinstance(x.get("text"), str) else ""
|
|
483
|
+
return "\n".join(_parts(p) for p in x) if isinstance(x, list) else ""
|
|
484
|
+
|
|
485
|
+
|
|
486
|
+
def _gemini(path: Path, pace: Callable[[], None]) -> Chat:
|
|
487
|
+
"""A Gemini CLI session replayed whole, as chatRecordingService.ts loads it: a message
|
|
488
|
+
record (one with the same id replaces it in place), `$rewindTo` (that message and the ones
|
|
489
|
+
after it dropped; all of them for an unknown id), `$patch` (content, removeIds, orderIds),
|
|
490
|
+
`$set` (a legacy full `messages` list), metadata; or a legacy .json ConversationRecord.
|
|
491
|
+
Records can rewrite earlier ones, so nothing is carried between passes. A message keeps
|
|
492
|
+
only its type, time, the user's text (displayContent, else content) and the tool calls."""
|
|
493
|
+
msgs: dict[str, list] = {} # id -> [type, timestamp, user text, [(tool, args)]]
|
|
494
|
+
meta: dict = {}
|
|
495
|
+
|
|
496
|
+
def message(m) -> None:
|
|
497
|
+
if not isinstance(m, dict) or not isinstance(m.get("id"), str):
|
|
498
|
+
return
|
|
499
|
+
kind = m.get("type")
|
|
500
|
+
text = _parts(m.get("displayContent") or m.get("content")) if kind == "user" else ""
|
|
501
|
+
calls = [(t.get("name"), t.get("args")) for t in m.get("toolCalls") or []
|
|
502
|
+
if isinstance(t, dict) and isinstance(t.get("args"), dict)] \
|
|
503
|
+
if kind == "gemini" and isinstance(m.get("toolCalls"), list) else []
|
|
504
|
+
msgs[m["id"]] = [kind, str(m.get("timestamp") or ""), text, calls]
|
|
505
|
+
|
|
506
|
+
def record(r) -> None:
|
|
507
|
+
nonlocal msgs
|
|
508
|
+
if not isinstance(r, dict):
|
|
509
|
+
return
|
|
510
|
+
if isinstance(r.get("$rewindTo"), str):
|
|
511
|
+
ids = list(msgs)
|
|
512
|
+
cut = ids.index(r["$rewindTo"]) if r["$rewindTo"] in ids else 0
|
|
513
|
+
msgs = {i: msgs[i] for i in ids[:cut]}
|
|
514
|
+
elif isinstance(p := r.get("$patch"), dict):
|
|
515
|
+
for u in [p, *(p.get("updates") if isinstance(p.get("updates"), list) else [])]:
|
|
516
|
+
m = msgs.get(u.get("id")) if isinstance(u, dict) else None
|
|
517
|
+
if m and m[0] == "user" and u.get("content") is not None:
|
|
518
|
+
m[2] = _parts(u["content"])
|
|
519
|
+
for i in p.get("removeIds") if isinstance(p.get("removeIds"), list) else []:
|
|
520
|
+
if isinstance(i, str):
|
|
521
|
+
msgs.pop(i, None)
|
|
522
|
+
if isinstance(p.get("orderIds"), list):
|
|
523
|
+
last = [i for i in p["orderIds"] if isinstance(i, str) and i in msgs]
|
|
524
|
+
msgs = {i: msgs[i] for i in [*(i for i in msgs if i not in last), *last]}
|
|
525
|
+
elif isinstance(r.get("$set"), dict):
|
|
526
|
+
meta.update({k: v for k, v in r["$set"].items() if k != "messages"})
|
|
527
|
+
if isinstance(r["$set"].get("messages"), list):
|
|
528
|
+
msgs = {}
|
|
529
|
+
for m in r["$set"]["messages"]:
|
|
530
|
+
message(m)
|
|
531
|
+
elif isinstance(r.get("id"), str):
|
|
532
|
+
message(r)
|
|
533
|
+
elif isinstance(r.get("sessionId"), str):
|
|
534
|
+
meta.update(r)
|
|
535
|
+
|
|
536
|
+
if path.suffix == ".json":
|
|
537
|
+
try:
|
|
538
|
+
data = json.loads(path.read_bytes().decode("utf-8", "replace"))
|
|
539
|
+
except ValueError: # a broken file is an empty chat, as a broken transcript is
|
|
540
|
+
data = None
|
|
541
|
+
if isinstance(data, dict):
|
|
542
|
+
meta.update({k: v for k, v in data.items() if k != "messages"})
|
|
543
|
+
for m in data.get("messages") if isinstance(data.get("messages"), list) else []:
|
|
544
|
+
message(m)
|
|
545
|
+
else:
|
|
546
|
+
with path.open("rb") as f:
|
|
547
|
+
for b, _ in _lines(f):
|
|
548
|
+
pace()
|
|
549
|
+
try:
|
|
550
|
+
record(json.loads(b.decode("utf-8", "replace")) if b else None)
|
|
551
|
+
except ValueError:
|
|
552
|
+
continue
|
|
553
|
+
c = Chat()
|
|
554
|
+
if meta.get("kind") == "subagent":
|
|
555
|
+
return c
|
|
556
|
+
try: # the project folder Gemini CLI records beside its chats (config/projectRegistry.ts)
|
|
557
|
+
c.cwd = (path.parent.parent / ".project_root").read_text(encoding="utf-8").strip()[:1000]
|
|
558
|
+
except (OSError, UnicodeError):
|
|
559
|
+
pass
|
|
560
|
+
for kind, ts, text, calls in msgs.values():
|
|
561
|
+
if kind == "user" and text.strip():
|
|
562
|
+
c.turn(ts, text)
|
|
563
|
+
if kind in ("user", "gemini") and ts:
|
|
564
|
+
c.last = ts
|
|
565
|
+
# tool names and parameters: packages/core/src/tools/definitions/base-declarations.ts
|
|
566
|
+
for name, args in calls:
|
|
567
|
+
if name in ("write_file", "replace"):
|
|
568
|
+
_edited(c, args.get("file_path"))
|
|
569
|
+
elif name == "run_shell_command":
|
|
570
|
+
_ran(c, args.get("command"))
|
|
571
|
+
return c
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
def commits(cmd: str) -> list[str]:
|
|
575
|
+
"""The subject of each `git commit -m` in a shell command (a heredoc's first line too)."""
|
|
576
|
+
out = []
|
|
577
|
+
for m in _COMMIT.finditer(cmd):
|
|
578
|
+
if not (g := _MSG.search(cmd, m.end())):
|
|
579
|
+
continue
|
|
580
|
+
text = g[1].replace('\\"', '"') if g[1] is not None else g[2] if g[2] is not None \
|
|
581
|
+
else g[3]
|
|
582
|
+
if text.lstrip().startswith("$(cat"):
|
|
583
|
+
text = text.split("\n", 1)[1] if "\n" in text else ""
|
|
584
|
+
if first := next((ln.strip() for ln in text.splitlines() if ln.strip()), ""):
|
|
585
|
+
out.append(first)
|
|
586
|
+
return out
|
|
587
|
+
|
|
588
|
+
|
|
589
|
+
# ---- the page ---------------------------------------------------------------------------------
|
|
590
|
+
|
|
591
|
+
@dataclass
|
|
592
|
+
class Page:
|
|
593
|
+
title: str
|
|
594
|
+
day: str
|
|
595
|
+
body: str
|
|
596
|
+
text: str # what the category check reads
|
|
597
|
+
related: list = field(default_factory=list)
|
|
598
|
+
|
|
599
|
+
|
|
600
|
+
def _when(ts: str) -> datetime | None:
|
|
601
|
+
try:
|
|
602
|
+
t = datetime.fromisoformat(ts.replace("Z", "+00:00"))
|
|
603
|
+
except ValueError:
|
|
604
|
+
return None
|
|
605
|
+
return t if t.tzinfo else t.replace(tzinfo=UTC)
|
|
606
|
+
|
|
607
|
+
|
|
608
|
+
def _first(text: str) -> str:
|
|
609
|
+
return next((s for s in (ln.strip().lstrip("#>*-` \t") for ln in text.splitlines()) if s),
|
|
610
|
+
"")
|
|
611
|
+
|
|
612
|
+
|
|
613
|
+
def _line(text: str, n: int = 120) -> str:
|
|
614
|
+
return render.plain(chats.redact(text), n)
|
|
615
|
+
|
|
616
|
+
|
|
617
|
+
def _n(xs, word: str) -> str:
|
|
618
|
+
return f"{len(xs)} {word}{'s' * (len(xs) != 1)}"
|
|
619
|
+
|
|
620
|
+
|
|
621
|
+
def _list(xs: list[str], cap: int, total: int | None = None) -> list[str]:
|
|
622
|
+
total = len(xs) if total is None else total
|
|
623
|
+
return [f"- {x}" for x in xs[:cap]] + ([f"- …and {total - cap} more"] if total > cap else [])
|
|
624
|
+
|
|
625
|
+
|
|
626
|
+
def _rel(p: str, base: str) -> str | None:
|
|
627
|
+
"""`p` relative to the session's folder; None for a path outside it."""
|
|
628
|
+
p = p.replace("\\", "/")
|
|
629
|
+
if base and p.casefold().startswith(base.casefold() + "/"):
|
|
630
|
+
p = p[len(base) + 1:]
|
|
631
|
+
return None if _ABS.match(p) or p.startswith("..") else p
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def build(source: str, path: Path, c: Chat, ctx: Ctx) -> Page:
|
|
635
|
+
"""The chat page for `c` (which has at least one user turn)."""
|
|
636
|
+
label = LABELS[source]
|
|
637
|
+
t0 = _when(c.first) or datetime.fromtimestamp(path.stat().st_mtime, UTC)
|
|
638
|
+
day = local_day(t0)
|
|
639
|
+
month = day[:8] + "01"
|
|
640
|
+
up = f"[[{month}]] · " if ctx.vault.path_for("journal", month).is_file() else "· "
|
|
641
|
+
first, kept = c.head, c.kept
|
|
642
|
+
last = local_day(_when(c.last) or t0)
|
|
643
|
+
when = f"When: {day}" + (f" to {last}" if last > day else "") # R3-6: the fact header
|
|
644
|
+
if not c.coding:
|
|
645
|
+
title = _line(first, TITLE_CHARS) or f"{label} chat {day}"
|
|
646
|
+
out = [f"# {title}", "", f"Timeline: {up}Source: {label} · Date: {day} · {MINE}", "",
|
|
647
|
+
when, f"Who: me and {label}", ""]
|
|
648
|
+
if len(kept) < c.n:
|
|
649
|
+
out += [f"The first {len(kept)} of my {c.n} turns.", ""]
|
|
650
|
+
for ts, t in kept:
|
|
651
|
+
if w := _when(ts):
|
|
652
|
+
out.append(f"### {w.astimezone():%Y-%m-%d %H:%M}")
|
|
653
|
+
out += [f"**Me:** {_ESCAPE.sub(lambda m: chr(92), t)}", ""]
|
|
654
|
+
return Page(title, day, _body(out), "\n".join([title, *(t for _, t in kept)]))
|
|
655
|
+
base = c.cwd.replace("\\", "/").rstrip("/")
|
|
656
|
+
# a Gemini CLI session with no recorded folder: its project's folder in ~/.gemini/tmp
|
|
657
|
+
name = base.split("/.claude/worktrees/")[0].rsplit("/", 1)[-1] or (
|
|
658
|
+
path.parent.parent if source == "gemini-cli" else path.parent).name
|
|
659
|
+
title = _line(f"{name}: {first}" if first else f"Coding in {name}", TITLE_CHARS)
|
|
660
|
+
asked = c.asked
|
|
661
|
+
files = [f"`{r.replace('`', '')}`" for r in (_rel(p, base) for p in c.files) if r]
|
|
662
|
+
done = list(c.commits)
|
|
663
|
+
pid = ctx.project(name)
|
|
664
|
+
named = f"[[{pid}|{topics.alias(name)}]]" if pid else _line(name)
|
|
665
|
+
span = f"on {day}" if last <= day else f"from {day} to {last}"
|
|
666
|
+
out = [f"# {title}", "", f"Timeline: {up}Source: {label} · Date: {day}", "",
|
|
667
|
+
when, f"Who: me and {label}", f"Where: {named}", "",
|
|
668
|
+
f"Coding session in {named} {span}: {c.n_asked} request{'s' * (c.n_asked != 1)}, "
|
|
669
|
+
f"{_n(files, 'file')} changed, {_n(done, 'commit')}.", "", "## What I asked",
|
|
670
|
+
*_list(asked, REQUESTS, c.n_asked)]
|
|
671
|
+
if files:
|
|
672
|
+
out += ["", "## Files touched", *_list(files, FILES)]
|
|
673
|
+
if done:
|
|
674
|
+
out += ["", "## Commits", *_list(done, COMMITS)]
|
|
675
|
+
return Page(title, day, _body(out), "\n".join([title, *asked, *done]),
|
|
676
|
+
[f"[[{pid}]]"] if pid else [])
|
|
677
|
+
|
|
678
|
+
|
|
679
|
+
def _body(lines: list[str]) -> str:
|
|
680
|
+
"""The page body, redacted once more as a whole, ending in one newline."""
|
|
681
|
+
return chats.redact("\n".join(lines)).rstrip("\n") + "\n"
|
|
682
|
+
|
|
683
|
+
|
|
684
|
+
def page_id(source: str, path: Path, page: Page) -> str:
|
|
685
|
+
"""Stable for a transcript: its first turn's day and title, and a hash of its id."""
|
|
686
|
+
h = hashlib.sha1(_key(source, path).encode("utf-8")).hexdigest()[:6]
|
|
687
|
+
slug = slugify(page.title)[:40].rstrip("-")
|
|
688
|
+
return "-".join(x for x in ("chat", page.day, slug, h) if x)
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _core(body: str) -> str:
|
|
692
|
+
"""A page body as hashed: no `Topics:` line (topics.place adds it), LF line ends."""
|
|
693
|
+
body = body.replace("\r\n", "\n")
|
|
694
|
+
return topics._topics_line(body, None, "\n")
|
|
695
|
+
|
|
696
|
+
|
|
697
|
+
def _hash(body: str) -> str:
|
|
698
|
+
return hashlib.sha256(_core(body).encode("utf-8")).hexdigest()[:16]
|
|
699
|
+
|
|
700
|
+
|
|
701
|
+
# ---- one pass ---------------------------------------------------------------------------------
|
|
702
|
+
|
|
703
|
+
class Ctx:
|
|
704
|
+
"""What one pass looks up at most once: settings, the project pages and (for exports) the
|
|
705
|
+
chat pages an earlier import wrote."""
|
|
706
|
+
|
|
707
|
+
def __init__(self, vault: Vault, settings: privacy.Settings | None = None):
|
|
708
|
+
self.vault = vault
|
|
709
|
+
# an imported AI chat is global unless its category says otherwise
|
|
710
|
+
self.settings = replace(settings or privacy.load_settings(), visible_to_claude=True)
|
|
711
|
+
self.folder = chat_archive.folder() # where a new page goes (C5: the archive)
|
|
712
|
+
self._projects: dict[str, str] | None = None
|
|
713
|
+
self._pages: dict | None = None
|
|
714
|
+
self._excluded: dict[str, bool] = {}
|
|
715
|
+
self._heads: dict | None = None # path -> (source, opening, start)
|
|
716
|
+
self._openings: dict = {} # opening -> [(source, start, path)]
|
|
717
|
+
|
|
718
|
+
def audience(self, text: str) -> str:
|
|
719
|
+
return self.judge(text)[1]
|
|
720
|
+
|
|
721
|
+
def judge(self, text: str) -> tuple[str | None, str]:
|
|
722
|
+
"""(the sensitive category `text` falls in or None, that category's audience)."""
|
|
723
|
+
cat = privacy.category("", "/", text)[0]
|
|
724
|
+
return cat, privacy.audience(cat, self.settings)
|
|
725
|
+
|
|
726
|
+
def excluded(self, cwd: str) -> bool:
|
|
727
|
+
if cwd not in self._excluded:
|
|
728
|
+
self._excluded[cwd] = bool(cwd) and taint.excluded(cwd) is not None
|
|
729
|
+
return self._excluded[cwd]
|
|
730
|
+
|
|
731
|
+
def project(self, name: str) -> str | None:
|
|
732
|
+
"""A non-private project page whose id or title is `name` (as slugs)."""
|
|
733
|
+
if self._projects is None:
|
|
734
|
+
self._projects = {}
|
|
735
|
+
for n in self.vault.iter_notes("project"):
|
|
736
|
+
if not is_private(n):
|
|
737
|
+
for k in (n.id, str(n.fields.get("title") or "")):
|
|
738
|
+
if s := slugify(k):
|
|
739
|
+
self._projects.setdefault(s, n.id)
|
|
740
|
+
return self._projects.get(slugify(name))
|
|
741
|
+
|
|
742
|
+
def duplicate(self, source: str, c: Chat, day: str) -> str | None:
|
|
743
|
+
"""A chat page from before (the 15 Nov import, not this module's) of the same app whose
|
|
744
|
+
first `**Me:**` line matches `c`'s first turn, dated within a day of it."""
|
|
745
|
+
if self._pages is None:
|
|
746
|
+
self._pages = {}
|
|
747
|
+
for p in self.vault.note_paths("resource"): # resources/ and archive/chats/
|
|
748
|
+
try:
|
|
749
|
+
with p.open("rb") as f:
|
|
750
|
+
head = f.read(4096).decode("utf-8", "replace")
|
|
751
|
+
except OSError:
|
|
752
|
+
continue
|
|
753
|
+
tl = topics.TL_RE.search(head)
|
|
754
|
+
src = _SOURCE.search(tl[0]) if tl and MINE not in tl[0] else None
|
|
755
|
+
me = _ME.search(head)
|
|
756
|
+
if src and me and (k := _match(me[1])):
|
|
757
|
+
d = _DATE.search(tl[0])
|
|
758
|
+
self._pages.setdefault((src[1].casefold(), k), []).append(
|
|
759
|
+
(d[1] if d else "", p.stem))
|
|
760
|
+
k = _match(c.head)
|
|
761
|
+
for d, pid in self._pages.get((LABELS[source].casefold(), k), []) if k else []:
|
|
762
|
+
try:
|
|
763
|
+
near = abs((date.fromisoformat(d) - date.fromisoformat(day)).days) <= 1
|
|
764
|
+
except ValueError: # no date, or not a real one
|
|
765
|
+
near = True
|
|
766
|
+
if near:
|
|
767
|
+
return pid
|
|
768
|
+
return None
|
|
769
|
+
|
|
770
|
+
def partner(self, path: Path) -> Path | None:
|
|
771
|
+
"""For a claude.ai export conversation its live Chat-tab log, for a live log its export
|
|
772
|
+
conversation: the one other-kind chat with the same opening started within SAME_CHAT,
|
|
773
|
+
and `path` the only such chat for it; None when none or several match."""
|
|
774
|
+
if self._heads is None:
|
|
775
|
+
self._heads = {}
|
|
776
|
+
for folder, s in (EXPORT, (chats.LIVE, chats.LIVE)):
|
|
777
|
+
for p in (chats.export_root() / folder).glob("*.jsonl"):
|
|
778
|
+
if h := _opening(p):
|
|
779
|
+
self._heads[p] = (s, *h)
|
|
780
|
+
self._openings.setdefault(h[0], []).append((s, h[1], p))
|
|
781
|
+
|
|
782
|
+
def near(p: Path) -> list:
|
|
783
|
+
s, k, t = self._heads[p]
|
|
784
|
+
return [q for s2, t2, q in self._openings[k] if s2 != s and abs(t2 - t) <= SAME_CHAT]
|
|
785
|
+
m = near(path) if path in self._heads else []
|
|
786
|
+
return m[0] if len(m) == 1 and near(m[0]) == [path] else None
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _said(text: str) -> str:
|
|
790
|
+
return " ".join(chats.redact(text).split())[:OPENING]
|
|
791
|
+
|
|
792
|
+
|
|
793
|
+
def _opening(p: Path) -> tuple[str, datetime] | None:
|
|
794
|
+
"""A chat's first message as compared (_said) and its time; None without one."""
|
|
795
|
+
try:
|
|
796
|
+
with closing(chats._turns(p)) as ts:
|
|
797
|
+
first = next(((t0, t) for r, t0, t in ts if r == "user"), None)
|
|
798
|
+
except OSError:
|
|
799
|
+
return None
|
|
800
|
+
w = _when(first[0]) if first else None
|
|
801
|
+
return (_said(first[1]), w) if w else None
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
def _merged(export: Path, live: Path, pace: Callable[[], None]) -> Chat:
|
|
805
|
+
"""One chat from both: the export's turns, then the live log's turns after the export's
|
|
806
|
+
last message that follow the last live turn the export holds (each turn once)."""
|
|
807
|
+
c, _ = read(export, None, pace)
|
|
808
|
+
ex = chats.turns(export)
|
|
809
|
+
said = [_said(t) for r, _, t in ex if r == "user"]
|
|
810
|
+
end = max((w for _, ts, _ in ex if (w := _when(ts))), default=None)
|
|
811
|
+
j, new = 0, []
|
|
812
|
+
for r, ts, t in chats.turns(live):
|
|
813
|
+
if r != "user":
|
|
814
|
+
continue
|
|
815
|
+
if (k := _said(t)) in said[j:]: # in order, so a repeated "go on" later is still new
|
|
816
|
+
j += said[j:].index(k) + 1
|
|
817
|
+
new.clear()
|
|
818
|
+
elif end is not None and (w := _when(ts)) is not None and w > end:
|
|
819
|
+
new.append((ts, t))
|
|
820
|
+
for ts, t in new:
|
|
821
|
+
c.turn(ts, t)
|
|
822
|
+
c.last = ts
|
|
823
|
+
return c
|
|
824
|
+
|
|
825
|
+
|
|
826
|
+
def _pid(e) -> str | None:
|
|
827
|
+
"""The page of a ledger entry."""
|
|
828
|
+
pages = e.get("pages") if isinstance(e, dict) else None
|
|
829
|
+
return pages[0] if isinstance(pages, list) and pages and isinstance(pages[0], str) else None
|
|
830
|
+
|
|
831
|
+
|
|
832
|
+
def _match(line: str) -> str:
|
|
833
|
+
return re.sub(r"\W+", "", chats.redact(line).casefold())[:60]
|
|
834
|
+
|
|
835
|
+
|
|
836
|
+
def _ledger(events) -> dict:
|
|
837
|
+
"""(source, chat id) -> the payload of its latest live chat_saved event."""
|
|
838
|
+
out = {}
|
|
839
|
+
for e in live(events):
|
|
840
|
+
p = e.get("payload")
|
|
841
|
+
if e.get("kind") == "log" and isinstance(p, dict) and p.get("kind") == "chat_saved":
|
|
842
|
+
out[(p.get("source"), p.get("chat_id"))] = p
|
|
843
|
+
return out
|
|
844
|
+
|
|
845
|
+
|
|
846
|
+
def made_private(vault: Vault, events, settings: privacy.Settings | None = None) -> list[dict]:
|
|
847
|
+
"""The imported chats this module wrote private for a sensitive category and that are still
|
|
848
|
+
private, newest first: [{id, title, app, date, category}]; titles plain (`render.plain`),
|
|
849
|
+
never chat text. The category is the one recorded when the page was written; a page
|
|
850
|
+
written before it was recorded is judged again from its body under the settings of now
|
|
851
|
+
(listed only when that category is local-only)."""
|
|
852
|
+
ctx = Ctx(vault, settings)
|
|
853
|
+
out: dict[str, dict] = {}
|
|
854
|
+
for p in _ledger(events).values():
|
|
855
|
+
pid = _pid(p)
|
|
856
|
+
if not p.get("auto") or pid is None or pid in out:
|
|
857
|
+
continue
|
|
858
|
+
try:
|
|
859
|
+
n = vault.read("resource", pid)
|
|
860
|
+
except VaultError:
|
|
861
|
+
continue
|
|
862
|
+
if n.fields.get("private") is not True:
|
|
863
|
+
continue
|
|
864
|
+
cat = p.get("category")
|
|
865
|
+
if not isinstance(cat, str):
|
|
866
|
+
cat, aud = ctx.judge(n.body)
|
|
867
|
+
if aud != "local" or cat is None:
|
|
868
|
+
continue
|
|
869
|
+
out[pid] = {"id": pid, "title": render.plain(str(n.fields.get("title") or pid)),
|
|
870
|
+
"app": LABELS.get(p.get("source"), str(p.get("source") or "")),
|
|
871
|
+
"date": str(n.fields.get("date") or ""), "category": cat}
|
|
872
|
+
return sorted(out.values(), key=lambda r: (r["date"], r["id"]), reverse=True)
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def _event(evlog: EventLog, ledger: dict, source: str, cid: str, title: str, pid: str,
|
|
876
|
+
h: str, category: str | None = None) -> None:
|
|
877
|
+
"""The chat_saved ledger line. The key makes a retry after a crash a no-op; `ledger` is
|
|
878
|
+
kept current for this pass. `category`: the sensitive category that made the page
|
|
879
|
+
private (`made_private` lists it)."""
|
|
880
|
+
key = "chat-import:" + hashlib.sha1(f"{source}:{cid}".encode()).hexdigest()[:16] + f":{h}"
|
|
881
|
+
payload = {"kind": "chat_saved", "source": source, "chat_id": cid, "title": title,
|
|
882
|
+
"pages": [pid], "auto": True, "hash": h, **({"category": category} if category
|
|
883
|
+
else {})}
|
|
884
|
+
evlog.append(session="import", kind="log", source="imported", key=key,
|
|
885
|
+
fields={"payload": payload})
|
|
886
|
+
ledger[(source, cid)] = payload
|
|
887
|
+
|
|
888
|
+
|
|
889
|
+
class _Edited(Exception):
|
|
890
|
+
pass
|
|
891
|
+
|
|
892
|
+
|
|
893
|
+
def _rewrite(vault: Vault, path: Path, page: Page, was: str, private: bool) -> None:
|
|
894
|
+
"""Replace the page body, keeping its `Topics:` line and frontmatter (the title follows the
|
|
895
|
+
heading unless the owner renamed it); `private` sets `private: true` (never unset).
|
|
896
|
+
_Edited when the body is no longer the one hashed `was`."""
|
|
897
|
+
def change(text: str) -> str:
|
|
898
|
+
parts = _split(text)
|
|
899
|
+
if parts is None:
|
|
900
|
+
raise _Edited
|
|
901
|
+
head, fm, close, body = parts
|
|
902
|
+
if _hash(body) != was:
|
|
903
|
+
raise _Edited
|
|
904
|
+
nl = _newline(text)
|
|
905
|
+
m = topics.TOP_RE.search(body)
|
|
906
|
+
data = _load_fm(fm)
|
|
907
|
+
h1 = body.lstrip().split("\n", 1)[0].removeprefix("# ").strip()
|
|
908
|
+
retitle = data.get("title") == h1 != page.title
|
|
909
|
+
if retitle or (private and not truthy(data.get("private"))):
|
|
910
|
+
if retitle:
|
|
911
|
+
data["title"] = page.title
|
|
912
|
+
if private:
|
|
913
|
+
data["private"] = True
|
|
914
|
+
fm = _dump_fm(data, nl)
|
|
915
|
+
new = topics._topics_line(page.body, m[0] if m else None, "\n")
|
|
916
|
+
return head + fm + close + new.replace("\n", nl)
|
|
917
|
+
vault.update_text(path, change)
|
|
918
|
+
|
|
919
|
+
|
|
920
|
+
def one(vault: Vault, evlog: EventLog, ctx: Ctx, ledger: dict, source: str, path: Path,
|
|
921
|
+
prev: dict | None = None, pace: Callable[[], None] = lambda: None) -> tuple[str, dict]:
|
|
922
|
+
"""Write or update one transcript's page from its STATE record `prev`; returns what
|
|
923
|
+
happened (a count's name) and the new record."""
|
|
924
|
+
cid = chats._cid(path)
|
|
925
|
+
had = ledger.get((source, cid))
|
|
926
|
+
if had is not None and not had.get("auto"):
|
|
927
|
+
return "saved_by_hand", {}
|
|
928
|
+
if prev and isinstance(prev.get("adopted"), str):
|
|
929
|
+
return "earlier_import", prev
|
|
930
|
+
c, rec = read(path, prev, pace, source)
|
|
931
|
+
if not c.n:
|
|
932
|
+
return "empty", rec
|
|
933
|
+
if ctx.excluded(c.cwd):
|
|
934
|
+
return "excluded_folder", rec
|
|
935
|
+
keys = [(source, cid)] # the ledger keys this page is written for
|
|
936
|
+
if source in (EXPORT[1], chats.LIVE) and (other := ctx.partner(path)) is not None:
|
|
937
|
+
okey = (EXPORT[1] if source == chats.LIVE else chats.LIVE, chats._cid(other))
|
|
938
|
+
o = ledger.get(okey)
|
|
939
|
+
mine, theirs = _pid(had), _pid(o)
|
|
940
|
+
# a hand-saved partner, or two pages already (written before this rule), stay apart
|
|
941
|
+
if (o is None or o.get("auto")) and not (mine and theirs and mine != theirs):
|
|
942
|
+
c = _merged(*((path, other) if source == EXPORT[1] else (other, path)), pace)
|
|
943
|
+
keys.append(okey)
|
|
944
|
+
had = had if mine else o
|
|
945
|
+
page = build(source, path, c, ctx)
|
|
946
|
+
cat, audience = ctx.judge(page.text)
|
|
947
|
+
if audience == "skip":
|
|
948
|
+
return "skipped_category", rec
|
|
949
|
+
# R3-5: an imported chat's //tags are the owner's typed words, so said; a private
|
|
950
|
+
# (local-only) chat's stay in its private page, off the shared me/* pages
|
|
951
|
+
if c.tags and audience != "local":
|
|
952
|
+
try:
|
|
953
|
+
tags.apply_in(vault, [tuple(t) for t in c.tags], evlog, forget_said=False)
|
|
954
|
+
except (OSError, ValueError, VaultError) as e: # the page is still written
|
|
955
|
+
log.warning("chat import: the //tags of %s not saved (%s)", cid,
|
|
956
|
+
getattr(e, "code", type(e).__name__))
|
|
957
|
+
pid = _pid(had)
|
|
958
|
+
if pid is None and source not in AGENTS and (old := ctx.duplicate(source, c, page.day)):
|
|
959
|
+
# kept in STATE only, not the event log: thousands of these would each cost an append
|
|
960
|
+
return "earlier_import", {"adopted": old}
|
|
961
|
+
pid = pid or page_id(source, path, page)
|
|
962
|
+
h, md = _hash(page.body), vault.path_for("resource", pid)
|
|
963
|
+
|
|
964
|
+
def mark() -> None:
|
|
965
|
+
for s, i in keys:
|
|
966
|
+
e = ledger.get((s, i))
|
|
967
|
+
if e is None or e.get("hash") != h or _pid(e) != pid:
|
|
968
|
+
_event(evlog, ledger, s, i, page.title, pid, h,
|
|
969
|
+
cat if audience == "local" else None)
|
|
970
|
+
if not md.is_file():
|
|
971
|
+
if had is not None:
|
|
972
|
+
return "deleted_by_you", rec # never brought back
|
|
973
|
+
fields = {"title": page.title, "kind": "resource", "resource_type": "other",
|
|
974
|
+
"status": "reference", "covers": [], "related": page.related,
|
|
975
|
+
"date": page.day, **({"private": True} if audience == "local" else {})}
|
|
976
|
+
vault.create_note("resource", pid, fields, page.body, folder=ctx.folder)
|
|
977
|
+
mark()
|
|
978
|
+
return "saved", rec
|
|
979
|
+
now = _hash(vault.read("resource", pid).body)
|
|
980
|
+
if now == h:
|
|
981
|
+
mark()
|
|
982
|
+
return "unchanged", rec
|
|
983
|
+
if had is None or had.get("hash") != now:
|
|
984
|
+
return "edited_by_you", rec
|
|
985
|
+
try:
|
|
986
|
+
_rewrite(vault, md, page, now, audience == "local")
|
|
987
|
+
except _Edited:
|
|
988
|
+
return "edited_by_you", rec
|
|
989
|
+
mark()
|
|
990
|
+
return "updated", rec
|
|
991
|
+
|
|
992
|
+
|
|
993
|
+
def run(vault: Vault, *, progress: Callable | None = None,
|
|
994
|
+
cancelled: Callable[[], bool] | None = None,
|
|
995
|
+
settings: privacy.Settings | None = None, now: float | None = None) -> dict:
|
|
996
|
+
"""One pass over pending() under LOCK (VaultError("busy") while another runs), newest
|
|
997
|
+
first, STATE saved after each transcript. Returns counts: saved, updated, unchanged, failed
|
|
998
|
+
and each kind of skip; `stopped` when cancelled. `progress(done, total, seconds)` follows
|
|
999
|
+
each chat."""
|
|
1000
|
+
taint.check_config("the chat import")
|
|
1001
|
+
with vault.job_lock(LOCK, 0, BUSY), closing(State(vault)) as state:
|
|
1002
|
+
todo = pending(vault, now, state.sigs())
|
|
1003
|
+
counts: Counter = Counter()
|
|
1004
|
+
if not todo:
|
|
1005
|
+
return {}
|
|
1006
|
+
evlog = EventLog(vault)
|
|
1007
|
+
ledger = _ledger(evlog.iter_events())
|
|
1008
|
+
ctx, t0, pace = Ctx(vault, settings), time.monotonic(), Pace(cancelled)
|
|
1009
|
+
if ctx.folder:
|
|
1010
|
+
chat_archive.ensure_ignored(vault) # an older vault: before a page lands there
|
|
1011
|
+
for k, (source, path, sig) in enumerate(todo, 1):
|
|
1012
|
+
key = _key(source, path)
|
|
1013
|
+
try:
|
|
1014
|
+
if cancelled is not None and cancelled():
|
|
1015
|
+
raise _Stop
|
|
1016
|
+
pace()
|
|
1017
|
+
what, rec = one(vault, evlog, ctx, ledger, source, path, state.get(key), pace)
|
|
1018
|
+
except _Stop:
|
|
1019
|
+
counts["stopped"] = 1
|
|
1020
|
+
break
|
|
1021
|
+
except (OSError, ValueError, VaultError) as e:
|
|
1022
|
+
log.warning("chat import: %s not imported (%s)", chats._cid(path),
|
|
1023
|
+
getattr(e, "code", type(e).__name__))
|
|
1024
|
+
what, rec = "failed", {} # read from the start once it changes
|
|
1025
|
+
if isinstance(e, OSError) or getattr(e, "code", None) in TRANSIENT:
|
|
1026
|
+
sig = None # tried again next pass
|
|
1027
|
+
counts[what] += 1
|
|
1028
|
+
if sig is not None:
|
|
1029
|
+
state.put(key, sig, rec)
|
|
1030
|
+
if progress is not None:
|
|
1031
|
+
progress(k, len(todo), time.monotonic() - t0)
|
|
1032
|
+
if n := counts["saved"] + counts["updated"]:
|
|
1033
|
+
vault.append_log(local_day(datetime.now(UTC)), "chat",
|
|
1034
|
+
f"{n} chat{'s' * (n != 1)} saved automatically")
|
|
1035
|
+
return dict(counts)
|
|
1036
|
+
|
|
1037
|
+
|
|
1038
|
+
def eta(done: int, total: int, seconds: float) -> str:
|
|
1039
|
+
"""The progress line: "12 of 300 chats", plus a percent and the time left past FEW."""
|
|
1040
|
+
line = f"{done} of {total} chats"
|
|
1041
|
+
if total <= FEW:
|
|
1042
|
+
return line
|
|
1043
|
+
left = seconds / max(done, 1) * (total - done)
|
|
1044
|
+
when = f"{round(left)} s" if left < 90 else f"{round(left / 60)} min"
|
|
1045
|
+
return f"{line} ({done * 100 // total}%), about {when} left"
|