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/test_claude_sessions.py

View on GitHub
#!/usr/bin/env python3
"""Offline unit tests for claude_sessions — no network, no shared state.

The filesystem is exercised only through tempdirs holding synthetic JSONL
transcripts; parsing runs on those files, so nothing reads the developer's real
~/.claude or ~/.hermes. Run:  python3 test_claude_sessions.py
"""
import io
import json
import os
import tempfile
import unittest
from contextlib import redirect_stderr, redirect_stdout
from datetime import date
from unittest import mock

import claude_sessions as cs


# --------------------------------------------------------------------------- #
# Synthetic transcript builders
# --------------------------------------------------------------------------- #
def _write_jsonl(path, records):
    with open(path, "w", encoding="utf-8") as fh:
        for r in records:
            fh.write(json.dumps(r) + "\n")


def _session_records(*, cwd="/home/u/proj", branch="main", ts_start=None,
                     ts_end=None, prompt="do the thing", ai_title=None,
                     assistant_model="claude-opus-4-8", tool_names=(),
                     files=(), in_tok=100, out_tok=50):
    """A minimal but realistic set of transcript records for one session."""
    recs = []
    if ai_title:
        recs.append({"type": "ai-title", "aiTitle": ai_title})
    # real user prompt
    recs.append({"type": "user", "cwd": cwd, "gitBranch": branch,
                 "version": "2.1.0", "timestamp": ts_start,
                 "message": {"role": "user", "content": prompt}})
    # a meta / slash-command user turn that must NOT count as a prompt or title
    recs.append({"type": "user", "timestamp": ts_start,
                 "message": {"role": "user",
                             "content": "<command-name>/clear</command-name>"}})
    # a tool-result user turn (also not a prompt)
    recs.append({"type": "user", "timestamp": ts_start,
                 "message": {"role": "user",
                             "content": [{"type": "tool_result",
                                          "content": "ok"}]}})
    content = [{"type": "text", "text": "working"}]
    edit_i = 0
    for name in tool_names:
        block = {"type": "tool_use", "name": name, "input": {}}
        if name in cs.EDIT_TOOLS and edit_i < len(files):
            block["input"] = {"file_path": files[edit_i]}
            edit_i += 1
        content.append(block)
    recs.append({"type": "assistant", "cwd": cwd, "timestamp": ts_end,
                 "message": {"role": "assistant", "model": assistant_model,
                             "content": content,
                             "usage": {"input_tokens": in_tok,
                                       "output_tokens": out_tok,
                                       "cache_read_input_tokens": 5,
                                       "cache_creation_input_tokens": 7}}})
    return recs


def _subagent_records(parent_id, *, cwd="/home/u/proj", ts="2026-06-30T08:30:00Z",
                      model="claude-haiku-4-5-20251001", in_tok=50, out_tok=20,
                      tool_names=()):
    """Records for a subagent (`agent-*.jsonl`) transcript: sidechain turns whose
    `sessionId` points at the parent session that spawned them."""
    content = [{"type": "text", "text": "sub working"}]
    for name in tool_names:
        content.append({"type": "tool_use", "name": name, "input": {}})
    return [
        {"type": "user", "isSidechain": True, "sessionId": parent_id, "cwd": cwd,
         "timestamp": ts, "message": {"role": "user", "content": "go"}},
        {"type": "assistant", "isSidechain": True, "sessionId": parent_id,
         "cwd": cwd, "timestamp": ts,
         "message": {"role": "assistant", "id": "submsg", "model": model,
                     "content": content,
                     "usage": {"input_tokens": in_tok, "output_tokens": out_tok,
                               "cache_read_input_tokens": 0,
                               "cache_creation_input_tokens": 0}}},
    ]


