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

View on GitHub
#!/usr/bin/env python3
"""weekly-report — one weekly report stitched from the other Hermes skills.

Gathers, in one deterministic step, the data for a weekly report from the
sibling skills in this tap:

    * superproductivity-report  → projects + tasks + time worked this week
    * obsidian-notes            → notes modified/created this week (+ their bodies)
    * umami-report              → site visits this week vs the previous week
    * emailops (emailops-cli)   → emails you sent this week
    * git-report                → commits you authored this week (per repo)
    * claude-sessions           → Claude Code sessions this week, grouped by project

and prints a single combined **JSON bundle** (the default — this tool feeds the
agent, which writes the per-note bullet points and the prose). ``--text`` prints
a human-readable skeleton of the deterministic parts for direct CLI use.

Each source is independent and **degrades gracefully**: if a source isn't
configured (its env vars are missing) or its script errors, that section becomes
an ``{"error": ...}`` entry and the rest of the report is still produced.

Configuration is reused from the source skills (no new vars):
``SP_DATA_FILE``, ``OBSIDIAN_VAULT``, ``UMAMI_URL``/``UMAMI_USERNAME``/
``UMAMI_PASSWORD`` (and ``emailops-cli`` on PATH for the emails section). Hermes
injects a skill's vars when it runs *that* skill, but those don't always reach a
nested subprocess — so this orchestrator also loads ``~/.hermes/.env`` itself and
passes the values down to the children (secrets go via the child environment,
never on the command line).

Windows are computed in **local time** with **Monday-start** weeks, the shared
vocabulary of the report skills. Python standard library only.
"""
from __future__ import annotations

import argparse
import concurrent.futures
import json
import os
import re
import shutil
import subprocess
import sys
from datetime import date, datetime, timedelta

# Relative locations of the sibling skill scripts, from the tap ROOT.
SIBLINGS = {
    "sp": ("productivity", "superproductivity-report", "scripts", "sp_report.py"),
    "obsidian": ("notes", "obsidian-notes", "scripts", "obsidian_notes.py"),
    "umami": ("analytics", "umami-report", "scripts", "umami_report.py"),
    "calendar": ("calendar", "calendar", "scripts", "calendar_agenda.py"),
    "git": ("development", "git-report", "scripts", "git_report.py"),
    "sessions": ("development", "claude-sessions", "scripts", "claude_sessions.py"),
}

# External CLI for the "emails sent this week" section (not a sibling script).
EMAILOPS_CLI = "emailops-cli"

CHILD_TIMEOUT = 120  # seconds per child invocation

# Env vars the child skills read. We backfill these from ~/.hermes/.env when the
# orchestrator's own environment doesn't already carry them. GIT_AUTHOR is
# optional (git-report falls back to `git config user.email`) but backfilled too
# so a configured override reaches the child. CLAUDE_PROJECTS_DIR is optional
# (claude-sessions defaults to ~/.claude/projects) but backfilled so a configured
# override reaches the child.
CHILD_ENV_VARS = ("SP_DATA_FILE", "OBSIDIAN_VAULT",
                  "UMAMI_URL", "UMAMI_USERNAME", "UMAMI_PASSWORD",
                  "GIT_REPOS_DIR", "GIT_AUTHOR", "GIT_EXCLUDE",
                  "CLAUDE_PROJECTS_DIR")

# Optional (undeclared → not prompted): comma-separated Obsidian folder prefixes
# to drop from the notes section. Read from the real env, else from ~/.hermes/.env.
EXCLUDE_ENV = "OBSIDIAN_EXCLUDE"
# Comma-separated substrings; calendar events whose summary contains any of them
# (case-insensitive) are dropped from the calendar section and the meetings count.
CAL_EXCLUDE_ENV = "CALENDAR_EXCLUDE"


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


# --------------------------------------------------------------------------- #
# Choosing the interpreter that runs the python sibling skills
# --------------------------------------------------------------------------- #
def _imports_ssl(py):
    """True if interpreter `py` can import ssl (umami needs working HTTPS)."""
    try:
        r = subprocess.run([py, "-c", "import ssl"],
                           capture_output=True, timeout=15)
        return r.returncode == 0
    except (OSError, subprocess.TimeoutExpired):
        return False


_CHILD_PY = None


# Absolute interpreters that bypass pyenv/venv shims — checked when the PATH
# python lacks SSL (e.g. a pyenv shim pinned to a build with a broken _ssl).
_ABS_PYTHONS = ("/opt/homebrew/bin/python3", "/usr/local/bin/python3",
                "/usr/bin/python3")


def child_python():
    """Interpreter used to run the python sibling skills.

    NOT necessarily ``sys.executable`` / ``python3`` on PATH: under Hermes those
    can be a bundled venv or a pyenv shim pinned to a Python whose ``ssl`` module
    is broken — which makes the umami child fail with "unknown url type: https".
    We therefore probe several candidates (PATH pythons, then absolute Homebrew/
    system pythons that bypass pyenv) and pick the **first one whose ssl imports**.
    Cached after the first call; falls back to the first candidate if none has SSL.
    """
    global _CHILD_PY
    if _CHILD_PY:
        return _CHILD_PY
    candidates = []
    for name in ("python3", "python"):
        p = shutil.which(name)
        if p and p not in candidates:
            candidates.append(p)
    for p in _ABS_PYTHONS:
        if os.path.exists(p) and p not in candidates:
            candidates.append(p)
    if sys.executable and sys.executable not in candidates:
        candidates.append(sys.executable)
    for p in candidates:                       # prefer one with working SSL
        if _imports_ssl(p):
            _CHILD_PY = p
            return p
    _CHILD_PY = candidates[0] if candidates else sys.executable
    return _CHILD_PY


