Skip to content

gerodp/hermes-productivity-skills / development/claude-sessions

claude-sessions

Verified

List your Claude Code sessions for any time window — start, duration, project, message counts, title, models, token usage, API-equivalent cost, and an A–D cost-efficiency grade with per-session recommendations, straight from the local transcripts.

FileKindSize
SKILL.mdskill md16.1 KB
scripts/claude_sessions.pyscript54.0 KB
scripts/test_claude_sessions.pyscript31.5 KB

scripts/claude_sessions.py

View on GitHub
#!/usr/bin/env python3
"""claude-sessions — list your Claude Code sessions for any time window.

Claude Code stores every conversation as a JSONL transcript on disk under
``~/.claude/projects/<encoded-cwd>/<session-id>.jsonl`` (one file per session).
This skill scans those transcripts and reports the sessions that were **active**
within a time window — grouped/sorted by recency — with per-session start, end,
duration, project, message counts, title, and (with ``--rich``) the models used,
token usage, API-equivalent cost, and a cost-efficiency grade.

No configuration and no network: it only reads local files. The transcript root
defaults to ``~/.claude/projects`` and can be overridden with ``--projects-dir``
or a ``CLAUDE_PROJECTS_DIR`` env var / ``~/.hermes/.env`` value.

Subcommands:
    check       Verify the transcript root exists; count sessions & projects.
    list        Sessions active in a window (default), newest first.
    efficiency  Grade sessions A–D by cost efficiency; suggest habits.
    find        Search sessions by title / slug / project / id (all time).
    projects    One row per project: session / prompt / token counts in a window.
    show        Deep dive on a single session by id (or id prefix).

All windows are computed in **local time** with **Monday-start** weeks. A session
matches a window if any of its activity falls inside it (its [start, end] overlaps
the window).

Python standard library only — no third-party dependencies, no subprocesses,
no network. Read-only: it never modifies a transcript.
"""
from __future__ import annotations

import argparse
import collections
import glob
import json
import os
import re
import sys
from datetime import date, datetime, timedelta, timezone

# Titles come from transcript content (AI-generated or the user's first prompt,
# which can quote hostile web/file text) — keep the first line and strip control
# chars so a title can't smuggle terminal escapes into rendered output.
CONTROL_CHARS_RE = re.compile(r"[\x00-\x1f\x7f]")


def _clean_title(s):
    first = s.splitlines()[0] if s else ""
    return CONTROL_CHARS_RE.sub("", first).strip() or "(untitled)"

ENV_DIR = "CLAUDE_PROJECTS_DIR"  # optional override; intentionally UNDECLARED
DEFAULT_PROJECTS_DIR = "~/.claude/projects"

# Tool names whose `input.file_path` we record as a "file touched".
EDIT_TOOLS = {"Edit", "Write", "NotebookEdit", "MultiEdit"}
# Wrapper prefixes that mark a synthetic / non-typed "user" turn (slash commands,
# caveats, injected reminders) — skipped when picking a title / counting prompts.
META_PREFIXES = ("<command-", "<local-command-", "<system-reminder", "<bash-",
                 "<user-", "<policy", "<request-")

# Published list price per 1M tokens (USD): (input, output). Cache is derived from
# the input rate: read = 0.1×, 5-minute write = 1.25×, 1-hour write = 2×. These are
# list prices for a rough cost estimate — not a billing statement (no batch/tier
# discounts). Keyed by model *family*; see model_family().
PRICING = {
    "opus": (5.0, 25.0),
    "sonnet": (3.0, 15.0),
    "haiku": (1.0, 5.0),
    "fable": (10.0, 50.0),
}

# Reference context window (Opus/Sonnet/Fable are 1M) — used only to express the
# average context re-read per turn as a fraction, for the efficiency rating.
CONTEXT_WINDOW = 1_000_000
# Efficiency thresholds (see session_efficiency): the primary axis is how much
# context is re-shipped (and re-billed as cache-read) on every assistant turn.
CTX_LEAN = 0.06 * CONTEXT_WINDOW      # <=  60k/turn — a tight, focused session
CTX_MODERATE = 0.18 * CONTEXT_WINDOW  # <= 180k/turn — fine
CTX_HEAVY = 0.35 * CONTEXT_WINDOW     # <= 350k/turn — carrying a lot; above = bloated
MARATHON_DAYS = 2                     # wall-clock span that starts wasting 1h caches
# Below this API-equivalent cost, a low output-share isn't worth acting on: a tiny
# session (a brief tool run, a quick lookup) naturally reads more context than it
# writes, and there's no meaningful "split this up" to do. Gate the low-output
# flag / recommendation on it so it only fires on sessions big enough to matter.
LOW_OUTPUT_MIN_COST = 5.0


def model_family(model):
    m = (model or "").lower()
    if "opus" in m:
        return "opus"
    if "sonnet" in m:
        return "sonnet"
    if "haiku" in m:
        return "haiku"
    if "fable" in m or "mythos" in m:
        return "fable"
    return None


def model_cost_parts(model, u):
    """USD cost of one model's usage dict, broken out by component, or None if
    the model isn't priced.

    Cache writes are split into 5-minute (1.25×) and 1-hour (2×) buckets when the
    transcript records the split; otherwise all cache creation is treated as
    5-minute. Cache reads bill at 0.1× the input rate.
    """
    fam = model_family(model)
    if fam is None:
        return None
    inp, out = PRICING[fam]
    return {
        "input": u.get("input", 0) * inp / 1_000_000,
        "output": u.get("output", 0) * out / 1_000_000,
        "cache_read": u.get("cache_read", 0) * inp * 0.1 / 1_000_000,
        "cache_write": (u.get("cw_5m", 0) * inp * 1.25
                        + u.get("cw_1h", 0) * inp * 2.0) / 1_000_000,
    }


def model_cost(model, u):
    """USD cost of one model's usage dict, or None if the model isn't priced."""
    parts = model_cost_parts(model, u)
    return None if parts is None else sum(parts.values())


