Skip to content

gerodp/hermes-productivity-skills / reports/weekly-report

weekly-report

Verified

One weekly report combining Super Productivity time per project/task (with week-over-week deltas), Obsidian notes of the week grouped by folder (with key bullet points), emails sent this week, calendar events, git commits per repo, Claude Code sessions per project, and Umami page visits vs last week — with a skimmable TL;DR summary at the top.

scripts/test_weekly_report.py

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

The child-running helpers (`run_json` for python siblings, `run_cli_json` for
emailops-cli) are monkeypatched to return canned JSON shaped like the real
`--json` output, so these tests are hermetic and fast.

Run:  python3 test_weekly_report.py
"""
import argparse
import os
import tempfile
import unittest
from unittest.mock import patch
from datetime import date, datetime

import weekly_report as wr


# Canned child outputs ------------------------------------------------------ #
SP_JSON = {
    "range": {"start": "2026-06-22", "end": "2026-06-26"},
    "projects": [
        {"project": "Contoso", "ms": 16200000, "hours": 4.5,
         "ms_prev": 10800000, "hours_prev": 3.0},
        {"project": "Internal R&D", "ms": 10800000, "hours": 3.0,
         "ms_prev": 0, "hours_prev": 0.0},
    ],
    "range_prev": {"start": "2026-06-15", "end": "2026-06-21"},
    "total_ms_prev": 10800000,
    "tasks": [
        {"title": "Plan IA", "project": "Contoso", "ms": 16200000, "hours": 4.5},
        {"title": "Research", "project": "Internal R&D", "ms": 10800000, "hours": 3.0},
    ],
    "total_ms": 27000000,
}

UMAMI_JSON = {
    "range": {"start": "2026-06-22", "end": "2026-06-26"},
    "sites": [
        {"site_id": "blog-uuid-1", "name": "blog.example.com", "domain": "blog.example.com",
         "visitors": 4415, "visitors_prev": 4000,
         "visits": 5680, "visits_prev": 5200,
         "pageviews": 15171, "pageviews_prev": 12000, "bounce_pct": 62.8},
    ],
}

NOTES_LIST = {
    "vault": "/tmp/vault", "count": 2, "by": "modified",
    "notes": [
        {"rel": "Daily/Mon.md", "name": "Mon", "modified": "2026-06-22",
         "created": "2026-06-22", "size": 120},
        {"rel": "Ideas.md", "name": "Ideas", "modified": "2026-06-25",
         "created": "2026-06-01", "size": 60},
    ],
}
NOTE_BODIES = {
    "Daily/Mon.md": "Reviewed the PR and shipped the fix.",
    "Ideas.md": "x" * 5000,  # long → should be truncated
}


def _ts(y, m, d, hh=12):
    return int(datetime(y, m, d, hh, 0, 0).timestamp())


# Sent emails: two inside the 2026-06-22..24 window, one outside (06-10).
SENT_EMAILS = [
    {"id": "e1", "timestamp": _ts(2026, 6, 24), "recipients": ["b@y.com"],
     "subject": "Re: foo", "snippet": "..."},
    {"id": "e2", "timestamp": _ts(2026, 6, 23), "recipients": ["a@x.com"],
     "subject": "Hi", "snippet": "hello"},
    {"id": "e3", "timestamp": _ts(2026, 6, 10), "recipients": ["c@z.com"],
     "subject": "Old", "snippet": "old"},
]
DOCTOR = {"ok": True, "accountsEnabled": 5, "emailCount": 90106}


CAL_JSON = {
    "range": {"start": "2026-06-22", "end": "2026-06-26"},
    "count": 2,
    "events": [
        {"id": "e1", "summary": "Standup", "day": "2026-06-22",
         "start_local": "09:00", "end_local": "09:15", "all_day": False,
         "location": "Zoom"},
        {"id": "e2", "summary": "Offsite", "day": "2026-06-24",
         "start_local": None, "end_local": None, "all_day": True, "location": ""},
    ],
}


GIT_JSON = {
    "range": {"start": "2026-06-22", "end": "2026-06-28"},
    "root": "/tmp/CTO", "authors": ["me@x.com"], "total": 3,
    "repos": [
        {"repo": "hermes", "path": "/tmp/CTO/hermes", "count": 2,
         "insertions": 40, "deletions": 5, "files": 3, "commits": [
             {"short": "aaa1111", "date": "2026-06-24", "subject": "add git section"},
             {"short": "bbb2222", "date": "2026-06-23", "subject": "fix bug"}]},
        {"repo": "site", "path": "/tmp/CTO/site", "count": 1,
         "insertions": 10, "deletions": 0, "files": 1, "commits": [
             {"short": "ccc3333", "date": "2026-06-22", "subject": "tweak"}]},
    ],
    "errors": [],
}


# claude-sessions `list --json`: three sessions across two projects, one skipped.
SESSIONS_LIST = {
    "range": {"start": "2026-06-22", "end": "2026-06-28"},
    "projects_dir": "/tmp/.claude/projects", "total": 3, "shown": 3, "skipped": 1,
    "sessions": [
        {"session_id": "s1", "project_label": "~/CTO/hermes",
         "title": "Wire weekly report", "start_local": "2026-06-24T10:00:00+02:00",
         "duration": "1h2m", "prompts": 5, "cost_usd": 12.5,
         "models": ["claude-opus-4-8"], "efficiency": {"grade": "B", "rating": "moderate"}},
        {"session_id": "s2", "project_label": "~/CTO/hermes",
         "title": "Fix parser bug", "start_local": "2026-06-23T09:00:00+02:00",
         "duration": "20m", "prompts": 2, "cost_usd": 3.0,
         "models": ["claude-opus-4-8"], "efficiency": {"grade": "A", "rating": "lean"}},
        {"session_id": "s3", "project_label": "~/CTO/site",
         "title": "Tweak CSS", "start_local": "2026-06-22T14:00:00+02:00",
         "duration": "15m", "prompts": 1, "cost_usd": 1.25,
         "models": ["claude-opus-4-8"], "efficiency": {"grade": "A", "rating": "lean"}},
    ],
}


def fake_run_json(script, args, env=None):
    base = os.path.basename(script)
    sub = args[0] if args else ""
    if base == "sp_report.py" and sub == "projects":
        return dict(SP_JSON)
    if base == "umami_report.py" and sub == "report":
        return dict(UMAMI_JSON)
    if base == "obsidian_notes.py" and sub == "list":
        return dict(NOTES_LIST)
    if base == "obsidian_notes.py" and sub == "show":
        # The orchestrator prefixes "./" so a leading-dash filename can't be
        # parsed as an option — normalise it away like the child would.
        rel = os.path.normpath(args[1])
        return {"rel": rel, "body": NOTE_BODIES.get(rel, ""), "content": ""}
    if base == "calendar_agenda.py" and sub == "agenda":
        return dict(CAL_JSON)
    if base == "git_report.py" and sub == "commits":
        return dict(GIT_JSON)
    if base == "claude_sessions.py" and sub == "list":
        return dict(SESSIONS_LIST)
    return {"error": f"unexpected child call: {base} {sub}"}


def fake_run_cli_json(cmd, env=None):
    if cmd[:2] == ["emailops-cli", "emails"]:
        return {"data": list(SENT_EMAILS)}
    if cmd[:2] == ["emailops-cli", "doctor"]:
        return {"data": dict(DOCTOR)}
    return {"error": f"unexpected cli: {cmd}"}


def make_args(**over):
    """A namespace with gather's defaults, overridable per test. env_file points
    at a nonexistent path so build_child_env stays hermetic."""
    base = dict(period=None, days=None, start=None, end=None, by="modified",
                max_notes=40, note_chars=2000, max_emails=200, exclude=None,
                exclude_events=None, text=False,
                env_file="/nonexistent.env", sp_script="sp_report.py",
                obsidian_script="obsidian_notes.py", umami_script="umami_report.py",
                calendar_script="calendar_agenda.py", git_script="git_report.py",
                sessions_script="claude_sessions.py",
                emailops_cli="emailops-cli")
    base.update(over)
    return argparse.Namespace(**base)


class TestWindows(unittest.TestCase):
    TODAY = date(2026, 6, 24)  # Wednesday

    def test_this_week_capped(self):
        self.assertEqual(wr.compute_range(self.TODAY, period="this-week"),
                         (date(2026, 6, 22), date(2026, 6, 24)))

    def test_days(self):
        self.assertEqual(wr.compute_range(self.TODAY, days=3),
                         (date(2026, 6, 22), date(2026, 6, 24)))

    def test_explicit(self):
        self.assertEqual(
            wr.compute_range(self.TODAY, start="2026-06-01", end="2026-06-07"),
            (date(2026, 6, 1), date(2026, 6, 7)))

    def test_half_open(self):
        with self.assertRaises(wr.WeeklyError):
            wr.compute_range(self.TODAY, start="2026-06-01")

    def test_window_args(self):
        self.assertEqual(wr.window_args(date(2026, 6, 22), date(2026, 6, 24)),
                         ["--start", "2026-06-22", "--end", "2026-06-24"])


class TestSiblingPaths(unittest.TestCase):
    def test_resolves_repo_scripts(self):
        for key in ("sp", "obsidian", "umami"):
            self.assertTrue(os.path.exists(wr.sibling_script(key)),
                            f"missing sibling for {key}: {wr.sibling_script(key)}")

    def test_override_used(self):
        self.assertEqual(wr.sibling_script("sp", "/x/y.py"), "/x/y.py")


class TestEnvFile(unittest.TestCase):
    def test_parses_export_quotes_and_skips_noise(self):
        with tempfile.NamedTemporaryFile("w", suffix=".env", delete=False) as fh:
            fh.write("# comment\n")
            fh.write("export SP_DATA_FILE=/a/b.json\n")
            fh.write('OBSIDIAN_VAULT="/c/d e"\n')
            fh.write("UMAMI_PASSWORD='p#ss:word'\n")
            fh.write("this is not a kv line\n")
            fh.write("\n")
            path = fh.name
        try:
            env = wr.load_env_file(path)
        finally:
            os.unlink(path)
        self.assertEqual(env["SP_DATA_FILE"], "/a/b.json")
        self.assertEqual(env["OBSIDIAN_VAULT"], "/c/d e")
        self.assertEqual(env["UMAMI_PASSWORD"], "p#ss:word")  # # not a comment here
        self.assertNotIn("this", env)

    def test_missing_file_is_empty(self):
        self.assertEqual(wr.load_env_file("/no/such/file.env"), {})

    def test_build_child_env_backfills_only_missing(self):
        with tempfile.TemporaryDirectory() as d:
            path = os.path.join(d, "x.env")
            with open(path, "w", encoding="utf-8") as fh:
                fh.write("SP_DATA_FILE=/from/file.json\nOBSIDIAN_VAULT=/vault\n")
            # patch.dict snapshots os.environ and fully restores it on exit,
            # so this test never leaks or clobbers the real environment.
            with patch.dict(os.environ, {"SP_DATA_FILE": "/from/real/env.json"},
                            clear=False):
                os.environ.pop("OBSIDIAN_VAULT", None)
                env = wr.build_child_env(path)
        self.assertEqual(env["SP_DATA_FILE"], "/from/real/env.json")  # real wins
        self.assertEqual(env["OBSIDIAN_VAULT"], "/vault")             # file backfills


class TestChildPython(unittest.TestCase):
    def test_resolves_an_ssl_capable_interpreter(self):
        wr._CHILD_PY = None  # reset cache
        py = wr.child_python()
        self.assertTrue(py)
        # The test runner's environment has SSL, so the chosen one must too.
        self.assertTrue(wr._imports_ssl(py))


class TestRunCliJson(unittest.TestCase):
    def test_missing_cli_is_error(self):
        out = wr.run_cli_json(["definitely-not-a-real-cli-xyz", "doctor"])
        self.assertIn("error", out)
        self.assertIn("not found", out["error"])


class TestEmails(unittest.TestCase):
    def setUp(self):
        self._orig = wr.run_cli_json
        wr.run_cli_json = fake_run_cli_json

    def tearDown(self):
        wr.run_cli_json = self._orig

    def test_filters_to_window(self):
        out = wr.gather_emails(date(2026, 6, 22), date(2026, 6, 24),
                               max_emails=200)
        ids = [e["id"] for e in out["emails"]]
        self.assertEqual(out["count"], 2)
        self.assertEqual(ids, ["e2", "e1"])         # sorted by date asc
        self.assertNotIn("e3", ids)                  # 06-10 outside window
        self.assertEqual(out["emails"][0]["to"], ["a@x.com"])

    def test_truncation_flag(self):
        # Cap below the number of in-window-or-newer rows → possibly_truncated.
        out = wr.gather_emails(date(2026, 6, 1), date(2026, 6, 30), max_emails=3)
        self.assertTrue(out.get("possibly_truncated"))

    def test_error_passthrough(self):
        wr.run_cli_json = lambda cmd, env=None: {"error": "emailops-cli not found on PATH"}
        out = wr.gather_emails(date(2026, 6, 22), date(2026, 6, 24))
        self.assertIn("error", out)


class TestBundle(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_assembles_all_sections(self):
        b = wr.build_bundle(make_args(period="this-week"), today=date(2026, 6, 24))
        self.assertEqual(b["range"]["start"], "2026-06-22")
        self.assertEqual(b["projects"]["projects"][0]["project"], "Contoso")
        self.assertEqual(b["visits"]["sites"][0]["visitors"], 4415)
        self.assertEqual(b["notes"]["count"], 2)
        self.assertEqual(b["emails"]["count"], 2)
        self.assertEqual(b["calendar"]["count"], 2)
        self.assertEqual(b["calendar"]["events"][0]["summary"], "Standup")
        self.assertEqual(b["git"]["total"], 3)
        self.assertEqual(b["git"]["repos"][0]["repo"], "hermes")
        # Claude Code sessions grouped by project, most sessions first.
        self.assertEqual(b["sessions"]["total_sessions"], 3)
        self.assertEqual(b["sessions"]["projects"][0]["project"], "hermes")
        self.assertEqual(b["sessions"]["projects"][0]["sessions"], 2)
        self.assertEqual(b["errors"], [])

    def test_note_bodies_fetched_and_truncated(self):
        b = wr.build_bundle(make_args(note_chars=100), today=date(2026, 6, 24))
        notes = {n["rel"]: n for n in b["notes"]["notes"]}
        self.assertIn("shipped the fix", notes["Daily/Mon.md"]["body"])
        self.assertFalse(notes["Daily/Mon.md"]["truncated"])
        self.assertTrue(notes["Ideas.md"]["truncated"])

    def test_max_notes_cap_reported(self):
        b = wr.build_bundle(make_args(max_notes=1), today=date(2026, 6, 24))
        self.assertEqual(len(b["notes"]["notes"]), 1)
        self.assertEqual(b["notes"]["dropped"], 1)

    def test_excluded_folder_dropped_from_notes(self):
        # NOTES_LIST has Daily/Mon.md and Ideas.md; excluding "Daily" drops Mon.
        b = wr.build_bundle(make_args(exclude="Daily"), today=date(2026, 6, 24))
        rels = [n["rel"] for n in b["notes"]["notes"]]
        self.assertNotIn("Daily/Mon.md", rels)
        self.assertIn("Ideas.md", rels)
        self.assertEqual(b["notes"]["excluded"], 1)

    def test_graceful_degradation(self):
        def partial(script, args, env=None):
            if os.path.basename(script) == "umami_report.py":
                return {"error": "missing environment variable(s): UMAMI_URL"}
            return fake_run_json(script, args, env)
        wr.run_json = partial
        b = wr.build_bundle(make_args(), today=date(2026, 6, 24))
        self.assertIn("error", b["visits"])
        self.assertTrue(any(e.startswith("visits:") for e in b["errors"]))
        self.assertNotIn("error", b["projects"])
        self.assertEqual(b["emails"]["count"], 2)   # other sections still present


class TestHtml(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_html_written_in_one_process(self):
        import tempfile
        with tempfile.TemporaryDirectory() as d:
            out = os.path.join(d, "report.html")
            rc = wr.do_html(make_args(days=7, output=out, title="T"))
            self.assertEqual(rc, 0)
            html = open(out, encoding="utf-8").read()
        self.assertTrue(html.startswith("<!DOCTYPE html>"))
        self.assertIn("Contoso", html)          # projects rendered
        self.assertIn("Git activity", html)     # git section rendered

    def test_bad_output_path_raises_weekly_error(self):
        with self.assertRaises(wr.WeeklyError):
            wr.do_html(make_args(days=7, output="/no/such/dir/x.html", title="T"))


class TestMarkdownCommand(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

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

    def test_markdown_renders_emails_and_site_names_verbatim(self):
        # Children are faked, so no real transcripts/network are touched.
        with patch.dict(os.environ, {}, clear=True):
            rc, out, err = self._run([
                "markdown", "--start", "2026-06-22", "--end", "2026-06-24",
                "--env-file", "/nonexistent.env"])
        self.assertEqual(rc, 0)
        # The real email row and site name must be present (not a placeholder).
        self.assertIn("Re: foo", out)                 # SENT_EMAILS subject
        self.assertIn("blog.example.com", out)        # UMAMI_JSON site name
        self.assertIn("blog-uuid-1", out)             # site id
        self.assertNotIn("see source", out)
        self.assertNotIn("included in bundle", out)


class TestExclude(unittest.TestCase):
    def test_split_folders(self):
        self.assertEqual(wr._split_folders("Notion/Personal, Archive/ ,"),
                         ["Notion/Personal", "Archive"])
        self.assertEqual(wr._split_folders(None), [])

    def test_is_excluded_matches_whole_components(self):
        ex = ["Notion/Personal"]
        self.assertTrue(wr.is_excluded("Notion/Personal", ex))
        self.assertTrue(wr.is_excluded("Notion/Personal/Diary.md", ex))
        self.assertFalse(wr.is_excluded("Notion/PersonalStuff.md", ex))  # not a subfolder
        self.assertFalse(wr.is_excluded("Work/Notes.md", ex))

    def test_resolve_precedence_cli_env_dotenv(self):
        none = "/nonexistent.env"
        with patch.dict(os.environ, {}, clear=False):
            os.environ.pop(wr.EXCLUDE_ENV, None)
            # CLI wins
            self.assertEqual(
                wr.resolve_excludes(argparse.Namespace(exclude="A,B"), env_file=none),
                ["A", "B"])
            # env fallback when no CLI
            os.environ[wr.EXCLUDE_ENV] = "Notion/Personal"
            self.assertEqual(
                wr.resolve_excludes(argparse.Namespace(exclude=None), env_file=none),
                ["Notion/Personal"])

    def test_gather_notes_filters_and_counts(self):
        def stub(script, args, env=None):
            if args and args[0] == "list":
                return {"notes": [
                    {"rel": "Work/A.md", "name": "A", "modified": "x",
                     "created": "y", "size": 1},
                    {"rel": "Notion/Personal/Diary.md", "name": "Diary",
                     "modified": "x", "created": "y", "size": 1},
                ]}
            if args and args[0] == "show":
                return {"rel": args[1], "body": "body", "content": ""}
            return {"error": "unexpected"}
        old = wr.run_json
        wr.run_json = stub
        try:
            out = wr.gather_notes("obsidian_notes.py", date(2026, 6, 22),
                                  date(2026, 6, 28), exclude=["Notion/Personal"])
        finally:
            wr.run_json = old
        self.assertEqual([n["rel"] for n in out["notes"]], ["Work/A.md"])
        self.assertEqual(out["count"], 1)
        self.assertEqual(out["excluded"], 1)


class TestCalendarExclude(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_event_excluded_substring_ci(self):
        ex = ["Dentista", "Fisio"]
        self.assertTrue(wr.event_excluded("Revisión Dentista- Clínica Sol", ex))  # mid-title
        self.assertTrue(wr.event_excluded("fisio 18:00", ex))                     # case-insensitive
        self.assertFalse(wr.event_excluded("Standup", ex))

    def test_build_bundle_excludes_events(self):
        # CAL_JSON has "Standup" and "Offsite"; excluding "Standup" drops it.
        b = wr.build_bundle(make_args(exclude_events="Standup"), today=date(2026, 6, 24))
        summaries = [e["summary"] for e in b["calendar"]["events"]]
        self.assertNotIn("Standup", summaries)
        self.assertIn("Offsite", summaries)
        self.assertEqual(b["calendar"]["excluded"], 1)
        self.assertEqual(b["calendar"]["count"], 1)


class TestSessions(unittest.TestCase):
    def _gather(self, list_out):
        def stub(script, args, env=None):
            if args and args[0] == "list":
                return dict(list_out)
            return {"error": "unexpected"}
        old = wr.run_json
        wr.run_json = stub
        try:
            return wr.gather_sessions("claude_sessions.py", date(2026, 6, 22),
                                      date(2026, 6, 28))
        finally:
            wr.run_json = old

    def test_groups_by_project_and_sums_cost(self):
        out = self._gather(SESSIONS_LIST)
        self.assertEqual(out["total_sessions"], 3)
        self.assertEqual(out["total_cost_usd"], 16.75)   # 12.5 + 3.0 + 1.25
        self.assertEqual(out["skipped"], 1)
        # hermes first (2 sessions), then site (1)
        self.assertEqual([p["project"] for p in out["projects"]], ["hermes", "site"])
        hermes = out["projects"][0]
        self.assertEqual(hermes["sessions"], 2)
        self.assertEqual(hermes["cost_usd"], 15.5)
        # entries sorted by cost desc; grade carried through
        self.assertEqual([e["title"] for e in hermes["entries"]],
                         ["Wire weekly report", "Fix parser bug"])
        self.assertEqual(hermes["entries"][0]["grade"], "B")
        self.assertEqual(hermes["entries"][0]["when"], "2026-06-24 10:00")

    def test_error_passthrough(self):
        old = wr.run_json
        wr.run_json = lambda s, a, env=None: {"error": "transcript directory not found"}
        try:
            out = wr.gather_sessions("claude_sessions.py", date(2026, 6, 22),
                                     date(2026, 6, 28))
        finally:
            wr.run_json = old
        self.assertIn("error", out)

    def test_empty_sessions(self):
        out = self._gather({"sessions": [], "total": 0})
        self.assertEqual(out["total_sessions"], 0)
        self.assertEqual(out["projects"], [])
        self.assertEqual(out["total_cost_usd"], 0)


class TestSummary(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json
        self.bundle = wr.build_bundle(make_args(), today=date(2026, 6, 24))

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_summary_numbers(self):
        s = self.bundle["summary"]
        self.assertEqual(s["hours"], 7.5)          # 4.5 + 3.0
        self.assertEqual(s["projects"], 2)
        self.assertEqual(s["commits"], 3)
        self.assertEqual(s["sessions"], 3)
        self.assertEqual(s["meetings"], 1)          # Offsite is all-day
        self.assertEqual(s["notes"], 2)
        self.assertEqual(s["emails"], 2)
        self.assertEqual(s["visitors"], 4415)

    def test_summary_line_segments(self):
        line = self.bundle["summary"]["line"]
        for token in ("7.5h across 2 project(s)", "3 commit(s) (+50/-5)",
                      "3 Claude session(s)", "1 meeting(s)", "2 note(s)",
                      "2 email(s) sent", "4.4k visitor(s)"):
            self.assertIn(token, line)

    def test_render_text_has_tldr(self):
        out = wr.render_text(self.bundle)
        self.assertIn("TL;DR:", out)
        self.assertIn("7.5h across 2 project(s)", out)

    def test_summary_skips_errored_sections(self):
        def partial(script, args, env=None):
            if os.path.basename(script) == "git_report.py":
                return {"error": "GIT_REPOS_DIR not set"}
            return fake_run_json(script, args, env)
        wr.run_json = partial
        b = wr.build_bundle(make_args(), today=date(2026, 6, 24))
        self.assertNotIn("commit", b["summary"]["line"])
        self.assertNotIn("commits", b["summary"])


class TestVisitsTotals(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json
        self.bundle = wr.build_bundle(make_args(), today=date(2026, 6, 24))

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_text_visits_has_total_row(self):
        out = wr.render_text(self.bundle)
        visits = out.split("VISITS", 1)[1]
        self.assertIn("TOTAL", visits)
        self.assertIn("4,415", visits)   # single site → total equals its visitors

    def test_text_visits_shows_site_id(self):
        out = wr.render_text(self.bundle)
        self.assertIn("[blog-uuid-1]", out)


class TestNoteGrouping(unittest.TestCase):
    def test_note_group_key(self):
        self.assertEqual(wr.note_group("Acme/IA/plan.md"), "Acme")
        self.assertEqual(wr.note_group("Ideas.md"), "(root)")
        self.assertEqual(wr.note_group("A\\B\\c.md"), "A")

    def test_bundle_notes_carry_group_and_text_groups(self):
        rj, rc = wr.run_json, wr.run_cli_json
        wr.run_json, wr.run_cli_json = fake_run_json, fake_run_cli_json
        try:
            b = wr.build_bundle(make_args(), today=date(2026, 6, 24))
            groups = {n["rel"]: n["group"] for n in b["notes"]["notes"]}
            self.assertEqual(groups["Daily/Mon.md"], "Daily")
            self.assertEqual(groups["Ideas.md"], "(root)")
            out = wr.render_text(b)
            notes_section = out.split("NOTES", 1)[1].split("EMAILS", 1)[0]
            self.assertIn("Daily  (1 note(s))", notes_section)
            self.assertIn("(root)  (1 note(s))", notes_section)
        finally:
            wr.run_json, wr.run_cli_json = rj, rc


class TestCalendarError(unittest.TestCase):
    def test_auth_failure_becomes_actionable(self):
        for raw in ("invalid_grant: token expired",
                    "HttpError 401 unauthorized",
                    "not authenticated with Google"):
            msg = wr.friendly_calendar_error(raw)
            self.assertIn("calendar check", msg)
            self.assertIn("re-authenticate", msg.lower())

    def test_opaque_traceback_becomes_actionable(self):
        # A bare traceback first line is useless — rewrite it (most common cause
        # is an expired token).
        msg = wr.friendly_calendar_error("Traceback (most recent call last):")
        self.assertNotIn("Traceback", msg)
        self.assertIn("calendar check", msg)
        self.assertIn("re-authenticate", msg.lower())

    def test_non_auth_error_passthrough_with_hint(self):
        msg = wr.friendly_calendar_error("google_api.py: non-JSON output")
        self.assertIn("non-JSON output", msg)
        self.assertIn("calendar check", msg)

    def test_gather_calendar_rewrites_error(self):
        old = wr.run_json
        wr.run_json = lambda s, a, env=None: {"error": "invalid_grant: token has been expired or revoked"}
        try:
            out = wr.gather_calendar("calendar_agenda.py", date(2026, 6, 22),
                                     date(2026, 6, 28))
        finally:
            wr.run_json = old
        self.assertIn("error", out)
        self.assertIn("credentials are missing or expired", out["error"])
        self.assertIn("calendar check", out["error"])


class TestCompactBody(unittest.TestCase):
    def test_strips_trailing_ws_and_squeezes_blank_lines(self):
        raw = "line one   \n\n\n\n line two\t\n   \nend  "
        self.assertEqual(wr.compact_body(raw), "line one\n\n line two\n\nend")

    def test_preserves_internal_indentation(self):
        # Code/list indentation must survive (only trailing ws is trimmed).
        raw = "def f():\n    return 1\n\n\n- a\n  - nested"
        self.assertEqual(wr.compact_body(raw), "def f():\n    return 1\n\n- a\n  - nested")

    def test_empty_and_whitespace_only(self):
        self.assertEqual(wr.compact_body(""), "")
        self.assertEqual(wr.compact_body("\n\n  \n\t\n"), "")

    def test_shortens_token_footprint(self):
        raw = "a  \n\n\n\n\n\nb"          # lots of blank-line noise
        self.assertLess(len(wr.compact_body(raw)), len(raw))


class TestCheckSmoke(unittest.TestCase):
    """`check` (the orchestrator's fan-out diagnostic), exercised hermetically.

    `do_check` shells out to each sibling's own `check` via `_check_sibling`
    (which spawns `child_python()`) and to emailops via `_check_emailops`. We
    stub BOTH of those seams at the module level so NO real subprocess runs and
    no interpreter is probed — the test only exercises the aggregation logic:
    it returns `0 if any source is ok else 1`.
    """
    def setUp(self):
        self._cs, self._ce = wr._check_sibling, wr._check_emailops

    def tearDown(self):
        wr._check_sibling, wr._check_emailops = self._cs, self._ce

    def _run_check(self):
        import io
        from contextlib import redirect_stdout, redirect_stderr
        out, err = io.StringIO(), io.StringIO()
        with redirect_stdout(out), redirect_stderr(err):
            rc = wr.main(["check", "--env-file", "/nonexistent.env"])
        return rc, out.getvalue(), err.getvalue()

    def test_all_sources_unconfigured_returns_nonzero(self):
        wr._check_sibling = lambda name, script, env: (name, False, "not configured")
        wr._check_emailops = lambda cli, env: ("emailops", False, "not configured")
        rc, out, err = self._run_check()
        self.assertEqual(rc, 1)
        self.assertNotIn("Traceback", out)
        self.assertNotIn("Traceback", err)
        self.assertIn("✗", out)          # every source reported as unavailable

    def test_any_source_ok_returns_zero(self):
        # Only obsidian-notes reports ready; everything else is down.
        def one_ok(name, script, env):
            if name == "obsidian-notes":
                return (name, True, "vault reachable")
            return (name, False, "not configured")
        wr._check_sibling = one_ok
        wr._check_emailops = lambda cli, env: ("emailops", False, "not configured")
        rc, out, err = self._run_check()
        self.assertEqual(rc, 0)
        self.assertNotIn("Traceback", out)
        self.assertNotIn("Traceback", err)
        self.assertIn("✓ obsidian-notes", out)


class TestRenderText(unittest.TestCase):
    def setUp(self):
        self._rj, self._rc = wr.run_json, wr.run_cli_json
        wr.run_json = fake_run_json
        wr.run_cli_json = fake_run_cli_json
        self.bundle = wr.build_bundle(make_args(), today=date(2026, 6, 24))

    def tearDown(self):
        wr.run_json, wr.run_cli_json = self._rj, self._rc

    def test_skeleton_has_all_sections(self):
        out = wr.render_text(self.bundle)
        for token in ("PROJECTS & TIME", "Contoso", "NOTES", "Ideas.md",
                      "EMAILS SENT", "Re: foo", "CALENDAR", "Standup",
                      "all-day", "VISITS", "blog.example.com",
                      "COMMITS", "add git section", "+40/-5",
                      "CLAUDE CODE SESSIONS", "hermes", "Wire weekly report"):
            self.assertIn(token, out)

    def test_delta_formatting(self):
        self.assertEqual(wr._delta(110, 100), "▲10.0%")
        self.assertEqual(wr._delta(90, 100), "▼10.0%")
        self.assertEqual(wr._delta(5, 0), "▲new")
        self.assertEqual(wr._delta(0, 0), "—")

    def test_projects_show_week_over_week_delta(self):
        out = wr.render_text(self.bundle)
        projects = out.split("PROJECTS & TIME", 1)[1].split("NOTES", 1)[0]
        self.assertIn("Δ prev", projects)
        self.assertIn("▲50.0%", projects)   # Contoso 4.5h vs 3.0h prev
        self.assertIn("▲new", projects)      # Internal R&D had 0 prev

    def test_unavailable_section_rendered(self):
        b = dict(self.bundle)
        b["emails"] = {"error": "emailops-cli not found on PATH"}
        out = wr.render_text(b)
        self.assertIn("unavailable: emailops-cli not found", out)


class TestRedactSecrets(unittest.TestCase):
    def test_secret_env_values_masked_in_child_errors(self):
        # A child traceback echoing a secret must not land in the bundle.
        env = {"UMAMI_PASSWORD": "hunter22", "SP_DATA_FILE": "/tmp/x"}
        out = wr._redact_secrets("urllib error: https://u:hunter22@host /tmp/x", env)
        self.assertNotIn("hunter22", out)
        self.assertIn("/tmp/x", out)  # non-secret config values stay readable


if __name__ == "__main__":
    unittest.main(verbosity=2)
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