Skip to content

tobihagemann/turbo / claude/skills/recall-session

recall-session

Verified

Recall what a past Claude Code session did and why by locating its transcript. Use when the user asks to "recall the session", "why did we do X", or "why was this changed".

FileKindSize
SKILL.mdskill md6.3 KB
scripts/find_transcript.pyscript19.5 KB

scripts/find_transcript.py

View on GitHub
#!/usr/bin/env python3
"""Find the Claude Code transcript that produced a given commit and excerpt the prompts and replies behind it.

Usage:
  python3 scripts/find_transcript.py --commit <sha>
  python3 scripts/find_transcript.py --file <path>[:<line>]
  python3 scripts/find_transcript.py --file <path>:<line> --window-days 14
  python3 scripts/find_transcript.py --phrase "<text from the passage>"

Resolves a commit SHA (directly or via `git blame`), locates candidate Claude Code
project transcript directories under the effective configuration home
(`CLAUDE_CONFIG_DIR` or `~/.claude`), ranks candidate transcripts by time overlap and
file/tool-use references, and extracts relevant user prompts and assistant text from
the top candidate. With `--phrase`, skips git entirely and ranks the project's
transcripts by mentions of the phrase instead, for changes with no commit to resolve.

Output: JSON on stdout with commit metadata (null with `--phrase`), candidate list, and excerpts.
Exit codes: 0 on success (even if no transcripts found), 1 on usage errors, 2 on git failures.
"""

import argparse
import json
import os
import subprocess
import sys
from bisect import bisect_left
from datetime import datetime, timedelta, timezone
from pathlib import Path


def run_git(args, cwd=None):
    result = subprocess.run(
        ['git', *args],
        cwd=cwd,
        capture_output=True,
        text=True,
    )
    if result.returncode != 0:
        return None
    return result.stdout


def resolve_commit(commit, file_ref, repo_root):
    """Return commit SHA, resolving via git blame if needed."""
    if commit:
        sha = run_git(['rev-parse', commit], cwd=repo_root)
        if sha is None:
            return None
        return sha.strip()

    if file_ref:
        path, _, line = file_ref.partition(':')
        line = line or '1'
        blame = run_git(['blame', '-L', f'{line},{line}', '--porcelain', path], cwd=repo_root)
        if blame is None:
            return None
        blame_lines = blame.splitlines()
        first_line = blame_lines[0] if blame_lines else ''
        sha = first_line.split(' ', 1)[0] if first_line else ''
        if not sha or sha == '0000000000000000000000000000000000000000':
            return None
        return sha

    return None


def get_commit_meta(sha, repo_root):
    """Return dict with sha, timestamp (ISO), message, files touched."""
    info = run_git(
        ['show', '-s', '--format=%H%n%cI%n%s%n%b', sha],
        cwd=repo_root,
    )
    if info is None:
        return None
    lines = info.splitlines()
    if len(lines) < 3:
        return None
    files = run_git(['show', '--name-only', '--format=', sha], cwd=repo_root) or ''
    return {
        'sha': lines[0],
        'timestamp': lines[1],
        'subject': lines[2],
        'body': '\n'.join(lines[3:]).strip(),
        'files': [f for f in files.splitlines() if f],
    }


def claude_projects_root():
    """Return the effective Claude Code transcript-storage root."""
    config_home = os.environ.get('CLAUDE_CONFIG_DIR')
    if config_home:
        return Path(config_home).expanduser() / 'projects'
    return Path.home() / '.claude' / 'projects'


def project_transcript_dirs():
    """Return Claude Code project directories for authoritative cwd filtering."""
    projects_root = claude_projects_root()
    if not projects_root.is_dir():
        return []
    return sorted(
        (path for path in projects_root.iterdir() if path.is_dir()),
        key=lambda p: p.stat().st_mtime,
        reverse=True,
    )