def session_efficiency(s):
    """Grade a parsed session on *cost efficiency* — not on the work it did, but
    on how much of its spend went to re-shipping context rather than producing
    output. Returns None when there's nothing to judge (no assistant turns / no
    priced usage).

    The signal comes straight from the cost analysis: cache-read (context re-sent
    every turn) dominates long sessions, so the primary axis is the average
    context re-read per assistant turn. A multi-day wall-clock span makes it worse
    (idle gaps expire 1-hour caches, which are then rewritten at a premium with no
    reuse), so it drops the grade. Grades: A (lean) → D (bloated / marathon).
    """
    turns = s["assistant_turns"]
    tk = s["tokens"]
    total = s["cost_usd"]
    if turns <= 0 or (tk["input"] + tk["output"] + tk["cache_read"]) == 0:
        return None

    parts = s.get("cost_parts") or {}
    avg_ctx = int(tk["cache_read"] / turns)
    cache_cost = parts.get("cache_read", 0.0) + parts.get("cache_write", 0.0)
    cache_share = (cache_cost / total) if total else 0.0
    output_share = (parts.get("output", 0.0) / total) if total else 0.0
    span_days = s["duration_seconds"] / 86400.0
    cost_per_prompt = (total / s["prompts"]) if s["prompts"] else total

    if avg_ctx <= CTX_LEAN:
        rating, score = "lean", 0
    elif avg_ctx <= CTX_MODERATE:
        rating, score = "moderate", 1
    elif avg_ctx <= CTX_HEAVY:
        rating, score = "heavy", 2
    else:
        rating, score = "bloated", 3
    if span_days >= 5:
        score += 2
    elif span_days >= MARATHON_DAYS:
        score += 1
    grade = "ABCD"[min(score, 3)]

    flags, tips = [], []
    if avg_ctx > CTX_MODERATE:
        flags.append(f"re-reads ~{human_int(avg_ctx)} of context per turn "
                     f"({avg_ctx / CONTEXT_WINDOW * 100:.0f}% of a 1M window)")
        tips.append("Split into focused, shorter-lived sessions and /compact at "
                    "phase boundaries — the whole context is re-read (and re-billed "
                    "as cache) on every turn.")
    if span_days >= MARATHON_DAYS:
        flags.append(f"spans {fmt_duration(s['duration_seconds'])} of wall-clock")
        tips.append("Do a task in one sitting or /clear between days — long idle "
                    "gaps expire 1-hour caches, which get rewritten at a premium "
                    "with no reuse benefit.")
    if total >= LOW_OUTPUT_MIN_COST and output_share < 0.25:
        flags.append(f"only {output_share * 100:.0f}% of spend produced output; "
                     f"{cache_share * 100:.0f}% was carrying context")
    if not flags:
        tips.append("Healthy — lean context per turn and a tight time span.")

    return {
        "grade": grade,
        "rating": rating,
        "avg_context_per_turn": avg_ctx,
        "cache_cost_share": round(cache_share, 3),
        "output_cost_share": round(output_share, 3),
        "span_days": round(span_days, 2),
        "cost_per_prompt": round(cost_per_prompt, 4),
        "flags": flags,
        "tips": tips,
    }


def _recommendation_items(s):
    """Ordered cost-reduction levers for a session (most impactful first), each a
    dict with a `full` phrasing and a `brief` one for a narrow table column.
    Empty when the session is lean or has no priced usage. Every clause names the
    concrete lever *and* the number that triggered it, so the advice is actionable
    rather than generic.
    """
    eff = s.get("efficiency")
    if not eff:
        return []
    items = []
    if eff["avg_context_per_turn"] > CTX_MODERATE:
        items.append({
            "full": f"/compact at phase boundaries "
                    f"(~{human_int(eff['avg_context_per_turn'])} ctx re-read/turn)",
            "brief": "/compact"})
    if eff["span_days"] >= MARATHON_DAYS:
        items.append({
            "full": f"do it in one sitting or /clear between days "
                    f"(spans {fmt_duration(s['duration_seconds'])})",
            "brief": "/clear"})
    if s["cost_usd"] >= LOW_OUTPUT_MIN_COST and eff["output_cost_share"] < 0.25:
        pct = eff["output_cost_share"] * 100
        items.append({
            "full": f"split unrelated tasks into separate sessions — only "
                    f"{pct:.0f}% of this session's cost produced output "
                    f"(the rest re-shipped context)",
            "brief": f"split {pct:.0f}% out"})
    return items


def session_recommendation(s):
    """The full, specific cost-reduction recommendation for a session (all levers
    joined), or a lean/unpriced note. Used by `show`."""
    if not s.get("efficiency"):
        return "no priced usage — nothing to tune"
    items = _recommendation_items(s)
    if not items:
        return "lean — no change needed"
    return "; ".join(it["full"] for it in items)


def session_recommendation_brief(s):
    """Compact form for the `list` table's Recommendation column: **every**
    applicable lever (each named with the number that triggered it), joined. Full
    sentences are available via `show`."""
    if not s.get("efficiency"):
        return "-"
    items = _recommendation_items(s)
    if not items:
        return "lean"
    return ", ".join(it["brief"] for it in items)


class ClaudeSessionsError(Exception):
    """User-facing error — message is safe to print (never contains secrets)."""


# --------------------------------------------------------------------------- #
# Date windows (local time, Monday-start weeks) — shared with the report skills.
# --------------------------------------------------------------------------- #
PERIODS = ("today", "this-week", "last-week", "this-month",
           "last-month", "this-year", "last-year")

_CURRENT = {"today", "this-week", "this-month", "this-year"}


def _monday(d):
    return d - timedelta(days=d.weekday())


def _first_of_month(d):
    return d.replace(day=1)


def _last_of_month(d):
    nxt = (d.replace(day=28) + timedelta(days=4)).replace(day=1)
    return nxt - timedelta(days=1)


def _parse_date(s):
    try:
        return datetime.strptime(s, "%Y-%m-%d").date()
    except ValueError:
        raise ClaudeSessionsError(f"invalid date (use YYYY-MM-DD): {s}")


def compute_range(today, *, period=None, days=None, start=None, end=None):
    """Return (start_date, end_date) inclusive for the requested window.

    Precedence: explicit start/end > days > period. Default period: this-week.
    Current-period ends are capped at `today` (no empty future days).
    """
    if start or end:
        if not (start and end):
            raise ClaudeSessionsError("--start and --end must be given together")
        s, e = _parse_date(start), _parse_date(end)
        if e < s:
            raise ClaudeSessionsError("--end is before --start")
        return s, e

    if days is not None:
        if days < 1:
            raise ClaudeSessionsError("--days must be >= 1")
        return today - timedelta(days=days - 1), today

    period = period or "this-week"
    if period == "today":
        s, e = today, today
    elif period == "this-week":
        s, e = _monday(today), _monday(today) + timedelta(days=6)
    elif period == "last-week":
        s = _monday(today) - timedelta(days=7)
        e = s + timedelta(days=6)
    elif period == "this-month":
        s, e = _first_of_month(today), _last_of_month(today)
    elif period == "last-month":
        e = _first_of_month(today) - timedelta(days=1)
        s = _first_of_month(e)
    elif period == "this-year":
        s, e = date(today.year, 1, 1), date(today.year, 12, 31)
    elif period == "last-year":
        s, e = date(today.year - 1, 1, 1), date(today.year - 1, 12, 31)
    else:
        raise ClaudeSessionsError(f"unknown period: {period}")

    if period in _CURRENT and e > today:
        e = today
    return s, e


