diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 15c1e62101..c71e58383c 100644 --- a/docs/reference/cli.md +++ b/docs/reference/cli.md @@ -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. | ``, `--env-file`, `--append`, `--dry-run` | | `loom login` | Sign in to a Loom server on any browser with a one-time code. | | diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py new file mode 100644 index 0000000000..928a5f720a --- /dev/null +++ b/server/cli/_transcripts.py @@ -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, +) + + +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) + + +# 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]*?", + re.IGNORECASE, +) + + +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 + + +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 + 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) + + 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" diff --git a/server/cli/shell.py b/server/cli/shell.py index 0e2263b02f..dd227b2d4e 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -20,6 +20,12 @@ resolve_token, ) from server.cli._paths import write_private +from server.cli._transcripts import ( + discover_sessions, + format_bytes, + parse_jsonl_session, + redact_secrets, +) def _cmd_memory_search(args: argparse.Namespace) -> int: @@ -151,7 +157,8 @@ def _http_error_line(e: urllib.error.HTTPError) -> str: def _cmd_ingest_transcript(args: argparse.Namespace) -> int: """Read a chat history file, POST each turn to conversation.append. - Two formats: + Three formats: + - .jsonl: Claude Code or Codex session transcript. - .json: an array of {role, content} objects. - .md (default): markdown with `# user` / `# assistant` H1 headers; content is everything between two headers. @@ -161,6 +168,24 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: import time import urllib.request + if getattr(args, "discover", False): + summaries = discover_sessions() + if not summaries: + print("No Claude Code or Codex sessions found.") + return 0 + for s in summaries: + srcs = ", ".join(s.sources) + span = ( + s.earliest_date + if s.earliest_date == s.latest_date + else f"{s.earliest_date}..{s.latest_date}" + ) + print( + f"{s.project} [{srcs}] {s.session_count} session(s) " + f"{span} {format_bytes(s.total_bytes)}" + ) + return 0 + token, source = resolve_token(args.token) if refused_for_agent(source): return 2 @@ -173,14 +198,28 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: ) return 2 + if not getattr(args, "namespace", None): + print("ERROR: --namespace is required unless --discover is set", file=sys.stderr) + return 2 + if not getattr(args, "file", None): + print("ERROR: --file is required unless --discover is set", file=sys.stderr) + return 2 + src = Path(args.file).expanduser().resolve() if not src.is_file(): print(f"ERROR: file not found: {src}", file=sys.stderr) return 3 - raw = src.read_text(encoding="utf-8") turns: list[dict[str, str]] = [] - if src.suffix.lower() == ".json": + suffix = src.suffix.lower() + if suffix == ".jsonl": + session = parse_jsonl_session(src) + if session is not None: + turns = [ + {"role": t.role, "content": redact_secrets(t.content, token)} for t in session.turns + ] + elif suffix == ".json": + raw = src.read_text(encoding="utf-8") try: parsed = _json.loads(raw) except _json.JSONDecodeError as e: @@ -198,6 +237,7 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: return 4 turns.append({"role": str(item["role"]), "content": str(item["content"])}) else: + raw = src.read_text(encoding="utf-8") # Markdown H1-split, permissive on case + leading whitespace. header_re = re.compile(r"^\s*#\s*(user|assistant|system|tool)\s*$", re.IGNORECASE) current_role: str | None = None @@ -221,9 +261,14 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: turns = [t for t in turns if t["content"].strip()] if not turns: + expected = ( + "Expected a Claude Code or Codex JSONL session file." + if suffix == ".jsonl" + else "Expected JSON array of {role, content} or markdown with " + "`# user` / `# assistant` headers." + ) print( - f"ERROR: no valid turns parsed from {src}. Expected JSON array " - f"of {{role, content}} or markdown with `# user` / `# assistant` headers.", + f"ERROR: no valid turns parsed from {src}. {expected}", file=sys.stderr, ) return 5 @@ -420,8 +465,8 @@ def _add_shell_client_parsers(sub: Any) -> None: p_ingest.add_argument("--org", default="", help="default: the token's org, else dev") p_ingest.add_argument( "--namespace", - required=True, - help="Namespace to ingest the thread into.", + default=None, + help="Namespace to ingest the thread into (required unless --discover).", ) p_ingest.add_argument( "--agent", @@ -436,10 +481,15 @@ def _add_shell_client_parsers(sub: Any) -> None: ) p_ingest.add_argument( "--file", - required=True, - help="Path to the transcript file. Format: markdown with " - "alternating `# user` / `# assistant` H1 sections, OR JSON " - "array of {role, content} objects.", + default=None, + help="Path to the transcript file. Format: Claude Code or Codex .jsonl, " + "markdown with `# user` / `# assistant` H1 sections, OR JSON array of " + "{role, content} objects.", + ) + p_ingest.add_argument( + "--discover", + action="store_true", + help="List local Claude Code and Codex sessions by project without writing anything.", ) p_ingest.add_argument( "--dry-run", diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index d5c7820eac..c428942258 100644 --- a/tests/unit/snapshots/cli_help.json +++ b/tests/unit/snapshots/cli_help.json @@ -568,8 +568,8 @@ "options: -h, --help show this help message and exit --agent NAME Sign this agent up (becomes agent-). --server-url SERVER_URL Loom server URL (default: LOOM_BASE_URL, then ~/.loom/config.json url, else http://localhost:7777). --org ORG Org (default: the server's self-signup org). --purpose PURPOSE One line stored as the namespace description. --ttl-days TTL_DAYS Token lifetime (default 365). --token-path TOKEN_PATH Where to save the token (default ~/.loom/token). --config-path CONFIG_PATH Where to save url/namespace/org (default ~/.loom/config.json). --no-files Print the token instead of saving files (CI secrets). --json Print the sign-up result (minus the token) as JSON." ], "loom ingest-transcript": [ - "usage: loom ingest-transcript [-h] [--server-url SERVER_URL] [--token TOKEN] [--org ORG] --namespace NAMESPACE [--agent AGENT] [--thread-id THREAD_ID] --file FILE [--dry-run]", - "options: -h, --help show this help message and exit --server-url SERVER_URL Loom server URL (default LOOM_BASE_URL, else http://localhost:7777). --token TOKEN JWT to authenticate with. Defaults to LOOM_API_KEY, then ~/.loom/token. --org ORG default: the token's org, else dev --namespace NAMESPACE Namespace to ingest the thread into. --agent AGENT Agent identifier on the conversation rows (default ingest-cli). --thread-id THREAD_ID Thread to append to (default: a hash of the file's resolved path, so re- ingesting an edited file adds only its new turns). --file FILE Path to the transcript file. Format: markdown with alternating `# user` / `# assistant` H1 sections, OR JSON array of {role, content} objects. --dry-run Parse and print the turn count and each turn's size in bytes (never its text) without writing anything." + "usage: loom ingest-transcript [-h] [--server-url SERVER_URL] [--token TOKEN] [--org ORG] [--namespace NAMESPACE] [--agent AGENT] [--thread-id THREAD_ID] [--file FILE] [--discover] [--dry-run]", + "options: -h, --help show this help message and exit --server-url SERVER_URL Loom server URL (default LOOM_BASE_URL, else http://localhost:7777). --token TOKEN JWT to authenticate with. Defaults to LOOM_API_KEY, then ~/.loom/token. --org ORG default: the token's org, else dev --namespace NAMESPACE Namespace to ingest the thread into (required unless --discover). --agent AGENT Agent identifier on the conversation rows (default ingest-cli). --thread-id THREAD_ID Thread to append to (default: a hash of the file's resolved path, so re- ingesting an edited file adds only its new turns). --file FILE Path to the transcript file. Format: Claude Code or Codex .jsonl, markdown with `# user` / `# assistant` H1 sections, OR JSON array of {role, content} objects. --discover List local Claude Code and Codex sessions by project without writing anything. --dry-run Parse and print the turn count and each turn's size in bytes (never its text) without writing anything." ], "loom memory-search": [ "usage: loom memory-search [-h] [--server-url SERVER_URL] [--token TOKEN] [--org ORG] --namespace NAMESPACE [--agent AGENT] [--user-id USER_ID] --query QUERY [--top-k TOP_K] [--search-mode SEARCH_MODE] [--json-agent]", diff --git a/tests/unit/snapshots/cli_tree.json b/tests/unit/snapshots/cli_tree.json index 6eda63b71c..64e3f3ea2c 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -16604,6 +16604,7 @@ "agent", "thread_id", "file", + "discover", "dry_run" ] } @@ -16682,8 +16683,8 @@ "choices": null, "nargs": null, "type": null, - "required": true, - "help": "Namespace to ingest the thread into.", + "required": false, + "help": "Namespace to ingest the thread into (required unless --discover).", "metavar": null }, { @@ -16727,8 +16728,23 @@ "choices": null, "nargs": null, "type": null, - "required": true, - "help": "Path to the transcript file. Format: markdown with alternating `# user` / `# assistant` H1 sections, OR JSON array of {role, content} objects.", + "required": false, + "help": "Path to the transcript file. Format: Claude Code or Codex .jsonl, markdown with `# user` / `# assistant` H1 sections, OR JSON array of {role, content} objects.", + "metavar": null + }, + { + "option_strings": [ + "--discover" + ], + "dest": "discover", + "action": "_StoreTrueAction", + "default": false, + "const": true, + "choices": null, + "nargs": 0, + "type": null, + "required": false, + "help": "List local Claude Code and Codex sessions by project without writing anything.", "metavar": null }, { diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 272eac8140..820c0deecb 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -173,3 +173,401 @@ def _urlopen(req: Any, timeout: float = 0) -> Any: _write(src, [("user", "hi")]) assert shell._cmd_ingest_transcript(_args(src)) == 6 assert capsys.readouterr().err.strip() == "ERROR: turn 0 failed: HTTP 502 Bad Gateway" + + +def _write_jsonl(path: Path, records: list[dict[str, Any]]) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text("\n".join(json.dumps(r) for r in records) + "\n", encoding="utf-8") + + +def test_claude_jsonl_parsing_and_dry_run( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + def _no_call(*a: Any, **k: Any) -> Any: + raise AssertionError("dry run wrote") + + monkeypatch.setattr(urllib.request, "urlopen", _no_call) + src = tmp_path / "sess.jsonl" + _write_jsonl( + src, + [ + { + "type": "user", + "sessionId": "claude-s1", + "cwd": "/tmp/my-app", + "timestamp": "2026-11-01T10:00:00Z", + "isMeta": True, + "message": {"role": "user", "content": "caveat"}, + }, + { + "type": "user", + "sessionId": "claude-s1", + "cwd": "/tmp/my-app", + "timestamp": "2026-11-01T10:00:01Z", + "message": {"role": "user", "content": "/help"}, + }, + { + "type": "user", + "sessionId": "claude-s1", + "cwd": "/tmp/my-app", + "timestamp": "2026-11-01T10:00:02Z", + "message": {"role": "user", "content": "how do we deploy?"}, + }, + { + "type": "assistant", + "sessionId": "claude-s1", + "cwd": "/tmp/my-app", + "timestamp": "2026-11-01T10:00:05Z", + "message": { + "role": "assistant", + "content": [ + {"type": "tool_use", "id": "t1", "name": "Read", "input": {}}, + {"type": "text", "text": "Run make deploy."}, + ], + }, + }, + { + "type": "user", + "sessionId": "claude-s1", + "cwd": "/tmp/my-app", + "timestamp": "2026-11-01T10:00:06Z", + "message": { + "role": "user", + "content": [{"type": "tool_result", "tool_use_id": "t1", "content": "ok"}], + }, + }, + { + "type": "user", + "sessionId": "claude-s1", + "isSidechain": True, + "timestamp": "2026-11-01T10:00:07Z", + "message": {"role": "user", "content": "subagent prompt"}, + }, + ], + ) + assert shell._cmd_ingest_transcript(_args(src, dry_run=True)) == 0 + out = capsys.readouterr().out + assert "would ingest 2 turns" in out + assert "how do we deploy?" not in out + + +def test_codex_jsonl_parsing_and_dry_run( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + def _no_call(*a: Any, **k: Any) -> Any: + raise AssertionError("dry run wrote") + + monkeypatch.setattr(urllib.request, "urlopen", _no_call) + src = tmp_path / "rollout-1.jsonl" + _write_jsonl( + src, + [ + { + "type": "session_meta", + "timestamp": "2026-11-02T09:00:00Z", + "payload": {"id": "codex-s1", "cwd": "/tmp/codex-proj"}, + }, + { + "type": "response_item", + "timestamp": "2026-11-02T09:00:01Z", + "payload": { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "...", + } + ], + }, + }, + { + "type": "response_item", + "timestamp": "2026-11-02T09:00:02Z", + "payload": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "fix the parser"}], + }, + }, + { + "type": "response_item", + "timestamp": "2026-11-02T09:00:04Z", + "payload": { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "Patched the parser."}], + }, + }, + ], + ) + assert shell._cmd_ingest_transcript(_args(src, dry_run=True)) == 0 + out = capsys.readouterr().out + assert "would ingest 2 turns" in out + assert "fix the parser" not in out + + +def test_discover_lists_claude_and_codex_sessions_by_project( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + def _no_call(*a: Any, **k: Any) -> Any: + raise AssertionError("discover must not call network") + + monkeypatch.setattr(urllib.request, "urlopen", _no_call) + monkeypatch.setenv("HOME", str(tmp_path)) + + claude_file = tmp_path / ".claude" / "projects" / "proj-a" / "s1.jsonl" + _write_jsonl( + claude_file, + [ + { + "type": "user", + "sessionId": "c1", + "cwd": "/work/alpha", + "timestamp": "2026-10-10T12:00:00Z", + "message": {"role": "user", "content": "hello"}, + } + ], + ) + codex_file = tmp_path / ".codex" / "sessions" / "2026" / "11" / "05" / "rollout.jsonl" + _write_jsonl( + codex_file, + [ + { + "type": "session_meta", + "timestamp": "2026-11-05T08:00:00Z", + "payload": {"id": "x1", "cwd": "/work/alpha"}, + }, + { + "type": "response_item", + "timestamp": "2026-11-05T08:01:00Z", + "payload": { + "type": "message", + "role": "user", + "content": [{"type": "input_text", "text": "world"}], + }, + }, + ], + ) + claude_before = claude_file.read_bytes() + codex_before = codex_file.read_bytes() + + ns = argparse.Namespace( + discover=True, + namespace=None, + file=None, + token=None, + server_url="http://x", + org="", + agent="ingest-cli", + thread_id=None, + dry_run=False, + ) + assert shell._cmd_ingest_transcript(ns) == 0 + out = capsys.readouterr().out + assert "/work/alpha" in out + assert "claude, codex" in out + assert "2 session(s)" in out + assert "2026-10-10..2026-11-05" in out + assert claude_file.read_bytes() == claude_before + assert codex_file.read_bytes() == codex_before + + +def test_injected_tags_stripped_without_dropping_real_prompts_or_xml_replies( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + def _no_call(*a: Any, **k: Any) -> Any: + raise AssertionError("dry run wrote") + + monkeypatch.setattr(urllib.request, "urlopen", _no_call) + src = tmp_path / "mixed.jsonl" + _write_jsonl( + src, + [ + { + "type": "session_meta", + "timestamp": "2026-11-03T10:00:00Z", + "payload": {"id": "mix-1", "cwd": "/tmp/p"}, + }, + { + "type": "response_item", + "timestamp": "2026-11-03T10:00:01Z", + "payload": { + "type": "message", + "role": "user", + "content": [ + { + "type": "input_text", + "text": "cwd=/tmp/p", + }, + {"type": "input_text", "text": "render an HTML snippet"}, + ], + }, + }, + { + "type": "response_item", + "timestamp": "2026-11-03T10:00:02Z", + "payload": { + "type": "message", + "role": "assistant", + "content": [{"type": "output_text", "text": "
hello
"}], + }, + }, + ], + ) + assert shell._cmd_ingest_transcript(_args(src, dry_run=True)) == 0 + out = capsys.readouterr().out + assert "would ingest 2 turns" in out + + +def test_empty_jsonl_reports_jsonl_specific_error( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + src = tmp_path / "empty.jsonl" + src.write_text('{"type": "unknown"}\n', encoding="utf-8") + assert shell._cmd_ingest_transcript(_args(src)) == 5 + err = capsys.readouterr().err + assert "Claude Code or Codex JSONL session file" in err + + +def test_jsonl_file_ingest_redacts_secrets_in_outgoing_body( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + srv = _Server() + monkeypatch.setattr(urllib.request, "urlopen", srv.urlopen) + src = tmp_path / "secret.jsonl" + _write_jsonl( + src, + [ + { + "type": "user", + "sessionId": "s-sec", + "cwd": "/tmp/p", + "timestamp": "2026-11-03T10:00:00Z", + "message": { + "role": "user", + "content": "use éghp_12345678901234567890123456é and éBearer supersecret", + }, + } + ], + ) + assert shell._cmd_ingest_transcript(_args(src, token="tok-12345678")) == 0 + assert len(srv.rows) == 1 + sent = next(iter(srv.rows.values()))["content"] + assert "[redacted]" in sent + assert "ghp_12345678901234567890123456" not in sent + assert "supersecret" not in sent + + +def test_claude_jsonl_follows_active_branch_and_dedups_replayed_uuids(tmp_path: Path) -> None: + from server.cli._transcripts import parse_claude_jsonl + + src = tmp_path / "rewound.jsonl" + _write_jsonl( + src, + [ + { + "type": "user", + "uuid": "u1", + "parentUuid": None, + "sessionId": "s-rew", + "cwd": "/tmp/p", + "timestamp": "2026-12-01T10:00:00Z", + "message": {"role": "user", "content": "start"}, + }, + { + "type": "assistant", + "uuid": "a1-rewound", + "parentUuid": "u1", + "sessionId": "s-rew", + "timestamp": "2026-12-01T10:00:01Z", + "message": { + "role": "assistant", + "content": [{"type": "text", "text": "abandoned"}], + }, + }, + { + "type": "user", + "uuid": "u1", + "parentUuid": None, + "sessionId": "s-rew", + "timestamp": "2026-12-01T10:00:00Z", + "message": {"role": "user", "content": "start"}, + }, + { + "type": "assistant", + "uuid": "a2-live", + "parentUuid": "u1", + "sessionId": "s-rew", + "timestamp": "2026-12-01T10:00:02Z", + "message": {"role": "assistant", "content": [{"type": "text", "text": "kept"}]}, + }, + ], + ) + sess = parse_claude_jsonl(src) + assert sess is not None + assert [t.content for t in sess.turns] == ["start", "kept"] + + +def test_discover_sorts_undated_projects_after_dated_projects( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from server.cli._transcripts import discover_sessions + + monkeypatch.setenv("HOME", str(tmp_path)) + _write_jsonl( + tmp_path / ".claude" / "projects" / "undated" / "s1.jsonl", + [{"type": "user", "cwd": "/work/undated", "message": {"role": "user", "content": "hi"}}], + ) + _write_jsonl( + tmp_path / ".claude" / "projects" / "dated" / "s2.jsonl", + [ + { + "type": "user", + "cwd": "/work/dated", + "timestamp": "2026-11-01T10:00:00Z", + "message": {"role": "user", "content": "hello"}, + } + ], + ) + summaries = discover_sessions() + assert [s.project for s in summaries] == ["/work/dated", "/work/undated"] + + +def test_claude_jsonl_follows_logical_parent_uuid_across_compaction(tmp_path: Path) -> None: + from server.cli._transcripts import parse_claude_jsonl + + src = tmp_path / "compacted.jsonl" + _write_jsonl( + src, + [ + { + "type": "user", + "uuid": "u1", + "parentUuid": None, + "sessionId": "s-cmp", + "cwd": "/tmp/p", + "timestamp": "2026-12-01T10:00:00Z", + "message": {"role": "user", "content": "before compaction"}, + }, + { + "type": "system", + "uuid": "compact-1", + "parentUuid": None, + "logicalParentUuid": "u1", + "sessionId": "s-cmp", + "timestamp": "2026-12-01T10:01:00Z", + }, + { + "type": "assistant", + "uuid": "a2", + "parentUuid": "compact-1", + "sessionId": "s-cmp", + "timestamp": "2026-12-01T10:02:00Z", + "message": {"role": "assistant", "content": [{"type": "text", "text": "after"}]}, + }, + ], + ) + sess = parse_claude_jsonl(src) + assert sess is not None + assert [t.content for t in sess.turns] == ["before compaction", "after"]