def iter_transcripts(project_dirs):
    transcripts = [
        transcript
        for project_dir in project_dirs
        for transcript in project_dir.glob('*.jsonl')
    ]
    return sorted(transcripts, key=lambda p: p.stat().st_mtime, reverse=True)


def parse_timestamp(value):
    if not value:
        return None
    try:
        return datetime.fromisoformat(value.replace('Z', '+00:00'))
    except ValueError:
        return None


def load_transcript_records(path, max_records=20000):
    """Stream-load a transcript JSONL file, capping records to avoid runaway memory."""
    records = []
    try:
        with path.open('r', encoding='utf-8', errors='replace') as f:
            for i, line in enumerate(f):
                if i >= max_records:
                    break
                line = line.strip()
                if not line:
                    continue
                try:
                    records.append(json.loads(line))
                except json.JSONDecodeError:
                    continue
    except OSError:
        return []
    return records


def transcript_belongs_to_project(records, repo_root):
    """Return whether a transcript was launched in the repo or a subdirectory."""
    root = str(repo_root)
    seen = set()
    for record in records:
        cwd = record.get('cwd')
        if not cwd or cwd in seen:
            continue
        seen.add(cwd)
        resolved = str(Path(cwd).expanduser().resolve())
        if resolved == root or resolved.startswith(root + os.sep):
            return True
    return False


def transcript_time_range(records):
    timestamps = []
    for r in records:
        ts = parse_timestamp(r.get('timestamp'))
        if ts is not None:
            timestamps.append(ts)
    if not timestamps:
        return (None, None)
    return (min(timestamps), max(timestamps))


def extract_text(message_content):
    """Pull plain text out of assistant or user message content (string or list of parts)."""
    if message_content is None:
        return ''
    if isinstance(message_content, str):
        return message_content
    if isinstance(message_content, list):
        parts = []
        for p in message_content:
            if not isinstance(p, dict):
                continue
            t = p.get('type')
            if t == 'text' and p.get('text'):
                parts.append(p['text'])
            elif t == 'tool_use':
                name = p.get('name', '')
                inp = p.get('input') or {}
                parts.append(f'[tool_use:{name} {json.dumps(inp)[:500]}]')
        return '\n'.join(parts)
    return ''


def score_transcript(records, commit_ts, touched_files):
    """Return (score, reasons, relevant_record_indices) for how well this transcript matches the commit."""
    score = 0
    reasons = []
    relevant_indices = []

    # Time overlap
    start, end = transcript_time_range(records)
    if start is not None and end is not None and commit_ts is not None:
        # Session must have had activity before the commit
        if start <= commit_ts:
            score += 2
            reasons.append('session active before commit')
        if start <= commit_ts <= end + timedelta(hours=2):
            score += 3
            reasons.append('commit within session window')

    file_hits = {}
    tool_hits = {}

    for idx, r in enumerate(records):
        is_relevant = False
        text_blob = ''
        msg = r.get('message') or {}
        content = msg.get('content')
        if content is not None:
            text_blob = extract_text(content)

        # Full-path text mentions only. Basename-only matching would false-positive on common filenames
        # (e.g., index.ts, main.py) appearing across unrelated transcripts in the time window.
        for full_path in touched_files:
            if full_path and full_path in text_blob:
                file_hits[full_path] = file_hits.get(full_path, 0) + 1
                is_relevant = True

        # Tool uses referencing touched files
        if isinstance(content, list):
            for part in content:
                if not isinstance(part, dict) or part.get('type') != 'tool_use':
                    continue
                name = part.get('name', '')
                if name not in ('Edit', 'Write', 'MultiEdit', 'NotebookEdit'):
                    continue
                inp = part.get('input') or {}
                fp = inp.get('file_path', '')
                for f in touched_files:
                    # Match full equality or a proper path suffix; plain endswith would
                    # false-match (e.g., '/src/foobar.py'.endswith('bar.py') is True).
                    if f and (fp == f or fp.endswith('/' + f)):
                        tool_hits[f] = tool_hits.get(f, 0) + 1
                        is_relevant = True
                        break

        if is_relevant:
            relevant_indices.append(idx)

    score += sum(file_hits.values())
    score += 3 * sum(tool_hits.values())

    if file_hits:
        reasons.append(f'mentions {len(file_hits)} touched file(s): {", ".join(sorted(file_hits))[:200]}')
    if tool_hits:
        reasons.append(f'edits {len(tool_hits)} touched file(s)')

    return score, reasons, relevant_indices