class TestWindows(unittest.TestCase):
    def test_this_week_monday_start(self):
        s, e = cs.compute_range(date(2026, 7, 1), period="this-week")
        self.assertEqual((s, e), (date(2026, 6, 29), date(2026, 7, 1)))

    def test_last_week_full_mon_sun(self):
        s, e = cs.compute_range(date(2026, 7, 1), period="last-week")
        self.assertEqual((s, e), (date(2026, 6, 22), date(2026, 6, 28)))

    def test_days_inclusive_of_today(self):
        s, e = cs.compute_range(date(2026, 7, 1), days=7)
        self.assertEqual((s, e), (date(2026, 6, 25), date(2026, 7, 1)))

    def test_explicit_precedence(self):
        s, e = cs.compute_range(date(2026, 7, 1), days=3,
                                start="2026-01-01", end="2026-01-31")
        self.assertEqual((s, e), (date(2026, 1, 1), date(2026, 1, 31)))

    def test_start_without_end_raises(self):
        with self.assertRaises(cs.ClaudeSessionsError):
            cs.compute_range(date(2026, 7, 1), start="2026-01-01")

    def test_days_must_be_positive(self):
        with self.assertRaises(cs.ClaudeSessionsError):
            cs.compute_range(date(2026, 7, 1), days=0)


class TestInWindow(unittest.TestCase):
    W = (date(2026, 6, 29), date(2026, 7, 5))

    def test_inside(self):
        self.assertTrue(cs.in_window(date(2026, 6, 30), date(2026, 6, 30), *self.W))

    def test_overlap_spanning_boundary(self):
        # starts before, ends inside → overlaps
        self.assertTrue(cs.in_window(date(2026, 6, 27), date(2026, 6, 30), *self.W))

    def test_entirely_before(self):
        self.assertFalse(cs.in_window(date(2026, 6, 20), date(2026, 6, 25), *self.W))

    def test_entirely_after(self):
        self.assertFalse(cs.in_window(date(2026, 7, 6), date(2026, 7, 7), *self.W))


class TestParseTs(unittest.TestCase):
    def test_zulu_millis(self):
        dt = cs.parse_ts("2026-06-26T14:34:53.979Z")
        self.assertIsNotNone(dt)
        self.assertEqual(dt.utcoffset().total_seconds(), 0)

    def test_offset(self):
        dt = cs.parse_ts("2026-06-26T14:34:53+02:00")
        self.assertEqual(dt.utcoffset().total_seconds(), 7200)

    def test_garbage_is_none(self):
        self.assertIsNone(cs.parse_ts("not-a-date"))
        self.assertIsNone(cs.parse_ts(None))


class TestUserText(unittest.TestCase):
    def test_string(self):
        self.assertEqual(cs._user_text("hi"), "hi")

    def test_tool_result_is_none(self):
        self.assertIsNone(cs._user_text([{"type": "tool_result", "content": "x"}]))

    def test_text_blocks_joined(self):
        self.assertEqual(
            cs._user_text([{"type": "text", "text": "a"},
                           {"type": "text", "text": "b"}]), "a\nb")

    def test_meta_prefix_detected(self):
        self.assertTrue(cs._is_meta_text("<command-name>/x</command-name>"))
        self.assertTrue(cs._is_meta_text("  <system-reminder>hi"))
        self.assertFalse(cs._is_meta_text("real prompt"))


