Skip to content

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

fix(doctor): honest source classification + drop zero-item footer lines (#815)

Matt Van Hornc24584704649
diff --git a/skills/last30days/scripts/lib/doctor.py b/skills/last30days/scripts/lib/doctor.py
index a89b60ae..fad38417 100644
--- a/skills/last30days/scripts/lib/doctor.py
+++ b/skills/last30days/scripts/lib/doctor.py
@@ -99,6 +99,7 @@ SOURCE_ORDER = (
"pinterest",
"xiaohongshu",
"jobs",
+ "library",
)
# Key-presence booleans for the setup block. NEVER values.
@@ -178,6 +179,33 @@ def _finding_json(finding: backends.BackendFinding) -> Dict[str, Any]:
}
+def _host_native_web_note(config: Dict[str, Any]) -> str:
+ """Doctor-local note when the host's own web search serves this run.
+
+ Keys on LAST30DAYS_NATIVE_SEARCH (via env.is_native_search) AND on
+ CLAUDECODE as a host signal - Claude Code always exposes a web-search tool,
+ but `doctor` run in a plain shell never sees the LAST30DAYS_NATIVE_SEARCH
+ the engine exports only for its own run, so without the CLAUDECODE signal it
+ would mislabel a fine setup as "degraded/keyless". Messaging only: it does
+ not change env.is_native_search or the engine's keyless-floor behavior. The
+ note names the signal actually detected so it never cites an env var the
+ user did not set.
+ """
+ if env.is_native_search(config):
+ return (
+ "host-native search active (LAST30DAYS_NATIVE_SEARCH): the host's "
+ "own web search serves this run; set a web key only if you want "
+ "engine-side web search"
+ )
+ if config.get("CLAUDECODE") or os.environ.get("CLAUDECODE"):
+ return (
+ "host-native web search active (Claude Code): the host's own web "
+ "search serves this run; set a web key only if you want "
+ "engine-side web search"
+ )
+ return ""
+
+
def _chained_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:
descriptor = backends.get_descriptor(source)
res = backends.resolve(source, config)
@@ -202,6 +230,23 @@ def _chained_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:
active = by_name.get(res.active_backend)
return _record(status=health.OK, note=res.summary,
requires=active.requires if active else "", **common)
+
+ # Doctor-local (KTD-3): on a host that brings its own web search, the
+ # engine's web lanes (keyless floor or nothing configured) are intentionally
+ # dormant - report that, not an alarming "degraded/keyless". This must run
+ # before the WARN branch, because the keyless floor resolves to WARN and
+ # would otherwise return first. Messaging only; it never touches
+ # env.is_native_search or the engine's keyless-floor runtime behavior.
+ if source == "web":
+ host_note = _host_native_web_note(config)
+ if host_note:
+ return _record(
+ status="unconfigured",
+ note=host_note,
+ requires=res.findings[0].requires if res.findings else "",
+ **common,
+ )
+
if res.tier == backends.TIER_WARN:
active = by_name.get(res.active_backend)
return _record(status=health.DEGRADED, note=res.summary,
@@ -211,19 +256,6 @@ def _chained_record(source: str, config: Dict[str, Any]) -> Dict[str, Any]:
# res.tier == error: separate "nothing configured" (tier off) from
# "configured but broken" (tier error).
- if source == "web" and env.is_native_search(config):
- # The engine's web lanes are all unavailable BECAUSE the host brings
- # its own (better) native search — intentionally off, no false alarm.
- return _record(
- status="unconfigured",
- note=(
- "host-native search active (LAST30DAYS_NATIVE_SEARCH): the "
- "host's own web search serves this run; set a web key only "
- "if you want engine-side web search"
- ),
- requires=res.findings[0].requires if res.findings else "",
- **common,
- )
if res.findings and all(f.status == health.MISSING for f in res.findings):
return _record(
status="unconfigured",
@@ -275,18 +307,63 @@ def _reddit_record(config):
def _x_record(config):
- return _chained_record("x", config)
+ record = _chained_record("x", config)
+ # Diagnose/doctor load config in plan_only mode, so browser cookies are not
+ # extracted and every X backend reads as statically missing -> unconfigured.
+ # But if bird is installed and FROM_BROWSER will authenticate X at run time,
+ # a normal run serves X fine (this is how the reporting user pulled 29 posts
+ # while doctor said "Off"). Reuse the existing shared predicate so doctor and
+ # diagnose cannot drift. It reads no cookie *values*, so it confirms a run
+ # will *attempt* browser auth, not that the session is currently valid -
+ # keep the note honest and point at the verified key-backed path.
+ if record["status"] == "unconfigured" and env.x_pending_browser_auth(
+ config, local_only=True
+ ):
+ record["status"] = health.OK
+ record["tier"] = TIER_BY_STATUS[health.OK]
+ record["note"] = (
+ "will use: bird (browser cookies; session not verified until a run "
+ "- add XAI_API_KEY for a verified, cookie-free path)"
+ )
+ record["fix"] = ""
+ return record
def _youtube_record(config):
record = _chained_record("youtube", config)
- if record["status"] == health.OK and not env.transcription_providers(config):
- # Usable, but the caption-free transcript backstop is unavailable.
+ if record["status"] != health.OK:
+ return record
+ notes: List[str] = []
+ # yt-dlp already provides search + transcripts. A transcription key only
+ # backfills captions for the occasional caption-free video - an enhancement,
+ # not a sign YouTube is broken.
+ if not env.transcription_providers(config):
entry = prescriptions.get("youtube", "transcription_key_missing")
- record["note"] = (record["note"] + "; " if record["note"] else "") + (
- "no transcription key for caption-free videos"
+ notes.append(
+ "search + transcripts work; a transcription key only adds "
+ "captions for caption-free videos"
)
record["fix"] = _fix_text(entry)
+ # Comment *text* comes from ScrapeCreators, never yt-dlp (yt-dlp yields
+ # search, transcripts, and a comment count only). Say so accurately so a
+ # user does not expect yt-dlp to surface comment text.
+ if not env.is_youtube_comments_available(config):
+ notes.append(
+ "comment text needs a ScrapeCreators key + youtube_comments opt-in"
+ )
+ # Actionable fix, matching the transcription branch. The transcription
+ # fix takes precedence when both caveats fire (one fix line per record).
+ if not record["fix"]:
+ if not config.get("SCRAPECREATORS_API_KEY"):
+ record["fix"] = _sc_fix()
+ else:
+ record["fix"] = (
+ "add youtube_comments to INCLUDE_SOURCES in "
+ "~/.config/last30days/.env to enable YouTube comment text"
+ )
+ if notes:
+ joined = "; ".join(notes)
+ record["note"] = (record["note"] + "; " + joined) if record["note"] else joined
return record
@@ -437,6 +514,58 @@ def _jobs_record(config):
)
+def _count_saved_briefs(memory_dir) -> int:
+ """Cheap count of saved research briefs (directory listing, no file parse).
+
+ Globs the ``*-raw*.md`` artifacts the engine writes, deliberately avoiding
+ library.scan_library's read_text+parse of every file - a count does not
+ need the parsed content, and the full scan adds real latency to every
+ `doctor` run on a large library.
+ """
+ path = Path(memory_dir).expanduser()
+ return sum(1 for _ in path.glob("*-raw*.md"))
+
+
+def _library_record(config):
+ """Local research library that feeds the report's 'From your library' block.
+
+ This is not a network source - it reports how many saved briefs are indexed
+ so the 'From your library' block's presence is explained on the health
+ surface. Read-only and never fails the run: an empty store, a missing store,
+ or a SQLite build without FTS5 all resolve to an informational OK line.
+ """
+ from . import library, library_index
+
+ if not library_index.fts5_available():
+ return _record(
+ status=health.OK,
+ requires="none (local SQLite)",
+ note=(
+ "search index unavailable (this SQLite build lacks FTS5); "
+ "saved briefs still render, `library search` is disabled"
+ ),
+ )
+ try:
+ count = _count_saved_briefs(
+ config.get("LAST30DAYS_MEMORY_DIR") or library.DEFAULT_MEMORY_DIR
+ )
+ except Exception:
+ return _record(
+ status=health.OK,
+ requires="none (local SQLite)",
+ note="local research library (powers the 'From your library' block)",
+ )
+ if count == 0:
+ note = "no saved briefs yet - runs you save build this over time"
+ else:
+ plural = "brief" if count == 1 else "briefs"
+ note = (
+ f"{count} saved {plural}; powers the 'From your library' block "
+ "(LAST30DAYS_LIBRARY_CONTEXT=off to hide)"
+ )
+ return _record(status=health.OK, requires="none (local SQLite)", note=note)
+
+
_SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
"reddit": _reddit_record,
"x": _x_record,
@@ -456,6 +585,7 @@ _SOURCE_BUILDERS: Dict[str, Callable[[Dict[str, Any]], Dict[str, Any]]] = {
"pinterest": _pinterest_record,
"xiaohongshu": _xiaohongshu_record,
"jobs": _jobs_record,
+ "library": _library_record,
}
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 0aab13f5..0824a0c5 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -198,7 +198,15 @@ def _render_drill_context(report: schema.Report) -> list[str]:
def _render_library_context(report: schema.Report) -> list[str]:
if not report.library_context:
return []
- lines = [library_index.LIBRARY_CONTEXT_START, "## From your library", ""]
+ lines = [
+ library_index.LIBRARY_CONTEXT_START,
+ "## From your library",
+ "",
+ "_Prior saved runs on this topic from your local research library "
+ "(historical context, not fresh evidence; set "
+ "LAST30DAYS_LIBRARY_CONTEXT=off to hide)._",
+ "",
+ ]
for item in report.library_context:
detail = _truncate(item.summary or item.headline, 220)
lines.append(
@@ -2038,9 +2046,12 @@ def _footer_line_for_source(emoji: str, label: str, count: int, item_word: str,
def _build_source_footer_lines(report: schema.Report) -> list[str]:
- """Return emoji-tree lines for populated and outcome-bearing sources.
+ """Return emoji-tree lines for populated sources only (>=1 item).
- The caller adds the tree characters (├─ / └─) after assembling all lines.
+ Sources that returned zero items - clean NO_RESULTS or a failure - are
+ omitted; their outcome still surfaces in the ## Source Coverage /
+ ## Partial Coverage evidence blocks. The caller adds the tree characters
+ (├─ / └─) after assembling all lines.
"""
out: list[str] = []
for source_key, emoji, label, item_word, engagement_fields in _FOOTER_SOURCES:
@@ -2103,18 +2114,12 @@ def _build_source_footer_lines(report: schema.Report) -> list[str]:
line += f" │ ⚠ {_format_outcome(outcome)}"
out.append(line)
- populated = {source for source, items in report.items_by_source.items() if items}
- footer_meta = {
- source: (emoji, label)
- for source, emoji, label, _item_word, _engagement in _FOOTER_SOURCES
- }
- footer_meta.update({"polymarket": ("📊", "Polymarket"), "grounding": ("🌐", "Web")})
- for source, outcome in sorted(report.source_status.items()):
- if source in populated:
- continue
- emoji, label = footer_meta.get(source, ("⚪", _source_label(source)))
- out.append(f"{emoji} {label}: {_format_outcome(outcome)}")
-
+ # Only populated sources (>=1 item) get an emoji-tree line. A source that
+ # returned zero items - whether it completed cleanly (NO_RESULTS) or failed
+ # (rate-limited / unreachable / etc.) - is omitted from the user-facing
+ # footer. Its failure signal remains visible to synthesis in the
+ # ## Partial Coverage / ## Source Coverage evidence blocks, so nothing is
+ # silently lost; the conclusion surface just stays clean.
return out
@@ -2156,12 +2161,12 @@ def _render_emoji_footer(report: schema.Report, save_path: str | None) -> list[s
"""Produce the deterministic magic footer block.
Returns a list of markdown lines, including enclosing ``---`` separators.
- Returns an empty list if the report has neither source items nor outcomes.
+ Returns an empty list only when there is nothing to report - no populated
+ sources, no top voices, and no save path. When every source returned zero
+ items but a save path exists, the banner and the 'Raw results saved to' line
+ still render so the durable raw-file citation is never silently dropped.
"""
source_lines = _build_source_footer_lines(report)
- if not source_lines:
- return []
-
voices_line = _top_voices_footer_line(report)
raw_line = f"📎 Raw results saved to {save_path}" if save_path else None
@@ -2172,6 +2177,9 @@ def _render_emoji_footer(report: schema.Report, save_path: str | None) -> list[s
if raw_line:
body.append(raw_line)
+ if not body:
+ return []
+
# Apply tree characters: ├─ for all but the last body line, └─ for the last.
tree_lines: list[str] = []
for i, line in enumerate(body):
diff --git a/tests/test_doctor.py b/tests/test_doctor.py
index aa643693..78185116 100644
--- a/tests/test_doctor.py
+++ b/tests/test_doctor.py
@@ -17,6 +17,7 @@ Covers the plan's U4 scenarios:
import io
import json
+import os
import sys
import unittest
from contextlib import redirect_stderr, redirect_stdout
@@ -107,11 +108,24 @@ class _Hermetic:
return_value=("missing", "no token store at ~/.xurl"),
),
mock.patch("lib.backends.which", lambda name: None),
+ # Hermetic library: never glob the user's real saved-research dir.
+ # Tests that assert a specific brief count override this.
+ mock.patch("lib.doctor._count_saved_briefs", return_value=0),
+ # FTS5 is present on CI/dev SQLite; pin it so the library record's
+ # branch is deterministic regardless of the host's SQLite build.
+ mock.patch("lib.library_index.fts5_available", return_value=True),
+ # Snapshot os.environ so the CLAUDECODE scrub below is restored on
+ # exit. The real test shell (Claude Code) sets CLAUDECODE=1, which
+ # would otherwise make doctor's host-native web detection fire in
+ # every test and mask the keyless-degraded path. Tests that want the
+ # host-native path pass CLAUDECODE explicitly in their config dict.
+ mock.patch.dict(os.environ, {}, clear=False),
]
def __enter__(self):
for p in self._patches:
p.start()
+ os.environ.pop("CLAUDECODE", None)
return self
def __exit__(self, *exc):
@@ -210,6 +224,78 @@ class UnconfiguredXWithBrokenNode(unittest.TestCase):
self.assertNotIn("node", bird["fix"].lower())
+class CookieBackedXReadiness(unittest.TestCase):
+ """U2: when bird is installed and FROM_BROWSER will authenticate X at run
+ time, doctor reports X as Ready (not Off) with an honest, unverified note -
+ matching the real run behavior where browser cookies serve X fine even
+ though diagnose loads config in plan_only mode."""
+
+ def test_x_ready_when_bird_installed_and_from_browser(self):
+ with _Hermetic(), mock.patch("lib.bird_x.is_bird_installed", return_value=True):
+ report = doctor.build_report({"FROM_BROWSER": "auto"})
+ record = report["sources"]["x"]
+ self.assertEqual("ok", record["tier"])
+ self.assertEqual("ok", record["status"])
+ note = record["note"].lower()
+ self.assertIn("browser cookies", note)
+ self.assertIn("not verified", note)
+ self.assertIn("xai_api_key", note)
+
+ def test_x_stays_off_when_bird_installed_but_no_consent(self):
+ # bird installed but FROM_BROWSER=off -> no cookie path -> genuinely off.
+ with _Hermetic(), mock.patch("lib.bird_x.is_bird_installed", return_value=True):
+ report = doctor.build_report({"FROM_BROWSER": "off"})
+ record = report["sources"]["x"]
+ self.assertEqual("off", record["tier"])
+ self.assertEqual("unconfigured", record["status"])
+
+ def test_x_stays_off_when_consent_but_bird_missing(self):
+ # FROM_BROWSER set but bird not installed -> no runtime path -> off.
+ report = _build({"FROM_BROWSER": "auto"})
+ record = report["sources"]["x"]
+ self.assertEqual("off", record["tier"])
+ self.assertEqual("unconfigured", record["status"])
+
+
+class LibraryDoctorLine(unittest.TestCase):
+ """U5: doctor reports the local research library so the report's
+ 'From your library' block is explained on the health surface."""
+
+ def test_library_reports_indexed_brief_count(self):
+ with _Hermetic(), mock.patch("lib.doctor._count_saved_briefs", return_value=3):
+ record = doctor.build_report({})["sources"]["library"]
+ self.assertEqual("ok", record["status"])
+ self.assertIn("3 saved briefs", record["note"])
+
+ def test_library_empty_store_is_informational_ok(self):
+ record = _build({})["sources"]["library"] # count stubbed to 0
+ self.assertEqual("ok", record["status"])
+ self.assertIn("no saved briefs yet", record["note"])
+
+ def test_library_without_fts5_degrades_informationally(self):
+ # Inner patch overrides the _Hermetic FTS5 pin.
+ with _Hermetic(), mock.patch("lib.library_index.fts5_available", return_value=False):
+ record = doctor.build_report({})["sources"]["library"]
+ self.assertEqual("ok", record["status"])
+ self.assertIn("FTS5", record["note"])
+
+ def test_library_scan_failure_is_informational_ok(self):
+ # A glob/OS error must never fail the run - it degrades to an OK line.
+ with _Hermetic(), mock.patch(
+ "lib.doctor._count_saved_briefs", side_effect=OSError("permission denied")
+ ):
+ record = doctor.build_report({})["sources"]["library"]
+ self.assertEqual("ok", record["status"])
+ self.assertIn("local research library", record["note"])
+
+ def test_library_line_present_in_text_render(self):
+ text = doctor.render_text(_build({}))
+ self.assertTrue(
+ any("library" in l for l in text.splitlines()),
+ "doctor text output must carry a library line",
+ )
+
+
class JsonShape(unittest.TestCase):
"""Scenario 2: documented per-source shape for every registered source."""
@@ -456,20 +542,84 @@ class YoutubeTranscriptionNote(unittest.TestCase):
record = self.report["sources"]["youtube"]
self.assertEqual("ok", record["tier"])
self.assertEqual("ok", record["status"])
- self.assertIn("no transcription key for caption-free videos", record["note"])
+ note = record["note"].lower()
+ # Honest note: affirms the working path, scopes the key to caption-free.
+ self.assertIn("search + transcripts work", note)
+ self.assertIn("caption-free", note)
+ # Does not read as broken and does not attribute comment text to yt-dlp.
+ self.assertNotIn("no transcription key for caption-free videos", note)
self.assertIn(self.entry.fix_nl, record["fix"])
self.assertIn(self.entry.fix_cli, record["fix"])
+ def test_comment_text_attributed_to_scrapecreators_not_ytdlp(self):
+ # config has no ScrapeCreators key -> comment note names ScrapeCreators,
+ # never claims comment text comes from yt-dlp.
+ note = self.report["sources"]["youtube"]["note"].lower()
+ self.assertIn("comment text needs a scrapecreators key", note)
+
def test_text_line_includes_the_fix_on_the_ok_line(self):
text = doctor.render_text(self.report)
line = next(
l for l in text.splitlines() if l.strip().startswith("✓ youtube")
)
- self.assertIn("no transcription key for caption-free videos", line)
+ self.assertIn("search + transcripts work", line)
self.assertIn(f"fix: {self.entry.fix_nl}", line)
self.assertIn(self.entry.fix_cli, line)
+class YoutubeCommentsFixLine(unittest.TestCase):
+ """Greptile P2: when only the comment-text caveat fires (transcription key
+ present), the record still carries an actionable fix line."""
+
+ def test_comments_fix_names_scrapecreators_when_no_key(self):
+ record = _build(
+ {"GROQ_API_KEY": "dummy-groq-secret-000"},
+ probe_map={"yt-dlp": health.OK},
+ )["sources"]["youtube"]
+ self.assertEqual("ok", record["status"])
+ note = record["note"].lower()
+ self.assertIn("comment text needs", note)
+ self.assertNotIn("caption-free", note) # transcription caveat absent
+ self.assertTrue(record["fix"], "comment-text caveat must carry a fix")
+
+ def test_comments_fix_names_optin_when_key_present(self):
+ record = _build(
+ {
+ "GROQ_API_KEY": "dummy-groq-secret-000",
+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",
+ },
+ probe_map={"yt-dlp": health.OK},
+ )["sources"]["youtube"]
+ self.assertEqual("ok", record["status"])
+ self.assertIn("youtube_comments", record["fix"])
+ self.assertIn("INCLUDE_SOURCES", record["fix"])
+
+ def test_transcription_fix_takes_precedence_when_both_fire(self):
+ record = _build({}, probe_map={"yt-dlp": health.OK})["sources"]["youtube"]
+ entry = prescriptions.get("youtube", "transcription_key_missing")
+ self.assertIn(entry.fix_nl, record["fix"])
+
+
+class YoutubeHealthyWhenFullyConfigured(unittest.TestCase):
+ """U3: with a transcription key AND comment access, the YouTube note carries
+ no caveat - it is cleanly Ready."""
+
+ def test_no_caveats_when_transcription_and_comments_available(self):
+ report = _build(
+ {
+ "GROQ_API_KEY": "dummy-groq-secret-000",
+ "SCRAPECREATORS_API_KEY": "dummy-sc-secret-000",
+ "INCLUDE_SOURCES": "youtube_comments",
+ },
+ probe_map={"yt-dlp": health.OK},
+ )
+ record = report["sources"]["youtube"]
+ self.assertEqual("ok", record["status"])
+ note = record["note"].lower()
+ self.assertNotIn("caption-free", note)
+ self.assertNotIn("comment text needs", note)
+
+
class NativeSearchHost(unittest.TestCase):
"""Scenario 6: native-search host with no web keys -> off, not error."""
@@ -480,6 +630,35 @@ class NativeSearchHost(unittest.TestCase):
self.assertEqual("unconfigured", record["status"])
self.assertIn("host-native search", record["note"])
+ def test_web_on_claudecode_host_is_native_not_degraded(self):
+ # CLAUDECODE set but LAST30DAYS_NATIVE_SEARCH unset (the standalone
+ # `doctor` case) -> host-native note, not "degraded/keyless".
+ report = _build({"CLAUDECODE": "1"})
+ record = report["sources"]["web"]
+ self.assertEqual("off", record["tier"])
+ self.assertEqual("unconfigured", record["status"])
+ note = record["note"]
+ self.assertIn("Claude Code", note)
+ # Must NOT cite an env var the user never set.
+ self.assertNotIn("LAST30DAYS_NATIVE_SEARCH", note)
+
+ def test_web_native_via_real_env_var_not_just_config(self):
+ # Production path: env.get_config() never puts CLAUDECODE in the config
+ # dict, so the os.environ branch is the ONLY one a real Claude Code
+ # session hits. Set the process env var (config has no CLAUDECODE key).
+ with _Hermetic(), mock.patch.dict(os.environ, {"CLAUDECODE": "1"}):
+ record = doctor.build_report({})["sources"]["web"]
+ self.assertEqual("off", record["tier"])
+ self.assertIn("Claude Code", record["note"])
+ self.assertNotIn("LAST30DAYS_NATIVE_SEARCH", record["note"])
+
+ def test_web_stays_degraded_keyless_without_native_signal(self):
+ # No CLAUDECODE, no LAST30DAYS_NATIVE_SEARCH -> genuine keyless floor.
+ record = _build({})["sources"]["web"]
+ self.assertEqual("warn", record["tier"])
+ self.assertEqual("degraded", record["status"])
+ self.assertEqual("keyless", record["active_backend"])
+
def test_web_with_key_stays_ok_on_native_host(self):
report = _build({
"LAST30DAYS_NATIVE_SEARCH": "1",
diff --git a/tests/test_render_footer.py b/tests/test_render_footer.py
new file mode 100644
index 00000000..b072e163
--- /dev/null
+++ b/tests/test_render_footer.py
@@ -0,0 +1,185 @@
+"""Footer rendering: non-populated sources are dropped from the emoji tree.
+
+Covers U1 of the doctor-classification-and-footer-noresults plan. A source that
+returned zero items - whether it completed cleanly (NO_RESULTS) or failed
+(RATE_LIMITED / UNREACHABLE) - must not appear as its own emoji-tree line. The
+failure signal stays visible in the evidence blocks (## Partial Coverage /
+## Source Coverage) so synthesis still sees it (R7), just not in the user-facing
+footer.
+"""
+
+from lib import health, render, schema
+
+
+def _report(*, items_by_source=None, source_status=None, errors_by_source=None):
+ return schema.Report(
+ topic="test topic",
+ range_from="2026-06-10",
+ range_to="2026-07-10",
+ generated_at="2026-07-10T18:22:03Z",
+ provider_runtime=schema.ProviderRuntime(
+ reasoning_provider="gemini",
+ planner_model="test-planner",
+ rerank_model="test-reranker",
+ ),
+ query_plan=schema.QueryPlan(
+ intent="general",
+ freshness_mode="balanced_recent",
+ cluster_mode="story",
+ raw_topic="test topic",
+ subqueries=[
+ schema.SubQuery(
+ label="primary",
+ search_query="test topic",
+ ranking_query="test topic",
+ sources=["reddit"],
+ )
+ ],
+ source_weights={"reddit": 1.0},
+ ),
+ clusters=[],
+ ranked_candidates=[],
+ items_by_source=items_by_source or {},
+ errors_by_source=errors_by_source or {},
+ source_status=source_status or {},
+ )
+
+
+def _reddit_item():
+ return schema.SourceItem(
+ item_id="r1",
+ source="reddit",
+ title="A thread",
+ body="body",
+ url="https://reddit.com/r/test/comments/1",
+ )
+
+
+def test_footer_omits_clean_no_results_sources():
+ report = _report(
+ items_by_source={"reddit": [_reddit_item()]},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
+ "jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS),
+ "polymarket": schema.SourceOutcome(source="polymarket", state=schema.NO_RESULTS),
+ "youtube": schema.SourceOutcome(source="youtube", state=schema.NO_RESULTS),
+ },
+ )
+
+ text = render.render_compact(report)
+
+ # Populated source stays.
+ assert "🟠 Reddit: 1 thread" in text
+ # Clean zero-result sources do not get a footer line.
+ assert "Jobs: no results" not in text
+ assert "Polymarket: no results" not in text
+ assert "YouTube: no results" not in text
+
+
+def test_footer_omits_errored_zero_item_source_but_keeps_evidence():
+ report = _report(
+ items_by_source={"reddit": [_reddit_item()]},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
+ "x": schema.SourceOutcome(
+ source="x",
+ state=schema.RATE_LIMITED,
+ detail="HTTP 429 after retry budget",
+ fix_hint="doctor",
+ ),
+ },
+ errors_by_source={"x": "HTTP 429 after retry budget"},
+ )
+
+ text = render.render_compact(report)
+
+ # The failed zero-item source is dropped from the emoji-tree footer.
+ assert "🔵 X: rate-limited" not in text
+ # ... but its failure is still visible to synthesis in the evidence blocks (R7).
+ assert "## Partial Coverage" in text
+ assert "Do not interpret a failed source as no discussion" in text
+
+
+def test_footer_preserves_save_path_when_all_sources_empty():
+ # Every source returned zero items -> no source lines, but the durable
+ # raw-file citation must still render (regression guard for the U1 loop
+ # removal, which previously suppressed the whole footer incl. save path).
+ report = _report(
+ source_status={
+ "jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS),
+ "x": schema.SourceOutcome(
+ source="x", state=schema.RATE_LIMITED, detail="429", fix_hint="doctor"
+ ),
+ },
+ )
+ footer = render._render_emoji_footer(report, "/tmp/l30d-scratch/topic-raw.md")
+
+ text = "\n".join(footer)
+ assert "✅ All agents reported back!" in text
+ assert "Raw results saved to /tmp/l30d-scratch/topic-raw.md" in text
+ # No per-source line for the zero-item sources.
+ assert "Jobs" not in text
+ assert "rate-limited" not in text
+
+
+def test_footer_empty_with_no_save_path_returns_nothing():
+ report = _report(
+ source_status={"jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS)},
+ )
+ assert render._render_emoji_footer(report, None) == []
+
+
+def test_library_block_carries_explainer_when_populated():
+ report = _report(items_by_source={"reddit": [_reddit_item()]})
+ report.library_context = [
+ schema.LibraryContext(
+ topic="test topic",
+ published_date="2026-07-01",
+ headline="a prior finding",
+ summary="a prior finding",
+ source_kind="brief",
+ )
+ ]
+
+ text = render.render_compact(report)
+
+ assert "## From your library" in text
+ assert "Prior saved runs" in text
+ assert "LAST30DAYS_LIBRARY_CONTEXT=off" in text
+
+
+def test_library_block_and_explainer_absent_when_empty():
+ report = _report(items_by_source={"reddit": [_reddit_item()]})
+ text = render.render_compact(report)
+ assert "## From your library" not in text
+ assert "Prior saved runs" not in text
+
+
+def test_footer_keeps_partial_populated_source_with_warning():
+ """A source that returned SOME items but then failed stays in the footer
+ with its ⚠ suffix - only zero-item sources are dropped."""
+ ig_item = schema.SourceItem(
+ item_id="ig1",
+ source="instagram",
+ title="A reel",
+ body="caption",
+ url="https://instagram.com/reel/1",
+ )
+ report = _report(
+ items_by_source={"reddit": [_reddit_item()], "instagram": [ig_item]},
+ source_status={
+ "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
+ "instagram": schema.SourceOutcome(
+ source="instagram",
+ state=schema.PARTIAL,
+ items_returned=1,
+ detail="HTTP 400: Bad Request",
+ fix_hint="doctor",
+ ),
+ },
+ )
+
+ text = render.render_compact(report)
+
+ assert "📸 Instagram: 1 reel" in text
+ assert "⚠" in text # partial suffix preserved on the populated line
diff --git a/tests/test_source_outcomes.py b/tests/test_source_outcomes.py
index 9ac3a59a..129c503a 100644
--- a/tests/test_source_outcomes.py
+++ b/tests/test_source_outcomes.py
@@ -305,9 +305,12 @@ def test_footer_and_synthesis_note_surface_failed_source():
text = render.render_compact(report)
+ # A failed source that returned zero items is surfaced to synthesis via the
+ # evidence blocks (## Partial Coverage), NOT as a user-facing footer line -
+ # zero-item sources are dropped from the emoji tree (see test_render_footer).
assert "## Partial Coverage" in text
assert "Do not interpret a failed source as no discussion" in text
- assert "🔵 X: rate-limited: HTTP 429 after retry budget (run doctor for fixes)" in text
+ assert "🔵 X: rate-limited: HTTP 429 after retry budget (run doctor for fixes)" not in text
def test_report_source_status_round_trips_through_schema_serialization():