def normalize_text(text):
    """Collapse whitespace and case so a phrase matches across reflowed or recased copies."""
    return ' '.join(text.split()).casefold()


def iter_strings(value):
    """Yield every string nested in a message part, including tool inputs and results in full."""
    if isinstance(value, str):
        yield value
    elif isinstance(value, dict):
        for v in value.values():
            yield from iter_strings(v)
    elif isinstance(value, list):
        for v in value:
            yield from iter_strings(v)


def score_phrase(records, phrase):
    """Return (score, reasons, relevant_record_indices) for how often this transcript handles the phrase."""
    needle = normalize_text(phrase)
    hits = {'tool_use': 0, 'tool_result': 0, 'text': 0}
    relevant_indices = []
    last_match = None

    def message_parts(record):
        content = (record.get('message') or {}).get('content')
        if isinstance(content, str):
            return [{'type': 'text', 'text': content}]
        if not isinstance(content, list):
            return []
        return [part for part in content if isinstance(part, dict)]

    # Phrase lookups carry the phrase in their command and echo it in their output,
    # so a session that ran one, including the running one, would match itself.
    lookup_ids = set()
    for r in records:
        for part in message_parts(r):
            if part.get('type') != 'tool_use':
                continue
            strings = list(iter_strings(part.get('input')))
            is_lookup = any('find_transcript.py' in s for s in strings) and any('--phrase' in s for s in strings)
            if is_lookup and part.get('id'):
                lookup_ids.add(part['id'])

    for idx, r in enumerate(records):
        matched = False
        for part in message_parts(r):
            if part.get('id') in lookup_ids or part.get('tool_use_id') in lookup_ids:
                continue
            if not any(needle in normalize_text(s) for s in iter_strings(part)):
                continue
            kind = part.get('type')
            hits[kind if kind in hits else 'text'] += 1
            matched = True
        if matched:
            relevant_indices.append(idx)
            last_match = r.get('timestamp') or last_match

    # Tool calls carrying the phrase are edits or commands on the passage, the strongest signal.
    score = 3 * hits['tool_use'] + hits['tool_result'] + hits['text']
    reasons = []
    if hits['tool_use']:
        reasons.append(f'phrase in {hits["tool_use"]} tool call(s)')
    if hits['tool_result']:
        reasons.append(f'phrase in {hits["tool_result"]} tool result(s)')
    if hits['text']:
        reasons.append(f'phrase in {hits["text"]} message(s)')
    if last_match:
        reasons.append(f'last match at {last_match}')
    return score, reasons, relevant_indices


NOISE_PREFIXES = (
    '<command-message>',
    '<command-name>',
    '<command-args>',
    '<local-command-stdout>',
    '<local-command-caveat>',
    '<bash-input>',
    '<bash-stdout>',
    '<bash-stderr>',
    '<system-reminder>',
    '<task-notification>',
    'Base directory for this skill:',
    'Caveat: The messages below were generated',
    '(Re-invocation of',
)

# Read like ordinary prose, so only harness-injected user records are filtered.
USER_NOISE_PREFIXES = (
    'Called the ',
    'Skill /',
    'Another Claude session sent',
)


def clean_text(content, rtype):
    """Extract and clean message text, returning None for tool results and noise."""
    text = extract_text(content).strip()
    if not text:
        return None
    if rtype == 'user' and isinstance(content, list):
        if all(isinstance(p, dict) and p.get('type') == 'tool_result' for p in content):
            return None
    if any(text.startswith(p) for p in NOISE_PREFIXES):
        return None
    if rtype == 'user' and text.startswith(USER_NOISE_PREFIXES):
        return None
    if rtype == 'assistant' and '[tool_use:' in text:
        lines = [l for l in text.split('\n') if not l.startswith('[tool_use:')]
        text = '\n'.join(lines).strip()
    return text or None