# --------------------------------------------------------------------------- #
# Locating the sibling scripts
# --------------------------------------------------------------------------- #
def tap_root():
    """The tap root: ``<root>/reports/weekly-report/scripts/weekly_report.py``.

    realpath() first so the dev symlink (~/.hermes/skills/reports → repo) lands
    on the real repo path, where the sibling categories live.
    """
    here = os.path.dirname(os.path.realpath(__file__))   # .../scripts
    return os.path.dirname(os.path.dirname(os.path.dirname(here)))


def sibling_script(key, override=None):
    if override:
        return os.path.expanduser(override)
    return os.path.join(tap_root(), *SIBLINGS[key])


# --------------------------------------------------------------------------- #
# Config: load ~/.hermes/.env and build the environment children inherit
# --------------------------------------------------------------------------- #
def default_env_file():
    home = os.environ.get("HERMES_HOME") or os.path.expanduser("~/.hermes")
    return os.path.join(home, ".env")


def load_env_file(path):
    """Parse a dotenv file into a dict. Tolerant: skips blanks, comments, and any
    line that isn't ``KEY=VALUE`` (the file may contain unrelated noise). Strips
    an optional leading ``export`` and matching surrounding quotes. No shell
    expansion is performed."""
    out = {}
    try:
        with open(path, "r", encoding="utf-8") as fh:
            lines = fh.readlines()
    except (OSError, UnicodeDecodeError):
        return out
    for raw in lines:
        line = raw.strip()
        if not line or line.startswith("#"):
            continue
        if line.startswith("export "):
            line = line[7:].lstrip()
        m = re.match(r"([A-Za-z_][A-Za-z0-9_]*)=(.*)$", line)
        if not m:
            continue
        key, val = m.group(1), m.group(2).strip()
        if len(val) >= 2 and val[0] == val[-1] and val[0] in "\"'":
            val = val[1:-1]
        out[key] = val
    return out


def build_child_env(env_file=None):
    """``os.environ`` with any missing CHILD_ENV_VARS backfilled from the dotenv
    file. Real environment values win, so Hermes injection still takes effect."""
    env = dict(os.environ)
    fromfile = load_env_file(env_file or default_env_file())
    for k in CHILD_ENV_VARS:
        if not env.get(k) and fromfile.get(k):
            env[k] = fromfile[k]
    return env


def resolve_excludes(args, env_file=None):
    """Obsidian folder prefixes to drop from the notes section.

    Precedence: ``--exclude`` (CLI, comma-separated) > ``$OBSIDIAN_EXCLUDE`` (real
    env) > ``OBSIDIAN_EXCLUDE`` in ~/.hermes/.env. Undeclared so Hermes never
    prompts for it (gotcha #5) — we read the dotenv ourselves."""
    cli = getattr(args, "exclude", None)
    if cli:
        return _split_folders(cli)
    val = os.environ.get(EXCLUDE_ENV)
    if not val:
        val = load_env_file(env_file or default_env_file()).get(EXCLUDE_ENV)
    return _split_folders(val)


def _split_csv(s):
    """Split a comma-separated string into trimmed, non-empty items (verbatim —
    preserves spaces/accents; unlike _split_folders it doesn't touch slashes)."""
    return [p.strip() for p in (s or "").split(",") if p.strip()]


def resolve_cal_excludes(args, env_file=None):
    """Calendar summary substrings to drop. Precedence: ``--exclude-events`` >
    ``$CALENDAR_EXCLUDE`` (real env) > ``CALENDAR_EXCLUDE`` in ~/.hermes/.env.
    Undeclared, so Hermes never prompts (gotcha #5)."""
    cli = getattr(args, "exclude_events", None)
    if cli:
        return _split_csv(cli)
    val = os.environ.get(CAL_EXCLUDE_ENV)
    if not val:
        val = load_env_file(env_file or default_env_file()).get(CAL_EXCLUDE_ENV)
    return _split_csv(val)


def event_excluded(summary, excludes):
    """True if `summary` contains any excluded substring (case-insensitive)."""
    s = (summary or "").lower()
    return any(x.lower() in s for x in excludes)


