|
| 1 | +""" |
| 2 | +convo_scanner.py — Parse Claude Code conversation directories into ProjectInfo. |
| 3 | +
|
| 4 | +Claude Code stores sessions under ``~/.claude/projects/<slug>/<id>.jsonl``, |
| 5 | +where the ``<slug>`` is the original CWD with ``/`` replaced by ``-``. That |
| 6 | +encoding is lossy: we can't tell whether ``foo-bar`` in a slug is the |
| 7 | +literal project name ``foo-bar`` or two path segments ``foo/bar``. |
| 8 | +
|
| 9 | +Fortunately, every message record in the JSONL carries a ``cwd`` field with |
| 10 | +the true path. This scanner reads one record per session to recover the |
| 11 | +accurate project name, falling back to slug-decoding only if the JSONL |
| 12 | +is malformed or empty. |
| 13 | +
|
| 14 | +Output is the same ``ProjectInfo`` shape used by ``project_scanner``, so the |
| 15 | +``discover_entities`` orchestrator can mix-and-match sources. |
| 16 | +
|
| 17 | +Public: |
| 18 | + is_claude_projects_root(path) -> bool |
| 19 | + scan_claude_projects(path) -> list[ProjectInfo] |
| 20 | +""" |
| 21 | + |
| 22 | +from __future__ import annotations |
| 23 | + |
| 24 | +import json |
| 25 | +from pathlib import Path |
| 26 | +from typing import Optional |
| 27 | + |
| 28 | +from mempalace.project_scanner import ProjectInfo |
| 29 | + |
| 30 | + |
| 31 | +MAX_HEADER_LINES = 20 # lines to read per session looking for `cwd` |
| 32 | + |
| 33 | + |
| 34 | +def is_claude_projects_root(path: Path) -> bool: |
| 35 | + """Return True if path looks like `.claude/projects/`. |
| 36 | +
|
| 37 | + Heuristic: at least one child dir whose name starts with ``-`` and which |
| 38 | + contains at least one ``.jsonl`` file. |
| 39 | + """ |
| 40 | + if not path.is_dir(): |
| 41 | + return False |
| 42 | + try: |
| 43 | + children = list(path.iterdir()) |
| 44 | + except OSError: |
| 45 | + return False |
| 46 | + for child in children: |
| 47 | + if not (child.is_dir() and child.name.startswith("-")): |
| 48 | + continue |
| 49 | + try: |
| 50 | + if any(p.suffix == ".jsonl" for p in child.iterdir() if p.is_file()): |
| 51 | + return True |
| 52 | + except OSError: |
| 53 | + continue |
| 54 | + return False |
| 55 | + |
| 56 | + |
| 57 | +def _extract_cwd_from_session(session_file: Path) -> Optional[str]: |
| 58 | + """Return the ``cwd`` from the first message record that carries one. |
| 59 | +
|
| 60 | + Returns None if the file can't be read, has no JSON, or no record has cwd. |
| 61 | + """ |
| 62 | + try: |
| 63 | + with open(session_file, encoding="utf-8", errors="replace") as f: |
| 64 | + for i, line in enumerate(f): |
| 65 | + if i >= MAX_HEADER_LINES: |
| 66 | + break |
| 67 | + line = line.strip() |
| 68 | + if not line: |
| 69 | + continue |
| 70 | + try: |
| 71 | + obj = json.loads(line) |
| 72 | + except json.JSONDecodeError: |
| 73 | + continue |
| 74 | + cwd = obj.get("cwd") |
| 75 | + if isinstance(cwd, str) and cwd: |
| 76 | + return cwd |
| 77 | + except OSError: |
| 78 | + return None |
| 79 | + return None |
| 80 | + |
| 81 | + |
| 82 | +def _decode_slug_fallback(slug: str) -> str: |
| 83 | + """Best-effort project name from slug when cwd is unavailable. |
| 84 | +
|
| 85 | + The slug is lossy (`/` and `-` both become `-`). Last non-empty segment |
| 86 | + is the closest guess at the project name, preserving kebab-case is |
| 87 | + impossible without cwd. |
| 88 | + """ |
| 89 | + stripped = slug.lstrip("-") |
| 90 | + parts = [p for p in stripped.split("-") if p] |
| 91 | + return parts[-1] if parts else slug |
| 92 | + |
| 93 | + |
| 94 | +def _safe_mtime(path: Path) -> float: |
| 95 | + """Return file mtime, defaulting old on permission or filesystem errors.""" |
| 96 | + try: |
| 97 | + return path.stat().st_mtime |
| 98 | + except OSError: |
| 99 | + return 0.0 |
| 100 | + |
| 101 | + |
| 102 | +def _resolve_project_name(project_dir: Path) -> str: |
| 103 | + """Read one session's cwd to recover the original project name. |
| 104 | +
|
| 105 | + Falls back to slug-decoding if no session has a readable cwd. |
| 106 | + """ |
| 107 | + sessions = sorted( |
| 108 | + (p for p in project_dir.iterdir() if p.is_file() and p.suffix == ".jsonl"), |
| 109 | + key=_safe_mtime, |
| 110 | + reverse=True, # newest first — most likely to be well-formed |
| 111 | + ) |
| 112 | + for session in sessions: |
| 113 | + cwd = _extract_cwd_from_session(session) |
| 114 | + if cwd: |
| 115 | + return Path(cwd).name or cwd |
| 116 | + return _decode_slug_fallback(project_dir.name) |
| 117 | + |
| 118 | + |
| 119 | +def scan_claude_projects(path: str | Path) -> list[ProjectInfo]: |
| 120 | + """Scan a ``.claude/projects/`` directory for Claude Code conversations. |
| 121 | +
|
| 122 | + One ProjectInfo per subdir. ``has_git`` is False (the directory isn't a |
| 123 | + repo itself) but ``total_commits`` is repurposed here as session count so |
| 124 | + the UX surfaces a density signal for ranking. |
| 125 | + """ |
| 126 | + root = Path(path).expanduser().resolve() |
| 127 | + if not is_claude_projects_root(root): |
| 128 | + return [] |
| 129 | + |
| 130 | + projects: dict[str, ProjectInfo] = {} |
| 131 | + for sub in sorted(root.iterdir()): |
| 132 | + if not (sub.is_dir() and sub.name.startswith("-")): |
| 133 | + continue |
| 134 | + try: |
| 135 | + sessions = [p for p in sub.iterdir() if p.is_file() and p.suffix == ".jsonl"] |
| 136 | + except OSError: |
| 137 | + continue |
| 138 | + if not sessions: |
| 139 | + continue |
| 140 | + |
| 141 | + name = _resolve_project_name(sub) |
| 142 | + session_count = len(sessions) |
| 143 | + |
| 144 | + proj = ProjectInfo( |
| 145 | + name=name, |
| 146 | + repo_root=sub, |
| 147 | + manifest=None, |
| 148 | + has_git=False, |
| 149 | + total_commits=session_count, |
| 150 | + user_commits=session_count, |
| 151 | + is_mine=True, # Claude Code sessions are authored by the user |
| 152 | + ) |
| 153 | + existing = projects.get(name) |
| 154 | + if existing is None or session_count > existing.user_commits: |
| 155 | + projects[name] = proj |
| 156 | + |
| 157 | + return sorted( |
| 158 | + projects.values(), |
| 159 | + key=lambda p: (-p.user_commits, p.name), |
| 160 | + ) |
0 commit comments