Repository navigation
feat(cli): add Claude Code and Codex session parsing and --discover to ingest-transcript #2099
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
cc5b7a3
6d4e3b4
9249bc3
db04f2d
7084797
0e67ef9
95304b3
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,382 @@ | ||
| """Read-only discovery and parsing of local Claude Code and Codex session transcripts.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| import re | ||
| from dataclasses import dataclass | ||
| from pathlib import Path | ||
| from typing import Any | ||
|
|
||
| # Client-side secret redaction matching integrations/claude-code-plugin/lib/loom-client.mjs. | ||
| _PRIVATE_KEY_RE = re.compile( | ||
| r"-----BEGIN [A-Z ]{0,40}PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)" | ||
| ) | ||
| _TOKEN_SHAPES_RE = re.compile( | ||
| r"\b(?:(?:AKIA|ASIA)[0-9A-Z]{16}|(?:ghp|gho|ghs|ghu|ghr)_[A-Za-z0-9]{20,}" | ||
| r"|github_pat_\w{20,}|xox[abeprs]-[A-Za-z0-9-]{10,}|sk-(?:ant|proj)-[\w-]{20,}" | ||
| r"|glpat-[\w-]{20,})\b", | ||
| re.ASCII, | ||
| ) | ||
| _SECRET_ASSIGNMENT_RE = re.compile( | ||
| r"""\b([\w.-]{0,64}?(?:password|passwd|secret|secret[_-]?key|token|api[_-]?key""" | ||
| r"""|access[_-]?key|private[_-]?key)\b["']?\s*[=:]\s*)("[^"]*"|'[^']*'|[^\s"'\\,;}]+)""", | ||
| re.IGNORECASE | re.ASCII, | ||
| ) | ||
| _JWT_RE = re.compile(r"\beyJ[\w-]{0,512}\.[\w-]{1,8192}\.[\w-]{0,1024}", re.ASCII) | ||
| _BEARER_RE = re.compile(r"\b(Bearer)\s+[^\s\"'\\]+", re.IGNORECASE | re.ASCII) | ||
| _BASIC_AUTH_RE = re.compile( | ||
| r"(\bAuthorization[\"']?\s*[:=]\s*[\"']?Basic)\s+[^\s\"'\\]+", | ||
| re.IGNORECASE | re.ASCII, | ||
| ) | ||
| _URL_CREDENTIALS_RE = re.compile( | ||
| r"\b([a-z][a-z0-9+.-]{0,31}://)[^\s/@\"']{1,256}:[^\s/@\"']{0,256}@", | ||
| re.IGNORECASE | re.ASCII, | ||
| ) | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def _quoted_redaction(match: re.Match[str]) -> str: | ||
| name, value = match.group(1), match.group(2) | ||
| q = value[0] if value and value[0] in ('"', "'") else "" | ||
| return f"{name}{q}[redacted]{q}" | ||
|
|
||
|
|
||
| def redact_secrets(text: str, token: str = "") -> str: | ||
| """Redact common credentials, tokens, JWTs, and the caller's own token.""" | ||
| s = str(text or "") | ||
| if token and len(token) >= 8: | ||
| s = s.replace(token, "[redacted]") | ||
| s = _PRIVATE_KEY_RE.sub("[redacted private key]", s) | ||
| s = _TOKEN_SHAPES_RE.sub("[redacted]", s) | ||
| s = _SECRET_ASSIGNMENT_RE.sub(_quoted_redaction, s) | ||
| s = _JWT_RE.sub("[redacted]", s) | ||
| s = _BEARER_RE.sub(r"\1 [redacted]", s) | ||
| s = _BASIC_AUTH_RE.sub(r"\1 [redacted]", s) | ||
| return _URL_CREDENTIALS_RE.sub(r"\1[redacted]@", s) | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. URL redaction eats ordinary pathsMedium Severity
Reviewed by Cursor Bugbot for commit 7084797. Configure here. |
||
|
|
||
|
|
||
| # Injected client wrapper blocks that may precede or wrap user prompts. | ||
| _INJECTED_TAG_NAMES = ( | ||
| "system-reminder|environment_context|command-name|command-message|" | ||
| "command-args|local-command-stdout|local-command-caveat|user_instructions|" | ||
| "turn_aborted|ide_opened_file|ide_selection|ide_context|task-notification|" | ||
| "user_shell_command|subagent_notification" | ||
| ) | ||
| _INJECTED_TAG_RE = re.compile( | ||
| rf"<({_INJECTED_TAG_NAMES})\b[^>]*>[\s\S]*?</\1>", | ||
| re.IGNORECASE, | ||
| ) | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def _strip_injected_tags(text: str) -> str: | ||
| return _INJECTED_TAG_RE.sub("", text).strip() | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SessionTurn: | ||
| role: str | ||
| content: str | ||
| timestamp: str = "" | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class SessionInfo: | ||
| source: str # "claude" or "codex" | ||
| session_id: str | ||
| project: str | ||
| path: Path | ||
| size_bytes: int | ||
| first_ts: str | ||
| last_ts: str | ||
| turns: list[SessionTurn] | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class ProjectSummary: | ||
| project: str | ||
| sources: tuple[str, ...] | ||
| session_count: int | ||
| earliest_date: str | ||
| latest_date: str | ||
| total_bytes: int | ||
|
|
||
|
|
||
| def _extract_claude_text(content: Any) -> str: | ||
| if isinstance(content, str): | ||
| return content.strip() | ||
| if isinstance(content, list): | ||
| parts: list[str] = [] | ||
| for block in content: | ||
| if isinstance(block, str): | ||
| parts.append(block) | ||
| elif isinstance(block, dict) and block.get("type") == "text": | ||
| text = block.get("text") | ||
| if isinstance(text, str): | ||
| parts.append(text) | ||
| return "\n".join(parts).strip() | ||
| return "" | ||
|
|
||
|
|
||
| def _extract_codex_text(content: Any) -> str: | ||
| if isinstance(content, str): | ||
| return content.strip() | ||
| if isinstance(content, list): | ||
| parts = [ | ||
| item["text"] | ||
| for item in content | ||
| if isinstance(item, dict) and isinstance(item.get("text"), str) | ||
| ] | ||
| return "\n".join(parts).strip() | ||
| return "" | ||
|
|
||
|
|
||
| def _has_tool_result(content: Any) -> bool: | ||
| return isinstance(content, list) and any( | ||
| isinstance(b, dict) and b.get("type") == "tool_result" for b in content | ||
| ) | ||
|
|
||
|
|
||
| def _update_ts_bounds(first_ts: str, last_ts: str, ts: str) -> tuple[str, str]: | ||
| if not ts: | ||
| return first_ts, last_ts | ||
| if not first_ts or ts < first_ts: | ||
| first_ts = ts | ||
| if not last_ts or ts > last_ts: | ||
| last_ts = ts | ||
| return first_ts, last_ts | ||
|
|
||
|
|
||
| def _read_jsonl_records(path: Path) -> list[dict[str, Any]]: | ||
| records: list[dict[str, Any]] = [] | ||
| with path.open("r", encoding="utf-8", errors="replace") as fh: | ||
| for line in fh: | ||
| stripped = line.strip() | ||
| if not stripped: | ||
| continue | ||
| try: | ||
| obj = json.loads(stripped) | ||
| except json.JSONDecodeError: | ||
| continue | ||
| if isinstance(obj, dict): | ||
| records.append(obj) | ||
| return records | ||
|
|
||
|
|
||
| def _active_claude_branch(records: list[dict[str, Any]]) -> list[dict[str, Any]]: | ||
| """Follow parentUuid from the last non-sidechain record, dropping rewound branches.""" | ||
| by_uuid: dict[str, dict[str, Any]] = {} | ||
| tail_uuid = "" | ||
| for rec in records: | ||
| if rec.get("isSidechain"): | ||
| continue | ||
| uid = rec.get("uuid") | ||
| if isinstance(uid, str) and uid.strip(): | ||
| uid = uid.strip() | ||
| by_uuid[uid] = rec | ||
| tail_uuid = uid | ||
| if not by_uuid or not tail_uuid: | ||
| return records | ||
|
|
||
| chain: list[dict[str, Any]] = [] | ||
| seen: set[str] = set() | ||
| cur: str | None = tail_uuid | ||
| while cur and cur not in seen and cur in by_uuid: | ||
| seen.add(cur) | ||
| rec = by_uuid[cur] | ||
| chain.append(rec) | ||
| parent = rec.get("parentUuid") or rec.get("logicalParentUuid") | ||
| cur = parent.strip() if isinstance(parent, str) and parent.strip() else None | ||
| chain.reverse() | ||
| return chain | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
|
|
||
| def parse_claude_jsonl(path: Path) -> SessionInfo | None: | ||
| """Parse a Claude Code session ``.jsonl`` file without modifying it.""" | ||
| records = _read_jsonl_records(path) | ||
| turns: list[SessionTurn] = [] | ||
| session_id = "" | ||
| project = "" | ||
| first_ts = "" | ||
| last_ts = "" | ||
|
|
||
| for rec in records: | ||
| if not session_id and isinstance(rec.get("sessionId"), str): | ||
| session_id = rec["sessionId"].strip() | ||
| if not project and isinstance(rec.get("cwd"), str): | ||
| project = rec["cwd"].strip() | ||
|
|
||
| for rec in _active_claude_branch(records): | ||
| ts = str(rec.get("timestamp") or "").strip() | ||
|
|
||
| if rec.get("isSidechain") or rec.get("isMeta") or rec.get("isCompactSummary"): | ||
| continue | ||
| msg = rec.get("message") | ||
| if not isinstance(msg, dict): | ||
| continue | ||
|
|
||
| rec_type = rec.get("type") | ||
| content = msg.get("content") | ||
| if rec_type == "user": | ||
| if _has_tool_result(content): | ||
| continue | ||
| text = _strip_injected_tags(_extract_claude_text(content)) | ||
| if not text: | ||
| continue | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
| turns.append(SessionTurn(role="user", content=text, timestamp=ts)) | ||
| first_ts, last_ts = _update_ts_bounds(first_ts, last_ts, ts) | ||
| elif rec_type == "assistant": | ||
| text = _extract_claude_text(content) | ||
| if not text: | ||
| continue | ||
| turns.append(SessionTurn(role="assistant", content=text, timestamp=ts)) | ||
| first_ts, last_ts = _update_ts_bounds(first_ts, last_ts, ts) | ||
|
cursor[bot] marked this conversation as resolved.
Resolved
|
||
|
|
||
| if not turns: | ||
| return None | ||
| return SessionInfo( | ||
| source="claude", | ||
| session_id=session_id or path.stem, | ||
| project=project or path.parent.name, | ||
| path=path, | ||
| size_bytes=path.stat().st_size, | ||
| first_ts=first_ts, | ||
| last_ts=last_ts, | ||
| turns=turns, | ||
| ) | ||
|
|
||
|
|
||
| def parse_codex_jsonl(path: Path) -> SessionInfo | None: | ||
| """Parse a Codex rollout ``.jsonl`` file without modifying it.""" | ||
| records = _read_jsonl_records(path) | ||
| turns: list[SessionTurn] = [] | ||
| session_id = "" | ||
| project = "" | ||
| first_ts = "" | ||
| last_ts = "" | ||
|
|
||
| for rec in records: | ||
| ts = str(rec.get("timestamp") or "").strip() | ||
| rec_type = rec.get("type") | ||
| payload = rec.get("payload") | ||
| if not isinstance(payload, dict): | ||
| continue | ||
|
|
||
| if rec_type == "session_meta": | ||
| if not session_id and isinstance(payload.get("id"), str): | ||
| session_id = payload["id"].strip() | ||
| if not project and isinstance(payload.get("cwd"), str): | ||
| project = payload["cwd"].strip() | ||
| meta_ts = str(payload.get("timestamp") or ts).strip() | ||
| first_ts, last_ts = _update_ts_bounds(first_ts, last_ts, meta_ts) | ||
| continue | ||
|
|
||
| if rec_type == "response_item" and payload.get("type") == "message": | ||
| role = str(payload.get("role") or "").strip().lower() | ||
| if role not in {"user", "assistant"}: | ||
| continue | ||
| text = _extract_codex_text(payload.get("content")) | ||
| if role == "user": | ||
| text = _strip_injected_tags(text) | ||
| if not text: | ||
| continue | ||
| turns.append(SessionTurn(role=role, content=text, timestamp=ts)) | ||
| first_ts, last_ts = _update_ts_bounds(first_ts, last_ts, ts) | ||
|
|
||
| if not turns: | ||
| return None | ||
| return SessionInfo( | ||
| source="codex", | ||
| session_id=session_id or path.stem, | ||
| project=project or "codex", | ||
| path=path, | ||
| size_bytes=path.stat().st_size, | ||
| first_ts=first_ts, | ||
| last_ts=last_ts, | ||
| turns=turns, | ||
| ) | ||
|
|
||
|
|
||
| def parse_jsonl_session(path: Path) -> SessionInfo | None: | ||
| """Auto-detect Claude Code vs Codex JSONL format and parse the session.""" | ||
| for rec in _read_jsonl_records(path)[:20]: | ||
| rec_type = rec.get("type") | ||
| if rec_type in {"session_meta", "response_item"} and isinstance(rec.get("payload"), dict): | ||
| return parse_codex_jsonl(path) | ||
| if rec_type in {"user", "assistant"} and isinstance(rec.get("message"), dict): | ||
| return parse_claude_jsonl(path) | ||
| return parse_claude_jsonl(path) or parse_codex_jsonl(path) | ||
|
|
||
|
|
||
| def _accumulate_project(grouped: dict[str, dict[str, Any]], sess: SessionInfo) -> None: | ||
| acc = grouped.setdefault( | ||
| sess.project, | ||
| {"sources": set(), "count": 0, "earliest": "", "latest": "", "bytes": 0}, | ||
| ) | ||
| acc["sources"].add(sess.source) | ||
| acc["count"] += 1 | ||
| acc["bytes"] += sess.size_bytes | ||
| for ts in (sess.first_ts, sess.last_ts): | ||
| if len(ts) < 10: | ||
| continue | ||
| day = ts[:10] | ||
| if not acc["earliest"] or day < acc["earliest"]: | ||
| acc["earliest"] = day | ||
| if not acc["latest"] or day > acc["latest"]: | ||
| acc["latest"] = day | ||
|
|
||
|
|
||
| def discover_sessions( | ||
| claude_dir: Path | None = None, codex_dir: Path | None = None | ||
| ) -> list[ProjectSummary]: | ||
| """Scan local Claude Code and Codex directories and group sessions by project.""" | ||
| c_dir = claude_dir if claude_dir is not None else Path.home() / ".claude" / "projects" | ||
| x_dir = codex_dir if codex_dir is not None else Path.home() / ".codex" / "sessions" | ||
|
|
||
| grouped: dict[str, dict[str, Any]] = {} | ||
| if c_dir.is_dir(): | ||
| for path in sorted(c_dir.glob("*/*.jsonl")): | ||
| try: | ||
| parsed = parse_claude_jsonl(path) | ||
| except OSError: | ||
| continue | ||
| if parsed is not None: | ||
| _accumulate_project(grouped, parsed) | ||
|
|
||
| if x_dir.is_dir(): | ||
| for path in sorted(x_dir.rglob("*.jsonl")): | ||
| try: | ||
| parsed = parse_codex_jsonl(path) | ||
| except OSError: | ||
| continue | ||
| if parsed is not None: | ||
| _accumulate_project(grouped, parsed) | ||
|
|
||
| summaries = [ | ||
| ProjectSummary( | ||
| project=project, | ||
| sources=tuple(sorted(acc["sources"])), | ||
| session_count=acc["count"], | ||
| earliest_date=acc["earliest"] or "unknown", | ||
| latest_date=acc["latest"] or "unknown", | ||
| total_bytes=acc["bytes"], | ||
| ) | ||
| for project, acc in grouped.items() | ||
| ] | ||
| summaries.sort( | ||
| key=lambda s: ( | ||
| "" if s.latest_date == "unknown" else s.latest_date, | ||
| s.session_count, | ||
| s.project, | ||
| ), | ||
| reverse=True, | ||
| ) | ||
| return summaries | ||
|
|
||
|
|
||
| def format_bytes(num_bytes: int) -> str: | ||
| """Format a byte count concisely for CLI output.""" | ||
| if num_bytes < 1024: | ||
| return f"{num_bytes} B" | ||
| if num_bytes < 1024 * 1024: | ||
| return f"{num_bytes / 1024:.1f} KiB" | ||
| return f"{num_bytes / (1024 * 1024):.1f} MiB" | ||


There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
P1 — With re.ASCII on the whole expression, Bearer followed by a non-breaking space and a credential no longer matches. The assignment and Basic auth patterns have the same regression. Scope ASCII to the boundary with (?a:\b), keep Unicode whitespace matching, and exercise the outgoing request with a non-breaking space.