def extract_excerpts(records, relevant_indices, max_excerpts=40):
    """Return excerpts relevant to the change in transcript order.

    Draws on every non-sidechain user prompt in the session (the intent is gold), plus
    substantive assistant text near relevant tool calls (filters out short transitions).
    When the cap binds, records nearest a relevant one win, so a long session's early
    prompts cannot crowd out the matches.
    """
    excerpts = []
    relevant = sorted(set(relevant_indices))

    interesting = set()
    for idx in relevant:
        for j in range(max(0, idx - 2), min(len(records), idx + 3)):
            interesting.add(j)

    for idx, r in enumerate(records):
        if r.get('type') == 'user' and not r.get('isSidechain'):
            interesting.add(idx)

    def distance(idx):
        if not relevant:
            return 0
        pos = bisect_left(relevant, idx)
        return min(abs(idx - relevant[p]) for p in (pos - 1, pos) if 0 <= p < len(relevant))

    for idx in sorted(interesting, key=lambda i: (distance(i), i)):
        r = records[idx]
        rtype = r.get('type')
        if rtype not in ('user', 'assistant'):
            continue
        if r.get('isSidechain'):
            continue
        msg = r.get('message') or {}
        text = clean_text(msg.get('content'), rtype)
        if text is None:
            continue
        # Assistant: skip short transitional messages unless they sit directly at a relevant tool call
        if rtype == 'assistant' and len(text) < 80 and idx not in relevant_indices:
            continue
        excerpts.append({
            'index': idx,
            'role': rtype,
            'timestamp': r.get('timestamp'),
            'text': text[:2000],
        })
        if len(excerpts) >= max_excerpts:
            break

    excerpts.sort(key=lambda e: e['index'])
    return excerpts


def transcript_mtime(path):
    return datetime.fromtimestamp(path.stat().st_mtime, tz=timezone.utc)


def rank_transcripts(paths, repo_root, score_records, limit):
    """Score the project's transcripts; return (top candidates, directories holding project transcripts)."""
    scored = []
    matching_dirs = set()
    for path in paths:
        records = load_transcript_records(path)
        if not records or not transcript_belongs_to_project(records, repo_root):
            continue
        matching_dirs.add(path.parent)
        score, reasons, rel_idx = score_records(records)
        if score <= 0:
            continue
        excerpts = extract_excerpts(records, rel_idx)
        scored.append({
            'session_id': path.stem,
            'jsonl_path': str(path),
            'mtime': transcript_mtime(path).isoformat(),
            'score': score,
            'match_reasons': reasons,
            'excerpt_count': len(excerpts),
            'excerpts': excerpts,
        })

    scored.sort(key=lambda c: c['score'], reverse=True)
    return scored[:limit], sorted(matching_dirs)