def in_window(start_date, end_date, wstart, wend):
    """True if a session's active span [start_date, end_date] overlaps [wstart, wend]."""
    return start_date <= wend and end_date >= wstart


# --------------------------------------------------------------------------- #
# Timestamp / formatting helpers
# --------------------------------------------------------------------------- #
def parse_ts(s):
    """Parse a transcript ISO-8601 timestamp (UTC, e.g. '...T14:34:53.979Z')
    into an aware UTC datetime, or None if unparseable."""
    if not isinstance(s, str) or not s:
        return None
    t = s.strip()
    if t.endswith("Z"):
        t = t[:-1] + "+00:00"
    try:
        dt = datetime.fromisoformat(t)
    except ValueError:
        try:
            dt = datetime.strptime(s[:19], "%Y-%m-%dT%H:%M:%S")
        except ValueError:
            return None
    if dt.tzinfo is None:
        dt = dt.replace(tzinfo=timezone.utc)
    return dt


def to_local(dt):
    """Convert an aware datetime to the machine's local timezone."""
    return dt.astimezone()


def fmt_duration(seconds):
    seconds = int(max(0, seconds))
    d, rem = divmod(seconds, 86400)
    h, rem = divmod(rem, 3600)
    m, _ = divmod(rem, 60)
    if d:
        return f"{d}d{h}h"
    if h:
        return f"{h}h{m}m"
    if m:
        return f"{m}m"
    return f"{seconds}s"


def human_int(n):
    n = int(n or 0)
    if n >= 1_000_000:
        return f"{n / 1_000_000:.1f}M".replace(".0M", "M")
    if n >= 1_000:
        return f"{n / 1_000:.1f}k".replace(".0k", "k")
    return str(n)


def fmt_usd(x):
    if x is None:
        return "n/a"
    if x < 0.01:
        return "<$0.01"
    if x < 100:
        return f"${x:.2f}"
    return f"${x:,.0f}"


def short_model(m):
    return (m or "").replace("claude-", "")


def shorten_home(p):
    home = os.path.expanduser("~")
    if p and p.startswith(home):
        return "~" + p[len(home):]
    return p or "(unknown)"


def _ellipsis(s, n):
    s = s or ""
    return s if len(s) <= n else s[: n - 1] + "…"


# --------------------------------------------------------------------------- #
# Transcript parsing (one JSONL file == one session)
# --------------------------------------------------------------------------- #
def _user_text(content):
    """Return the human text of a 'user' message, or None if it's a tool result.

    `content` is either a plain string (the prompt) or a list of blocks. A list
    carrying a `tool_result` block is a tool-output turn, not a typed prompt.
    """
    if isinstance(content, str):
        return content
    if isinstance(content, list):
        texts = []
        for p in content:
            if not isinstance(p, dict):
                continue
            if p.get("type") == "tool_result":
                return None
            if p.get("type") == "text" and isinstance(p.get("text"), str):
                texts.append(p["text"])
        return "\n".join(texts) if texts else None
    return None


def _is_meta_text(text):
    t = (text or "").lstrip()
    return t.startswith(META_PREFIXES)


def project_of(path, cwd):
    """The project path for a session: the real `cwd` if the transcript recorded
    one, else a best-effort decode of the encoded parent-directory name."""
    if cwd:
        return cwd
    name = os.path.basename(os.path.dirname(path))
    # Claude encodes the cwd by replacing path separators with '-'. This is lossy
    # (real dashes/dots collapse too), so it's only a fallback for cwd-less files.
    return name.replace("-", "/") if name else "(unknown)"