# --------------------------------------------------------------------------- #
# Date windows (local time, Monday-start weeks) — shared with the other 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 WeeklyError(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 WeeklyError("--start and --end must be given together")
        s, e = _parse_date(start), _parse_date(end)
        if e < s:
            raise WeeklyError("--end is before --start")
        return s, e

    if days is not None:
        if days < 1:
            raise WeeklyError("--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 WeeklyError(f"unknown period: {period}")

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


def window_args(start, end):
    """The explicit-range flags to pass to a child for [start, end]."""
    return ["--start", start.isoformat(), "--end", end.isoformat()]


# --------------------------------------------------------------------------- #
# Running children (never raises on child failure — returns {"error": ...})
# --------------------------------------------------------------------------- #
def run_json(script, args, env=None):
    """Run ``python3 <script> <args> --json`` and return parsed JSON.

    On a missing script, non-zero exit, timeout, or unparseable output, returns
    ``{"error": "<reason>"}`` instead of raising — so one broken/unconfigured
    source never sinks the whole report.
    """
    if not os.path.exists(script):
        return {"error": f"script not found: {script}"}
    cmd = [child_python(), script] + list(args) + ["--json"]
    try:
        proc = subprocess.run(cmd, capture_output=True, text=True,
                              timeout=CHILD_TIMEOUT, env=env)
    except subprocess.TimeoutExpired:
        return {"error": f"timed out after {CHILD_TIMEOUT}s"}
    except OSError as e:
        return {"error": f"could not run: {e.strerror or e}"}
    if proc.returncode != 0:
        # Some children emit a structured {"error": ...} on stdout even on
        # failure (e.g. the calendar skill) — prefer that message.
        try:
            obj = json.loads(proc.stdout)
            if isinstance(obj, dict) and obj.get("error"):
                return {"error": _redact_secrets(str(obj["error"]), env)}
        except (json.JSONDecodeError, ValueError):
            pass
        line = _redact_secrets(_first_line(proc.stderr), env)
        return {"error": line or f"exit code {proc.returncode}"}
    try:
        return json.loads(proc.stdout)
    except json.JSONDecodeError:
        return {"error": "child produced non-JSON output"}


def run_cli_json(cmd, env=None):
    """Run an external CLI that prints an EmailOps-style ``{ok,data,error}``
    envelope on stdout; return ``{"data": ...}`` or ``{"error": ...}``."""
    exe = cmd[0]
    if shutil.which(exe) is None and not os.path.exists(exe):
        return {"error": f"{exe} not found on PATH"}
    try:
        proc = subprocess.run(cmd, capture_output=True, text=True,
                              timeout=CHILD_TIMEOUT, env=env)
    except subprocess.TimeoutExpired:
        return {"error": f"{exe} timed out after {CHILD_TIMEOUT}s"}
    except OSError as e:
        return {"error": f"could not run {exe}: {e.strerror or e}"}
    try:
        envelope = json.loads(proc.stdout)
    except json.JSONDecodeError:
        return {"error": _first_line(proc.stderr) or f"{exe}: non-JSON output"}
    if not envelope.get("ok"):
        err = envelope.get("error") or {}
        return {"error": err.get("message") or f"{exe}: command failed"}
    return {"data": envelope.get("data")}


def _first_line(text):
    for line in (text or "").splitlines():
        line = line.strip()
        if line:
            # children print "error: <msg>" — drop the prefix for a clean note.
            return line[7:] if line.lower().startswith("error: ") else line
    return ""


_SECRET_KEY_HINTS = ("PASSWORD", "TOKEN", "SECRET", "APIKEY", "API_KEY")


def _redact_secrets(text, env):
    """Mask secret env values in a child's error text — the bundle ends up in
    shareable reports, and an unexpected child traceback could echo one."""
    if not text:
        return text
    for k, v in (env or {}).items():
        if v and len(v) >= 4 and any(h in k.upper() for h in _SECRET_KEY_HINTS):
            text = text.replace(v, "***")
    return text


# --------------------------------------------------------------------------- #
# Gathering each section
# --------------------------------------------------------------------------- #
def gather_projects(script, start, end, *, env=None):
    # --compare-prev adds hours_prev/ms_prev per project (week-over-week delta).
    return run_json(script, ["projects", *window_args(start, end),
                             "--detail", "--compare-prev"], env)


def gather_visits(script, start, end, *, env=None):
    return run_json(script, ["report", *window_args(start, end)], env)


# Substrings (case-insensitive) in a calendar error that mean "auth is broken" —
# expired/missing OAuth token, revoked grant, 401, etc. When we see one we replace
# the opaque underlying google-libs message with an actionable hint.
_CAL_AUTH_HINTS = ("credential", "token", "unauthorized", "401", "invalid_grant",
                   "expired", "not authenticated", "authenticate", "oauth",
                   "refresh", "access_denied", "login")


def friendly_calendar_error(msg):
    """Rewrite an opaque calendar failure into an actionable message.

    The underlying google-libs text can be cryptic — a bare ``Traceback (most
    recent call last):`` first line, or an OAuth error. If it looks like an auth
    failure (or is just an opaque traceback, whose most common cause is an expired
    token), point the user at re-auth; otherwise pass the message through with a
    hint to run the skill's own diagnostic."""
    low = (msg or "").lower()
    opaque = "traceback" in low or not (msg or "").strip()
    if opaque or any(h in low for h in _CAL_AUTH_HINTS):
        return ("Google Workspace credentials are missing or expired (or setup is "
                "incomplete) — re-authenticate, then retry. Run `calendar check` "
                "for the exact setup/re-auth steps.")
    return f"{msg} (run `calendar check` to diagnose)"


def gather_calendar(script, start, end, *, env=None, exclude=()):
    """Calendar events in [start, end] via the calendar skill's agenda --json.

    The calendar skill resolves its own (Google-libs) interpreter internally, so
    we just run it like any sibling. Events whose summary matches CALENDAR_EXCLUDE
    (personal appointments, etc.) are dropped from both the calendar section and
    the meetings count. Returns {count, events, ...} or {"error":…} (the error is
    rewritten into an actionable message)."""
    res = run_json(script, ["agenda", *window_args(start, end)], env)
    if isinstance(res, dict) and "error" in res:
        return {"error": friendly_calendar_error(res["error"])}
    if not isinstance(res, dict) or not exclude:
        return res
    events = res.get("events", []) or []
    kept = [e for e in events if not event_excluded(e.get("summary", ""), exclude)]
    excluded = len(events) - len(kept)
    if excluded:
        res = dict(res)
        res["events"] = kept
        res["count"] = len(kept)
        res["excluded"] = excluded
    return res


# Summarisation-irrelevant noise inflates the tokens the LLM must read without
# helping the bullets. We squeeze trailing whitespace and runs of blank lines —
# conservative on purpose (internal spacing/indentation is left intact so code
# blocks, tables and nested lists in a note body aren't mangled).
_BLANKS_RE = re.compile(r"\n{3,}")


def compact_body(text):
    """Trim a note body to cut LLM input tokens without losing content.

    Strips trailing whitespace per line and collapses 3+ consecutive newlines to
    one blank line. Returns the compacted, stripped body."""
    if not text:
        return ""
    joined = "\n".join(line.rstrip() for line in text.splitlines())
    return _BLANKS_RE.sub("\n\n", joined).strip()


def gather_git(script, start, end, *, env=None):
    """Commits you authored in [start, end] across the repos under GIT_REPOS_DIR.

    Runs git-report's ``commits --stat`` so the bundle carries per-repo commit
    lists (subject/date) plus churn — what the HTML "Commits" section and the
    "top repos by commits" highlight card consume. Returns {repos, total, …} or
    ``{"error": …}`` (e.g. GIT_REPOS_DIR unset), degrading like every source."""
    return run_json(script, ["commits", *window_args(start, end), "--stat"], env)


def gather_sessions(script, start, end, *, env=None):
    """Claude Code sessions active in [start, end], **grouped by project**.

    Runs claude-sessions' ``list --limit 0 --json`` (every session in the window,
    subagents already folded into their parent) and rolls the flat list up into
    one entry per project: the session count, the summed API-equivalent cost, and
    a compact per-session list (title, when, duration, prompts, cost, efficiency
    grade). Projects are ordered by session count desc, then cost desc; each
    project's sessions by cost desc. Returns ``{"error": …}`` (degrading like
    every source) if the transcript root is missing or the child fails."""
    res = run_json(script, ["list", *window_args(start, end), "--limit", "0"], env)
    if not isinstance(res, dict) or "error" in res:
        return res
    sessions = res.get("sessions", []) or []
    groups = {}
    for s in sessions:
        label = s.get("project_label") or s.get("project") or "(unknown)"
        name = label.rsplit("/", 1)[-1] or label     # concise basename for display
        g = groups.setdefault(name, {"project": name, "path": label,
                                     "sessions": 0, "cost_usd": 0.0, "entries": []})
        g["sessions"] += 1
        g["cost_usd"] += s.get("cost_usd", 0) or 0
        eff = s.get("efficiency") or {}
        g["entries"].append({
            "session_id": s.get("session_id"),
            "title": s.get("title") or "(untitled)",
            "when": (s.get("start_local") or "")[:16].replace("T", " "),
            "duration": s.get("duration"),
            "prompts": s.get("prompts", 0),
            "cost_usd": round(s.get("cost_usd", 0) or 0, 2),
            "grade": eff.get("grade"),
            "rating": eff.get("rating"),
        })
    for g in groups.values():
        g["cost_usd"] = round(g["cost_usd"], 2)
        g["entries"].sort(key=lambda e: e["cost_usd"], reverse=True)
    projects = sorted(groups.values(),
                      key=lambda g: (-g["sessions"], -g["cost_usd"], g["project"].lower()))
    out = {
        "total_sessions": len(sessions),
        "total_cost_usd": round(sum(g["cost_usd"] for g in projects), 2),
        "projects": projects,
    }
    if res.get("skipped"):
        out["skipped"] = res["skipped"]
    return out


def _split_folders(s):
    """Parse a comma-separated folder list into normalised path prefixes."""
    return [p.strip().strip("/").replace("\\", "/")
            for p in (s or "").split(",") if p.strip()]


def note_group(rel):
    """Top-level folder of a note's vault-relative path — a thin grouping key so
    the notes section can cluster by area (e.g. ``Acme/IA/x.md`` → ``Acme``).
    A note at the vault root groups under ``(root)``."""
    r = (rel or "").replace("\\", "/").strip("/")
    return r.split("/", 1)[0] if "/" in r else "(root)"


def is_excluded(rel, excludes):
    """True if note path `rel` sits in (or under) any excluded folder.

    Matches on whole path components, so ``Notion/Personal`` excludes
    ``Notion/Personal`` and ``Notion/Personal/Sub.md`` but NOT
    ``Notion/PersonalStuff.md``."""
    r = (rel or "").replace("\\", "/")
    return any(r == f or r.startswith(f + "/") for f in excludes)


def gather_notes(script, start, end, *, env=None, by="modified", max_notes=40,
                 note_chars=1200, exclude=()):
    listed = run_json(script, ["list", *window_args(start, end), "--by", by,
                              "--limit", "0"], env)
    if "error" in listed:
        return listed
    listed_notes = listed.get("notes", [])
    # Drop notes under any excluded folder BEFORE pulling bodies (saves work).
    all_notes = [n for n in listed_notes if not is_excluded(n.get("rel", ""), exclude)]
    excluded = len(listed_notes) - len(all_notes)
    notes = []
    dropped = max(0, len(all_notes) - max_notes)
    for n in all_notes[:max_notes]:
        body, truncated, err = _note_body(script, n["rel"], note_chars, env)
        entry = {
            "rel": n["rel"], "name": n.get("name"), "group": note_group(n["rel"]),
            "modified": n.get("modified"), "created": n.get("created"),
            "size": n.get("size"), "body": body, "truncated": truncated,
        }
        if err:
            entry["body_error"] = err
        notes.append(entry)
    out = {"count": len(all_notes), "by": by, "notes": notes}
    if dropped:
        out["dropped"] = dropped  # surfaced, never silently truncated
    if excluded:
        out["excluded"] = excluded  # notes filtered out by OBSIDIAN_EXCLUDE
    return out


def _note_body(script, rel, note_chars, env=None):
    """Return (body, truncated, error) for one note via obsidian show --json.

    The body is compacted (whitespace/blank-line noise removed) **before**
    truncation, so the char budget is spent on real content — fewer tokens for
    the LLM to read, and better summaries per token."""
    # "./" prefix: `rel` comes from the child's own listing, and a vault file
    # named like an option (leading "-") must not be parsed as one. (run_json
    # appends --json last, so a bare "--" separator would swallow it.)
    shown = run_json(script, ["show", os.path.join(".", rel), "--no-frontmatter"], env)
    if "error" in shown:
        return "", False, shown["error"]
    body = compact_body(shown.get("body") or shown.get("content") or "")
    if note_chars and len(body) > note_chars:
        return body[:note_chars].rstrip() + "…", True, None
    return body, False, None


def gather_emails(start, end, *, env=None, cli=EMAILOPS_CLI, mailbox="sent",
                  max_emails=200):
    """Emails in `mailbox` whose local date falls in [start, end], via emailops-cli."""
    fetch = max(int(max_emails), 1)
    res = run_cli_json([cli, "emails", "--mailbox", mailbox, "--limit", str(fetch),
                        "--json", "--quiet"], env)
    if "error" in res:
        return res
    rows = res.get("data") or []
    start_s, end_s = start.isoformat(), end.isoformat()
    emails = []
    for m in rows:
        ts = m.get("timestamp")
        if not isinstance(ts, (int, float)):
            continue
        day = datetime.fromtimestamp(ts).date().isoformat()
        if start_s <= day <= end_s:
            emails.append({
                "id": m.get("id"),
                "date": day,
                "to": m.get("recipients") or [],
                "subject": (m.get("subject") or "").strip(),
                "snippet": (m.get("snippet") or "").strip(),
            })
    emails.sort(key=lambda e: e["date"])
    out = {"count": len(emails), "mailbox": mailbox, "emails": emails}
    # If we hit the fetch cap and the OLDEST fetched message is still on/after the
    # window start, there may be more in-window emails beyond the cap — surface it.
    ts_vals = [m.get("timestamp") for m in rows
               if isinstance(m.get("timestamp"), (int, float))]
    if len(rows) >= fetch and ts_vals:
        oldest = datetime.fromtimestamp(min(ts_vals)).date().isoformat()
        if oldest >= start_s:
            out["possibly_truncated"] = True
    return out


def _short_int(n):
    """Compact integer: 1234 → '1.2k', 1_800_000 → '1.8M'."""
    n = int(n or 0)
    if abs(n) >= 1_000_000:
        return f"{n / 1_000_000:.1f}M".replace(".0M", "M")
    if abs(n) >= 1_000:
        return f"{n / 1_000:.1f}k".replace(".0k", "k")
    return str(n)


def build_summary(sections):
    """A deterministic top-of-report snapshot from the gathered sections.

    Returns a dict of the headline numbers plus a one-line ``line`` string
    (skimmable TL;DR). Each source contributes a segment only when it's available
    (no error) and non-empty, so a partial report yields a shorter summary rather
    than noisy zeros."""
    seg, parts = [], {}

    def ok(key):
        s = sections.get(key)
        return s if isinstance(s, dict) and "error" not in s else None

    p = ok("projects")
    if p is not None:
        plist = p.get("projects", []) or []
        hours = sum(float(x.get("hours", 0) or 0) for x in plist)
        parts["hours"], parts["projects"] = round(hours, 1), len(plist)
        if plist:
            seg.append(f"{hours:.1f}h across {len(plist)} project(s)")
    g = ok("git")
    if g is not None:
        repos = g.get("repos", []) or []
        total = g.get("total", sum(r.get("count", 0) for r in repos))
        ins = sum(r.get("insertions", 0) for r in repos)
        dele = sum(r.get("deletions", 0) for r in repos)
        parts["commits"] = total
        if total:
            churn = f" (+{_short_int(ins)}/-{_short_int(dele)})" if (ins or dele) else ""
            seg.append(f"{total} commit(s){churn}")
    s = ok("sessions")
    if s is not None:
        n = s.get("total_sessions", 0)
        parts["sessions"] = n
        if n:
            cost = s.get("total_cost_usd", 0)
            seg.append(f"{n} Claude session(s)"
                       + (f" (${cost:,.0f} API-eq)" if cost else ""))
    c = ok("calendar")
    if c is not None:
        meetings = [e for e in (c.get("events", []) or []) if not e.get("all_day")]
        parts["meetings"] = len(meetings)
        if meetings:
            seg.append(f"{len(meetings)} meeting(s)")
    n_ = ok("notes")
    if n_ is not None:
        cnt = n_.get("count", 0)
        parts["notes"] = cnt
        if cnt:
            seg.append(f"{cnt} note(s)")
    e = ok("emails")
    if e is not None:
        cnt = e.get("count", 0)
        parts["emails"] = cnt
        if cnt:
            seg.append(f"{cnt} email(s) sent")
    v = ok("visits")
    if v is not None:
        sites = v.get("sites", []) or []
        tv = sum(x.get("visitors", 0) or 0 for x in sites)
        parts["visitors"] = tv
        if sites:
            seg.append(f"{_short_int(tv)} visitor(s)")
    parts["line"] = " · ".join(seg)
    return parts


def build_bundle(args, *, today=None):
    """Assemble the weekly report bundle.

    Each child skill runs **in parallel** via ThreadPoolExecutor so wall time is
    roughly *max* of the six children instead of their sum (often 3–5× faster).
    Results are collected and errors aggregated — any single failure degrades
    gracefully into an ``{"error": ...}`` section.
    """
    today = today or date.today()
    start, end = compute_range(today, period=args.period, days=args.days,
                              start=args.start, end=args.end)
    env = build_child_env(getattr(args, "env_file", None))
    sp = sibling_script("sp", args.sp_script)
    ob = sibling_script("obsidian", args.obsidian_script)
    um = sibling_script("umami", args.umami_script)
    cal = sibling_script("calendar", args.calendar_script)
    gt = sibling_script("git", args.git_script)
    cs = sibling_script("sessions", args.sessions_script)
    excludes = resolve_excludes(args, getattr(args, "env_file", None))
    cal_excludes = resolve_cal_excludes(args, getattr(args, "env_file", None))

    # Warm the interpreter cache once, single-threaded: child_python() probes
    # candidate pythons for a working ssl and memoises the winner in a global.
    # Doing it here avoids all six worker threads racing to run that probe.
    child_python()

    # All sources are independent — run them in parallel.
    def _projects():
        return ("projects", gather_projects(sp, start, end, env=env))

    def _notes():
        return ("notes", gather_notes(ob, start, end, env=env, by=args.by,
                                      max_notes=args.max_notes, note_chars=args.note_chars,
                                      exclude=excludes))

    def _emails():
        return ("emails", gather_emails(start, end, env=env, cli=args.emailops_cli,
                                        max_emails=args.max_emails))

    def _calendar():
        return ("calendar", gather_calendar(cal, start, end, env=env,
                                            exclude=cal_excludes))

    def _visits():
        return ("visits", gather_visits(um, start, end, env=env))

    def _git():
        return ("git", gather_git(gt, start, end, env=env))

    def _sessions():
        return ("sessions", gather_sessions(cs, start, end, env=env))

    tasks = ((_projects, "projects"), (_notes, "notes"), (_emails, "emails"),
             (_calendar, "calendar"), (_visits, "visits"), (_git, "git"),
             (_sessions, "sessions"))
    sections = {}
    errors = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=len(tasks)) as pool:
        futures = {pool.submit(fn): name for fn, name in tasks}
        for future in concurrent.futures.as_completed(futures):
            name = futures[future]
            try:
                key, section = future.result()
                sections[key] = section
            except Exception as exc:
                sections[name] = {"error": str(exc)}

    for label in ("projects", "notes", "emails", "calendar", "visits", "git",
                  "sessions"):
        section = sections.get(label)
        if isinstance(section, dict) and "error" in section:
            errors.append(f"{label}: {section['error']}")

    return {
        "range": {"start": start.isoformat(), "end": end.isoformat(),
                  "label": args.period or ("custom" if args.start else
                                           f"{args.days}d" if args.days else "this-week")},
        "summary": build_summary(sections),
        "projects": sections.get("projects", {"error": "missing"}),
        "notes": sections.get("notes", {"error": "missing"}),
        "emails": sections.get("emails", {"error": "missing"}),
        "calendar": sections.get("calendar", {"error": "missing"}),
        "visits": sections.get("visits", {"error": "missing"}),
        "git": sections.get("git", {"error": "missing"}),
        "sessions": sections.get("sessions", {"error": "missing"}),
        "errors": errors,
    }