class TestParseSession(unittest.TestCase):
    def test_full_extraction(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid-1.jsonl")
            _write_jsonl(path, _session_records(
                cwd="/home/u/proj", branch="dev",
                ts_start="2026-06-30T08:00:00.000Z",
                ts_end="2026-06-30T09:30:00.000Z",
                prompt="fix the parser", ai_title="Parser fix",
                tool_names=("Bash", "Edit", "Edit"),
                files=("/a.py", "/b.py"),  # only Edit calls carry files
                in_tok=200, out_tok=80))
            s = cs.parse_session(path)
        self.assertEqual(s["session_id"], "sid-1")
        self.assertEqual(s["project"], "/home/u/proj")
        self.assertEqual(s["branch"], "dev")
        self.assertEqual(s["title"], "Parser fix")
        self.assertEqual(s["title_source"], "ai")
        self.assertEqual(s["prompts"], 1)          # meta + tool_result excluded
        self.assertEqual(s["assistant_turns"], 1)
        self.assertEqual(s["models"], ["claude-opus-4-8"])
        self.assertEqual(s["tokens"]["input"], 200)
        self.assertEqual(s["tokens"]["output"], 80)
        self.assertEqual(s["tool_calls"], 3)
        self.assertEqual(s["tools"], {"Bash": 1, "Edit": 2})
        self.assertEqual(s["files_edited"], ["/a.py", "/b.py"])
        self.assertEqual(s["duration_seconds"], 5400)

    def test_title_falls_back_to_prompt(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid-2.jsonl")
            _write_jsonl(path, _session_records(
                ts_start="2026-06-30T08:00:00Z", ts_end="2026-06-30T08:05:00Z",
                prompt="first line\nsecond line", ai_title=None))
            s = cs.parse_session(path)
        self.assertEqual(s["title"], "first line")
        self.assertEqual(s["title_source"], "prompt")

    def test_no_timestamps_returns_none(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "empty.jsonl")
            _write_jsonl(path, [{"type": "mode", "mode": "default"},
                                {"type": "user",
                                 "message": {"role": "user", "content": "hi"}}])
            self.assertIsNone(cs.parse_session(path))

    def test_malformed_lines_skipped(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid-3.jsonl")
            with open(path, "w", encoding="utf-8") as fh:
                fh.write("not json\n")
                fh.write(json.dumps({"type": "user", "cwd": "/p",
                                     "timestamp": "2026-06-30T08:00:00Z",
                                     "message": {"role": "user",
                                                 "content": "ok"}}) + "\n")
            s = cs.parse_session(path)
        self.assertIsNotNone(s)
        self.assertEqual(s["prompts"], 1)

    def test_cwdless_project_decoded_from_dirname(self):
        with tempfile.TemporaryDirectory() as root:
            sub = os.path.join(root, "-home-u-proj")
            os.makedirs(sub)
            path = os.path.join(sub, "sid-4.jsonl")
            _write_jsonl(path, [{"type": "assistant",
                                 "timestamp": "2026-06-30T08:00:00Z",
                                 "message": {"role": "assistant",
                                             "model": "claude-opus-4-8",
                                             "content": [], "usage": {}}}])
            s = cs.parse_session(path)
        self.assertEqual(s["project"], "/home/u/proj")


class TestGather(unittest.TestCase):
    def _make_store(self, root):
        # two projects, three sessions across different dates
        p1 = os.path.join(root, "-home-u-a")
        p2 = os.path.join(root, "-home-u-b")
        os.makedirs(p1)
        os.makedirs(p2)
        _write_jsonl(os.path.join(p1, "s-in.jsonl"), _session_records(
            cwd="/home/u/a", ts_start="2026-06-30T08:00:00Z",
            ts_end="2026-06-30T09:00:00Z", prompt="in window"))
        _write_jsonl(os.path.join(p2, "s-out.jsonl"), _session_records(
            cwd="/home/u/b", ts_start="2026-06-01T08:00:00Z",
            ts_end="2026-06-01T09:00:00Z", prompt="too old"))
        _write_jsonl(os.path.join(p1, "s-recent.jsonl"), _session_records(
            cwd="/home/u/a", ts_start="2026-07-01T08:00:00Z",
            ts_end="2026-07-01T09:00:00Z", prompt="newest"))

    def test_window_filter_and_sort(self):
        with tempfile.TemporaryDirectory() as root:
            self._make_store(root)
            sessions, skipped = cs.gather(root, date(2026, 6, 29), date(2026, 7, 5))
        ids = [s["session_id"] for s in sessions]
        self.assertEqual(ids, ["s-recent", "s-in"])   # newest first, old excluded
        self.assertEqual(skipped, 0)

    def test_project_filter(self):
        with tempfile.TemporaryDirectory() as root:
            self._make_store(root)
            sessions, _ = cs.gather(root, date(2026, 1, 1), date(2026, 12, 31),
                                    project_filter="/b")
        self.assertEqual([s["session_id"] for s in sessions], ["s-out"])

    def test_projects_aggregation(self):
        with tempfile.TemporaryDirectory() as root:
            self._make_store(root)
            sessions, _ = cs.gather(root, date(2026, 1, 1), date(2026, 12, 31))
            rows = cs.aggregate_projects(sessions)
        by = {r["project"]: r for r in rows}
        self.assertEqual(by["/home/u/a"]["sessions"], 2)
        self.assertEqual(by["/home/u/b"]["sessions"], 1)
        # rows sorted by session count desc → /home/u/a first
        self.assertEqual(rows[0]["project"], "/home/u/a")


class TestStreamingDedup(unittest.TestCase):
    """Claude Code re-emits each streamed assistant response across several JSONL
    lines with the identical final `usage`; usage must be counted once per
    `message.id`, else tokens/cost roughly double."""

    @staticmethod
    def _asst(mid, *, out, cwd="/p"):
        return {"type": "assistant", "cwd": cwd,
                "timestamp": "2026-06-30T08:00:00Z",
                "message": {"role": "assistant", "id": mid,
                            "model": "claude-opus-4-8", "content": [],
                            "usage": {"input_tokens": 100, "output_tokens": out,
                                      "cache_read_input_tokens": 10,
                                      "cache_creation_input_tokens": 0}}}

    def test_duplicate_message_ids_counted_once(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            _write_jsonl(path, [self._asst("m1", out=50)] * 3)  # same id 3x
            s = cs.parse_session(path)
        self.assertEqual(s["assistant_turns"], 1)
        self.assertEqual(s["tokens"]["input"], 100)     # not 300
        self.assertEqual(s["tokens"]["output"], 50)
        self.assertEqual(s["tokens"]["cache_read"], 10)

    def test_distinct_message_ids_accumulate(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            _write_jsonl(path, [self._asst("a", out=10), self._asst("b", out=20)])
            s = cs.parse_session(path)
        self.assertEqual(s["assistant_turns"], 2)
        self.assertEqual(s["tokens"]["output"], 30)
        self.assertEqual(s["tokens"]["input"], 200)

    def test_records_without_id_are_not_deduped(self):
        # No message.id → can't dedupe; each record counts (older transcripts).
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            rec = {"type": "assistant", "cwd": "/p",
                   "timestamp": "2026-06-30T08:00:00Z",
                   "message": {"role": "assistant", "model": "claude-opus-4-8",
                               "content": [],
                               "usage": {"input_tokens": 100, "output_tokens": 0,
                                         "cache_read_input_tokens": 0,
                                         "cache_creation_input_tokens": 0}}}
            _write_jsonl(path, [rec, rec])
            s = cs.parse_session(path)
        self.assertEqual(s["assistant_turns"], 2)
        self.assertEqual(s["tokens"]["input"], 200)


class TestSubagents(unittest.TestCase):
    def test_agent_file_flagged_and_links_parent(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "agent-abc123.jsonl")
            _write_jsonl(path, _subagent_records("parent-sid"))
            s = cs.parse_session(path)
        self.assertTrue(s["is_subagent"])
        self.assertEqual(s["parent_session_id"], "parent-sid")
        self.assertEqual(s["prompts"], 0)               # sidechain turns aren't prompts

    def test_agent_name_records_are_not_subagents(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            recs = [{"type": "agent-name", "agentName": "relabel-a", "sessionId": "sid"},
                    {"type": "agent-name", "agentName": "relabel-b", "sessionId": "sid"}]
            recs += _session_records(ts_start="2026-06-30T08:00:00Z",
                                     ts_end="2026-06-30T09:00:00Z")
            _write_jsonl(path, recs)
            s = cs.parse_session(path)
        self.assertFalse(s["is_subagent"])
        self.assertEqual(s["subagents"], 0)             # relabels, not subagents

    def _store(self, root):
        p = os.path.join(root, "-home-u-proj")
        os.makedirs(p)
        _write_jsonl(os.path.join(p, "parent-sid.jsonl"), _session_records(
            cwd="/home/u/proj", ts_start="2026-06-30T08:00:00Z",
            ts_end="2026-06-30T09:00:00Z", prompt="parent",
            in_tok=100, out_tok=100))
        _write_jsonl(os.path.join(p, "agent-aaa.jsonl"), _subagent_records(
            "parent-sid", cwd="/home/u/proj", in_tok=50, out_tok=20,
            tool_names=("Bash",)))
        _write_jsonl(os.path.join(p, "agent-bbb.jsonl"), _subagent_records(
            "parent-sid", cwd="/home/u/proj", in_tok=10, out_tok=5))
        return p

    def test_subagents_folded_into_parent(self):
        with tempfile.TemporaryDirectory() as root:
            self._store(root)
            sessions, _ = cs.gather(root, date(2026, 6, 29), date(2026, 7, 5))
        self.assertEqual(len(sessions), 1)              # both subagents absorbed
        s = sessions[0]
        self.assertEqual(s["session_id"], "parent-sid")
        self.assertEqual(s["subagents"], 2)
        self.assertEqual(s["tokens"]["input"], 100 + 50 + 10)
        self.assertEqual(s["tokens"]["output"], 100 + 20 + 5)
        self.assertIn("claude-haiku-4-5-20251001", s["models"])  # subagent model
        self.assertIn("claude-opus-4-8", s["models"])            # parent model
        self.assertEqual(s["tools"].get("Bash"), 1)              # subagent tool rolled up

    def test_merged_cost_is_sum_of_parts(self):
        with tempfile.TemporaryDirectory() as root:
            p = self._store(root)
            parent = cs.parse_session(os.path.join(p, "parent-sid.jsonl"))
            sub_a = cs.parse_session(os.path.join(p, "agent-aaa.jsonl"))
            sub_b = cs.parse_session(os.path.join(p, "agent-bbb.jsonl"))
            sessions, _ = cs.gather(root, date(2026, 6, 29), date(2026, 7, 5))
        self.assertAlmostEqual(
            sessions[0]["cost_usd"],
            round(parent["cost_usd"] + sub_a["cost_usd"] + sub_b["cost_usd"], 4),
            places=4)

    def test_orphan_subagent_kept_when_parent_absent(self):
        with tempfile.TemporaryDirectory() as root:
            p = os.path.join(root, "-home-u-proj")
            os.makedirs(p)
            _write_jsonl(os.path.join(p, "agent-lonely.jsonl"),
                         _subagent_records("missing-parent"))
            sessions, _ = cs.gather(root, date(2026, 6, 29), date(2026, 7, 5))
        self.assertEqual(len(sessions), 1)
        self.assertTrue(sessions[0]["is_subagent"])     # left visible on its own


class TestFormat(unittest.TestCase):
    def test_human_int(self):
        self.assertEqual(cs.human_int(500), "500")
        self.assertEqual(cs.human_int(1500), "1.5k")
        self.assertEqual(cs.human_int(2_000_000), "2M")

    def test_fmt_duration(self):
        self.assertEqual(cs.fmt_duration(45), "45s")
        self.assertEqual(cs.fmt_duration(90), "1m")
        self.assertEqual(cs.fmt_duration(3660), "1h1m")
        self.assertEqual(cs.fmt_duration(90000), "1d1h")


class TestCost(unittest.TestCase):
    def test_model_family(self):
        self.assertEqual(cs.model_family("claude-opus-4-8"), "opus")
        self.assertEqual(cs.model_family("claude-haiku-4-5-20251001"), "haiku")
        self.assertEqual(cs.model_family("claude-fable-5"), "fable")
        self.assertIsNone(cs.model_family("<synthetic>"))

    def test_model_cost_input_output(self):
        # Opus: $5/1M in, $25/1M out. 1M in + 1M out = $5 + $25 = $30.
        c = cs.model_cost("claude-opus-4-8",
                          {"input": 1_000_000, "output": 1_000_000,
                           "cache_read": 0, "cw_5m": 0, "cw_1h": 0})
        self.assertAlmostEqual(c, 30.0)

    def test_model_cost_cache_multipliers(self):
        # cache read 0.1×, 5m write 1.25×, 1h write 2× of the $5 input rate.
        c = cs.model_cost("claude-opus-4-8",
                          {"input": 0, "output": 0, "cache_read": 1_000_000,
                           "cw_5m": 1_000_000, "cw_1h": 1_000_000})
        self.assertAlmostEqual(c, 0.5 + 6.25 + 10.0)

    def test_unpriced_model_returns_none(self):
        self.assertIsNone(cs.model_cost("some-future-model", {"input": 100}))

    def test_session_cost_uses_ttl_split(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            _write_jsonl(path, [{
                "type": "assistant", "cwd": "/p",
                "timestamp": "2026-06-30T08:00:00Z",
                "message": {"role": "assistant", "model": "claude-opus-4-8",
                            "content": [],
                            "usage": {"input_tokens": 1_000_000,
                                      "cache_creation_input_tokens": 2_000_000,
                                      "cache_creation": {
                                          "ephemeral_5m_input_tokens": 0,
                                          "ephemeral_1h_input_tokens": 2_000_000}}}}])
            s = cs.parse_session(path)
        # 1M input ($5) + 2M @ 1h-write rate ($10/1M → $20) = $25.
        self.assertAlmostEqual(s["cost_usd"], 25.0, places=2)
        self.assertTrue(s["cost_complete"])


class TestEfficiency(unittest.TestCase):
    @staticmethod
    def _sess(*, turns, cache_read, cost, parts, span_seconds, prompts=5,
              inp=0, out=0):
        return {
            "assistant_turns": turns,
            "tokens": {"input": inp, "output": out,
                       "cache_read": cache_read, "cache_creation": 0},
            "cost_usd": cost, "cost_parts": parts,
            "duration_seconds": span_seconds, "prompts": prompts,
        }

    def test_none_when_no_activity(self):
        self.assertIsNone(cs.session_efficiency(self._sess(
            turns=0, cache_read=0, cost=0.0,
            parts={"input": 0, "output": 0, "cache_read": 0, "cache_write": 0},
            span_seconds=0)))

    def test_lean_session_grade_a(self):
        e = cs.session_efficiency(self._sess(
            turns=10, cache_read=100_000, cost=5.0,
            parts={"input": 0.5, "output": 2.0, "cache_read": 2.0, "cache_write": 0.5},
            span_seconds=3600, inp=1000, out=1000))
        self.assertEqual(e["grade"], "A")
        self.assertEqual(e["rating"], "lean")
        self.assertEqual(e["avg_context_per_turn"], 10_000)
        self.assertEqual(e["flags"], [])

    def test_bloated_marathon_grade_d(self):
        e = cs.session_efficiency(self._sess(
            turns=100, cache_read=40_000_000, cost=100.0,
            parts={"input": 0, "output": 5.0, "cache_read": 90.0, "cache_write": 5.0},
            span_seconds=6 * 86400, prompts=10))
        self.assertEqual(e["grade"], "D")
        self.assertEqual(e["rating"], "bloated")
        self.assertEqual(e["avg_context_per_turn"], 400_000)
        # all three flags trip: heavy context, marathon span, low output share
        self.assertEqual(len(e["flags"]), 3)
        self.assertGreaterEqual(len(e["tips"]), 2)

    def test_span_downgrades_grade(self):
        # Same lean context, but a 2-day span pushes lean(A) → B.
        base = dict(turns=10, cache_read=100_000, cost=5.0,
                    parts={"input": 0.5, "output": 2.0,
                           "cache_read": 2.0, "cache_write": 0.5})
        short = cs.session_efficiency(self._sess(span_seconds=3600, **base))
        marathon = cs.session_efficiency(self._sess(span_seconds=2 * 86400, **base))
        self.assertEqual(short["grade"], "A")
        self.assertEqual(marathon["grade"], "B")
        self.assertTrue(any("wall-clock" in f for f in marathon["flags"]))

    def test_parse_attaches_efficiency_and_parts(self):
        with tempfile.TemporaryDirectory() as root:
            path = os.path.join(root, "sid.jsonl")
            _write_jsonl(path, _session_records(
                ts_start="2026-06-30T08:00:00Z", ts_end="2026-06-30T09:00:00Z",
                in_tok=1000, out_tok=500))
            s = cs.parse_session(path)
        self.assertIn("cost_parts", s)
        self.assertIn("efficiency", s)
        self.assertIsNotNone(s["efficiency"])
        self.assertIn(s["efficiency"]["grade"], list("ABCD"))


class TestCli(unittest.TestCase):
    def _store_with_one(self, root):
        os.makedirs(os.path.join(root, "-home-u-p"))
        _write_jsonl(os.path.join(root, "-home-u-p", "sid-9.jsonl"),
                     _session_records(cwd="/home/u/p",
                                      ts_start="2026-06-30T08:00:00Z",
                                      ts_end="2026-06-30T09:00:00Z",
                                      prompt="hello", ai_title="A title"))

    def _run(self, argv):
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = cs.main(argv)
        return rc, out.getvalue(), err.getvalue()

    def test_check_missing_dir_returns_one(self):
        with mock.patch.dict(os.environ, {}, clear=True):
            missing = os.path.join(tempfile.gettempdir(), "no_such_claude_dir_xyz")
            rc, out, err = self._run(["check", "--projects-dir", missing])
        self.assertEqual(rc, 1)
        self.assertIn("NOT FOUND", out)

    def test_check_json_ok(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["check", "--projects-dir", root, "--json"])
        self.assertEqual(rc, 0)
        payload = json.loads(out)
        self.assertTrue(payload["exists"])
        self.assertEqual(payload["session_files"], 1)

    def test_list_json_contract(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run([
                    "list", "--projects-dir", root, "--json",
                    "--start", "2026-06-29", "--end", "2026-07-05"])
        self.assertEqual(rc, 0)
        payload = json.loads(out)
        self.assertEqual(payload["total"], 1)
        s = payload["sessions"][0]
        self.assertEqual(s["title"], "A title")
        # date objects must have been stripped for JSON serialisation
        self.assertNotIn("start_date", s)

    def test_list_default_period_no_traceback(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["list", "--projects-dir", root])
        self.assertEqual(rc, 0)
        self.assertNotIn("Traceback", out + err)

    def _store_cheap_new_pricey_old(self, root):
        p = os.path.join(root, "-home-u-p")
        os.makedirs(p)
        _write_jsonl(os.path.join(p, "cheap.jsonl"), _session_records(
            cwd="/home/u/p", ts_start="2026-07-02T08:00:00Z",
            ts_end="2026-07-02T08:10:00Z", prompt="cheap", in_tok=10, out_tok=10))
        _write_jsonl(os.path.join(p, "pricey.jsonl"), _session_records(
            cwd="/home/u/p", ts_start="2026-06-30T08:00:00Z",
            ts_end="2026-06-30T08:10:00Z", prompt="pricey",
            in_tok=1_000_000, out_tok=1_000_000))

    def test_list_sorts_by_cost_by_default(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_cheap_new_pricey_old(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run([
                    "list", "--projects-dir", root, "--json",
                    "--start", "2026-06-29", "--end", "2026-07-05"])
        ids = [s["session_id"] for s in json.loads(out)["sessions"]]
        self.assertEqual(ids, ["pricey", "cheap"])   # cost desc, despite cheap newer

    def test_list_sort_recent_flips_order(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_cheap_new_pricey_old(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run([
                    "list", "--projects-dir", root, "--json", "--sort", "recent",
                    "--start", "2026-06-29", "--end", "2026-07-05"])
        ids = [s["session_id"] for s in json.loads(out)["sessions"]]
        self.assertEqual(ids, ["cheap", "pricey"])   # newest first

    def test_show_by_prefix(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["show", "sid-9",
                                          "--projects-dir", root, "--json"])
        self.assertEqual(rc, 0)
        self.assertEqual(json.loads(out)["session_id"], "sid-9")

    def test_find_by_title(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)  # ai title "A title"
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["find", "title",
                                          "--projects-dir", root, "--json"])
        self.assertEqual(rc, 0)
        payload = json.loads(out)
        self.assertEqual(payload["total"], 1)
        self.assertEqual(payload["sessions"][0]["session_id"], "sid-9")

    def test_find_no_match(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["find", "zzz-nope",
                                          "--projects-dir", root])
        self.assertEqual(rc, 0)
        self.assertIn("no sessions match", out)

    def test_efficiency_json_grades_sessions(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run([
                    "efficiency", "--projects-dir", root, "--json",
                    "--start", "2026-06-29", "--end", "2026-07-05"])
        self.assertEqual(rc, 0)
        payload = json.loads(out)
        self.assertEqual(len(payload["sessions"]), 1)
        self.assertIn(payload["sessions"][0]["efficiency"]["grade"], list("ABCD"))

    def test_efficiency_text_no_traceback(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run([
                    "efficiency", "--projects-dir", root,
                    "--start", "2026-06-29", "--end", "2026-07-05"])
        self.assertEqual(rc, 0)
        self.assertIn("Session efficiency", out)
        self.assertIn("Habits:", out)
        self.assertNotIn("Traceback", out + err)

    def test_show_unknown_returns_one(self):
        with tempfile.TemporaryDirectory() as root:
            self._store_with_one(root)
            with mock.patch.dict(os.environ, {}, clear=True):
                rc, out, err = self._run(["show", "nope", "--projects-dir", root])
        self.assertEqual(rc, 1)
        self.assertIn("error:", err)
        self.assertNotIn("Traceback", out + err)


class TestCleanTitle(unittest.TestCase):
    def test_control_chars_and_extra_lines_dropped(self):
        # Titles derive from transcript content — first line only, no escapes.
        self.assertEqual(cs._clean_title("evil\x1b[2J title\nsecond line"),
                         "evil[2J title")
        self.assertEqual(cs._clean_title(""), "(untitled)")
        self.assertEqual(cs._clean_title("\x1b\x07"), "(untitled)")


if __name__ == "__main__":
    unittest.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