def parse_session(path):
    """Scan one transcript file and return a session dict, or None if it carries
    no timestamps (can't be placed in a window) or can't be read.

    A single pass collects: identity/context, first & last activity, message and
    prompt counts, title, models, token usage, tool activity, skills/MCP used,
    subagent invocations, API errors, and files edited.
    """
    session_id = os.path.splitext(os.path.basename(path))[0]
    # Subagent (Task) conversations are written to their own `agent-*.jsonl`
    # transcript, whose records carry `sessionId` = the PARENT session's id. We
    # detect them here and fold their tokens/cost into the parent later, so they
    # don't show up as separate rows.
    is_subagent = os.path.basename(path).startswith("agent-")
    inner_session_id = None
    cwd = branch = version = slug = None
    first_dt = last_dt = None
    first_ts = last_ts = None
    assistant_turns = 0
    user_prompts = 0
    first_prompt = None
    ai_title = custom_title = None
    models = set()
    tok = {"input": 0, "output": 0, "cache_read": 0, "cache_creation": 0}
    # Per-model usage, so a session mixing (e.g.) Opus + Haiku subagents is priced
    # at each model's own rate. cw_5m / cw_1h are the two cache-write TTL buckets.
    usage_by_model = {}
    tools = collections.Counter()
    skills, mcps = set(), set()
    subagents = 0
    errors = 0
    files = collections.Counter()
    # Claude Code re-emits the same assistant API response across several JSONL
    # lines as it streams (each carrying the identical, final `usage`). Counting
    # every record double-counts tokens/cost ~2x, so accumulate each unique
    # `message.id` exactly once. This matches `/usage`'s per-session figures.
    seen_msg_ids = set()

    try:
        fh = open(path, encoding="utf-8", errors="replace")
    except OSError:
        return None
    with fh:
        for line in fh:
            line = line.strip()
            if not line:
                continue
            try:
                d = json.loads(line)
            except ValueError:
                continue
            t = d.get("type")

            if t == "ai-title":
                ai_title = d.get("aiTitle") or ai_title
                continue
            if t == "custom-title":
                custom_title = d.get("customTitle") or custom_title
                continue
            if t == "agent-name":
                # An `agent-name` record re-labels *this* session (same sessionId),
                # e.g. as its focus shifts across tasks — it is NOT a subagent. The
                # real subagent count comes from merging `agent-*.jsonl` transcripts.
                continue

            ts = d.get("timestamp")
            if ts:
                pdt = parse_ts(ts)
                if pdt is not None:
                    if first_dt is None or pdt < first_dt:
                        first_dt, first_ts = pdt, ts
                    if last_dt is None or pdt > last_dt:
                        last_dt, last_ts = pdt, ts

            if inner_session_id is None and d.get("sessionId"):
                inner_session_id = d["sessionId"]
            if cwd is None and d.get("cwd"):
                cwd = d["cwd"]
            if slug is None and d.get("slug"):
                slug = d["slug"]
            if branch is None and d.get("gitBranch"):
                branch = d["gitBranch"]
            if version is None and d.get("version"):
                version = d["version"]
            if d.get("attributionSkill"):
                skills.add(d["attributionSkill"])
            if d.get("attributionMcpServer"):
                mcps.add(d["attributionMcpServer"])
            if d.get("isApiErrorMessage") or d.get("apiErrorStatus"):
                errors += 1

            m = d.get("message")
            if t == "assistant" and isinstance(m, dict):
                # Skip streaming duplicates of an already-counted response.
                mid = m.get("id")
                if mid is not None:
                    if mid in seen_msg_ids:
                        continue
                    seen_msg_ids.add(mid)
                assistant_turns += 1
                mdl = m.get("model")
                if mdl and mdl != "<synthetic>":
                    models.add(mdl)
                u = m.get("usage")
                if isinstance(u, dict):
                    inp = u.get("input_tokens") or 0
                    out = u.get("output_tokens") or 0
                    cr = u.get("cache_read_input_tokens") or 0
                    cc = u.get("cache_creation_input_tokens") or 0
                    tok["input"] += inp
                    tok["output"] += out
                    tok["cache_read"] += cr
                    tok["cache_creation"] += cc
                    # Split cache writes by TTL when the transcript records it;
                    # otherwise bill the whole lot at the cheaper 5-minute rate.
                    ccd = u.get("cache_creation")
                    if isinstance(ccd, dict):
                        cw_5m = ccd.get("ephemeral_5m_input_tokens") or 0
                        cw_1h = ccd.get("ephemeral_1h_input_tokens") or 0
                    else:
                        cw_5m, cw_1h = cc, 0
                    acc = usage_by_model.setdefault(
                        mdl or "unknown",
                        {"input": 0, "output": 0, "cache_read": 0,
                         "cw_5m": 0, "cw_1h": 0})
                    acc["input"] += inp
                    acc["output"] += out
                    acc["cache_read"] += cr
                    acc["cw_5m"] += cw_5m
                    acc["cw_1h"] += cw_1h
                c = m.get("content")
                if isinstance(c, list):
                    for p in c:
                        if isinstance(p, dict) and p.get("type") == "tool_use":
                            name = p.get("name", "?")
                            tools[name] += 1
                            if name in EDIT_TOOLS:
                                fp = (p.get("input") or {}).get("file_path")
                                if fp:
                                    files[fp] += 1
            elif (t == "user" and isinstance(m, dict)
                  and not d.get("isMeta") and not d.get("isSidechain")):
                text = _user_text(m.get("content"))
                if text is not None and text.strip() and not _is_meta_text(text):
                    user_prompts += 1
                    if first_prompt is None:
                        first_prompt = text

    if first_dt is None:
        return None  # no datable activity — cannot place in a window

    start_local = to_local(first_dt)
    end_local = to_local(last_dt)
    duration = (last_dt - first_dt).total_seconds()

    if custom_title:
        title, title_src = _clean_title(custom_title), "custom"
    elif ai_title:
        title, title_src = _clean_title(ai_title), "ai"
    elif first_prompt:
        title, title_src = _clean_title(first_prompt.strip()), "prompt"
    else:
        title, title_src = "(untitled)", "none"

    # Cost: price each model's usage at its own rate; sum the priced ones. A
    # session is only fully priced if every model that ran is in PRICING. We also
    # keep the per-component split (input / output / cache read / cache write) so
    # the efficiency rating can see where the spend went.
    cost_by_model, cost, priced_all = {}, 0.0, True
    cost_parts = {"input": 0.0, "output": 0.0, "cache_read": 0.0, "cache_write": 0.0}
    for mdl, u in usage_by_model.items():
        p = model_cost_parts(mdl, u)
        if p is None:
            priced_all = False
            continue
        cost_by_model[mdl] = round(sum(p.values()), 4)
        cost += sum(p.values())
        for k in cost_parts:
            cost_parts[k] += p[k]
    cost = round(cost, 4) if usage_by_model else 0.0
    cost_parts = {k: round(v, 4) for k, v in cost_parts.items()}

    project = project_of(path, cwd)
    sess = {
        "session_id": session_id,
        "internal_id": inner_session_id or session_id,
        "is_subagent": is_subagent,
        "parent_session_id": inner_session_id if is_subagent else None,
        "path": path,
        "slug": slug,
        "project": project,
        "project_label": shorten_home(project),
        "branch": branch,
        "version": version,
        "cost_usd": cost,
        "cost_by_model": cost_by_model,
        "cost_parts": cost_parts,
        "cost_complete": priced_all,
        "start": first_ts,
        "end": last_ts,
        "start_local": start_local.isoformat(),
        "end_local": end_local.isoformat(),
        "start_date": start_local.date(),           # local date (for windowing)
        "end_date": end_local.date(),
        "duration_seconds": int(duration),
        "duration": fmt_duration(duration),
        "prompts": user_prompts,
        "assistant_turns": assistant_turns,
        "messages": user_prompts + assistant_turns,
        "title": title,
        "title_source": title_src,
        "models": sorted(models),
        "tokens": tok,
        "tool_calls": sum(tools.values()),
        "tools": dict(tools),
        "skills": sorted(skills),
        "mcp_servers": sorted(mcps),
        "subagents": subagents,
        "errors": errors,
        "files_edited": sorted(files),
    }
    sess["efficiency"] = session_efficiency(sess)
    return sess


# --------------------------------------------------------------------------- #
# Gathering across all transcripts
# --------------------------------------------------------------------------- #
def transcript_files(projects_dir):
    return sorted(glob.glob(os.path.join(projects_dir, "**", "*.jsonl"),
                            recursive=True))


def _merge_subagents(sessions):
    """Fold each subagent (`agent-*.jsonl`) session into its parent, so a session's
    row reflects the full cost of the work it drove — subagents included — instead
    of scattering that spend across separate rows. Returns the list of sessions to
    report: parents (with subagent usage merged in) plus any orphan subagent whose
    parent isn't present. A subagent links to its parent via `parent_session_id`
    (its transcript's `sessionId` field)."""
    parents = {s["internal_id"]: s for s in sessions if not s["is_subagent"]}
    out = []
    for s in sessions:
        if s["is_subagent"]:
            p = parents.get(s["parent_session_id"])
            if p is not None:
                _fold_into(p, s)
                continue  # absorbed — not a standalone row
            # Orphan (parent outside the scan): keep it visible on its own.
        out.append(s)
    return out