# --------------------------------------------------------------------------- #
# Text skeleton (deterministic parts only — bullets/prose are the agent's job)
# --------------------------------------------------------------------------- #
def _table(headers, rows):
    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):
        out = [cells[0].ljust(widths[0])]
        out += [cells[i].rjust(widths[i]) for i in range(1, len(cells))]
        return "  ".join(out)

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


def _delta(cur, prev):
    if prev == 0:
        return "—" if cur == 0 else "▲new"
    pct = 100.0 * (cur - prev) / prev
    arrow = "▲" if pct > 0 else "▼" if pct < 0 else "—"
    return f"{arrow}{abs(pct):.1f}%"


def _section_err(section):
    return section["error"] if isinstance(section, dict) and "error" in section else None


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


def render_text(bundle):
    r = bundle["range"]
    out = [f"Weekly report  {r['start']} → {r['end']}"]
    summary = (bundle.get("summary") or {}).get("line")
    if summary:
        out.append(f"TL;DR: {summary}")
    out.append("")

    # Projects ------------------------------------------------------------- #
    out.append("PROJECTS & TIME")
    err = _section_err(bundle["projects"])
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        projs = bundle["projects"].get("projects", [])
        has_prev = any("hours_prev" in p for p in projs)   # week-over-week delta
        rows = []
        for p in projs:
            row = [p["project"], f"{p.get('hours', 0):.2f}h"]
            if has_prev:
                row.append(_delta(p.get("hours", 0), p.get("hours_prev", 0)))
            rows.append(row)
        if rows:
            total = sum(p.get("hours", 0) for p in projs)
            headers = ["Project", "Hours"] + (["Δ prev"] if has_prev else [])
            body, sep, line = _table(headers, rows)
            total_row = ["TOTAL", f"{total:.2f}h"]
            if has_prev:
                total_row.append(_delta(total, sum(p.get("hours_prev", 0) for p in projs)))
            out += [body, sep, line(total_row)]
        else:
            out.append("  (no time tracked this week)")
    out.append("")

    # Notes ---------------------------------------------------------------- #
    out.append("NOTES (modified/created this week)")
    err = _section_err(bundle["notes"])
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        notes = bundle["notes"].get("notes", [])
        # Cluster by top-level folder so related notes read together.
        groups = {}
        for n in notes:
            groups.setdefault(n.get("group") or note_group(n.get("rel", "")), []).append(n)
        for g in sorted(groups, key=lambda k: (k == "(root)", k.lower())):
            gnotes = groups[g]
            out.append(f"  {g}  ({len(gnotes)} note(s))")
            for n in gnotes:
                out.append(f"    • {n['rel']}  (mod {n['modified']}, created {n['created']})")
        if not notes:
            out.append("  (no notes this week)")
        if bundle["notes"].get("dropped"):
            out.append(f"  (+{bundle['notes']['dropped']} more not shown — raise --max-notes)")
        if bundle["notes"].get("excluded"):
            out.append(f"  ({bundle['notes']['excluded']} note(s) excluded by {EXCLUDE_ENV})")
        out.append("  → 3–4 bullet points per note are written by the agent from each body.")
    out.append("")

    # Emails sent ---------------------------------------------------------- #
    out.append("EMAILS SENT (this week)")
    err = _section_err(bundle["emails"])
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        emails = bundle["emails"].get("emails", [])
        for e in emails:
            to = ", ".join(e["to"]) or "(no recipient)"
            out.append(f"  • {e['date']}  {_ellipsis(e['subject'] or '(no subject)', 50)}  → {_ellipsis(to, 40)}")
        if not emails:
            out.append("  (no emails sent this week)")
        if bundle["emails"].get("possibly_truncated"):
            out.append("  (list may be incomplete — raise --max-emails)")
    out.append("")

    # Calendar ------------------------------------------------------------- #
    out.append("CALENDAR (events this week)")
    err = _section_err(bundle.get("calendar", {}))
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        events = (bundle.get("calendar") or {}).get("events", [])
        for ev in events:
            when = "all-day" if ev.get("all_day") else \
                (f"{ev.get('start_local')}–{ev.get('end_local')}"
                 if ev.get("end_local") else ev.get("start_local", ""))
            loc = f"  @ {ev['location']}" if ev.get("location") else ""
            out.append(f"  • {ev.get('day', '')}  {when:>11}  "
                       f"{_ellipsis(ev.get('summary', '(no title)'), 50)}{loc}")
        if not events:
            out.append("  (no events this week)")
        if (bundle.get("calendar") or {}).get("excluded"):
            out.append(f"  ({bundle['calendar']['excluded']} event(s) excluded by {CAL_EXCLUDE_ENV})")
    out.append("")

    # Visits --------------------------------------------------------------- #
    out.append("VISITS (vs last week)")
    err = _section_err(bundle["visits"])
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        sites = bundle["visits"].get("sites", [])
        rows, tv, tp = [], 0, 0
        for s in sites:
            v = s.get("visitors", 0) or 0
            pv = s.get("pageviews", 0) or 0
            tv += v
            tp += pv
            # Show the Umami site id alongside the friendly name when available,
            # so multiple sites can be told apart / verified.
            name = s.get("name", "?")
            if s.get("site_id"):
                name = f"{name} [{s['site_id']}]"
            rows.append([name,
                         f"{v:,} {_delta(v, s.get('visitors_prev', 0))}",
                         f"{pv:,} {_delta(pv, s.get('pageviews_prev', 0))}"])
        if rows:
            body, sep, line = _table(["Site", "Visitors", "Pageviews"], rows)
            out.append(body)
            out.append(sep)
            out.append(line(["TOTAL", f"{tv:,}", f"{tp:,}"]))
        else:
            out.append("  (no sites / no data)")
    out.append("")

    # Commits -------------------------------------------------------------- #
    out.append("COMMITS (this week)")
    err = _section_err(bundle.get("git", {}))
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        repos = (bundle.get("git") or {}).get("repos", [])
        for r in repos:
            churn = ""
            if "insertions" in r or "deletions" in r:
                churn = f", +{r.get('insertions', 0)}/-{r.get('deletions', 0)}"
            out.append(f"  {r.get('repo', '?')}  ({r.get('count', 0)} commit(s){churn})")
            for c in r.get("commits", []):
                out.append(f"    • {c.get('date', '')}  {c.get('short', '')}  "
                           f"{_ellipsis(c.get('subject', ''), 60)}")
        if not repos:
            out.append("  (no commits this week)")
    out.append("")

    # Claude Code sessions (per project) ----------------------------------- #
    out.append("CLAUDE CODE SESSIONS (per project)")
    err = _section_err(bundle.get("sessions", {}))
    if err:
        out.append(f"  (unavailable: {err})")
    else:
        sess = bundle.get("sessions") or {}
        sprojects = sess.get("projects", [])
        for p in sprojects:
            cost = f", ${p.get('cost_usd', 0):.2f} API-eq" if p.get("cost_usd") else ""
            out.append(f"  {p.get('project', '?')}  "
                       f"({p.get('sessions', 0)} session(s){cost})")
            for e in p.get("entries", []):
                grade = f"[{e['grade']}] " if e.get("grade") else ""
                out.append(f"    • {e.get('when', '')}  {e.get('duration', ''):>6}  "
                           f"{grade}{_ellipsis(e.get('title', ''), 55)}")
        if not sprojects:
            out.append("  (no Claude Code sessions this week)")
        else:
            out.append(f"  TOTAL: {sess.get('total_sessions', 0)} session(s)"
                       + (f", ${sess.get('total_cost_usd', 0):.2f} API-equivalent"
                          " (list price — not your bill)"
                          if sess.get("total_cost_usd") else ""))
    return "\n".join(out)


