cotrail 0.7.1__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.
Files changed (82) hide show
  1. cotrail/__init__.py +64 -0
  2. cotrail/aliases.py +132 -0
  3. cotrail/assistant_setup.py +280 -0
  4. cotrail/beads.py +41 -0
  5. cotrail/calls.py +100 -0
  6. cotrail/cc_transcripts.py +323 -0
  7. cotrail/claude_ai_export.py +116 -0
  8. cotrail/cli.py +643 -0
  9. cotrail/clients.py +423 -0
  10. cotrail/e1/__init__.py +1 -0
  11. cotrail/e1/budget.py +71 -0
  12. cotrail/e1/judge.py +131 -0
  13. cotrail/e1/llm.py +109 -0
  14. cotrail/e1/tasks.py +82 -0
  15. cotrail/e1/variants.py +275 -0
  16. cotrail/e1b/__init__.py +1 -0
  17. cotrail/e1b/backends.py +281 -0
  18. cotrail/e1b/chat.py +95 -0
  19. cotrail/e1b/coverage.py +169 -0
  20. cotrail/e1b/decisions.py +114 -0
  21. cotrail/e1b/judge.py +252 -0
  22. cotrail/e1b/memory.py +383 -0
  23. cotrail/e1b/replaces.py +110 -0
  24. cotrail/e1b/runner.py +264 -0
  25. cotrail/e1b/selection.py +162 -0
  26. cotrail/e1b/sleeves.py +305 -0
  27. cotrail/e1b/steps.py +164 -0
  28. cotrail/e1b/thinking.py +245 -0
  29. cotrail/e1b/v9.py +412 -0
  30. cotrail/e3/__init__.py +1 -0
  31. cotrail/e3/data.py +135 -0
  32. cotrail/embed.py +77 -0
  33. cotrail/episodes.py +143 -0
  34. cotrail/flow.py +203 -0
  35. cotrail/graph.py +562 -0
  36. cotrail/graphify.py +256 -0
  37. cotrail/ingest.py +264 -0
  38. cotrail/legacy.py +140 -0
  39. cotrail/lexical.py +72 -0
  40. cotrail/mcp_server.py +69 -0
  41. cotrail/memory.py +2645 -0
  42. cotrail/memory_mcp.py +517 -0
  43. cotrail/menu.py +176 -0
  44. cotrail/model.py +131 -0
  45. cotrail/overview.py +578 -0
  46. cotrail/pasted.py +173 -0
  47. cotrail/privacy.py +75 -0
  48. cotrail/setup.py +544 -0
  49. cotrail/sources/__init__.py +16 -0
  50. cotrail/sources/base.py +40 -0
  51. cotrail/sources/conceptnet.py +94 -0
  52. cotrail/sources/experience.py +96 -0
  53. cotrail/sources/wikidata.py +312 -0
  54. cotrail/sources/wordnet.py +210 -0
  55. cotrail/store.py +352 -0
  56. cotrail/text.py +598 -0
  57. cotrail/topics.py +56 -0
  58. cotrail/v2/__init__.py +5 -0
  59. cotrail/v2/english.py +78 -0
  60. cotrail/v2/extract.py +155 -0
  61. cotrail/v2/gate.py +190 -0
  62. cotrail/v2/graph.py +478 -0
  63. cotrail/v2/planner.py +59 -0
  64. cotrail/v2/sleeves.py +212 -0
  65. cotrail/v2/store.py +193 -0
  66. cotrail/vendor/3d-force-graph.LICENSE +27 -0
  67. cotrail/vendor/3d-force-graph.min.js +5 -0
  68. cotrail/vendor/force-graph.LICENSE +21 -0
  69. cotrail/vendor/force-graph.min.js +5 -0
  70. cotrail/vendor/three.LICENSE +21 -0
  71. cotrail/vendor/three.min.js +6 -0
  72. cotrail/viewer.py +223 -0
  73. cotrail/viewer_cosmos.js +514 -0
  74. cotrail/viewer_flow.js +502 -0
  75. cotrail/viewer_i18n.js +110 -0
  76. cotrail/viewer_template.html +393 -0
  77. cotrail-0.7.1.dist-info/METADATA +471 -0
  78. cotrail-0.7.1.dist-info/RECORD +82 -0
  79. cotrail-0.7.1.dist-info/WHEEL +5 -0
  80. cotrail-0.7.1.dist-info/entry_points.txt +9 -0
  81. cotrail-0.7.1.dist-info/licenses/LICENSE +202 -0
  82. cotrail-0.7.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,323 @@