def _fold_into(p, sub):
    """Accumulate one subagent session `sub` into its parent `p` in place, then
    re-grade the parent. Time span is left as the parent's — subagents run within
    it — so only usage/cost/activity roll up."""
    for k in p["tokens"]:
        p["tokens"][k] += sub["tokens"].get(k, 0)
    for k in p["cost_parts"]:
        p["cost_parts"][k] = round(p["cost_parts"][k] + sub["cost_parts"].get(k, 0.0), 4)
    for mdl, c in sub["cost_by_model"].items():
        p["cost_by_model"][mdl] = round(p["cost_by_model"].get(mdl, 0.0) + c, 4)
    p["cost_usd"] = round(p["cost_usd"] + sub["cost_usd"], 4)
    p["cost_complete"] = p["cost_complete"] and sub["cost_complete"]
    p["assistant_turns"] += sub["assistant_turns"]
    p["tool_calls"] += sub["tool_calls"]
    for name, n in sub["tools"].items():
        p["tools"][name] = p["tools"].get(name, 0) + n
    p["errors"] += sub["errors"]
    p["subagents"] += 1
    p["models"] = sorted(set(p["models"]) | set(sub["models"]))
    p["files_edited"] = sorted(set(p["files_edited"]) | set(sub["files_edited"]))
    p["messages"] = p["prompts"] + p["assistant_turns"]
    p["efficiency"] = session_efficiency(p)


def gather(projects_dir, wstart, wend, *, project_filter=None):
    """Return (sessions, skipped): sessions active in [wstart, wend] sorted
    newest-first, with each subagent transcript folded into its parent; `skipped`
    counts transcripts with no datable activity."""
    parsed, skipped = [], 0
    for path in transcript_files(projects_dir):
        s = parse_session(path)
        if s is None:
            skipped += 1
            continue
        parsed.append(s)
    pf = project_filter.lower() if project_filter else None
    sessions = []
    for s in _merge_subagents(parsed):
        if not in_window(s["start_date"], s["end_date"], wstart, wend):
            continue
        if pf and pf not in s["project"].lower():
            continue
        sessions.append(s)
    sessions.sort(key=lambda s: s["start"] or "", reverse=True)
    return sessions, skipped


def _json_safe(s):
    """A JSON-serialisable copy of a session dict (drop the date objects that are
    only used for in-process windowing)."""
    return {k: v for k, v in s.items() if k not in ("start_date", "end_date")}


# --------------------------------------------------------------------------- #
# Rendering (human output)
# --------------------------------------------------------------------------- #
def _title_line(label, start, end):
    if start == end:
        return f"{label}  {start.isoformat()}"
    return f"{label}  {start.isoformat()} → {end.isoformat()}"


def _when(iso_local):
    # 'MM-DD HH:MM' from a local ISO datetime string.
    return iso_local[5:16].replace("T", " ")


def render_table(headers, rows, right_align=frozenset()):
    """Render an aligned monospace table. `right_align` is the set of column
    indexes to right-justify; all other columns are left-justified. Returns the
    header row, a dashed separator, and one line per data row."""
    widths = [len(h) for h in headers]
    for row in rows:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], len(cell))

    def line(cells):
        return "  ".join(
            cells[i].rjust(widths[i]) if i in right_align
            else cells[i].ljust(widths[i]) for i in range(len(cells))).rstrip()

    sep = "-" * (sum(widths) + 2 * (len(widths) - 1))
    return "\n".join([line(headers), sep] + [line(r) for r in rows])


def _list_row(s, rich):
    """The table cells for one session — 5 columns plain, 11 columns with --rich."""
    proj = _ellipsis(s["project_label"].rsplit("/", 1)[-1], 18 if rich else 24)
    if not rich:
        return [_when(s["start_local"]), s["duration"], str(s["prompts"]),
                proj, _ellipsis(s["title"], 60)]
    tk = s["tokens"]
    eff = s.get("efficiency")
    effcell = f"{eff['grade']} {eff['rating']}" if eff else "-"
    marks = ([f"{s['subagents']} sub"] if s["subagents"] else []) \
        + ([f"{s['errors']} err"] if s["errors"] else [])
    if marks:
        effcell += ", " + ", ".join(marks)
    cost = fmt_usd(s["cost_usd"]) + ("" if s["cost_complete"] else "+")
    return [
        _when(s["start_local"]), s["duration"], str(s["prompts"]), proj,
        _ellipsis(s["title"], 22),
        _ellipsis(",".join(short_model(m) for m in s["models"]) or "-", 12),
        f"{human_int(tk['input'])}/{human_int(tk['output'])}",
        f"{human_int(tk['cache_read'])}/{human_int(tk['cache_creation'])}",
        cost, effcell, session_recommendation_brief(s),
    ]


def render_list(sessions, skipped, wstart, wend, *, rich, shown, total,
                project_filter):
    out = [_title_line("Claude sessions", wstart, wend)]
    scope = f"  ({total} session(s)"
    if project_filter:
        scope += f", project ~ {project_filter}"
    if shown < total:
        scope += f"; showing newest {shown}"
    scope += ")"
    out.append(scope)
    out.append("")
    if not sessions:
        out.append("(no sessions active in this window)")
        return "\n".join(out)

    if rich:
        headers = ["When", "Duration", "Prompts", "Project", "Title", "Model",
                   "Input/Output", "Cache Read/Write", "API Cost", "Efficiency",
                   "Recommendation"]
        right = {1, 2, 6, 7, 8}
    else:
        headers = ["When", "Duration", "Prompts", "Project", "Title"]
        right = {1, 2}
    out.append(render_table(headers, [_list_row(s, rich) for s in sessions], right))

    out.append("")
    out.append(f"Total: {total} session(s)"
               + (f", {skipped} skipped (no timestamps)" if skipped else "") + ".")
    if rich:
        out.append("")
        out.append("Legend")
        out.append("  Input/Output      input / output tokens.")
        out.append("  Cache Read/Write  cache read / cache write tokens.")
        out.append("  API Cost          API list-price equivalent (not your "
                   "subscription bill); trailing '+' = a model in the mix was "
                   "unpriced.")
        out.append("  Efficiency        A lean · B moderate · C heavy · D bloated "
                   "— graded on context re-read per turn; a multi-day span drops "
                   "the grade. Trailing counts flag subagents (sub) / api-errors "
                   "(err).")
        out.append("  Recommendation    cost-reduction levers (run `show <id>` for "
                   "full sentences):")
        out.append("      /compact      heavy context re-read per turn — /compact "
                   "at phase boundaries.")
        out.append("      /clear        multi-day span — do it in one sitting or "
                   "/clear between days.")
        out.append("      split N% out  only N% of cost produced output — split "
                   "unrelated tasks into separate sessions.")
        out.append("      lean          nothing to tune.")
    return "\n".join(out)