# --------------------------------------------------------------------------- #
# Subcommands
# --------------------------------------------------------------------------- #
def do_gather(args):
    bundle = build_bundle(args)
    if args.text:
        print(render_text(bundle))
    else:
        print(json.dumps(bundle, indent=2, ensure_ascii=False))
    return 0


def do_html(args):
    """Gather + render the HTML report + write it — all in one process.

    Deliberately a single command (no shell ``VAR=…``, no ``gather | render_html``
    pipe, no ``>`` redirect): those compound forms trip Hermes' per-command
    approval gate and can hang the pipeline. Here the file write happens inside
    this trusted Python process, and the command is one clean invocation."""
    # render_html is a sibling module in this scripts/ dir (sys.path[0]).
    import render_html
    bundle = build_bundle(args)
    doc = render_html.build_html(bundle, title=args.title)
    out = os.path.expanduser(args.output or "~/weekly-report.html")
    try:
        with open(out, "w", encoding="utf-8") as fh:
            fh.write(doc)
    except OSError as e:
        raise WeeklyError(f"could not write {out}: {e.strerror or e}")
    print(out)
    return 0


def do_markdown(args):
    """Gather + render a **deterministic** Markdown report in one process.

    This is the reliable path for the data sections — every value (site names,
    email recipients, counts) is copied verbatim from the bundle, so no LLM can
    hallucinate or drop a row. Prints to stdout by default (so the agent can show
    it directly); writes to a file with ``-o``."""
    import render_markdown
    bundle = build_bundle(args)
    doc = render_markdown.build_markdown(bundle, title=args.title)
    if getattr(args, "output", None):
        out = os.path.expanduser(args.output)
        try:
            with open(out, "w", encoding="utf-8") as fh:
                fh.write(doc)
        except OSError as e:
            raise WeeklyError(f"could not write {out}: {e.strerror or e}")
        print(out)
    else:
        print(doc)
    return 0


