Skip to content

AI agent skill that researches any topic across Reddit, X, YouTube, HN, Polymarket, and the web - then synthesizes a grounded summary

feat(pipeline): typed source health + preserved degradation (U3)

Matt Van Horn3c7edd69dee7
diff --git a/skills/last30days/scripts/lib/health.py b/skills/last30days/scripts/lib/health.py
new file mode 100644
index 00000000..2e3f2337
--- /dev/null
+++ b/skills/last30days/scripts/lib/health.py
@@ -0,0 +1,92 @@
+"""Typed source health: classify a source/tool outcome honestly.
+
+The pipeline historically collapsed every failure into "returned nothing" or a
+flat ``errors_by_source`` entry, which hides the difference between a tool that
+is *absent*, one that is *present but broken* (the classic stale-venv-shim after
+a Python upgrade), one that *timed out*, and one that merely *degraded* (fewer
+results than expected). This module gives callers a small typed vocabulary so
+warnings can say what actually happened and prescribe the right fix.
+
+It complements ``preflight.py`` (which gates doomed *queries*); this gates
+doomed *sources/tools*.
+"""
+
+from __future__ import annotations
+
+import shutil
+import subprocess
+from dataclasses import dataclass
+
+# Health states, best to worst.
+OK = "ok"
+DEGRADED = "degraded" # ran, but returned less than expected
+MISSING = "missing" # tool/binary/credential absent
+BROKEN = "broken" # present but won't execute (stale shim, bad perms)
+TIMEOUT = "timeout" # exceeded the probe deadline
+ERROR = "error" # ran and failed for another reason
+
+
+@dataclass
+class SourceHealth:
+ """Typed outcome for a source or the tool backing it.
+
+ ``state`` is one of the module-level constants. ``reason`` is a short,
+ human-readable explanation suitable for a run warning.
+ """
+
+ name: str
+ state: str
+ reason: str = ""
+
+ @property
+ def ok(self) -> bool:
+ return self.state == OK
+
+ @property
+ def usable(self) -> bool:
+ """True when the source produced something worth keeping (ok/degraded)."""
+ return self.state in (OK, DEGRADED)
+
+
+def probe_command(
+ command: list[str],
+ timeout: float = 5.0,
+) -> SourceHealth:
+ """Probe an external command, distinguishing missing/broken/timeout/ok.
+
+ Separating these is what lets the caller emit a correct repair prescription
+ instead of a generic "failed":
+ - ``missing``: the executable is not on PATH.
+ - ``broken``: on PATH but won't run — FileNotFoundError/OSError on exec, or
+ shell exit 126/127 (not-executable / not-found-after-resolution), the
+ signature of a stale interpreter shim after an upgrade.
+ - ``timeout``: exceeded ``timeout`` seconds.
+ - ``ok``: exited 0.
+ - ``error``: ran but exited non-zero for another reason.
+
+ The command should be side-effect-free (e.g. ``["gh", "auth", "status"]``);
+ callers pass a status/version subcommand, not a mutating one.
+ """
+ name = command[0] if command else ""
+ if not name or shutil.which(name) is None:
+ return SourceHealth(name=name, state=MISSING, reason=f"{name or 'command'} not found on PATH")
+
+ try:
+ proc = subprocess.run(
+ command,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ )
+ except (FileNotFoundError, OSError) as exc:
+ return SourceHealth(name=name, state=BROKEN, reason=f"{name} present but won't execute: {exc}")
+ except subprocess.TimeoutExpired:
+ return SourceHealth(name=name, state=TIMEOUT, reason=f"{name} timed out after {timeout:g}s")
+
+ if proc.returncode == 0:
+ return SourceHealth(name=name, state=OK)
+ if proc.returncode in (126, 127):
+ return SourceHealth(name=name, state=BROKEN, reason=f"{name} not executable (exit {proc.returncode})")
+ detail = (proc.stderr or proc.stdout or "").strip().splitlines()
+ first = detail[0] if detail else f"exit {proc.returncode}"
+ return SourceHealth(name=name, state=ERROR, reason=f"{name}: {first}")
diff --git a/skills/last30days/scripts/lib/pipeline.py b/skills/last30days/scripts/lib/pipeline.py
index c80ab8fb..021c9ca7 100644
--- a/skills/last30days/scripts/lib/pipeline.py
+++ b/skills/last30days/scripts/lib/pipeline.py
@@ -484,10 +484,16 @@ def run(
skip_sources=_github_skip_retry,
)
- # Clear errors for sources that returned items despite partial failures.
- # A source that 429'd on one subquery but succeeded on another is not "errored".
+ # Reclassify partial failures as DEGRADED instead of silently dropping them.
+ # A source that 429'd on one subquery but succeeded on another is not a hard
+ # failure, but it is not healthy either: it likely returned fewer results
+ # than it should have. Move it out of errors_by_source (so it isn't reported
+ # as "failed") and into degraded_by_source (so it survives into warnings),
+ # rather than deleting the signal outright as the engine used to.
+ degraded_by_source: dict[str, str] = {}
for source in list(bundle.errors_by_source):
if bundle.items_by_source.get(source):
+ degraded_by_source[source] = bundle.errors_by_source[source]
del bundle.errors_by_source[source]
hiring_summary = _apply_hiring_signal_gate(
@@ -524,7 +530,7 @@ def run(
)
clusters = cluster_candidates(ranked_candidates, plan)
- warnings = _warnings(items_by_source, ranked_candidates, bundle.errors_by_source)
+ warnings = _warnings(items_by_source, ranked_candidates, bundle.errors_by_source, degraded_by_source)
return schema.Report(
topic=topic,
@@ -682,6 +688,7 @@ def _warnings(
items_by_source: dict[str, list[schema.SourceItem]],
candidates: list[schema.Candidate],
errors_by_source: dict[str, str],
+ degraded_by_source: dict[str, str] | None = None,
) -> list[str]:
warnings: list[str] = []
if not candidates:
@@ -697,6 +704,13 @@ def _warnings(
warnings.append("Top evidence is highly concentrated in one source.")
if errors_by_source:
warnings.append(f"Some sources failed: {', '.join(sorted(errors_by_source))}")
+ if degraded_by_source:
+ # Partial failures: the source returned some items but errored/timed out
+ # on at least one subquery, so its coverage is likely incomplete. Kept
+ # distinct from hard failures so the signal is not silently dropped.
+ warnings.append(
+ f"Some sources returned partial results (degraded): {', '.join(sorted(degraded_by_source))}"
+ )
if not items_by_source:
warnings.append("No source returned usable items.")
return warnings
diff --git a/tests/test_health.py b/tests/test_health.py
new file mode 100644
index 00000000..3e7e52d8
--- /dev/null
+++ b/tests/test_health.py
@@ -0,0 +1,75 @@
+"""Tests for scripts/lib/health.py and pipeline degradation preservation."""
+
+import subprocess
+from unittest import mock
+
+from lib import health, pipeline
+
+
+class TestProbeCommand:
+ def test_missing_when_not_on_path(self):
+ result = health.probe_command(["definitely-not-a-real-binary-xyz"])
+ assert result.state == health.MISSING
+ assert not result.usable
+
+ def test_ok_on_exit_zero(self):
+ result = health.probe_command(["true"])
+ assert result.state == health.OK
+ assert result.ok
+
+ def test_error_on_nonzero_exit(self):
+ result = health.probe_command(["false"])
+ assert result.state == health.ERROR
+ assert not result.ok
+
+ def test_timeout(self):
+ result = health.probe_command(["sleep", "5"], timeout=0.1)
+ assert result.state == health.TIMEOUT
+
+ def test_broken_when_exec_raises(self):
+ # On PATH (which returns a path) but exec raises -> broken, not missing.
+ with mock.patch.object(health.shutil, "which", return_value="/usr/bin/x"), \
+ mock.patch.object(health.subprocess, "run", side_effect=OSError("exec format error")):
+ result = health.probe_command(["x"])
+ assert result.state == health.BROKEN
+
+ def test_broken_on_exit_127(self):
+ fake = subprocess.CompletedProcess(args=["x"], returncode=127, stdout="", stderr="not found")
+ with mock.patch.object(health.shutil, "which", return_value="/usr/bin/x"), \
+ mock.patch.object(health.subprocess, "run", return_value=fake):
+ result = health.probe_command(["x"])
+ assert result.state == health.BROKEN
+
+
+class _FakeCandidate:
+ def __init__(self, sources):
+ self.sources = sources
+
+
+def _candidates(n=6):
+ return [_FakeCandidate(["reddit"]) for _ in range(n)]
+
+
+class TestDegradationWarnings:
+ """Partial failures survive as a distinct 'degraded' warning."""
+
+ def test_degraded_surfaced_distinctly_from_failed(self):
+ warnings = pipeline._warnings(
+ items_by_source={"reddit": [object()], "github": [object()]},
+ candidates=_candidates(),
+ errors_by_source={"x": "hard failure"},
+ degraded_by_source={"reddit": "429 on one subquery"},
+ )
+ joined = " | ".join(warnings)
+ assert "Some sources failed: x" in joined
+ assert "degraded" in joined.lower()
+ assert "reddit" in joined
+
+ def test_no_degraded_warning_when_none(self):
+ warnings = pipeline._warnings(
+ items_by_source={"reddit": [object()]},
+ candidates=_candidates(),
+ errors_by_source={},
+ degraded_by_source={},
+ )
+ assert not any("degraded" in w.lower() for w in warnings)