def aggregate_projects(sessions):
    by = {}
    for s in sessions:
        g = by.setdefault(s["project_label"], {
            "project": s["project_label"], "sessions": 0, "prompts": 0,
            "assistant_turns": 0, "input": 0, "output": 0, "cost_usd": 0.0,
            "models": set()})
        g["sessions"] += 1
        g["prompts"] += s["prompts"]
        g["assistant_turns"] += s["assistant_turns"]
        g["input"] += s["tokens"]["input"]
        g["output"] += s["tokens"]["output"]
        g["cost_usd"] += s["cost_usd"]
        g["models"].update(s["models"])
    rows = list(by.values())
    for g in rows:
        g["models"] = sorted(g["models"])
        g["cost_usd"] = round(g["cost_usd"], 2)
    rows.sort(key=lambda g: (-g["sessions"], g["project"].lower()))
    return rows


def render_projects(rows, wstart, wend):
    out = [_title_line("Sessions per project", wstart, wend), ""]
    if not rows:
        out.append("(no sessions active in this window)")
        return "\n".join(out)
    headers = ["Project", "Sessions", "Prompts", "In", "Out", "API-eq"]
    data = [[_ellipsis(g["project"], 40), str(g["sessions"]), str(g["prompts"]),
             human_int(g["input"]), human_int(g["output"]), fmt_usd(g["cost_usd"])]
            for g in rows]
    widths = [len(h) for h in headers]
    for row in data:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], len(cell))

    def line(cells):
        return "  ".join([cells[0].ljust(widths[0])]
                         + [cells[i].rjust(widths[i]) for i in range(1, len(cells))])

    sep = "-" * (sum(widths) + 2 * (len(widths) - 1))
    out += [line(headers), sep]
    out += [line(r) for r in data]
    out.append(sep)
    out.append(line(["TOTAL", str(sum(g["sessions"] for g in rows)),
                     str(sum(g["prompts"] for g in rows)),
                     human_int(sum(g["input"] for g in rows)),
                     human_int(sum(g["output"] for g in rows)),
                     fmt_usd(sum(g["cost_usd"] for g in rows))]))
    out.append("")
    out.append("API-eq = pay-as-you-go API list price for this usage "
               "(input/output + cache read & write) — NOT your subscription bill.")
    return "\n".join(out)


def render_show(s):
    tk = s["tokens"]
    out = [
        f"Session {s['session_id']}",
        f"  title:     {s['title']}  ({s['title_source']})",
        f"  project:   {s['project_label']}"
        + (f"   [{s['branch']}]" if s["branch"] else ""),
        f"  started:   {s['start_local']}",
        f"  ended:     {s['end_local']}",
        f"  duration:  {s['duration']}",
        f"  activity:  {s['prompts']} prompt(s), {s['assistant_turns']} "
        f"assistant turn(s)"
        + (f", {s['subagents']} subagent(s)" if s["subagents"] else "")
        + (f", {s['errors']} api-error(s)" if s["errors"] else ""),
        f"  models:    {', '.join(s['models']) or '-'}",
        f"  tokens:    in {human_int(tk['input'])}  out {human_int(tk['output'])}"
        f"  cache-read {human_int(tk['cache_read'])}"
        f"  cache-write {human_int(tk['cache_creation'])}",
        f"  api-equiv: {fmt_usd(s['cost_usd'])}  (list price — not your subscription bill)"
        + ("  [partial]" if not s["cost_complete"] else "")
        + ("   " + ", ".join(f"{short_model(m)} {fmt_usd(c)}"
                             for m, c in sorted(s["cost_by_model"].items()))
           if len(s["cost_by_model"]) > 1 else ""),
        f"  version:   {s['version'] or '-'}",
        f"  file:      {shorten_home(s['path'])}",
    ]
    eff = s.get("efficiency")
    if eff:
        out.append(
            f"  efficiency: {eff['grade']} ({eff['rating']}) — "
            f"~{human_int(eff['avg_context_per_turn'])} context/turn, "
            f"{eff['cache_cost_share'] * 100:.0f}% cache / "
            f"{eff['output_cost_share'] * 100:.0f}% output, "
            f"{fmt_usd(eff['cost_per_prompt'])}/prompt")
        for fl in eff["flags"]:
            out.append(f"     ⚠ {fl}")
        for tip in eff["tips"]:
            out.append(f"     → {tip}")
    if s["skills"]:
        out.append(f"  skills:    {', '.join(s['skills'])}")
    if s["mcp_servers"]:
        out.append(f"  mcp:       {', '.join(s['mcp_servers'])}")
    if s["tools"]:
        top = sorted(s["tools"].items(), key=lambda kv: -kv[1])
        out.append("  tools:     "
                   + ", ".join(f"{n}×{c}" for n, c in top))
    if s["files_edited"]:
        out.append(f"  files ({len(s['files_edited'])}):")
        for f in s["files_edited"][:40]:
            out.append(f"    - {shorten_home(f)}")
        if len(s["files_edited"]) > 40:
            out.append(f"    … and {len(s['files_edited']) - 40} more")
    return "\n".join(out)


def render_efficiency(sessions, wstart, wend):
    """A cost-efficiency audit: sessions with usage, ranked by API-equivalent
    cost, each graded, plus consolidated 'habits' tips across the window."""
    out = [_title_line("Session efficiency", wstart, wend)]
    graded = [s for s in sessions if s.get("efficiency")]
    graded.sort(key=lambda s: s["cost_usd"], reverse=True)
    out.append(f"  ({len(graded)} session(s) with usage; sorted by "
               f"API-equivalent cost, worst-graded first on ties)")
    out.append("")
    if not graded:
        out.append("(no sessions with token usage in this window)")
        return "\n".join(out)

    headers = ["Gr", "When", "Dur", "Pr", "API-eq", "Ctx/turn", "Cache", "Rating", "Title"]
    left = {0, 1, 7, 8}
    data = []
    for s in graded:
        e = s["efficiency"]
        data.append([
            e["grade"], _when(s["start_local"]), s["duration"], str(s["prompts"]),
            fmt_usd(s["cost_usd"]), human_int(e["avg_context_per_turn"]),
            f"{e['cache_cost_share'] * 100:.0f}%", e["rating"],
            _ellipsis(s["title"], 32),
        ])
    widths = [len(h) for h in headers]
    for row in data:
        for i, cell in enumerate(row):
            widths[i] = max(widths[i], len(cell))

    def line(cells):
        return "  ".join(cells[i].ljust(widths[i]) if i in left
                         else cells[i].rjust(widths[i]) for i in range(len(cells)))

    sep = "-" * (sum(widths) + 2 * (len(widths) - 1))
    out += [line(headers), sep] + [line(r) for r in data]

    # Consolidated habits: how many sessions are heavy/marathon, plus deduped tips
    # drawn only from sessions that actually tripped a flag.
    n_heavy = sum(1 for s in graded if s["efficiency"]["rating"] in ("heavy", "bloated"))
    n_marathon = sum(1 for s in graded
                     if s["duration_seconds"] >= MARATHON_DAYS * 86400)
    tips = []
    for s in graded:
        if s["efficiency"]["flags"]:
            for tip in s["efficiency"]["tips"]:
                if tip not in tips:
                    tips.append(tip)
    out.append("")
    out.append(f"Habits: {n_heavy}/{len(graded)} session(s) carry heavy context "
               f"per turn; {n_marathon} span {MARATHON_DAYS}+ days.")
    for tip in tips[:3]:
        out.append(f"  • {tip}")
    out.append("")
    out.append("Grade = cost efficiency (context re-read per turn + wall-clock "
               "span), not a judgment of the work. $ is API-equivalent, not your bill.")
    return "\n".join(out)


