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: four independently-verified bugs (#905, #908, #886, #909) (#912)

Som Samantraya940c9896503
diff --git a/changelog.d/886.fixed.md b/changelog.d/886.fixed.md
new file mode 100644
index 00000000..63d2946b
--- /dev/null
+++ b/changelog.d/886.fixed.md
@@ -0,0 +1 @@
+Source URLs in the saved raw report and internal evidence output now render as clickable markdown links instead of plain text.
diff --git a/changelog.d/886.security.md b/changelog.d/886.security.md
new file mode 100644
index 00000000..fb4abf68
--- /dev/null
+++ b/changelog.d/886.security.md
@@ -0,0 +1 @@
+Source URLs containing unsafe schemes or Markdown delimiters are now rendered as inert escaped text instead of raw Markdown.
diff --git a/changelog.d/905.fixed.md b/changelog.d/905.fixed.md
new file mode 100644
index 00000000..7d50be06
--- /dev/null
+++ b/changelog.d/905.fixed.md
@@ -0,0 +1 @@
+`--web-backend=keyless` is now accepted by the CLI, matching what `CONFIGURATION.md` already documented. The keyless web-search floor was already fully supported internally; only the argument parser rejected the value.
diff --git a/changelog.d/908.fixed.md b/changelog.d/908.fixed.md
new file mode 100644
index 00000000..ad476973
--- /dev/null
+++ b/changelog.d/908.fixed.md
@@ -0,0 +1 @@
+arXiv no longer returns zero results for natural-language multi-word topics. The exact-phrase quoted query now retries unquoted once when it matches nothing, instead of silently dropping arXiv from the report.
diff --git a/changelog.d/909.fixed.md b/changelog.d/909.fixed.md
new file mode 100644
index 00000000..b1014fa8
--- /dev/null
+++ b/changelog.d/909.fixed.md
@@ -0,0 +1 @@
+Truth Social search no longer fails with a Cloudflare-triggered HTTP 403 on every request. Requests now send browser-like headers, the same fix already applied to Reddit.
diff --git a/skills/last30days/scripts/last30days.py b/skills/last30days/scripts/last30days.py
index a430df06..7c8224cf 100644
--- a/skills/last30days/scripts/last30days.py
+++ b/skills/last30days/scripts/last30days.py
@@ -677,8 +677,9 @@ def build_parser() -> argparse.ArgumentParser:
parser.add_argument("--x-handle", help="X handle for targeted supplemental search")
parser.add_argument("--x-related", help="Comma-separated related X handles (searched with lower weight)")
parser.add_argument("--web-backend", default="auto",
- choices=["auto", "brave", "exa", "serper", "parallel", "none"],
- help="Web search backend (default: auto, tries Brave then Exa then Serper then Parallel)")
+ choices=["auto", "brave", "exa", "serper", "parallel", "keyless", "none"],
+ help="Web search backend (default: auto, tries Brave then Exa then Serper then Parallel; "
+ "keyless forces the zero-key DuckDuckGo/SearXNG floor)")
parser.add_argument("--deep-research", action="store_true",
help="Use Perplexity Deep Research (~$0.90/query) for in-depth analysis. Requires PERPLEXITY_API_KEY or OPENROUTER_API_KEY.")
parser.add_argument("--hiring-signals", action="store_true",
diff --git a/skills/last30days/scripts/lib/arxiv.py b/skills/last30days/scripts/lib/arxiv.py
index c333d715..082547b8 100644
--- a/skills/last30days/scripts/lib/arxiv.py
+++ b/skills/last30days/scripts/lib/arxiv.py
@@ -61,13 +61,21 @@ def _today() -> datetime:
return datetime.now(timezone.utc)
-def _build_search_query(topic: str) -> str:
- """Quote the topic so arXiv treats it as a phrase across all fields.
+def _build_search_query(topic: str, *, quoted: bool = True) -> str:
+ """Build the arXiv search-query string for ``topic``.
- Inner double-quotes are stripped (arXiv has no phrase-escaping); the outer
- quotes plus ``all:`` give a phrase-scoped relevance search.
+ Quoted (default): phrase-scoped exact match across all fields. Precise
+ for topics that genuinely appear as a phrase in a title/abstract, but a
+ natural-language multi-word topic ("AI video generation advances") almost
+ never appears verbatim, so it returns zero results (#908). Unquoted uses
+ an AND-conjoined clause for every individual term as a fallback retry.
+
+ Inner double-quotes are stripped (arXiv has no phrase-escaping) either way.
"""
- return f'all:"{_clean_phrase(topic)}"'
+ phrase = _clean_phrase(topic)
+ if quoted:
+ return f'all:"{phrase}"'
+ return " AND ".join(f'all:"{term}"' for term in phrase.split())
def _clean_phrase(topic: str) -> str:
@@ -75,12 +83,12 @@ def _clean_phrase(topic: str) -> str:
return " ".join(topic.replace('"', " ").split())
-def _build_search_args(topic: str, limit: int) -> List[str]:
+def _build_search_args(topic: str, limit: int, *, quoted: bool = True) -> List[str]:
return [
CLI_BIN,
"query",
"--search-query",
- _build_search_query(topic),
+ _build_search_query(topic, quoted=quoted),
"--sort-by",
"relevance",
"--max-results",
@@ -118,13 +126,18 @@ def _run_cli(cmd: List[str], timeout: int) -> Dict[str, Any]:
stdout = result.stdout or ""
if not stdout.strip():
- return {"results": []}
+ _log("CLI returned empty stdout")
+ return {"results": [], "error": "empty stdout"}
try:
data = json.loads(stdout)
except json.JSONDecodeError as exc:
_log(f"JSON decode failed: {exc}")
return {"results": [], "error": f"json decode: {exc}"}
+ if not _is_entry_envelope(data):
+ _log("CLI returned an unrecognized JSON response")
+ return {"results": [], "error": "unrecognized JSON response"}
+
return {"results": _extract_entries(data)}
@@ -150,6 +163,20 @@ def _extract_entries(data: Any) -> List[Dict[str, Any]]:
return []
+def _is_entry_envelope(data: Any) -> bool:
+ """Return whether ``data`` has one of the supported entry-list shapes."""
+ if isinstance(data, list):
+ return True
+ if not isinstance(data, dict):
+ return False
+ results = data.get("results")
+ return (
+ isinstance(results, list)
+ or (isinstance(results, dict) and isinstance(results.get("entries"), list))
+ or isinstance(data.get("entries"), list)
+ )
+
+
def search_arxiv(
topic: str,
from_date: str,
@@ -172,6 +199,13 @@ def search_arxiv(
_log(f"query '{topic}' (relevance, max={limit})")
response = _run_cli(cmd, timeout=SEARCH_TIMEOUT)
_log(f"found {len(response.get('results') or [])} entries")
+ # Retry a clean zero-result phrase match with individually quoted AND terms.
+ # CLI failures, malformed responses, and missing binaries skip the retry.
+ if not response.get("error") and not response.get("results"):
+ retry_cmd = _build_search_args(topic, limit, quoted=False)
+ _log(f"quoted phrase matched nothing; retrying unquoted for '{topic}'")
+ response = _run_cli(retry_cmd, timeout=SEARCH_TIMEOUT)
+ _log(f"unquoted retry found {len(response.get('results') or [])} entries")
return response
diff --git a/skills/last30days/scripts/lib/render.py b/skills/last30days/scripts/lib/render.py
index 39e78b56..828ba143 100644
--- a/skills/last30days/scripts/lib/render.py
+++ b/skills/last30days/scripts/lib/render.py
@@ -1641,6 +1641,75 @@ def render_comparison_multi_context(
return "\n".join(lines).strip() + "\n"
+_SAFE_MARKDOWN_LINK_SCHEMES = ("http", "https")
+_MARKDOWN_LINK_UNSAFE_CHARS = ("(", ")", "[", "]", "\\", "<", ">", "`")
+_MARKDOWN_PLAIN_TEXT_ESCAPES = re.compile(r"([\\`*_{}\[\]()#+\-.!|~:])")
+
+
+def _sanitize_url_for_single_line_output(url: str) -> str:
+ """Collapse embedded newlines/carriage-returns out of an untrusted URL.
+
+ A URL is not supposed to contain raw line breaks; a source-controlled
+ value that does could otherwise inject fabricated report structure
+ (fake headings, list items) into the saved single-line output --
+ whether or not it ends up wrapped in markdown link syntax. Applied
+ before either the link-safety check or the plain-text fallback below,
+ so this closes the injection at the root rather than only for links.
+ """
+ return "".join(
+ " "
+ if ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F
+ else ch
+ for ch in url
+ )
+
+
+def _escape_markdown_plain_text(value: str) -> str:
+ """Make untrusted text inert in Markdown without hiding its contents."""
+ value = value.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
+ return _MARKDOWN_PLAIN_TEXT_ESCAPES.sub(r"\\\1", value)
+
+
+def _markdown_url_link(url: str) -> str:
+ """Render ``url`` as a markdown link when it's safe to, else escaped text.
+
+ Source URLs are untrusted API responses, not authored content: `(`/`)`/
+ `[`/`]` would corrupt markdown link syntax, a backslash can escape
+ adjacent markdown delimiters, and an unrestricted scheme (e.g.
+ ``javascript:``) would become an active link with none of the safety
+ filtering ``html_render.py`` already applies via
+ ``html.escape(url, quote=True)``. Falls back to escaped plain text so
+ rejected input cannot remain active Markdown or raw HTML.
+ """
+ if not url:
+ return ""
+ sanitized_url = _sanitize_url_for_single_line_output(url)
+ if not sanitized_url.strip():
+ return ""
+
+ has_whitespace_or_control = any(
+ ch.isspace() or ord(ch) < 0x20 or 0x7F <= ord(ch) <= 0x9F
+ for ch in url
+ )
+ safe_destination = False
+ if not has_whitespace_or_control and not any(
+ ch in sanitized_url for ch in _MARKDOWN_LINK_UNSAFE_CHARS
+ ):
+ try:
+ parsed = urlparse(sanitized_url)
+ _ = parsed.port
+ safe_destination = (
+ parsed.scheme.lower() in _SAFE_MARKDOWN_LINK_SCHEMES
+ and bool(parsed.netloc and parsed.hostname)
+ )
+ except ValueError:
+ safe_destination = False
+
+ if safe_destination:
+ return f"[{sanitized_url}]({sanitized_url})"
+ return _escape_markdown_plain_text(sanitized_url)
+
+
def render_full(report: schema.Report) -> str:
"""Full data dump: ALL clusters + ALL items by source. For saved files and debugging."""
evidence_report = schema.without_sources(report, {"corpus"})
@@ -1735,7 +1804,9 @@ def render_full(report: schema.Report) -> str:
)
lines.append(f" {item.title}")
if item.url:
- lines.append(f" {item.url}")
+ rendered_url = _markdown_url_link(item.url)
+ if rendered_url:
+ lines.append(f" {rendered_url}")
if item.container:
lines.append(f" *{item.container}*")
if item.snippet:
@@ -2208,8 +2279,11 @@ def _render_candidate(
f"{prefix} [{schema.candidate_source_label(candidate)}] {candidate.title}"
+ (_candidate_freshness_flag(report, candidate.candidate_id) if report else ""),
f" - {details}",
- f" - URL: {candidate.url}",
]
+ if candidate.url:
+ rendered_url = _markdown_url_link(candidate.url)
+ if rendered_url:
+ lines.append(f" - URL: {rendered_url}")
corroboration = _format_corroboration(candidate)
if corroboration:
lines.append(f" - {corroboration}")
diff --git a/skills/last30days/scripts/lib/truthsocial.py b/skills/last30days/scripts/lib/truthsocial.py
index c0a338dd..c871117b 100644
--- a/skills/last30days/scripts/lib/truthsocial.py
+++ b/skills/last30days/scripts/lib/truthsocial.py
@@ -89,7 +89,15 @@ def search_truthsocial(
try:
response = http.request(
"GET", url,
- headers={"Authorization": f"Bearer {token}"},
+ headers={
+ "Authorization": f"Bearer {token}",
+ # Cloudflare 403s the skill's default User-Agent regardless of token validity (#909).
+ # Reuse http.BROWSER_USER_AGENT, as the keyless Reddit path does.
+ "User-Agent": http.BROWSER_USER_AGENT,
+ "Accept": "application/json, text/plain, */*",
+ "Accept-Language": "en-US,en;q=0.9",
+ "Referer": "https://truthsocial.com/",
+ },
timeout=30,
)
except http.HTTPError as e:
diff --git a/tests/test_arxiv_source.py b/tests/test_arxiv_source.py
index 293f7e7e..8efed231 100644
--- a/tests/test_arxiv_source.py
+++ b/tests/test_arxiv_source.py
@@ -46,6 +46,28 @@ def test_search_query_strips_inner_quotes():
assert q == 'all:"say hello world"'
+def test_unquoted_fallback_search_args_conjoin_terms_at_command_boundary():
+ args = arxiv._build_search_args("AI video generation advances", 10, quoted=False)
+ assert args == [
+ "arxiv-pp-cli",
+ "query",
+ "--search-query",
+ 'all:"AI" AND all:"video" AND all:"generation" AND all:"advances"',
+ "--sort-by",
+ "relevance",
+ "--max-results",
+ "10",
+ "--agent",
+ ]
+
+
+def test_unquoted_fallback_quotes_operator_and_colon_terms_at_command_boundary():
+ args = arxiv._build_search_args("AI AND OR title:video", 5, quoted=False)
+ assert args[args.index("--search-query") + 1] == (
+ 'all:"AI" AND all:"AND" AND all:"OR" AND all:"title:video"'
+ )
+
+
# ---- envelope extraction ----
def test_extract_entries_handles_nested_results_envelope():
@@ -165,3 +187,99 @@ def test_run_cli_bad_json_returns_error(monkeypatch):
monkeypatch.setattr(arxiv.subproc, "run_with_timeout", lambda cmd, timeout: _Proc(0, "not json"))
resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
assert resp["results"] == [] and "error" in resp
+
+
+def test_empty_stdout_returns_error_without_retry(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ return _Proc(0, "")
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp == {"results": [], "error": "empty stdout"}
+ assert len(calls) == 1
+
+
+def test_unrecognized_json_returns_error_without_retry(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ return _Proc(0, '{"status":"ok"}')
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp == {"results": [], "error": "unrecognized JSON response"}
+ assert len(calls) == 1
+
+
+def test_recognized_empty_list_retries(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ return _Proc(0, "[]")
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp == {"results": []}
+ assert len(calls) == 2
+
+
+# ---- unquoted-retry on zero results (#908) ----
+
+def test_zero_result_quoted_query_retries_unquoted_and_finds_results(monkeypatch):
+ """A natural-language multi-word topic matches nothing as an exact
+ phrase, but the unquoted retry finds it -- the fix for #908."""
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ query = cmd[cmd.index("--search-query") + 1]
+ if query == 'all:"AI video generation advances"':
+ return _Proc(0, '{"results":{"entries":[]}}')
+ return _Proc(0, '{"results":{"entries":[{"title":"AI video generation advances"}]}}')
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("AI video generation advances", "2026-06-01", "2026-06-27")
+ assert resp["results"] == [{"title": "AI video generation advances"}]
+ assert len(calls) == 2
+ assert 'all:"AI video generation advances"' in calls[0]
+ assert 'all:"AI" AND all:"video" AND all:"generation" AND all:"advances"' in calls[1]
+
+
+def test_zero_result_quoted_query_retry_also_empty_returns_empty(monkeypatch):
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ return _Proc(0, '{"results":{"entries":[]}}')
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("truly obscure nonsense topic", "2026-06-01", "2026-06-27")
+ assert resp["results"] == []
+ assert "error" not in resp
+ assert len(calls) == 2
+
+
+def test_real_cli_error_does_not_trigger_unquoted_retry(monkeypatch):
+ """A genuine failure (nonzero exit) must not retry -- only a clean
+ zero-result success should (R6)."""
+ monkeypatch.setattr(arxiv, "_is_available", lambda: True)
+ calls = []
+
+ def fake_run(cmd, timeout):
+ calls.append(cmd)
+ return _Proc(1, "", "boom")
+
+ monkeypatch.setattr(arxiv.subproc, "run_with_timeout", fake_run)
+ resp = arxiv.search_arxiv("topic", "2026-06-01", "2026-06-27")
+ assert resp["results"] == [] and "boom" in resp["error"]
+ assert len(calls) == 1
diff --git a/tests/test_cli_v3.py b/tests/test_cli_v3.py
index 359501f2..22c4285d 100644
--- a/tests/test_cli_v3.py
+++ b/tests/test_cli_v3.py
@@ -186,6 +186,26 @@ class CliV3Tests(unittest.TestCase):
self.assertEqual(["biosecurity", "ai", "agents"], args.topic)
self.assertEqual([], extra)
+ def test_build_parser_accepts_web_backend_keyless(self):
+ """Regression for #905: CONFIGURATION.md documents --web-backend=keyless
+ to force the zero-key floor, but the choices list rejected it."""
+ parser = cli.build_parser()
+ args, extra = parser.parse_known_args(["--web-backend", "keyless", "biosecurity"])
+ self.assertEqual("keyless", args.web_backend)
+ self.assertEqual([], extra)
+
+ def test_build_parser_still_accepts_other_web_backend_values(self):
+ parser = cli.build_parser()
+ for value in ("auto", "brave", "exa", "serper", "parallel", "none"):
+ args, extra = parser.parse_known_args(["--web-backend", value, "biosecurity"])
+ self.assertEqual(value, args.web_backend)
+ self.assertEqual([], extra)
+
+ def test_build_parser_rejects_invalid_web_backend(self):
+ parser = cli.build_parser()
+ with self.assertRaises(SystemExit):
+ parser.parse_known_args(["--web-backend", "bogus", "biosecurity"])
+
def test_build_parser_accepts_explicit_output_file(self):
parser = cli.build_parser()
args, extra = parser.parse_known_args(
diff --git a/tests/test_registers.py b/tests/test_registers.py
index 43c07deb..ae3fb688 100644
--- a/tests/test_registers.py
+++ b/tests/test_registers.py
@@ -203,7 +203,9 @@ def test_default_register_is_byte_identical_when_omitted(monkeypatch):
assert implicit == explicit
assert hashlib.sha256(implicit.encode()).hexdigest() == (
- "fe85fb29fb787ed71f7cc1b6fcce48e07e4dfba4e2d4d16a0eceb9d9152bce1c"
+ # Hash includes #886's linked evidence URLs and #890's Hacker News
+ # comment-rendering changes from main.
+ "351089b5c0eae7ef55bcfd35cc23a6eca1008a7f3d8c28e3266fe351a788c985"
)
diff --git a/tests/test_render_v3.py b/tests/test_render_v3.py
index 0603658c..3a2e6ba4 100644
--- a/tests/test_render_v3.py
+++ b/tests/test_render_v3.py
@@ -1530,3 +1530,253 @@ class TestPolymarketTopMarkets(unittest.TestCase):
item = self._pm_item("Who wins the primary?", "Kanye", 0.12)
line = render._polymarket_top_markets([item])[0]
self.assertIn(": Kanye ", line)
+
+
+class TestMarkdownUrlLinkSafety(unittest.TestCase):
+ """Greptile follow-up on #886/#912: source URLs are untrusted API
+ responses, not authored content -- must not be embedded verbatim into
+ markdown link syntax without checking for characters/schemes that would
+ corrupt or misuse it."""
+
+ def test_plain_https_url_becomes_a_link(self):
+ self.assertEqual(
+ render._markdown_url_link("https://example.com/thread"),
+ "[https://example.com/thread](https://example.com/thread)",
+ )
+
+ def test_url_with_closing_paren_falls_back_to_plain_text(self):
+ # A `)` in the URL would prematurely close the markdown destination.
+ url = "https://example.com/wiki/Foo_(bar)"
+ result = render._markdown_url_link(url)
+ self.assertEqual(result, r"https\://example\.com/wiki/Foo\_\(bar\)")
+ self.assertNotIn("](", result)
+
+ def test_url_with_bracket_falls_back_to_plain_text(self):
+ url = "https://example.com/search?q=[test]"
+ self.assertEqual(
+ render._markdown_url_link(url),
+ r"https\://example\.com/search?q=\[test\]",
+ )
+
+ def test_non_http_scheme_falls_back_to_plain_text(self):
+ # Untrusted scheme (e.g. javascript:) must never become an active link.
+ url = "javascript:alert(1)"
+ self.assertEqual(render._markdown_url_link(url), r"javascript\:alert\(1\)")
+
+ def test_url_with_backslash_falls_back_to_plain_text(self):
+ # A backslash can escape adjacent markdown delimiters.
+ url = "https://example.com/\\]"
+ result = render._markdown_url_link(url)
+ self.assertEqual(result, "https\\://example\\.com/\\\\\\]")
+ self.assertNotIn("](", result)
+
+ def test_embedded_markdown_link_is_escaped_as_plain_text(self):
+ result = render._markdown_url_link("[click](javascript:alert)")
+ self.assertEqual(result, r"\[click\]\(javascript\:alert\)")
+ self.assertNotIn("[click](javascript:alert)", result)
+
+ def test_angle_autolink_and_raw_html_are_encoded(self):
+ autolink = render._markdown_url_link("<javascript:alert(1)>")
+ raw_html = render._markdown_url_link(
+ '<a href="javascript:alert(1)">click</a>'
+ )
+ self.assertEqual(autolink, r"&lt;javascript\:alert\(1\)&gt;")
+ self.assertNotIn("<a ", raw_html)
+ self.assertIn("&lt;a href=", raw_html)
+
+ def test_http_url_with_raw_html_delimiters_is_plain_text(self):
+ result = render._markdown_url_link("https://example.com/<script>")
+ self.assertEqual(result, r"https\://example\.com/&lt;script&gt;")
+ self.assertNotIn("](", result)
+
+ def test_embedded_newline_is_stripped_even_from_plain_text_fallback(self):
+ """Greptile follow-up: an embedded newline/CR must not survive into
+ the rendered line at all -- whether or not the URL becomes a link --
+ since it could otherwise inject fabricated report structure (fake
+ headings, list items) into the single-line output."""
+ url = "https://example.com/x\n## Injected Heading\nmore"
+ result = render._markdown_url_link(url)
+ self.assertNotIn("\n", result)
+ url_cr = "https://example.com/x\r\nmore"
+ self.assertNotIn("\r", render._markdown_url_link(url_cr))
+ self.assertNotIn("\n", render._markdown_url_link(url_cr))
+ self.assertNotIn("##", result)
+ self.assertNotEqual(result, url)
+
+ def test_url_with_controls_is_escaped_and_single_line(self):
+ url = "https://example.com/x\t\x00\u2028more"
+ result = render._markdown_url_link(url)
+ self.assertNotEqual(result, url)
+ self.assertNotIn("\t", result)
+ self.assertNotIn("\x00", result)
+ self.assertNotIn("](", result)
+
+ def test_safe_url_with_query_fragment_and_encoded_delimiters_stays_clickable(self):
+ url = "https://example.com/search?q=one&other=two%28x%29#result"
+ self.assertEqual(
+ render._markdown_url_link(url),
+ f"[{url}]({url})",
+ )
+
+ def test_malformed_or_unsafe_destinations_are_escaped(self):
+ for url in (
+ "data:text/plain,hello",
+ "vbscript:alert(1)",
+ "file:///tmp/report.md",
+ "mailto:[email protected]",
+ "//evil.example/path",
+ "https:example.com/path",
+ " https://example.com/path ",
+ ):
+ with self.subTest(url=url):
+ result = render._markdown_url_link(url)
+ self.assertNotEqual(result, url)
+ self.assertNotIn("](", result)
+
+ def test_empty_url_returns_empty_string(self):
+ self.assertEqual(render._markdown_url_link(""), "")
+ self.assertEqual(render._markdown_url_link(" \t\r\n"), "")
+ self.assertEqual(render._markdown_url_link("\x00\u2028"), "")
+
+
+class TestSourceUrlsAreClickable(unittest.TestCase):
+ """Regression for #886: source URLs rendered as plain text instead of
+ markdown links in the saved raw report and internal evidence block."""
+
+ def test_all_items_by_source_url_is_markdown_link(self):
+ text = render.render_full(sample_report())
+ self.assertIn("[https://example.com](https://example.com)", text)
+ # No bare unlinked URL line remains for the item that has one.
+ self.assertNotIn("\n https://example.com\n", text)
+
+ def test_all_items_by_source_empty_url_renders_no_url_line(self):
+ report = sample_report()
+ empty_url_item = schema.SourceItem(
+ item_id="i3",
+ source="perplexity",
+ title="Perplexity Sonar Pro: test topic",
+ body="AI synthesis body.",
+ url="",
+ container="perplexity.ai",
+ published_at="2026-03-16",
+ date_confidence="high",
+ engagement={"citations": 3},
+ metadata={},
+ )
+ report.items_by_source["perplexity"] = [empty_url_item]
+ text = render.render_full(report)
+ self.assertNotIn("[]()", text)
+
+ def test_all_items_by_source_whitespace_url_renders_no_url_line(self):
+ report = sample_report()
+ report.items_by_source["grounding"][0].url = " \t\r\n"
+ text = render.render_full(report)
+ all_items = text.split("## All Items by Source", 1)[1]
+ self.assertNotIn("URL:", all_items)
+ self.assertNotIn("[]()", all_items)
+
+ def test_all_items_by_source_unsafe_url_is_escaped(self):
+ report = sample_report()
+ report.items_by_source["grounding"][0].url = "https://example.test/[click](javascript:alert(1))"
+ text = render.render_full(report)
+ all_items = text.split("## All Items by Source", 1)[1]
+ url_lines = [line for line in all_items.splitlines() if "click" in line]
+ self.assertEqual(len(url_lines), 1)
+ self.assertNotIn("](", url_lines[0])
+ self.assertIn(r"\[click\]\(javascript\:alert\(1\)\)", url_lines[0])
+
+ def test_all_items_by_source_newline_url_cannot_create_structure(self):
+ report = sample_report()
+ report.items_by_source["grounding"][0].url = "https://example.test/x\n## forged heading\n- forged item"
+ text = render.render_full(report)
+ self.assertNotIn("\n## forged heading", text)
+ self.assertNotIn("\n- forged item", text)
+ self.assertNotIn("\n https://example.test/x", text)
+
+ def test_all_items_by_source_rejected_url_is_inert_plain_text(self):
+ report = sample_report()
+ report.items_by_source["reddit"][0].url = "[click](javascript:alert)"
+ text = render.render_full(report)
+ self.assertIn(r" \[click\]\(javascript\:alert\)", text)
+ self.assertNotIn("[click](javascript:alert)", text)
+
+ def test_render_candidate_url_is_markdown_link(self):
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="reddit",
+ title="Grounded result", url="https://example.com/thread",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"reddit": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["reddit"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertIn(
+ "URL: [https://example.com/thread](https://example.com/thread)", text
+ )
+
+ def test_render_candidate_rejected_url_is_inert_plain_text(self):
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="reddit",
+ title="Grounded result", url="<javascript:alert(1)>",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"reddit": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["reddit"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertIn(r"URL: &lt;javascript\:alert\(1\)&gt;", text)
+ self.assertNotIn("<javascript:", text)
+
+ def test_render_candidate_empty_url_renders_no_url_line(self):
+ """Regression: unlike the item-loop location, _render_candidate had
+ no guard at all -- an empty candidate.url produced a broken `[]()`."""
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="perplexity",
+ title="Grounded result", url="",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["perplexity"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertNotIn("[]()", text)
+ self.assertNotIn("URL:", text)
+
+ def test_render_candidate_whitespace_url_renders_no_url_line(self):
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="perplexity",
+ title="Grounded result", url=" \t\r\n",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["perplexity"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertNotIn("URL:", text)
+ self.assertNotIn("[]()", text)
+
+ def test_render_candidate_unsafe_url_is_escaped(self):
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="perplexity",
+ title="Grounded result", url="javascript:alert(1)",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["perplexity"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertIn(r"URL: javascript\:alert\(1\)", text)
+ self.assertNotIn("](", text)
+
+ def test_render_candidate_newline_url_cannot_create_structure(self):
+ candidate = schema.Candidate(
+ candidate_id="c1", item_id="i1", source="perplexity",
+ title="Grounded result", url="https://example.test/x\n## forged heading",
+ snippet="A snippet.", subquery_labels=["primary"],
+ native_ranks={"perplexity": 1}, local_relevance=1.0, freshness=1,
+ engagement=100, source_quality=1.0, rrf_score=1.0,
+ sources=["perplexity"], source_items=[],
+ )
+ text = "\n".join(render._render_candidate(candidate, "1."))
+ self.assertNotIn("\n## forged heading", text)
+ self.assertNotIn("URL: [", text)
diff --git a/tests/test_truthsocial.py b/tests/test_truthsocial.py
index 2f6ccf2f..8d88e809 100644
--- a/tests/test_truthsocial.py
+++ b/tests/test_truthsocial.py
@@ -90,6 +90,25 @@ class TestSearchTruthSocial(unittest.TestCase):
self.assertEqual(result["statuses"], [])
self.assertIn("not configured", result["error"])
+ @patch("lib.truthsocial.http.request")
+ def test_search_sends_browser_like_headers(self, mock_request):
+ """Regression for #909: Cloudflare 403s the skill's default
+ User-Agent regardless of token validity; the request must include
+ browser-like headers alongside Authorization."""
+ from lib import http as http_module
+ mock_request.return_value = {"statuses": []}
+ truthsocial.search_truthsocial(
+ "health policy", "2026-02-09", "2026-03-09",
+ config={"TRUTHSOCIAL_TOKEN": "valid_token"},
+ )
+ _, kwargs = mock_request.call_args
+ headers = kwargs["headers"]
+ self.assertEqual(headers["Authorization"], "Bearer valid_token")
+ self.assertEqual(headers["User-Agent"], http_module.BROWSER_USER_AGENT)
+ self.assertIn("Accept", headers)
+ self.assertIn("Accept-Language", headers)
+ self.assertEqual(headers["Referer"], "https://truthsocial.com/")
+
@patch("lib.truthsocial.http.request")
def test_401_returns_token_expired(self, mock_request):
from lib.http import HTTPError