1
+ """Read Claude Code session transcripts (~/.claude/projects/<project>/*.jsonl) as conversation turns (ARCHITECTURE_V2 §3.15).
2
+
3
+ Only what the people in the chat said: user prompts and the assistant's visible prose. Not stored (noise for a
4
+ decision memory): tool calls and results, thinking, system reminders and harness notices, compaction summaries,
5
+ sidechains (subagents), code blocks, command lines, git / log / traceback output, and lines repeated from earlier
6
+ turns (pastes, resumed sessions). Each turn: {"id", "session", "role", "ts", "text", "source"}.
7
+
8
+ python -m cotrail.cc_transcripts <project_dir>
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import hashlib
14
+ import json
15
+ import re
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ NOISE = re.compile(r"<system-reminder>.*?</system-reminder>|<task-notification>.*?</task-notification>|"
20
+ r"<command-[a-z-]+>.*?</command-[a-z-]+>|<local-command-[a-z-]+>.*?</local-command-[a-z-]+>|"
21
+ r"<agent-message.*?</agent-message>|\[Request interrupted[^\]]*\]|\[SYSTEM NOTIFICATION[^\n]*|"
22
+ r"<(side-sessions-event|ci-monitor-event)[^>]*>.*?</\1>|^API Error:[^\n]*", re.S | re.M) # fmt: skip
23
+ PASTE = re.compile(r"</?pasted_content[^>]*>")
24
+ PASTE_BLOCK = re.compile(r"<pasted_content[^>]*>(.*?)</pasted_content>", re.S)
25
+ TERM_START = re.compile(r"^\s*(PS [A-Za-z]:\\[^>\n]*>|\$ )")
26
+
27
+
28
+ def pasted_blocks(raw: str) -> str:
29
+ """The pasted material of a user turn (the inbox rule B): `<pasted_content>` blocks and terminal blocks (a line
30
+ `PS C:\\...>` / `$ ` and the non-blank lines after it); "" when none."""
31
+ out = [m.group(1).strip() for m in PASTE_BLOCK.finditer(raw or "")]
32
+ cur: list[str] | None = None
33
+ for ln in PASTE_BLOCK.sub("\n", raw or "").splitlines():
34
+ if TERM_START.match(ln):
35
+ cur = [ln]
36
+ out.append(cur) # type: ignore[arg-type]
37
+ elif cur is not None and ln.strip():
38
+ cur.append(ln)
39
+ else:
40
+ cur = None
41
+ return "\n\n".join(b if isinstance(b, str) else "\n".join(b) for b in out if b).strip()
42
+ FENCE = re.compile(r"```.*?(```|$)", re.S)
43
+ # a line of tool / git / log output rather than something a person said
44
+ OUTPUT_LINE = re.compile(
45
+ r"^\s*(\$ |> \$|PS [A-Z]:|warning:|error:|fatal:|Traceback| File \"|Exit code|exit \d|\[\d{2}/\d{2}/\d{2}|"
46
+ r"[0-9a-f]{7,40} [A-Z][^\n]{0,80}$|(On branch|Your branch|Changes (not staged|to be committed)|Untracked files)|"
47
+ r"\s*(M|A|D|R|\?\?) +[\w./-]+$|Kernel (version|push)|Dataset version|Upload successful|Starting upload|"
48
+ r"Loading weights|Batches:|INFO |DEBUG |WARN(ING)? |\d+ (passed|failed)|=+ .* =+$|[A-Z]:[\\/][^ ]+$|"
49
+ r"/c/Users/[^ ]+$|https?://\S+$)", re.I) # fmt: skip
50
+ # A short user turn with no content of its own ("Fix them", "да", "ок", "давай", "Yes, recreate") confirms the
51
+ # assistant's previous message. Criterion fixed before any check: at most SHORT_WORDS words and not
52
+ # a question. It is kept as an anchor (the report that follows belongs to it) but has no place of its own in search.
53
+ SHORT_WORDS = 3
54
+ ASKS = re.compile(r"(\?\s*$|^\W*(?:(?:ну|а|и|ок|ok),?\s+)?(почему|зачем|как|что|где|когда|сколько|кто|какой|какая|какие|"
55
+ r"чем|разве|what|why|how|where|when|which|who)\b)", re.I)
56
+
57
+
58
+ def is_short(text: str) -> bool:
59
+ t = text.strip()
60
+ return 0 < len(re.findall(r"\w+", t)) <= SHORT_WORDS and not ASKS.search(t)
61
+
62
+
63
+ # Dialogue act of a short user turn (ISO 24617-2 / DAMSL classes, rules written before
64
+ # the check). Checked in this order, the first that fires wins: reject / defer -> status -> agree -> directive -> other.
65
+ ACT_REJECT = re.compile(r"^(нет|не надо|не нужно|не стоит|отмена|отменяй|стоп|no|nope|don'?t|cancel|stop|"
66
+ # v2 (the english cues v2 rule)
67
+ r"nah|not that|let'?s not|skip( it| that)?|never ?mind|scratch that|scrap( it| that)?|forget)\b", re.I)
68
+ ACT_DEFER = re.compile(r"\b(потом|позже|подожди|погоди|не сейчас|сначала обсудим|обсудим|later|wait|not now|hold on|"
69
+ r"postpone|discuss first|let'?s discuss|"
70
+ # v2 (the english cues v2 rule)
71
+ r"revisit|park( it| that)?|table( it| that)|punt|tomorrow|next (week|sprint|time)|hold off|hang on|"
72
+ r"(a|one) (sec|second|minute|moment)|remind me|someday)\b", re.I)
73
+ ACT_STATUS_WORDS = {"готово", "готов", "завершён", "завершен", "завершено", "закончилось", "ошибка", "ошибкой", "упал",
74
+ "упало", "done", "started", "finished", "failed", "error", "crashed", "deleted", "ready"}
75
+ ACT_ED_EXCEPT = {"need", "seed", "feed", "speed", "bed"}
76
+ # v2 (the english cues v2 rule): "still broken", "works now", "ci is green"
77
+ ACT_STATUS = re.compile(r"\b(still (broken|failing|red)|works now|working now|(is|are) (green|red|broken|passing|failing))\b")
78
+ ACT_AGREE = re.compile(r"^(да|ага|угу|ок|окей|ok|okay|давай|давайте|согласен|согласна|конечно|хорошо|ладно|принято|yes|"
79
+ r"yep|yeah|sure|go|fine|agreed|approved|lgtm|sounds good|go ahead|do it|let'?s go|"
80
+ # v2 (the english cues v2 rule)
81
+ r"ship it|perfect|makes sense|alright|all right|works for me|great|nice|cool)\b", re.I)
82
+ ACT_EN_VERBS = {"fix", "do", "push", "start", "connect", "continue", "run", "delete", "check", "add", "make", "try",
83
+ "commit", "merge", "retry", "rerun", "proceed", "use", "keep", "remove", "revert", "apply", "deploy",
84
+ "publish", "send", "write", "go", "restart", "recreate", "rollback", "undo", "open", "show", "stop",
85
+ "bump", "refactor", "rename", "update", "implement", "revert", "wire", "install", "upgrade"}
86
+ _MORPH = None
87
+
88
+
89
+ def _morph():
90
+ global _MORPH
91
+ if _MORPH is None:
92
+ import pymorphy3
93
+
94
+ _MORPH = pymorphy3.MorphAnalyzer()
95
+ return _MORPH
96
+
97
+
98
+ def short_act(text: str) -> str:
99
+ """"reject" / "defer" / "status" / "agree" / "directive" / "other" for a short user turn."""
100
+ s = " ".join(re.findall(r"[\w'-]+", text.lower()))
101
+ words = s.split()
102
+ if ACT_REJECT.search(s):
103
+ return "reject"
104
+ if ACT_DEFER.search(s):
105
+ return "defer"
106
+ if ACT_STATUS.search(s) or any(w in ACT_STATUS_WORDS for w in words) or any(re.fullmatch(r"[a-z]+ed", w) and w not in ACT_ED_EXCEPT
107
+ for w in words): # fmt: skip
108
+ return "status"
109
+ cyr = [w for w in words if re.search(r"[а-яё]", w)]
110
+ parses = [_morph().parse(w)[0] for w in cyr]
111
+ if any(("VERB" in p.tag and "past" in p.tag) or "PRTS" in p.tag for p in parses):
112
+ return "status"
113
+ if ACT_AGREE.search(s):
114
+ return "agree"
115
+ lead_infn = bool(cyr) and words[0] == cyr[0] and "INFN" in parses[0].tag # "Откатить миграцию": directive infinitive
116
+ lets = len(words) >= 2 and words[0] in ("let's", "lets") # "let's do it", "let's ship"
117
+ if any(_imperative(w) for w in cyr) or lead_infn or lets or (words and words[0] in ACT_EN_VERBS):
118
+ return "directive"
119
+ return "other"
120
+
121
+
122
+ CONTINUE = re.compile(r"^\W*(continue|продолжай|продолжи|продолжаем)\W*$", re.I)
123
+ QUOTED = re.compile(r"«[^»]*»|`[^`]*`|\"[^\"]*\"")
124
+
125
+
126
+ def is_request(assistant_text: str) -> bool:
127
+ """The assistant's message asks the user to do something: a Russian imperative verb outside quotes, English
128
+ "please", or a sentence starting with an English verb of the directive list (the dialog acts rule, addendum 2)."""
129
+ s = QUOTED.sub(" ", assistant_text)
130
+ if re.search(r"\bplease\b", s, re.I):
131
+ return True
132
+ for sent in re.split(r"(?<=[.!?:])\s+|\n", s):
133
+ w = re.findall(r"[a-z]+", sent.strip().lower()[:20])
134
+ if w and sent.strip()[:1].isalpha() and sent.strip().lower().startswith(w[0]) and w[0] in ACT_EN_VERBS:
135
+ return True
136
+ return any(_imperative(w) for w in re.findall(r"[а-яё]+", s.lower()))
137
+
138
+
139
+ def _imperative(word: str) -> bool:
140
+ """A verb that reads as imperative: its first parse is a verb and a parse of the same lemma has `impr`
141
+ ("удалите" is first parsed as future indicative; "мой" is a pronoun, not "мыть")."""
142
+ ps = _morph().parse(word)
143
+ return "VERB" in ps[0].tag and any("impr" in p.tag and p.normal_form == ps[0].normal_form for p in ps)
144
+
145
+
146
+ SERVICE = re.compile(r"^(Continue\.?|Tool loaded\.?|No response requested\.?|ок|ok|да|нет|ну что там|сколько там ещё)$", re.I)
147
+
148
+
149
+ def _ask(content) -> str:
150
+ """The question of the desktop app's end-of-turn box (`wrap_up.ask`): what the assistant asked the user to decide
151
+ or do; the user's short reply answers it."""
152
+ for b in content or [] if isinstance(content, list) else []:
153
+ if isinstance(b, dict) and b.get("type") == "tool_use" and str(b.get("name", "")).endswith("wrap_up"):
154
+ return str((b.get("input") or {}).get("ask") or "")
155
+ return ""
156
+
157
+
158
+ def _text(content) -> str:
159
+ """Visible text. The desktop app's end-of-turn box (`wrap_up`) holds the assistant's final recap in a tool call,
160
+ not in text - it is the turn's report, so it is kept."""
161
+ if isinstance(content, str):
162
+ return content
163
+ parts = []
164
+ for b in content or []:
165
+ if not isinstance(b, dict):
166
+ continue
167
+ if b.get("type") == "text":
168
+ parts.append(b.get("text", ""))
169
+ elif b.get("type") == "tool_use" and str(b.get("name", "")).endswith("wrap_up"):
170
+ parts.append((b.get("input") or {}).get("recap", ""))
171
+ return "\n".join(p for p in parts if p)
172
+
173
+
174
+ def agent_origin(r: dict) -> dict | None:
175
+ """A `user` record the human did not type (rules written before the code): a peer session's message
176
+ (`turnOrigin` / `origin.kind` "peer"), the task another session started this one with (`host_synthetic`), or a
177
+ note of the app (`sdk` / `sdk`). None for the human's own turns and for old records without these fields."""
178
+ o = r.get("origin") if isinstance(r.get("origin"), dict) else {}
179
+ to, ps = r.get("turnOrigin"), r.get("promptSource")
180
+ if to == "peer" or o.get("kind") == "peer":
181
+ return {"kind": "peer", "parent": str(o.get("from") or ""), "body": str(o.get("body") or "")}
182
+ if to == "host_synthetic":
183
+ return {"kind": "brief", "parent": "", "body": ""}
184
+ if to == "sdk" and ps == "sdk":
185
+ return {"kind": "host", "parent": "", "body": ""}
186
+ return None
187
+
188
+
189
+ def launches(path: Path) -> list[tuple[str, str]]:
190
+ """(session, text) of the tasks this transcript sent to other sessions: `start_session` prompts and
191
+ `SendMessage` messages."""
192
+ out = []
193
+ for line in path.read_text("utf-8", errors="replace").splitlines():
194
+ if '"tool_use"' not in line or ("start_session" not in line and "SendMessage" not in line):
195
+ continue
196
+ try:
197
+ r = json.loads(line)
198
+ except json.JSONDecodeError:
199
+ continue
200
+ for b in (r.get("message") or {}).get("content") or []:
201
+ if isinstance(b, dict) and b.get("type") == "tool_use":
202
+ name, inp = str(b.get("name", "")), b.get("input") or {}
203
+ text = inp.get("prompt") if name.endswith("start_session") else inp.get("message") if name == "SendMessage" else None
204
+ if text:
205
+ out.append((r.get("sessionId") or path.stem, str(text)))
206
+ return out
207
+
208
+
209
+ def _key(text: str, n: int | None = 200) -> str:
210
+ k = re.sub(r"\W+", " ", text).strip().lower()
211
+ return k[:n] if n else k
212
+
213
+
214
+ def clean(text: str) -> str:
215
+ text = FENCE.sub("\n", PASTE.sub("", NOISE.sub("", text)))
216
+ lines = [ln for ln in text.splitlines() if not OUTPUT_LINE.search(ln)]
217
+ return re.sub(r"\n{3,}", "\n\n", "\n".join(lines)).strip()
218
+
219
+
220
+ def title_of(lines: list[str]) -> str:
221
+ """A Claude Code session's title: its `summary` record (the name the app shows), else ""."""
222
+ for line in lines:
223
+ if '"summary"' not in line:
224
+ continue
225
+ try:
226
+ r = json.loads(line)
227
+ except json.JSONDecodeError:
228
+ continue
229
+ if r.get("type") == "summary" and isinstance(r.get("summary"), str) and r["summary"].strip():
230
+ return r["summary"].strip()[:120]
231
+ return ""
232
+
233
+
234
+ def turns(path: Path):
235
+ after_summary = False # the next kept turn comes right after a compaction summary
236
+ lines = path.read_text("utf-8", errors="replace").splitlines()
237
+ title = title_of(lines)
238
+ for line in lines:
239
+ try:
240
+ r = json.loads(line)
241
+ except json.JSONDecodeError:
242
+ continue
243
+ if r.get("isCompactSummary"):
244
+ after_summary = True
245
+ continue
246
+ peer = r.get("type") == "user" and (agent_origin(r) or {}).get("kind") == "peer"
247
+ if r.get("isSidechain") or (r.get("isMeta") and not peer) or r.get("type") not in ("user", "assistant"):
248
+ continue # isMeta: notes the app injects, not typed by the user (a peer session's message is kept as a task)
249
+ content = (r.get("message") or {}).get("content")
250
+ if r["type"] == "user" and isinstance(content, list) and any(
251
+ isinstance(b, dict) and b.get("type") == "tool_result" for b in content): # fmt: skip
252
+ continue
253
+ role = "user" if r["type"] == "user" else "assistant"
254
+ agent = agent_origin(r) if role == "user" else None
255
+ text = clean(agent["body"] if agent and agent["body"] else _text(content))
256
+ anchor = role == "user" and not agent and is_short(text)
257
+ if text.startswith("This session is being continued from a previous"):
258
+ after_summary = True
259
+ continue
260
+ if (not anchor and (len(text) < 12 or SERVICE.match(text))) or text.startswith("Caveat: The messages below"):
261
+ continue
262
+ uid = r.get("uuid") or hashlib.sha1(f"{path.stem}|{r.get('timestamp')}|{text[:200]}".encode()).hexdigest()
263
+ yield {"id": uid, "session": r.get("sessionId") or path.stem, "role": role, "ts": r.get("timestamp", ""),
264
+ "text": text, "source": "transcript", "after_summary": after_summary and role == "user",
265
+ "pasted": pasted_blocks(_text(content)) if role == "user" and not agent else "", "title": title,
266
+ "ask": _ask(content) if role == "assistant" else "",
267
+ "agent": {k: agent[k] for k in ("kind", "parent")} if agent else None} # fmt: skip
268
+ after_summary = False
269
+
270
+
271
+ def dedupe(turns_: list[dict]) -> list[dict]:
272
+ """Drop turns repeated verbatim (resumed sessions) and, in the user's turns, lines already said earlier (pastes of
273
+ earlier text). The assistant's lines are kept: a final report restates what was said along the way, and cutting
274
+ those lines would cut the report."""
275
+ seen_turn, seen_line, out = set(), set(), []
276
+ for t in sorted(turns_, key=lambda t: (t["ts"], t["id"])):
277
+ # a short confirmation ("да") repeats verbatim but each one is its own event
278
+ k = (t["role"], t["text"]) if not (t["role"] == "user" and is_short(t["text"])) else (t["id"],)
279
+ if k in seen_turn:
280
+ continue
281
+ seen_turn.add(k)
282
+ keep = []
283
+ for ln in t["text"].splitlines():
284
+ if t["role"] != "user":
285
+ keep.append(ln)
286
+ continue
287
+ norm = re.sub(r"\W+", " ", ln).strip().lower()
288
+ if len(norm) >= 40 and norm in seen_line:
289
+ continue
290
+ if len(norm) >= 40:
291
+ seen_line.add(norm)
292
+ keep.append(ln)
293
+ text = "\n".join(keep).strip()
294
+ if len(text) >= 12 or (t["role"] == "user" and is_short(text)):
295
+ out.append(t | {"text": text})
296
+ return out
297
+
298
+
299
+ def link_parents(ts: list[dict], files: list[Path]) -> list[dict]:
300
+ """An agent task's parent: the transcript that sent its text (start_session / SendMessage), else `origin.from`."""
301
+ sent = [(s, _key(t, 120)) for f in files for s, t in launches(f)]
302
+ for t in ts:
303
+ a = t.get("agent")
304
+ if a and a["kind"] != "host":
305
+ k = _key(t["text"], None) # a brief = the parent's background + its prompt: the prompt is inside
306
+ hit = next((s for s, sk in sent if len(sk) >= 40 and sk in k and s != t["session"]), "")
307
+ a["parent"] = hit or a["parent"]
308
+ return ts
309
+
310
+
311
+ def project_turns(project_dir: Path) -> list[dict]:
312
+ files = sorted(project_dir.glob("*.jsonl"))
313
+ return link_parents(dedupe([t for p in files for t in turns(p)]), files)
314
+
315
+
316
+ if __name__ == "__main__":
317
+ ts = project_turns(Path(sys.argv[1]))
318
+ by: dict = {}
319
+ for t in ts:
320
+ by[t["role"]] = by.get(t["role"], 0) + 1
321
+ print(len(ts), "turns", by, "chars", sum(len(t["text"]) for t in ts))
322
+ if ts:
323
+ print("from", ts[0]["ts"], "to", ts[-1]["ts"])
@@ -0,0 +1,116 @@
1
+ """Reader for a claude.ai data export (Settings -> Privacy -> Export data): a .zip with `conversations.json`
2
+ (and `projects.json`, `users.json`). ARCHITECTURE_V2.md §3.15: import = replaying turns in order with their original
3
+ times through the normal append path; the privacy scrub runs before storage, as for any turn.
4
+
5
+ Only what people wrote is kept: the user's messages and the assistant's visible text. Thinking, tool calls and tool
6
+ results, attachments' extracted text and uploaded files are skipped (counted in the report, without values).
7
+
8
+ The export holds every chat of the account, most of them unrelated to a project: `select()` filters conversations by
9
+ a regex over the title and the first messages, by claude.ai project name, by date, or by explicit ids; `--list` in the
10
+ CLI shows titles first so the user chooses. Everything stays local.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import hashlib
16
+ import json
17
+ import re
18
+ import zipfile
19
+ from pathlib import Path
20
+
21
+ from cotrail.cc_transcripts import SERVICE, clean, is_short
22
+
23
+
24
+ def load(path: str | Path) -> tuple[list[dict], dict[str, str]]:
25
+ """(conversations, project uuid -> name) from the export .zip, its unpacked folder, or conversations.json."""
26
+ p = Path(path)
27
+ if p.is_dir():
28
+ conv = json.loads((p / "conversations.json").read_text("utf-8"))
29
+ proj = json.loads((p / "projects.json").read_text("utf-8")) if (p / "projects.json").exists() else []
30
+ elif zipfile.is_zipfile(p):
31
+ with zipfile.ZipFile(p) as z:
32
+ names = {Path(n).name: n for n in z.namelist()}
33
+ conv = json.loads(z.read(names["conversations.json"]).decode("utf-8"))
34
+ proj = json.loads(z.read(names["projects.json"]).decode("utf-8")) if "projects.json" in names else []
35
+ else:
36
+ conv, proj = json.loads(p.read_text("utf-8")), []
37
+ return conv, {x.get("uuid", ""): x.get("name", "") for x in proj if isinstance(x, dict)}
38
+
39
+
40
+ def _project_of(c: dict) -> str:
41
+ pr = c.get("project")
42
+ return c.get("project_uuid") or (pr.get("uuid", "") if isinstance(pr, dict) else "") or ""
43
+
44
+
45
+ def _text(msg: dict, skipped: dict) -> str:
46
+ """Visible text of a message. New exports: `content` blocks; older ones: `text` only."""
47
+ blocks = msg.get("content")
48
+ if isinstance(blocks, list) and blocks:
49
+ parts = []
50
+ for b in blocks:
51
+ if not isinstance(b, dict):
52
+ continue
53
+ kind = b.get("type", "")
54
+ if kind == "text":
55
+ parts.append(b.get("text") or "")
56
+ else: # thinking, tool_use, tool_result, ...
57
+ skipped[kind or "other"] = skipped.get(kind or "other", 0) + 1
58
+ text = "\n".join(parts)
59
+ else:
60
+ text = msg.get("text") or ""
61
+ n_att = len(msg.get("attachments") or []) + len(msg.get("files") or [])
62
+ if n_att:
63
+ skipped["attachments"] = skipped.get("attachments", 0) + n_att
64
+ return text
65
+
66
+
67
+ def summary(conv: list[dict], projects: dict[str, str]) -> list[dict]:
68
+ """One row per conversation for choosing what to import: id, date, messages, title, claude.ai project."""
69
+ rows = []
70
+ for c in conv:
71
+ msgs = c.get("chat_messages") or []
72
+ rows.append({"id": c.get("uuid", ""), "date": (c.get("created_at") or "")[:10], "messages": len(msgs),
73
+ "title": c.get("name") or "(untitled)", "project": projects.get(_project_of(c), "")}) # fmt: skip
74
+ return sorted(rows, key=lambda r: r["date"])
75
+
76
+
77
+ def select(conv: list[dict], projects: dict[str, str], match: str | None = None, project: str | None = None,
78
+ since: str | None = None, ids: list[str] | None = None) -> list[dict]: # fmt: skip
79
+ """Conversations to import. `match` - regex over the title and the first 3 messages; `project` - claude.ai
80
+ project name (substring, case-insensitive); `since` - YYYY-MM-DD; `ids` - conversation uuids (prefixes)."""
81
+ rx = re.compile(match, re.I) if match else None
82
+ out = []
83
+ for c in conv:
84
+ if ids and not any((c.get("uuid") or "").startswith(i) for i in ids):
85
+ continue
86
+ if since and (c.get("created_at") or "")[:10] < since:
87
+ continue
88
+ if project and project.lower() not in projects.get(_project_of(c), "").lower():
89
+ continue
90
+ if rx:
91
+ head = " ".join([c.get("name") or ""] + [_text(m, {}) for m in (c.get("chat_messages") or [])[:3]])
92
+ if not rx.search(head):
93
+ continue
94
+ out.append(c)
95
+ return out
96
+
97
+
98
+ def turns(conv: list[dict]) -> tuple[list[dict], dict]:
99
+ """Turns in the importer's format (id, session, role, ts, text, source) and a report of what was skipped."""
100
+ out, skipped = [], {}
101
+ for c in conv:
102
+ cid = c.get("uuid") or hashlib.sha1((c.get("name") or "").encode()).hexdigest()
103
+ for m in c.get("chat_messages") or []:
104
+ sender = m.get("sender")
105
+ if sender not in ("human", "assistant"):
106
+ skipped["other_sender"] = skipped.get("other_sender", 0) + 1
107
+ continue
108
+ text = clean(_text(m, skipped))
109
+ if not (sender == "human" and is_short(text)) and (len(text) < 12 or SERVICE.match(text)):
110
+ skipped["short_or_service"] = skipped.get("short_or_service", 0) + 1
111
+ continue
112
+ ts = m.get("created_at") or c.get("created_at") or ""
113
+ mid = m.get("uuid") or hashlib.sha1(f"{cid}|{ts}|{text[:200]}".encode()).hexdigest()
114
+ out.append({"id": mid, "session": f"claude.ai:{cid}", "role": "user" if sender == "human" else "assistant",
115
+ "ts": ts, "text": text, "source": "claude.ai", "title": (c.get("name") or "")[:120]}) # fmt: skip
116
+ return out, skipped