# --------------------------------------------------------------------------- #
# Config helpers
# --------------------------------------------------------------------------- #
def default_env_file():
    home = os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")
    return os.path.join(home, ".env")


def _env_file_value(key, env_file=None):
    """Value of `key` from the dotenv file, or None. Tolerant parser (skips
    blanks/comments/non KEY=VALUE lines, strips `export` + surrounding quotes)."""
    path = env_file or default_env_file()
    try:
        with open(path, "r", encoding="utf-8") as fh:
            lines = fh.readlines()
    except (OSError, UnicodeDecodeError):
        return None
    for raw in lines:
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("export "):
            line = line[7:].lstrip()
        k, sep, val = line.partition("=")
        if not sep or k.strip() != key:
            continue
        val = val.strip()
        if len(val) >= 2 and val[0] == val[-1] and val[0] in "\"'":
            val = val[1:-1]
        return val or None
    return None


def resolve_projects_dir(explicit=None, env_file=None):
    """Transcript root. Precedence: --projects-dir > $CLAUDE_PROJECTS_DIR (real
    env, then ~/.hermes/.env) > ~/.claude/projects."""
    raw = (explicit or os.environ.get(ENV_DIR)
           or _env_file_value(ENV_DIR, env_file) or DEFAULT_PROJECTS_DIR)
    return os.path.abspath(os.path.expanduser(raw))


# --------------------------------------------------------------------------- #
# Subcommands
# --------------------------------------------------------------------------- #
def _today():
    return date.today()


def _window(args):
    return compute_range(
        _today(),
        period=getattr(args, "period", None),
        days=getattr(args, "days", None),
        start=getattr(args, "start", None),
        end=getattr(args, "end", None),
    )


def _dir(args):
    d = resolve_projects_dir(getattr(args, "projects_dir", None))
    if not os.path.isdir(d):
        raise ClaudeSessionsError(
            f"transcript directory not found: {d} — is Claude Code installed? "
            f"Override with --projects-dir PATH or {ENV_DIR} in ~/.hermes/.env.")
    return d


def do_check(args):
    d = resolve_projects_dir(getattr(args, "projects_dir", None))
    exists = os.path.isdir(d)
    files = transcript_files(d) if exists else []
    project_dirs = ([p for p in os.listdir(d)
                     if os.path.isdir(os.path.join(d, p))] if exists else [])
    if args.json:
        print(json.dumps({
            "projects_dir": d,
            "exists": exists,
            "session_files": len(files),
            "project_dirs": len(project_dirs),
        }, indent=2, ensure_ascii=False))
        return 0 if exists else 1
    if not exists:
        print(f"NOT FOUND — {d}")
        print("  Claude Code transcripts were not found here. Override with "
              f"--projects-dir or set {ENV_DIR} in ~/.hermes/.env.")
        return 1
    print(f"OK — {d}")
    print(f"  session transcripts: {len(files)}")
    print(f"  project directories: {len(project_dirs)}")
    return 0


def do_list(args):
    d = _dir(args)
    wstart, wend = _window(args)
    sessions, skipped = gather(d, wstart, wend, project_filter=args.project)
    # gather() returns newest-first; re-order by cost unless --sort recent. Python's
    # sort is stable, so cost ties keep newest-first.
    if getattr(args, "sort", "cost") == "cost":
        sessions.sort(key=lambda s: s["cost_usd"], reverse=True)
    total = len(sessions)
    limit = args.limit if args.limit and args.limit > 0 else None
    shown = sessions[:limit] if limit else sessions
    if args.json:
        print(json.dumps({
            "range": {"start": wstart.isoformat(), "end": wend.isoformat()},
            "projects_dir": d,
            "project_filter": args.project,
            "total": total,
            "shown": len(shown),
            "skipped": skipped,
            "sessions": [_json_safe(s) for s in shown],
        }, indent=2, ensure_ascii=False))
        return 0
    print(render_list(shown, skipped, wstart, wend, rich=not args.shorten,
                      shown=len(shown), total=total, project_filter=args.project))
    return 0


def do_projects(args):
    d = _dir(args)
    wstart, wend = _window(args)
    sessions, _ = gather(d, wstart, wend, project_filter=args.project)
    rows = aggregate_projects(sessions)
    if args.json:
        print(json.dumps({
            "range": {"start": wstart.isoformat(), "end": wend.isoformat()},
            "projects_dir": d,
            "total_sessions": sum(g["sessions"] for g in rows),
            "projects": rows,
        }, indent=2, ensure_ascii=False))
        return 0
    print(render_projects(rows, wstart, wend))
    return 0


def do_efficiency(args):
    d = _dir(args)
    wstart, wend = _window(args)
    sessions, _ = gather(d, wstart, wend, project_filter=args.project)
    graded = sorted((s for s in sessions if s.get("efficiency")),
                    key=lambda s: s["cost_usd"], reverse=True)
    if args.json:
        print(json.dumps({
            "range": {"start": wstart.isoformat(), "end": wend.isoformat()},
            "projects_dir": d,
            "sessions": [_json_safe(s) for s in graded],
        }, indent=2, ensure_ascii=False))
        return 0
    print(render_efficiency(sessions, wstart, wend))
    return 0


def find_session(projects_dir, sid):
    """Locate a transcript by exact session-id (filename stem) or unique prefix."""
    matches = [p for p in transcript_files(projects_dir)
               if os.path.splitext(os.path.basename(p))[0] == sid]
    if not matches:
        matches = [p for p in transcript_files(projects_dir)
                   if os.path.basename(p).startswith(sid)]
    if not matches:
        raise ClaudeSessionsError(f"no session found matching id: {sid}")
    if len(matches) > 1:
        ids = ", ".join(os.path.splitext(os.path.basename(p))[0] for p in matches[:6])
        raise ClaudeSessionsError(f"ambiguous id '{sid}' matches multiple sessions: {ids}")
    return matches[0]