def main():
    parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    parser.add_argument('--commit', help='commit SHA to look up (overrides --file)')
    parser.add_argument('--file', help='file path, optionally FILE:LINE to use git blame')
    parser.add_argument('--phrase',
                        help='distinctive text from the passage, for changes with no commit '
                             '(overrides --commit and --file; works outside git)')
    parser.add_argument('--window-days', type=int, default=14,
                        help='max days between commit and transcript mtime (default 14)')
    parser.add_argument('--limit', type=int, default=3,
                        help='max candidate transcripts to report (default 3)')
    parser.add_argument('--cwd', default=os.getcwd(),
                        help='project directory (default: current working directory)')
    args = parser.parse_args()

    if not args.commit and not args.file and not args.phrase:
        print('error: --commit, --file, or --phrase is required', file=sys.stderr)
        return 1
    if args.phrase is not None and not args.phrase.strip():
        print('error: --phrase must contain text', file=sys.stderr)
        return 1

    repo_root_raw = run_git(['rev-parse', '--show-toplevel'], cwd=args.cwd)

    if args.phrase:
        # Outside git, the given directory stands in for the repo root.
        repo_root = Path(repo_root_raw.strip() if repo_root_raw else args.cwd).resolve()
        result = {'status': 'ok', 'commit': None, 'phrase': args.phrase}
        keep_path = lambda path: True
        score_records = lambda records: score_phrase(records, args.phrase)
        no_match_error = 'no project transcript mentions the phrase'
    else:
        if repo_root_raw is None:
            print('error: not a git repository', file=sys.stderr)
            return 2
        repo_root = Path(repo_root_raw.strip()).resolve()

        sha = resolve_commit(args.commit, args.file, repo_root)
        if sha is None:
            print(json.dumps({
                'status': 'no-commit',
                'error': 'could not resolve a commit (blame returned no author, or commit not found)',
            }))
            return 0

        meta = get_commit_meta(sha, repo_root)
        if meta is None:
            print(json.dumps({'status': 'no-commit', 'error': f'commit {sha} not found'}))
            return 0

        commit_ts = parse_timestamp(meta['timestamp'])
        window = timedelta(days=args.window_days)
        result = {'status': 'ok', 'commit': meta}
        # Coarse pre-filter: skip files whose mtime is far from the commit to avoid
        # loading and parsing every historical transcript. score_transcript() uses
        # the precise in-file timestamps for the final time-overlap check.
        keep_path = lambda path: commit_ts is None or abs(transcript_mtime(path) - commit_ts) <= window
        score_records = lambda records: score_transcript(records, commit_ts, meta['files'])
        no_match_error = 'no transcript in the window matched the touched files'

    result.update({'project_dir': None, 'project_dirs': [], 'candidates': []})

    storage_dirs = project_transcript_dirs()
    if not storage_dirs:
        result['status'] = 'no-transcripts'
        result['error'] = 'no Claude Code transcript directories under the effective config home'
        print(json.dumps(result, indent=2))
        return 0

    paths = [path for path in iter_transcripts(storage_dirs) if keep_path(path)]
    candidates, matching_dirs = rank_transcripts(paths, repo_root, score_records, args.limit)
    result['candidates'] = candidates
    result['project_dirs'] = [str(path) for path in matching_dirs]

    if not candidates:
        result['status'] = 'no-match'
        result['error'] = no_match_error
    else:
        result['project_dir'] = str(Path(candidates[0]['jsonl_path']).parent)

    print(json.dumps(result, indent=2))
    return 0


if __name__ == '__main__':
    sys.exit(main())
reverse-engineer-anythingmorluto/reaReverse engineer native, managed, Electron/JavaScript, packaged, firmware, and browser targets with REA, and build agent environments (AgentEnv bundles) of web applications from a live instance or a capture, and of Linux desktop apps with a task from a request. Use shipped-artifact or requested runtime evidence to explain features, compare versions, decompile code, or guide a reconstruction. Skip REA for ordinary source-repository architecture analysis.Stars: 472kUpdated Claude CodeCodexVerifiedInstall
diagnosing-superpowersobra/superpowersUse when a superpowers session went wrong and your human partner wants to know why — repeated work, ignored plans, stumbles, poor results, a skill that didn't fire, "it took too long", "why is it so expensive", "what is it doing" — or wants to build a bug report for the superpowers maintainers, for the current session or a past one identified by id or path, on any harness.Stars: 322kUpdated Claude CodeCodexVerifiedInstall
dispatching-parallel-agentsobra/superpowersUse when facing 2+ independent tasks that can be worked on without shared state or sequential dependenciesStars: 322kUpdated Claude CodeCodexVerifiedInstall
executing-plansobra/superpowersUse when executing an implementation plan in the current session as the implementer yourself — your human partner chose inline execution, or no subagent tool is availableStars: 322kUpdated Claude CodeCodexVerifiedInstall