From cc5b7a368f99145f13725650062d1e8cabdfa6fa Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Thu, 3 Dec 2026 23:36:40 +0530 Subject: [PATCH 1/9] feat(cli): add Claude Code and Codex session parsing and --discover to ingest-transcript Signed-off-by: suryanshxharma --- docs/reference/cli.md | 2 +- server/cli/_transcripts.py | 271 +++++++++++++++++++++++ server/cli/shell.py | 56 ++++- tests/unit/snapshots/cli_help.json | 4 +- tests/unit/snapshots/cli_tree.json | 24 +- tests/unit/test_cli_ingest_transcript.py | 198 +++++++++++++++++ 6 files changed, 539 insertions(+), 16 deletions(-) create mode 100644 server/cli/_transcripts.py diff --git a/docs/reference/cli.md b/docs/reference/cli.md index 15c1e62101e..c71e58383ca 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 00000000000..676d666af57 --- /dev/null +++ b/server/cli/_transcripts.py @@ -0,0 +1,271 @@ +"""Read-only discovery and parsing of local Claude Code and Codex session transcripts.""" + +from __future__ import annotations + +import json +from dataclasses import dataclass +from pathlib import Path +from typing import Any + + +@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 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() + 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 = _extract_claude_text(content) + if not text or text.startswith("<"): + 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 not text or text.startswith("<"): + 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 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" + + sessions: list[SessionInfo] = [] + 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: + sessions.append(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: + sessions.append(parsed) + + grouped: dict[str, list[SessionInfo]] = {} + for sess in sessions: + grouped.setdefault(sess.project, []).append(sess) + + summaries: list[ProjectSummary] = [] + for project, items in grouped.items(): + sources = tuple(sorted({s.source for s in items})) + dates = [d[:10] for s in items for d in (s.first_ts, s.last_ts) if len(d) >= 10] + earliest = min(dates) if dates else "unknown" + latest = max(dates) if dates else "unknown" + summaries.append( + ProjectSummary( + project=project, + sources=sources, + session_count=len(items), + earliest_date=earliest, + latest_date=latest, + total_bytes=sum(s.size_bytes for s in items), + ) + ) + + summaries.sort(key=lambda s: (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 0e2263b02f7..fefa1ced44f 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -20,6 +20,7 @@ resolve_token, ) from server.cli._paths import write_private +from server.cli._transcripts import discover_sessions, format_bytes, parse_jsonl_session def _cmd_memory_search(args: argparse.Namespace) -> int: @@ -151,7 +152,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 +163,31 @@ 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 + + if not args.namespace: + print("ERROR: --namespace is required unless --discover is set", file=sys.stderr) + return 2 + if not args.file: + print("ERROR: --file is required unless --discover is set", file=sys.stderr) + return 2 + token, source = resolve_token(args.token) if refused_for_agent(source): return 2 @@ -177,10 +204,15 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: 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": t.content} 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 +230,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 @@ -420,8 +453,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 +469,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 d5c7820eac0..c4289422583 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 6eda63b71c8..64e3f3ea2c1 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 272eac8140c..3cc703b8d79 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -173,3 +173,201 @@ 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 From 6d4e3b4e419855b7d89ea307d7413e3106dc740a Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Thu, 3 Dec 2026 23:53:12 +0530 Subject: [PATCH 2/9] fix(cli): strip injected tags instead of dropping turns and improve JSONL error Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 22 +++++++-- server/cli/shell.py | 9 +++- tests/unit/test_cli_ingest_transcript.py | 57 ++++++++++++++++++++++++ 3 files changed, 83 insertions(+), 5 deletions(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index 676d666af57..530a28be2b8 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -3,10 +3,24 @@ from __future__ import annotations import json +import re from dataclasses import dataclass from pathlib import Path from typing import Any +# Injected client wrapper blocks that may precede or wrap user prompts. +_INJECTED_TAG_RE = re.compile( + r"<(?:system-reminder|environment_context|command-name|command-message|" + r"command-args|local-command-stdout|user_instructions|turn_aborted)\b[^>]*>" + r"[\s\S]*?", + re.IGNORECASE, +) + + +def _strip_injected_tags(text: str) -> str: + return _INJECTED_TAG_RE.sub("", text).strip() + @dataclass(frozen=True) class SessionTurn: @@ -125,8 +139,8 @@ def parse_claude_jsonl(path: Path) -> SessionInfo | None: if rec_type == "user": if _has_tool_result(content): continue - text = _extract_claude_text(content) - if not text or text.startswith("<"): + 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) @@ -181,7 +195,9 @@ def parse_codex_jsonl(path: Path) -> SessionInfo | None: if role not in {"user", "assistant"}: continue text = _extract_codex_text(payload.get("content")) - if not text or text.startswith("<"): + 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) diff --git a/server/cli/shell.py b/server/cli/shell.py index fefa1ced44f..fb07e5962cf 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -254,9 +254,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 diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 3cc703b8d79..4886245a4a7 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -371,3 +371,60 @@ def _no_call(*a: Any, **k: Any) -> Any: 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 From 9249bc3870b79687b033e74bf579891fa96355e2 Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 00:01:20 +0530 Subject: [PATCH 3/9] fix(cli): strip IDE and Codex wrapper tags from user turns Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index 530a28be2b8..a2148e176c1 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -9,11 +9,14 @@ from typing import Any # 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( - r"<(?:system-reminder|environment_context|command-name|command-message|" - r"command-args|local-command-stdout|user_instructions|turn_aborted)\b[^>]*>" - r"[\s\S]*?", + rf"<({_INJECTED_TAG_NAMES})\b[^>]*>[\s\S]*?", re.IGNORECASE, ) From db04f2dc6a003c46e527ee040f9f4a39fd69bc8c Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 21:24:24 +0530 Subject: [PATCH 4/9] fix(cli): stream session discovery, redact JSONL file turns, and check token before args Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 100 +++++++++++++++++------ server/cli/shell.py | 25 ++++-- tests/unit/test_cli_ingest_transcript.py | 29 +++++++ 3 files changed, 121 insertions(+), 33 deletions(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index a2148e176c1..2a8cafb7d83 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -8,6 +8,50 @@ 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" +) +_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, +) +_JWT_RE = re.compile(r"\beyJ[\w-]{0,512}\.[\w-]{1,8192}\.[\w-]{0,1024}") +_BEARER_RE = re.compile(r"\b(Bearer)\s+[^\s\"'\\]+", re.IGNORECASE) +_BASIC_AUTH_RE = re.compile( + r"(\bAuthorization[\"']?\s*[:=]\s*[\"']?Basic)\s+[^\s\"'\\]+", re.IGNORECASE +) +_URL_CREDENTIALS_RE = re.compile( + r"\b([a-z][a-z0-9+.-]{0,31}://)[^\s/@\"']{1,256}:[^\s/@\"']{0,256}@", re.IGNORECASE +) + + +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|" @@ -230,6 +274,24 @@ def parse_jsonl_session(path: Path) -> SessionInfo | None: 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]: @@ -237,7 +299,7 @@ def discover_sessions( 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" - sessions: list[SessionInfo] = [] + grouped: dict[str, dict[str, Any]] = {} if c_dir.is_dir(): for path in sorted(c_dir.glob("*/*.jsonl")): try: @@ -245,7 +307,7 @@ def discover_sessions( except OSError: continue if parsed is not None: - sessions.append(parsed) + _accumulate_project(grouped, parsed) if x_dir.is_dir(): for path in sorted(x_dir.rglob("*.jsonl")): @@ -254,29 +316,19 @@ def discover_sessions( except OSError: continue if parsed is not None: - sessions.append(parsed) - - grouped: dict[str, list[SessionInfo]] = {} - for sess in sessions: - grouped.setdefault(sess.project, []).append(sess) - - summaries: list[ProjectSummary] = [] - for project, items in grouped.items(): - sources = tuple(sorted({s.source for s in items})) - dates = [d[:10] for s in items for d in (s.first_ts, s.last_ts) if len(d) >= 10] - earliest = min(dates) if dates else "unknown" - latest = max(dates) if dates else "unknown" - summaries.append( - ProjectSummary( - project=project, - sources=sources, - session_count=len(items), - earliest_date=earliest, - latest_date=latest, - total_bytes=sum(s.size_bytes for s in items), - ) + _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: (s.latest_date, s.session_count, s.project), reverse=True) return summaries diff --git a/server/cli/shell.py b/server/cli/shell.py index fb07e5962cf..dd227b2d4e9 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -20,7 +20,12 @@ resolve_token, ) from server.cli._paths import write_private -from server.cli._transcripts import discover_sessions, format_bytes, parse_jsonl_session +from server.cli._transcripts import ( + discover_sessions, + format_bytes, + parse_jsonl_session, + redact_secrets, +) def _cmd_memory_search(args: argparse.Namespace) -> int: @@ -181,13 +186,6 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: ) return 0 - if not args.namespace: - print("ERROR: --namespace is required unless --discover is set", file=sys.stderr) - return 2 - if not args.file: - print("ERROR: --file is required unless --discover is set", file=sys.stderr) - return 2 - token, source = resolve_token(args.token) if refused_for_agent(source): return 2 @@ -200,6 +198,13 @@ 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) @@ -210,7 +215,9 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: if suffix == ".jsonl": session = parse_jsonl_session(src) if session is not None: - turns = [{"role": t.role, "content": t.content} for t in session.turns] + 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: diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 4886245a4a7..0644c3826dd 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -428,3 +428,32 @@ def test_empty_jsonl_reports_jsonl_specific_error( 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 From 7084797d696478e34a9846cd1ecf9cfb09e4fc50 Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 22:39:17 +0530 Subject: [PATCH 5/9] fix(cli): use re.ASCII for secret redaction word boundaries Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 15 +++++++++------ tests/unit/test_cli_ingest_transcript.py | 2 +- 2 files changed, 10 insertions(+), 7 deletions(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index 2a8cafb7d83..3a49c3cff61 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -15,20 +15,23 @@ _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" + 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.IGNORECASE | re.ASCII, ) -_JWT_RE = re.compile(r"\beyJ[\w-]{0,512}\.[\w-]{1,8192}\.[\w-]{0,1024}") -_BEARER_RE = re.compile(r"\b(Bearer)\s+[^\s\"'\\]+", re.IGNORECASE) +_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 + 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 + r"\b([a-z][a-z0-9+.-]{0,31}://)[^\s/@\"']{1,256}:[^\s/@\"']{0,256}@", + re.IGNORECASE | re.ASCII, ) diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 0644c3826dd..a6c89389062 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -446,7 +446,7 @@ def test_jsonl_file_ingest_redacts_secrets_in_outgoing_body( "timestamp": "2026-11-03T10:00:00Z", "message": { "role": "user", - "content": "use ghp_12345678901234567890123456 and Bearer supersecret", + "content": "use éghp_12345678901234567890123456é and éBearer supersecret", }, } ], From 0e67ef9583e702694c3efefb7fffebbc64dc9ad7 Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 22:52:54 +0530 Subject: [PATCH 6/9] fix(cli): follow active parentUuid branch and sort undated projects last Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 39 +++++++++++- tests/unit/test_cli_ingest_transcript.py | 75 ++++++++++++++++++++++++ 2 files changed, 113 insertions(+), 1 deletion(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index 3a49c3cff61..6b5745dff83 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -162,6 +162,34 @@ def _read_jsonl_records(path: Path) -> list[dict[str, Any]]: 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") + 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) @@ -176,6 +204,8 @@ def parse_claude_jsonl(path: Path) -> SessionInfo | None: 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"): @@ -332,7 +362,14 @@ def discover_sessions( ) for project, acc in grouped.items() ] - summaries.sort(key=lambda s: (s.latest_date, s.session_count, s.project), reverse=True) + summaries.sort( + key=lambda s: ( + "" if s.latest_date == "unknown" else s.latest_date, + s.session_count, + s.project, + ), + reverse=True, + ) return summaries diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index a6c89389062..4cc6f316e1c 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -457,3 +457,78 @@ def test_jsonl_file_ingest_redacts_secrets_in_outgoing_body( 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"] From 95304b3d75cfa4b311f3d344937436febd76363e Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 23:02:46 +0530 Subject: [PATCH 7/9] fix(cli): follow logicalParentUuid across compaction boundaries Signed-off-by: suryanshxharma --- server/cli/_transcripts.py | 2 +- tests/unit/test_cli_ingest_transcript.py | 39 ++++++++++++++++++++++++ 2 files changed, 40 insertions(+), 1 deletion(-) diff --git a/server/cli/_transcripts.py b/server/cli/_transcripts.py index 6b5745dff83..928a5f720aa 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -184,7 +184,7 @@ def _active_claude_branch(records: list[dict[str, Any]]) -> list[dict[str, Any]] seen.add(cur) rec = by_uuid[cur] chain.append(rec) - parent = rec.get("parentUuid") + parent = rec.get("parentUuid") or rec.get("logicalParentUuid") cur = parent.strip() if isinstance(parent, str) and parent.strip() else None chain.reverse() return chain diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 4cc6f316e1c..820c0deecba 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -532,3 +532,42 @@ def test_discover_sorts_undated_projects_after_dated_projects( ) 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"] From 60c7ec904afb4ae50ee0c16867002c81e91c9bc1 Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Fri, 4 Dec 2026 21:45:49 +0530 Subject: [PATCH 8/9] feat(cli): batch import local sessions with redaction, retention, and dedup Signed-off-by: suryanshxharma --- docs/reference/cli.md | 2 +- server/cli/_transcripts.py | 79 ++++++ server/cli/shell.py | 310 +++++++++++++++++++---- tests/unit/snapshots/cli_help.json | 4 +- tests/unit/snapshots/cli_tree.json | 48 ++++ tests/unit/test_cli_ingest_transcript.py | 210 +++++++++++++++ 6 files changed, 597 insertions(+), 56 deletions(-) diff --git a/docs/reference/cli.md b/docs/reference/cli.md index c71e58383ca..5f37961329d 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`, `--discover`, `--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`, `--project`, `--newest`, `--retention-days`, `--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 index 928a5f720aa..410a09ab8a2 100644 --- a/server/cli/_transcripts.py +++ b/server/cli/_transcripts.py @@ -5,6 +5,7 @@ import json import re from dataclasses import dataclass +from datetime import UTC, datetime, timedelta from pathlib import Path from typing import Any @@ -380,3 +381,81 @@ def format_bytes(num_bytes: int) -> str: if num_bytes < 1024 * 1024: return f"{num_bytes / 1024:.1f} KiB" return f"{num_bytes / (1024 * 1024):.1f} MiB" + + +def _session_sort_key(sess: SessionInfo) -> tuple[str, float]: + if sess.last_ts: + return (sess.last_ts, 0.0) + try: + return ("", sess.path.stat().st_mtime) + except OSError: + return ("", 0.0) + + +def find_project_sessions( + project_filters: list[str], + *, + claude_dir: Path | None = None, + codex_dir: Path | None = None, +) -> list[SessionInfo]: + """Return sessions matching any project name or path, newest first.""" + 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" + wanted = {p.strip() for p in project_filters if p.strip()} + if not wanted: + return [] + + matches: list[SessionInfo] = [] + candidates: list[tuple[Path, Any]] = [] + if c_dir.is_dir(): + candidates.extend((p, parse_claude_jsonl) for p in sorted(c_dir.glob("*/*.jsonl"))) + if x_dir.is_dir(): + candidates.extend((p, parse_codex_jsonl) for p in sorted(x_dir.rglob("*.jsonl"))) + + for path, parser in candidates: + try: + sess = parser(path) + except OSError: + continue + if sess is None: + continue + if sess.project in wanted or Path(sess.project).name in wanted: + matches.append(sess) + + matches.sort(key=_session_sort_key, reverse=True) + return matches + + +def _parse_ts(raw: str, fallback_path: Path) -> datetime: + if raw: + try: + dt = datetime.fromisoformat(raw.replace("Z", "+00:00")) + return dt if dt.tzinfo else dt.replace(tzinfo=UTC) + except ValueError: + pass + try: + return datetime.fromtimestamp(fallback_path.stat().st_mtime, tz=UTC) + except OSError: + return datetime.now(UTC) + + +def filter_by_retention( + sessions: list[SessionInfo], + retention_days: int, + *, + now: datetime | None = None, +) -> tuple[list[SessionInfo], int]: + """Drop sessions whose last timestamp is older than ``retention_days``.""" + if retention_days <= 0: + return list(sessions), 0 + ref = now or datetime.now(UTC) + cutoff = ref - timedelta(days=retention_days) + kept: list[SessionInfo] = [] + skipped = 0 + for sess in sessions: + ts = _parse_ts(sess.last_ts or sess.first_ts, sess.path) + if ts < cutoff: + skipped += 1 + else: + kept.append(sess) + return kept, skipped diff --git a/server/cli/shell.py b/server/cli/shell.py index dd227b2d4e9..b60d42377e8 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -22,6 +22,8 @@ from server.cli._paths import write_private from server.cli._transcripts import ( discover_sessions, + filter_by_retention, + find_project_sessions, format_bytes, parse_jsonl_session, redact_secrets, @@ -154,6 +156,146 @@ def _http_error_line(e: urllib.error.HTTPError) -> str: return error_line(e.code, str(e.reason), raw) +def _post_json_op( + base: str, op_name: str, body: dict[str, Any], headers: dict[str, str] +) -> dict[str, Any] | None: + """Best-effort POST to a Loom JSON operation; returns decoded dict or None.""" + import json as _json + import urllib.request + + data = _json.dumps(body).encode("utf-8") + req = urllib.request.Request(f"{base}/v1/{op_name}", data=data, headers=headers, method="POST") + try: + with urllib.request.urlopen(req, timeout=15) as resp: + parsed = _json.loads(resp.read().decode("utf-8") or "{}") + return parsed if isinstance(parsed, dict) else {} + except (urllib.error.HTTPError, urllib.error.URLError, OSError, ValueError): + return None + + +def _fetch_namespace_policy( + base: str, org: str, namespace: str, headers: dict[str, str] +) -> tuple[bool, int] | None: + """Return (recording_enabled, retention_days) from namespace.get, or None on failure.""" + info = _post_json_op(base, "namespace.get", {"org": org, "namespace": namespace}, headers) + if info is None: + return None + recording = info.get("conversation_logging_enabled") + if recording is None: + recording = info.get("record_conversations") + if recording is None: + recording = info.get("logging_enabled", False) + retention = info.get("retention_conversations_days") or info.get("retention_days") or 0 + try: + retention_days = max(0, int(retention)) + except (TypeError, ValueError): + retention_days = 0 + return bool(recording), retention_days + + +def _cmd_ingest_project_sessions( + args: argparse.Namespace, + *, + post_turns: Any, +) -> int: + """Batch-import discovered sessions for ``--project`` with redaction and retention.""" + sessions = find_project_sessions(list(args.project)) + if not sessions: + print(f"ERROR: no Claude Code or Codex sessions matched {args.project}", file=sys.stderr) + return 3 + + newest = int(getattr(args, "newest", 0) or 0) + if newest > 0: + sessions = sessions[:newest] + + if args.dry_run: + retention_days = int(getattr(args, "retention_days", 0) or 0) + sessions, skipped_old = filter_by_retention(sessions, retention_days) + total_turns = sum(len(s.turns) for s in sessions) + print( + f"would import {len(sessions)} session(s) ({total_turns} turns, " + f"{skipped_old} past retention) into {args.namespace}" + ) + for s in sessions: + size = format_bytes(s.size_bytes) + print(f" [{s.source}] {s.session_id} ({len(s.turns)} turns, {size})") + return 0 + + token, source = resolve_token(args.token) + if refused_for_agent(source): + return 2 + if not token: + print( + "ERROR: --token is required (or set LOOM_API_KEY, or save one to ~/.loom/token). " + "Mint one with `loom mint-token --subject you@x --org default " + "--namespaces my-ns --roles writer`.", + file=sys.stderr, + ) + return 2 + + base = args.server_url.rstrip("/") + namespace = args.namespace + org = args.org or str(jwt_claims(token).get("org") or "") or "dev" + headers = {"Content-Type": "application/json", "Authorization": f"Bearer {token}"} + + policy = _fetch_namespace_policy(base, org, namespace, headers) + if policy is None: + print( + f"ERROR: could not verify recording/retention policy for namespace {namespace}; " + "aborting import", + file=sys.stderr, + ) + return 1 + recording_on, ns_retention = policy + if not recording_on: + print(f"recording is disabled for namespace {namespace}; skipping import") + return 0 + + retention_days = int(getattr(args, "retention_days", 0) or 0) or ns_retention + kept, skipped_old = filter_by_retention(sessions, retention_days) + + print(f"importing {len(kept)} session(s) into {namespace} ({skipped_old} past retention)") + if not kept: + return 0 + + total_written = 0 + stored_sessions = 0 + for sess in kept: + redacted_turns = [ + { + "role": t.role, + "content": redact_secrets(t.content, token), + "timestamp": t.timestamp, + } + for t in sess.turns + ] + redacted_turns = [t for t in redacted_turns if t["content"].strip()] + if not redacted_turns: + continue + written, rc = post_turns( + base=base, + headers=headers, + org=org, + namespace=namespace, + agent=args.agent, + thread_id=sess.session_id, + turns=redacted_turns, + extra_metadata={ + "source_class": "imported", + "source": sess.source, + "project": sess.project, + }, + ) + if rc != 0: + return rc + if written > 0: + stored_sessions += 1 + total_written += written + + print(f"✓ imported {stored_sessions} session(s) ({total_written} new turns) into {namespace}") + return 0 + + def _cmd_ingest_transcript(args: argparse.Namespace) -> int: """Read a chat history file, POST each turn to conversation.append. @@ -168,6 +310,71 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: import time import urllib.request + def _post_turns( + *, + base: str, + headers: dict[str, str], + org: str, + namespace: str, + agent: str, + thread_id: str, + turns: list[dict[str, Any]], + extra_metadata: dict[str, Any] | None = None, + ) -> tuple[int, int]: + msg_ids = _turn_msg_ids(turns) + written = 0 + for i, turn in enumerate(turns): + body: dict[str, Any] = { + "org": org, + "namespace": namespace, + "agent": agent, + "thread_id": thread_id, + "msg_id": msg_ids[i], + "role": turn["role"], + "content": turn["content"], + } + meta = dict(extra_metadata or {}) + if turn.get("timestamp"): + meta["session_ts"] = turn["timestamp"] + if meta: + body["metadata"] = meta + + data = _json.dumps(body).encode("utf-8") + req = urllib.request.Request( + f"{base}/v1/conversation.append", + data=data, + headers=headers, + method="POST", + ) + try: + with urllib.request.urlopen(req, timeout=15) as resp: + raw_resp = resp.read().decode("utf-8") or "{}" + try: + ack = _json.loads(raw_resp) + except ValueError: + ack = {} + if isinstance(ack, dict) and ( + ack.get("stored") is False or ack.get("reason") == "duplicate" + ): + continue + except urllib.error.HTTPError as e: + print(f"ERROR: turn {i} failed: {_http_error_line(e)}", file=sys.stderr) + return written, 6 + except urllib.error.URLError as e: + print(f"ERROR: turn {i} network error: {e}", file=sys.stderr) + return written, 7 + except OSError as e: + print( + f"ERROR: turn {i}: no answer from {base} ({type(e).__name__}: {e}); " + f"{written} turn(s) were written before it", + file=sys.stderr, + ) + return written, 1 + written += 1 + if i % 30 == 29: + time.sleep(0.5) + return written, 0 + if getattr(args, "discover", False): summaries = discover_sessions() if not summaries: @@ -186,23 +393,28 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: ) return 0 - token, source = resolve_token(args.token) - if refused_for_agent(source): - return 2 - if not token: - print( - "ERROR: --token is required (or set LOOM_API_KEY, or save one to ~/.loom/token). " - "Mint one with `loom mint-token --subject you@x --org default " - "--namespaces my-ns --roles writer`.", - file=sys.stderr, - ) - return 2 + if not getattr(args, "dry_run", False): + token, source = resolve_token(args.token) + if refused_for_agent(source): + return 2 + if not token: + print( + "ERROR: --token is required (or set LOOM_API_KEY, or save one to ~/.loom/token). " + "Mint one with `loom mint-token --subject you@x --org default " + "--namespaces my-ns --roles writer`.", + file=sys.stderr, + ) + return 2 + else: + token = "" if not getattr(args, "namespace", None): print("ERROR: --namespace is required unless --discover is set", file=sys.stderr) return 2 + if getattr(args, "project", None): + return _cmd_ingest_project_sessions(args, post_turns=_post_turns) if not getattr(args, "file", None): - print("ERROR: --file is required unless --discover is set", file=sys.stderr) + print("ERROR: --file or --project is required unless --discover is set", file=sys.stderr) return 2 src = Path(args.file).expanduser().resolve() @@ -274,7 +486,6 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: return 5 thread_id = args.thread_id or _default_thread_id(src) - msg_ids = _turn_msg_ids(turns) if args.dry_run: # Counts and sizes only: the transcript text stays out of the terminal @@ -292,46 +503,21 @@ def _cmd_ingest_transcript(args: argparse.Namespace) -> int: "Content-Type": "application/json", "Authorization": f"Bearer {token}", } - # No conversation.create — append works against an unknown thread_id; - # the thread row is implicit. One append per turn, fail-fast. - written = 0 - for i, turn in enumerate(turns): - body = { - "org": org, - "namespace": namespace, - "agent": args.agent, - "thread_id": thread_id, - "msg_id": msg_ids[i], - "role": turn["role"], - "content": turn["content"], - } - data = _json.dumps(body).encode("utf-8") - req = urllib.request.Request( - f"{base}/v1/conversation.append", - data=data, - headers=headers, - method="POST", - ) - try: - with urllib.request.urlopen(req, timeout=15) as resp: - resp.read() - except urllib.error.HTTPError as e: - print(f"ERROR: turn {i} failed: {_http_error_line(e)}", file=sys.stderr) - return 6 - except urllib.error.URLError as e: - print(f"ERROR: turn {i} network error: {e}", file=sys.stderr) - return 7 - except OSError as e: # a read timeout or a dropped connection after connect - print( - f"ERROR: turn {i}: no answer from {base} ({type(e).__name__}: {e}); " - f"{written} turn(s) were written before it", - file=sys.stderr, - ) - return 1 - written += 1 - # Pace to avoid hammering CH's async-insert queue on large transcripts. - if i % 30 == 29: - time.sleep(0.5) + if suffix == ".jsonl": + turns = [{**t, "content": redact_secrets(t["content"], token)} for t in turns] + turns = [t for t in turns if t["content"].strip()] + written, rc = _post_turns( + base=base, + headers=headers, + org=org, + namespace=namespace, + agent=args.agent, + thread_id=thread_id, + turns=turns, + extra_metadata={"source_class": "imported"} if suffix == ".jsonl" else None, + ) + if rc != 0: + return rc print(f"✓ ingested {written} turns into thread {thread_id} on {namespace}") return 0 @@ -491,6 +677,24 @@ def _add_shell_client_parsers(sub: Any) -> None: action="store_true", help="List local Claude Code and Codex sessions by project without writing anything.", ) + p_ingest.add_argument( + "--project", + action="append", + default=[], + help="Project name or path from --discover to batch-import (repeatable).", + ) + p_ingest.add_argument( + "--newest", + type=int, + default=0, + help="Import at most the N newest sessions per run (0 = all).", + ) + p_ingest.add_argument( + "--retention-days", + type=int, + default=0, + help="Skip sessions older than N days (0 = use namespace setting or no limit).", + ) p_ingest.add_argument( "--dry-run", action="store_true", diff --git a/tests/unit/snapshots/cli_help.json b/tests/unit/snapshots/cli_help.json index c4289422583..7272fbe1c8f 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] [--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." + "usage: loom ingest-transcript [-h] [--server-url SERVER_URL] [--token TOKEN] [--org ORG] [--namespace NAMESPACE] [--agent AGENT] [--thread-id THREAD_ID] [--file FILE] [--discover] [--project PROJECT] [--newest NEWEST] [--retention-days RETENTION_DAYS] [--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. --project PROJECT Project name or path from --discover to batch-import (repeatable). --newest NEWEST Import at most the N newest sessions per run (0 = all). --retention-days RETENTION_DAYS Skip sessions older than N days (0 = use namespace setting or no limit). --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 64e3f3ea2c1..091b2b6b14b 100644 --- a/tests/unit/snapshots/cli_tree.json +++ b/tests/unit/snapshots/cli_tree.json @@ -16605,6 +16605,9 @@ "thread_id", "file", "discover", + "project", + "newest", + "retention_days", "dry_run" ] } @@ -16747,6 +16750,51 @@ "help": "List local Claude Code and Codex sessions by project without writing anything.", "metavar": null }, + { + "option_strings": [ + "--project" + ], + "dest": "project", + "action": "_AppendAction", + "default": [], + "const": null, + "choices": null, + "nargs": null, + "type": null, + "required": false, + "help": "Project name or path from --discover to batch-import (repeatable).", + "metavar": null + }, + { + "option_strings": [ + "--newest" + ], + "dest": "newest", + "action": "_StoreAction", + "default": 0, + "const": null, + "choices": null, + "nargs": null, + "type": "builtins:int", + "required": false, + "help": "Import at most the N newest sessions per run (0 = all).", + "metavar": null + }, + { + "option_strings": [ + "--retention-days" + ], + "dest": "retention_days", + "action": "_StoreAction", + "default": 0, + "const": null, + "choices": null, + "nargs": null, + "type": "builtins:int", + "required": false, + "help": "Skip sessions older than N days (0 = use namespace setting or no limit).", + "metavar": null + }, { "option_strings": [ "--dry-run" diff --git a/tests/unit/test_cli_ingest_transcript.py b/tests/unit/test_cli_ingest_transcript.py index 820c0deecba..0367ac76a58 100644 --- a/tests/unit/test_cli_ingest_transcript.py +++ b/tests/unit/test_cli_ingest_transcript.py @@ -373,6 +373,216 @@ def _no_call(*a: Any, **k: Any) -> Any: assert codex_file.read_bytes() == codex_before +class _JsonResp: + def __init__(self, payload: dict[str, Any]) -> None: + self._raw = json.dumps(payload).encode("utf-8") + + def __enter__(self) -> _JsonResp: + return self + + def __exit__(self, *a: Any) -> None: + return None + + def read(self) -> bytes: + return self._raw + + +class _ImportServer: + def __init__( + self, + *, + recording: bool = True, + retention_days: int = 0, + fail_policy: bool = False, + ) -> None: + self.recording = recording + self.retention_days = retention_days + self.fail_policy = fail_policy + self.rows: dict[tuple[str, str], dict[str, Any]] = {} + + def urlopen(self, req: Any, timeout: float = 0) -> _JsonResp: + url = req.full_url + body = json.loads(req.data) + if url.endswith("/v1/namespace.get"): + if self.fail_policy: + raise urllib.error.URLError("timeout") + return _JsonResp( + { + "conversation_logging_enabled": self.recording, + "retention_conversations_days": self.retention_days, + } + ) + if url.endswith("/v1/conversation.append"): + key = (body["thread_id"], body["msg_id"]) + if key in self.rows: + return _JsonResp({"msg_id": body["msg_id"], "reason": "duplicate"}) + self.rows[key] = body + return _JsonResp({"msg_id": body["msg_id"], "stored": True}) + raise AssertionError(f"unexpected URL {url}") + + +def test_project_import_redacts_dedups_and_respects_retention( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + from datetime import UTC, datetime, timedelta + + srv = _ImportServer(recording=True, retention_days=30) + monkeypatch.setattr(urllib.request, "urlopen", srv.urlopen) + monkeypatch.setenv("HOME", str(tmp_path)) + + now = datetime.now(UTC) + recent_ts = (now - timedelta(days=2)).strftime("%Y-%m-%dT%H:%M:%SZ") + old_ts = (now - timedelta(days=90)).strftime("%Y-%m-%dT%H:%M:%SZ") + + recent_file = tmp_path / ".claude" / "projects" / "alpha" / "recent.jsonl" + _write_jsonl( + recent_file, + [ + { + "type": "user", + "sessionId": "sess-recent", + "cwd": "/work/alpha", + "timestamp": recent_ts, + "message": { + "role": "user", + "content": "use token ghp_12345678901234567890123456 and Bearer mysecret", + }, + }, + { + "type": "assistant", + "sessionId": "sess-recent", + "cwd": "/work/alpha", + "timestamp": recent_ts, + "message": {"role": "assistant", "content": [{"type": "text", "text": "done"}]}, + }, + ], + ) + old_file = tmp_path / ".claude" / "projects" / "alpha" / "old.jsonl" + _write_jsonl( + old_file, + [ + { + "type": "user", + "sessionId": "sess-old", + "cwd": "/work/alpha", + "timestamp": old_ts, + "message": {"role": "user", "content": "ancient question"}, + } + ], + ) + + ns = argparse.Namespace( + discover=False, + project=["/work/alpha"], + newest=0, + retention_days=0, + namespace="my-ns", + file=None, + token="tok-12345678", + server_url="http://x", + org="o", + agent="ingest-cli", + thread_id=None, + dry_run=False, + ) + assert shell._cmd_ingest_transcript(ns) == 0 + out1 = capsys.readouterr().out + assert "importing 1 session(s) into my-ns (1 past retention)" in out1 + assert "imported 1 session(s) (2 new turns)" in out1 + assert len(srv.rows) == 2 + threads = {tid for tid, _ in srv.rows} + assert threads == {"sess-recent"} + contents = [row["content"] for row in srv.rows.values()] + assert any("[redacted]" in c for c in contents) + assert all("ghp_12345678901234567890123456" not in c for c in contents) + assert all("mysecret" not in c for c in contents) + assert all(row["metadata"]["source_class"] == "imported" for row in srv.rows.values()) + + # Second run: per-message dedup returns duplicate, so 0 new sessions/turns are stored. + assert shell._cmd_ingest_transcript(ns) == 0 + out2 = capsys.readouterr().out + assert "imported 0 session(s) (0 new turns)" in out2 + assert len(srv.rows) == 2 + + +def test_project_import_aborts_when_policy_lookup_fails( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + srv = _ImportServer(fail_policy=True) + monkeypatch.setattr(urllib.request, "urlopen", srv.urlopen) + monkeypatch.setenv("HOME", str(tmp_path)) + + f = tmp_path / ".claude" / "projects" / "gamma" / "s1.jsonl" + _write_jsonl( + f, + [ + { + "type": "user", + "sessionId": "s1", + "cwd": "/work/gamma", + "timestamp": "2026-12-01T10:00:00Z", + "message": {"role": "user", "content": "private prompt"}, + } + ], + ) + ns = argparse.Namespace( + discover=False, + project=["gamma"], + newest=0, + retention_days=0, + namespace="my-ns", + file=None, + token="tok-12345678", + server_url="http://x", + org="o", + agent="ingest-cli", + thread_id=None, + dry_run=False, + ) + assert shell._cmd_ingest_transcript(ns) == 1 + assert "could not verify" in capsys.readouterr().err + assert len(srv.rows) == 0 + + +def test_project_import_skips_when_recording_disabled( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + srv = _ImportServer(recording=False) + monkeypatch.setattr(urllib.request, "urlopen", srv.urlopen) + monkeypatch.setenv("HOME", str(tmp_path)) + + f = tmp_path / ".claude" / "projects" / "beta" / "s1.jsonl" + _write_jsonl( + f, + [ + { + "type": "user", + "sessionId": "s1", + "cwd": "/work/beta", + "timestamp": "2026-12-01T10:00:00Z", + "message": {"role": "user", "content": "hi"}, + } + ], + ) + ns = argparse.Namespace( + discover=False, + project=["beta"], + newest=0, + retention_days=0, + namespace="my-ns", + file=None, + token="tok-12345678", + server_url="http://x", + org="o", + agent="ingest-cli", + thread_id=None, + dry_run=False, + ) + assert shell._cmd_ingest_transcript(ns) == 0 + assert "recording is disabled" in capsys.readouterr().out + assert len(srv.rows) == 0 + + def test_injected_tags_stripped_without_dropping_real_prompts_or_xml_replies( monkeypatch: pytest.MonkeyPatch, tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: From 151ae7e1c3e762d4a88a0aa022ff14d4a0487127 Mon Sep 17 00:00:00 2001 From: suryanshxharma Date: Sat, 5 Dec 2026 00:59:16 +0530 Subject: [PATCH 9/9] fix(cli): type post_turns callback to satisfy mypy no-any-return Signed-off-by: suryanshxharma --- server/cli/shell.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/server/cli/shell.py b/server/cli/shell.py index b60d42377e8..5dcb04588c7 100644 --- a/server/cli/shell.py +++ b/server/cli/shell.py @@ -8,6 +8,7 @@ import hashlib import sys import urllib.error +from collections.abc import Callable from pathlib import Path from typing import Any @@ -196,7 +197,7 @@ def _fetch_namespace_policy( def _cmd_ingest_project_sessions( args: argparse.Namespace, *, - post_turns: Any, + post_turns: Callable[..., tuple[int, int]], ) -> int: """Batch-import discovered sessions for ``--project`` with redaction and retention.""" sessions = find_project_sessions(list(args.project))