def search_sessions(projects_dir, query, *, project_filter=None):
    """All sessions whose title, slug, project path, or id contains `query`
    (case-insensitive), newest first. Ignores time window — searches everything."""
    q = query.lower()
    pf = project_filter.lower() if project_filter else None
    out = []
    for path in transcript_files(projects_dir):
        s = parse_session(path)
        if s is None:
            continue
        if pf and pf not in s["project"].lower():
            continue
        hay = " ".join([s["title"], s["slug"] or "", s["project"],
                        s["session_id"]]).lower()
        if q in hay:
            out.append(s)
    out.sort(key=lambda s: s["start"] or "", reverse=True)
    return out


def do_find(args):
    d = _dir(args)
    matches = search_sessions(d, args.query, project_filter=args.project)
    total = len(matches)
    limit = args.limit if args.limit and args.limit > 0 else None
    shown = matches[:limit] if limit else matches
    if args.json:
        print(json.dumps({
            "query": args.query,
            "projects_dir": d,
            "total": total,
            "shown": len(shown),
            "sessions": [_json_safe(s) for s in shown],
        }, indent=2, ensure_ascii=False))
        return 0
    out = [f"Sessions matching '{args.query}'  ({total} match(es)"
           + (f"; showing newest {len(shown)}" if len(shown) < total else "") + ")",
           ""]
    if not shown:
        out.append("(no sessions match — try a shorter query, or check --projects-dir)")
    for s in shown:
        proj = _ellipsis(s["project_label"].rsplit("/", 1)[-1], 20)
        out.append(f"{_when(s['start_local'])}  {s['duration']:>6}  {proj:<20}  "
                   f"{_ellipsis(s['title'], 50)}")
        out.append(f"          id {s['session_id']}"
                   + (f"   slug {s['slug']}" if s["slug"] else ""))
    print("\n".join(out))
    return 0


def do_show(args):
    d = _dir(args)
    path = find_session(d, args.session_id)
    s = parse_session(path)
    if s is None:
        raise ClaudeSessionsError(
            f"session transcript could not be parsed: {shorten_home(path)}")
    # For a parent session, fold in its subagent (`agent-*.jsonl`) transcripts so
    # `show` matches the merged figures `list` reports.
    if not s["is_subagent"]:
        for ap in transcript_files(d):
            if not os.path.basename(ap).startswith("agent-"):
                continue
            sub = parse_session(ap)
            if sub and sub["is_subagent"] and sub["parent_session_id"] == s["internal_id"]:
                _fold_into(s, sub)
    if args.json:
        print(json.dumps(_json_safe(s), indent=2, ensure_ascii=False))
        return 0
    print(render_show(s))
    return 0


# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def _add_window_args(p):
    g = p.add_mutually_exclusive_group()
    g.add_argument("--period", choices=PERIODS, help="named window (default this-week)")
    g.add_argument("--days", type=int, help="last N days (inclusive of today)")
    p.add_argument("--start", help="explicit start date YYYY-MM-DD (with --end)")
    p.add_argument("--end", help="explicit end date YYYY-MM-DD (with --start)")
    p.add_argument("--project", help="only sessions whose project path contains "
                                     "this substring (case-insensitive)")
    p.add_argument("--projects-dir", help=f"transcript root (overrides ${ENV_DIR})")
    p.add_argument("--json", action="store_true", help="machine-readable output")


def build_parser():
    p = argparse.ArgumentParser(
        prog="claude_sessions",
        description="List your Claude Code sessions for any time window.")
    sub = p.add_subparsers(dest="cmd")

    chk = sub.add_parser("check", help="verify the transcript root + counts")
    chk.add_argument("--projects-dir", help=f"transcript root (overrides ${ENV_DIR})")
    chk.add_argument("--json", action="store_true", help="machine-readable output")

    lst = sub.add_parser("list", help="sessions active in a window (default)")
    _add_window_args(lst)
    lst.add_argument("--sort", choices=("cost", "recent"), default="cost",
                     help="row order: 'cost' = most expensive first (default), "
                          "'recent' = newest first")
    lst.add_argument("--shorten", action="store_true",
                     help="compact 5-column view (When, Duration, Prompts, "
                          "Project, Title) — omits tokens, cost, efficiency")
    lst.add_argument("--rich", action="store_true",
                     help="deprecated: the full table is now the default "
                          "(this flag is accepted but has no effect)")
    lst.add_argument("--limit", type=int, default=100,
                     help="max sessions to show (newest first; default 100, 0=all)")

    prj = sub.add_parser("projects", help="per-project session/prompt/token counts")
    _add_window_args(prj)

    eff = sub.add_parser("efficiency",
                         help="grade sessions by cost efficiency + suggest habits")
    _add_window_args(eff)

    fnd = sub.add_parser("find", help="search sessions by title / slug / project (all time)")
    fnd.add_argument("query", help="text to match in title, slug, project path, or id")
    fnd.add_argument("--project", help="also require the project path to contain this substring")
    fnd.add_argument("--limit", type=int, default=50,
                     help="max matches to show (newest first; default 50, 0=all)")
    fnd.add_argument("--projects-dir", help=f"transcript root (overrides ${ENV_DIR})")
    fnd.add_argument("--json", action="store_true", help="machine-readable output")

    shw = sub.add_parser("show", help="deep dive on one session by id (or prefix)")
    shw.add_argument("session_id", help="session id (filename stem) or unique prefix")
    shw.add_argument("--projects-dir", help=f"transcript root (overrides ${ENV_DIR})")
    shw.add_argument("--json", action="store_true", help="machine-readable output")
    return p


def main(argv=None):
    parser = build_parser()
    args = parser.parse_args(argv)
    try:
        if args.cmd == "check":
            return do_check(args)
        if args.cmd == "projects":
            return do_projects(args)
        if args.cmd == "efficiency":
            return do_efficiency(args)
        if args.cmd == "find":
            return do_find(args)
        if args.cmd == "show":
            return do_show(args)
        if args.cmd in (None, "list"):
            if args.cmd is None:  # default subcommand: list, this-week
                args = parser.parse_args(["list"])
            return do_list(args)
        parser.error(f"unknown command {args.cmd}")
    except ClaudeSessionsError as e:
        print(f"error: {e}", file=sys.stderr)
        return 1
    except KeyboardInterrupt:
        return 130


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 CodeCodexUnverifiedInstall
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