def _check_sibling(name, script, env):
    """Run one sibling's own `check`; return (name, ok, message)."""
    if not os.path.exists(script):
        return (name, False, f"script not found ({script})")
    try:
        proc = subprocess.run([child_python(), script, "check"],
                              capture_output=True, text=True,
                              timeout=CHILD_TIMEOUT, env=env)
    except (OSError, subprocess.TimeoutExpired) as e:
        return (name, False, str(e))
    if proc.returncode == 0:
        return (name, True, _first_line(proc.stdout))
    return (name, False, _first_line(proc.stderr) or "not configured")


def _check_emailops(cli, env):
    em = run_cli_json([cli, "doctor", "--json", "--quiet"], env)
    if "error" in em:
        return ("emailops", False, em["error"])
    d = em.get("data") or {}
    return ("emailops", True,
            f"{d.get('accountsEnabled', '?')} account(s), {d.get('emailCount', '?')} emails")


def do_check(args):
    env = build_child_env(getattr(args, "env_file", None))
    print("weekly-report — source skills:")

    # Probe every source in parallel — same fan-out as gather, so the diagnostic
    # takes ~max(child) instead of the sum of all six sequential checks.
    checks = [
        (lambda: _check_sibling("superproductivity-report", sibling_script("sp", args.sp_script), env)),
        (lambda: _check_sibling("obsidian-notes", sibling_script("obsidian", args.obsidian_script), env)),
        (lambda: _check_sibling("umami-report", sibling_script("umami", args.umami_script), env)),
        (lambda: _check_sibling("calendar", sibling_script("calendar", args.calendar_script), env)),
        (lambda: _check_sibling("git-report", sibling_script("git", args.git_script), env)),
        (lambda: _check_sibling("claude-sessions", sibling_script("sessions", args.sessions_script), env)),
        (lambda: _check_emailops(args.emailops_cli, env)),
    ]
    order = ["superproductivity-report", "obsidian-notes", "umami-report",
             "calendar", "git-report", "claude-sessions", "emailops"]
    results = {}
    with concurrent.futures.ThreadPoolExecutor(max_workers=len(checks)) as pool:
        for fut in concurrent.futures.as_completed([pool.submit(c) for c in checks]):
            name, ok, msg = fut.result()
            results[name] = (ok, msg)

    any_ok = False
    for name in order:
        ok, msg = results.get(name, (False, "no result"))
        if ok:
            any_ok = True
            print(f"  ✓ {name}: ready — {msg}")
        else:
            print(f"  ✗ {name}: {msg}")

    print()
    print("The weekly report includes whichever sources are ready (✓); the rest"
          " are skipped with a note.")
    return 0 if any_ok else 1


