Skip to content
2 changes: 1 addition & 1 deletion docs/reference/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ python scripts/codegen/docs_reference.py
| `loom install` | Wire Loom into a local AI client's config. | `--client`, `--server-url`, `--token`, `--name`, `--toolset`, `--dry-run`, `--force` |
| `loom demo` | The first five minutes: ingest this repo's AGENTS.md (or --file) into the knowledge plane the way `make ingest` does, ask it a question, and print the answer with its evidence rows. | `--file`, `--question`, `--tags`, `--base-url`, `--token`, `--org`, `--namespace`, `--root`, `--search-only` |
| `loom init` | Create an identity on a Loom server. | `--agent`, `--server-url`, `--org`, `--purpose`, `--ttl-days`, `--token-path`, `--config-path`, `--no-files`, `--json` |
| `loom ingest-transcript` | Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. | `--server-url`, `--token`, `--org`, `--namespace`, `--agent`, `--thread-id`, `--file`, `--dry-run` |
| `loom ingest-transcript` | Pipe a chat-history file (markdown / JSON) into Loom's conversation table as one thread. | `--server-url`, `--token`, `--org`, `--namespace`, `--agent`, `--thread-id`, `--file`, `--discover`, `--dry-run` |
| `loom memory-search` | Run a memory.search from the shell. | `--server-url`, `--token`, `--org`, `--namespace`, `--agent`, `--user-id`, `--query`, `--top-k`, `--search-mode`, `--json-agent` |
| `loom set-host` | Designate the Loom host(s) for this deployment. | `<emails>`, `--env-file`, `--append`, `--dry-run` |
| `loom login` | Sign in to a Loom server on any browser with a one-time code. | |
Expand Down
382 changes: 382 additions & 0 deletions server/cli/_transcripts.py
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)

Copy link
Copy Markdown
Member

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.

_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,
)
Comment thread
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

URL redaction eats ordinary paths

Medium Severity

_URL_CREDENTIALS_RE is documented as matching the client redactor, but its userinfo class is [^\s/@\"'] and therefore allows /. A normal URL whose path contains : and a later @ is treated as credentials and rewritten to scheme://[redacted]@... before the turn is stored.

Fix in Cursor Fix in Web

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,
)
Comment thread
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
Comment thread
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
Comment thread
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)
Comment thread
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"
Loading
Loading