返回 last30days-skill
test_render_footer.py
根目录 / tests / test_render_footer.py
1 """Footer rendering: non-populated sources are dropped from the emoji tree.
2
3 Covers U1 of the doctor-classification-and-footer-noresults plan. A source that
4 returned zero items - whether it completed cleanly (NO_RESULTS) or failed
5 (RATE_LIMITED / UNREACHABLE) - must not appear as its own emoji-tree line. The
6 failure signal stays visible in the evidence blocks (## Partial Coverage /
7 ## Source Coverage) so synthesis still sees it (R7), just not in the user-facing
8 footer.
9 """
10
11 from lib import health, render, schema
12
13
14 def _report(*, items_by_source=None, source_status=None, errors_by_source=None):
15 return schema.Report(
16 topic="test topic",
17 range_from="2026-06-10",
18 range_to="2026-07-10",
19 generated_at="2026-07-10T18:22:03Z",
20 provider_runtime=schema.ProviderRuntime(
21 reasoning_provider="gemini",
22 planner_model="test-planner",
23 rerank_model="test-reranker",
24 ),
25 query_plan=schema.QueryPlan(
26 intent="general",
27 freshness_mode="balanced_recent",
28 cluster_mode="story",
29 raw_topic="test topic",
30 subqueries=[
31 schema.SubQuery(
32 label="primary",
33 search_query="test topic",
34 ranking_query="test topic",
35 sources=["reddit"],
36 )
37 ],
38 source_weights={"reddit": 1.0},
39 ),
40 clusters=[],
41 ranked_candidates=[],
42 items_by_source=items_by_source or {},
43 errors_by_source=errors_by_source or {},
44 source_status=source_status or {},
45 )
46
47
48 def _reddit_item():
49 return schema.SourceItem(
50 item_id="r1",
51 source="reddit",
52 title="A thread",
53 body="body",
54 url="https://reddit.com/r/test/comments/1",
55 )
56
57
58 def test_compact_keeps_untyped_source_failures_visible():
59 report = _report(
60 items_by_source={"reddit": [_reddit_item()]},
61 errors_by_source={"x": "unavailable from legacy runner"},
62 )
63 text = render.render_compact(report)
64 assert "## Partial Coverage" in text
65 assert "X failed" in text
66 assert "- X: 0 items (failed)" in text
67 assert "unavailable from legacy runner" not in text
68
69
70 def test_footer_omits_clean_no_results_sources():
71 report = _report(
72 items_by_source={"reddit": [_reddit_item()]},
73 source_status={
74 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
75 "jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS),
76 "polymarket": schema.SourceOutcome(source="polymarket", state=schema.NO_RESULTS),
77 "youtube": schema.SourceOutcome(source="youtube", state=schema.NO_RESULTS),
78 },
79 )
80
81 text = render.render_compact(report)
82
83 # Populated source stays.
84 assert "🟠 Reddit: 1 thread" in text
85 # Clean zero-result sources do not get a footer line.
86 assert "Jobs: no results" not in text
87 assert "Polymarket: no results" not in text
88 assert "YouTube: no results" not in text
89
90
91 def test_footer_omits_errored_zero_item_source_but_keeps_evidence():
92 report = _report(
93 items_by_source={"reddit": [_reddit_item()]},
94 source_status={
95 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
96 "x": schema.SourceOutcome(
97 source="x",
98 state=schema.RATE_LIMITED,
99 detail="HTTP 429 after retry budget",
100 fix_hint="doctor",
101 ),
102 },
103 errors_by_source={"x": "HTTP 429 after retry budget"},
104 )
105
106 text = render.render_compact(report)
107
108 # The failed zero-item source is dropped from the emoji-tree footer.
109 assert "🔵 X: rate-limited" not in text
110 # ... but its failure is still visible to synthesis in the evidence blocks (R7).
111 assert "## Partial Coverage" in text
112 assert "A failed source is not evidence of no discussion" in text
113
114
115 def test_footer_preserves_save_path_when_all_sources_empty():
116 # Every source returned zero items -> no source lines, but the durable
117 # raw-file citation must still render (regression guard for the U1 loop
118 # removal, which previously suppressed the whole footer incl. save path).
119 report = _report(
120 source_status={
121 "jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS),
122 "x": schema.SourceOutcome(
123 source="x", state=schema.RATE_LIMITED, detail="429", fix_hint="doctor"
124 ),
125 },
126 )
127 footer = render._render_emoji_footer(report, "/tmp/l30d-scratch/topic-raw.md")
128
129 text = "\n".join(footer)
130 assert "✅ All agents reported back!" in text
131 assert "Raw results saved to /tmp/l30d-scratch/topic-raw.md" in text
132 # No per-source line for the zero-item sources.
133 assert "Jobs" not in text
134 assert "rate-limited" not in text
135
136
137 def test_footer_empty_with_no_save_path_returns_nothing():
138 report = _report(
139 source_status={"jobs": schema.SourceOutcome(source="jobs", state=schema.NO_RESULTS)},
140 )
141 assert render._render_emoji_footer(report, None) == []
142
143
144 def test_library_block_carries_explainer_when_populated():
145 report = _report(items_by_source={"reddit": [_reddit_item()]})
146 report.library_context = [
147 schema.LibraryContext(
148 topic="test topic",
149 published_date="2026-07-01",
150 headline="a prior finding",
151 summary="a prior finding",
152 source_kind="brief",
153 )
154 ]
155
156 text = render.render_compact(report)
157
158 assert "## From your library" in text
159 assert "Prior saved runs" in text
160 assert "LAST30DAYS_LIBRARY_CONTEXT=off" in text
161
162
163 def test_library_block_and_explainer_absent_when_empty():
164 report = _report(items_by_source={"reddit": [_reddit_item()]})
165 text = render.render_compact(report)
166 assert "## From your library" not in text
167 assert "Prior saved runs" not in text
168
169
170 def test_footer_keeps_partial_populated_source_without_warning_text():
171 """A source that returned SOME items but then failed stays in the footer
172 as counts only: run diagnostics live in doctor --postmortem, the saved raw
173 file, and the model-facing ## Partial Coverage note, never on the
174 user-facing conclusion surface."""
175 ig_item = schema.SourceItem(
176 item_id="ig1",
177 source="instagram",
178 title="A reel",
179 body="caption",
180 url="https://instagram.com/reel/1",
181 )
182 report = _report(
183 items_by_source={"reddit": [_reddit_item()], "instagram": [ig_item]},
184 source_status={
185 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
186 "instagram": schema.SourceOutcome(
187 source="instagram",
188 state=schema.PARTIAL,
189 items_returned=1,
190 detail="HTTP 400: Bad Request",
191 fix_hint="doctor",
192 ),
193 },
194 )
195
196 text = render.render_compact(report)
197
198 assert "📸 Instagram: 1 reel" in text
199 footer = text.split("✅ All agents reported back!", 1)[1]
200 assert "⚠" not in footer
201 assert "run doctor" not in footer
202 assert "## Partial Coverage" in text
203 assert "Instagram" in text.split("## Partial Coverage", 1)[1].split("\n\n", 1)[0] or "Instagram partial" in text
204
205
206 def test_footer_auth_failed_populated_source_has_no_warning_text():
207 ig_item = schema.SourceItem(
208 item_id="ig1",
209 source="instagram",
210 title="A reel",
211 body="caption",
212 url="https://instagram.com/reel/1",
213 )
214 report = _report(
215 items_by_source={"reddit": [_reddit_item()], "instagram": [ig_item]},
216 source_status={
217 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
218 "instagram": schema.SourceOutcome(
219 source="instagram",
220 state=schema.AUTH_FAILED,
221 items_returned=1,
222 detail="HTTP 401",
223 fix_hint="doctor",
224 ),
225 },
226 )
227
228 text = render.render_compact(report)
229 footer = text.split("✅ All agents reported back!", 1)[1]
230
231 assert "📸 Instagram: 1 reel" in footer
232 assert "⚠" not in footer
233 assert "auth-failed" in text.split("## Partial Coverage", 1)[1]
234
235
236 def test_compact_drops_source_failure_warnings_and_source_errors_block():
237 report = _report(
238 items_by_source={"reddit": [_reddit_item()]},
239 source_status={
240 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
241 "jobs": schema.SourceOutcome(source="jobs", state=schema.UNREACHABLE, items_returned=0, detail="DNS"),
242 },
243 )
244 report.warnings = [
245 "Some sources failed: jobs",
246 "Some sources returned partial results (degraded): reddit",
247 "Evidence is thin for this topic.",
248 ]
249 report.errors_by_source = {"jobs": "URL Error: nodename nor servname provided"}
250
251 compact = render.render_compact(report)
252 assert "## Source Errors" not in compact
253 assert "Some sources failed" not in compact
254 assert "returned partial results" not in compact
255 assert "Evidence is thin for this topic." in compact
256
257 full = render.render_full(report)
258 assert "## Source Errors" in full
259
260 payload = schema.to_dict(report)
261 assert payload["warnings"] == report.warnings
262 assert payload["errors_by_source"] == {"jobs": "URL Error: nodename nor servname provided"}
263 assert payload["source_status"]["jobs"]["state"] == schema.UNREACHABLE
264
265
266 def test_future_and_invalid_dates_do_not_count_as_recent_evidence():
267 def item(date):
268 return schema.SourceItem(item_id=date, source="reddit", title="Evidence", body="",
269 url="https://example.test/", published_at=date)
270
271 report = _report(items_by_source={"reddit": [
272 item("2026-07-03"),
273 item("2026-07-11T00:30:00+02:00"),
274 item("2026-07-10T23:30:00-02:00"),
275 item("2026-07-11"),
276 item("not a date"),
277 item(12345),
278 ]})
279 text = render.render_compact(report)
280 assert "2 of 2 dated items are from the last 7 days" in text
281
282
283 def test_footer_carries_freshness_verdict():
284 """The freshness verdict reaches the footer, not just the report body."""
285 stale = [
286 schema.SourceItem(
287 item_id=f"r{i}",
288 source="reddit",
289 title=f"Old thread {i}",
290 body="body",
291 url=f"https://reddit.com/r/test/comments/{i}",
292 published_at="2026-06-12",
293 date_confidence="high",
294 )
295 for i in range(6)
296 ]
297 report = _report(
298 items_by_source={"reddit": stale},
299 source_status={
300 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=6),
301 },
302 )
303
304 text = render.render_compact(report)
305
306 assert "🕒" in text
307 assert "from the last 7 days" in text
308
309
310 def test_footer_freshness_line_absent_when_evidence_is_recent():
311 fresh = [
312 schema.SourceItem(
313 item_id=f"r{i}",
314 source="reddit",
315 title=f"Fresh thread {i}",
316 body="body",
317 url=f"https://reddit.com/r/test/comments/{i}",
318 published_at="2026-07-08",
319 date_confidence="high",
320 )
321 for i in range(6)
322 ]
323 report = _report(
324 items_by_source={"reddit": fresh},
325 source_status={
326 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=6),
327 },
328 )
329
330 assert "🕒" not in render.render_compact(report)
331
332
333 def test_github_snapshot_cards_are_visible_but_do_not_count_as_recent_events():
334 cards = [
335 schema.SourceItem(
336 item_id=f"repo-{i}", source="github", title=f"Project {i}", body="",
337 url=f"https://github.com/example/project-{i}", published_at="2026-07-10",
338 metadata={"date_is_snapshot": True},
339 )
340 for i in range(3)
341 ]
342 report = _report(items_by_source={"github": cards})
343 text = render.render_compact(report)
344 assert "GitHub: 3 items" in text
345 assert "no usable dated evidence" in text
346
347 # An actual release and a legacy item with no snapshot marker keep their dates.
348 cards[0].metadata["date_is_snapshot"] = False
349 cards[1].metadata.clear()
350 cards[1].published_at = "2026-06-15"
351 assert "1 of 2 dated items" in render.render_compact(report)
352
353 restored = schema.report_from_dict(schema.to_dict(report))
354 assert "1 of 2 dated items" in render.render_full(restored, save_path="topic-raw.md")
355 assert "1 of 2 dated items" in render.render_for_html(restored)
356 assert any("1 of 2 dated items" in note for note in render.collect_html_warnings(restored))
357
358
359 def test_archived_github_counts_keep_their_observation_date_across_renderers():
360 repo = schema.SourceItem(
361 item_id="repo", source="github", title="Release", body="", url="https://github.com/example/one",
362 published_at="2026-07-08", engagement={"stars": 1200, "open_issues": 17},
363 metadata={"repo_counts_observed_on": "2026-07-12"},
364 )
365 profile = schema.SourceItem(
366 item_id="person", source="github", title="Contribution velocity", body="", url="https://github.com/example",
367 engagement={"merged_prs": 3, "total_prs": 8},
368 )
369 report = _report(items_by_source={"github": [repo, profile]})
370 report.generated_at = "2026-07-15T00:30:00+02:00"
371 restored = schema.report_from_dict(schema.to_dict(report))
372 note = "stars and open issues/PRs observed 2026-07-12 UTC"
373 for output in (
374 render.render_compact(restored), render.render_full(restored, save_path="saved.md"),
375 render.render_for_html(restored), render.render_comparison_multi([("A", restored), ("B", report)]),
376 render.render_for_html_comparison([("A", restored), ("B", report)]),
377 ):
378 line = next(line for line in output.splitlines() if "🐙 GitHub:" in line)
379 assert "1,200 stars" in line and "3 merged" in line and "8 total PRs" in line
380 assert note in line
381 assert note in "\n".join(render._render_stats(restored))
382
383 # Old captures only have a report time. Keep the UTC report date distinct from an observation.
384 repo.metadata.clear()
385 restored = schema.report_from_dict(schema.to_dict(report))
386 line = render._build_source_footer_lines(restored)[0]
387 assert "stars and open issues/PRs at retrieval (report generated 2026-07-14 UTC)" in line
388 assert "observed" not in line
389
390
391 def test_multiple_github_observation_days_and_undated_rows_in_a_drill():
392 def repo(name, day):
393 return schema.SourceItem(
394 item_id=name, source="github", title=name, body="", url=f"https://github.com/example/{name}",
395 engagement={"stars": 2}, metadata={"repo_counts_observed_on": day},
396 )
397
398 older = repo("one", "2026-07-12")
399 newer = repo("two", "2026-07-15")
400 report = _report(items_by_source={"github": [newer, older]})
401 report.generated_at = "2026-07-15T20:00:00Z"
402 report.artifacts["drill_history"] = [{"target": "two"}]
403 assert "4 stars │ stars observed 2026-07-12 to 2026-07-15 UTC" in render._build_source_footer_lines(report)[0]
404 older.engagement["stars"] = 0
405 assert "2 stars │ stars observed 2026-07-12 to 2026-07-15 UTC" in render._build_source_footer_lines(report)[0]
406 older.metadata["repo_counts_observed_on"] = "unrecorded"
407 report.range_to = "2026-07-15"
408 line = render._build_source_footer_lines(report)[0]
409 assert "stars at retrieval (report generated 2026-07-15 UTC)" in line and "observed" not in line
410
411 # A current-window report keeps its normal footer even when reopened later.
412 report.items_by_source["github"] = [newer]
413 assert render._build_source_footer_lines(report) == ["🐙 GitHub: 1 item │ 2 stars"]
414 newer.engagement = {"merged_prs": 3}
415 report.range_to = "2026-07-10"
416 assert render._build_source_footer_lines(report) == ["🐙 GitHub: 1 item │ 3 merged"]
417
418
419 def test_github_footer_and_stats_distinguish_missing_and_measured_zero():
420 def card(name, kind, counts):
421 return schema.SourceItem(
422 item_id=name, source="github", title=name, body="", url=f"https://github.com/example/{name}",
423 engagement=counts, metadata={"labels": [kind], **(
424 {"repo_counts_observed_on": "2026-07-12"} if counts else {}
425 )},
426 )
427
428 issue = card("thread", "bug", {"reactions": 4})
429 issue.metadata["labels"] = "bug-in-recent-push"
430 missing = card("push", "recent-push", {})
431 zeros = card("project", "project-mode", {"stars": 0, "open_issues": 0})
432 partial = card("owned", "own-repo", {"open_issues": 0})
433 external = card("other", "external-repo", {})
434 legacy = card("legacy", "own-repo", {"stars": 0, "open_issues": 0})
435 del legacy.metadata["repo_counts_observed_on"]
436 report = _report(items_by_source={"github": [issue]})
437 report.generated_at = "2026-07-12T12:00:00Z"
438 for items, expected, absent in [
439 ([issue], ["4 reactions"], ["unavailable", "0 stars"]),
440 ([missing], ["stars unavailable", "open issue/PR count unavailable"], ["0 stars", "observed"]),
441 ([zeros], ["0 stars", "0 open issues/PRs", "observed 2026-07-12 UTC"], ["unavailable"]),
442 ([partial], ["stars unavailable", "0 open issues/PRs", "open issues/PRs observed"], ["0 stars"]),
443 ([external], ["stars unavailable"], ["open issue", "0 stars"]),
444 ([legacy], [], ["0 stars", "0 open issues/PRs", "observed"]),
445 ([zeros, legacy], ["0 stars", "0 open issues/PRs", "1 of 2 repository cards"],
446 ["stars observed", "open issues/PRs observed"]),
447 ([issue, missing, zeros], ["0 stars", "0 open issues/PRs", "1 of 2 repository cards"],
448 ["1 of 3", "stars unavailable"]),
449 ]:
450 report.items_by_source["github"] = items
451 footer = render._build_source_footer_lines(report)[0]
452 assert all(word in footer for word in expected), footer
453 assert all(word not in footer for word in absent), footer
454 if items != [issue]:
455 stats = "\n".join(render._render_stats(report))
456 assert all(word in stats for word in expected), stats
457 assert footer in render.render_for_html(report)
458
459
460 def test_issue_labels_do_not_claim_repository_counter_coverage():
461 repo = schema.SourceItem(
462 item_id="selected", source="github", title="Selected project", body="", url="https://github.com/one/tool",
463 engagement={"stars": 8, "open_issues": 2}, metadata={"labels": ["project-mode"]},
464 )
465 for label in ("project-mode", "recent-push", "own-repo", "external-repo"):
466 for path, is_pr in (("issues/12", False), ("pull/13", True)):
467 issue = schema.SourceItem(
468 item_id="discussion", source="github", title="Discussion", body="",
469 url=f"https://github.com/one/tool/{path}", container="one/tool", engagement={"comments": 3},
470 metadata={"labels": [label], "is_pr": is_pr, "github_stars": {"one/tool": 8}},
471 )
472 assert not schema.github_repo_counter_fields(issue)
473 for items in ([issue], [issue, repo]):
474 report = _report(items_by_source={"github": items})
475 footer = render._build_source_footer_lines(report)[0]
476 assert "unavailable" not in footer and "of 2 repository cards" not in footer
477 assert "3 comments" in footer
478 if len(items) == 2:
479 assert "8 stars" in footer and "2 open issues/PRs" in footer
480
481
482 def test_raw_results_only_footer_includes_freshness_line():
483 """AE3: raw-results-only footer still includes the freshness line.
484
485 When every source returns zero items (so source_lines would be empty and
486 body starts empty) but a save_path is provided, the freshness verdict
487 must still appear alongside the raw-results line. Without the fix,
488 `if freshness_line and body:` would be False because body was empty.
489 """
490 report = _report(
491 items_by_source={},
492 source_status={},
493 )
494
495 footer = render._render_emoji_footer(report, "/tmp/l30d-scratch/topic-raw.md")
496 text = "\n".join(footer)
497
498 assert "🕒" in text
499 assert "no usable dated evidence" in text
500 assert "Raw results saved to /tmp/l30d-scratch/topic-raw.md" in text
501
502
503 def test_saved_raw_file_footer_is_fenced():
504 """A bare footer ends its tree row directly above ``---``, which CommonMark
505 reads as a Setext heading underline in the saved raw Markdown file."""
506 report = _report(
507 items_by_source={"reddit": [_reddit_item()]},
508 source_status={
509 "reddit": schema.SourceOutcome(source="reddit", state=health.OK, items_returned=1),
510 },
511 )
512
513 text = render.render_full(report, save_path="/tmp/l30d-scratch/topic-raw.md")
514 footer = text[text.index("✅ All agents reported back!") - len("```text\n---\n") :]
515
516 assert footer.startswith("```text\n---\n✅ All agents reported back!\n")
517 assert footer.rstrip("\n").endswith(
518 "└─ 📎 Raw results saved to /tmp/l30d-scratch/topic-raw.md\n---\n```"
519 )
520
520 lines PYTHON