Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(signals): add helper scripts to exploring-signals-scouts skill (#62093)

Andrew Maguire255473e563e8
diff --git a/products/signals/skills/exploring-signals-scouts/SKILL.md b/products/signals/skills/exploring-signals-scouts/SKILL.md
index 7e4a7d3a45d3..1e4423fca107 100644
--- a/products/signals/skills/exploring-signals-scouts/SKILL.md
+++ b/products/signals/skills/exploring-signals-scouts/SKILL.md
@@ -45,6 +45,22 @@ The orienting fifth is `signals-scout-project-profile-get` — the deterministic
true about this project" that every scout cold-starts from. When a scout found nothing, this is
usually why.
+## Output handling: expect to offload to a file
+
+Two of these tools — `signals-scout-runs-list` and especially
+`tasks-runs-session-logs-retrieve` — routinely return payloads that **overflow an MCP client's
+token budget and get spilled to a file**. This is the normal path, not an error. Plan for it up
+front rather than discovering it after a failed call:
+
+- **Keep `limit` small** on `signals-scout-runs-list` (~10–15). Each row carries a long prose
+ `summary`, and runs come back newest-first across the _whole_ fleet, so even a modest page is
+ large.
+- **Session logs are large by nature.** A single run's log is hundreds of KB to a few MB. Fetch it
+ with **`call --json`** (so the saved file is real JSON, not the pretty text format — `jq`-able)
+ and read the saved file with `jq` / a script rather than inline.
+- **Don't hand-parse the session log.** The bundled [`scripts/`](#helper-scripts) do the
+ reconstruction for you — see below.
+
## Start here: is the fleet even set up?
Don't assume the project has scouts. The fleet only runs on teams enrolled via the `signals-scout`
@@ -150,10 +166,19 @@ the list row, so to learn _why_ it failed you need the transcript.
You don't have to open the UI for that: **`tasks-runs-session-logs-retrieve` returns the run's
session log (every tool call, message, and reasoning step) as data** — handy when you're
diagnosing a failure or want to trace exactly what a run did without leaving the conversation. Pass
-the run's `task_run_id` as `id` and its `task_id` (both are on the run row). The raw stream is
-large and dominated by incremental `tool_call_update` chunks, so filter to keep it readable — e.g.
-`exclude_types: "tool_call_update,usage_update,_posthog/console,agent_thought_chunk"` leaves just
-the `tool_call` and `agent_message` events, which is enough to reconstruct the run's timeline.
+the run's `task_run_id` as `id` and its `task_id` (both are on the run row).
+
+The raw stream is large (hundreds of KB to a few MB) and will overflow inline, so **fetch it with
+`call --json` and let it spill to a file**, then run it through
+[`scripts/render_run_report.py`](#helper-scripts) rather than parsing it by hand.
+
+⚠️ **Do not reach for `exclude_types: "tool_call_update,…"` to slim it down.** It is tempting —
+the stream is dominated by incremental `tool_call_update` chunks — but each tool's **actual input
+lives only in those chunks**: the base `tool_call` event carries an empty `rawInput`, and the
+streamed updates build the input (and the final `rawOutput`) token by token. Excluding them leaves
+you with tool _names_ but no idea what the scout actually queried. Fetch the **full** log and let
+the script reassemble each call (it groups by `toolCallId`, keeps the richest `rawInput`, and
+attaches the completion's `rawOutput`/`status`).
**Telling whether a run emitted is not as direct as you'd hope.** The run row carries no emit
flag and no finding count — the only readily-available signal is the prose `summary`, which says
@@ -248,6 +273,82 @@ below. The full playbook, including how to read each signal and the common failu
- **Memory growth** — a healthy scout accumulates `pattern:` / `noise:` / `dedupe:` entries over
time. A scout with an empty scratchpad after many runs isn't learning.
+## Helper scripts
+
+The skill bundles three **pure formatters** under [`scripts/`](scripts/) for the most common asks.
+They do **no network I/O** — they are the back half of an "agent fetches, script formats" split.
+The pattern is always the same:
+
+1. Fetch each payload with the MCP using **`call --json`** (raw JSON, not the pretty text format)
+ and save it to a file. For the big ones (`runs-list`, `tasks-runs-session-logs-retrieve`) this
+ is mandatory anyway — they overflow inline and spill to a file you can point the script at.
+2. Run the script over those files.
+
+All three are stdlib-only Python 3.11+ and print **plain text** to stdout (or `--out`) — designed
+to read well in a terminal, so save them as `.txt`.
+
+### `scripts/render_run_report.py` — drill into one run
+
+Produces the kind of detailed write-up you'd want when inspecting a single run: header
+(status, duration, posture), a **narrated timeline that interleaves the agent's narration with
+each tool call _and its real input_**, the end-of-run summary, and any scratchpad memory.
+
+```bash
+# fetch (note --json), saving each to a file:
+# call --json signals-scout-runs-retrieve { "id": "<run_id>" } -> run.json
+# call --json tasks-runs-session-logs-retrieve { "id": "<task_run_id>", "task_id": "<task_id>", "offset": 0 } -> log.json (FULL — no exclude_types)
+# (optional) call --json signals-scout-scratchpad-search { ... } -> mem.json
+# (optional) call --json signals-scout-config-list {} -> cfg.json
+python scripts/render_run_report.py --run run.json --log log.json \
+ --scratchpad mem.json --config cfg.json --out report.txt
+```
+
+Modes (`--mode`, default `detailed`):
+
+| Mode | Contains | `--log` needed? |
+| ---------- | ------------------------------------------------------------------ | --------------- |
+| `summary` | header + posture + close-out prose | no |
+| `detailed` | + narrated timeline with tool **inputs** + tool tally + scratchpad | yes |
+| `full` | + each tool call's (truncated) **output** inline | yes |
+
+Other flags: `--show-output` (outputs in detailed mode), `--input-width` / `--output-width`
+(truncation), `--no-art` (skip the hedgehog banner), `--base-url` (defaults to `us.posthog.com`).
+
+### `scripts/fleet_survey.py` — survey the whole fleet
+
+One scannable table — scout, enabled, posture, cadence, last run, last outcome — with a "worth a
+look" section that flags never-run, stuck-in-dry-run, and last-run-failed scouts.
+
+```bash
+# call --json signals-scout-config-list {} -> cfg.json
+# (optional) call --json signals-scout-runs-list { "limit": 30 } -> runs.json (small limit!)
+python scripts/fleet_survey.py --config cfg.json --runs runs.json --now <current-ISO-time>
+```
+
+Pass `--now` (the current time, ISO-8601) to get relative "ago" columns; the emit/quiet column is
+a **heuristic** on each run's summary prose — confirm against the summary before trusting it.
+
+### `scripts/assess_health.py` — health over a window of runs
+
+Implements the "assess health and performance" workflow above: a per-scout table (runs, success
+%, emit %, cadence gap vs interval, adherence, median duration, memory growth) plus a "worth a
+look" section flagging all-failed scouts, timeout-shaped failures, cadence stalls, staleness, and
+empty scratchpads.
+
+```bash
+# call --json signals-scout-runs-list { "limit": 100, "date_from": "<ISO>" } -> runs.json
+# (optional) call --json signals-scout-config-list {} -> cfg.json
+# (optional) call --json signals-scout-scratchpad-search {} -> mem.json
+python scripts/assess_health.py --runs runs.json --config cfg.json \
+ --scratchpad mem.json --now <current-ISO-time> [--skill signals-scout-general]
+```
+
+`--config` is what lets it score cadence adherence (the expected interval) and staleness (the
+authoritative `last_run_at`, which the windowed runs can miss when the 100-row cap truncates the
+newest runs). Without `--scratchpad` the memory column shows `n/a` and no memory flags fire. The
+emit % is the same summary-prose heuristic — cross-check signal-to-noise against
+`inbox-reports-list`.
+
## Tips
- **Always surface the `emit` posture.** "Running but in dry-run" is the single most common reason
diff --git a/products/signals/skills/exploring-signals-scouts/scripts/assess_health.py b/products/signals/skills/exploring-signals-scouts/scripts/assess_health.py
new file mode 100644
index 000000000000..398a80f34002
--- /dev/null
+++ b/products/signals/skills/exploring-signals-scouts/scripts/assess_health.py
@@ -0,0 +1,287 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 — CLI tool; stdout/stderr prints are the intended output
+"""Assess Signals scout health/performance across a window of runs (plain text).
+
+Pure formatter — no network I/O. Answers the "is my scout actually working / earning
+its cost?" question, which (unlike a single-run report or a point-in-time fleet survey)
+needs reasoning across a *window* of runs. Judges each scout on the five dimensions from
+the exploring-signals-scouts health playbook: cadence adherence, success rate, emit rate,
+run duration, and memory growth.
+
+Inputs (`call --json` payloads saved to a file):
+ --runs signals-scout-runs-list --json (REQUIRED) fetched over a window via
+ `date_from` (e.g. the last 3 days). Returns all scouts mixed, newest-first.
+ Keep the page within the 100-row cap; walk back with `date_to` if needed and
+ concatenate the JSON arrays into one file.
+ --config signals-scout-config-list --json (optional) supplies each scout's expected
+ `run_interval_minutes` so cadence adherence can be scored.
+ --scratchpad signals-scout-scratchpad-search --json (optional) memory-growth signal;
+ entries are attributed to a scout via `created_by_run_id`. Without it, the
+ memory column shows `n/a` and no memory flags are raised.
+ --now ISO-8601 current time (optional) — enables "time since last run" staleness.
+ --skill restrict the report to one scout (e.g. signals-scout-general).
+
+Output is plain text (terminal-friendly). Pipe to a .txt file with --out.
+
+Usage:
+ python assess_health.py --runs runs.json --config cfg.json [--scratchpad mem.json] \
+ [--now 2026-06-08T09:00:00Z] [--skill signals-scout-general] [--out health.txt]
+
+Stdlib only. Python 3.11+."""
+
+from __future__ import annotations
+
+import sys
+import json
+import argparse
+import statistics
+from datetime import datetime
+from typing import Any
+
+# a failed run whose wall-clock is this long or longer is timeout-shaped, not a fast crash
+TIMEOUT_MINUTES = 20.0
+# a gap larger than this multiple of the expected interval counts as a stall
+STALL_FACTOR = 2.0
+
+# the obligatory hedgehog
+HEDGEHOG = r"""
+ /////////,
+ ///////////// . PostHog · Signals
+ /////////////// `. health & performance
+ //////////////// o `.
+ ````````````````` `-.>
+ ' ' ' ' '
+"""
+
+
+def load(path: str) -> Any:
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def rows(payload: Any) -> list[dict]:
+ if isinstance(payload, dict):
+ inner = payload.get("results")
+ return inner if isinstance(inner, list) else []
+ return payload if isinstance(payload, list) else []
+
+
+def parse_ts(ts: str | None) -> datetime | None:
+ if not ts:
+ return None
+ try:
+ return datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def minutes_between(a: str | None, b: str | None) -> float | None:
+ x, y = parse_ts(a), parse_ts(b)
+ if not x or not y:
+ return None
+ return (y - x).total_seconds() / 60.0
+
+
+def quiet_or_emit(summary: str | None) -> str:
+ """Heuristic read of emit-vs-quiet from a run's prose summary (no emit flag exists).
+
+ 'EMITTED NOTHING' / 'nothing to emit' = quiet. A bare 'emitted' may describe a PRIOR
+ run, so it is ambiguous — counted as a maybe, never as a confirmed emit.
+ """
+ if not summary:
+ return "unknown"
+ low = summary.lower()
+ if "emitted nothing" in low or "nothing to emit" in low or "did not emit" in low:
+ return "quiet"
+ if "emitted" in low:
+ return "maybe"
+ return "quiet"
+
+
+def pct(num: int, den: int) -> str:
+ return f"{round(100 * num / den)}%" if den else "-"
+
+
+def fmt_age(minutes: float | None) -> str:
+ if minutes is None:
+ return "-"
+ if minutes < 90:
+ return f"{int(minutes)}m"
+ if minutes < 60 * 36:
+ return f"{round(minutes / 60)}h"
+ return f"{round(minutes / 1440)}d"
+
+
+def table(headers: list[str], body: list[list[str]]) -> list[str]:
+ """Left-aligned fixed-width text table with a dashed header rule."""
+ widths = [len(h) for h in headers]
+ for r in body:
+ for i, cell in enumerate(r):
+ widths[i] = max(widths[i], len(cell))
+
+ def fmt(r: list[str]) -> str:
+ return " ".join(cell.ljust(widths[i]) for i, cell in enumerate(r)).rstrip()
+
+ out = [fmt(headers), " ".join("-" * w for w in widths)]
+ out += [fmt(r) for r in body]
+ return out
+
+
+def assess_scout(name: str, runs: list[dict], interval: float | None, mem_count: int | None,
+ now: datetime | None, config_last_run: str | None) -> dict:
+ runs = sorted(runs, key=lambda r: r.get("started_at") or "")
+ n = len(runs)
+ completed = sum(1 for r in runs if r.get("status") == "completed")
+ failed = sum(1 for r in runs if r.get("status") == "failed")
+
+ durations = [m for r in runs if (m := minutes_between(r.get("started_at"), r.get("completed_at"))) is not None]
+ median_dur = round(statistics.median(durations), 1) if durations else None
+ timeouts = sum(
+ 1
+ for r in runs
+ if r.get("status") == "failed"
+ and (m := minutes_between(r.get("started_at"), r.get("completed_at"))) is not None
+ and m >= TIMEOUT_MINUTES
+ )
+
+ # cadence: consecutive gaps between run starts
+ starts = [s for r in runs if (s := parse_ts(r.get("started_at")))]
+ gaps = [(starts[i] - starts[i - 1]).total_seconds() / 60.0 for i in range(1, len(starts))]
+ median_gap = round(statistics.median(gaps), 1) if gaps else None
+ stalls = sum(1 for g in gaps if interval and g > STALL_FACTOR * interval)
+
+ span_min = (starts[-1] - starts[0]).total_seconds() / 60.0 if len(starts) >= 2 else 0.0
+ expected = (int(span_min / interval) + 1) if interval and span_min > 0 else None
+ adherence = pct(n, expected) if expected else "-"
+
+ emit_like = sum(1 for r in runs if quiet_or_emit(r.get("summary")) == "maybe")
+ # staleness uses the config's authoritative last_run_at when available — the runs
+ # window can be truncated by the 100-row cap and miss the newest runs.
+ last_start = parse_ts(config_last_run) or (starts[-1] if starts else None)
+ stale_min = (now - last_start).total_seconds() / 60.0 if now and last_start else None
+
+ return {
+ "name": name, "runs": n, "completed": completed, "failed": failed, "timeouts": timeouts,
+ "success_pct": pct(completed, n), "median_dur": median_dur, "median_gap": median_gap,
+ "interval": interval, "adherence": adherence, "stalls": stalls,
+ "emit_like": emit_like, "emit_pct": pct(emit_like, n), "mem_count": mem_count, "stale_min": stale_min,
+ }
+
+
+def render(scouts: list[dict], window_note: str, has_mem: bool, *, art: bool = True) -> str:
+ banner: list[str] = []
+ if art:
+ banner = [HEDGEHOG.strip("\n"), "", " judge a scout over a window of runs, not on any single tick", ""]
+
+ if not scouts:
+ return "\n".join([*banner, "SCOUT HEALTH", "",
+ "No runs in the supplied window — nothing to assess."])
+
+ L: list[str] = [*banner, "=" * 78, " SIGNALS SCOUT HEALTH & PERFORMANCE", "=" * 78, " " + window_note, ""]
+
+ body: list[list[str]] = []
+ for s in sorted(scouts, key=lambda x: x["name"]):
+ gap = f"{s['median_gap']}m" if s["median_gap"] is not None else "-"
+ interval = f"{int(s['interval'])}m" if s["interval"] else "?"
+ dur = f"{s['median_dur']}m" if s["median_dur"] is not None else "-"
+ runs_cell = f"{s['runs']}" + (f" ({s['failed']}F)" if s["failed"] else "")
+ mem = "n/a" if s["mem_count"] is None else (str(s["mem_count"]) if s["mem_count"] else "0")
+ body.append([s["name"], runs_cell, s["success_pct"], s["emit_pct"],
+ f"{gap}/{interval}", s["adherence"], dur, mem])
+
+ L += table(["scout", "runs", "ok", "emit*", "gap/ival", "adher", "med", "mem"], body)
+ L += [""]
+
+ flags: list[str] = []
+ for s in scouts:
+ if s["failed"] and s["completed"] == 0:
+ flags.append(f" * {s['name']}: EVERY run failed ({s['failed']}/{s['runs']}) — broken, not quiet.")
+ elif s["timeouts"]:
+ flags.append(f" * {s['name']}: {s['timeouts']} timeout-shaped failure(s) (>={int(TIMEOUT_MINUTES)}m) — likely over-investigation; read the session log.")
+ if s["stalls"]:
+ flags.append(f" * {s['name']}: {s['stalls']} cadence stall(s) (gap >{int(STALL_FACTOR)}x interval) — coordinator skipped it (paused / drained / capped).")
+ if has_mem and s["runs"] >= 5 and s["mem_count"] == 0:
+ flags.append(f" * {s['name']}: {s['runs']} runs but an EMPTY scratchpad — not learning.")
+ if s["stale_min"] is not None and s["interval"] and s["stale_min"] > STALL_FACTOR * s["interval"]:
+ flags.append(f" * {s['name']}: last run {fmt_age(s['stale_min'])} ago vs a {int(s['interval'])}m cadence — may be drained from the flag.")
+
+ L += ["-" * 78, " worth a look", "-" * 78]
+ L += sorted(set(flags)) if flags else [" (none — cadence, success, and memory all look nominal)"]
+
+ L += ["", "-" * 78, " column key", "-" * 78,
+ " runs runs in the window; (NF) = N of them failed",
+ " ok success rate — % of runs that reached a clean 'completed' status",
+ " emit* emit rate — % of runs whose summary reads like it emitted. HEURISTIC",
+ " on the prose: can over-count when a summary recaps a PRIOR run's",
+ " emit. Confirm signal-to-noise against inbox-reports-list.",
+ " gap/ival median gap between consecutive run starts / the configured",
+ " run_interval_minutes. gap well above ival = the scout is being skipped.",
+ " adher cadence adherence — runs observed / runs expected across the window",
+ " span at that interval. 100% = fired on (nearly) every scheduled tick.",
+ " med median run duration (start -> finish). healthy runs finish in a couple",
+ " of minutes; a ~30m median is timeout-shaped over-investigation.",
+ " mem durable scratchpad entries attributed to this scout (via the run that",
+ " wrote them) in --scratchpad. 'n/a' = no --scratchpad passed; '0' = passed",
+ " but none matched (often the writing run falls outside the runs window)."]
+ return "\n".join(L)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--runs", required=True, help="signals-scout-runs-list --json over a window")
+ ap.add_argument("--config", help="signals-scout-config-list --json (for expected interval)")
+ ap.add_argument("--scratchpad", help="signals-scout-scratchpad-search --json (for memory growth)")
+ ap.add_argument("--now", help="ISO-8601 current time, for staleness")
+ ap.add_argument("--skill", help="restrict to one scout skill_name")
+ ap.add_argument("--no-art", dest="art", action="store_false", help="skip the hedgehog banner")
+ ap.add_argument("--out", help="write here instead of stdout (use a .txt path)")
+ args = ap.parse_args()
+
+ run_rows = rows(load(args.runs))
+ if args.skill:
+ run_rows = [r for r in run_rows if r.get("skill_name") == args.skill]
+
+ cfg_rows = rows(load(args.config)) if args.config else []
+ intervals = {r.get("skill_name"): r.get("run_interval_minutes") for r in cfg_rows}
+ last_run_by_skill = {r.get("skill_name"): r.get("last_run_at") for r in cfg_rows}
+ now = parse_ts(args.now) if args.now else None
+
+ # attribute scratchpad entries to a scout via the run that wrote them
+ has_mem = bool(args.scratchpad)
+ mem_by_skill: dict[str, int] = {}
+ if has_mem:
+ run_to_skill = {r.get("run_id"): r.get("skill_name") for r in run_rows}
+ for entry in rows(load(args.scratchpad)):
+ skill = run_to_skill.get(entry.get("created_by_run_id"))
+ if skill:
+ mem_by_skill[skill] = mem_by_skill.get(skill, 0) + 1
+
+ by_skill: dict[str, list[dict]] = {}
+ for r in run_rows:
+ by_skill.setdefault(r.get("skill_name", "?"), []).append(r)
+
+ assessed = [
+ assess_scout(name, runs, intervals.get(name), (mem_by_skill.get(name, 0) if has_mem else None),
+ now, last_run_by_skill.get(name))
+ for name, runs in by_skill.items()
+ ]
+
+ starts = [s for r in run_rows if (s := parse_ts(r.get("started_at")))]
+ if starts:
+ lo, hi = min(starts), max(starts)
+ window_note = f"window: {lo:%Y-%m-%d %H:%M} -> {hi:%Y-%m-%d %H:%M} UTC · {len(run_rows)} runs across {len(assessed)} scout(s)."
+ else:
+ window_note = f"{len(run_rows)} runs across {len(assessed)} scout(s)."
+
+ report = render(assessed, window_note, has_mem, art=args.art)
+ if args.out:
+ with open(args.out, "w", encoding="utf-8") as fh:
+ fh.write(report + "\n")
+ print(f"wrote {args.out}", file=sys.stderr)
+ else:
+ print(report)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/products/signals/skills/exploring-signals-scouts/scripts/fleet_survey.py b/products/signals/skills/exploring-signals-scouts/scripts/fleet_survey.py
new file mode 100644
index 000000000000..49c10f8d5cf9
--- /dev/null
+++ b/products/signals/skills/exploring-signals-scouts/scripts/fleet_survey.py
@@ -0,0 +1,207 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 — CLI tool; stdout/stderr prints are the intended output
+"""Render a plain-text fleet-survey table for a project's Signals scouts.
+
+Pure formatter — no network I/O. You fetch the inputs through the PostHog MCP with
+`call --json` and save them to files, then point this script at them. Answers the
+"what scouts do I have / what are they doing?" question with one row per scout:
+schedule, posture, last run, and last outcome.
+
+Inputs (`call --json` payloads saved to a file):
+ --config signals-scout-config-list --json (REQUIRED) the roster
+ --runs signals-scout-runs-list --json (optional) to enrich with the
+ most recent run per scout (status + quiet/emit heuristic). Fetch with a
+ small limit (~30) — runs-list overflows easily; offload to a file.
+ --now ISO-8601 timestamp to compute "ago" columns against (optional; pass the
+ current time. Without it, ages are shown as raw timestamps).
+
+Output is plain text (terminal-friendly). Pipe to a .txt file with --out.
+
+Usage:
+ python fleet_survey.py --config cfg.json [--runs runs.json] [--now 2026-06-08T09:00:00Z]
+
+Stdlib only. Python 3.11+."""
+
+from __future__ import annotations
+
+import sys
+import json
+import argparse
+from datetime import datetime
+from typing import Any
+
+
+# the obligatory hedgehog
+HEDGEHOG = r"""
+ /////////,
+ ///////////// . PostHog · Signals
+ /////////////// `. fleet survey
+ //////////////// o `.
+ ````````````````` `-.>
+ ' ' ' ' '
+"""
+
+
+def load(path: str) -> Any:
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def rows(payload: Any) -> list[dict]:
+ if isinstance(payload, dict):
+ inner = payload.get("results")
+ return inner if isinstance(inner, list) else []
+ return payload if isinstance(payload, list) else []
+
+
+def parse_ts(ts: str | None) -> datetime | None:
+ if not ts:
+ return None
+ try:
+ return datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def ago(ts: str | None, now: datetime | None) -> str:
+ dt = parse_ts(ts)
+ if not dt:
+ return "never"
+ if not now:
+ return ts or "?"
+ secs = int((now - dt).total_seconds())
+ if secs < 0:
+ return "future?"
+ if secs < 3600:
+ return f"{secs // 60}m ago"
+ if secs < 86400:
+ return f"{secs // 3600}h ago"
+ return f"{secs // 86400}d ago"
+
+
+def latest_run_per_scout(runs_payload: Any) -> dict[str, dict]:
+ """runs-list returns newest-first across the whole fleet; keep the first per skill."""
+ latest: dict[str, dict] = {}
+ for run in rows(runs_payload):
+ name = run.get("skill_name")
+ if name and name not in latest:
+ latest[name] = run
+ return latest
+
+
+def quiet_or_emit(summary: str | None) -> str:
+ """Best-effort read of whether a run emitted, from its prose summary.
+
+ There is no emit flag on the run row, so this is heuristic only — the summary
+ is authoritative, this is a hint. 'EMITTED NOTHING' / 'nothing to emit' = quiet.
+ """
+ if not summary:
+ return "?"
+ low = summary.lower()
+ if "emitted nothing" in low or "nothing to emit" in low or "did not emit" in low:
+ return "quiet"
+ if "emitted" in low:
+ return "emit?" # ambiguous: may describe a prior run — verify the summary
+ return "quiet?"
+
+
+def table(headers: list[str], body: list[list[str]]) -> list[str]:
+ """Left-aligned fixed-width text table with a dashed header rule."""
+ widths = [len(h) for h in headers]
+ for r in body:
+ for i, cell in enumerate(r):
+ widths[i] = max(widths[i], len(cell))
+
+ def fmt(r: list[str]) -> str:
+ return " ".join(cell.ljust(widths[i]) for i, cell in enumerate(r)).rstrip()
+
+ out = [fmt(headers), " ".join("-" * w for w in widths)]
+ out += [fmt(r) for r in body]
+ return out
+
+
+def render(config: Any, runs_payload: Any, now: datetime | None, *, art: bool = True) -> str:
+ latest = latest_run_per_scout(runs_payload) if runs_payload else {}
+ scouts = sorted(rows(config), key=lambda r: r.get("skill_name", ""))
+
+ banner: list[str] = []
+ if art:
+ banner = [HEDGEHOG.strip("\n"), "", " an empty close-out is a healthy scout outcome", ""]
+
+ if not scouts:
+ return "\n".join([*banner,
+ "SIGNALS SCOUT FLEET", "",
+ "No scout configs registered — this project is not enrolled in the "
+ "scout fleet (or hasn't ticked yet). Nothing is running."])
+
+ L: list[str] = [*banner, "=" * 72, f" SIGNALS SCOUT FLEET ({len(scouts)} configured)", "=" * 72, ""]
+
+ body: list[list[str]] = []
+ anomalies: list[str] = []
+ for s in scouts:
+ name = s.get("skill_name", "?")
+ enabled = "yes" if s.get("enabled") else "OFF"
+ posture = "live" if s.get("emit") else "dry-run"
+ cadence = f"{s.get('run_interval_minutes', '?')}m"
+ last = ago(s.get("last_run_at"), now)
+
+ run = latest.get(name)
+ if run:
+ st = run.get("status", "?")
+ tag = {"completed": "done", "failed": "FAIL"}.get(st, st)
+ outcome = f"{tag} / {quiet_or_emit(run.get('summary'))}"
+ else:
+ outcome = "-"
+ body.append([name, enabled, posture, cadence, last, outcome])
+
+ if s.get("last_run_at") is None and s.get("enabled"):
+ anomalies.append(f" * {name}: enabled but has NEVER run — check fleet enrolment.")
+ if not s.get("emit") and s.get("enabled"):
+ anomalies.append(f" * {name}: stuck in DRY-RUN (emit: false) — running but posting nothing.")
+ if run and run.get("status") == "failed":
+ anomalies.append(f" * {name}: most recent run FAILED — read its session log (often a timeout).")
+
+ L += table(["scout", "enabled", "posture", "cadence", "last run", "last outcome"], body)
+
+ if anomalies:
+ L += ["", "-" * 72, " worth a look", "-" * 72]
+ L += sorted(set(anomalies))
+
+ L += ["", "-" * 72, " column key", "-" * 72,
+ " enabled yes = scheduled to run; OFF = paused (nothing runs)",
+ " posture live = emits findings to the inbox; dry-run = reasons every",
+ " tick but posts nothing (emit=false) — the #1 'my scout is",
+ " broken' confusion, since it IS running, just not emitting",
+ " cadence configured minutes between scheduled runs (run_interval_minutes)",
+ " last run how long ago the most recent run started ('-' = never run)",
+ " last outcome <status> / <emit guess> of that run: done|FAIL, and quiet|emit?.",
+ " emit-vs-quiet is a HEURISTIC on the summary prose — confirm",
+ " against the summary before trusting it."]
+ return "\n".join(L)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--config", required=True, help="signals-scout-config-list --json payload")
+ ap.add_argument("--runs", help="signals-scout-runs-list --json payload (small limit)")
+ ap.add_argument("--now", help="ISO-8601 current time for 'ago' columns")
+ ap.add_argument("--no-art", dest="art", action="store_false", help="skip the hedgehog banner")
+ ap.add_argument("--out", help="write here instead of stdout (use a .txt path)")
+ args = ap.parse_args()
+
+ config = load(args.config)
+ runs_payload = load(args.runs) if args.runs else None
+ now = parse_ts(args.now) if args.now else None
+
+ report = render(config, runs_payload, now, art=args.art)
+ if args.out:
+ with open(args.out, "w", encoding="utf-8") as fh:
+ fh.write(report + "\n")
+ print(f"wrote {args.out}", file=sys.stderr)
+ else:
+ print(report)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/products/signals/skills/exploring-signals-scouts/scripts/render_run_report.py b/products/signals/skills/exploring-signals-scouts/scripts/render_run_report.py
new file mode 100644
index 000000000000..19f533ba94af
--- /dev/null
+++ b/products/signals/skills/exploring-signals-scouts/scripts/render_run_report.py
@@ -0,0 +1,355 @@
+#!/usr/bin/env python3
+# ruff: noqa: T201 — CLI tool; stdout/stderr prints are the intended output
+"""Render a plain-text terminal report for a single Signals scout run.
+
+This is a *pure formatter*: it does no network I/O. You (the agent) fetch the raw
+data through the PostHog MCP with `call --json` and save each payload to a file,
+then point this script at those files. This split exists because the run-list and
+session-log MCP tools routinely overflow an MCP client's token budget — they are
+meant to be offloaded to a file and parsed, not read inline.
+
+Inputs (all are `call --json` payloads saved verbatim to a file):
+ --run signals-scout-runs-retrieve --json (REQUIRED) the run row + summary
+ --log tasks-runs-session-logs-retrieve --json (optional) the FULL session log
+ — fetch it WITHOUT `exclude_types`. The tool inputs live only in the
+ `tool_call_update` stream, so excluding updates discards what each tool
+ actually ran. This script reassembles them. Omit --log for a metadata-only
+ report (summary mode does not need it).
+ --scratchpad signals-scout-scratchpad-search --json (optional) durable memory
+ --config signals-scout-config-list --json (optional) for emit posture
+
+Modes (--mode, default: detailed):
+ summary header + posture + end-of-run summary prose. No timeline. (--log optional)
+ detailed summary + a shell-style timeline (agent narration + tool calls WITH inputs)
+ + tool tally + scratchpad. The default.
+ full detailed + each tool call's (truncated) output inline.
+
+Output is plain text (terminal-friendly). Pipe to a .txt file with --out.
+
+Usage:
+ python render_run_report.py --run run.json --log log.json
+ python render_run_report.py --run run.json --mode summary --no-art
+ python render_run_report.py --run run.json --log log.json --mode full --out report.txt
+
+Stdlib only. Python 3.11+ (uses datetime.fromisoformat with offsets)."""
+
+from __future__ import annotations
+
+import sys
+import json
+import argparse
+import textwrap
+from collections import OrderedDict
+from datetime import datetime
+from typing import Any
+
+WIDTH = 66
+
+# the obligatory hedgehog
+HEDGEHOG = r"""
+ /////////,
+ ///////////// . PostHog · Signals
+ /////////////// `. scout run report
+ //////////////// o `.
+ ````````````````` `-.>
+ ' ' ' ' '
+"""
+
+
+def rule(title: str = "", width: int = WIDTH) -> str:
+ if not title:
+ return "-" * width
+ body = f"---- {title} "
+ return body + "-" * max(0, width - len(body))
+
+
+def load(path: str) -> Any:
+ with open(path, encoding="utf-8") as fh:
+ return json.load(fh)
+
+
+def parse_ts(ts: str | None) -> datetime | None:
+ if not ts:
+ return None
+ try:
+ return datetime.fromisoformat(ts.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+
+
+def hms(ts: str | None) -> str:
+ dt = parse_ts(ts)
+ return dt.strftime("%H:%M:%S") if dt else "??:??:??"
+
+
+def human_duration(start: str | None, end: str | None) -> str:
+ a, b = parse_ts(start), parse_ts(end)
+ if not a or not b:
+ return "unknown"
+ secs = int((b - a).total_seconds())
+ m, s = divmod(secs, 60)
+ return f"{m}m{s:02d}s" if m else f"{s}s"
+
+
+def _rows(payload: Any) -> list[dict]:
+ """MCP list payloads come back either as a bare list or wrapped in {results: [...]}."""
+ if isinstance(payload, dict):
+ inner = payload.get("results")
+ return inner if isinstance(inner, list) else []
+ return payload if isinstance(payload, list) else []
+
+
+# --- session log reconstruction --------------------------------------------
+
+
+def _updates(log: list[dict]) -> list[tuple[str, dict]]:
+ """Yield (timestamp, update) for every session/update notification, in order."""
+ out: list[tuple[str, dict]] = []
+ for ev in log:
+ note = ev.get("notification") or {}
+ if note.get("method") != "session/update":
+ continue
+ upd = (note.get("params") or {}).get("update")
+ if isinstance(upd, dict):
+ out.append((ev.get("timestamp", ""), upd))
+ return out
+
+
+def reconstruct(log: list[dict]) -> list[dict]:
+ """Collapse the streamed session log into an ordered list of timeline events.
+
+ Tool calls arrive as one `tool_call` event (empty input) followed by a stream
+ of `tool_call_update`s that build `rawInput` token by token and finish with a
+ `status`+`rawOutput` event. We group by `toolCallId` and keep the richest input
+ and the final output, then emit one event per tool call at its first timestamp.
+ """
+ calls: OrderedDict[str, dict] = OrderedDict()
+ timeline: list[dict] = []
+
+ for ts, upd in _updates(log):
+ kind = upd.get("sessionUpdate")
+
+ if kind == "user_message_chunk":
+ txt = (upd.get("content") or {}).get("text", "")
+ timeline.append({"t": ts, "type": "prompt", "text": txt})
+
+ elif kind == "agent_message":
+ txt = (upd.get("content") or {}).get("text", "")
+ if txt.strip():
+ timeline.append({"t": ts, "type": "say", "text": txt})
+
+ elif kind in ("tool_call", "tool_call_update"):
+ cid = upd.get("toolCallId")
+ if not cid:
+ continue
+ rec = calls.get(cid)
+ if rec is None:
+ rec = {"t": ts, "type": "tool", "id": cid, "name": None, "input": None, "output": None, "status": None}
+ calls[cid] = rec
+ timeline.append(rec)
+ # the tool name shows up on some events as _meta.claudeCode.toolName, on others as title
+ name = (((upd.get("_meta") or {}).get("claudeCode") or {}).get("toolName")) or upd.get("title")
+ if name:
+ rec["name"] = name
+ ri = upd.get("rawInput")
+ if isinstance(ri, dict) and ri:
+ # keep the input with the most total content (last full one wins)
+ if rec["input"] is None or len(json.dumps(ri)) >= len(json.dumps(rec["input"])):
+ rec["input"] = ri
+ if upd.get("status"):
+ rec["status"] = upd["status"]
+ ro = upd.get("rawOutput")
+ if ro is not None:
+ rec["output"] = ro
+
+ timeline.sort(key=lambda e: e["t"])
+ return timeline
+
+
+# --- input/output prettying -------------------------------------------------
+
+
+def summarize_input(inp: dict | None, width: int) -> str:
+ if not inp:
+ return ""
+ # The most useful single field for each common tool.
+ for key in ("command", "query", "text"):
+ if key in inp and isinstance(inp[key], str):
+ val = " ".join(inp[key].split())
+ return val if len(val) <= width else val[: width - 1] + "..."
+ blob = json.dumps(inp, ensure_ascii=False)
+ return blob if len(blob) <= width else blob[: width - 1] + "..."
+
+
+def summarize_output(out: Any, width: int) -> str:
+ if out is None:
+ return ""
+ blob = json.dumps(out, ensure_ascii=False) if isinstance(out, (dict, list)) else str(out)
+ blob = " ".join(blob.split())
+ return blob if len(blob) <= width else blob[: width - 1] + "..."
+
+
+def emit_posture(config: Any, skill_name: str) -> dict | None:
+ for row in _rows(config):
+ if row.get("skill_name") == skill_name:
+ return row
+ return None
+
+
+# --- rendering --------------------------------------------------------------
+
+
+def render_header(L: list[str], run: dict, posture: dict | None, base_url: str) -> None:
+ name = run.get("skill_name", "unknown-scout")
+ status = run.get("status", "?")
+ status_tag = {"completed": "done", "failed": "FAILED"}.get(status, status)
+ dur = human_duration(run.get("started_at"), run.get("completed_at"))
+ task_url = run.get("task_url", "")
+ full_url = (base_url.rstrip("/") + task_url) if task_url.startswith("/") else task_url
+
+ L.append("=" * WIDTH)
+ L.append(f" SIGNALS SCOUT RUN {name}")
+ L.append("=" * WIDTH)
+ L.append(f" run {run.get('run_id', '?')} (skill v{run.get('skill_version', '?')})")
+ L.append(f" status {status_tag} {hms(run.get('started_at'))} -> {hms(run.get('completed_at'))} (~{dur})")
+ if posture:
+ emit = "live (emit: true)" if posture.get("emit") else "DRY-RUN (emit: false)"
+ enabled = "enabled" if posture.get("enabled") else "disabled"
+ L.append(f" posture {enabled} · {emit} · every {posture.get('run_interval_minutes', '?')}m")
+ if full_url:
+ L.append(f" transcript {full_url}")
+ L.append("")
+
+
+def render_timeline(L: list[str], timeline: list[dict], *, show_output: bool, input_width: int, output_width: int) -> None:
+ L.append(rule("timeline"))
+ legend = " markers: # narration $ tool call (with input) ~ prompt"
+ if show_output:
+ legend += " => output"
+ L.append(legend)
+ L.append("")
+ for ev in timeline:
+ t = hms(ev["t"])
+ if ev["type"] == "prompt":
+ txt = " ".join(ev["text"].split())
+ L.append(f" {t} ~ {txt[:140]}{'...' if len(txt) > 140 else ''}")
+ elif ev["type"] == "say":
+ txt = " ".join(ev["text"].split())
+ for i, line in enumerate(textwrap.wrap(txt, WIDTH - 14) or [""]):
+ L.append(f" {t} # {line}" if i == 0 else f" {' ' * 8} {line}")
+ elif ev["type"] == "tool":
+ st = ev.get("status") or ""
+ st_tag = {"completed": "", "failed": " [FAILED]"}.get(st, f" [{st}]" if st else "")
+ L.append(f" {t} $ {ev['name']}{st_tag}")
+ inp = summarize_input(ev["input"], input_width)
+ if inp:
+ L.append(f" {' ' * 8} {inp}")
+ if show_output:
+ outp = summarize_output(ev["output"], output_width)
+ if outp:
+ L.append(f" {' ' * 8} => {outp}")
+ L.append("")
+
+ tally: dict[str, int] = {}
+ for ev in timeline:
+ if ev["type"] == "tool":
+ tally[ev["name"] or "?"] = tally.get(ev["name"] or "?", 0) + 1
+ if tally:
+ parts = ", ".join(f"{k} x{v}" for k, v in sorted(tally.items(), key=lambda kv: -kv[1]))
+ L.append(f" tool budget: {sum(tally.values())} calls — {parts}")
+ L.append("")
+
+
+def render_summary(L: list[str], run: dict) -> None:
+ summary = run.get("summary")
+ if not summary:
+ return
+ L.append(rule("end-of-run summary (scout's own close-out)"))
+ for para in summary.split("\n"):
+ if not para.strip():
+ L.append("")
+ continue
+ for line in textwrap.wrap(para, WIDTH - 1):
+ L.append(f" {line}")
+ L.append("")
+
+
+def render_scratchpad(L: list[str], scratchpad: Any) -> None:
+ rows = _rows(scratchpad)
+ if not rows:
+ return
+ L.append(rule("scratchpad memory referenced / written"))
+ for row in rows:
+ key = row.get("key", "?")
+ content = " ".join((row.get("content") or "").split())
+ L.append(f" * {key}")
+ for line in textwrap.wrap(content[:600], WIDTH - 6):
+ L.append(f" {line}")
+ L.append("")
+
+
+def render(run: dict, timeline: list[dict] | None, scratchpad: Any, posture: dict | None, *,
+ mode: str, base_url: str, art: bool, show_output: bool, input_width: int, output_width: int) -> str:
+ L: list[str] = []
+ if art:
+ L.append(HEDGEHOG.strip("\n"))
+ L.append("")
+ L.append(" an empty close-out is a healthy scout outcome")
+ L.append("")
+ render_header(L, run, posture, base_url)
+
+ if mode != "summary" and timeline:
+ render_timeline(L, timeline, show_output=show_output, input_width=input_width, output_width=output_width)
+
+ render_summary(L, run)
+
+ if mode != "summary":
+ render_scratchpad(L, scratchpad)
+
+ return "\n".join(L)
+
+
+def main() -> int:
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ ap.add_argument("--run", required=True, help="signals-scout-runs-retrieve --json payload")
+ ap.add_argument("--log", help="tasks-runs-session-logs-retrieve --json payload (FULL, no exclude_types)")
+ ap.add_argument("--scratchpad", help="signals-scout-scratchpad-search --json payload")
+ ap.add_argument("--config", help="signals-scout-config-list --json payload (for emit posture)")
+ ap.add_argument("--mode", choices=("summary", "detailed", "full"), default="detailed",
+ help="summary = metadata + close-out prose; detailed = + timeline w/ inputs (default); full = + tool outputs")
+ ap.add_argument("--show-output", action="store_true", help="include tool outputs in the timeline (implied by --mode full)")
+ ap.add_argument("--input-width", type=int, default=160, help="truncate tool inputs to this many chars (default 160)")
+ ap.add_argument("--output-width", type=int, default=140, help="truncate tool outputs to this many chars (default 140)")
+ ap.add_argument("--no-art", dest="art", action="store_false", help="skip the hedgehog banner")
+ ap.add_argument("--base-url", default="https://us.posthog.com")
+ ap.add_argument("--out", help="write here instead of stdout (use a .txt path)")
+ args = ap.parse_args()
+
+ run = load(args.run)
+ log = load(args.log) if args.log else None
+ scratchpad = load(args.scratchpad) if args.scratchpad else None
+ config = load(args.config) if args.config else None
+
+ if args.mode != "summary" and log is None:
+ print(f"note: --mode {args.mode} wants --log for the timeline; rendering metadata only.", file=sys.stderr)
+
+ timeline = reconstruct(log) if log else None
+ posture = emit_posture(config, run.get("skill_name", "")) if config else None
+ report = render(
+ run, timeline, scratchpad, posture,
+ mode=args.mode, base_url=args.base_url, art=args.art,
+ show_output=args.show_output or args.mode == "full",
+ input_width=args.input_width, output_width=args.output_width,
+ )
+
+ if args.out:
+ with open(args.out, "w", encoding="utf-8") as fh:
+ fh.write(report + "\n")
+ print(f"wrote {args.out}", file=sys.stderr)
+ else:
+ print(report)
+ return 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())