def build_parser():
    p = argparse.ArgumentParser(
        prog="weekly_report",
        description="One weekly report stitched from the other Hermes skills.")
    sub = p.add_subparsers(dest="cmd")

    def add_common(sp):
        sp.add_argument("--env-file", help="dotenv to read config from "
                        "(default ~/.hermes/.env)")
        sp.add_argument("--sp-script", help="override path to sp_report.py")
        sp.add_argument("--obsidian-script", help="override path to obsidian_notes.py")
        sp.add_argument("--umami-script", help="override path to umami_report.py")
        sp.add_argument("--calendar-script", help="override path to calendar_agenda.py")
        sp.add_argument("--git-script", help="override path to git_report.py")
        sp.add_argument("--sessions-script", help="override path to claude_sessions.py")
        sp.add_argument("--emailops-cli", default=EMAILOPS_CLI,
                        help="emailops CLI command/path (default emailops-cli)")

    def add_gather_args(sp):
        win = sp.add_mutually_exclusive_group()
        win.add_argument("--period", choices=PERIODS, help="named window (default this-week)")
        win.add_argument("--days", type=int, help="last N days (inclusive of today)")
        sp.add_argument("--start", help="explicit start date YYYY-MM-DD (with --end)")
        sp.add_argument("--end", help="explicit end date YYYY-MM-DD (with --start)")
        sp.add_argument("--by", choices=("modified", "created"), default="modified",
                        help="which note timestamp the window filters on (default modified)")
        sp.add_argument("--max-notes", type=int, default=40,
                        help="max notes to pull bodies for (default 40; overflow is reported)")
        sp.add_argument("--note-chars", type=int, default=1200,
                        help="truncate each note body to N chars (default 1200, tuned for "
                             "fast summarisation; raise for fuller bodies, 0 = no limit)")
        sp.add_argument("--max-emails", type=int, default=200,
                        help="max recent sent emails to scan for the window (default 200)")
        sp.add_argument("--exclude", help="comma-separated Obsidian folder(s) to drop "
                        f"from the notes section (overrides ${EXCLUDE_ENV})")
        sp.add_argument("--exclude-events", help="comma-separated substrings; calendar "
                        f"events matching any are dropped (overrides ${CAL_EXCLUDE_ENV})")
        add_common(sp)

    chk = sub.add_parser("check", help="show which source skills are configured")
    add_common(chk)

    g = sub.add_parser("gather", help="gather the weekly report bundle (default)")
    add_gather_args(g)
    g.add_argument("--text", action="store_true",
                   help="human-readable skeleton instead of the JSON bundle")

    h = sub.add_parser("html", help="gather + write a self-contained HTML report "
                                    "(one process — no shell pipe needed)")
    add_gather_args(h)
    h.add_argument("--output", "-o", help="HTML file to write "
                   "(default ~/weekly-report.html); prints the path written")
    h.add_argument("--title", default="Weekly report", help="report heading")

    md = sub.add_parser("markdown", help="gather + render a deterministic Markdown "
                                         "report (faithful data — no LLM)")
    add_gather_args(md)
    md.add_argument("--output", "-o", help="Markdown file to write "
                    "(default: print to stdout)")
    md.add_argument("--title", default="Weekly report", help="report heading")
    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 == "html":
            return do_html(args)
        if args.cmd == "markdown":
            return do_markdown(args)
        if args.cmd in (None, "gather"):
            if args.cmd is None:  # default subcommand: gather, this-week
                args = parser.parse_args(["gather"])
            return do_gather(args)
        parser.error(f"unknown command {args.cmd}")
    except WeeklyError 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 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